text:
from __future__ import print_function
import textwrap
import base64
import struct

b8 = struct.Struct('>Q')
b4 = struct.Struct('>L') # unsigned
b2 = struct.Struct('>H')
b1 = struct.Struct('B') # unsigned

py23basestring = ("".__class__, u"".__class__) # useful for isinstance checks

RSA_ENCRYPTION_OID = (1,2,840,113549,1,1,1)
DSA_OID            = (1,2,840,10040,4,1)       # identifier for DSA public/private keys; see RFC 3279, section 2.2.2 (e.g. in PKCS#8 PrivateKeyInfo or X.509 SubjectPublicKeyInfo)
DSA_WITH_SHA1_OID  = (1,2,840,10040,4,3)       # identifier for the DSA signature algorithm; see RFC 3279, section 2.3.2 (e.g. in X.509 signatures)

class KeystoreException(Exception):
    """Superclass for all pyjks exceptions."""
    pass
class KeystoreSignatureException(KeystoreException):
    """Signifies that the supplied password for a keystore integrity check is incorrect."""
    pass
class DuplicateAliasException(KeystoreException):
    """Signifies that duplicate aliases were encountered in a keystore."""
    pass
class NotYetDecryptedException(KeystoreException):
    """
    Signifies that an attribute of a key store entry can not be accessed because the entry has not yet been decrypted.

    By default, the keystore ``load`` and ``loads`` methods automatically try to decrypt all key entries using the store password.
    Any keys for which that attempt fails are returned undecrypted, and will raise this exception when its attributes are accessed.

    To resolve, first call decrypt() with the correct password on the entry object whose attributes you want to access.
    """
    pass
class BadKeystoreFormatException(KeystoreException):
    """Signifies that a structural error was encountered during key store parsing."""
    pass
class BadDataLengthException(KeystoreException):
    """Signifies that given input data was of wrong or unexpected length."""
    pass
class BadPaddingException(KeystoreException):
    """Signifies that bad padding was encountered during decryption."""
    pass
class BadHashCheckException(KeystoreException):
    """Signifies that a hash computation did not match an expected value."""
    pass
class DecryptionFailureException(KeystoreException):
    """Signifies failure to decrypt a value."""
    pass
class UnsupportedKeystoreVersionException(KeystoreException):
    """Signifies an unexpected or unsupported keystore format version."""
    pass
class UnexpectedJavaTypeException(KeystoreException):
    """Signifies that a serialized Java object of unexpected type was encountered."""
    pass
class UnexpectedAlgorithmException(KeystoreException):
    """Signifies that an unexpected cryptographic algorithm was used in a keystore."""
    pass
class UnexpectedKeyEncodingException(KeystoreException):
    """Signifies that a key was stored in an unexpected format or encoding."""
    pass
class UnsupportedKeystoreTypeException(KeystoreException):
    """Signifies that the keystore was an unsupported type."""
    pass
class UnsupportedKeystoreEntryTypeException(KeystoreException):
    """Signifies that the keystore entry was an unsupported type."""
    pass
class UnsupportedKeyFormatException(KeystoreException):
    """Signifies that the key format was an unsupported type."""
    pass

class AbstractKeystore(object):
    """
    Abstract superclass for keystores.
    """
    def __init__(self, store_type, entries):
        self.store_type = store_type  #: A string indicating the type of keystore that was loaded.
        self.entries = dict(entries)  #: A dictionary of all entries in the keystore, mapped by alias.

    @classmethod
    def load(cls, filename, store_password, try_decrypt_keys=True):
        """
        Convenience wrapper function; reads the contents of the given file
        and passes it through to :func:`loads`. See :func:`loads`.
        """
        with open(filename, 'rb') as file:
            input_bytes = file.read()
            ret = cls.loads(input_bytes,
                            store_password,
                            try_decrypt_keys=try_decrypt_keys)
        return ret

    def save(self, filename, store_password):
        """
        Convenience wrapper function; calls the :func:`saves`
        and saves the content to a file.
        """
        with open(filename, 'wb') as file:
            keystore_bytes = self.saves(store_password)
            file.write(keystore_bytes)

    @classmethod
    def _read_utf(cls, data, pos, kind=None):
        """
        :param kind: Optional; a human-friendly identifier for the kind of UTF-8 data we're loading (e.g. is it a keystore alias? an algorithm identifier? something else?).
                     Used to construct more informative exception messages when a decoding error occurs.
        """
        size = b2.unpack_from(data, pos)[0]
        pos += 2
        try:
            return data[pos:pos+size].decode('utf-8'), pos+size
        except (UnicodeEncodeError, UnicodeDecodeError) as e:
            raise BadKeystoreFormatException(("Failed to read %s, contains bad UTF-8 data: %s" % (kind, str(e))) if kind else \
                                             ("Encountered bad UTF-8 data: %s" % str(e)))

    @classmethod
    def _read_data(cls, data, pos):
        size = b4.unpack_from(data, pos)[0]
        pos += 4
        return data[pos:pos+size], pos+size

    @classmethod
    def _write_utf(cls, text):
        encoded_text = text.encode('utf-8')
        size = len(encoded_text)
        result = b2.pack(size)
        result += encoded_text
        return result

    @classmethod
    def _write_data(cls, data):
        size = len(data)
        result = b4.pack(size)
        result += data
        return result

class AbstractKeystoreEntry(object):
    """Abstract superclass for keystore entries."""
    def __init__(self, **kwargs):
        super(AbstractKeystoreEntry, self).__init__()
        self.store_type = kwargs.get("store_type")
        self.alias = kwargs.get("alias")
        self.timestamp = kwargs.get("timestamp")

    @classmethod
    def new(cls, alias):
        """
        Helper function to create a new KeyStoreEntry.
        """
        raise NotImplementedError("Abstract method")

    def is_decrypted(self):
        """
        Returns ``True`` if the entry has already been decrypted, ``False`` otherwise.
        """
        raise NotImplementedError("Abstract method")

    def decrypt(self, key_password):
        """
        Decrypts the entry using the given password. Has no effect if the entry has already been decrypted.

        :param str key_password: The password to decrypt the entry with.
        :raises DecryptionFailureException: If the entry could not be decrypted using the given password.
        :raises UnexpectedAlgorithmException: If the entry was encrypted with an unknown or unexpected algorithm
        """
        raise NotImplementedError("Abstract method")

    def encrypt(self, key_password):
        """
        Encrypts the entry using the given password, so that it can be saved.

        :param str key_password: The password to encrypt the entry with.
        """
        raise NotImplementedError("Abstract method")

def as_hex(ba):
    return "".join("{:02x}".format(b) for b in bytearray(ba))

def as_pem(der_bytes, type):
    result = "-----BEGIN %s-----\n" % type
    result += "\n".join(textwrap.wrap(base64.b64encode(der_bytes).decode('ascii'), 64))
    result += "\n-----END %s-----" % type
    return result

def bitstring_to_bytes(bitstr):
    """
    Converts a pyasn1 univ.BitString instance to byte sequence of type 'bytes'.
    The bit string is interpreted big-endian and is left-padded with 0 bits to form a multiple of 8.
    """
    bitlist = list(bitstr)
    bits_missing = (8 - len(bitlist) % 8) % 8
    bitlist = [0]*bits_missing + bitlist # pad with 0 bits to a multiple of 8
    result = bytearray()
    for i in range(0, len(bitlist), 8):
        byte = 0
        for j in range(8):
            byte = (byte << 1) | bitlist[i+j]
        result.append(byte)
    return bytes(result)

def xor_bytearrays(a, b):
    return bytearray([x^y for x,y in zip(a,b)])

def print_pem(der_bytes, type):
    print(as_pem(der_bytes, type))

def pkey_as_pem(pk):
    if pk.algorithm_oid == RSA_ENCRYPTION_OID:
        return as_pem(pk.pkey, "RSA PRIVATE KEY")
    else:
        return as_pem(pk.pkey_pkcs8, "PRIVATE KEY")

def strip_pkcs5_padding(m):
    """
    Drop PKCS5 padding:  8-(||M|| mod 8) octets each with value 8-(||M|| mod 8)
    Note: ideally we would use pycrypto for this, but it doesn't provide padding functionality and the project is virtually dead at this point.
    """
    return strip_pkcs7_padding(m, 8)

def strip_pkcs7_padding(m, block_size):
    """
    Same as PKCS#5 padding, except generalized to block sizes other than 8.
    """
    if len(m) < block_size or len(m) % block_size != 0:
        raise BadPaddingException("Unable to strip padding: invalid message length")

    m = bytearray(m) # py2/3 compatibility: always returns individual indexed elements as ints
    last_byte = m[-1]
    # the <last_byte> bytes of m must all have value <last_byte>, otherwise something's wrong
    if (last_byte <= 0 or last_byte > block_size) or (m[-last_byte:] != bytearray([last_byte])*last_byte):
        raise BadPaddingException("Unable to strip padding: invalid padding found")

    return bytes(m[:-last_byte]) # back to 'str'/'bytes'

def add_pkcs7_padding(m, block_size):
    if block_size <= 0 or block_size > 255:
        raise ValueError("Invalid block size")

    m = bytearray(m)
    num_padding_bytes = block_size - (len(m) % block_size)
    m = m + bytearray([num_padding_bytes]*num_padding_bytes)
    return bytes(m)


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
	//For view all the languages go to the folder assets/grocery_crud/languages/
	$config['grocery_crud_default_language']	= 'english';

	// There are only three choices: "uk-date" (dd/mm/yyyy), "us-date" (mm/dd/yyyy) or "sql-date" (yyyy-mm-dd)
	$config['grocery_crud_date_format']			= 'uk-date';

	// The default per page when a user firstly see a list page
	$config['grocery_crud_default_per_page']	= 25; //Can only take values 10,25,50,100

	$config['grocery_crud_file_upload_allow_file_types'] 		= 'gif|jpeg|jpg|png|tiff|doc|docx|txt|odt|xls|xlsx|pdf|ppt|pptx|pps|ppsx|mp3|m4a|ogg|wav|mp4|m4v|mov|wmv|flv|avi|mpg|ogv|3gp|3g2';
	$config['grocery_crud_file_upload_max_file_size'] 			= '20MB'; //ex. '10MB' (Mega Bytes), '1067KB' (Kilo Bytes), '5000B' (Bytes)

	//You can choose 'ckeditor','tinymce' or 'markitup'
	$config['grocery_crud_default_text_editor'] = 'ckeditor';
	//You can choose 'minimal' or 'full'
	$config['grocery_crud_text_editor_type'] 	= 'full';

	//The character limiter at the list page, zero(0) value if you don't want character limiter at your list page
	$config['grocery_crud_character_limiter'] 	= 30;

