text:
package etcd

import (
	"github.com/go-kit/kit/metrics"
	"github.com/go-kit/kit/metrics/prometheus"
	promc "github.com/prometheus/client_golang/prometheus"
)

type raftMetrics struct {
	leader      metrics.Gauge
	commitIndex metrics.Gauge
}

var rmetrics = &raftMetrics{
	leader: prometheus.NewGaugeFrom(promc.GaugeOpts{
		Namespace: "raft",
		Subsystem: "etcd_server",
		Name:      "leader",
		Help:      "Current Raft leader.",
	}, []string{}),
	commitIndex: prometheus.NewGaugeFrom(promc.GaugeOpts{
		Namespace: "raft",
		Subsystem: "etcd_server",
		Name:      "commit_index",
		Help:      "Current commit index.",
	}, []string{}),
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.sysds.runtime.controlprogram.parfor;

import java.util.List;

import org.apache.sysds.runtime.instructions.cp.IntObject;

/**
 * This is the base class for all task partitioner. For this purpose it stores relevant information such as
 * the loop specification (FROM, TO, INCR), the index variable and the task size. Furthermore, it declares two
 * prototypes: (1) full task creation, (2) streaming task creation.
 *
 * Known implementation classes: TaskPartitionerFixedsize, TaskPartitionerFactoring
 *
 */
public abstract class TaskPartitioner
{
	protected long           _taskSize     = -1;
	protected String  		 _iterVarName  = null;
	protected IntObject      _fromVal      = null;
	protected IntObject      _toVal        = null;
	protected IntObject      _incrVal      = null;
	protected long           _numIter      = -1;

	protected TaskPartitioner( long taskSize, String iterVarName, IntObject fromVal, IntObject toVal, IntObject incrVal )
	{
		_taskSize    = taskSize;
		_iterVarName = iterVarName;
		_fromVal     = fromVal;
		_toVal       = toVal;
		_incrVal     = incrVal;

		//normalize predicate if necessary
		normalizePredicate();

		//compute number of iterations
		_numIter     = (long)Math.ceil(((double)(_toVal.getLongValue()-_fromVal.getLongValue()+1 )) / _incrVal.getLongValue());
	}

	/**
	 * Creates and returns set of all tasks for given problem at once.
	 *
	 * @return list of tasks
	 */
	public abstract List<Task> createTasks();

	/**
	 * Creates set of all tasks for given problem, but streams them directly
	 * into task queue. This allows for more tasks than fitting in main memory.
	 *
	 *
	 * @param queue queue of takss
	 * @return ?
	 */
	public abstract long createTasks( LocalTaskQueue<Task> queue );

	public long getNumIterations() {
		return _numIter;
	}

	/**
	 * Normalizes the (from, to, incr) predicate to a predicate w/
	 * positive increment.
	 */
	private void normalizePredicate() {
		//check for positive increment
		if( _incrVal.getLongValue() >= 0 )
			return;

		long lfrom = _fromVal.getLongValue();
		long lto = _toVal.getLongValue();
		long lincr = _incrVal.getLongValue();

		_fromVal = new IntObject(lfrom - ((lfrom - lto)/lincr * lincr));
		_toVal   = new IntObject(lfrom);
		_incrVal = new IntObject(-1 * lincr);
	}
}


text:
<<<<<<< HEAD
<<<<<<< HEAD
var extend = require('util')._extend

function constructObject(initialObject) {
  initialObject = initialObject || {}

  return {
    extend: function (object) {
      return constructObject(extend(initialObject, object))
    },
    done: function () {
      return initialObject
    }
  }
}

function constructOptionsFrom(uri, options) {
  var params = constructObject()
  if (typeof uri === 'object') params.extend(uri)
  if (typeof uri === 'string') params.extend({uri: uri})
  params.extend(options)
  return params.done()
}

function filterForCallback(values) {
  var callbacks = values.filter(isFunction)
  return callbacks[0]
}

function isFunction(value) {
  return typeof value === 'function'
}

function paramsHaveRequestBody(params) {
  return (
    params.options.body ||
    params.options.requestBodyStream ||
    (params.options.json && typeof params.options.json !== 'boolean') ||
    params.options.multipart
  )
}

exports.isFunction            = isFunction
exports.constructObject       = constructObject
exports.constructOptionsFrom  = constructOptionsFrom
exports.filterForCallback     = filterForCallback
exports.paramsHaveRequestBody = paramsHaveRequestBody
=======
var extend = require('util')._extend

function constructObject(initialObject) {
  initialObject = initialObject || {}

  return {
    extend: function (object) {
      return constructObject(extend(initialObject, object))
    },
    done: function () {
      return initialObject
    }
  }
}

function constructOptionsFrom(uri, options) {
  var params = constructObject()
  if (typeof uri === 'object') params.extend(uri)
  if (typeof uri === 'string') params.extend({uri: uri})
  params.extend(options)
  return params.done()
}

function filterForCallback(values) {
  var callbacks = values.filter(isFunction)
  return callbacks[0]
}

function isFunction(value) {
  return typeof value === 'function'
}

function paramsHaveRequestBody(params) {
  return (
    params.options.body ||
    params.options.requestBodyStream ||
    (params.options.json && typeof params.options.json !== 'boolean') ||
    params.options.multipart
  )
}

exports.isFunction            = isFunction
exports.constructObject       = constructObject
exports.constructOptionsFrom  = constructOptionsFrom
exports.filterForCallback     = filterForCallback
exports.paramsHaveRequestBody = paramsHaveRequestBody
>>>>>>> b875702c9c06ab5012e52ff4337439b03918f453
=======
var extend = require('util')._extend

function constructObject(initialObject) {
  initialObject = initialObject || {}

  return {
    extend: function (object) {
      return constructObject(extend(initialObject, object))
    },
    done: function () {
      return initialObject
    }
  }
}

function constructOptionsFrom(uri, options) {
  var params = constructObject()
  if (typeof uri === 'object') params.extend(uri)
  if (typeof uri === 'string') params.extend({uri: uri})
  params.extend(options)
  return params.done()
}

function filterForCallback(values) {
  var callbacks = values.filter(isFunction)
  return callbacks[0]
}

function isFunction(value) {
  return typeof value === 'function'
}

function paramsHaveRequestBody(params) {
  return (
    params.options.body ||
    params.options.requestBodyStream ||
    (params.options.json && typeof params.options.json !== 'boolean') ||
    params.options.multipart
  )
}

exports.isFunction            = isFunction
exports.constructObject       = constructObject
exports.constructOptionsFrom  = constructOptionsFrom
exports.filterForCallback     = filterForCallback
exports.paramsHaveRequestBody = paramsHaveRequestBody
>>>>>>> b875702c9c06ab5012e52ff4337439b03918f453


text:
// Copyright (c) MOSA Project. Licensed under the New BSD License.

namespace Mosa.Compiler.Framework.IR
{
	/// <summary>
	/// Intermediate representation of an integer comparison.
	/// </summary>
	public sealed class IntegerCompare : ThreeOperandInstruction
	{
		#region Construction

		/// <summary>
		/// Initializes a new instance of the <see cref="IntegerCompare"/> class.
		/// </summary>
		public IntegerCompare()
		{
		}

		#endregion Construction

		#region ThreeOperandInstruction Overrides

		/// <summary>
		/// Abstract visitor method for intermediate representation visitors.
		/// </summary>
		/// <param name="visitor">The visitor object.</param>
		/// <param name="context">The context.</param>
		public override void Visit(IIRVisitor visitor, Context context)
		{
			visitor.IntegerCompare(context);
		}

		#endregion ThreeOperandInstruction Overrides
	}
}


text:
using System.Data.Entity;
using System.Linq;
using Abp.Configuration.Startup;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.TestBase.SampleApplication.Messages;
using Shouldly;
using Xunit;

namespace Abp.TestBase.SampleApplication.Tests.ContactLists
{
    public class Querying_Tests : SampleApplicationTestBase
    {
        private readonly IRepository<Message> _messageRepository;

        public Querying_Tests()
        {
            _messageRepository = Resolve<IRepository<Message>>();
        }

        protected override void CreateInitialData()
        {
            Resolve<IMultiTenancyConfig>().IsEnabled = true;
            base.CreateInitialData();
        }

        [Fact]
        public void Simple_Querying_With_AsNoTracking()
        {
            using (var uow = Resolve<IUnitOfWorkManager>().Begin())
            {
                var messages = _messageRepository
                    .GetAll()
                    .AsNoTracking()
                    .ToList();

                messages.Any().ShouldBeTrue();

                uow.Complete();
            }
        }
    }
}


text:
using System.Diagnostics.CodeAnalysis;

namespace Clang2Sharp.Contracts
{
    public interface ISourceRange
    {
        ISourceLocation Start { get; }

        [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "End", Justification = "It's ok")]
        ISourceLocation End { get; }

        bool IsNull { get; }
    }
}


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

    var module = angular.module('std.null.not.null.query', []);

    module.controller('stdNullNotNullController', ['$scope', 'stdOperatorLookup', 'stdUtil',
        function ($scope, operatorLookup, util) {
            var ctrlValue = $scope.field.property.value;
            var ctrlDefault = $scope.field.property.default;
            var ctrlValueHasValue = typeof ctrlValue !== 'undefined';
            var ctrlDefaultHasValue = typeof ctrlDefault !== 'undefined';
            var operator = operatorLookup[$scope.field.property.operator].operator;

            var onClearCB = function(){
                return function() {
                    if (ctrlValueHasValue) return;
                    $scope.field.value.$ = undefined;
                    $scope.updateQueryPredicate();
                }
            }();

            var onDefaultCB = function(){
                return function() {
                    if (ctrlValueHasValue) return;
                    if (ctrlDefaultHasValue)
                        $scope.field.value.$ = util.tryParseInt(ctrlDefault, ctrlDefault);
                    else
                        $scope.field.value.$ = undefined;
                    $scope.updateQueryPredicate();
                }
            }();

            $scope.updateQueryPredicate = function() {
                var value = $scope.field.value.$;
                var queryPredicate = $scope.field.queryPredicate;
                if (typeof value !== 'undefined') {
                    if (value) {
                        operator = 'ne';
                    } else {
                        operator = 'eq';
                    }
                    queryPredicate.set('', operator, null);
                } else {
                    queryPredicate.clear();
                }
            };

            $scope.data = {
                choices: [],
                label: undefined
            };

            var loadChoices = function() {
                $scope.data.choices.push({label: 'Is Set', value: {$: 1}});
                $scope.data.choices.push({label: 'Is Not Set', value: {$: 0}});
                $scope.data.choices.unshift({label: '', value: {$: undefined}});

                if (ctrlValueHasValue) {
                    $scope.data.label = $scope.data.choices.filter(function (obj) {
                        return obj.value.$ === ctrlValue;
                    })[0].label;
                    $scope.field.value.$ = util.tryParseInt(ctrlValue, ctrlValue);
                } else if (ctrlDefaultHasValue)
                    $scope.field.value.$ = util.tryParseInt(ctrlDefault, ctrlDefault);
                else
                    $scope.field.value.$ = undefined;

                $scope.updateQueryPredicate();
            };

            $scope.valueIsUndefined = function () {
                return (typeof ctrlValue === 'undefined');
            };

            $scope.controlValueIsUndefined = function () {
                return (typeof $scope.field === 'undefined') || (typeof $scope.field.value.$ === 'undefined') || $scope.field.value.$ === '';
            };

            $scope.onOperatorClick = function() {
                if (ctrlValueHasValue || $scope.field.context.isEditing) return;
                $scope.field.value.$ = undefined;
                $scope.updateQueryPredicate();
            };

            $scope.operatorImage = operatorLookup['equal'].operatorImage;
            $scope.operatorImageMessage = operatorLookup['equal'].operatorImageMessage;

            if(ctrlValue === null) {
                $scope.data.label = 'Null';
                $scope.field.value.$ = null;
                $scope.updateQueryPredicate();
            }

            $scope.init = function() {
                $scope.searchGroupCtrl.registerClear(onClearCB);
                $scope.searchGroupCtrl.registerDefault(onDefaultCB);
                loadChoices();
            };
        }]);

    module.directive('stdNullNotNullQuery',
        ['$templateCache', '$timeout',
            function ($templateCache, $timeout) {
                return {
                    restrict: 'E',
                    scope: {
                        field: '=',
                        label: '@'
                    },
                    require: '^truSearchGroup',
                    template: $templateCache.get('src/templates/query/std-null-not-null-query.html'),
                    controller: 'stdNullNotNullController',
                    link: function (scope, element, attrs, searchGroupCtrl) {
                        $timeout(function() {
                            var select = element[0].querySelectorAll('select')[0];

                            angular.element(select).bind('keydown', function (e) {
                                if (e.keyCode === 46) {
                                    scope.field.value.$ = undefined;
                                }
                                scope.updateQueryPredicate();
                            });
                        });

                        scope.searchGroupCtrl = searchGroupCtrl;
                        scope.init();
                    }
                };
            }
        ]);
})();


