text:
import os
import os.path
import sys
import traceback
import logging
import config as sdm_config
import mount_table as sdm_mount_table
import repository as sdm_repository
import backends as sdm_backends
import abstract_backend as sdm_absbackends
import util as sdm_util

from prettytable import PrettyTable

SDM_CONFIG_DIR = "~/.sdm"
CONFIG_PATH = ""
MOUNT_TABLE_PATH = ""

config = None
mount_table = None
repository = None
backend = None

OPTIONS_TABLE = {}
COMMANDS = []
COMMANDS_TABLE = {}

def fill_options_table():
    """
    Additional options
    """
    OPTIONS_TABLE["log"] = getattr(logging, "WARNING", None)
    OPTIONS_TABLE["config"] = SDM_CONFIG_DIR

def fill_commands_table():
    COMMANDS.append((["list_datasets", "ls", "list"], list_datasets, "list datasets"))
    COMMANDS.append((["search_datasets", "find", "search", "grep"], search_datasets, "search datasets"))
    COMMANDS.append((["show_mounts", "ps", "status"], show_mounts, "show mount status"))
    COMMANDS.append((["mount", "mnt"], mount_dataset, "mount a dataset"))
    COMMANDS.append((["mmount", "mmnt"], mount_multi_dataset, "mount multi-datasets"))
    COMMANDS.append((["unmount", "umount", "umnt"], unmount_dataset, "unmount a dataset"))
    COMMANDS.append((["munmount", "mumount", "mumnt"], unmount_multi_dataset, "unmount multi-dataset"))
    COMMANDS.append((["clean"], clean_mounts, "clear broken mounts"))
    COMMANDS.append((["help", "h"], show_help, "show help"))

    for cmd in COMMANDS:
        karr, _, _ = cmd
        for k in karr:
            COMMANDS_TABLE[k] = cmd

def list_datasets(argv):
    """
    List Datasets
    """
    if len(argv) == 0:
        entries = repository.list_entries()
        cnt = 0
        tbl = PrettyTable()
        tbl.field_names = ["DATASET", "DESCRIPTION"]
        for ent in entries:
            cnt += 1
            tbl.add_row([ent.dataset, ent.description])

        sdm_util.print_message(tbl)

        if cnt == 0:
            sdm_util.print_message("No available dataset")
            return 0
        else:
            return 0
    else:
        show_help(["list_datasets"])
        return 1

def search_datasets(argv):
    """
    Search Datasets

    args:
        arg1: query
    """
    if len(argv) >= 1:
        query = argv[0].strip().lower()

        entries = repository.list_entries(query)
        cnt = 0
        tbl = PrettyTable()
        tbl.field_names = ["DATASET", "DESCRIPTION"]
        for ent in entries:
            cnt += 1
            tbl.add_row([ent.dataset, ent.description])

        sdm_util.print_message(tbl)

        if cnt == 0:
            sdm_util.print_message("No matching dataset")
            return 0
        else:
            return 0
    else:
        show_help(["search_datasets"])
        return 1

def show_mounts(argv):
    """
    Show mounts
    """
    if len(argv) == 0:
        records = mount_table.list_records()
        cnt = 0
        tbl = PrettyTable()
        tbl.field_names = ["MOUNT_ID", "DATASET", "MOUNT_PATH", "BACKEND", "STATUS"]

        need_sync = False
        for rec in records:
            # detect out-of-sync record
            bimpl = sdm_backends.Backends.get_backend_instance(rec.backend, config.get_backend_config(rec.backend))

            is_mounted = bimpl.check_mount(rec.record_id, rec.dataset, rec.mount_path)
            is_status_mounted = rec.status == sdm_mount_table.MountRecordStatus.MOUNTED

            if is_mounted != is_status_mounted:
                if is_mounted:
                    rec.status = sdm_mount_table.MountRecordStatus.MOUNTED
                else:
                    rec.status = sdm_mount_table.MountRecordStatus.UNMOUNTED
                need_sync = True

            cnt += 1
            tbl.add_row([rec.record_id[:12], rec.dataset, rec.mount_path, rec.backend, rec.status])

        sdm_util.print_message(tbl)

        if need_sync:
            mount_table.save_table(MOUNT_TABLE_PATH)

        if cnt == 0:
            sdm_util.print_message("No mounts")
            return 0
        else:
            return 0
    else:
        show_help(["show_mounts"])
        return 1

def process_mount_dataset(dataset, mount_path):
    """
    Begin the dataset mount process
    """
    entry = repository.get_entry(dataset)
    if entry:
        username = entry.username
        user_pkey = entry.user_pkey
        if username.strip() == "" or user_pkey.strip() == "":
            # use local settings
            syndicate_users = config.list_syndicate_users_by_ms_host(entry.ms_host)
            for suser in syndicate_users:
                username = suser.username
                user_pkey = suser.user_pkey
                break

        if username.strip() == "" or user_pkey.strip() == "":
            sdm_util.print_message("Cannot find user accounts to access the dataset - %s" % (dataset))
            return 1

        try:
            bimpl = sdm_backends.Backends.get_backend_instance(backend, config.get_backend_config(backend))
            if not bimpl.is_legal_mount_path(mount_path):
                sdm_util.print_message("Cannot mount dataset to the given mount path for wrong mount path - %s" % (mount_path))
                return 1

            # check existance
            records = mount_table.get_records_by_mount_path(mount_path)
            for rec in records:
                if rec.dataset == dataset and rec.status == sdm_mount_table.MountRecordStatus.UNMOUNTED:
                    # same dataset but unmounted
                    # delete and overwrite
                    mount_table.delete_record(rec.record_id)

            mount_record = mount_table.add_record(dataset, mount_path, backend, sdm_mount_table.MountRecordStatus.UNMOUNTED)
            mount_table.save_table(MOUNT_TABLE_PATH)

            bimpl.mount(
                mount_record.record_id,
                entry.ms_host,
                entry.dataset,
                username,
                user_pkey,
                entry.gateway,
                mount_path
            )
            mount_record.status = sdm_mount_table.MountRecordStatus.MOUNTED
            mount_table.save_table(MOUNT_TABLE_PATH)
            return 0
        except sdm_mount_table.MountTableException, e:
            sdm_util.print_message("Cannot mount dataset - %s to  %s" % (dataset, mount_path), True, sdm_util.LogLevel.ERROR)
            sdm_util.print_message(e, True, sdm_util.LogLevel.ERROR)
            return 1
        except sdm_absbackends.AbstractBackendException, e:
            sdm_util.print_message("Cannot mount dataset - %s to  %s" % (dataset, mount_path), True, sdm_util.LogLevel.ERROR)
            sdm_util.print_message(e, True, sdm_util.LogLevel.ERROR)
            return 1
    else:
        sdm_util.print_message("Dataset not found - %s" % dataset)
        return 1

def mount_dataset(argv):
    """
    Mount the dataset

    args:
        arg1: dataset name
        arg2: mount_path (optional)
    """
    if len(argv) >= 1:
        dataset = argv[0].strip().lower()

        try:
            bimpl = sdm_backends.Backends.get_backend_instance(backend, config.get_backend_config(backend))
            mount_path = bimpl.make_default_mount_path(dataset, config.get_backend_config(backend).default_mount_path)

            if len(argv) >= 2 and len(argv[1].strip()) != 0:
                mount_path = argv[1].strip()

            abs_mount_path = sdm_util.get_abs_path(mount_path)
            return process_mount_dataset(dataset, abs_mount_path)
        except sdm_absbackends.AbstractBackendException, e:
            sdm_util.print_message("Cannot mount dataset - %s" % dataset, True, sdm_util.LogLevel.ERROR)
            sdm_util.print_message(e, True, sdm_util.LogLevel.ERROR)
            return 1
    else:
        show_help(["mount"])
        return 1

def mount_multi_dataset(argv):
    """
    Mount a multi dataset

    args:
        arg1: dataset name
    """
    if len(argv) >= 1:
        try:
            bimpl = sdm_backends.Backends.get_backend_instance(backend, config.get_backend_config(backend))

            for d in argv:
                dataset = d.strip().lower()
                mount_path = bimpl.make_default_mount_path(dataset, config.get_backend_config(backend).default_mount_path)
                abs_mount_path = sdm_util.get_abs_path(mount_path)
                res = process_mount_dataset(dataset, abs_mount_path)
                if res > 0:
                    return res
            return 0
        except sdm_absbackends.AbstractBackendException, e:
            sdm_util.print_message("Cannot mount dataset - %s" % dataset, True, sdm_util.LogLevel.ERROR)
            sdm_util.print_message(e, True, sdm_util.LogLevel.ERROR)
            return 1
    else:
        show_help(["mmount"])
        return 1

def process_unmount_dataset(record_id, cleanup=False):
    """
    Unmount a dataset
    """
    try:
        records = mount_table.get_records_by_record_id(record_id)
        if len(records) == 1:
            record = records[0]
            if not cleanup and record.status == sdm_mount_table.MountRecordStatus.UNMOUNTED:
                sdm_util.print_message("Dataset is already unmounted")
                return 1

            bimpl = sdm_backends.Backends.get_backend_instance(record.backend, config.get_backend_config(record.backend))
            record.status = sdm_mount_table.MountRecordStatus.UNMOUNTED

            bimpl.unmount(record.record_id, record.dataset, record.mount_path, cleanup)
            if cleanup:
                mount_table.delete_record(record.record_id)

            mount_table.save_table(MOUNT_TABLE_PATH)
            return 0
        else:
            sdm_util.print_message("Cannot unmount. There are %d mounts" % len(records))
            return 1
    except sdm_mount_table.MountTableException, e:
        sdm_util.print_message("Cannot unmount - %s" % (record_id), True, sdm_util.LogLevel.ERROR)
        sdm_util.print_message(e, True, sdm_util.LogLevel.ERROR)
        return 1
    except sdm_absbackends.AbstractBackendException, e:
        sdm_util.print_message("Cannot unmount - %s" % (record_id), True, sdm_util.LogLevel.ERROR)
        sdm_util.print_message(e, True, sdm_util.LogLevel.ERROR)
        return 1