redpajama_set_name: RedPajamaGithub


text:
<?php

if (!is_dir(__DIR__ . '/vendor')) {
    die("You must install package dependencies locally (`composer install` from package root)\n");
}

include_once(__DIR__ . '/vendor/autoload.php');


text:
<!DOCTYPE html>
<html>
  <head>
    <meta charset=utf-8 />
    <!--
      An example illustrating how to get and set fragment identifiers,
      the URL portion after the # that is ignored by the server,
      using jQuery.

      By Curran Kelleher 11/11/2013

      Draws from:
      http://en.wikipedia.org/wiki/Fragment_identifier
      http://stackoverflow.com/questions/680785/on-window-location-hash-change
    -->
    <title>Fragment Identifier Example</title>
  </head>
  <body>
    <script>

      // Gets the fragment identifier value.
      function getHashValue(){
        return location.hash.substr(1);
      }

      // Sets the fragment identifier value.
      function setHashValue(value){
        return location.hash = value;
      }

      // Get the initial hash value when the page loads.
      console.log(getHashValue());

      // Listen for fragment value changes.
      window.addEventListener('hashchange', function (){
        console.log('new hash value: ' + getHashValue());
      });

      // Set the fragment value to a random number
      // every 3 seconds.
      setInterval(function (){
        setHashValue(Math.random());
      }, 3000);
    </script>
  </body>
</html>


text:
using System.Collections.Generic;
using MQTTnet.Packets;
using MQTTnet.Protocol;

namespace MQTTnet.Client.Connecting
{
    public sealed class MqttClientConnectResult
    {
        /// <summary>
        /// Gets the result code.
        /// MQTTv5 only.
        /// </summary>
        public MqttClientConnectResultCode ResultCode { get; internal set; }

        /// <summary>
        /// Gets a value indicating whether a session was already available or not.
        /// MQTTv5 only.
        /// </summary>
        public bool IsSessionPresent { get; internal set; }

        /// <summary>
        /// Gets a value indicating whether wildcards can be used in subscriptions at the current server.
        /// MQTTv5 only.
        /// </summary>
        public bool WildcardSubscriptionAvailable { get; internal set; }

        /// <summary>
        /// Gets whether the server supports retained messages.
        /// MQTTv5 only.
        /// </summary>
        public bool RetainAvailable { get; internal set; }

        /// <summary>
        /// Gets the client identifier which was chosen by the server.
        /// MQTTv5 only.
        /// </summary>
        public string AssignedClientIdentifier { get; internal set; }

        /// <summary>
        /// Gets the authentication method.
        /// MQTTv5 only.
        /// </summary>
        public string AuthenticationMethod { get; internal set; }

        /// <summary>
        /// Gets the authentication data.
        /// MQTTv5 only.
        /// </summary>
        public byte[] AuthenticationData { get; internal set; }

        public uint? MaximumPacketSize { get; internal set; }

        /// <summary>
        /// Gets the reason string.
        /// MQTTv5 only.
        /// </summary>
        public string ReasonString { get; internal set; }

        public ushort? ReceiveMaximum { get; internal set; }

        /// <summary>
        /// Gets the maximum QoS which is supported by the server.
        /// MQTTv5 only.
        /// </summary>
        public MqttQualityOfServiceLevel MaximumQoS { get; internal set; }

        /// <summary>
        /// Gets the response information.
        /// MQTTv5 only.
        /// </summary>
        public string ResponseInformation { get; internal set; }

        /// <summary>
        /// Gets the maximum value for a topic alias. 0 means not supported.
        /// MQTTv5 only.
        /// </summary>
        public ushort TopicAliasMaximum { get; internal set; }

        /// <summary>
        /// Gets an alternate server which should be used instead of the current one.
        /// MQTTv5 only.
        /// </summary>
        public string ServerReference { get; internal set; }

        /// <summary>
        /// Gets the keep alive interval which was chosen by the server instead of the
        /// keep alive interval from the client CONNECT packet.
        /// MQTTv5 only.
        /// </summary>
        public ushort? ServerKeepAlive { get; internal set; }

        public uint? SessionExpiryInterval { get; internal set; }

        /// <summary>
        /// Gets a value indicating whether the subscription identifiers are available or not.
        /// MQTTv5 only.
        /// </summary>
        public bool SubscriptionIdentifiersAvailable { get; internal set; }

        /// <summary>
        /// Gets a value indicating whether the shared subscriptions are available or not.
        /// MQTTv5 only.
        /// </summary>
        public bool SharedSubscriptionAvailable { get; internal set; }

        /// <summary>
        /// Gets the user properties.
        /// In MQTT 5, user properties are basic UTF-8 string key-value pairs that you can append to almost every type of MQTT packet.
        /// As long as you don't exceed the maximum message size, you can use an unlimited number of user properties to add metadata to MQTT messages and pass information between publisher, broker, and subscriber.
        /// The feature is very similar to the HTTP header concept.
        /// MQTTv5 only.
        /// </summary>
        public List<MqttUserProperty> UserProperties { get; internal set; }
    }
}


text:
package com.github.nyrkovalex.ironadmin.core.utils;

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

import java.util.List;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

public class IronObjectsTest {

    private List<String> names;

    @Before
    public void setUp() throws Exception {
        names = IronObjects.getPropertyNames(SampleBean.class);
    }

    @Test
    public void testShouldGetAllPropertyNames() throws Exception {
        assertThat(names.size(), is(3));
    }

    @Test
    public void testShouldIncludeAllProperties() throws Exception {
        assertThat(names.contains("firstName"), is(true));
        assertThat(names.contains("lastName"), is(true));
        assertThat(names.contains("age"), is(true));
    }

}


text:
<?php

class Convenio extends \Eloquent {
	protected $softDelete = true;

	public $timestamps = false;

	protected $table = 'convenios';

	protected $garded = [
		"id"
	];

	protected $fillable = [
		"nome",
		"email",
		"phone"
	];

	//Relacionamentos

	public function recibo()
    {
        return $this->hasMany('Recibo');
    }
}


text:
module.exports = {
    malloc: function (root_object_val) {
        return new RingClass(root_object_val);
    },
};

function RingClass (root_object_val) {
    "use strict";

    this.init__ = function (root_object_val) {
        this.theRootObject = root_object_val;
        this.theInput = 0;
        this.theOutput = 0;
        this.theSize = 2;
        this.theLeft = this.size();
        this.theArray = [this.size()];
        this.debug(false, "init__", "");
    };

    this.objectName = function () {
        return "RingClass";
    };

    this.holderPoolModule = function () {
        return require("./holder_pool_module.js");
    };

    this.rootObject = function () {
        return this.theRootObject;
    };

    this.input = function () {
        return this.theInput;
    }

    this.setInput = function (val) {
        this.theInput = val;
    }

    this.incrementInput = function () {
        this.theInput += 1;
    }

    this.output = function () {
        return this.theOutput;
    }

    this.setOutput = function (val) {
        this.theOutput = val;
    }

    this.incrementOutput = function () {
        this.theOutput += 1;
    }

    this.size = function () {
        return this.theSize;
    }

    this.setSize = function (val) {
        this.theSize = val;
    }

    this.incrementSize = function () {
        this.theSize += 1;
    }

    this.decrementSize = function () {
        this.theSize -= 1;
    }

    this.left = function () {
        return this.theLeft;
    }

    this.setLeft = function (val) {
        this.theLeft = val;
    }

    this.incrementLeft = function () {
        this.theLeft += 1;
    }

    this.decrementLeft = function () {
        this.theLeft -= 1;
    }

    this.array = function (index_val) {
        return this.theArray[index_val];
    }

    this.setArray = function (index_val, data_val) {
        this.theArray[index_val] = data_val;
    }

    this.enQueue = function (data_val) {
        if (this.left() < 0) {
            this.abend("enQueue", "left=" + this.left());
            return;
        }

        if (this.left() <= (this.size() / 2)) {
            this.enlargeSize();
        }

        this.setArray(this.input(), data_val);
        this.incrementInput();
        if (this.input() === this.size()) {
            this.setInput(0);
        }
        this.decrementLeft();

        this.abendIt();
    };

    this.deQueue = function () {
        if (this.left() === this.size()) {
            return null;
        }

        var data = this.array(this.output());
        this.incrementOutput();
        if (this.output() === this.size()) {
            this.setOutput(0);
        }
        this.incrementLeft();

        this.abendIt();

        return data;
    };

    this.removeElement = function (func_val, input_val1, input_val2, input_val3) {
    };

    this.searchIt = function (func_val, input_val1, input_val2, input_val3) {
    };

    this.enlargeSize = function () {
        this.debug(false, "enlargeSize", "size=" + this.size() + "=>" + this.size() * 2);

        var i = this.size();
        while (i < this.size() * 2) {
            this.setArray(i, null);
            i += 1;
        }

        if (this.input() < this.output()) {
            i = 0;
            while (i <= this.input()) {
                this.setArray(this.size() + i, i);
                i += 1;
            }
            this.input += this.size();
        }

        this.setLeft(this.left() + this.size());
        this.setSize(this.size() * 2);

        this.abendIt();
    };

    this.abendIt = function () {
        if (this.left() < 0) {
            this.abend("abendIt", "left=" + this.left());
        }

        if ((this.input() + this.left() - this.output() !== this.size()) && (this.input() + this.left() - this.output() !== 0)) {
            this.abend('abendIt', "input(" + this.input() + ") + left(" + this.left() + ") - output(" + this.output() + ") !== size(" + this.size() + ")");
        }
    };

    this.debug = function (debug_val, str1_val, str2_val) {
        if (debug_val) {
            this.logit(str1_val, str2_val);
        }
    };

    this.logit = function (str1_val, str2_val) {
        this.rootObject().LOG_IT(this.objectName() + "." + str1_val, str2_val);
    };

    this.abend = function (str1_val, str2_val) {
        this.rootObject().ABEND(this.objectName() + "." + str1_val, str2_val);
    };

    this.init__(root_object_val);
}