text:
"""
Created on Thu May 31 11:09:39 2012

@author: Fela Winkelmolen

Some methods to generate test matrixes
"""

import scipy as sp
import scipy.linalg as linalg
import numpy.random as random
#import  load

def delta():
    return sp.finfo(float).eps * 16

def ortonormal(m):
    I = sp.identity(m)

    # eigenvectors of a random symmetric m by m matrix
    A = sp.rand(m, m)
    #print '---------------------------'
    #print A.sum()
    S = A * A.T
    _, P = linalg.eigh(S)
    #print P
    #print P.dot(P.T)
    # check if really ortonormal
    if ((P.dot(P.T) - I > delta()).any()):
        return ortonormal(m) # try again
    return P

def low_rank(m, rank):
    diag = sp.concatenate((sp.rand(rank)*5+1, sp.zeros(m-rank)))
    E = sp.diag(diag)
    return ortonormal(m).dot(E).dot(ortonormal(m).T)

def spiky(m, spikes=None, avg=1.0, sigma=None):
    # substitute None with default values
    spikes = spikes or m
    sigma = sigma or avg/6.0

    GA = sp.zeros((m, m))
    r = random.randint(0, m, spikes) # row indexes of spikes
    c = random.randint(0, m, spikes) # column indexes of spikes
    GA[[r, c]] = sigma * random.randn(spikes) + avg
    return GA

def selection(m, perc):
    return sp.rand(m, m) >= perc


text:
import { Inject } from 'common/annotations';
import { registerComponent } from 'common/register';

import template from './component.html';

const options = {
	template,
	bindings: {
		bookId: '<',
	},
};

const starIcons = {
	filled: ' ',
	empty: ' ',
};

@Inject('BooksService', '$scope', '$state', '$alert')
class BookFormComponent {
	constructor (BooksService, $scope, $state, $alert) {
		Object.assign(this, {
			BooksService,
			$scope,
			$state,
			$alert,
		});

		/**
		 * Options for rating selectbox
		 * @type {Array}
		 */
		this.ratingSelectOptions = [];
		this._setRatingSelectOptions();

		/**
		 * Book object
		 * @type {Object}
		 */
		this.book = {
			rating: 1,
		};
		if (this.bookId) {
			this._loadBook();
		}
	}

	/**
	 * Saves a book - desides to call update or create methods based on book id
	 *
	 * @public
	 */
	async saveBook () {
		if (this.bookForm.$invalid) {
			return;
		}

		if (this.book.id) {
			await this.BooksService.update(this.book);
		}
		else {
			await this.BooksService.create(this.book);
		}

		await this.$alert({
			title: 'Success!',
			content: 'Book succesfully saved.',
			type: 'success',
			placement: 'top',
			animation: 'am-fade-and-scale',
			container: 'body',
			duration: '4',
		}).$promise;

		this.$state.transitionTo('books-library-view');
	}

	/**
	 * Loads the book by id
	 *
	 * @private
	 */
	async _loadBook () {
		this.book = await this.BooksService.load(this.bookId);

		delete this.book.createdAt;
		delete this.book.updatedAt;

		this.$scope.$apply();
	}

	/**
	 * Creates options for rating selectbox
	 *
	 * @private
	 */
	_setRatingSelectOptions () {
		for (let i = 1; i <= 5; i++) {
			let starsHelper = '';

			for (let n = 1; n <= 5; n++) {
				starsHelper += n <= i ? starIcons.filled : starIcons.empty;
			}

			this.ratingSelectOptions.push({
				value: i,
				label: starsHelper,
			});
		}
	}
}

registerComponent('bookForm', BookFormComponent, options);


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Aecidium asphodeli Castagne

### Remarks
null


text:
/* Flex */
*[noclass] *[flex] {
	position: relative;
	display: -webkit-flex;
	display: -ms-flexbox;
	display: flex;
	flex-flow: column;
	justify-content: center;
	width: 100%;
	background-size: cover;
	background-position: center center;
	background-repeat: no-repeat;
	background-attachment: scroll;
}

*[noclass] *[flex] > section {
	position: relative;
	display: inherit;
	flex-flow: row;
	align-items: center;
	width: 100%;
	padding-top: 0;
	padding-bottom: 0;
	padding-left: 16px;  padding-left: var(--gutter, 16px);
	padding-right: 16px; padding-right: var(--gutter, 16px);
}


text:
"""
Copyright © 2017 by Stephen Genusa

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
"""

from __future__ import print_function
import argparse
import os
import re
import socket
import subprocess
import sys
import textwrap
import webbrowser
from time import sleep
#
import netifaces
import paramiko
#import hexdump
#import pprint

SSH_PORT = 22
CIP_PORT = 41794
CTP_PORT = 41795
MAX_RETRIES = 3
BUFF_SIZE = 20000
CR = "\r"
BROADCAST_IP = '255.255.255.255'
UDP_MSG = "\x14\x00\x00\x00\x01\x04\x00\x03\x00\x00\x66\x65\x65\x64" + \
    ("\x00" * 252)