def unmount_dataset(argv):
    """
    Unmount a dataset

    args:
        arg1: dataset name OR mount_path
    """
    if len(argv) >= 1:
        cleanup = False
        if len(argv) >= 2:
            cleanup = sdm_util.to_bool(argv[1])

        arg = argv[0]

        # dataset?
        records = mount_table.get_records_by_dataset(arg)
        if len(records) > 0:
            if len(records) == 1:
                return process_unmount_dataset(records[0].record_id, cleanup)
            else:
                sdm_util.print_message("Cannot unmount dataset. There are more %d mounts" % len(records))
                return 1

        # record_id?
        records = mount_table.get_records_by_record_id(arg)
        if len(records) > 0:
            if len(records) == 1:
                return process_unmount_dataset(records[0].record_id, cleanup)
            else:
                sdm_util.print_message("Cannot unmount dataset. There are more %d mounts" % len(records))
                return 1

        # path?
        path = sdm_util.get_abs_path(arg)
        records = mount_table.get_records_by_mount_path(path)
        if len(records) > 0:
            if len(records) == 1:
                return process_unmount_dataset(records[0].record_id, cleanup)
            else:
                sdm_util.print_message("Cannot unmount dataset. There are more %d mounts" % len(records))
                return 1

        sdm_util.print_message("Cannot find mount - %s" % argv[0])
        return 1
    else:
        show_help(["unmount"])
        return 1

def unmount_multi_dataset(argv):
    """
    Unmount a multi dataset

    args:
        arg1: dataset name OR mount_path
    """
    if len(argv) >= 1:
        cleanup = False
        res = 0
        for arg in argv:
            # dataset?
            records = mount_table.get_records_by_dataset(arg)
            if len(records) > 0:
                if len(records) == 1:
                    res |= process_unmount_dataset(records[0].record_id, cleanup)
                    continue
                else:
                    sdm_util.print_message("Cannot unmount dataset. There are more %d mounts" % len(records))
                    res |= 1
                    continue

            # record_id?
            records = mount_table.get_records_by_record_id(arg)
            if len(records) > 0:
                if len(records) == 1:
                    res |= process_unmount_dataset(records[0].record_id, cleanup)
                    continue
                else:
                    sdm_util.print_message("Cannot unmount dataset. There are more %d mounts" % len(records))
                    res |= 1
                    continue

            # path?
            path = sdm_util.get_abs_path(arg)
            records = mount_table.get_records_by_mount_path(path)
            if len(records) > 0:
                if len(records) == 1:
                    res |= process_unmount_dataset(records[0].record_id, cleanup)
                    continue
                else:
                    sdm_util.print_message("Cannot unmount dataset. There are more %d mounts" % len(records))
                    res |= 1
                    continue

            sdm_util.print_message("Cannot find mount - %s" % arg)
            res |= 1
        return res
    else:
        show_help(["unmount"])
        return 1

def clean_mounts(argv):
    """
    Clean or unmount mounted datasets
    """
    records = mount_table.list_records()
    for rec in records:
        if rec.status == sdm_mount_table.MountRecordStatus.UNMOUNTED:
            process_unmount_dataset(rec.record_id, True)
    return 0

def show_help(argv=None):
    """
    Print the standard help page
    """
    if argv:
        if "list_datasets" in argv:
            karr, _, desc = COMMANDS_TABLE["list_datasets"]
            sdm_util.print_message("command : %s" % (" | ".join(karr)))
            sdm_util.print_message("usage : sdm ls")
            sdm_util.print_message("")
            sdm_util.print_message(desc)
            return 0
        elif "search_datasets" in argv:
            karr, _, desc = COMMANDS_TABLE["search_datasets"]
            sdm_util.print_message("command : %s" % (" | ".join(karr)))
            sdm_util.print_message("usage : sdm search <keyword>")
            sdm_util.print_message("")
            sdm_util.print_message(desc)
            return 0
        elif "show_mounts" in argv:
            karr, _, desc = COMMANDS_TABLE["show_mounts"]
            sdm_util.print_message("command : %s" % (" | ".join(karr)))
            sdm_util.print_message("usage : sdm ps")
            sdm_util.print_message("")
            sdm_util.print_message(desc)
            return 0
        elif "mount" in argv:
            karr, _, desc = COMMANDS_TABLE["mount"]
            sdm_util.print_message("command : %s" % (" | ".join(karr)))
            sdm_util.print_message("usage : sdm mount <dataset_name> [<mount_path>]")
            sdm_util.print_message("")
            sdm_util.print_message(desc)
            return 0
        elif "mmount" in argv:
            karr, _, desc = COMMANDS_TABLE["mmount"]
            sdm_util.print_message("command : %s" % (" | ".join(karr)))
            sdm_util.print_message("usage : sdm mmount <dataset_name> [<dataset_name> ...]")
            sdm_util.print_message("")
            sdm_util.print_message(desc)
            return 0
        elif "unmount" in argv:
            karr, _, desc = COMMANDS_TABLE["unmount"]
            sdm_util.print_message("command : %s" % (" | ".join(karr)))
            sdm_util.print_message("usage : sdm unmount <mount_id> [<cleanup_flag>]")
            sdm_util.print_message("")
            sdm_util.print_message(desc)
            return 0
        elif "munmount" in argv:
            karr, _, desc = COMMANDS_TABLE["munmount"]
            sdm_util.print_message("command : %s" % (" | ".join(karr)))
            sdm_util.print_message("usage : sdm munmount <mount_id> [<mount_id> ...]")
            sdm_util.print_message("")
            sdm_util.print_message(desc)
            return 0
        elif "clean" in argv:
            karr, _, desc = COMMANDS_TABLE["clean"]
            sdm_util.print_message("command : %s" % (" | ".join(karr)))
            sdm_util.print_message("usage : sdm clean")
            sdm_util.print_message("")
            sdm_util.print_message(desc)
            return 0
        else:
            sdm_util.print_message("Unrecognized command")
            return 1
    else:
        sdm_util.print_message("command : sdm <COMMAND> [<COMMAND_SPECIFIC_ARGS> ...]")
        sdm_util.print_message("")
        sdm_util.print_message("Available Commands")

        tbl = PrettyTable()
        tbl.field_names = ["COMMAND", "DESCRIPTION"]
        for cmd in COMMANDS:
            command, _, desc = cmd
            command_str = " | ".join(command)
            tbl.add_row([command_str, desc])

        sdm_util.print_message(tbl)
        sdm_util.print_message("")
        return 0

def run(command, argv):
    """
    Run
    """
    if command is None:
        raise ValueError("No command is given")

    command = command.lower()

    if command in COMMANDS_TABLE:
        _, func, _ = COMMANDS_TABLE[command]
        func(argv)
    else:
        raise ValueError("Unrecognized command: %s" % (command))

def set_option(k, v="True"):
    """
    Set the option chosen, i.e. log, backend, config
    """
    if k == "log":
        OPTIONS_TABLE[k] = getattr(logging, v.upper(), None)
    elif k == "backend":
        OPTIONS_TABLE[k] = sdm_backends.Backends.get_backend_name(v)
    elif k == "config":
        OPTIONS_TABLE[k] = sdm_util.get_abs_path(v)

def extract_options(argv):
    """
    Extract command-line options
    """
    new_argv = []
    for arg in argv:
        if arg.startswith("--"):
            # extract
            p = arg[2:]
            if "=" in p:
                pa = p.split("=")
                k = pa[0].lower()
                v = pa[1]
                set_option(k, v)
            else:
                set_option(p)
        else:
            new_argv.append(arg)

    return new_argv

def process_options():
    """
    Process the options: log, config, backend
    """
    # do log first
    for k in OPTIONS_TABLE:
        if k == "log":
            numeric_level = OPTIONS_TABLE[k]
            if not isinstance(numeric_level, int):
                raise ValueError("Invalid log level: %s" % numeric_level)
            logging.basicConfig(level=numeric_level)
            sdm_util.log_message("Set log level to %s" % numeric_level)

    # defaults
    global CONFIG_PATH
    global MOUNT_TABLE_PATH
    global config
    global mount_table
    global repository
    global backend

    for k in OPTIONS_TABLE:
        if k == "config":
            _config_root = OPTIONS_TABLE[k]
            sdm_util.log_message("Set config root to %s" % _config_root)

            ABS_SDM_CONFIG_DIR = sdm_util.get_abs_path(_config_root)
            CONFIG_PATH = "%s/sdm.conf" % ABS_SDM_CONFIG_DIR
            MOUNT_TABLE_PATH = "%s/sdm_mtab" % ABS_SDM_CONFIG_DIR

            config = sdm_config.Config(CONFIG_PATH)
            mount_table = sdm_mount_table.MountTable(MOUNT_TABLE_PATH)
            repository = sdm_repository.Repository(config.repo_url)
            backend = config.default_backend

    for k in OPTIONS_TABLE:
        if k == "backend":
            _backend = OPTIONS_TABLE[k]
            sdm_util.log_message("Set backend to %s" % _backend)
            backend = _backend

def main(argv=None):
    """
    Main
    """
    if argv is None:
        argv = sys.argv[1:]

    fill_options_table()
    fill_commands_table()

    argv = extract_options(argv)
    process_options()

    if len(argv) >= 1:
        # has command part
        command = argv[0]
        oargs = argv[1:]

        try:
            run(command, oargs)
        except Exception, e:
            sdm_util.print_message(e, True, sdm_util.LogLevel.ERROR)
            traceback.print_exc()
    else:
        show_help()

if __name__ == "__main__":
    main()


text:
import React from 'react';
import {mount} from 'enzyme';
import {expect} from 'chai';
import sinon from 'sinon';

import {HotKeys} from '../../src/';
import FocusableElement from '../support/FocusableElement';

describe('Passing props to HotKeys:', () => {
  context('when an onFocus function is passed to HotKeys', () => {
    beforeEach(function () {
      this.onFocus = sinon.spy();

      this.wrapper = mount(
        <HotKeys onFocus={this.onFocus}>

        </HotKeys>
      );

      this.targetElement = new FocusableElement(this.wrapper, '.childElement');
    });

    it('then calls the function when the component is focused', function() {
      this.targetElement.focus();
      expect(this.onFocus).to.have.been.calledOnce;
    });
  });

  context('when an onBlur function is passed to HotKeys', () => {
    beforeEach(function () {
      this.onBlur = sinon.spy();

      this.wrapper = mount(
        <HotKeys onBlur={this.onBlur}>

        </HotKeys>
      );

      this.targetElement = new FocusableElement(this.wrapper, '.childElement');
    });

    it('then calls the function when the component is blurred', function() {
      this.targetElement.focus();
      expect(this.onBlur).to.not.have.been.called;

      this.targetElement.blur();
      expect(this.onBlur).to.have.been.calledOnce;
    });
  });
});

redpajama_set_name: RedPajamaGithub