text:
namespace {

using ::testing::HasSubstr;
using PartialLinkage = spvtest::LinkerTest;

TEST_F(PartialLinkage, Allowed) {
  const std::string body1 = R"(
OpCapability Linkage
OpDecorate %1 LinkageAttributes "foo" Import
OpDecorate %2 LinkageAttributes "bar" Import
%3 = OpTypeFloat 32
%1 = OpVariable %3 Uniform
%2 = OpVariable %3 Uniform
)";
  const std::string body2 = R"(
OpCapability Linkage
OpDecorate %1 LinkageAttributes "bar" Export
%2 = OpTypeFloat 32
%3 = OpConstant %2 3.1415
%1 = OpVariable %2 Uniform %3
)";

  spvtest::Binary linked_binary;
  spvtools::LinkerOptions linker_options;
  linker_options.SetAllowPartialLinkage(true);
  ASSERT_EQ(SPV_SUCCESS,
            AssembleAndLink({body1, body2}, &linked_binary, linker_options));

  const std::string expected_res = R"(OpCapability Linkage
OpModuleProcessed "Linked by SPIR-V Tools Linker"
OpDecorate %1 LinkageAttributes "foo" Import
%2 = OpTypeFloat 32
%1 = OpVariable %2 Uniform
%3 = OpConstant %2 3.1415
%4 = OpVariable %2 Uniform %3
)";
  std::string res_body;
  SetDisassembleOptions(SPV_BINARY_TO_TEXT_OPTION_NO_HEADER);
  ASSERT_EQ(SPV_SUCCESS, Disassemble(linked_binary, &res_body))
      << GetErrorMessage();
  EXPECT_EQ(expected_res, res_body);
}

TEST_F(PartialLinkage, Disallowed) {
  const std::string body1 = R"(
OpCapability Linkage
OpDecorate %1 LinkageAttributes "foo" Import
OpDecorate %2 LinkageAttributes "bar" Import
%3 = OpTypeFloat 32
%1 = OpVariable %3 Uniform
%2 = OpVariable %3 Uniform
)";
  const std::string body2 = R"(
OpCapability Linkage
OpDecorate %1 LinkageAttributes "bar" Export
%2 = OpTypeFloat 32
%3 = OpConstant %2 3.1415
%1 = OpVariable %2 Uniform %3
)";

  spvtest::Binary linked_binary;
  EXPECT_EQ(SPV_ERROR_INVALID_BINARY,
            AssembleAndLink({body1, body2}, &linked_binary));
  EXPECT_THAT(GetErrorMessage(),
              HasSubstr("Unresolved external reference to \"foo\"."));
}

}  // anonymous namespace


text:
// Code generated by client-gen. DO NOT EDIT.

package fake

import (
	"context"
	json "encoding/json"
	"fmt"

	networkingv1 "k8s.io/api/networking/v1"
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	labels "k8s.io/apimachinery/pkg/labels"
	schema "k8s.io/apimachinery/pkg/runtime/schema"
	types "k8s.io/apimachinery/pkg/types"
	watch "k8s.io/apimachinery/pkg/watch"
	applyconfigurationsnetworkingv1 "k8s.io/client-go/applyconfigurations/networking/v1"
	testing "k8s.io/client-go/testing"
)

// FakeIngressClasses implements IngressClassInterface
type FakeIngressClasses struct {
	Fake *FakeNetworkingV1
}

var ingressclassesResource = schema.GroupVersionResource{Group: "networking.k8s.io", Version: "v1", Resource: "ingressclasses"}

var ingressclassesKind = schema.GroupVersionKind{Group: "networking.k8s.io", Version: "v1", Kind: "IngressClass"}

// Get takes name of the ingressClass, and returns the corresponding ingressClass object, and an error if there is any.
func (c *FakeIngressClasses) Get(ctx context.Context, name string, options v1.GetOptions) (result *networkingv1.IngressClass, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootGetAction(ingressclassesResource, name), &networkingv1.IngressClass{})
	if obj == nil {
		return nil, err
	}
	return obj.(*networkingv1.IngressClass), err
}

// List takes label and field selectors, and returns the list of IngressClasses that match those selectors.
func (c *FakeIngressClasses) List(ctx context.Context, opts v1.ListOptions) (result *networkingv1.IngressClassList, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootListAction(ingressclassesResource, ingressclassesKind, opts), &networkingv1.IngressClassList{})
	if obj == nil {
		return nil, err
	}

	label, _, _ := testing.ExtractFromListOptions(opts)
	if label == nil {
		label = labels.Everything()
	}
	list := &networkingv1.IngressClassList{ListMeta: obj.(*networkingv1.IngressClassList).ListMeta}
	for _, item := range obj.(*networkingv1.IngressClassList).Items {
		if label.Matches(labels.Set(item.Labels)) {
			list.Items = append(list.Items, item)
		}
	}
	return list, err
}

// Watch returns a watch.Interface that watches the requested ingressClasses.
func (c *FakeIngressClasses) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {
	return c.Fake.
		InvokesWatch(testing.NewRootWatchAction(ingressclassesResource, opts))
}

// Create takes the representation of a ingressClass and creates it.  Returns the server's representation of the ingressClass, and an error, if there is any.
func (c *FakeIngressClasses) Create(ctx context.Context, ingressClass *networkingv1.IngressClass, opts v1.CreateOptions) (result *networkingv1.IngressClass, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootCreateAction(ingressclassesResource, ingressClass), &networkingv1.IngressClass{})
	if obj == nil {
		return nil, err
	}
	return obj.(*networkingv1.IngressClass), err
}

// Update takes the representation of a ingressClass and updates it. Returns the server's representation of the ingressClass, and an error, if there is any.
func (c *FakeIngressClasses) Update(ctx context.Context, ingressClass *networkingv1.IngressClass, opts v1.UpdateOptions) (result *networkingv1.IngressClass, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootUpdateAction(ingressclassesResource, ingressClass), &networkingv1.IngressClass{})
	if obj == nil {
		return nil, err
	}
	return obj.(*networkingv1.IngressClass), err
}

// Delete takes name of the ingressClass and deletes it. Returns an error if one occurs.
func (c *FakeIngressClasses) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {
	_, err := c.Fake.
		Invokes(testing.NewRootDeleteActionWithOptions(ingressclassesResource, name, opts), &networkingv1.IngressClass{})
	return err
}

// DeleteCollection deletes a collection of objects.
func (c *FakeIngressClasses) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {
	action := testing.NewRootDeleteCollectionAction(ingressclassesResource, listOpts)

	_, err := c.Fake.Invokes(action, &networkingv1.IngressClassList{})
	return err
}

// Patch applies the patch and returns the patched ingressClass.
func (c *FakeIngressClasses) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *networkingv1.IngressClass, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootPatchSubresourceAction(ingressclassesResource, name, pt, data, subresources...), &networkingv1.IngressClass{})
	if obj == nil {
		return nil, err
	}
	return obj.(*networkingv1.IngressClass), err
}

// Apply takes the given apply declarative configuration, applies it and returns the applied ingressClass.
func (c *FakeIngressClasses) Apply(ctx context.Context, ingressClass *applyconfigurationsnetworkingv1.IngressClassApplyConfiguration, opts v1.ApplyOptions) (result *networkingv1.IngressClass, err error) {
	if ingressClass == nil {
		return nil, fmt.Errorf("ingressClass provided to Apply must not be nil")
	}
	data, err := json.Marshal(ingressClass)
	if err != nil {
		return nil, err
	}
	name := ingressClass.Name
	if name == nil {
		return nil, fmt.Errorf("ingressClass.Name must be provided to Apply")
	}
	obj, err := c.Fake.
		Invokes(testing.NewRootPatchSubresourceAction(ingressclassesResource, *name, types.ApplyPatchType, data), &networkingv1.IngressClass{})
	if obj == nil {
		return nil, err
	}
	return obj.(*networkingv1.IngressClass), err
}


text:
<?php

namespace Zend\Service\Audioscrobbler\Exception;

use Zend\Service\Audioscrobbler\Exception;

/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Audioscrobbler
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class BadMethodCallException
    extends \BadMethodCallException
    implements Exception
{}


text:
@interface VXAdjustmentSliderCell : NSSliderCell

@end


text:
<!DOCTYPE html>

    <title>1-github</title>
    <meta charset='utf-8' />
    <meta content='width=1024, user-scalable=no' name='viewport' />

    <link href="deck.js/core/deck.core.css" rel="stylesheet" type="text/css"/>

    <link href="deck.js/extensions/scale/deck.scale.css" rel="stylesheet" type="text/css"/>
    <link href="deck.js/extensions/hash/deck.hash.css" rel="stylesheet" type="text/css"/>
    <link href="deck.js/extensions/navigation/deck.navigation.css" rel="stylesheet" type="text/css"/>
    <link href="deck.js/extensions/status/deck.status.css" rel="stylesheet" type="text/css"/>
    <link href="deck.js/extensions/menu/deck.menu.css" rel="stylesheet" type="text/css"/>
    <link href="deck.js/extensions/codemirror/deck.codemirror.css" rel="stylesheet" type="text/css"/>
    <link href="deck.js/extensions/goto/deck.goto.css" rel="stylesheet" type="text/css"/>

    <link href="css/keydown.css" rel="stylesheet" type="text/css"/>
    <link href="css/1-github.css" rel="stylesheet" type="text/css"/>
    <link href="css/horizontal-slide.css" rel="stylesheet" type="text/css"/>
    <link href="css/swiss.css" rel="stylesheet" type="text/css"/>
    <link href="css/default.css" rel="stylesheet" type="text/css"/>