class CrestronDeviceDocumenter(object):
    """
    Attempt to identify all commands on a Crestron device
    """
    # pylint: disable=too-many-instance-attributes

    def __init__(self, args):
        """
        initialize internal properties
        """
        self.active_ips_to_check = []
        if args.iptocheck:
            self.active_ips_to_check.append(args.iptocheck)
        self.preseed_command_list = []
        self.possible_commands_filename = args.addtestcommands
        self.preseed_commands_filename = "preseed.upc"
        self.do_not_execute_commands_filename = "donotexec.upc"
        self.do_not_execute_command_list = []
        self.firmwareversion = ""
        self.console_prompt = ""
        self.htmldocfilename = ""
        self.unpublished_commands_filename = ""
        self.args = args

    def initialize_run_variables(self):
        self.console_prompt = ""
        self.firmwareversion = ""
        self.help_dict = {}
        self.pub_command_list = []
        self.hidden_command_list = []
        self.unpublished_command_list = []
        self.htmldocfilename = ""
        self.unpublished_commands_filename = ""

    def place_on_win_clipboard(self, text_to_clipboard):
        """
        For testing of regular expressions
        """
        from Tkinter import Tk
        r = Tk()
        r.withdraw()
        r.clipboard_clear()
        r.clipboard_append(text_to_clipboard)
        r.update()
        r.destroy()

    def print_debug_data(self, data, msg):
        """
        debug printing of data
        """
        print("*" * 35, msg, "*" * 35)
        print(data)
        print("*" * 35, msg, "*" * 35)
        print("\n")

    def build_list_of_activeips(self, subnet):
        """
        Build a list of devices that respond to ping for a /24 subnet like 17.1.6.{1}:
        """
        print ("Building list of active IP addresses on subnet {0}.0/24\nPlease wait...".format(subnet))
        with open(os.devnull, "wb") as limbo:
            for last_octet in xrange(1, 255):
                ip = "{0}.{1}".format(subnet, last_octet)
                result = subprocess.Popen(["ping", "-n", "1", "-w", "200", ip],
                         stdout=limbo, stderr=limbo).wait()
                if not result:
                    self.active_ips_to_check.append(ip)
            if self.active_ips_to_check:
                print("Located {0} active IPs on subnet".format(len(self.active_ips_to_check)))

    def build_list_of_crestronips(self):
        """
        Build a list of Crestron devices that respond to a UDP message
        """
        for iface in netifaces.interfaces():
            if netifaces.AF_INET in netifaces.ifaddresses(iface):
                # This works better than current version of Crestron Toolbox's Device Discovery
                if 'broadcast' in netifaces.ifaddresses(iface)[netifaces.AF_INET][0] and \
                   'addr' in netifaces.ifaddresses(iface)[netifaces.AF_INET][0]:
                    cur_ip = netifaces.ifaddresses(iface)[netifaces.AF_INET][0]['addr']
                    loc_bcast_ip = netifaces.ifaddresses(iface)[netifaces.AF_INET][0]['broadcast']
                    print("Testing IP subnet", cur_ip)
                    for bcast_ip in [BROADCAST_IP, loc_bcast_ip]:
                        udp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                        udp_sock.bind((cur_ip, CIP_PORT))
                        udp_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
                        udp_sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
                        udp_sock.sendto(UDP_MSG, (bcast_ip, CIP_PORT))
                        udp_sock.settimeout(2.0)
                        try:
                            while True:
                                data, addr = udp_sock.recvfrom(4096)
                                search = re.findall ('\x00([a-zA-Z0-9-]{2,30})\x00', data[9:40])
                                if search:
                                    dev_name = search[0]
                                    dev_ip = addr[0]
                                    if cur_ip != dev_ip and dev_ip not in self.active_ips_to_check and dev_name is not "feed":
                                        self.active_ips_to_check.append(dev_ip)
                        except Exception, e:
                            #print ("The exception was: %s" % e) //timed out
                            pass
        total_dev_count = len(self.active_ips_to_check)
        print ("\nLocated a total of {0} Crestron".format(total_dev_count), "device" if total_dev_count == 1 else "devices")

    def open_device_connection(self):
        """
        Open the device connection, attempting port 41795
        """
        SOCKET_TIMEOUT = 5.0

        if not self.args.forcessh:
            try:
                self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                server_address = (self.device_ip_address, 41795)
                self.sock.settimeout(SOCKET_TIMEOUT)
                print("Attempting to connect to {0} port {1}".format(self.device_ip_address, CTP_PORT))
                self.sock.connect(server_address)
                self.usingssh = False
                return True
            except:
                pass
        else:
            self.sshclient = paramiko.client.SSHClient()
            try:
                self.sshclient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                self.sshclient.load_system_host_keys()
                print("Attempting to connect to {0} port {1}".format(self.device_ip_address, SSH_PORT))
                self.sshclient.connect(self.device_ip_address, port=22, username=self.args.username, password=self.args.password, timeout=SOCKET_TIMEOUT)
                self.usingssh = True
                return True
            except:
                print("Error: Unable to connect to device.")
        return False

    def close_device_connection(self):
        """
        Close the socket
        """
        try:
            print("\nProcess complete.")
            if self.usingssh:
                self.sshclient.close()
            else:
                self.sock.close()
        except:
            pass

    def get_console_prompt(self):
        """
        Determine the device console prompt
        """
        data = ""
        #try:
        for _unused in range(0, MAX_RETRIES):
            if self.usingssh:
                stdin,stdout,stderr=self.sshclient.exec_command("ver")
                data = str(stdout.readlines())
                search = re.findall("([\w-]{3,30})\ ", data, re.MULTILINE)
            else:
                self.sock.sendall(CR)
                data += self.sock.recv(BUFF_SIZE)
                search = re.findall("[\n\r]([\w-]{3,30})>", data, re.MULTILINE)

            sleep(.25)
            #self.place_on_win_clipboard(data)
            #print(hexdump.hexdump(data))
            if search:
                self.console_prompt = search[0]
                self.unpublished_commands_filename = self.console_prompt + ".upc"
                print("Console prompt is", self.console_prompt)
                if self.console_prompt == "MERCURY":
                    print("Mercury currently unsupported due to Crestron engin.err.uity")
                    exit()
                return True
        #except:
        #    pass
        print("Console prompt not found on device.")
        return False

    def remove_prompt(self, data, char_limit):
        """
        Remove the console prompt from the text within the specified character limit
        """
        prompt_pos = data.find(self.console_prompt+">")
        if prompt_pos < char_limit:
            data = data.replace(self.console_prompt+">", "", 1)
        if char_limit == -1:
            data = data.replace(self.console_prompt+">", "")
        return data

    def send_command_wait_prompt(self, command, waitforpromptlocation):
        """
        Send a command and wait for the console prompt following the specified location
        """
        if self.usingssh:
            stdin,stdout,stderr=self.sshclient.exec_command(command)
            data = stdout.readlines()
            data = "".join(data)
        else:
            message = CR + command + CR
            self.sock.sendall(message)
            data = ""
            sleep(0.2)
            waitcount = 0
            data = self.sock.recv(BUFF_SIZE)
            data = data.replace(message, "")
            while data.find(self.console_prompt, waitforpromptlocation) == -1:
                # Deal with newer firmware that executes commands / doesn't return a prompt
                #   instead of printing help
                try:
                    sleep(0.2)
                    data += self.sock.recv(BUFF_SIZE)
                except:
                    self.sock.sendall(CR)
                waitcount += 1
                if waitcount == 5:
                    self.sock.sendall(CR)
                    waitcount = 0
        return data

    def get_firmware_version(self):
        """
        Get the firmware version of the device
        """
        data = self.send_command_wait_prompt("ver", 40)
        if not self.usingssh:
            data = data.replace(self.console_prompt + ">", "")
            search = re.search(r"[\r\n]{1,2}([\w\[\]\.\ \(\),#@-]{20,90})[\r\n]{1,2}", data, re.MULTILINE)
            if search:
                self.firmwareversion = search.group().strip()
        else:
            self.firmwareversion = data.strip()
        print("Firmware version ", self.firmwareversion)

    def get_command_help(self, command):
        """
        Get the help text for a command
        """
        if command in self.do_not_execute_command_list:
            return self.help_dict[cmd]

        message = command + " ?"
        data = self.send_command_wait_prompt(message, 30)
        if data.upper().find("BAD COMM") > -1 or data.upper().find("INCOMPLETE COMM") > -1:
            return ""
        if data.find("Authentication is not on. Command not allowed.") > -1 or \
           data.find("ERROR: Command Blocked from this console type.") > -1 or \
           data == "":
            return "No help available for this command."
        help_text = ""
        if not self.usingssh:
            search = re.findall(r"[\r\n]{1,2}(.{5," + str(len(data)) + "})[\r\n]{1,2}" + \
                    self.console_prompt + ">", data, re.M|re.S)
            if search:
                help_text = search[0].replace(self.console_prompt + ">", ""). \
                            replace(">", ">").replace("<", "<")
                if help_text.find(message, 1, 30) > -1:
                    help_text = help_text[len(message) + 2:]
        else:
            help_text = data.replace("\r\n\r\n", "\r\n")
        reformatted_help_text = ""
        for line in help_text.split("\n"):
            reformatted_help_text += textwrap.fill(line, 150) + "\n"
        return reformatted_help_text

    def get_command_categories(self):
        """
        Get a list of the command categories
        Not currently used
        """
        print("Getting command categories")
        data = self.send_command_wait_prompt("hidhelp", 20)
        data = data[12:]
        category_list = []
        category_desc = []
        search = re.findall(r"^HELP ([A-Za-z]{2,20})\ will\ (.{10,100})$", data,
                            re.M)
        if search:
            for find in search:
                if find[0] != "ALL":
                    category_list.append(find[0])
                    category_desc.append(find[1])

    def get_categorial_command_list(self, category):
        """
        Get a list of the commands in a given category
        Not currently used
        """
        print("\n\nGetting categorial commandset", category)
        message = CR + "hidhelp " + category
        data = self.send_command_wait_prompt(message, 30)
        data = data[len(message)+4:]
        command_list = []
        help_desc = []
        search = re.findall("^(.{1,200})$", data, re.M)
        if search:
            for find in search:
                search2 = re.findall(r"^(\w{2,25})\ *(\w{7,19}|User\ or\ Connect)?\ *(.{1,120})$", find, re.M|re.S)
                if search2:
                    command_list.append(search2[0][0].strip())
                    help_desc.append(search2[0][2].strip())
            if not command_list:
                print("[None]")

    def get_help_list(self, help_command, command_list, command_dict):
        """
        Get a list of the normal/published commands
        """
        data = self.send_command_wait_prompt(help_command, 30)
        data = data.replace(help_command, "")
        data = self.remove_prompt(data, 100)
        data = self.remove_prompt(data, -1)
        if data.find("\r\n"):
            data = data.replace("\r\n", "\r").replace("\r", "\n")
        if data.find("Bad") > -1 or data.find("Incomplete Command") > -1:
            return
        search = re.findall(r"\n(.{1,200}?)(?=\n)", data, re.MULTILINE)
        if search:
            for find in search:
                search2 = re.findall(r"(\w{2,25})\ *(Programmer|Operator|Administrator|User\ or\ Connect)?\ *(.{1,120})", find, re.MULTILINE)
                if search2:
                    command = search2[0][0].strip()
                    if command not in command_list and command <> "Add":
                        command_list.append(command)
                        if command not in command_dict:
                            command_dict[command] = search2[0][2].strip()

    def get_published_command_list(self):
        """
        Get a list of the normal/published commands
        """
        print("Getting Normal Commandset")
        self.get_help_list("help all", self.pub_command_list, self.help_dict)
        print("Found", len(self.pub_command_list), "Normal commands")

    def get_hidden_command_list(self):
        """
        Get a list of the hidden commands
        """
        print("Getting Hidden Commandset (if available)")
        self.get_help_list("hidhelp all", self.hidden_command_list, self.help_dict)
        if self.hidden_command_list:
            print("Found", len(self.hidden_command_list)-len(self.pub_command_list), "Hidden commands")

    def save_unpublished_command_list(self):
        """
        Save the unpublished commands for reuse
        """
        if self.unpublished_command_list:
            with open(self.unpublished_commands_filename, "w") as cmd_file:
                cmd_file.writelines(["%s\n" % item for item in self.unpublished_command_list])

    def load_preseed_command_list(self):
        """
        Load the preseed unpublished command list
        """
        if os.path.isfile(self.preseed_commands_filename):
            with open(self.preseed_commands_filename, "r") as cmd_file:
                upc_lines = cmd_file.readlines()
                self.preseed_command_list = [item.strip() for item in upc_lines if item.strip != ""]

    def save_preseed_command_list(self):
        """
        Save the unpublished commands for reuse
        """
        if self.preseed_command_list:
            with open(self.preseed_commands_filename, "w") as cmd_file:
                cmd_file.writelines(["%s\n" % item for item in self.preseed_command_list])

    def test_if_command_exists(self, complete_command_list, command1):
        """
        Test if the command exists
        """
        command1 = command1.strip()
        if not command1:
            return
        command_exists = False
        command1_help = self.get_command_help(command1)
        for cmd_known in complete_command_list:
            if cmd_known.upper() == command1.upper():
                command_exists = True
            elif command1.upper() == cmd_known[:len(command1)].upper() or \
               cmd_known.upper() == command1[:len(cmd_known)].upper():
                command2_help = self.get_command_help(cmd_known)
                if len(command1_help) == len(command2_help):
                    command_exists = True
        if not command_exists and command1_help:
            if command1 not in self.preseed_command_list:
                self.preseed_command_list.append(command1)
            if command1 not in self.unpublished_command_list:
                self.unpublished_command_list.append(command1)
                if command1 not in self.help_dict:
                    self.help_dict[command1] = ""
                print(command1 + " ", end="")
                sys.stdout.flush()

    def load_do_not_execute_command_list(self):
        """
        Load commands not to execute from a text file
        File format:
          CMD1FORM1,CMD1FORM2~Short help description|Long help description
          CMD2FORM1,CMD2FORM2~Short help description|Long help description
        """
        if os.path.isfile(self.do_not_execute_commands_filename):
            print ("Loading and parsing do-not-execute commands")
            with open(self.do_not_execute_commands_filename, "r") as cmd_file:
                upc_lines = cmd_file.readlines()
                for item in upc_lines:
                    if item.strip != "":
                        item = item.strip()
                        if item[0] != "#":
                            cmd_forms, short_long_help = item.split("~")
                            cmd_forms = cmd_forms.split(",")
                            for cmd in cmd_forms:
                                if cmd not in self.do_not_execute_command_list:
                                    self.do_not_execute_command_list.append(cmd)
                                if cmd not in self.help_dict:
                                    self.help_dict[cmd] = short_long_help

    def load_possible_command_list(self):
        """
        Load possible commands from a text file
        """
        poss_list = []
        if os.path.isfile(self.possible_commands_filename):
            print ("Loading and parsing possible commands")
            with open(self.possible_commands_filename, "r") as cmd_list_file:
                for line in iter(cmd_list_file):
                    cmds = line.strip().upper()
                    cmds = re.split(r"([\w]+)", cmds)
                    #print (cmds)
                    if cmds:
                        for cmd in cmds:
                            poss_list.append(cmd)
            uniq_cmds = set(poss_list)
            poss_list = list(uniq_cmds)
            poss_list.sort()
            with open("a_" + self.possible_commands_filename, "w") as cmd_list_file:
                for cmd in poss_list:
                    cmd_list_file.write(cmd + "\n")
            return poss_list

    def test_for_unpublished_commands(self):
        """
        Load a text file and test the commands for inclusion in the device documentation
        """
        complete_command_list = []
        complete_command_list.extend(self.pub_command_list)
        if self.hidden_command_list:
            complete_command_list.extend(self.hidden_command_list)

        # Load the possible commands file
        poss_cmds = self.load_possible_command_list()
        if not poss_cmds:
            poss_cmds = []

        # Load the device specific existing unpublished commands file, if it exists
        if os.path.isfile(self.unpublished_commands_filename):
            with open(self.unpublished_commands_filename, "r") as cmd_list_file:
                for line in iter(cmd_list_file):
                    a_cmd = line.strip()
                    if a_cmd:
                        poss_cmds.insert(0, a_cmd)

        # Preseed with known unpublished commands file, it if exists
        if os.path.isfile(self.preseed_commands_filename):
            with open(self.preseed_commands_filename, "r") as cmd_list_file:
                for line in iter(cmd_list_file):
                    a_cmd = line.strip()
                    if a_cmd and a_cmd not in poss_cmds:
                        poss_cmds.insert(0, a_cmd)

        if poss_cmds:
            print("Testing for Unpublished commands")
            for cmd in poss_cmds:
                self.test_if_command_exists(complete_command_list, cmd)
            self.unpublished_command_list.sort()
            self.save_unpublished_command_list()
            self.save_preseed_command_list()
        if self.unpublished_command_list:
            print("\nFound", len(self.unpublished_command_list), "Unpublished commands")

    def write_html_documentation(self):
        """
        Write the HTML file
        """
        if not self.pub_command_list and not self.hidden_command_list and \
           not self.unpublished_command_list:
            print("Help commands not found on this device.")
            return

        complete_command_list = []
        complete_command_list.extend(self.pub_command_list)
        if self.hidden_command_list:
            complete_command_list.extend(self.hidden_command_list)
        if self.unpublished_command_list:
            complete_command_list.extend(self.unpublished_command_list)

        print("")
        uniq_cmds = set(complete_command_list)
        complete_command_list = list(uniq_cmds)
        complete_command_list.sort()

        special_command_color = "#0000FF"
        unpublished_command_color = "#8B0000"

        self.htmldocfilename = self.console_prompt + ".html"
        htmlfile = open(self.htmldocfilename, "w")
        pagetitle = "Commandset for the " + self.console_prompt
        htmlfile.write("<!DOCTYPE HTML>\n")
        htmlfile.write("<html>\n")
        htmlfile.write("<head>\n  <title>" + pagetitle +
                       "</title>\n  <meta name=\"utility_author\" content=\"Stephen Genusa\">\n")
        htmlfile.write("  <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n")
        htmlfile.write("  <style type=\"text/css\">\n")
        htmlfile.write("      table { page-break-inside:auto }\n")
        htmlfile.write("      tr    { page-break-inside:avoid; page-break-after:auto }\n")
        htmlfile.write("      thead { display:table-header-group }\n")
        htmlfile.write("      tfoot { display:table-footer-group }\n")
        htmlfile.write("      fwver { font-size:12px }\n")
        htmlfile.write("  </style>\n")
        htmlfile.write("</head>\n<body>\n<font face='arial'>\n")
        htmlfile.write("<h1>" + pagetitle + "</h1>\n")
        htmlfile.write("<blockquote>\n")
        htmlfile.write("<p style=\"font-size:12px\">" + self.firmwareversion + "</p>\n")
        htmlfile.write("<p>" + str(len(self.pub_command_list)) +
                       " normal commands found. ")

        if self.hidden_command_list:
            htmlfile.write("<font color=\"" + special_command_color + "\">" +
                           str(len(self.hidden_command_list)-len(self.pub_command_list)) +
                           "</font> hidden commands available. ")
        if self.unpublished_command_list:
            htmlfile.write("<font color=\"" + unpublished_command_color + "\">" +
                           str(len(self.unpublished_command_list)) +
                           " unpublished commands available.</font>")
        htmlfile.write("</p>\n")
        htmlfile.write("</blockquote>\n")

        htmlfile.write("<table border=\"1\" cellpadding=\"5\" cellspacing=\"5\" style=\"border-collapse:collapse;\" width=\"100%\">\n")

        for index, command in enumerate(complete_command_list):
            if command in self.unpublished_command_list:
                color = unpublished_command_color
                class_name = "unpub"
            elif command in self.pub_command_list:
                color = "#000000"
                class_name = "pub"
            else:
                color = special_command_color
                class_name = "hid"
            if command in self.do_not_execute_command_list:
                short_help = self.help_dict[command].split("|")[0]
                long_help = self.help_dict[command].split("|")[1]
            else:
                short_help = self.help_dict[command]
                long_help = self.get_command_help(command)
            htmlfile.write("<tr class=\"" + class_name + "\" bgcolor=\"#C0C0C0\">\n  <th width=\"20%\"><font color=\"" +
                           color + "\">" + command +
                           "</font></th>\n  <th align=\"left\"><font color=\"" +
                           color + "\"> " + short_help +
                           "</font></th>\n</tr>\n")
            htmlfile.write("<tr>\n  <td colspan=\"2\">\n<pre>" + long_help +
                           "</pre>\n</td>\n</tr>\n")
            print("(" + str(index) + ")" + command + " ", end="")
            sys.stdout.flush()
        htmlfile.write("</table>\n</font>\n")
        htmlfile.write("</body>\n</html>")

    def generate_documentation(self):
        """
        Generate device documentation
        """
        self.load_preseed_command_list()
        if self.args.autolocatecrestron:
            self.build_list_of_crestronips()
        elif self.args.autolocateactiveips:
            self.build_list_of_activeips(self.args.autolocateactiveips)
        for self.device_ip_address in self.active_ips_to_check:
            self.initialize_run_variables()
            self.load_do_not_execute_command_list()
            if self.open_device_connection():
                if self.get_console_prompt():
                    if not os.path.isfile(self.console_prompt + ".html") or self.args.overwrite:
                        try:
                            self.get_firmware_version()
                            self.get_published_command_list()
                            self.get_hidden_command_list()
                            self.test_for_unpublished_commands()
                            self.write_html_documentation()
                        finally:
                            self.close_device_connection()
                            if os.path.isfile(os.path.realpath(self.htmldocfilename)):
                                webbrowser.open_new_tab("file://" + os.path.realpath(self.htmldocfilename))
                    else:
                        print("Documentation file already found for {0}. Overwrite is off.".format(self.console_prompt))