text:
define({
  testing: 'negation'
});


text:
import os
from tempfile import mkdtemp
from shutil import rmtree

import numpy as np

from nipype.testing import (assert_equal, assert_false, assert_true,
                            assert_raises, skipif)
import nibabel as nb
import nipype.interfaces.spm.model as spm
from nipype.interfaces.spm import no_spm
import nipype.interfaces.matlab as mlab

try:
    matlab_cmd = os.environ['MATLABCMD']
except:
    matlab_cmd = 'matlab'

mlab.MatlabCommand.set_default_matlab_cmd(matlab_cmd)

def create_files_in_directory():
    outdir = mkdtemp()
    cwd = os.getcwd()
    os.chdir(outdir)
    filelist = ['a.nii','b.nii']
    for f in filelist:
        hdr = nb.Nifti1Header()
        shape = (3,3,3,4)
        hdr.set_data_shape(shape)
        img = np.random.random(shape)
        nb.save(nb.Nifti1Image(img,np.eye(4),hdr),
                 os.path.join(outdir,f))
    return filelist, outdir, cwd

def clean_directory(outdir, old_wd):
    if os.path.exists(outdir):
        rmtree(outdir)
    os.chdir(old_wd)

def test_level1design():
    yield assert_equal, spm.Level1Design._jobtype, 'stats'
    yield assert_equal, spm.Level1Design._jobname, 'fmri_spec'

def test_estimatemodel():
    yield assert_equal, spm.EstimateModel._jobtype, 'stats'
    yield assert_equal, spm.EstimateModel._jobname, 'fmri_est'

def test_estimatecontrast():
    yield assert_equal, spm.EstimateContrast._jobtype, 'stats'
    yield assert_equal, spm.EstimateContrast._jobname, 'con'

def test_threshold():
    yield assert_equal, spm.Threshold._jobtype, 'basetype'
    yield assert_equal, spm.Threshold._jobname, 'basename'

def test_factorialdesign():
    yield assert_equal, spm.FactorialDesign._jobtype, 'stats'
    yield assert_equal, spm.FactorialDesign._jobname, 'factorial_design'

def test_onesamplettestdesign():
    yield assert_equal, spm.OneSampleTTestDesign._jobtype, 'stats'
    yield assert_equal, spm.OneSampleTTestDesign._jobname, 'factorial_design'

def test_twosamplettestdesign():
    yield assert_equal, spm.TwoSampleTTestDesign._jobtype, 'stats'
    yield assert_equal, spm.TwoSampleTTestDesign._jobname, 'factorial_design'


text:
function onTabKeyPress(direction) {
  this.setMode(this.nextMode(direction));
}


text:
<?php
/**
 * Spiral Framework.
 *
 * @license   MIT
 * @author    Anton Titov (Wolfy-J)
 */

namespace Spiral\Core\Exceptions\Container;

use Spiral\Core\Exceptions\DependencyException;

/**
 * Something inside container.
 */
class ContainerException extends DependencyException implements \Interop\Container\Exception\ContainerException
{
}


text:
using NUnit.Framework;
using Rhino.Mocks;
using TradingApi.Client.Framework.Services;

namespace TradingApi.Client.Framework.Tests.Services.Tests
{
    [TestFixture]
    public class FutureOptionServiceFactoryTests
    {
        private IApiConnection _mockApiConnection;

        [SetUp]
        public void Setup()
        {
            _mockApiConnection = MockRepository.GenerateMock<IApiConnection>();
        }

        [Test]
        public void FutureOptionServiceFactoryCreatesFutureOptionServiceWithAValidApiConnection()
        {
            var service = new FutureOptionServiceFactory().Create(_mockApiConnection);
            Assert.IsInstanceOfType(typeof(FutureOptionService), service);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using BuildAProject.BuildManagement.BuildManagers.Definitions;
using BuildAProject.BuildManagement.Locators;

namespace BuildAProject.Console.Logging
{
  sealed class ProjectsLocatorLogger : IProjectsLocator
  {
    private readonly IProjectsLocator composite;
    private readonly ILog logger;

    public ProjectsLocatorLogger(IProjectsLocator composite, ILog logger)
    {
      if (composite == null)
      {
        throw new ArgumentNullException("composite");
      }

      if (logger == null)
      {
        throw new ArgumentNullException("logger");
      }

      this.composite = composite;
      this.logger = logger;
    }

    public IEnumerable<IProject> FindProjects(string rootDirectoryPath)
    {
      logger.Information(String.Format("Looking for new projects in '{0}'", rootDirectoryPath), 1);
      var projectsFound = composite.FindProjects(rootDirectoryPath);
      logger.Information(String.Format("{0} projects found{1}", projectsFound.Count(), Environment.NewLine), 4);

      return projectsFound;
    }
  }
}


text:
from six.moves import configparser
config = configparser.ConfigParser()
config.read('bot.cfg')
url = config.get('main', 'url')
wallet = config.get('main', 'wallet')
password = config.get('main', 'password')

# Request to node
from common_rpc import *

result = unlock(wallet, password)
print(result)


text:
<?php
namespace PhpApns\Client;

use PhpApns\Response\Message as MessageResponse;
use PhpApns\Message as ApnsMessage;

class Message extends AbstractClient
{
    /**
     * APNS URIs
     * @var array
     */
    protected $uris = [
        'tls://gateway.sandbox.push.apple.com:2195',
        'tls://gateway.push.apple.com:2195',
    ];

    /**
     * Send Message
     *
     * @param  ApnsMessage          $message
     * @return MessageResponse
     */
    public function send(ApnsMessage $message){
        if(!$this->isConnected())
            throw new \RuntimeException('You must first open the connection by calling open()');
        $result = @$this->write($message->getPayloadJson());
        if(!$result)
            throw new \RuntimeException('Server is unavailable; please retry later');
        return new MessageResponse($this->read());
    }

    /**
     * Get Response
     *
     * @return MessageResponse
     */
    public function getResponse(){
        if (!$this->isConnected())
            throw new \RuntimeException('You must first open the connection by calling open()');
        return new MessageResponse($this->read());
    }
}


text:
package io.github.codemumbler.fittimer.model;

import android.os.Parcel;
import android.os.Parcelable;

import org.json.JSONException;
import org.json.JSONObject;

public class Pose implements Parcelable {

    private String name;
    private long duration;

    public Pose(String name, long duration) {
        this.name = name;
        this.duration = duration;
    }

    public Pose(String name) {
        this(name, 45000);
    }

    protected Pose(Parcel in) {
        this.name = in.readString();
        this.duration = in.readLong();
    }

    public static final Creator<Pose> CREATOR = new Creator<Pose>() {
        @Override
        public Pose createFromParcel(Parcel in) {
            return new Pose(in);
        }

        @Override
        public Pose[] newArray(int size) {
            return new Pose[size];
        }
    };

    public String getName() {
        return name;
    }

    public long getDuration() { return duration; }

    public void setName(String name) {
        this.name = name;
    }

    public void setDuration(long duration) {
        this.duration = duration;
    }

    @Override
    public String toString() {
        return name + " for " + duration/1000 + " seconds";
    }

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeLong(duration);
    }

    public JSONObject toJsonObject() throws JSONException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", name);
        jsonObject.put("duration", duration);
        return jsonObject;
    }
}


text:
package provaConfigurationServer;

public class Server {

	private int portConexionBBDD;
	private String IPBBDD;
	private String nameBBDD;
	private String userBBDD;
	private String passwordBBDD;
	private int portClientComunication;

	public Server(int portConexionBBDD, String iPBBDD, String nameBBDD,
			String userBBDD, String passwordBBDD, int portClientComunication) {
		super();
		this.portConexionBBDD = portConexionBBDD;
		this.IPBBDD = iPBBDD;
		this.nameBBDD = nameBBDD;
		this.userBBDD = userBBDD;
		this.passwordBBDD = passwordBBDD;
		this.portClientComunication = portClientComunication;
	}
	public Server(){
	}
	public int getPortConexionBBDD() {
		return portConexionBBDD;
	}
	public void setPortConexionBBDD(int portConexionBBDD) {
		this.portConexionBBDD = portConexionBBDD;
	}
	public String getIPBBDD() {
		return IPBBDD;
	}
	public void setIPBBDD(String iPBBDD) {
		IPBBDD = iPBBDD;
	}
	public String getNameBBDD() {
		return nameBBDD;
	}
	public void setNameBBDD(String nameBBDD) {
		this.nameBBDD = nameBBDD;
	}
	public String getUserBBDD() {
		return userBBDD;
	}
	public void setUserBBDD(String userBBDD) {
		this.userBBDD = userBBDD;
	}
	public String getPasswordBBDD() {
		return passwordBBDD;
	}
	public void setPasswordBBDD(String passwordBBDD) {
		this.passwordBBDD = passwordBBDD;
	}
	public int getPortClientComunication() {
		return portClientComunication;
	}
	public void setPortClientComunication(int portClientComunication) {
		this.portClientComunication = portClientComunication;
	}
}


text:
<?php

  // Remove WP emoji stuff
  remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
  remove_action( 'wp_print_styles', 'print_emoji_styles' );

  // Trim excerpt
  require get_template_directory() . '/inc/excerpt.php';

  // Ajax setup
  require get_template_directory() . '/inc/ajax.php';

?>


text:
using System.Web.Http;
using System.Web.Http.OData.Builder;
using ImageGallery.Models;
using Microsoft.Owin.Security.OAuth;
using Newtonsoft.Json.Serialization;

namespace ImageGallery
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            // Use camel case for JSON data.
            config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            // OData API routes
            //ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            //builder.Entity<ImageContent>().Ignore(e => e.User);
            //builder.EntitySet<ImageContent>("ImageContents");
            //config.Routes.MapODataRoute("odata", "odata", builder.GetEdmModel());
        }
    }
}


text:
package oort

import (
	"bytes"
	"fmt"
	"log"
	"net"
	"os"
	"strconv"
	"strings"

	"github.com/BurntSushi/toml"
	"github.com/gholt/ring"
	"github.com/pandemicsyn/cmdctrl"
	"github.com/pandemicsyn/syndicate/utils/srvconf"
)

// FExists true if a file or dir exists
func FExists(name string) bool {
	if _, err := os.Stat(name); os.IsNotExist(err) {
		return false
	}
	return true
}

type ccc struct {
	CmdCtrlConfig cmdctrl.ConfigOpts
}