Welcome KAT

Today we'll talk about github

Why?

Cause it's awesome

Where to start?

Go to (github.com)

Create an account

Follow your friends

Create a repository

Hello World

Install Git on your computer

Clone your repository

Edit the Readme.md

Push your changes!

Working together

Fork from KAT repository

Clone your repository

  git clone git@github.com:<Your name>/helloWorld.git

Edit README.md

View git status

  git status

Add your changes

  git add .

Commit your changes

  git commit -m "my super explicit message"

Send your changes to your github repo

  git push origin master

Knowing git commands

Git commands explained

Understanding Git

Git for ages 4 and up

Git website

Git interactive cheat sheat

Git commands explained

    ←
    →

    #

      /


text:
@class NSDictionary, NSMutableURLRequest, NSString, NSURL;

@protocol UnityWWWRequestProvider <NSObject>
+ (NSMutableURLRequest *)allocRequestForHTTPMethod:(NSString *)arg1 url:(NSURL *)arg2 headers:(NSDictionary *)arg3;
@end


text:
/**
 * @name MainCtrl
 * @description Main controller.
 * @author Carlos Justiniano
 */
angular.module('umfTestApp')
  .controller('MainCtrl', ['$scope', '$location', function ($scope, $location) {
    'use strict';

    var VERSION = "1.0"
      , WEB_SOCKET_PORT = 80
      , userID
      , shortUID;

    $scope.payloadSizeOptions = [
      {name: '.5 kB', value: 0.5},
      {name: '1 kB', value: 1},
      {name: '2 kB', value: 2},
      {name: '4 kB', value: 4},
      {name: '8 kB', value: 8},
      {name: '16 kB', value: 16},
      {name: '32 kB', value: 32},
      {name: '64 kB', value: 64},
      {name: '128 kB', value: 128},
      {name: '256 kB', value: 256},
      {name: '512 kB', value: 512},
      {name: '1024 kB', value: 1024}
    ];
    $scope.msgTypes = [
      {name: 'Chat', value: 'chat'},
      {name: 'Client info', value: 'client'},
      {name: 'Mouse position', value: 'mouse'},
      {name: 'Heart beat', value: 'heart'},
      {name: 'Random', value: 'random'}
    ];
    $scope.startTestButtonOptions = [
      {name: 'Start', class: 'btn-primary'},
      {name: 'Stop', class: 'btn-danger'}
    ];
    $scope.iterationChoices = [
      {name: 'One shot', value: 1},
      {name: 'Twice', value: 2},
      {name: 'Five times', value: 5},
      {name: 'Until stopped', value: -1}
    ];
    $scope.console = [];

    $scope.settings = {
      userID: generateUserID(),
      textBuffer: '',
      timerID: null,
      msgPerSecond: 1,
      iterationCnt: 0,
      iteration: $scope.iterationChoices[0],
      payloadSize: $scope.payloadSizeOptions[0],
      msgType: $scope.msgTypes[0],
      startTestButton: $scope.startTestButtonOptions[0]
    };
    userID = $scope.settings.userID;
    $scope.settings.shortUID = userID.slice(0, 2) + userID.slice(userID.length - 2);
    shortUID = $scope.settings.shortUID;

    $scope.messages = [
      {
        "mid": 0,
        "type": "msg",
        "to": "umfTestServer",
        "from": "UMFTester:" + shortUID,
        "version": "1.0",
        "timestamp": "",
        "body": {
        }
      }
    ];

    if ("WebSocket" in window) {
      $scope.ws = new WebSocket("ws://" + document.domain + ":" + WEB_SOCKET_PORT + "/ws");
      if ($scope.ws) {
        consoleLog("Initializing UMFTester v" + VERSION);
        consoleLog("Running with userID: " + userID + " (" + shortUID + ")");
        consoleLog("Connected to WebSocket.");
        consoleLog("Ready for testing.");
      }
    }

    $scope.ws.onmessage = function (msg) {
      var message = JSON.parse(msg.data);
      consoleLog("Incoming message: ", message);
    };

    // Cleanly close websocket when unload window
    window.onbeforeunload = function () {
      $scope.ws.onclose = function () {
        // intentionally set to empty
      }; // disable onclose handler first
      $scope.ws.close();
    };

    $scope.startTest = function () {
      var cnt
        , i
        , msg
        , payloadSize
        , settings = $scope.settings;

      settings.startTestButton = (settings.startTestButton.name == 'Start') ?
        $scope.startTestButtonOptions[1] : $scope.startTestButtonOptions[0];

      if (settings.startTestButton.name == 'Start') {
        if (settings.timerID != null) {
          clearInterval($scope.settings.timerID);
          $scope.settings.timerID = null;
          consoleLog("Test ended.");
        }
      } else {
        $scope.console = [];
        payloadSize = settings.payloadSize.value * 1024;
        settings.textBuffer = randomText(payloadSize);
        settings.iterationCnt = Number(settings.iteration.value);

        consoleLog("Starting test.");
        consoleLog("Messages per second: " + settings.msgPerSecond);
        consoleLog("Payload size: " + payloadSize + " bytes.");

        $scope.settings.timerID = setInterval(function () {
          if (settings.iterationCnt == -1) {
            consoleLog("iterationCnt: 1");
          } else {
            consoleLog("iterationCnt: " + settings.iterationCnt);
          }

          var go = true;
          if (settings.iteration.value != -1) {
            if (--settings.iterationCnt < 0) {
              clearInterval($scope.settings.timerID);
              $scope.settings.timerID = null;
              settings.startTestButton = $scope.startTestButtonOptions[0];
              consoleLog("Test ended.");
              go = false;
            }
          }
          if (go) {
            cnt = Number(settings.msgPerSecond);
            for (i = 0; i < cnt; i++) {
              msg = $scope.messages[0];
              msg.body.addon = settings.textBuffer;
              var msgType = $scope.settings.msgType.value;
              if ($scope.settings.msgType.value == "random") {
                msgType = $scope.msgTypes[Math.floor((Math.random() * 4))].value;
              }
              msg = buildUMFMessage(msg, msgType);
              msg = JSON.stringify(msg);
              $scope.ws.send(msg);
            }
          }
          $scope.$apply();
        }, 1000);
      }
    };

    function getDate() {
      var date = new Date()
        , hours = date.getHours()
        , minutes = date.getMinutes()
        , seconds = date.getSeconds();

      hours = hours < 10 ? "0" + hours : hours;
      minutes = minutes < 10 ? "0" + minutes : minutes;
      seconds = seconds < 10 ? "0" + seconds : seconds;

      return "" + hours + ":" + minutes + ":" + seconds + "." +
        date.getMilliseconds();
    }

    function consoleLog(message, objectValue) {
      var strDate = getDate();
      try {
        if (typeof objectValue != "undefined") {
          if (typeof objectValue == "object") {
            message = message + "(object) " + JSON.stringify(objectValue);
          } else {
            message = message + "(" + typeof message + ") " + objectValue;
          }
        }

        $scope.console.push(strDate + " | (" + $scope.settings.shortUID + "): " + message);
      } catch (exception) {
      }
    }

    function randomText(count) {
      var chars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"
        , buffer = ''
        , i
        , rnum
        , wordSpace;

      for (i = 0; i < count; i++) {
        wordSpace = Math.floor(Math.random() * 5) + 2;
        if (count % wordSpace) {
          buffer += ' ';
        }
        rnum = Math.floor(Math.random() * chars.length);
        buffer += chars.substring(rnum, rnum + 1);
      }
      return buffer;
    }

    function generateUserID() {
      var strDate = getDate();
      return Sha1.hash(strDate);
    }

    function buildUMFMessage(message, messageType) {
      var dateUTC = new Date().toUTCString()
        , iso8601TimeStamp = new Date(dateUTC).toISOString();
      message.type = messageType;
      message.timestamp = iso8601TimeStamp;
      message.mid = UUID.generateWeakUUID();
      return message;
    }

  }]);


text:
import {inject} from 'aurelia-framework';

@inject(Element)
export class PopupCustomAttribute {
  constructor(element) {
    this.element = element;
  }

  attached() {
    this.element.addEventListener('click', this._listener = e => {
      e.preventDefault();
      window.open(this.element.getAttribute('href'));
    });
  }

  detached() {
    this.element.removeEventListener('click', this._listener);
  }
}


text:
/*
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/*
 * Tester.java
 * Copyright (C) 2005 University of Waikato, Hamilton, New Zealand
 *
 */

package weka.experiment;

import weka.core.Instance;
import weka.core.Instances;
import weka.core.Range;

import java.io.Serializable;

/**
 * Interface for different kinds of Testers in the Experimenter.
 *
 * @author FracPete (fracpete at waikato dot ac dot nz)
 * @version $Revision: 1.4 $
 */