if __name__ == "__main__":
    # pylint: disable-msg=C0103
    print("\nStephen Genusa's Crestron Device Command Documentation Builder 1.82\n")
    parser = argparse.ArgumentParser()
    parser.add_argument("-ip", "--iptocheck", help="A single Crestron IP address to build documentation for.")
    parser.add_argument("-fssh", "--forcessh", action="store_true",
                        help="Force use of SSH rather than CTP 41795")
    parser.add_argument("-uid", "--username", default="crestron", type=str,
                        help="Authentication user name.")
    parser.add_argument("-pwd", "--password", default="", type=str,
                        help="Authentication password.")
    parser.add_argument("-alc", "--autolocatecrestron", action="store_true",
                        help="Automatically locate Crestron devices on all connected subnets and build documentation.")
    parser.add_argument("-ala", "--autolocateactiveips", default="", type=str,
                        help="Automatically locate active IPs on a subnet and look for Crestron devices. Example: 174.209.101 as an argument will check 174.209.101.0/24.")
    parser.add_argument("-atc", "--addtestcommands", default='',
                        help="Filename containing additional commands to test for")
    parser.add_argument("-ow", "--overwrite", action="store_true", default=False,
                        help="Overwrite doc file if it already exists. Off by default.")
    parser_args = parser.parse_args()
    if not parser_args.iptocheck and not parser_args.autolocatecrestron and not parser_args.autolocateactiveips:
        parser.print_help()
        exit()

    documenter = CrestronDeviceDocumenter(parser_args)
    documenter.generate_documentation()


text:
package dagger.tests.integration.codegen;

import com.google.common.base.Joiner;
import com.google.testing.compile.JavaFileObjects;
import javax.tools.JavaFileObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource;
import static com.google.testing.compile.JavaSourcesSubjectFactory.javaSources;
import static dagger.tests.integration.ProcessorTestUtils.daggerProcessors;
import static java.util.Arrays.asList;
import static org.truth0.Truth.ASSERT;

@RunWith(JUnit4.class)
public final class ModuleAdapterGenerationTest {
  /**
   * Shows current behavior for a {@link dagger.Provides provides method}
   * used to supply an injected ctor parameter.
   *
   *

   *
{@code ProvidesAdapter} invokes the module's provides method on
   *   {@code get}

   *
On {@code getBindings}, the above is newed up and linked to its type
   *   key.
   *
{@code InjectAdapter} contains a field for the parameter binding,
   *   referenced in {@code getDependencies} and set on {@code attach}

   *
On {@code get}, the injected constructor is called with the value of
   *   {@link dagger.internal.Binding#get}

   *

   */
  @Test public void providerForCtorInjection() {
    JavaFileObject sourceFile = JavaFileObjects.forSourceString("Field", Joiner.on("\n").join(
        "import dagger.Module;",
        "import dagger.Provides;",
        "import javax.inject.Inject;",
        "class Field {",
        "  static class A { final String name; @Inject A(String name) { this.name = name; }}",
        "  @Module(injects = { A.class, String.class })",
        "  static class AModule { @Provides String name() { return \"foo\"; }}",
        "}"));

    JavaFileObject expectedModuleAdapter =
        JavaFileObjects.forSourceString("Field$AModule$$ModuleAdapter", Joiner.on("\n").join(
        "import dagger.internal.BindingsGroup;",
        "import dagger.internal.ModuleAdapter;",
        "import dagger.internal.ProvidesBinding;",
        "import javax.inject.Provider;",
        "public final class Field$AModule$$ModuleAdapter",
        "    extends ModuleAdapter<Field.AModule> {",
        "  private static final String[] INJECTS = ",
        "      {\"members/Field$A\", \"members/java.lang.String\"};",
        "  private static final Class<?>[] STATIC_INJECTIONS = {};",
        "  private static final Class<?>[] INCLUDES = {};",
        "  public Field$AModule$$ModuleAdapter() {",
        "    super(Field.AModule.class, INJECTS, STATIC_INJECTIONS, false, INCLUDES, true, false);",
        "  }",
        "  @Override public Field.AModule newModule() {",
        "    return new Field.AModule();",
        "  }",
        "  @Override public void getBindings(BindingsGroup bindings, Field.AModule module) {",
        "    bindings.contributeProvidesBinding(\"java.lang.String\",",
        "        new NameProvidesAdapter(module));", // eager new!
        "  }",
        "  public static final class NameProvidesAdapter", // corresponds to method name
        "      extends ProvidesBinding<String> implements Provider<String> {",
        "    private final Field.AModule module;",
        "    public NameProvidesAdapter(Field.AModule module) {",
        "      super(\"java.lang.String\", NOT_SINGLETON, \"Field.AModule\", \"name\");",
        "      this.module = module;",
        "      setLibrary(false);",
        "    }",
        "    @Override public String get() {",
        "      return module.name();", // corresponds to @Provides method
        "    }",
        "  }",
        "}"));

    JavaFileObject expectedInjectAdapter =
        JavaFileObjects.forSourceString("Field$A$$InjectAdapter", Joiner.on("\n").join(
            "import dagger.internal.Binding;",
            "import dagger.internal.Linker;",
            "import java.util.Set;",
            "import javax.inject.Provider;",
            "public final class Field$A$$InjectAdapter",
            "    extends Binding<Field.A> implements Provider<Field.A> {",
            "  private Binding<String> name;", // for ctor
            "  public Field$A$$InjectAdapter() {",
            "    super(\"Field$A\", \"members/Field$A\", NOT_SINGLETON, Field.A.class);",
            "  }",
            "  @Override @SuppressWarnings(\"unchecked\")",
            "  public void attach(Linker linker) {",
            "    name = (Binding<String>)linker.requestBinding(", // binding key is not a class
            "      \"java.lang.String\", Field.A.class, getClass().getClassLoader());",
            "  }",
            "  @Override public void getDependencies(",
            "      Set<Binding<?>> getBindings, Set<Binding<?>> injectMembersBindings) {",
            "    getBindings.add(name);", // name is added to dependencies
            "  }",
            "  @Override public Field.A get() {",
            "    Field.A result = new Field.A(name.get());", // adds ctor param
            "    return result;",
            "  }",
            "}"));

    ASSERT.about(javaSource()).that(sourceFile).processedWith(daggerProcessors())
        .compilesWithoutError()
        .and()
        .generatesSources(expectedModuleAdapter, expectedInjectAdapter);

  }