func (o *Server) loadCmdCtrlConfig() error {
	config := ccc{}
	err := o.LoadRingConfig(&config)
	o.CmdCtrlConfig = config.CmdCtrlConfig
	return err
}

func (o *Server) LoadRingConfig(config interface{}) (err error) {
	o.Lock()
	defer o.Unlock()
	e := NewEnvGetter(fmt.Sprintf("OORT_%s", strings.ToUpper(o.serviceName)), "_")
	localConfig := e.Get("LOCAL_CONFIG")
	if localConfig != "" {
		_, err = toml.DecodeFile(localConfig, config)
		if err != nil {
			return err
		}
	}
	log.Println("Using ring version:", o.ring.Version())
	b := bytes.NewReader(o.ring.Config())
	if b.Len() > 0 {
		_, err = toml.DecodeReader(b, config)
		if err != nil {
			return err
		}
	}
	// Now overlay per node config on top
	n := o.ring.LocalNode()
	if n == nil {
		panic("n is nil")
	}
	b = bytes.NewReader(o.ring.LocalNode().Config())
	if b.Len() > 0 {
		_, err = toml.DecodeReader(b, config)
		if err != nil {
			return err
		}
	}
	log.Printf("Local Node config is: \n%s", o.ring.LocalNode().Config())
	log.Printf("Ring config is: \n%s", o.ring.Config())
	return nil
}

type EnvGetter struct {
	pre string
	sep string
}

func NewEnvGetter(prefix, seperator string) *EnvGetter {
	return &EnvGetter{pre: prefix, sep: seperator}
}

func (e *EnvGetter) Get(varname string) string {
	return os.Getenv(fmt.Sprintf("%s%s%s", e.pre, e.sep, varname))
}

func (o *Server) ObtainConfig() (err error) {
	e := NewEnvGetter(fmt.Sprintf("OORT_%s", strings.ToUpper(o.serviceName)), "_")
	envSkipSRV := e.Get("SKIP_SRV")
	// Check whether we're supposed to skip loading via srv method
	if strings.ToLower(envSkipSRV) != "true" {
		s := &srvconf.SRVLoader{
			SyndicateURL: e.Get("SYNDICATE_OVERRIDE"),
		}
		s.Record, err = GenServiceID(o.serviceName, "syndicate", "tcp")
		if err != nil {
			if e.Get("SYNDICATE_OVERRIDE") == "" {
				log.Println(err)
			} else {
				log.Fatalln("No SYNDICATE_OVERRIDE provided and", err)
			}
		}
		if e.Get("SYNDICATE_OVERRIDE") != "" {
			log.Println("Over wrote syndicate url with url from env!", e.Get("SYNDICATE_OVERRIDE"))
		}
		nc, err := s.Load()
		if err != nil {
			return err
		}
		o.ring, err = ring.LoadRing(bytes.NewReader(nc.Ring))
		if err != nil {
			return fmt.Errorf("Error while loading ring for config get via srv lookup: %s", err)
		}
		err = ring.PersistRingOrBuilder(o.ring, nil, fmt.Sprintf("%s/ring/%d-%s.ring", o.cwd, o.ring.Version(), o.serviceName))
		if err != nil {
			return err
		}
		o.localID = nc.Localid
		o.ring.SetLocalNode(o.localID)
		o.ringFile = fmt.Sprintf("%s/ring/%d-%s.ring", o.cwd, o.ring.Version(), o.serviceName)
		err = o.loadCmdCtrlConfig()
		if err != nil {
			return err
		}
	} else {
		// if you skip the srv load you have to provide all of the info in env vars!
		log.Println("Skipped SRV Config attempting to load from env")
		s, err := strconv.ParseUint(e.Get("LOCALID"), 10, 64)
		if err != nil {
			return fmt.Errorf("Unable to load env specified local id")
		}
		o.localID = s
		o.ringFile = e.Get("RING_FILE")
		o.ring, _, err = ring.RingOrBuilder(o.ringFile)
		if err != nil {
			return fmt.Errorf("Unable to road env specified ring: %s", err)
		}
		o.ring.SetLocalNode(o.localID)
		err = o.loadCmdCtrlConfig()
		if err != nil {
			return err
		}
	}
	return nil
}

//TODO: need to remove the hack to add IAD3 identifier -- What hack? Not sure
// what this refers to.
func GenServiceID(service, name, proto string) (string, error) {
	h, _ := os.Hostname()
	d := strings.SplitN(h, ".", 2)
	if len(d) != 2 {
		return "", fmt.Errorf("Unable to determine FQDN, only got short name.")
	}
	return fmt.Sprintf("_%s-%s._%s.%s", service, name, proto, d[1]), nil
}