public interface Tester
  extends Serializable {

  /**
   * returns the name of the testing algorithm
   */
  public String getDisplayName();

  /**
   * returns a string that is displayed as tooltip on the "perform test"
   * button in the experimenter
   */
  public String getToolTipText();

  /**
   * retrieves all the settings from the given Tester
   *
   * @param tester      the Tester to get the settings from
   */
  public void assign(Tester tester);

  /**
   * Sets the matrix to use to produce the output.
   * @param matrix the instance to use to produce the output
   * @see ResultMatrix
   */
  public void setResultMatrix(ResultMatrix matrix);

  /**
   * Gets the instance that produces the output.
   * @return the instance to produce the output
   */
  public ResultMatrix getResultMatrix();

  /**
   * Set whether standard deviations are displayed or not.
   * @param s true if standard deviations are to be displayed
   */
  public void setShowStdDevs(boolean s);

  /**
   * Returns true if standard deviations have been requested.
   * @return true if standard deviations are to be displayed.
   */
  public boolean getShowStdDevs();

  /**
   * Gets the number of datasets in the resultsets
   *
   * @return the number of datasets in the resultsets
   */
  public int getNumDatasets();

  /**
   * Gets the number of resultsets in the data.
   *
   * @return the number of resultsets in the data
   */
  public int getNumResultsets();

  /**
   * Gets a string descriptive of the specified resultset.
   *
   * @param index the index of the resultset
   * @return a descriptive string for the resultset
   */
  public String getResultsetName(int index);

  /**
   * Checks whether the resultset with the given index shall be displayed.
   *
   * @param index the index of the resultset to check whether it shall be displayed
   * @return whether the specified resultset is displayed
   */
  public boolean displayResultset(int index);

  /**
   * Computes a paired t-test comparison for a specified dataset between
   * two resultsets.
   *
   * @param datasetSpecifier the dataset specifier
   * @param resultset1Index the index of the first resultset
   * @param resultset2Index the index of the second resultset
   * @param comparisonColumn the column containing values to compare
   * @return the results of the paired comparison
   * @exception Exception if an error occurs
   */
  public PairedStats calculateStatistics(Instance datasetSpecifier,
					 int resultset1Index,
					 int resultset2Index,
					 int comparisonColumn) throws Exception;

  /**
   * Creates a key that maps resultset numbers to their descriptions.
   *
   * @return a value of type 'String'
   */
  public String resultsetKey();

  /**
   * Creates a "header" string describing the current resultsets.
   *
   * @param comparisonColumn a value of type 'int'
   * @return a value of type 'String'
   */
  public String header(int comparisonColumn);

  /**
   * Carries out a comparison between all resultsets, counting the number
   * of datsets where one resultset outperforms the other.
   *
   * @param comparisonColumn the index of the comparison column
   * @return a 2d array where element [i][j] is the number of times resultset
   * j performed significantly better than resultset i.
   * @exception Exception if an error occurs
   */
  public int [][] multiResultsetWins(int comparisonColumn, int [][] nonSigWin)
    throws Exception;

  /**
   * Carries out a comparison between all resultsets, counting the number
   * of datsets where one resultset outperforms the other. The results
   * are summarized in a table.
   *
   * @param comparisonColumn the index of the comparison column
   * @return the results in a string
   * @exception Exception if an error occurs
   */
  public String multiResultsetSummary(int comparisonColumn)
    throws Exception;

  public String multiResultsetRanking(int comparisonColumn)
    throws Exception;

  /**
   * Creates a comparison table where a base resultset is compared to the
   * other resultsets. Results are presented for every dataset.
   *
   * @param baseResultset the index of the base resultset
   * @param comparisonColumn the index of the column to compare over
   * @return the comparison table string
   * @exception Exception if an error occurs
   */
  public String multiResultsetFull(int baseResultset,
				   int comparisonColumn) throws Exception;

  /**
   * Get the value of ResultsetKeyColumns.
   *
   * @return Value of ResultsetKeyColumns.
   */
  public Range getResultsetKeyColumns();

  /**
   * Set the value of ResultsetKeyColumns.
   *
   * @param newResultsetKeyColumns Value to assign to ResultsetKeyColumns.
   */
  public void setResultsetKeyColumns(Range newResultsetKeyColumns);

  /**
   * Gets the indices of the the datasets that are displayed (if null
   * then all are displayed). The base is always displayed.
   *
   * @return the indices of the datasets to display
   */
  public int[] getDisplayedResultsets();

  /**
   * Sets the indicies of the datasets to display (null means all).
   * The base is always displayed.
   *
   * @param cols the indices of the datasets to display
   */
  public void setDisplayedResultsets(int[] cols);

  /**
   * Get the value of SignificanceLevel.
   *
   * @return Value of SignificanceLevel.
   */
  public double getSignificanceLevel();

  /**
   * Set the value of SignificanceLevel.
   *
   * @param newSignificanceLevel Value to assign to SignificanceLevel.
   */
  public void setSignificanceLevel(double newSignificanceLevel);

  /**
   * Get the value of DatasetKeyColumns.
   *
   * @return Value of DatasetKeyColumns.
   */
  public Range getDatasetKeyColumns();

  /**
   * Set the value of DatasetKeyColumns.
   *
   * @param newDatasetKeyColumns Value to assign to DatasetKeyColumns.
   */
  public void setDatasetKeyColumns(Range newDatasetKeyColumns);

  /**
   * Get the value of RunColumn.
   *
   * @return Value of RunColumn.
   */
  public int getRunColumn();

  /**
   * Set the value of RunColumn.
   *
   * @param newRunColumn Value to assign to RunColumn.
   */
  public void setRunColumn(int newRunColumn);

  /**
   * Get the value of FoldColumn.
   *
   * @return Value of FoldColumn.
   */
  public int getFoldColumn();

  /**
   * Set the value of FoldColumn.
   *
   * @param newFoldColumn Value to assign to FoldColumn.
   */
  public void setFoldColumn(int newFoldColumn);

  /**
   * Returns the name of the column to sort on.
   *
   * @return the name of the column to sort on.
   */
  public String getSortColumnName();

  /**
   * Returns the column to sort on, -1 means the default sorting.
   *
   * @return the column to sort on.
   */
  public int getSortColumn();

  /**
   * Set the column to sort on, -1 means the default sorting.
   *
   * @param newSortColumn the new sort column.
   */
  public void setSortColumn(int newSortColumn);

  /**
   * Get the value of Instances.
   *
   * @return Value of Instances.
   */
  public Instances getInstances();

  /**
   * Set the value of Instances.
   *
   * @param newInstances Value to assign to Instances.
   */
  public void setInstances(Instances newInstances);
}


text:
/*
 * GuardForCpp.cpp
 *
 *  Created on: 19 janv. 2016
 *      Author: FrancisANDRE
 */

#include "GuardForCpp.h"

namespace ALS {
	namespace SMC {
		namespace PARSER {
			namespace CPP {
				 void GuardForCpp::generateInclude(ostream& inc, bool debug) const {
				}
				 void GuardForCpp::generateCode(ostream& cpp, bool debug) const {
				}
			}
		}
	}
}


text:
<?php

namespace Ger\Bundle\WorkflowBundle\Entity;

use Ger\Bundle\WorkflowBundle\Model\Step as BaseStep;
use Doctrine\ORM\Mapping as ORM;

/**
 * Class Step
 * @package Ger\Bundle\WorkflowBundle\Entity
 * @ORM\Entity
 * @ORM\Table("steps")
 */
class Step extends BaseStep {

    /**
     * @ORM\Id
     * @var id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var worfklow
     * @ORM\ManyToOne(targetEntity="Ger\Bundle\WorkflowBundle\Entity\Workflow", cascade={"all"}, fetch="EAGER", inversedBy="steps")
     */
    protected $workflow;

    /**
     * @var child
     * @ORM\OneToMany(targetEntity="Ger\Bundle\WorkflowBundle\Entity\Step",orphanRemoval=true, mappedBy="parent", cascade={"all"})
     */
    protected $child;

    /**
     * @var parent
     * @ORM\ManyToOne(targetEntity="Ger\Bundle\WorkflowBundle\Entity\Step", inversedBy="child")
     * @ORM\JoinColumn(name="parent_id", referencedColumnName="id", onDelete="set null")
     */
    protected $parent;

    /**
     * @var retry_on_failure
     * @ORM\Column(type="boolean")
     */
    protected $retry_on_failure;

    /**
     * @return id
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set workflow
     *
     * @param \Ger\Bundle\WorkflowBundle\Entity\Workflow $workflow
     * @return Step
     */
    public function setWorkflow(\Ger\Bundle\WorkflowBundle\Entity\Workflow $workflow = null)
    {
        $this->workflow = $workflow;

        return $this;
    }

    /**
     * Get workflow
     *
     * @return \Ger\Bundle\WorkflowBundle\Entity\Workflow
     */
    public function getWorkflow()
    {
        return $this->workflow;
    }

    /**
     * Set parent
     *
     * @param \Ger\Bundle\WorkflowBundle\Entity\Step $parent
     * @return Step
     */
    public function setParent(\Ger\Bundle\WorkflowBundle\Entity\Step $parent = null)
    {
        $this->parent = $parent;

        return $this;
    }

    /**
     * Get parent
     *
     * @return \Ger\Bundle\WorkflowBundle\Entity\Step
     */
    public function getParent()
    {
        return $this->parent;
    }

    /**
     * Set retry_on_failure
     *
     * @param boolean $retryOnFailure
     * @return Step
     */
    public function setRetryOnFailure($retryOnFailure)
    {
        $this->retry_on_failure = $retryOnFailure;

        return $this;
    }

    /**
     * Get retry_on_failure
     *
     * @return boolean
     */
    public function getRetryOnFailure()
    {
        return $this->retry_on_failure;
    }

    /**
     * Set child
     *
     * @param \Ger\Bundle\WorkflowBundle\Entity\Step $child
     * @return Step
     */
    public function setChild(\Ger\Bundle\WorkflowBundle\Entity\Step $child = null)
    {
        $this->child = $child;

        return $this;
    }

    /**
     * Get child
     *
     * @return \Ger\Bundle\WorkflowBundle\Entity\Step
     */
    public function getChild()
    {
        return $this->child;
    }
}


text:
package org.apache.asterix.installer.error;

public class InstallerException extends Exception {

    private static final long serialVersionUID = 1L;

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

}


text:
<?php
declare(strict_types=1);
/**
 * This file is part of beotie/core_bundle
 *
 * As each files provides by the CSCFA, this file is licensed
 * under the MIT license.
 *
 * PHP version 7.1
 *
 * @category Response
 * @package  Beotie_Core_Bundle
 * @author   matthieu vallance <matthieu.vallance@cscfa.fr>
 * @license  MIT <https://opensource.org/licenses/MIT>
 * @link     http://cscfa.fr
 */
namespace Beotie\CoreBundle\Response;

use Beotie\CoreBundle\Response\Error\ResponseErrorBagInterface;
use Beotie\CoreBundle\Response\Data\ResponseDataBagInterface;

/**
 * Response bag interface
 *
 * This interface is used to manage a response
 *
 * @category Response
 * @package  Beotie_Core_Bundle
 * @author   matthieu vallance <matthieu.vallance@cscfa.fr>
 * @license  MIT <https://opensource.org/licenses/MIT>
 * @link     http://cscfa.fr
 */