  @Test public void injectsMembersInjectedAndProvidedAndConstructedTypes() {
    JavaFileObject sourceFile = JavaFileObjects.forSourceString("Field", Joiner.on("\n").join(
        "import dagger.Module;",
        "import dagger.Provides;",
        "import javax.inject.Inject;",
        "class Field {",
        "  static class A { final String name; @Inject A(String name) { this.name = name; }}",
        "  static class B { @Inject String name; }",
        "  @Module(injects = { A.class, String.class, B.class })",
        "  static class AModule { @Provides String name() { return \"foo\"; }}",
        "}"));

    JavaFileObject expectedModuleAdapter =
        JavaFileObjects.forSourceString("Field$AModule$$ModuleAdapter", Joiner.on("\n").join(
        "import dagger.internal.BindingsGroup;",
        "import dagger.internal.ModuleAdapter;",
        "import dagger.internal.ProvidesBinding;",
        "import javax.inject.Provider;",
        "public final class Field$AModule$$ModuleAdapter extends ModuleAdapter<Field.AModule> {",
        "  private static final String[] INJECTS = ",
        "      {\"members/Field$A\", \"members/java.lang.String\", \"members/Field$B\"};",
        "  private static final Class<?>[] STATIC_INJECTIONS = {};",
        "  private static final Class<?>[] INCLUDES = {};",
        "  public Field$AModule$$ModuleAdapter() {",
        "    super(Field.AModule.class, INJECTS, STATIC_INJECTIONS, false, INCLUDES, true, false);",
        "  }",
        "  @Override public Field.AModule newModule() {",
        "    return new Field.AModule();",
        "  }",
        "  @Override public void getBindings(BindingsGroup bindings, Field.AModule module) {",
        "    bindings.contributeProvidesBinding(\"java.lang.String\",",
        "        new NameProvidesAdapter(module));", // eager new!
        "  }",
        "  public static final class NameProvidesAdapter", // corresponds to method name
        "      extends ProvidesBinding<String> implements Provider<String> {",
        "    private final Field.AModule module;",
        "    public NameProvidesAdapter(Field.AModule module) {",
        "      super(\"java.lang.String\", NOT_SINGLETON, \"Field.AModule\", \"name\");",
        "      this.module = module;",
        "      setLibrary(false);",
        "    }",
        "    @Override public String get() {",
        "      return module.name();", // corresponds to @Provides method
        "    }",
        "  }",
        "}"));

    JavaFileObject expectedInjectAdapterA =
        JavaFileObjects.forSourceString("Field$A$$InjectAdapter", Joiner.on("\n").join(
            "import dagger.internal.Binding;",
            "import dagger.internal.Linker;",
            "import java.util.Set;",
            "import javax.inject.Provider;",
            "public final class Field$A$$InjectAdapter",
            "    extends Binding<Field.A> implements Provider<Field.A> {",
            "  private Binding<String> name;", // For Constructor.
            "  public Field$A$$InjectAdapter() {",
            "    super(\"Field$A\", \"members/Field$A\", NOT_SINGLETON, Field.A.class);",
            "  }",
            "  @Override @SuppressWarnings(\"unchecked\")",
            "  public void attach(Linker linker) {",
            "    name = (Binding<String>)linker.requestBinding(",
            "      \"java.lang.String\", Field.A.class, getClass().getClassLoader());",
            "  }",
            "  @Override public void getDependencies(",
            "      Set<Binding<?>> getBindings, Set<Binding<?>> injectMembersBindings) {",
            "    getBindings.add(name);", // Name is added to dependencies.
            "  }",
            "  @Override public Field.A get() {",
            "    Field.A result = new Field.A(name.get());", // Adds constructor parameter.
            "    return result;",
            "  }",
            "}"));

    JavaFileObject expectedInjectAdapterB =
        JavaFileObjects.forSourceString("Field$B$$InjectAdapter", Joiner.on("\n").join(
            "import dagger.MembersInjector;",
            "import dagger.internal.Binding;",
            "import dagger.internal.Linker;",
            "import java.util.Set;",
            "import javax.inject.Provider;",
            "public final class Field$B$$InjectAdapter",
            "    extends Binding<Field.B> implements Provider<Field.B>, MembersInjector<Field.B> {",
            "  private Binding<String> name;", // For field.
            "  public Field$B$$InjectAdapter() {",
            "    super(\"Field$B\", \"members/Field$B\", NOT_SINGLETON, Field.B.class);",
            "  }",
            "  @Override @SuppressWarnings(\"unchecked\")",
            "  public void attach(Linker linker) {",
            "    name = (Binding<String>)linker.requestBinding(",
            "      \"java.lang.String\", Field.B.class, getClass().getClassLoader());",
            "  }",
            "  @Override public void getDependencies(",
            "      Set<Binding<?>> getBindings, Set<Binding<?>> injectMembersBindings) {",
            "    injectMembersBindings.add(name);", // Name is added to dependencies.
            "  }",
            "  @Override public Field.B get() {",
            "    Field.B result = new Field.B();",
            "    injectMembers(result);",
            "    return result;",
            "  }",
            "  @Override public void injectMembers(Field.B object) {",
            "    object.name = name.get();", // Inject field.
            "  }",
            "}"));
    ASSERT.about(javaSource()).that(sourceFile).processedWith(daggerProcessors())
        .compilesWithoutError()
        .and()
        .generatesSources(expectedModuleAdapter, expectedInjectAdapterA, expectedInjectAdapterB);
  }

  @Test public void providesHasParameterNamedModule() {
    JavaFileObject a = JavaFileObjects.forSourceString("A", Joiner.on("\n").join(
        "import javax.inject.Inject;",
        "class A { @Inject A(){ }}"));
    JavaFileObject b = JavaFileObjects.forSourceString("B", Joiner.on("\n").join(
        "import javax.inject.Inject;",
        "class B { @Inject B(){ }}"));

    JavaFileObject module = JavaFileObjects.forSourceString("BModule", Joiner.on("\n").join(
        "import dagger.Module;",
        "import dagger.Provides;",
        "import javax.inject.Inject;",
        "@Module(injects = B.class)",
        "class BModule { @Provides B b(A module) { return new B(); }}"));

    ASSERT.about(javaSources()).that(asList(a, b, module)).processedWith(daggerProcessors())
        .compilesWithoutError();
  }

}


text:
<?php

namespace Sonata\AdminBundle\Tests\Fixtures\Generator;

use Sonata\AdminBundle\Generator\AbstractBcGenerator;

class GeneratorBc23 extends AbstractBcGenerator
{
    private $skeletonDirs;

    public function setSkeletonDirs($skeletonDirs)
    {
        $this->skeletonDirs = array($skeletonDirs);
    }

    protected function render($template, $parameters)
    {
        if ($this->skeletonDirs === array('path/to/templates') && $template === 'test.html.twig' && $parameters === array('foo' => 'bar')) {
            return 'Result OK';
        }

        return 'Result invalid';
    }

    protected function renderFile($template, $target, $parameters)
    {
        if ($this->render($template, $parameters) === 'Result OK' && $target === 'target_file') {
            return true;
        }

        return false;
    }
}


text:
class Service::FogBugz < Service::Base
  title 'FogBugz'

  string :project_url, :placeholder => "https://yourproject.fogbugz.com",
         :label => 'URL to your FogBugz project:'
  password :api_token, :placeholder => 'API Token',
           :label => 'Your FogBugz API Token.'

  # Create an issue
  def receive_issue_impact_change(payload)
    http.ssl[:verify] = true

    post_body = {
      :sTitle => "#{payload[:title]} [Crashlytics]",
      :sEvent => build_case_event(payload)
    }

    response = http_post fogbugz_url(:cmd => 'new') do |req|
      req.body = post_body
    end

    fogbugz_case, error = parse_response(response, 'response/case')

    if fogbugz_case && !error
      log('issue_impact_change successful')
    else
      log("issue_impact_change failure: #{error}")
      display_error("Could not create FogBugz case")
    end
  end

  def receive_verification
    http.ssl[:verify] = true

    response = http_get fogbugz_url(:cmd => 'listProjects')

    project, error = parse_response(response, 'response/projects')

    if project && !error
      log('verification successful')
    else
      log "verification failure: #{error}"
      display_error('Oops! Please check your API key again.')
    end
  end

  private
  def fogbugz_url(params={})
    query_params = params.map { |k,v| "#{k}=#{v}" }.join('&')

    "#{config[:project_url]}/api.asp?token=#{config[:api_token]}&#{query_params}"
  end

  def build_case_event(payload)
    users_text = if payload[:impacted_devices_count] == 1
      'This issue is affecting at least 1 user who has crashed '
    else
      "This issue is affecting at least #{payload[:impacted_devices_count]} users who have crashed "
    end

    crashes_text = if payload[:crashes_count] == 1
      'at least 1 time.'
    else
      "at least #{payload[:crashes_count]} times."
    end

<<-EOT
Crashlytics detected a new issue.
#{payload[:title]} in #{payload[:method]}

#{users_text}#{crashes_text}

More information: #{payload[:url]}
EOT
  end

  def parse_response(response, subject_selector)
    xml = Nokogiri.XML(response.body)
    error = xml.at('response/error')
    subject = xml.at(subject_selector)
    [subject, error]
  end
end


text:
#include <windows.h>

#if defined(__BORLANDC__)
  #pragma option -a1
#elif defined(__GNUC__) || (defined(__WATCOMC__) && (__WATCOMC__ < 1100)) || defined(__LCC__)
  #pragma pack(1)
#else
  #pragma pack(push,1)
#endif

const unsigned char iso_signature[] = {'C', 'D', '0', '0', '1', 0x1};
const unsigned char udf_signature[] = {'N', 'S', 'R', '0'};

const size_t MIN_HEADER_LEN = 0x8000+sizeof (iso_signature)+1;

int IsUdfHeader(const unsigned char *Data,int DataSize)
{
	if ( (size_t)DataSize < MIN_HEADER_LEN )
		return -1;

	if (memcmp (Data+0x8000+1, &iso_signature, sizeof (iso_signature)))
		return -1;

	const unsigned char *MaxData=Data+DataSize-sizeof(udf_signature);

	for (const unsigned char *CurData=Data+MIN_HEADER_LEN; CurData<MaxData; CurData++)
	{
		if ( !memcmp (CurData, &udf_signature, sizeof (udf_signature)) )
			return 0;
	}

	return -1;
}


text:
#include "uml/impl/ControlFlowImpl.hpp"
#ifdef NDEBUG
	#define DEBUG_MESSAGE(a) /**/
#else
	#define DEBUG_MESSAGE(a) a
#endif

#ifdef ACTIVITY_DEBUG_ON
    #define ACT_DEBUG(a) a
#else
    #define ACT_DEBUG(a) /**/
#endif

//#include "util/ProfileCallCount.hpp"

#include <cassert>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include "abstractDataTypes/SubsetUnion.hpp"

#include "abstractDataTypes/AnyEObject.hpp"
#include "abstractDataTypes/AnyEObjectBag.hpp"
#include "abstractDataTypes/SubsetUnion.hpp"
#include "ecore/EAnnotation.hpp"
#include "ecore/EClass.hpp"
#include "ecore/EAttribute.hpp"
#include "ecore/EStructuralFeature.hpp"
#include "ecore/ecorePackage.hpp"
//Forward declaration includes
#include "persistence/interfaces/XLoadHandler.hpp" // used for Persistence
#include "persistence/interfaces/XSaveHandler.hpp" // used for Persistence

#include <exception> // used in Persistence
#include "uml/umlFactory.hpp"
#include "uml/Activity.hpp"
#include "uml/ActivityEdge.hpp"
#include "uml/ActivityGroup.hpp"
#include "uml/ActivityNode.hpp"
#include "uml/ActivityPartition.hpp"
#include "uml/Classifier.hpp"
#include "uml/Comment.hpp"
#include "uml/Dependency.hpp"
#include "uml/Element.hpp"
#include "uml/InterruptibleActivityRegion.hpp"
#include "uml/Namespace.hpp"
#include "uml/RedefinableElement.hpp"
#include "uml/StringExpression.hpp"
#include "uml/StructuredActivityNode.hpp"
#include "uml/ValueSpecification.hpp"
//Factories and Package includes
#include "uml/umlPackage.hpp"