func GetRingServer(servicename string) (string, error) {
	// All-In-One defaults
	h, _ := os.Hostname()
	d := strings.SplitN(h, ".", 2)
	if strings.HasSuffix(d[0], "-aio") {
		// TODO: Not sure about name, proto -- are those ever *not* "syndicate"
		// and "tcp"?
		switch servicename {
		case "value":
			return h + ":8443", nil
		case "group":
			return h + ":8444", nil
		}
		panic("Unknown service " + servicename)
	}
	service, err := GenServiceID(servicename, "syndicate", "tcp")
	if err != nil {
		return "", err
	}
	_, addrs, err := net.LookupSRV("", "", service)
	if err != nil {
		return "", err
	}
	if len(addrs) == 0 {
		return "", fmt.Errorf("Syndicate SRV lookup is empty")
	}
	return fmt.Sprintf("%s:%d", addrs[0].Target, addrs[0].Port), nil
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <parent>
        <artifactId>spring-batch-lightmin</artifactId>
        <groupId>org.tuxdevelop</groupId>
        <version>2.2.2-SNAPSHOT</version>
    </parent>

    <artifactId>spring-batch-lightmin-core</artifactId>
    <packaging>pom</packaging>

    <modules>
        <module>spring-batch-lightmin-core-batch</module>
        <module>spring-batch-lightmin-core-service</module>
        <module>spring-batch-lightmin-core-configuration</module>
        <module>spring-batch-lightmin-core-starter</module>
    </modules>

</project>


text:
#ifndef Credential_h
#define Credential_h

#include <wtf/Platform.h>

#if PLATFORM(COCOA)
#include "CredentialCocoa.h"
#else

#include "CredentialBase.h"

namespace WebCore {

class Credential : public CredentialBase {
public:
    Credential()
        : CredentialBase()
    {
    }

    Credential(const String& user, const String& password, CredentialPersistence persistence)
        : CredentialBase(user, password, persistence)
    {
    }

    Credential(const Credential& original, CredentialPersistence persistence)
        : CredentialBase(original, persistence)
    {
    }
};

}

#endif

#endif // Credential_h


text:
package com.valarion.gameengine.core.interfaces;

import org.newdawn.slick.SlickException;
import org.w3c.dom.Element;

/**
 * Class containing the mechanics of accessing to a long value.
 * @author Rubén Tomás Gracia
 *
 */
public interface VarLong {
	public long getLong();

	public void load(Element node, Object context) throws SlickException;
}


text:
---
uid: SolidEdgeFrameworkSupport.EllipticalArc2d.SetKeyPoint(System.Int32,System.Double,System.Double,System.Double)
summary:
remarks:
syntax:
    parameters:
    - id: Index
      description: Specifies the index of the key point/handle.
    - id: x
      description: Specifies the x coordinate of the specified key point.
    - id: y
      description: Specifies the y coordinate of the specified key point.
    - id: z
      description: Specifies the z coordinate of the specified key point.
example: [*content]
---
[!code-vb[Main](..\snippets\SolidEdgeFrameworkSupport.EllipticalArc2d.SetKeyPoint.vb]
[!code-csharp[Main](..\snippets\SolidEdgeFrameworkSupport.EllipticalArc2d.SetKeyPoint.cs]


text:
import {EventType, dispatch} from './events';
import {renderAsElement} from './simple-template';
import {dict} from '../../../src/utils/object';
import {dev} from '../../../src/log';
import {Services} from '../../../src/services';
import {ProgressBar} from './progress-bar';
import {getMode} from '../../../src/mode';
import {DevelopmentModeLog, DevelopmentModeLogButtonSet} from './development-ui'; // eslint-disable-line max-len
import {KeyCodes} from '../../../src/utils/key-codes';

const MUTE_CLASS = 'i-amphtml-story-mute-audio-control';

const UNMUTE_CLASS = 'i-amphtml-story-unmute-audio-control';

const ENTER_FULLSCREEN_CLASS = 'i-amphtml-story-enter-fullscreen';

const EXIT_FULLSCREEN_CLASS = 'i-amphtml-story-exit-fullscreen';

const CLOSE_CLASS = 'i-amphtml-story-bookend-close';

/** @private @const {!./simple-template.ElementDef} */
const TEMPLATE = {
  tag: 'aside',
  attrs: dict({'class': 'i-amphtml-story-system-layer'}),
  children: [
    {
      tag: 'div',
      attrs: dict({'class': 'i-amphtml-story-ui-left'}),
      children: [
        {
          tag: 'div',
          attrs: dict({
            'role': 'button',
            'class': UNMUTE_CLASS + ' i-amphtml-story-button',
          }),
        },
        {
          tag: 'div',
          attrs: dict({
            'role': 'button',
            'class': MUTE_CLASS + ' i-amphtml-story-button',
          }),
        },
      ],
    },
    {
      tag: 'div',
      attrs: dict({'class': 'i-amphtml-story-ui-right'}),
      children: [
        {
          tag: 'div',
          attrs: dict({
            'role': 'button',
            'class': UNMUTE_CLASS + ' i-amphtml-story-button',
          }),
        },
        {
          tag: 'div',
          attrs: dict({
            'role': 'button',
            'class': MUTE_CLASS + ' i-amphtml-story-button',
          }),
        },
        {
          tag: 'div',
          attrs: dict({
            'role': 'button',
            'class': ENTER_FULLSCREEN_CLASS + ' i-amphtml-story-button',
            'hidden': true,
          }),
        },
        {
          tag: 'div',
          attrs: dict({
            'role': 'button',
            'class': EXIT_FULLSCREEN_CLASS + ' i-amphtml-story-button',
            'hidden': true,
          }),
        },
        {
          tag: 'div',
          attrs: dict({
            'role': 'button',
            'class': CLOSE_CLASS + ' i-amphtml-story-button',
            'hidden': true,
          }),
        },
      ],
    },
  ],
};

/**
 * @param {!../../../src/service/vsync-impl.Vsync} vsync
 * @param {!Element} el
 * @param {boolean} isHidden
 */
function toggleHiddenAttribute(vsync, el, isHidden) {
  vsync.mutate(() => {
    if (isHidden) {
      el.setAttribute('hidden', 'hidden');
    } else {
      el.removeAttribute('hidden');
    }
  });
}

/**
 * System Layer (i.e. UI Chrome) for <amp-story>.
 * Chrome contains:
 *   - mute/unmute button
 *   - fullscreen button
 *   - story progress bar
 *   - bookend close butotn
 */
export class SystemLayer {
  /**
   * @param {!Window} win
   */
  constructor(win) {
    /** @private {!Window} */
    this.win_ = win;

    /** @private {boolean} */
    this.isBuilt_ = false;

    /** @private {?Element} */
    this.root_ = null;

    /** @private {?Element} */
    this.exitFullScreenBtn_ = null;

    /** @private {?Element} */
    this.enterFullScreenBtn_ = null;

    /** @private {?Element} */
    this.closeBookendBtn_ = null;

    /** @private {?Element} */
    this.muteAudioBtn_ = null;

    /** @private {?Element} */
    this.unmuteAudioBtn_ = null;

    /** @private {?Element} */
    this.leftButtonTray_ = null;

    /** @private @const {!ProgressBar} */
    this.progressBar_ = ProgressBar.create(win);

    /** @private {!DevelopmentModeLog} */
    this.developerLog_ = DevelopmentModeLog.create(win);

    /** @private {!DevelopmentModeLogButtonSet} */
    this.developerButtons_ = DevelopmentModeLogButtonSet.create(win);
  }

  /**
   * @param {number} pageCount The number of pages in the story.
   * @return {!Element}
   */
  build(pageCount) {
    if (this.isBuilt_) {
      return this.getRoot();
    }

    this.isBuilt_ = true;

    this.root_ = renderAsElement(this.win_.document, TEMPLATE);

    this.root_.insertBefore(
        this.progressBar_.build(pageCount), this.root_.firstChild);

    this.leftButtonTray_ =
        this.root_.querySelector('.i-amphtml-story-ui-left');

    this.buildForDevelopmentMode_();

    this.exitFullScreenBtn_ =
        this.root_.querySelector('.i-amphtml-story-exit-fullscreen');

    this.enterFullScreenBtn_ =
        this.root_.querySelector('.i-amphtml-story-enter-fullscreen');

    this.closeBookendBtn_ =
        this.root_.querySelector('.i-amphtml-story-bookend-close');

    this.addEventHandlers_();

    return this.getRoot();
  }

  /**
   * @private
   */
  buildForDevelopmentMode_() {
    if (!getMode().development) {
      return;
    }

    this.leftButtonTray_.appendChild(this.developerButtons_.build(
        this.developerLog_.toggle.bind(this.developerLog_)));
    this.root_.appendChild(this.developerLog_.build());
  }

  /**
   * @private
   */
  addEventHandlers_() {
    // TODO(alanorozco): Listen to tap event properly (i.e. fastclick)
    this.root_.addEventListener('click', e => {
      const target = dev().assertElement(e.target);

      if (target.matches(
          `.${EXIT_FULLSCREEN_CLASS}, .${EXIT_FULLSCREEN_CLASS} *`)) {
        this.onExitFullScreenClick_(e);
      } else if (target.matches(
          `.${ENTER_FULLSCREEN_CLASS}, .${ENTER_FULLSCREEN_CLASS} *`)) {
        this.onEnterFullScreenClick_(e);
      } else if (target.matches(`.${CLOSE_CLASS}, .${CLOSE_CLASS} *`)) {
        this.onCloseBookend_(e);
      } else if (target.matches(`.${MUTE_CLASS}, .${MUTE_CLASS} *`)) {
        this.onMuteAudioClick_(e);
      } else if (target.matches(`.${UNMUTE_CLASS}, .${UNMUTE_CLASS} *`)) {
        this.onUnmuteAudioClick_(e);
      }
    });

    this.win_.addEventListener('keyup', e => {
      if (!this.closeBookendBtn_.hasAttribute('hidden')
          && e.keyCode == KeyCodes.ESCAPE) {
        this.onCloseBookend_(e);
      }
    });
  }

  /**
   * @return {!Element}
   */
  getRoot() {
    return dev().assertElement(this.root_);
  }

  /**
   * @param {boolean} inFullScreen
   */
  setInFullScreen(inFullScreen) {
    this.toggleExitFullScreenBtn_(inFullScreen);
    this.toggleEnterFullScreenBtn_(inFullScreen);
  }

  /**
   * @param {boolean} isEnabled
   * @private
   */
  toggleExitFullScreenBtn_(isEnabled) {
    toggleHiddenAttribute(
        Services.vsyncFor(this.win_),
        dev().assertElement(this.exitFullScreenBtn_),
        /* opt_isHidden */ !isEnabled);
  }

  /**
   * @param {boolean} isEnabled
   * @private
   */
  toggleEnterFullScreenBtn_(isEnabled) {
    toggleHiddenAttribute(
        Services.vsyncFor(this.win_),
        dev().assertElement(this.enterFullScreenBtn_),
        /* opt_isHidden */ isEnabled);
  }

  /**
   * @param {boolean} isEnabled
   */
  toggleCloseBookendButton(isEnabled) {
    toggleHiddenAttribute(
        Services.vsyncFor(this.win_),
        dev().assertElement(this.closeBookendBtn_),
        /* opt_isHidden */ !isEnabled);
  }

  /**
   * @param {!Event} e
   * @private
   */
  onExitFullScreenClick_(e) {
    this.dispatch_(EventType.EXIT_FULLSCREEN, e);
  }

  /**
   * @param {!Event} e
   * @private
   */
  onEnterFullScreenClick_(e) {
    this.dispatch_(EventType.ENTER_FULLSCREEN, e);
  }

  /**
   * @param {!Event} e
   * @private
   */
  onCloseBookend_(e) {
    this.dispatch_(EventType.CLOSE_BOOKEND, e);
  }

  /**
   * @param {!Event} e
   * @private
   */
  onMuteAudioClick_(e) {
    this.dispatch_(EventType.MUTE, e);
  }

  /**
   * @param {!Event} e
   * @private
   */
  onUnmuteAudioClick_(e) {
    this.dispatch_(EventType.UNMUTE, e);
  }

  /**
   * @param {string} eventType
   * @param {!Event=} opt_event
   * @private
   */
  dispatch_(eventType, opt_event) {
    if (opt_event) {
      dev().assert(opt_event).stopPropagation();
    }

    dispatch(this.getRoot(), eventType, /* opt_bubbles */ true);
  }

  /**
   * @param {number} pageIndex The index of the new active page.
   * @public
   */
  setActivePageIndex(pageIndex) {
    this.progressBar_.setActivePageIndex(pageIndex);
  }

  /**
   * @param {number} pageIndex The index of the page whose progress should be
   *     changed.
   * @param {number} progress A number from 0.0 to 1.0, representing the
   *     progress of the current page.
   * @public
   */
  updateProgress(pageIndex, progress) {
    this.progressBar_.updateProgress(pageIndex, progress);
  }

  /**
   * @param {!./logging.AmpStoryLogEntryDef} logEntry
   * @private
   */
  logInternal_(logEntry) {
    this.developerButtons_.log(logEntry);
    this.developerLog_.log(logEntry);
  }

  /**
   * Logs an array of entries to the developer logs.
   * @param {!Array<!./logging.AmpStoryLogEntryDef>} logEntries
   */
  logAll(logEntries) {
    if (!getMode().development) {
      return;
    }

    Services.vsyncFor(this.win_).mutate(() => {
      logEntries.forEach(logEntry => this.logInternal_(logEntry));
    });
  }

  /**
   * Logs a single entry to the developer logs.
   * @param {!./logging.AmpStoryLogEntryDef} logEntry
   */
  log(logEntry) {
    if (!getMode().development) {
      return;
    }

    this.logInternal_(logEntry);
  }

  /**
   * Clears any state held by the developer log or buttons.
   */
  resetDeveloperLogs() {
    if (!getMode().development) {
      return;
    }

    this.developerButtons_.clear();
    this.developerLog_.clear();
  }

  /**
   * Sets the string providing context for the developer logs window.  This is
   * often the name or ID of the element that all logs are for (e.g. the page).
   * @param {string} contextString
   */
  setDeveloperLogContextString(contextString) {
    if (!getMode().development) {
      return;
    }

    this.developerLog_.setContextString(contextString);
  }

  /**
   * Toggles the visibility of the developer log.
   * @private
   */
  toggleDeveloperLog_() {
    if (!getMode().development) {
      return;
    }

    this.developerLog_.toggle();
  }

  /**
   * Hides the developer log in the UI.
   */
  hideDeveloperLog() {
    if (!getMode().development) {
      return;
    }

    this.developerLog_.hide();
  }
}


text:
package io.dwak.holohackernews.app.manager;

import android.support.annotation.Nullable;

/**
 * Created by vishnu on 8/18/14.
 */
public interface Callback<T> {
    void onResponse(@Nullable T response, @Nullable Exception exception);
}


text:
package net.firejack.platform.core.model.registry.field;

import net.firejack.platform.api.registry.model.IndexType;
import net.firejack.platform.core.annotation.Lookup;
import net.firejack.platform.core.model.registry.IAllowCreateAutoDescription;
import net.firejack.platform.core.model.registry.LookupModel;
import net.firejack.platform.core.model.registry.RegistryNodeModel;
import net.firejack.platform.core.model.registry.RegistryNodeType;
import net.firejack.platform.core.model.registry.domain.EntityModel;
import net.firejack.platform.core.model.registry.domain.RelationshipModel;
import net.firejack.platform.core.utils.IHasName;
import org.hibernate.annotations.ForeignKey;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;

import javax.persistence.*;
import javax.xml.bind.annotation.XmlTransient;
import java.util.List;

@Entity
@XmlTransient
@Lookup(parent = RegistryNodeModel.class, suffix = "#index")
@Table(name = "opf_entity_index")
public class IndexModel extends LookupModel<EntityModel> implements IHasName, IAllowCreateAutoDescription {
    private static final long serialVersionUID = -7732961317538380854L;

    private List<IndexEntityReferenceModel> references;
    private List<FieldModel> fields;
    private IndexType indexType;
    private RelationshipModel relationship;

    /**
     * @return
     */
    //@OneToMany(mappedBy = "index", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
    @OneToMany(mappedBy = "index", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
	@OnDelete(action = OnDeleteAction.CASCADE)
    @ForeignKey(name = "FK_ENTITY_INDEX_REFERENCES")
    public List<IndexEntityReferenceModel> getReferences() {
        return references;
    }

    public void setReferences(List<IndexEntityReferenceModel> references) {
        this.references = references;
    }

    /**
     * @return
     */
    @ManyToMany(targetEntity = FieldModel.class, fetch = FetchType.LAZY)
    @JoinTable(
            name = "opf_entity_index_fields",
            joinColumns = @JoinColumn(name = "id_index", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "id_field", referencedColumnName = "id")
    )
    @ForeignKey(name = "FK_ENTITY_INDEX_FIELDS")
    public List<FieldModel> getFields() {
        return fields;
    }

    /**
     * @param fields
     */
    public void setFields(List<FieldModel> fields) {
        this.fields = fields;
    }

    @Enumerated(EnumType.STRING)
    public IndexType getIndexType() {
        return indexType;
    }

    public void setIndexType(IndexType indexType) {
        this.indexType = indexType;
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "id_relationship")
    @ForeignKey(name = "fk_entity_index_relationship")
    public RelationshipModel getRelationship() {
        return relationship;
    }

    public void setRelationship(RelationshipModel relationship) {
        this.relationship = relationship;
    }

    @Override
    @Transient
    public RegistryNodeType getType() {
        return RegistryNodeType.INDEX;
    }

}


text:
package net.emiliollbb.durango;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class BackgroundExporter2 {

	public static void main(final String args[]) throws IOException {
		final File file = new File("/tmp/boat1.png");
		//final File file = new File("/tmp/palette.png");
		final BufferedImage image = ImageIO.read(file);
		int addr = 0x6000;
		for(int row=0; row < image.getHeight(); row++) {
			for(int col=0; col<image.getWidth(); col+=2) {
				System.out.print("mem[");
				System.out.print(String.format("0x%02X",addr++));
				System.out.print("]=");
				System.out.print(String.format("0x%02X",
						Palette.getColorByte(image.getRGB(col, row), image.getRGB(col+1, row))));
				System.out.print(';');
				if(addr%16==15) {
					//System.out.println();
				}
			}
		}
	}

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Lens.Compiler;
using Lens.Compiler.Entities;
using Lens.Resolver;
using Lens.SyntaxTree.ControlFlow;
using Lens.Translations;

namespace Lens.SyntaxTree.Declarations.Functions
{
    /// <summary>
    /// A node that represents the lambda function.
    /// </summary>
    internal class LambdaNode : FunctionNodeBase
    {
        #region Constructor

        public LambdaNode()
        {
            Body = new CodeBlockNode(ScopeKind.LambdaRoot);
        }

        #endregion

        #region Fields

        /// <summary>
        /// Backing method reference.
        /// </summary>
        private MethodEntity _method;

        /// <summary>
        /// Return type inferred from context.
        /// </summary>
        private Type _inferredReturnType;

        /// <summary>
        /// Flag indicating that current lambda has arguments with omitted types and they must be resolved from the context.
        /// </summary>
        public bool MustInferArgTypes { get; private set; }

        #endregion

        #region Resolve

        protected override Type ResolveInternal(Context ctx, bool mustReturn)
        {
            var argTypes = new List<Type>();
            foreach (var curr in Arguments)
            {
                if (curr.IsVariadic)
                    Error(CompilerMessages.VariadicArgumentLambda);

                var type = curr.GetArgumentType(ctx);
                argTypes.Add(type);

                if (type == typeof(UnspecifiedType))
                    MustInferArgTypes = true;
            }

            if (MustInferArgTypes)
                return FunctionalHelper.CreateLambdaType(argTypes.ToArray());

            Body.Scope.RegisterArguments(ctx, false, Arguments);

            var retType = Body.Resolve(ctx);
            return FunctionalHelper.CreateDelegateType(retType, argTypes.ToArray());
        }

        #endregion

        #region Process closures

        public override void ProcessClosures(Context ctx)
        {
            if (MustInferArgTypes)
            {
                var name = Arguments.First(a => a.Type == typeof(UnspecifiedType)).Name;
                Error(CompilerMessages.LambdaArgTypeUnknown, name);
            }

            // get evaluated return type
            var retType = _inferredReturnType ?? Body.Resolve(ctx);
            if (retType == typeof(NullType))
                Error(CompilerMessages.LambdaReturnTypeUnknown);
            if (retType.IsVoid())
                retType = typeof(void);

            _method = ctx.Scope.CreateClosureMethod(ctx, Arguments, retType);
            _method.Body = Body;

            var outerMethod = ctx.CurrentMethod;
            ctx.CurrentMethod = _method;

            _method.Body.ProcessClosures(ctx);

            ctx.CurrentMethod = outerMethod;
        }

        #endregion

        #region Emit

        protected override void EmitInternal(Context ctx, bool mustReturn)
        {
            var gen = ctx.CurrentMethod.Generator;

            // find constructor
            var type = FunctionalHelper.CreateDelegateType(Body.Resolve(ctx), _method.ArgumentTypes);
            var ctor = ctx.ResolveConstructor(type, new[] {typeof(object), typeof(IntPtr)});

            var closureInstance = ctx.Scope.ActiveClosure.ClosureVariable;
            gen.EmitLoadLocal(closureInstance);
            gen.EmitLoadFunctionPointer(_method.MethodBuilder);
            gen.EmitCreateObject(ctor.ConstructorInfo);
        }

        #endregion

        #region Argument type detection

        /// <summary>
        /// Sets correct types for arguments which are inferred from usage (invocation, assignment, type casting).
        /// </summary>
        public void SetInferredArgumentTypes(Type[] argTypes)
        {
            if (Arguments.Count != argTypes.Length)
                Error(CompilerMessages.LambdaArgumentsCountMismatch, argTypes.Length, Arguments.Count);

            for (var idx = 0; idx < argTypes.Length; idx++)
            {
                var inferred = argTypes[idx];
                if (inferred == typeof(UnspecifiedType))
                    Error(CompilerMessages.LambdaArgTypeUnknown, Arguments[idx].Name);

#if DEBUG
                var specified = Arguments[idx].Type;
                if (specified != typeof(UnspecifiedType) && specified != inferred)
                    throw new InvalidOperationException($"Argument type differs: specified '{specified}', inferred '{inferred}'!");
#endif

                Arguments[idx].Type = inferred;
            }

            MustInferArgTypes = false;
            CachedExpressionType = null;
        }

        /// <summary>
        /// Interprets the lambda as a particular delegate with given arg & return types.
        /// </summary>
        public void SetInferredReturnType(Type type)
        {
            _inferredReturnType = type;
        }

        #endregion

        public override string ToString()
        {
            var arglist = Arguments.Select(x => string.Format("{0}:{1}", x.Name, x.Type != null ? x.Type.Name : x.TypeSignature));
            return string.Format("lambda({0})", string.Join(", ", arglist));
        }
    }
}


text:
package com.siyeh.ig.numeric;

import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.ConstantExpressionUtil;
import com.intellij.util.IncorrectOperationException;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.InspectionGadgetsFix;
import com.siyeh.ig.psiutils.ExpressionUtils;
import com.siyeh.ig.psiutils.TypeUtils;
import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.util.HashSet;
import java.util.Set;

public class PointlessArithmeticExpressionInspection
        extends BaseInspection {

    private static final Set<String> arithmeticTokens =
            new HashSet<String>(9);

    static {
        arithmeticTokens.add("+");
        arithmeticTokens.add("-");
        arithmeticTokens.add("*");
        arithmeticTokens.add("/");
        arithmeticTokens.add("%");
        arithmeticTokens.add(">");
        arithmeticTokens.add("<");
        arithmeticTokens.add("<=");
        arithmeticTokens.add(">=");
    }

    /**
     * @noinspection PublicField
     */
    public boolean m_ignoreExpressionsContainingConstants = false;

    @Override
    public JComponent createOptionsPanel() {
        return new SingleCheckboxOptionsPanel(
                InspectionGadgetsBundle.message(
                        "pointless.boolean.expression.ignore.option"),
                this, "m_ignoreExpressionsContainingConstants");
    }

    @Override
    @NotNull
    public String getDisplayName() {
        return InspectionGadgetsBundle.message(
                "pointless.arithmetic.expression.display.name");
    }

    @Override
    public boolean isEnabledByDefault() {
        return true;
    }

    @Override
    @NotNull
    public String buildErrorString(Object... infos) {
        return InspectionGadgetsBundle.message(
                "expression.can.be.replaced.problem.descriptor",
                calculateReplacementExpression((PsiExpression) infos[0]));
    }

    @NonNls
    String calculateReplacementExpression(
            PsiExpression expression) {
        final PsiBinaryExpression exp = (PsiBinaryExpression) expression;
        final PsiJavaToken sign = exp.getOperationSign();
        final PsiExpression lhs = exp.getLOperand();
        final PsiExpression rhs = exp.getROperand();
        assert rhs != null;
        final IElementType tokenType = sign.getTokenType();
        if (tokenType.equals(JavaTokenType.PLUS)) {
            if (isZero(lhs)) {
                return rhs.getText();
            } else {
                return lhs.getText();
            }
        } else if (tokenType.equals(JavaTokenType.MINUS)) {
            return lhs.getText();
        } else if (tokenType.equals(JavaTokenType.ASTERISK)) {
            if (isOne(lhs)) {
                return rhs.getText();
            } else if (isOne(rhs)) {
                return lhs.getText();
            } else {
                return "0";
            }
        } else if (tokenType.equals(JavaTokenType.DIV)) {
            return lhs.getText();
        } else if (tokenType.equals(JavaTokenType.PERC)) {
            return "0";
        } else if (tokenType.equals(JavaTokenType.LE) ||
                tokenType.equals(JavaTokenType.GE)) {
            return "true";
        } else if (tokenType.equals(JavaTokenType.LT) ||
                tokenType.equals(JavaTokenType.GT)) {
            return "false";
        } else {
            return "";
        }
    }

    @Override
    public InspectionGadgetsFix buildFix(Object... infos) {
        return new PointlessArithmeticFix();
    }

    private class PointlessArithmeticFix extends InspectionGadgetsFix {

        @NotNull
        public String getName() {
            return InspectionGadgetsBundle.message(
                    "constant.conditional.expression.simplify.quickfix");
        }

        @Override
        public void doFix(Project project, ProblemDescriptor descriptor)
                throws IncorrectOperationException {
            final PsiExpression expression =
                    (PsiExpression) descriptor.getPsiElement();
            final String newExpression =
                    calculateReplacementExpression(expression);
            replaceExpression(expression, newExpression);
        }
    }

    @Override
    public BaseInspectionVisitor buildVisitor() {
        return new PointlessArithmeticVisitor();
    }

    private class PointlessArithmeticVisitor extends BaseInspectionVisitor {

        @Override public void visitBinaryExpression(
                @NotNull PsiBinaryExpression expression) {
            super.visitBinaryExpression(expression);
            final PsiExpression rhs = expression.getROperand();
            if (rhs == null) {
                return;
            }
            final PsiType expressionType = expression.getType();
            if (PsiType.DOUBLE.equals(expressionType) ||
                    PsiType.FLOAT.equals(expressionType)) {
                return;
            }
            final PsiJavaToken sign = expression.getOperationSign();
            final String signText = sign.getText();
            if (!arithmeticTokens.contains(signText)) {
                return;
            }
            if (TypeUtils.expressionHasType(expression,
                    CommonClassNames.JAVA_LANG_STRING)) {
                return;
            }
            final PsiExpression lhs = expression.getLOperand();
            final IElementType tokenType = sign.getTokenType();
            final boolean isPointless;
            if (tokenType.equals(JavaTokenType.PLUS)) {
                isPointless = additionExpressionIsPointless(lhs, rhs);
            } else if (tokenType.equals(JavaTokenType.MINUS)) {
                isPointless = subtractionExpressionIsPointless(rhs);
            } else if (tokenType.equals(JavaTokenType.ASTERISK)) {
                isPointless = multiplyExpressionIsPointless(lhs, rhs);
            } else if (tokenType.equals(JavaTokenType.DIV)) {
                isPointless = divideExpressionIsPointless(rhs);
            } else if (tokenType.equals(JavaTokenType.PERC)) {
                isPointless = modExpressionIsPointless(rhs);
            } else if (tokenType.equals(JavaTokenType.LE) ||
                    tokenType.equals(JavaTokenType.GE) ||
                    tokenType.equals(JavaTokenType.GT) ||
                    tokenType.equals(JavaTokenType.LT)) {
                isPointless = comparisonExpressionIsPointless(lhs, rhs,
                        tokenType);
            } else {
                isPointless = false;
            }
            if (!isPointless) {
                return;
            }
            if (!PsiType.BOOLEAN.equals(expressionType)) {
                if (expressionType == null ||
                        !expressionType.equals(rhs.getType()) ||
                        !expressionType.equals(lhs.getType())) {
                    // A bit rude way to avoid false positive of
                    // 'int sum = 5, n = 6; float p = (1.0f * sum) / n;'
                    return;
                }
            }
            registerError(expression, expression);
        }

        private boolean subtractionExpressionIsPointless(PsiExpression rhs) {
            return isZero(rhs);
        }

        private boolean additionExpressionIsPointless(PsiExpression lhs,
                                                      PsiExpression rhs) {
            return isZero(lhs) || isZero(rhs);
        }

        private boolean multiplyExpressionIsPointless(PsiExpression lhs,
                                                      PsiExpression rhs) {
            return isZero(lhs) || isZero(rhs) || isOne(lhs) || isOne(rhs);
        }

        private boolean divideExpressionIsPointless(PsiExpression rhs) {
            return isOne(rhs);
        }

        private boolean modExpressionIsPointless(PsiExpression rhs) {
            return PsiType.INT.equals(rhs.getType()) && isOne(rhs);
        }

        private boolean comparisonExpressionIsPointless(
                PsiExpression lhs, PsiExpression rhs, IElementType comparison) {
            if (PsiType.INT.equals(lhs.getType()) &&
                PsiType.INT.equals(rhs.getType())) {
                return intComparisonIsPointless(lhs, rhs, comparison);
            } else if (PsiType.LONG.equals(lhs.getType()) &&
                       PsiType.LONG.equals(rhs.getType())) {
                return longComparisonIsPointless(lhs, rhs, comparison);
            }
            return false;
        }

        private boolean intComparisonIsPointless(
                PsiExpression lhs, PsiExpression rhs, IElementType comparison) {
            if (isMaxInt(lhs) || isMinInt(rhs)) {
                return JavaTokenType.GE.equals(comparison) ||
                       JavaTokenType.LT.equals(comparison);
            }
            if (isMinInt(lhs) || isMaxInt(rhs)) {
                return JavaTokenType.LE.equals(comparison) ||
                       JavaTokenType.GT.equals(comparison);
            }
            return false;
        }

        private boolean longComparisonIsPointless(
                PsiExpression lhs, PsiExpression rhs, IElementType comparison) {
            if (isMaxLong(lhs) || isMinLong(rhs)) {
                return JavaTokenType.GE.equals(comparison) ||
                       JavaTokenType.LT.equals(comparison);
            }
            if (isMinLong(lhs) || isMaxLong(rhs)) {
                return JavaTokenType.LE.equals(comparison) ||
                       JavaTokenType.GT.equals(comparison);
            }
            return false;
        }
    }

    boolean isZero(PsiExpression expression) {
        if (m_ignoreExpressionsContainingConstants &&
                !(expression instanceof PsiLiteralExpression)) {
            return false;
        }
        return ExpressionUtils.isZero(expression);
    }

    boolean isOne(PsiExpression expression) {
        if (m_ignoreExpressionsContainingConstants &&
                !(expression instanceof PsiLiteralExpression)) {
            return false;
        }
        return ExpressionUtils.isOne(expression);
    }

    private static boolean isMinDouble(PsiExpression expression) {
        final Double value = (Double)
                ConstantExpressionUtil.computeCastTo(
                        expression, PsiType.DOUBLE);
        return value != null && value.doubleValue() == Double.MIN_VALUE;
    }

    private static boolean isMaxDouble(PsiExpression expression) {
        final Double value = (Double)
                ConstantExpressionUtil.computeCastTo(
                        expression, PsiType.DOUBLE);
        //noinspection FloatingPointEquality
        return value != null && value.doubleValue() == Double.MAX_VALUE;
    }

    private static boolean isMinFloat(PsiExpression expression) {
        final Float value = (Float)
                ConstantExpressionUtil.computeCastTo(
                        expression, PsiType.FLOAT);
        //noinspection FloatingPointEquality
        return value != null && value.floatValue() == Float.MIN_VALUE;
    }

    private static boolean isMaxFloat(PsiExpression expression) {
        final Float value = (Float)
                ConstantExpressionUtil.computeCastTo(
                        expression, PsiType.FLOAT);
        //noinspection FloatingPointEquality
        return value != null && value.floatValue() == Float.MAX_VALUE;
    }

    private static boolean isMinInt(PsiExpression expression) {
        final Integer value = (Integer)
                ConstantExpressionUtil.computeCastTo(
                        expression, PsiType.INT);
        return value != null && value.intValue() == Integer.MIN_VALUE;
    }

    private static boolean isMaxInt(PsiExpression expression) {
        final Integer value = (Integer)
                ConstantExpressionUtil.computeCastTo(
                        expression, PsiType.INT);
        return value != null && value.intValue() == Integer.MAX_VALUE;
    }

    private static boolean isMinLong(PsiExpression expression) {
        final Long value = (Long)
                ConstantExpressionUtil.computeCastTo(
                        expression, PsiType.LONG);
        return value != null && value.longValue() == Long.MIN_VALUE;
    }

    private static boolean isMaxLong(PsiExpression expression) {
        final Long value = (Long)
                ConstantExpressionUtil.computeCastTo(
                        expression, PsiType.LONG);
        return value != null && value.longValue() == Long.MAX_VALUE;
    }
}


text:
<?php namespace Illuminate\Support\Facades;

/**
 * @see \Illuminate\Auth\Passwords\PasswordBroker
 */
class Password extends Facade {

	/**
	 * Constant representing a successfully sent reminder.
	 *
	 * @var string
	 */
	const RESET_LINK_SENT = 'passwords.sent';

	/**
	 * Constant representing a successfully reset password.
	 *
	 * @var string
	 */
	const PASSWORD_RESET = 'passwords.reset';

	/**
	 * Constant representing the user not found response.
	 *
	 * @var string
	 */
	const INVALID_USER = 'passwords.user';

	/**
	 * Constant representing an invalid password.
	 *
	 * @var string
	 */
	const INVALID_PASSWORD = 'passwords.password';

	/**
	 * Constant representing an invalid token.
	 *
	 * @var string
	 */
	const INVALID_TOKEN = 'passwords.token';

	/**
	 * Get the registered name of the component.
	 *
	 * @return string
	 */
	protected static function getFacadeAccessor()
	{
		return 'auth.password';
	}

}


text:
import jwt from 'jsonwebtoken';

const verifyRecoveryToken = (token) => {
  if (token) {
    return jwt.verify(token, 'ARSENAL', ((error) => {
      if (error) {
        return false;
      }
      return true;
    }));
  }
  return false;
};
export default verifyRecoveryToken;


text:
Version 0.1

## Install

1. pip install boto3, daemon, json-rpc, importlib

2. Deploy sqsworker.py

3. Create subdirectory called "modules"

4. Place worker modules and \_\_init\_\_.py into modules directory

5. Deploy init

6. CloudFormation or manually create the SQS Queue, ensure ec2 instance has the correct role

## Configuration

- /etc/sqsworker/sqsworker.cfg (although this location can be overridden with the -f option to the daemon)

```
[main]
visibilityTimeout   = 1             Defaults to 1, you probably don't need to change this unless you have a long-running module
WaitTimeSeconds     = 20            Long polling, max is 20, you probably don't need to change this unless you have a LOT of rpc calls
testMode            = true          true or false, if true this runs unit tests and exits
daemonMode          = true          true or false, if true this runs as a daemon
region              = us-east-1     Defaults to us-east-1

[queues]
queueName       = queueUrl          Queues must have unique names and URLs
```

## Plugin modules

See the examples in the 'modules' directory.

To create a plugin module:

1. Name the class the same as the file (without the .py extension)

2. Make sure there is a property called 'methodName' which will be the RPC method this is registered to

3. Make sure there is a method called 'Processor' that accepts arguments. It will be the same number of arguments
   that you expect to receive with that RPC message

## Cloudformation

A cloudformation template is presented as an example of how this stack could be deployed.


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.dns.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

/** An A record. */
@Fluent
public final class ARecord {
    @JsonIgnore private final ClientLogger logger = new ClientLogger(ARecord.class);

    /*
     * The IPv4 address of this A record.
     */
    @JsonProperty(value = "ipv4Address")
    private String ipv4Address;

    /**
     * Get the ipv4Address property: The IPv4 address of this A record.
     *
     * @return the ipv4Address value.
     */
    public String ipv4Address() {
        return this.ipv4Address;
    }

    /**
     * Set the ipv4Address property: The IPv4 address of this A record.
     *
     * @param ipv4Address the ipv4Address value to set.
     * @return the ARecord object itself.
     */
    public ARecord withIpv4Address(String ipv4Address) {
        this.ipv4Address = ipv4Address;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
    }
}


text: from core import Chain


text:
<?php

namespace OsmTech\LearningBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use OsmTech\LearningBundle\Entity\Cours;
use OsmTech\LearningBundle\Form\CoursType;

/**
 * Cours controller.
 *
 */
class CoursController extends Controller
{

    /**
     * Lists all Cours entities.
     *
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('OsmTechLearningBundle:Cours')->findAll();

        return $this->render('OsmTechLearningBundle:Cours:index.html.twig', array(
            'entities' => $entities,
        ));
    }
    /**
     * Creates a new Cours entity.
     *
     */
    public function createAction(Request $request)
    {
        $entity = new Cours();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('cours_show', array('id' => $entity->getId())));
        }

        return $this->render('OsmTechLearningBundle:Cours:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Creates a form to create a Cours entity.
     *
     * @param Cours $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(Cours $entity)
    {
        $form = $this->createForm(new CoursType(), $entity, array(
            'action' => $this->generateUrl('cours_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));

        return $form;
    }

    /**
     * Displays a form to create a new Cours entity.
     *
     */
    public function newAction()
    {
        $entity = new Cours();
        $form   = $this->createCreateForm($entity);

        return $this->render('OsmTechLearningBundle:Cours:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Finds and displays a Cours entity.
     *
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('OsmTechLearningBundle:Cours')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Cours entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return $this->render('OsmTechLearningBundle:Cours:show.html.twig', array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing Cours entity.
     *
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('OsmTechLearningBundle:Cours')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Cours entity.');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return $this->render('OsmTechLearningBundle:Cours:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
    * Creates a form to edit a Cours entity.
    *
    * @param Cours $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(Cours $entity)
    {
        $form = $this->createForm(new CoursType(), $entity, array(
            'action' => $this->generateUrl('cours_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array('label' => 'Update'));

        return $form;
    }
    /**
     * Edits an existing Cours entity.
     *
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('OsmTechLearningBundle:Cours')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Cours entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('cours_edit', array('id' => $id)));
        }

        return $this->render('OsmTechLearningBundle:Cours:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }
    /**
     * Deletes a Cours entity.
     *
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('OsmTechLearningBundle:Cours')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Cours entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('cours'));
    }

    /**
     * Creates a form to delete a Cours entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('cours_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Delete'))
            ->getForm()
        ;
    }
}


text:
require 'spec_helper'

describe 'delivery_build::workspace' do
  context 'by default' do
    before do
      default_mocks
    end

    let(:dirs) { %w(bin lib etc) }

    cached(:chef_run) do
      runner = ChefSpec::SoloRunner.new do |node|
        node.set['delivery_build']['chef_root'] = '/etc/chef'
      end
      runner.converge('delivery_build::workspace')
    end

    cached(:windows_chef_run) do
      runner = ChefSpec::SoloRunner.new(platform: 'windows', version: '2012R2')
      runner.converge('delivery_build::workspace')
    end

    describe 'windows' do
      let(:workspace) { 'C:/delivery/ws' }

      it 'should create the workspace' do
        expect(windows_chef_run).to create_directory(workspace).with(
          mode: '0755',
          recursive: true
        )
      end

      it 'should create subdirectories' do
        dirs.each do |dir|
          path = File.join(workspace, dir)
          expect(windows_chef_run).to create_directory(path).with(
            mode: '0755',
            recursive: true
          )
        end
      end

      it 'should add the delivery-cmd.cmd' do
        filename = "#{workspace}/bin/delivery-cmd.cmd"
        expect(windows_chef_run).to render_file(filename)
      end

      it 'creates the delivery-cmd' do
        filename = '/var/opt/delivery/workspace/bin/delivery-cmd'
        expect(chef_run).to render_file(filename).with_content(
          /class Streamy/
        )
        expect(chef_run).to_not render_file(filename).with_content(
          /Raven/
        )
      end
    end

    describe 'ubuntu' do
      it 'converges successfully' do
        chef_run
      end

      let(:workspace) { '/var/opt/delivery/workspace' }

      it 'should create the workspace own by dbuild' do
        expect(chef_run).to create_directory(workspace).with(
          owner: 'dbuild',
          group: 'dbuild',
          mode: '0755',
          recursive: true
        )
      end

      it 'should create the .chef own by dbuild' do
        expect(chef_run).to create_directory(File.join(workspace, '.chef')).with(
          owner: 'dbuild',
          group: 'dbuild',
          mode: '0755',
          recursive: true
        )
      end

      it 'should create subdirectories own by root' do
        dirs.each do |dir|
          path = File.join(workspace, dir)
          expect(chef_run).to create_directory(path).with(
            owner: 'root',
            mode: '0755',
            recursive: true
          )
        end
      end

      it 'writes the ssh wrapper' do
        filename = '/var/opt/delivery/workspace/bin/git_ssh'
        expect(chef_run).to create_template(filename).with(
          owner: 'root',
          mode: '0755'
        )
        [
          Regexp.new('-o UserKnownHostsFile=/var/opt/delivery/workspace/etc/delivery-git-ssh-known-hosts'),
          Regexp.new('-o IdentityFile=/var/opt/delivery/workspace/etc/builder_key'),
          Regexp.new('-l builder'),
        ].each do |check|
          expect(chef_run).to render_file(filename).with_content(check)
        end
      end

      it 'creates the known hosts file' do
        expect(chef_run).to create_file('/var/opt/delivery/workspace/etc/delivery-git-ssh-known-hosts')
      end

      it 'creates the delivery-cmd' do
        filename = '/var/opt/delivery/workspace/bin/delivery-cmd'
        expect(chef_run).to create_template(filename).with(
          owner: 'root',
          mode: '0755'
        )
        expect(chef_run).to render_file(filename).with_content(
          /class Streamy/
        )
        expect(chef_run).to_not render_file(filename).with_content(
          /Raven/
        )
      end

      it 'creates the builder ssh key' do
        ['/var/opt/delivery/workspace/etc/builder_key',
         '/var/opt/delivery/workspace/.chef/builder_key',
        ].each do |filename|
          expect(chef_run).to create_file(filename).with(
            owner: 'dbuild',
            mode: '0600'
          )
          # This means you got it from the data bag
          expect(chef_run).to render_file(filename).with_content(
            'rocks_is_aerosmiths_best_album'
          )
        end
      end

      it 'creates the delivery.pem for the chef server' do
        ['/var/opt/delivery/workspace/etc/delivery.pem',
         '/var/opt/delivery/workspace/.chef/delivery.pem',
        ].each do |filename|
          expect(chef_run).to create_file(filename).with(
            owner: 'dbuild',
            mode: '0600'
          )
          # This means you got it from the data bag
          expect(chef_run).to render_file(filename).with_content(
            'toys_in_the_attic_is_aerosmiths_best_album'
          )
        end
      end

      it 'creates the knife.rb' do
        filename = '/var/opt/delivery/workspace/.chef/knife.rb'
        expect(chef_run).to create_template(filename).with(
          owner: 'dbuild',
          mode: '0644'
        )
        [
          Regexp.new('node_name\s+"delivery"'),
          Regexp.new('client_key\s+"#{current_dir}/delivery.pem"'),
          Regexp.new('trusted_certs_dir\s+"/etc/chef/trusted_certs"'),
        ].each do |check|
          expect(chef_run).to render_file(filename).with_content(check)
        end
      end

      it 'fetches the delivery chef server ssl key' do
        expect(chef_run).to run_execute('fetch_ssl_certificate').with(
          command: 'knife ssl fetch -c /var/opt/delivery/workspace/etc/delivery.rb'
        )
      end

      it 'does not fetch the ssl certificate for the delivery api by default' do
        expect(chef_run).to_not run_execute('fetch_delivery_ssl_certificate')
      end
    end

    context "with node['delivery_build']['api'] set" do
      before do
        default_mocks
      end

      cached(:chef_run) do
        runner = ChefSpec::SoloRunner.new
        runner.node.normal['delivery_build']['api'] = 'https://192.168.33.1'
        runner.converge('delivery_build::workspace')
      end

      it 'fetches the delivery chef server ssl key' do
        expect(chef_run).to run_execute('fetch_delivery_ssl_certificate').with(
          command: 'knife ssl fetch -c /var/opt/delivery/workspace/etc/delivery.rb https://192.168.33.1'
        )
      end
    end

    context "with node['delivery_build']['sentry_dsn'] set" do
      before do
        default_mocks
      end

      cached(:chef_run) do
        runner = ChefSpec::SoloRunner.new
        runner.node.normal['delivery_build']['sentry_dsn'] = 'https://sentry_dsn'
        runner.converge('delivery_build::workspace')
      end

      it 'adds raven gem to chefdk' do
        expect(chef_run).to run_execute('install_sentry-raven').with(
          command: '/opt/chefdk/bin/chef gem install sentry-raven'
        )
      end

      it 'configures delivery-cmd to use Raven' do
        filename = '/var/opt/delivery/workspace/bin/delivery-cmd'
        expect(chef_run).to render_file(filename).with_content(
          /Raven/
        )
      end
    end
  end
end


text:
package todo.model.form;

import org.hibernate.validator.constraints.NotEmpty;

import java.util.Date;

/**
 * Form model todo create form
 *
 * @author Murat Duzgun
 */
public class TodoCreateForm {

    @NotEmpty
    private String content;

    @NotEmpty
    private String dateRangeUserFriendly;

    @NotEmpty
    private String dateRange;

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getDateRangeUserFriendly() {
        return dateRangeUserFriendly;
    }

    public void setDateRangeUserFriendly(String dateRangeUserFriendly) {
        this.dateRangeUserFriendly = dateRangeUserFriendly;
    }

    public String getDateRange() {
        return dateRange;
    }

    public void setDateRange(String dateRange) {
        this.dateRange = dateRange;
    }
}