interface ResponseBagInterface
{
    /**
     * Get error bag
     *
     * This method return the error bag of the response bag
     *
     * @return ResponseErrorBagInterface
     */
    public function getErrorBag() : ResponseErrorBagInterface;

    /**
     * Get data bag
     *
     * This method return the data bag of the response bag
     *
     * @return ResponseDataBagInterface
     */
    public function getDataBag() : ResponseDataBagInterface;
}


text:
module Main where

import App.Params
import App.Ui

main :: IO ()
main = getParams >>= runUi


text:
Personalización de DemocracyOS para debatir políticas de TICs del Instituto.

## Instalación

### Crear containers docker

1. Clonar o descargar este repo en el servidor con docker
2. Ejecutar `docker/bootstrap.sh`
3. Configurar variables en `docker/docker-compose.yml` y `docker/notifier/Dockerfile`
4. Ejecutar con sudo `docker/run_debatics.sh`

### Instalar/Actualizar Debatics Theme

1. Ejecutar con sudo `docker/install_debatics_theme.sh`

## Referencia:

https://github.com/Yachtsman/DemocracyOS-docker


text:
import numpy as np
import param

from panel.widgets import TextInput

from holoviews.core.spaces import DynamicMap, HoloMap
from holoviews.element import Image, Curve
from holoviews.element.comparison import ComparisonTestCase
from holoviews.streams import Params, ParamMethod

class ParamClass(param.Parameterized):

    label = param.String(default='Test')

    @param.depends('label')
    def apply_label(self, obj):
        return obj.relabel(self.label)

    @param.depends('label')
    def dynamic_label(self):
        return self.label + '!'

class TestApplyElement(ComparisonTestCase):

    def setUp(self):
        self.element = Curve([1, 2, 3])

    def test_element_apply_simple(self):
        applied = self.element.apply(lambda x: x.relabel('Test'))
        self.assertEqual(applied, self.element.relabel('Test'))

    def test_element_apply_method_as_string(self):
        applied = self.element.apply('relabel', label='Test')
        self.assertEqual(applied, self.element.relabel('Test'))

    def test_element_apply_with_kwarg(self):
        applied = self.element.apply(lambda x, label: x.relabel(label), label='Test')
        self.assertEqual(applied, self.element.relabel('Test'))

    def test_element_apply_not_dynamic_with_instance_param(self):
        pinst = ParamClass()
        applied = self.element.apply(lambda x, label: x.relabel(label), label=pinst.param.label, dynamic=False)
        self.assertEqual(applied, self.element.relabel('Test'))

    def test_element_apply_not_dynamic_with_method_string(self):
        pinst = ParamClass()
        applied = self.element.apply('relabel', dynamic=False, label=pinst.param.label)
        self.assertEqual(applied, self.element.relabel('Test'))

    def test_element_apply_not_dynamic_with_param_method(self):
        pinst = ParamClass()
        applied = self.element.apply(lambda x, label: x.relabel(label), label=pinst.dynamic_label, dynamic=False)
        self.assertEqual(applied, self.element.relabel('Test!'))

    def test_element_apply_dynamic(self):
        applied = self.element.apply(lambda x: x.relabel('Test'), dynamic=True)
        self.assertEqual(len(applied.streams), 0)
        self.assertEqual(applied[()], self.element.relabel('Test'))

    def test_element_apply_dynamic_with_widget_kwarg(self):
        text = TextInput()
        applied = self.element.apply(lambda x, label: x.relabel(label), label=text)
        self.assertEqual(len(applied.streams), 1)
        self.assertEqual(applied[()].label, '')
        text.value = 'Test'
        self.assertEqual(applied[()].label, 'Test')

    def test_element_apply_dynamic_with_kwarg(self):
        applied = self.element.apply(lambda x, label: x.relabel(label), dynamic=True, label='Test')
        self.assertEqual(len(applied.streams), 0)
        self.assertEqual(applied[()], self.element.relabel('Test'))

    def test_element_apply_dynamic_element_method(self):
        pinst = ParamClass()
        applied = self.element.apply(self.element.relabel, label=pinst.param.label)

        # Check stream
        self.assertEqual(len(applied.streams), 1)
        stream = applied.streams[0]
        self.assertIsInstance(stream, Params)
        self.assertEqual(stream.parameterized, pinst)
        self.assertEqual(stream.parameters, [pinst.param.label])

        # Check results
        self.assertEqual(applied[()], self.element.relabel('Test'))
        pinst.label = 'Another label'
        self.assertEqual(applied[()], self.element.relabel('Another label'))

    def test_element_apply_dynamic_with_instance_param(self):
        pinst = ParamClass()
        applied = self.element.apply(lambda x, label: x.relabel(label), label=pinst.param.label)

        # Check stream
        self.assertEqual(len(applied.streams), 1)
        stream = applied.streams[0]
        self.assertIsInstance(stream, Params)
        self.assertEqual(stream.parameterized, pinst)
        self.assertEqual(stream.parameters, [pinst.param.label])

        # Check results
        self.assertEqual(applied[()], self.element.relabel('Test'))
        pinst.label = 'Another label'
        self.assertEqual(applied[()], self.element.relabel('Another label'))

    def test_element_apply_param_method_with_dependencies(self):
        pinst = ParamClass()
        applied = self.element.apply(pinst.apply_label)

        # Check stream
        self.assertEqual(len(applied.streams), 1)
        stream = applied.streams[0]
        self.assertIsInstance(stream, ParamMethod)
        self.assertEqual(stream.parameterized, pinst)
        self.assertEqual(stream.parameters, [pinst.param.label])

        # Check results
        self.assertEqual(applied[()], self.element.relabel('Test'))
        pinst.label = 'Another label'
        self.assertEqual(applied[()], self.element.relabel('Another label'))

    def test_element_apply_function_with_dependencies(self):
        pinst = ParamClass()

        @param.depends(pinst.param.label)
        def get_label(label):
            return label + '!'

        applied = self.element.apply('relabel', label=get_label)

        # Check stream
        self.assertEqual(len(applied.streams), 1)
        stream = applied.streams[0]
        self.assertIsInstance(stream, Params)
        self.assertEqual(stream.parameters, [pinst.param.label])

        # Check results
        self.assertEqual(applied[()], self.element.relabel('Test!'))

        # Ensure subscriber gets called
        stream.add_subscriber(lambda **kwargs: applied[()])
        pinst.label = 'Another label'
        self.assertEqual(applied.last, self.element.relabel('Another label!'))

    def test_element_apply_function_with_dependencies_non_dynamic(self):
        pinst = ParamClass()

        @param.depends(pinst.param.label)
        def get_label(label):
            return label + '!'

        applied = self.element.apply('relabel', dynamic=False, label=get_label)
        self.assertEqual(applied, self.element.relabel('Test!'))

    def test_element_apply_dynamic_with_param_method(self):
        pinst = ParamClass()
        applied = self.element.apply(lambda x, label: x.relabel(label), label=pinst.dynamic_label)

        # Check stream
        self.assertEqual(len(applied.streams), 1)
        stream = applied.streams[0]
        self.assertIsInstance(stream, ParamMethod)
        self.assertEqual(stream.parameterized, pinst)
        self.assertEqual(stream.parameters, [pinst.param.label])

        # Check result
        self.assertEqual(applied[()], self.element.relabel('Test!'))
        pinst.label = 'Another label'
        self.assertEqual(applied[()], self.element.relabel('Another label!'))

    def test_holomap_apply_with_method(self):
        hmap = HoloMap({i: Image(np.array([[i, 2], [3, 4]])) for i in range(3)})
        reduced = hmap.apply.reduce(x=np.min)

        expected = HoloMap({i: Curve([(-0.25, 3), (0.25, i)], 'y', 'z') for i in range(3)})
        self.assertEqual(reduced, expected)