using namespace uml;

//*********************************
// Constructor / Destructor
//*********************************
ControlFlowImpl::ControlFlowImpl()
{
	/*
	NOTE: Due to virtual inheritance, base class constrcutors may not be called correctly
	*/
}

ControlFlowImpl::~ControlFlowImpl()
{
#ifdef SHOW_DELETION
	std::cout << "-------------------------------------------------------------------------------------------------\r\ndelete ControlFlow "<< this << "\r\n------------------------------------------------------------------------ " << std::endl;
#endif
}

//Additional constructor for the containments back reference
ControlFlowImpl::ControlFlowImpl(std::weak_ptr<uml::Activity> par_activity)
:ControlFlowImpl()
{
	m_activity = par_activity;
	m_owner = par_activity;
}

//Additional constructor for the containments back reference
ControlFlowImpl::ControlFlowImpl(std::weak_ptr<uml::StructuredActivityNode> par_inStructuredNode)
:ControlFlowImpl()
{
	m_inStructuredNode = par_inStructuredNode;
	m_owner = par_inStructuredNode;
}

//Additional constructor for the containments back reference
ControlFlowImpl::ControlFlowImpl(std::weak_ptr<uml::Namespace> par_namespace)
:ControlFlowImpl()
{
	m_namespace = par_namespace;
	m_owner = par_namespace;
}

//Additional constructor for the containments back reference
ControlFlowImpl::ControlFlowImpl(std::weak_ptr<uml::Element> par_owner)
:ControlFlowImpl()
{
	m_owner = par_owner;
}

ControlFlowImpl::ControlFlowImpl(const ControlFlowImpl & obj): ControlFlowImpl()
{
	*this = obj;
}

ControlFlowImpl& ControlFlowImpl::operator=(const ControlFlowImpl & obj)
{
	//call overloaded =Operator for each base class
	ActivityEdgeImpl::operator=(obj);
	/* TODO: Find out if this call is necessary
	 * Currently, this causes an error because it calls an implicit assignment operator of ControlFlow
	 * which is generated by the compiler (as ControlFlow is an abstract class and does not have a user-defined assignment operator).
	 * Implicit compiler-generated assignment operators however only create shallow copies of members,
	 * which implies, that not a real deep copy is created when using the copy()-method.
	 *
	 * NOTE: Since all members are deep-copied by this assignment-operator anyway, why is it even necessary to call this implicit assignment-operator?
	 * This is only done for ecore-models, not for UML-models.
	 */
	//ControlFlow::operator=(obj);

	//create copy of all Attributes
	#ifdef SHOW_COPIES
	std::cout << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\ncopy ControlFlow "<< this << "\r\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ " << std::endl;
	#endif
	//Clone Attributes with (deep copy)

	//copy references with no containment (soft copy)
	//Clone references with containment (deep copy)
	return *this;
}

std::shared_ptr<ecore::EObject> ControlFlowImpl::copy() const
{
	std::shared_ptr<ControlFlowImpl> element(new ControlFlowImpl());
	*element =(*this);
	element->setThisControlFlowPtr(element);
	return element;
}

//*********************************
// Operations
//*********************************
bool ControlFlowImpl::object_nodes(Any diagnostics,std::shared_ptr<std::map < Any, Any>> context)
{
	throw std::runtime_error("UnsupportedOperationException: " + std::string(__PRETTY_FUNCTION__));
}

//*********************************
// Attribute Getters & Setters
//*********************************

//*********************************
// Reference Getters & Setters
//*********************************

//*********************************
// Union Getter
//*********************************
std::shared_ptr<Union<uml::ActivityGroup>> ControlFlowImpl::getInGroup() const
{
	if(m_inGroup == nullptr)
	{
		/*Union*/
		m_inGroup.reset(new Union<uml::ActivityGroup>());
			#ifdef SHOW_SUBSET_UNION
			std::cout << "Initialising Union: " << "m_inGroup - Union<uml::ActivityGroup>()" << std::endl;
		#endif

	}
	return m_inGroup;
}

std::shared_ptr<Union<uml::Element>> ControlFlowImpl::getOwnedElement() const
{
	if(m_ownedElement == nullptr)
	{
		/*Union*/
		m_ownedElement.reset(new Union<uml::Element>());
			#ifdef SHOW_SUBSET_UNION
			std::cout << "Initialising Union: " << "m_ownedElement - Union<uml::Element>()" << std::endl;
		#endif

	}
	return m_ownedElement;
}

std::weak_ptr<uml::Element> ControlFlowImpl::getOwner() const
{
	return m_owner;
}

std::shared_ptr<Union<uml::RedefinableElement>> ControlFlowImpl::getRedefinedElement() const
{
	if(m_redefinedElement == nullptr)
	{
		/*Union*/
		m_redefinedElement.reset(new Union<uml::RedefinableElement>());
			#ifdef SHOW_SUBSET_UNION
			std::cout << "Initialising Union: " << "m_redefinedElement - Union<uml::RedefinableElement>()" << std::endl;
		#endif

	}
	return m_redefinedElement;
}

//*********************************
// Container Getter
//*********************************
std::shared_ptr<ecore::EObject> ControlFlowImpl::eContainer() const
{
	if(auto wp = m_activity.lock())
	{
		return wp;
	}

	if(auto wp = m_inStructuredNode.lock())
	{
		return wp;
	}

	if(auto wp = m_namespace.lock())
	{
		return wp;
	}

	if(auto wp = m_owner.lock())
	{
		return wp;
	}
	return nullptr;
}

//*********************************
// Persistence Functions
//*********************************
void ControlFlowImpl::load(std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler)
{
	std::map<std::string, std::string> attr_list = loadHandler->getAttributeList();
	loadAttributes(loadHandler, attr_list);

	//
	// Create new objects (from references (containment == true))
	//
	// get umlFactory
	int numNodes = loadHandler->getNumOfChildNodes();
	for(int ii = 0; ii < numNodes; ii++)
	{
		loadNode(loadHandler->getNextNodeName(), loadHandler);
	}
}

void ControlFlowImpl::loadAttributes(std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler, std::map<std::string, std::string> attr_list)
{

	ActivityEdgeImpl::loadAttributes(loadHandler, attr_list);
}

void ControlFlowImpl::loadNode(std::string nodeName, std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler)
{

	//load BasePackage Nodes
	ActivityEdgeImpl::loadNode(nodeName, loadHandler);
}

void ControlFlowImpl::resolveReferences(const int featureID, std::vector<std::shared_ptr<ecore::EObject> > references)
{
	ActivityEdgeImpl::resolveReferences(featureID, references);
}

void ControlFlowImpl::save(std::shared_ptr<persistence::interfaces::XSaveHandler> saveHandler) const
{
	saveContent(saveHandler);

	ActivityEdgeImpl::saveContent(saveHandler);

	RedefinableElementImpl::saveContent(saveHandler);

	NamedElementImpl::saveContent(saveHandler);

	ElementImpl::saveContent(saveHandler);

	ObjectImpl::saveContent(saveHandler);

	ecore::EObjectImpl::saveContent(saveHandler);
}

void ControlFlowImpl::saveContent(std::shared_ptr<persistence::interfaces::XSaveHandler> saveHandler) const
{
	try
	{
		std::shared_ptr<uml::umlPackage> package = uml::umlPackage::eInstance();
	}
	catch (std::exception& e)
	{
		std::cout << "| ERROR    | " << e.what() << std::endl;
	}
}

std::shared_ptr<ecore::EClass> ControlFlowImpl::eStaticClass() const
{
	return uml::umlPackage::eInstance()->getControlFlow_Class();
}

//*********************************
// EStructuralFeature Get/Set/IsSet
//*********************************
Any ControlFlowImpl::eGet(int featureID, bool resolve, bool coreType) const
{
	switch(featureID)
	{
	}
	return ActivityEdgeImpl::eGet(featureID, resolve, coreType);
}

bool ControlFlowImpl::internalEIsSet(int featureID) const
{
	switch(featureID)
	{
	}
	return ActivityEdgeImpl::internalEIsSet(featureID);
}

bool ControlFlowImpl::eSet(int featureID, Any newValue)
{
	switch(featureID)
	{
	}

	return ActivityEdgeImpl::eSet(featureID, newValue);
}

//*********************************
// EOperation Invoke
//*********************************
Any ControlFlowImpl::eInvoke(int operationID, std::shared_ptr<std::list<Any>> arguments)
{
	Any result;

  	switch(operationID)
	{
		// uml::ControlFlow::object_nodes(Any, std::map) : bool: 2629306994
		case umlPackage::CONTROLFLOW_OPERATION_OBJECT_NODES_EDIAGNOSTICCHAIN_EMAP:
		{
			//Retrieve input parameter 'diagnostics'
			//parameter 0
			Any incoming_param_diagnostics;
			std::list<Any>::const_iterator incoming_param_diagnostics_arguments_citer = std::next(arguments->begin(), 0);
			incoming_param_diagnostics = (*incoming_param_diagnostics_arguments_citer)->get<Any >();
			//Retrieve input parameter 'context'
			//parameter 1
			std::shared_ptr<std::map < Any, Any>> incoming_param_context;
			std::list<Any>::const_iterator incoming_param_context_arguments_citer = std::next(arguments->begin(), 1);
			incoming_param_context = (*incoming_param_context_arguments_citer)->get<std::shared_ptr<std::map < Any, Any>> >();
			result = eAny(this->object_nodes(incoming_param_diagnostics,incoming_param_context),0,false);
			break;
		}

		default:
		{
			// call superTypes
			result = ActivityEdgeImpl::eInvoke(operationID, arguments);
			if (result && !result->isEmpty())
				break;
			break;
		}
  	}

	return result;
}

std::shared_ptr<uml::ControlFlow> ControlFlowImpl::getThisControlFlowPtr() const
{
	return m_thisControlFlowPtr.lock();
}
void ControlFlowImpl::setThisControlFlowPtr(std::weak_ptr<uml::ControlFlow> thisControlFlowPtr)
{
	m_thisControlFlowPtr = thisControlFlowPtr;
	setThisActivityEdgePtr(thisControlFlowPtr);
}


text:
package server.connectivity.commands;

import java.io.BufferedWriter;

import server.YTJBServer;

public class GetListCommand extends Command {

	private boolean fromWishList;
	private YTJBServer server;

	public GetListCommand(BufferedWriter out,int messageType,YTJBServer server, boolean fromWishList) {
		super(out, messageType);
		this.fromWishList = fromWishList;
		this.server = server;
	}

	@Override
	public boolean handle() {
		response(server.getTitle(fromWishList));
		return true;
	}

}


text:
import React from 'react';
import Header from '../components/header/Header';
import UserDomains from '../components/domain/UserDomains';
import API from '../api';
import styled from '@emotion/styled';
import Head from 'next/head';

import DomainDetails from '../components/header/DomainDetails';
import RequestUtils from '../components/utils/RequestUtils';
import Tabs from '../components/header/Tabs';
import Error from './_error';
import GroupList from '../components/group/GroupList';
import createCache from '@emotion/cache';
import { CacheProvider } from '@emotion/react';

const AppContainerDiv = styled.div`
    align-items: stretch;
    flex-flow: row nowrap;
    height: 100%;
    display: flex;
    justify-content: flex-start;
`;

const MainContentDiv = styled.div`
    flex: 1 1 calc(100vh - 60px);
    overflow: hidden;
    font: 300 14px HelveticaNeue-Reg, Helvetica, Arial, sans-serif;
`;

const GroupsContainerDiv = styled.div`
    align-items: stretch;
    flex: 1 1;
    height: calc(100vh - 60px);
    overflow: auto;
    display: flex;
    flex-direction: column;
`;

const GroupsContentDiv = styled.div``;

const PageHeaderDiv = styled.div`
    background: linear-gradient(to top, #f2f2f2, #fff);
    padding: 20px 30px 0;
`;

const TitleDiv = styled.div`
    font: 600 20px HelveticaNeue-Reg, Helvetica, Arial, sans-serif;
    margin-bottom: 10px;
`;

export default class GroupPage extends React.Component {
    static async getInitialProps(props) {
        let api = API(props.req);
        let reload = false;
        let notFound = false;
        let error = undefined;
        const domains = await Promise.all([
            api.listUserDomains(),
            api.getHeaderDetails(),
            api.getDomain(props.query.domain),
            api.getGroups(props.query.domain),
            api.getPendingDomainMembersList(),
            api.getForm(),
            api.isAWSTemplateApplied(props.query.domain),
        ]).catch((err) => {
            let response = RequestUtils.errorCheckHelper(err);
            reload = response.reload;
            error = response.error;
            return [{}, {}, {}, {}, {}, {}, {}];
        });
        let domainDetails = domains[2];
        domainDetails.isAWSTemplateApplied = !!domains[6];
        return {
            api,
            reload,
            notFound,
            error,
            domains: domains[0],
            headerDetails: domains[1],
            domain: domains[2].name,
            domainDetails,
            groups: domains[3],
            users: domains[1],
            pending: domains[4],
            _csrf: domains[5],
            nonce: props.req.headers.rid,
        };
    }

    constructor(props) {
        super(props);
        this.api = props.api || API();
        this.cache = createCache({
            key: 'athenz',
            nonce: this.props.nonce,
        });
    }

    render() {
        const {
            domain,
            reload,
            domainDetails,
            groups,
            users,
            _csrf,
        } = this.props;
        if (reload) {
            window.location.reload();
            return <div />;
        }
        if (this.props.error) {
            return <Error err={this.props.error} />;
        }

        return (
            <CacheProvider value={this.cache}>
                <div data-testid='group'>
                    <Head>
                        <title>Athenz</title>
                    </Head>
                    <Header
                        showSearch={true}
                        headerDetails={this.props.headerDetails}
                        pending={this.props.pending}
                    />
                    <MainContentDiv>
                        <AppContainerDiv>
                            <GroupsContainerDiv>
                                <GroupsContentDiv>
                                    <PageHeaderDiv>
                                        <TitleDiv>{domain}</TitleDiv>
                                        <DomainDetails
                                            domainDetails={domainDetails}
                                            api={this.api}
                                            _csrf={_csrf}
                                            productMasterLink={
                                                this.props.headerDetails
                                                    .productMasterLink
                                            }
                                        />
                                        <Tabs
                                            api={this.api}
                                            domain={domain}
                                            selectedName={'groups'}
                                        />
                                    </PageHeaderDiv>
                                    <GroupList
                                        api={this.api}
                                        domain={domain}
                                        groups={groups}
                                        users={users}
                                        _csrf={_csrf}
                                        isDomainAuditEnabled={
                                            domainDetails.auditEnabled
                                        }
                                        userProfileLink={
                                            this.props.headerDetails.userData
                                                .userLink
                                        }
                                    />
                                </GroupsContentDiv>
                            </GroupsContainerDiv>
                            <UserDomains
                                domains={this.props.domains}
                                api={this.api}
                                domain={domain}
                            />
                        </AppContainerDiv>
                    </MainContentDiv>
                </div>
            </CacheProvider>
        );
    }
}


text:
touch NEWS README AUTHORS ChangeLog
aclocal
autoconf
automake --add-missing -c


text:
module Neo4j
  module Transaction
    extend self

    module Instance
      # @private
      def register_instance
        @pushed_nested = 0
        Neo4j::Transaction.register(self)
      end

      # Marks this transaction as failed, which means that it will unconditionally be rolled back when close() is called. Aliased for legacy purposes.
      def mark_failed
        @failure = true
      end
      alias_method :failure, :mark_failed

      # If it has been marked as failed. Aliased for legacy purposes.
      def failed?
        !!@failure
      end
      alias_method :failure?, :failed?

      def mark_expired
        @expired = true
      end

      def expired?
        !!@expired
      end

      # @private
      def push_nested!
        @pushed_nested += 1
      end

      # @private
      def pop_nested!
        @pushed_nested -= 1
      end

      # Only for the embedded neo4j !
      # Acquires a read lock for entity for this transaction.
      # See neo4j java docs.
      # @param [Neo4j::Node,Neo4j::Relationship] entity
      # @return [Java::OrgNeo4jKernelImplCoreapi::PropertyContainerLocker]
      def acquire_read_lock(entity)
      end

      # Only for the embedded neo4j !
      # Acquires a write lock for entity for this transaction.
      # See neo4j java docs.
      # @param [Neo4j::Node,Neo4j::Relationship] entity
      # @return [Java::OrgNeo4jKernelImplCoreapi::PropertyContainerLocker]
      def acquire_write_lock(entity)
      end

      # Commits or marks this transaction for rollback, depending on whether failure() has been previously invoked.
      def close
        pop_nested!
        return if @pushed_nested >= 0
        fail "Can't commit transaction, already committed" if @pushed_nested < -1
        Neo4j::Transaction.unregister(self)
        failed? ? delete : commit
      end
    end

    # @return [Neo4j::Transaction::Instance]
    def new(current = Session.current!)
      current.begin_tx
    end

    # Runs the given block in a new transaction.
    # @param [Boolean] run_in_tx if true a new transaction will not be created, instead if will simply yield to the given block
    # @@yield [Neo4j::Transaction::Instance]
    def run(run_in_tx = true)
      fail ArgumentError, 'Expected a block to run in Transaction.run' unless block_given?

      return yield(nil) unless run_in_tx

      tx = Neo4j::Transaction.new
      yield tx
    rescue Exception => e # rubocop:disable Lint/RescueException
      print_exception_cause(e)
      tx.mark_failed unless tx.nil?
      raise
    ensure
      tx.close unless tx.nil?
    end

    # @return [Neo4j::Transaction]
    def current
      Thread.current[:neo4j_curr_tx]
    end

    # @private
    def print_exception_cause(exception)
      return if !exception.respond_to?(:cause) || !exception.cause.respond_to?(:print_stack_trace)

      puts "Java Exception in a transaction, cause: #{exception.cause}"
      exception.cause.print_stack_trace
    end

    # @private
    def unregister(tx)
      Thread.current[:neo4j_curr_tx] = nil if tx == Thread.current[:neo4j_curr_tx]
    end

    # @private
    def register(tx)
      # we don't support running more then one transaction per thread
      fail 'Already running a transaction' if current
      Thread.current[:neo4j_curr_tx] = tx
    end

    # @private
    def unregister_current
      Thread.current[:neo4j_curr_tx] = nil
    end
  end
end


text:
<?php

namespace Alex\PizzaBundle\Controller;

use Sonata\AdminBundle\Controller\CRUDController as Controller;

class TypeAdminController extends Controller
{
    // Your code will be here
}


text:
#include "udp.h"

#include <arpa/inet.h>              // for inet_addr, htonl, htons
#include <cassert>                  // for assert
#include <cstring>                  // for memset
#include <errno.h>                  // for errno
#include <utility>
#include <fcntl.h>                  // for fcntl, F_GETFL, F_SETFL, O_NONBLOCK
#include <sys/types.h>              // for SOL_SOCKET, SO_NOSIGPIPE
#include <sys/socket.h>             // for setsockopt, bind, recvfrom, sendto
#include <netdb.h>                  // for getaddrinfo, addrinfo
#include <sysexits.h>               // for EX_CONFIG

#include "error.hh"                 // for error:name, error::description
#include "exception_xapian.h"       // for NetworkError
#include "io.hh"                    // for close, ignored_errno
#include "length.h"                 // for serialise_string, unserialise_string
#include "log.h"                    // for L_ERR, L_OBJ, L_CRIT, L_CONN, L_UDP_WIRE
#include "manager.h"                // for XapiandManager, sig_exit, Xapiand...
#include "opts.h"                   // for opts

// #undef L_DEBUG
// #define L_DEBUG L_GREY
// #undef L_CALL
// #define L_CALL L_STACKED_DIM_GREY
// #undef L_CONN
// #define L_CONN L_LIGHT_GREEN

UDP::UDP(const char* description, uint8_t major_version, uint8_t minor_version, int flags)
	: sock(-1),
	  closed(true),
	  flags(flags),
	  description(description),
	  major_version(major_version),
	  minor_version(minor_version),
	  addr{}
{}

UDP::~UDP() noexcept
{
	try {
		if (sock != -1) {
			if (io::close(sock) == -1) {
				L_WARNING("WARNING: close {{sock:{}}} - {} ({}): {}", sock, error::name(errno), errno, error::description(errno));
			}
		}
	} catch (...) {
		L_EXC("Unhandled exception in destructor");
	}
}

bool
UDP::close() {
	bool was_closed = closed.exchange(true);
	if (!was_closed && sock != -1) {
		// Safe way to close sock without releasing its file descriptor
		// (other threads could be using the same file descriptor)
		// First shutdown sock
		io::shutdown(sock, SHUT_RDWR);
		// Create a new socket in a temporary file descriptor
		int tmp = io::socket(AF_INET, SOCK_DGRAM, 0);
		if (tmp != -1) {
			// Shutdown the temporary socket
			io::shutdown(tmp, SHUT_RDWR);
			// Close sock and duplicate the temporary socket into the sock file descriptor
			io::dup2(tmp, sock);
			// Close the temporary socket file descriptor
			io::close(tmp);
		}
	}
	return was_closed;
}