class TestApplyDynamicMap(ComparisonTestCase):

    def setUp(self):
        self.element = Curve([1, 2, 3])
        self.dmap_unsampled = DynamicMap(lambda i: Curve([0, 1, i]), kdims='Y')
        self.dmap = self.dmap_unsampled.redim.values(Y=[0, 1, 2])

    def test_dmap_apply_not_dynamic_unsampled(self):
        with self.assertRaises(ValueError):
            self.dmap_unsampled.apply(lambda x: x.relabel('Test'), dynamic=False)

    def test_dmap_apply_not_dynamic(self):
        applied = self.dmap.apply(lambda x: x.relabel('Test'), dynamic=False)
        self.assertEqual(applied, HoloMap(self.dmap[[0, 1, 2]]).relabel('Test'))

    def test_dmap_apply_not_dynamic_with_kwarg(self):
        applied = self.dmap.apply(lambda x, label: x.relabel(label), dynamic=False, label='Test')
        self.assertEqual(applied, HoloMap(self.dmap[[0, 1, 2]]).relabel('Test'))

    def test_dmap_apply_not_dynamic_with_instance_param(self):
        pinst = ParamClass()
        applied = self.dmap.apply(lambda x, label: x.relabel(label), label=pinst.param.label, dynamic=False)
        self.assertEqual(applied, HoloMap(self.dmap[[0, 1, 2]]).relabel('Test'))

    def test_dmap_apply_not_dynamic_with_param_method(self):
        pinst = ParamClass()
        applied = self.dmap.apply(lambda x, label: x.relabel(label), label=pinst.dynamic_label, dynamic=False)
        self.assertEqual(applied, HoloMap(self.dmap[[0, 1, 2]]).relabel('Test!'))

    def test_dmap_apply_dynamic(self):
        applied = self.dmap.apply(lambda x: x.relabel('Test'))
        self.assertEqual(len(applied.streams), 0)
        self.assertEqual(applied[1], self.dmap[1].relabel('Test'))

    def test_element_apply_method_as_string(self):
        applied = self.dmap.apply('relabel', label='Test')
        self.assertEqual(applied[1], self.dmap[1].relabel('Test'))

    def test_dmap_apply_dynamic_with_kwarg(self):
        applied = self.dmap.apply(lambda x, label: x.relabel(label), label='Test')
        self.assertEqual(len(applied.streams), 0)
        self.assertEqual(applied[1], self.dmap[1].relabel('Test'))

    def test_dmap_apply_dynamic_with_instance_param(self):
        pinst = ParamClass()
        applied = self.dmap.apply(lambda x, label: x.relabel(label), label=pinst.param.label)

        # Check stream
        self.assertEqual(len(applied.streams), 1)
        stream = applied.streams[0]
        self.assertIsInstance(stream, Params)
        self.assertEqual(stream.parameterized, pinst)
        self.assertEqual(stream.parameters, [pinst.param.label])

        # Check results
        self.assertEqual(applied[1], self.dmap[1].relabel('Test'))
        pinst.label = 'Another label'
        self.assertEqual(applied[1], self.dmap[1].relabel('Another label'))

    def test_dmap_apply_method_as_string_with_instance_param(self):
        pinst = ParamClass()
        applied = self.dmap.apply('relabel', label=pinst.param.label)
        self.assertEqual(applied[1], self.dmap[1].relabel('Test'))
        pinst.label = 'Another label'
        self.assertEqual(applied[1], self.dmap[1].relabel('Another label'))

    def test_dmap_apply_param_method_with_dependencies(self):
        pinst = ParamClass()
        applied = self.dmap.apply(pinst.apply_label)

        # Check stream
        self.assertEqual(len(applied.streams), 1)
        stream = applied.streams[0]
        self.assertIsInstance(stream, ParamMethod)
        self.assertEqual(stream.parameterized, pinst)
        self.assertEqual(stream.parameters, [pinst.param.label])

        # Check results
        self.assertEqual(applied[1], self.dmap[1].relabel('Test'))
        pinst.label = 'Another label'
        self.assertEqual(applied[1], self.dmap[1].relabel('Another label'))

    def test_dmap_apply_dynamic_with_param_method(self):
        pinst = ParamClass()
        applied = self.dmap.apply(lambda x, label: x.relabel(label), label=pinst.dynamic_label)

        # Check stream
        self.assertEqual(len(applied.streams), 1)
        stream = applied.streams[0]
        self.assertIsInstance(stream, ParamMethod)
        self.assertEqual(stream.parameterized, pinst)
        self.assertEqual(stream.parameters, [pinst.param.label])

        # Check result
        self.assertEqual(applied[1], self.dmap[1].relabel('Test!'))
        pinst.label = 'Another label'
        self.assertEqual(applied[1], self.dmap[1].relabel('Another label!'))


text:
class SyncObjectJob < ApplicationJob
  queue_as :default

  def perform(sync_token:)
    sync_token.sync_object
  end
end


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

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
	xmlns:app="http://schemas.android.com/apk/res-auto"
	xmlns:tools="http://schemas.android.com/tools"
	android:layout_width="match_parent"
	android:layout_height="match_parent">

	<androidx.appcompat.widget.LinearLayoutCompat
		android:id="@+id/no_downloads"
		android:layout_width="match_parent"
		android:layout_height="match_parent"
		android:gravity="center"
		android:orientation="vertical"
		android:visibility="gone"
		tools:ignore="UseCompoundDrawables"
		tools:visibility="visible">

		<androidx.appcompat.widget.AppCompatImageView
			android:layout_width="match_parent"
			android:layout_height="100dp"
			android:contentDescription="@null"
			android:src="@drawable/ic_sad_tv"
			android:tint="#bebebe" />

		<com.google.android.material.textview.MaterialTextView
			style="@style/TextAppearance.MaterialComponents.Headline4"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:gravity="center"
			android:text="@string/fragment_downloads_no_results" />

	</androidx.appcompat.widget.LinearLayoutCompat>

	<androidx.recyclerview.widget.RecyclerView
		android:id="@+id/list"
		android:layout_width="match_parent"
		android:layout_height="match_parent"
		android:scrollbars="vertical"
		app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
		tools:context=".app.downloads.ui.list.DownloadsFragment"
		tools:listitem="@layout/downloads_fragment_list_item" />

</androidx.constraintlayout.widget.ConstraintLayout>


text:
namespace llvm {
class Error;
class GlobalValue;
class Metadata;
class Module;
class StructType;
class TrackingMDRef;
class Type;

class IRMover {
  struct StructTypeKeyInfo {
    struct KeyTy {
      ArrayRef<Type *> ETypes;
      bool IsPacked;
      KeyTy(ArrayRef<Type *> E, bool P);
      KeyTy(const StructType *ST);
      bool operator==(const KeyTy &that) const;
      bool operator!=(const KeyTy &that) const;
    };
    static StructType *getEmptyKey();
    static StructType *getTombstoneKey();
    static unsigned getHashValue(const KeyTy &Key);
    static unsigned getHashValue(const StructType *ST);
    static bool isEqual(const KeyTy &LHS, const StructType *RHS);
    static bool isEqual(const StructType *LHS, const StructType *RHS);
  };

  /// Type of the Metadata map in \a ValueToValueMapTy.
  typedef DenseMap<const Metadata *, TrackingMDRef> MDMapT;

public:
  class IdentifiedStructTypeSet {
    // The set of opaque types is the composite module.
    DenseSet<StructType *> OpaqueStructTypes;

    // The set of identified but non opaque structures in the composite module.
    DenseSet<StructType *, StructTypeKeyInfo> NonOpaqueStructTypes;

  public:
    void addNonOpaque(StructType *Ty);
    void switchToNonOpaque(StructType *Ty);
    void addOpaque(StructType *Ty);
    StructType *findNonOpaque(ArrayRef<Type *> ETypes, bool IsPacked);
    bool hasType(StructType *Ty);
  };

  IRMover(Module &M);

  typedef std::function<void(GlobalValue &)> ValueAdder;

  /// Move in the provide values in \p ValuesToLink from \p Src.
  ///
  /// - \p AddLazyFor is a call back that the IRMover will call when a global
  ///   value is referenced by one of the ValuesToLink (transitively) but was
  ///   not present in ValuesToLink. The GlobalValue and a ValueAdder callback
  ///   are passed as an argument, and the callback is expected to be called
  ///   if the GlobalValue needs to be added to the \p ValuesToLink and linked.
  /// - \p LinkModuleInlineAsm is true if the ModuleInlineAsm string in Src
  ///   should be linked with (concatenated into) the ModuleInlineAsm string
  ///   for the destination module. It should be true for full LTO, but not
  ///   when importing for ThinLTO, otherwise we can have duplicate symbols.
  /// - \p IsPerformingImport is true when this IR link is to perform ThinLTO
  ///   function importing from Src.
  Error move(std::unique_ptr<Module> Src, ArrayRef<GlobalValue *> ValuesToLink,
             std::function<void(GlobalValue &GV, ValueAdder Add)> AddLazyFor,
             bool LinkModuleInlineAsm, bool IsPerformingImport);
  Module &getModule() { return Composite; }

private:
  Module &Composite;
  IdentifiedStructTypeSet IdentifiedStructTypes;
  MDMapT SharedMDs; ///< A Metadata map to use for all calls to \a move().
};

} // End llvm namespace

#endif


text:
package engg2800.ui.listeners.action.event.handlers;

import engg2800.image.TransmittedImage;
import engg2800.image.processing.ByteArrayToBufferedImage;
import engg2800.ui.WindowFrame;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * Handles User actions on Load Button
 * @author Aaron Hayes
 */
public class LoadButtonActionHandler {
    private WindowFrame windowFrame;

    /**
     * Basic constructor
     * @param wf WindowFrame
     */
    public LoadButtonActionHandler(WindowFrame wf) {
        windowFrame = wf;

        ActionListener a = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser fc = new JFileChooser();
                fc.setDialogTitle("Load Image From File");
                int returnVal = fc.showOpenDialog(windowFrame);

                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    FileInputStream in = null;
                    File file = fc.getSelectedFile();

                    if (file.getAbsolutePath().endsWith(".raw") || file.getAbsolutePath().endsWith(".bytes") || !file.getAbsolutePath().contains("")) {
                        try {
                            in = new FileInputStream(file);
                            int c;

                            byte[] bytes = new byte[TransmittedImage.IMG_HEIGHT * TransmittedImage.IMG_WIDTH];

                            int count = 0;
                            while ((c = in.read()) != -1) {
                                bytes[count++] = (byte) (c & 0xFF);
                            }

                            BufferedImage bufferedImage = ByteArrayToBufferedImage.Convert(bytes, TransmittedImage.IMG_WIDTH, TransmittedImage.IMG_HEIGHT);
                            windowFrame.addImage(new TransmittedImage(bufferedImage, TransmittedImage.IMG_WIDTH, TransmittedImage.IMG_HEIGHT));

                        } catch (FileNotFoundException e1) {
                            e1.printStackTrace();
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        } catch (ArrayIndexOutOfBoundsException e1) {
                            System.err.println("Invalid file format, must be 8 bit 320 x 240 pixels");
                        }
                    } else {
                        try {
                        	BufferedImage bufferedimage = ImageIO.read(file);
                            TransmittedImage image = new TransmittedImage(bufferedimage, bufferedimage.getWidth(), bufferedimage.getHeight());
                            windowFrame.addImage(image);
                        } catch (IOException e1) {
                            System.out.println("Unable to Load Image");
                        }
                    }
                }
            }
        };

        wf.getControlPanel().getButtonPanel().addActionListenerLoad(a);
    }
}