void
UDP::bind(const char* hostname, unsigned int serv, int tries)
{
	if (!closed.exchange(false) || !tries) {
		return;
	}

	const int on = 1;
	const int off = 0;

	L_CONN("Binding UDP {}:{}", hostname ? hostname : "0.0.0.0", serv);

	for (; --tries >= 0; ++serv) {
		char servname[6];  // strlen("65535") + 1
		snprintf(servname, sizeof(servname), "%d", serv);

		struct addrinfo hints = {};
		hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST | AI_NUMERICSERV;  // No effect if hostname != nullptr
		hints.ai_family = PF_INET;
		hints.ai_socktype = SOCK_DGRAM;
		hints.ai_protocol = IPPROTO_UDP;

		struct addrinfo *addrinfo;
		if (int err = getaddrinfo(hostname, servname, &hints, &addrinfo)) {
			L_CRIT("ERROR: getaddrinfo {}:{} {{sock:{}}}: {}", hostname ? hostname : "0.0.0.0", servname, sock, gai_strerror(err));
			sig_exit(-EX_CONFIG);
			return;
		}

		for (auto ai = addrinfo; ai != nullptr; ai = ai->ai_next) {
			if ((sock = io::socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol)) == -1) {
				if (ai->ai_next == nullptr) {
					freeaddrinfo(addrinfo);
					L_CRIT("ERROR: {} socket: {} ({}): {}", description, error::name(errno), errno, error::description(errno));
					sig_exit(-EX_CONFIG);
					return;
				}
				L_CONN("ERROR: {} socket: {} ({}): {}", description, error::name(errno), errno, error::description(errno));
				continue;
			}

			if (io::fcntl(sock, F_SETFL, io::fcntl(sock, F_GETFL, 0) | O_NONBLOCK) == -1) {
				freeaddrinfo(addrinfo);
				if (!tries) {
					L_CRIT("ERROR: {} fcntl O_NONBLOCK {{sock:{}}}: {} ({}): {}", description, sock, error::name(errno), errno, error::description(errno));
					close();
					sig_exit(-EX_CONFIG);
					return;
				}
				L_CONN("ERROR: {} fcntl O_NONBLOCK {{sock:{}}}: {} ({}): {}", description, sock, error::name(errno), errno, error::description(errno));
				break;
			}

			if (io::setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(int)) == -1) {
				freeaddrinfo(addrinfo);
				if (!tries) {
					L_CRIT("ERROR: {} setsockopt SO_REUSEADDR {{sock:{}}}: {} ({}): {}", description, sock, error::name(errno), errno, error::description(errno));
					close();
					sig_exit(-EX_CONFIG);
					return;
				}
				L_CONN("ERROR: {} setsockopt SO_REUSEADDR {{sock:{}}}: {} ({}): {}", description, sock, error::name(errno), errno, error::description(errno));
				close();
				break;
			}

			if ((flags & UDP_SO_REUSEPORT) != 0) {
		#ifdef SO_REUSEPORT_LB
				if (io::setsockopt(sock, SOL_SOCKET, SO_REUSEPORT_LB, &on, sizeof(int)) == -1) {
					freeaddrinfo(addrinfo);
					if (!tries) {
						L_CRIT("ERROR: {} setsockopt SO_REUSEPORT_LB {{sock:{}}}: {} ({}): {}", description, sock, error::name(errno), errno, error::description(errno));
						close();
						sig_exit(-EX_CONFIG);
						return;
					}
					L_CONN("ERROR: {} setsockopt SO_REUSEPORT_LB {{sock:{}}}: {} ({}): {}", description, sock, error::name(errno), errno, error::description(errno));
					close();
					break;
				}
		#else
				if (io::setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &on, sizeof(int)) == -1) {
					freeaddrinfo(addrinfo);
					if (!tries) {
						L_CRIT("ERROR: {} setsockopt SO_REUSEPORT {{sock:{}}}: {} ({}): {}", description, sock, error::name(errno), errno, error::description(errno));
						close();
						sig_exit(-EX_CONFIG);
						return;
					}
					break;
				}
		#endif
			}

			size_t sndbuf_size = 0;
			socklen_t sndbuf_size_len = sizeof(size_t);
			if (io::getsockopt(sock, SOL_SOCKET, SO_SNDBUF, &sndbuf_size, &sndbuf_size_len) == -1) {
				if (!tries) {
					L_CRIT("ERROR: {} getsockopt SO_SNDBUF {{sock:{}}}: {} ({}): {}", description, sock, error::name(errno), errno, error::description(errno));
					close();
					sig_exit(-EX_CONFIG);
					return;
				}
				break;
			}
			for (size_t size = 4194304; size >= 262144 && size > sndbuf_size; size /= 2) {
				if (io::setsockopt(sock, SOL_SOCKET, SO_SNDBUF, &size, sizeof(size_t)) != -1) {
					if (size != 4194304) {
						L_WARNING("WARNING: {} SO_SNDBUF is set to {} {{sock:{}}}", description, size, sock);
					}
					sndbuf_size = 0;
					break;
				}
			}
			if (sndbuf_size) {
				L_WARNING("WARNING: {} SO_SNDBUF is set to {} {{sock:{}}}", description, sndbuf_size, sock);
			}

			size_t rcvbuf_size = 0;
			socklen_t rcvbuf_size_len = sizeof(size_t);
			if (io::getsockopt(sock, SOL_SOCKET, SO_RCVBUF, &rcvbuf_size, &rcvbuf_size_len) == -1) {
				if (!tries) {
					L_CRIT("ERROR: {} getsockopt SO_RCVBUF {{sock:{}}}: {} ({}): {}", description, sock, error::name(errno), errno, error::description(errno));
					close();
					sig_exit(-EX_CONFIG);
					return;
				}
				break;
			}
			for (size_t size = 4194304; size >= 262144 && size > rcvbuf_size; size /= 2) {
				if (io::setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size_t)) != -1) {
					if (size != 4194304) {
						L_WARNING("WARNING: {} SO_RCVBUF is set to {} {{sock:{}}}", description, size, sock);
					}
					rcvbuf_size = 0;
					break;
				}
			}
			if (rcvbuf_size) {
				L_WARNING("WARNING: {} SO_RCVBUF is set to {} {{sock:{}}}", description, rcvbuf_size, sock);
			}

			auto* onoff = ((flags & UDP_IP_MULTICAST_LOOP) != 0) ? &on : &off;
			if (io::setsockopt(sock, IPPROTO_IP, IP_MULTICAST_LOOP, onoff, sizeof(int)) == -1) {
				freeaddrinfo(addrinfo);
				if (!tries) {
					L_CRIT("ERROR: {} setsockopt IP_MULTICAST_LOOP {{sock:{}}}: {} ({}): {}", description, sock, error::name(errno), errno, error::description(errno));
					close();
					sig_exit(-EX_CONFIG);
					return;
				}
				break;
			}

			if ((flags & UDP_IP_MULTICAST_TTL) != 0) {
				unsigned char ttl = 3;
				if (io::setsockopt(sock, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)) == -1) {
					freeaddrinfo(addrinfo);
					if (!tries) {
						L_CRIT("ERROR: {} setsockopt IP_MULTICAST_TTL {{sock:{}}}: {} ({}): {}", description, sock, error::name(errno), errno, error::description(errno));
						close();
						sig_exit(-EX_CONFIG);
						return;
					}
					break;
				}
			}

			struct ip_mreq mreq = {};
			if ((flags & UDP_IP_ADD_MEMBERSHIP) != 0) {
				assert(hostname);
				mreq.imr_multiaddr = reinterpret_cast<struct sockaddr_in*>(ai->ai_addr)->sin_addr;
				mreq.imr_interface.s_addr = htonl(INADDR_ANY);
				if (io::setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) == -1) {
					freeaddrinfo(addrinfo);
					if (!tries) {
						L_CRIT("ERROR: {} setsockopt IP_ADD_MEMBERSHIP {{sock:{}}}: {} ({}): {}", description, sock, error::name(errno), errno, error::description(errno));
						close();
						sig_exit(-EX_CONFIG);
						return;
					}
					break;
				}
			}

			addr = *reinterpret_cast<struct sockaddr_in*>(ai->ai_addr);

#ifdef __APPLE__
			// Binding to the multicast group address results in errno
			// EADDRNOTAVAIL "Can't assign requested address" during
			// sendto(2) under OS X, for some reason...
			// So we bind to INADDR_ANY instead:
			if ((flags & UDP_IP_ADD_MEMBERSHIP) != 0) {
				reinterpret_cast<struct sockaddr_in*>(ai->ai_addr)->sin_addr.s_addr = htonl(INADDR_ANY);
			}
#endif

			if (io::bind(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
				freeaddrinfo(addrinfo);
				if (!tries) {
					L_CRIT("ERROR: {} bind error {{sock:{}}}: {} ({}): {}", description, sock, error::name(errno), errno, error::description(errno));
					close();
					sig_exit(-EX_CONFIG);
					return;
				}
				L_CONN("ERROR: {} bind error {{sock:{}}}: {} ({}): {}", description, sock, error::name(errno), errno, error::description(errno));
				close();
				break;
			}

			// L_RED("UDP addr -> {}:{}", inet_ntop(addr), ntohs(addr.sin_port));

			freeaddrinfo(addrinfo);
			return;
		}
	}

	L_CRIT("ERROR: {} unknown bind error {{sock:{}}}: {} ({}): {}", description, sock, error::name(errno), errno, error::description(errno));
	close();
	sig_exit(-EX_CONFIG);
}

ssize_t
UDP::send_message(const std::string& message)
{
	if (!closed) {
		L_UDP_WIRE("{{sock:{}}} <<-- {}", sock, repr(message));

#ifdef MSG_NOSIGNAL
		ssize_t written = io::sendto(sock, message.c_str(), message.size(), MSG_NOSIGNAL, (struct sockaddr *)&addr, sizeof(addr));
#else
		ssize_t written = io::sendto(sock, message.c_str(), message.size(), 0, (struct sockaddr *)&addr, sizeof(addr));
#endif

		if (written < 0) {
			if (!io::ignored_errno(errno, true, false, false)) {
				L_ERR_ONCE_PER_MINUTE("ERROR: sendto error {{sock:{}}}: {} ({}): {}", sock, error::name(errno), errno, error::description(errno));
			}
		}
		return written;
	}
	return 0;
}

ssize_t
UDP::send_message(char type, const std::string& content)
{
	if (!content.empty()) {
		std::string message;
		message.push_back(major_version);
		message.push_back(minor_version);
		message.push_back(type);
		message.append(serialise_string(opts.cluster_name));
		message.append(content);
		return send_message(message);
	}
	return 0;
}

char
UDP::get_message(std::string& result, char max_type)
{
	char buf[1500];
	ssize_t received = io::recv(sock, buf, sizeof(buf), 0);
	if (received < 0) {
		if (!io::ignored_errno(errno, true, false, false)) {
			L_ERR("ERROR: read error {{sock:{}}}: {} ({}): {}", sock, error::name(errno), errno, error::description(errno));
			THROW(NetworkError, error::description(errno));
		}
		// L_CONN("Received ERROR {{sock:{}}}: {} ({}): {}", sock, error::name(errno), errno, error::description(errno));
		return '\xff';
	} else if (received == 0) {
		// If no messages are available to be received and the peer has performed an orderly shutdown.
		L_CONN("Received EOF {{sock:{}}}!", sock);
		return '\xff';
	} else if (received < 4) {
		L_CONN("Badly formed message: Incomplete!");
		return '\xff';
	}

	L_UDP_WIRE("{{sock:{}}} -->> {}", sock, repr(buf, received));

	const char *p = buf;
	const char *p_end = p + received;

	uint8_t received_major_version = *p++;
	uint8_t received_minor_version = *p++;
	if (received_major_version > major_version || (received_major_version == major_version && received_minor_version > minor_version)) {
		L_CONN("Badly formed message: Protocol version mismatch!");
		return '\xff';
	}

	char type = *p++;
	if (type >= max_type) {
		L_CONN("Badly formed message: Invalid message type {}", unsigned(type));
		return '\xff';
	}

	auto remote_cluster_name = unserialise_string(&p, p_end);
	if (remote_cluster_name.empty()) {
		L_CONN("Badly formed message: No cluster name!");
		return '\xff';
	}

	if (remote_cluster_name != opts.cluster_name) {
		return '\xff';
	}

	result = std::string(p, p_end - p);
	return type;
}


text:
A generic error that is raised when TensorFlow execution fails.

Whenever possible, the session will raise a more specific subclass
of `OpError` from the `tf.errors` module.

- - -

#### `tf.OpError.op` {#OpError.op}

The operation that failed, if known.

*N.B.* If the failed op was synthesized at runtime, e.g. a `Send`
or `Recv` op, there will be no corresponding
[`Operation`](../../api_docs/python/framework.md#Operation)
object.  In that case, this will return `None`, and you should
instead use the [`OpError.node_def`](#OpError.node_def) to
discover information about the op.

##### Returns:

  The `Operation` that failed, or None.

- - -

#### `tf.OpError.node_def` {#OpError.node_def}

The `NodeDef` proto representing the op that failed.

#### Other Methods
- - -

#### `tf.OpError.__init__(node_def, op, message, error_code)` {#OpError.__init__}

Creates a new `OpError` indicating that a particular op failed.

##### Args:

*  <b>`node_def`</b>: The `graph_pb2.NodeDef` proto representing the op that failed,
    if known; otherwise None.
*  <b>`op`</b>: The `ops.Operation` that failed, if known; otherwise None.
*  <b>`message`</b>: The message string describing the failure.
*  <b>`error_code`</b>: The `error_codes_pb2.Code` describing the error.

- - -

#### `tf.OpError.error_code` {#OpError.error_code}

The integer error code that describes the error.

- - -

#### `tf.OpError.message` {#OpError.message}

The error message that describes the error.