text:
* Updates default test framework to RSpec 3
* Updates library to use SSL exclusively when hitting the Fitbit REST API. Fitbit is restricting access to its API via https only on November 3rd, 2014. See [issue #30](https://github.com/whazzmaster/fitgem/issues/30) for more information. This should be transparent to end users of fitgem, as the library simply ignores the :ssl option in the Client constructor and defaults to https everywhere.
* The previously-deprecated `weekly_leaderboard` and `monthly_leaderboard` methods have now been updated to throw a `DeprecatedApiError` rather than warning about deprecation. These methods will be removed in v1.0.

## v0.9.0

#### 2014-02-11 Zachery Moneypenny <fitgem@whazzmaster.com>

The v0.9.0 release adds a number of new methods to match new functionality available through the Fitbit REST API. It
also removes support for concepts (monthly leaderboards) that have been removed from the Fitbit REST API.

There's a big change to **leaderboard support** in this update; please read the notes below if you're currently using
`monthly_leaderboard` or `weekly_leaderboard` -- you should update your code to use the new method before v1.0 is
released.

* Add ability to target SSL Fitbit REST endpoints
* Add `activity_on_date_range` method
* Condense existing `weekly_leaderboard` and (no longer available) `monthly_leaderboard` into a simple `leaderboard`
method. There is now only one leaderboard (weekly) so no need to differentiate in the API. The previous leaderboard
methods are now deprecated and **will be removed** in v1.0.
* Add `create_or_update_weekly_goal` method and specs
* Add `create_or_update_daily_goal` method and specs
* Add `daily_goals` method and update documentation
* Add `delete_body_fat_log` method
* Add `delete_body_weight_log` method
* Add `create_or_update_body_fat_goal` method
* Add `create_or_update_body_weight_goal` method
* Add `log_body_fat` method to push a body fat measurement to Fitbit
* Add `body_fat_goal` method to fetch the current body fat goal
* Add `body_fat` method to fetch body fat measurements
* Add `body_weight` method to fetch body fat measurements
* For the `body_weight` and `body_fat` methods, determine a URI based on the base URI and provided options

## v0.8.0

#### 2013-08-03 Zachery Moneypenny <fitgem@whazzmaster.com>

* Add support for weekly goals
* Add support for silent alarms (including updates)
* Add support for intraday distance
* Add time zone support for usage of times
* Add support for badges

## v0.7.0

#### 2013-05-17 Zachery Moneypenny <fitgem@whazzmaster.com>

* Add support for intraday time series retrieval of various resources
* Removed rvmrc from project- use whatever ruby you want!
* Updated Travis CI configuration

## v0.6.1

#### 2013-02-28 Zachery Moneypenny <fitgem@whazzmaster.com>

* More unit tests
* Fix an issue where we weren't applying the `format_date` helper when constructing a date range fragment

## v0.6.0

* Streamline the README; add contributors link
* Removed FAQs from README
* Added support for daily activity goals
* Moved testing-focused gemspec dependencies to the Gemfile

#### 2013-02-13 Zachery Moneypenny <fitgem@whazzmaster.com>

## v0.5.2

#### 2012-03-04 Zachery Moneypenny <fitgem@whazzmaster.com>

* Added new <tt>symbolize_keys</tt> helper method for turning the string-key based return hashes into symbol-key based ones
* Added new <tt>label_for_measurement</tt> helper method to get the correct unit measurement label given a measurement type and the current user's ApiUnitSystem setting
* Added specs
* Added new <tt>connected?</tt> method on Fitgem::Client that will report whether API calls may be made
* Added <tt>InvalidUnitSystem</tt> error and <tt>InvalidMeasurementType</tt> error
* Fixed a small issue where date values were not being formatted correctly in calls to <tt>log_body_measurements</tt>

## v0.5.1

#### 2012-01-24 Zachery Moneypenny <fitgem@whazzmaster.com>

* Fix for creating and removing data subscriptions
* Updated specs

## v0.5.0

#### 2012-01-22 Zachery Moneypenny <fitgem@whazzmaster.com>

* Added view/log/delete access for blood pressure data
* Added view/log/delete access for glucose data
* Added view/log/delete access for heart rate data
* Added updated time series documentation for new endpoints
* Updated temporal information in the readme
* Added unit tests for <tt>format_time</tt> method
* Updated copyright date

## v0.4.0

#### 2011-11-29 Zachery Moneypenny <fitgem@whazzmaster.com>

* Added YARD documentation to thoroughly document code
* DEPRECATED: <tt>Fitgem::Client#log_weight</tt> method, use <tt>Fitgem::Client#log_body_measurements</tt> instead.
  The new method allows you to log more than weight (bicep size, body fat %, etc.)
* Added <tt>Fitgem::FoodFormType</tt> to be used in calls to <tt>Fitgem::Client#create_food</tt>
* Added <tt>Fitgem::Client#log_sleep</tt> to log sleep data to fitbit
* Added <tt>Fitgem::Client#delete_sleep_log</tt> to delete previously logged sleep data
* Added <tt>Fitgem::Client#activities</tt> method to get a list of all activities
* Added <tt>Fitgem::Client#activity_statistics</tt> method to get statistics for all logged activities
* Added to documentation of supported endpoints for <tt>Fitgem::Client#data_by_time_range</tt>
* Added unit tests for parameter validation for many methods
* Overhauled notifications methods, including extensive documentation,
  unit tests, refactoring, and a couple of bug fixes.  These methods now
  return both the HTTP status code and the JSON response body.  See https://wiki.fitbit.com/display/API/Subscriptions-API
  for information on how to interpret each of the error codes.
* Added fitgem to travis-ci for continuous integration (http://travis-ci.org/#!/whazzmaster/fitgem)
* Added fitgem to rubydoc.info (http://rubydoc.info/github/whazzmaster/fitgem/master/frames)
* Updated README
* Moved OAuth documentation from the README to the [fitgem wiki](https://github.com/whazzmaster/fitgem/wiki/The-OAuth-Process)

## v0.3.6

#### 2011-07-12 Zachery Moneypenny <fitgem@whazzmaster.com>

* Added friends support (get friends, friend leaderboard, create invites, accept/reject invites)
* Added water support (get water data per date)
* Added sleep support (get sleep data per date)
* Added ability to update user profile information

## Previous Releases

#### 2011-05-11 Zachery Moneypenny <fitgem@whazzmaster.com>

* Changed name and all references of this project from 'fitbit' to 'fitgem'

#### 2011-04-11 Zachery Moneypenny <fitgem@whazzmaster.com>

* Fixed an issue where blank user id's are used and an error is thrown.
* Added support for creating/removing subscriptions (this support is experimental for now, more tests coming)

#### 2011-03-24 Zachery Moneypenny <fitgem@whazzmaster.com>

* Added logging of activities and foods
* Added ability to add favorite activities and foods
* Added ability to delete logged activities and foods, and remove favorite activities and foods
* Refactored data_by_time_range for more testability
* Added ability to query devices

#### 2011-03-19 Zachery Moneypenny <fitgem@whazzmaster.com>

* Updated auth client to support first-time auth and reconnections (if you have previously been authorized and received token/secret).
* Added 'named' retrieval of activities and foods (recent_, favorite_, frequent_)
* Added ability to log weight back to the site using the API

#### 2011-03-18 Zachery Moneypenny <fitgem@whazzmaster.com>

* First revision. Supports the auth process via oauth, and retrieval of user info and activities.


text:
import pytest
from pytest import raises

import jj
from jj.middlewares import SelfMiddleware
from jj.mock import Mock, RemoteMock
from jj.mock._remote_mock import _RemoteMockError

from .._test_utils import run

@pytest.mark.asyncio
async def test_mock_default_handler():
    mock = Mock()
    self_middleware = SelfMiddleware(mock.resolver)

    async with run(mock, middlewares=[self_middleware]) as client:
        response = await client.get("/")
        assert response.status == 404

@pytest.mark.asyncio
async def test_mock_register():
    mock = Mock()
    self_middleware = SelfMiddleware(mock.resolver)
    matcher, response = jj.match("*"), jj.Response(status=200, body=b"text")

    async with run(mock, middlewares=[self_middleware]) as client:
        remote_mock = RemoteMock(client.make_url("/"))
        handler = remote_mock.create_handler(matcher, response)
        await handler.register()

        response = await client.get("/")
        response_body = await response.read()

        assert response.status == 200
        assert response_body == b"text"

@pytest.mark.asyncio
async def test_mock_register_bad_request():
    mock = Mock()
    self_middleware = SelfMiddleware(mock.resolver)

    async with run(mock, middlewares=[self_middleware]) as client:
        remote_mock = RemoteMock(client.make_url("/"))
        handler = remote_mock.create_handler(None, None)

        with raises(Exception) as exception:
            await handler.register()
        assert exception.type is _RemoteMockError

@pytest.mark.asyncio
async def test_mock_deregister():
    mock = Mock()
    self_middleware = SelfMiddleware(mock.resolver)
    matcher, response = jj.match("*"), jj.Response(status=200, body=b"text")

    async with run(mock, middlewares=[self_middleware]) as client:
        remote_mock = RemoteMock(client.make_url("/"))
        handler = remote_mock.create_handler(matcher, response)
        await handler.register()
        await handler.deregister()

        response = await client.get("/")
        assert response.status == 404

@pytest.mark.asyncio
async def test_mock_deregister_not_registered():
    mock = Mock()
    self_middleware = SelfMiddleware(mock.resolver)
    matcher, response = jj.match("*"), jj.Response(status=200, body=b"text")

    async with run(mock, middlewares=[self_middleware]) as client:
        remote_mock = RemoteMock(client.make_url("/"))
        handler = remote_mock.create_handler(matcher, response)
        await handler.deregister()

@pytest.mark.asyncio
async def test_mock_deregister_bad_request():
    mock = Mock()
    self_middleware = SelfMiddleware(mock.resolver)

    async with run(mock, middlewares=[self_middleware]) as client:
        remote_mock = RemoteMock(client.make_url("/"))
        handler = remote_mock.create_handler(None, None)

        with raises(Exception) as exception:
            await handler.deregister()
        assert exception.type is _RemoteMockError

@pytest.mark.asyncio
async def test_mock_handler_order():
    mock = Mock()
    self_middleware = SelfMiddleware(Mock().resolver)
    matcher1, response1 = jj.match("*"), jj.Response(body=b"text1")
    matcher2, response2 = jj.match("*"), jj.Response(body=b"text2")

    async with run(mock, middlewares=[self_middleware]) as client:
        remote_mock = RemoteMock(client.make_url("/"))
        handler1 = remote_mock.create_handler(matcher1, response1)
        handler2 = remote_mock.create_handler(matcher2, response2)
        async with handler1:
            async with handler2:
                resp = await client.get("/")
                assert resp.status == 200
                body = await resp.read()
                assert body == b"text2"