text:
package com.mkl.websuites.internal.command.impl.check;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.assertj.core.api.StringAssert;
import org.openqa.selenium.WebElement;

import com.mkl.websuites.command.CommandDescriptor;
import com.mkl.websuites.command.OperationOnWebElement;
import com.mkl.websuites.internal.command.impl.validator.SchemaValidationRule;

@CommandDescriptor(name = "checkElementAttr", argumentTypes = {String.class, String.class})
public class CheckElementAttributeCommand extends OperationOnWebElement {

    protected static final String ATT_NAME_PARAM = "attName";

    protected String inputAttributeName;

    protected String actualAttributeValue;

    public CheckElementAttributeCommand(Map<String, String> parameterMap) {
        super(parameterMap);
    }

    @SuppressWarnings("serial")
    public CheckElementAttributeCommand(final String selector, final String expectedText) {
        super(new HashMap<String, String>() {
            {
                put("css", selector);
                put(ATT_NAME_PARAM, expectedText);
            }
        });
    }

    protected class CheckElementAttr extends AbstractSingleStringCheck {

        @Override
        protected void runSingleStringAssertion(StringAssert assertion, String elementText) {

            assertion.overridingErrorMessage(
                    "Expecting attribute '%s' in the web page element with selector '%s'" + " to have a value",
                    inputAttributeName, by).isNotEmpty();
        }

        @Override
        protected String getStringParam() {
            return actualAttributeValue;
        }
    }

    @Override
    protected void doOperationOnElement(WebElement elem) {

        inputAttributeName = parameterMap.get(ATT_NAME_PARAM);
        actualAttributeValue = elem.getAttribute(inputAttributeName);

        AbstractCheck checkLogic = defineCheckLogic();

        checkLogic.runStandardCommand();

    }

    protected AbstractCheck defineCheckLogic() {
        return new CheckElementAttr();
    }

    @Override
    protected List<SchemaValidationRule> defineValidationRules() {

        List<SchemaValidationRule> parentValidationRules = super.defineValidationRules();

        for (SchemaValidationRule schemaValidationRule : parentValidationRules) {
            schemaValidationRule.addMandatoryElements(ATT_NAME_PARAM);
        }

        return parentValidationRules;
    }

}


text:
"""
SendGrid notification service.

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/notify.sendgrid/
"""
import logging

import voluptuous as vol

from homeassistant.const import (
    CONF_API_KEY, CONF_RECIPIENT, CONF_SENDER, CONTENT_TYPE_TEXT_PLAIN)
import homeassistant.helpers.config_validation as cv

from homeassistant.components.notify import (
    ATTR_TITLE, ATTR_TITLE_DEFAULT, PLATFORM_SCHEMA, BaseNotificationService)

REQUIREMENTS = ['sendgrid==5.6.0']

_LOGGER = logging.getLogger(__name__)

CONF_SENDER_NAME = 'sender_name'

DEFAULT_SENDER_NAME = 'Home Assistant'

# pylint: disable=no-value-for-parameter
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Required(CONF_API_KEY): cv.string,
    vol.Required(CONF_SENDER): vol.Email(),
    vol.Required(CONF_RECIPIENT): vol.Email(),
    vol.Optional(CONF_SENDER_NAME, default=DEFAULT_SENDER_NAME): cv.string,
})

def get_service(hass, config, discovery_info=None):
    """Get the SendGrid notification service."""
    return SendgridNotificationService(config)

class SendgridNotificationService(BaseNotificationService):
    """Implementation the notification service for email via Sendgrid."""

    def __init__(self, config):
        """Initialize the service."""
        from sendgrid import SendGridAPIClient

        self.api_key = config[CONF_API_KEY]
        self.sender = config[CONF_SENDER]
        self.sender_name = config[CONF_SENDER_NAME]
        self.recipient = config[CONF_RECIPIENT]

        self._sg = SendGridAPIClient(apikey=self.api_key)

    def send_message(self, message='', **kwargs):
        """Send an email to a user via SendGrid."""
        subject = kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT)

        data = {
            "personalizations": [
                {
                    "to": [
                        {
                            "email": self.recipient
                        }
                    ],
                    "subject": subject
                }
            ],
            "from": {
                "email": self.sender,
                "name": self.sender_name
            },
            "content": [
                {
                    "type": CONTENT_TYPE_TEXT_PLAIN,
                    "value": message
                }
            ]
        }

        response = self._sg.client.mail.send.post(request_body=data)
        if response.status_code != 202:
            _LOGGER.error("Unable to send notification")

redpajama_set_name: RedPajamaGithub


text:
package org.formbuilder.mapping.exception;

/** @author eav Date: 22.08.2010 Time: 12:34:45 */
public class NoGetterProvidedException
        extends MappingException
{
    public NoGetterProvidedException()
    {
        super( "A getter must be called for component injection", null );
    }
}


text:
package de.htwg.scala.ScalaSwing

import swing._
import event._

object TempConverter extends SimpleSwingApplication {
  def top = new MainFrame {
    title = "Celsius/Fahrenheit Converter"
    object celsius extends TextField { columns = 5 }
    object fahrenheit extends TextField { columns = 5 }
    contents = new FlowPanel {
      contents += celsius
      contents += new Label(" Celsius  =  ")
      contents += fahrenheit
      contents += new Label(" Fahrenheit")
      border = Swing.EmptyBorder(15, 10, 10, 10)
    }
    listenTo(celsius, fahrenheit)
    reactions += {
      case EditDone(`fahrenheit`) =>
        val f = fahrenheit.text.toInt
        val c = (f - 32) * 5 / 9
        celsius.text = c.toString
      case EditDone(`celsius`) =>
        val c = celsius.text.toInt
        val f = c * 9 / 5 + 32
        fahrenheit.text = f.toString
    }
  }
}


text:
import React, { PropTypes, Component } from 'react';
import Form from 'react-bootstrap/lib/Form';

class BsForm extends Component {
  getChildContext() {
    let {
      defaultHorizontal,
      defaultLabelDimensions,
      defaultFieldDimensions,
    } = this.props;

    return {
      defaultHorizontal,
      defaultLabelDimensions,
      defaultFieldDimensions,
    };
  }

  render() {
    let {
      /* eslint-disable */
      // consume props owned by BsForm
      defaultHorizontal, defaultLabelDimensions, defaultFieldDimensions,
      /* eslint-enable */
      children,
      ...rest
    } = this.props;

    return (
      <Form horizontal={defaultHorizontal} {...rest}>
        {children}
      </Form>
    );
  }
};

BsForm.propTypes = {
  defaultHorizontal: PropTypes.bool,
  defaultLabelDimensions: PropTypes.object,
  defaultFieldDimensions: PropTypes.object,
};

BsForm.childContextTypes = {
  defaultHorizontal: PropTypes.bool,
  defaultLabelDimensions: PropTypes.object,
  defaultFieldDimensions: PropTypes.object,
};

BsForm.defaultProps = {
  defaultHorizontal: true,
  defaultLabelDimensions: {
    sm: 2,
  },
  defaultFieldDimensions: {
    sm: 10,
  },
};

export default BsForm;


text:
  Péreyres est
       un village
       géographiquement positionné dans le département de l'Ardêche en Rhône-Alpes. Elle comptait 53 habitants en 2008.

La commune propose quelques  aménagements, elle dispose, entre autres, de une boucle de randonnée.

À proximité de Péreyres sont positionnées géographiquement les communes de
Juvinas à 8 km, 155 habitants,
Lachamp-Raphaël localisée à 4 km, 93 habitants,
Saint-Pierre-de-Colombier localisée à 8 km, 385 habitants,
Montpezat-sous-Bauzon localisée à 8 km, 748 habitants,
Sagnes-et-Goudoulet localisée à 2 km, 137 habitants,
Le Chambon localisée à 7 km, 52 habitants,
 entre autres. De plus, Péreyres est située à seulement 20 km de Aubenas.

Si vous pensez venir habiter à Péreyres, vous pourrez facilement trouver une maison à vendre.

Le nombre de logements, à Péreyres, était réparti en 2011 en quatre appartements et 71 maisons soit
 un marché plutôt équilibré.


text:
    /** An abstract class for finalizer generation.
     */
    abstract class GenFinalizer {
		/** Generate code to clean up when unwinding. */
		abstract void gen();

		/** Generate code to clean up at last. */
		abstract void genLast();

		/** Does this finalizer have some nontrivial cleanup to perform? */
		boolean hasFinalizer() { return true; }
    }


text:
package org.spongycastle.asn1;

import java.io.IOException;

public class DERSetParser
    implements ASN1SetParser
{
    private ASN1StreamParser _parser;

    DERSetParser(ASN1StreamParser parser)
    {
        this._parser = parser;
    }

    public ASN1Encodable readObject()
        throws IOException
    {
        return _parser.readObject();
    }

    public ASN1Primitive getLoadedObject()
        throws IOException
    {
        return new DERSet(_parser.readVector(), false);
    }

    public ASN1Primitive toASN1Primitive()
    {
        try
        {
            return getLoadedObject();
        }
        catch (IOException e)
        {
            throw new ASN1ParsingException(e.getMessage(), e);
        }
    }
}


text:
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
* Test whether the given domain is valid for a cookie.
*
* @param {string} domain Domain for a cookie.
* @return {boolean} True if the domain is valid, otherwise false.
*/
function isDomainValid(domain) {
  var dummyCookie = 'ChromeDriverwjers908fljsdf37459fsdfgdfwru=';

  document.cookie = dummyCookie + '; domain=' + domain;
  if (document.cookie.indexOf(dummyCookie) != -1) {
    // Expire the dummy cookie if it is added successfully.
    document.cookie = dummyCookie + '; Max-Age=0';
    return true;
  }
  return false;
}

/**
* Add the given cookie to the current web page.
*
* If path is not specified, default to '/'.
* If domain is not specified, default to document.domain, otherwise remove its
* port number.
*
* Validate name, value, domain and path of the cookie in the same way as the
* method CanonicalCookie::Create in src/net/cookies/canonical_cookie.cc. Besides
* the following requirements, name, value, domain and path of the cookie should
* not start or end with ' ' or '\t', and should not contain '\n', '\r', or '\0'.
*

*
name: no ';' or '='
*
value: no ';'
*
path: starts with '/', no ';'
*

*
* @param {!Object} cookie An object representing a Cookie JSON Object as
*     specified in https://code.google.com/p/selenium/wiki/JsonWireProtocol.
*/
function addCookie(cookie) {
  function isNameInvalid(value) {
    return /(^[ \t])|([;=\n\r\0])|([ \t]$)/.test(value);
  }
  function isValueInvalid(value) {
    return /(^[ \t])|([;\n\r\0])|([ \t]$)/.test(value);
  }
  function isPathInvalid(path) {
    return path[0] != '/' || /([;\n\r\0])|([ \t]$)/.test(path);
  }

  var name = cookie['name'];
  if (!name || isNameInvalid(name))
    throw new Error('name of cookie is missing or invalid:"' + name + '"');

  var value = cookie['value'] || '';
  if (isValueInvalid(value))
    throw new Error('value of cookie is invalid:"' + value + '"');

  var domain = cookie['domain'];
  // Remove the port number from domain.
  if (domain) {
    var domain_parts = domain.split(':');
    if (domain_parts.length > 2)
      throw new Error('domain of cookie has too many colons');
    else if (domain_parts.length == 2)
      domain = domain_parts[0];
  }
  // Validate domain.
  if (domain && (isValueInvalid(domain) || !isDomainValid(domain))) {
    var error = new Error();
    error.code = 24;  // Error code for InvalidCookieDomain.
    error.message = 'invalid domain:"' + domain + '"';
    throw error;
  }

  var path = cookie['path'];
  if (path && isPathInvalid(path))
    throw new Error('path of cookie is invalid:"' + path + '"');

  var newCookie = name + '=' + value;
  newCookie += '; path=' + (path || '/');
  newCookie += '; domain=' + (domain || document.domain);
  if (cookie['expiry']) {
    var expiredDate = new Date(cookie['expiry'] * 1000);
    newCookie += '; expires=' + expiredDate.toUTCString();
  }
  if (cookie['secure'])
    newCookie += '; secure';

  document.cookie = newCookie;
}


text:
package org.springframework.cloud.sleuth.instrument.web;

import static java.util.concurrent.TimeUnit.SECONDS;
import static org.springframework.cloud.sleuth.assertions.SleuthAssertions.then;

import java.util.concurrent.atomic.AtomicReference;

import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.sleuth.Sampler;
import org.springframework.cloud.sleuth.Span;
import org.springframework.cloud.sleuth.Tracer;
import org.springframework.cloud.sleuth.instrument.DefaultTestAutoConfiguration;
import org.springframework.cloud.sleuth.sampler.AlwaysSampler;
import org.springframework.cloud.sleuth.trace.TestSpanContextHolder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.test.context.junit4.SpringRunner;

import com.jayway.awaitility.Awaitility;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {
		TraceAsyncIntegrationTests.TraceAsyncITestConfiguration.class })
public class TraceAsyncIntegrationTests {

	@Autowired
	ClassPerformingAsyncLogic classPerformingAsyncLogic;
	@Autowired
	Tracer tracer;

	@Test
	public void should_set_span_on_an_async_annotated_method() {
		Span span = givenASpanInCurrentThread();

		whenAsyncProcessingTakesPlace();

		thenTraceIdIsPassedFromTheCurrentThreadToTheAsyncOne(span);
	}

	private Span givenASpanInCurrentThread() {
		return this.tracer.createSpan("http:existing");
	}

	private void whenAsyncProcessingTakesPlace() {
		this.classPerformingAsyncLogic.invokeAsynchronousLogic();
	}

	private void thenTraceIdIsPassedFromTheCurrentThreadToTheAsyncOne(final Span span) {
		Awaitility.await().atMost(5, SECONDS).until(new Runnable() {
			@Override
			public void run() {
				then(TraceAsyncIntegrationTests.this.classPerformingAsyncLogic.getSpan())
						.hasTraceIdEqualTo(span.getTraceId())
						.hasNameEqualTo("invoke-asynchronous-logic")
						.isALocalComponentSpan()
						.hasATag("class", "ClassPerformingAsyncLogic")
						.hasATag("method", "invokeAsynchronousLogic");
			}
		});
	}

	@After
	public void cleanTrace() {
		TestSpanContextHolder.removeCurrentSpan();
	}

	@DefaultTestAutoConfiguration
	@EnableAsync
	@Configuration
	static class TraceAsyncITestConfiguration {

		@Bean
		ClassPerformingAsyncLogic asyncClass() {
			return new ClassPerformingAsyncLogic();
		}

		@Bean
		Sampler defaultSampler() {
			return new AlwaysSampler();
		}

	}

	static class ClassPerformingAsyncLogic {

		AtomicReference<Span> span = new AtomicReference<>();

		@Async
		public void invokeAsynchronousLogic() {
			this.span.set(TestSpanContextHolder.getCurrentSpan());
		}

		public Span getSpan() {
			return this.span.get();
		}
	}
}


text:
using System;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager;
using Azure.ResourceManager.GuestConfiguration.Models;
using Azure.ResourceManager.Resources;

namespace Azure.ResourceManager.GuestConfiguration
{
    /// <summary>
    /// A Class representing a GuestConfigurationVmAssignment along with the instance operations that can be performed on it.
    /// If you have a <see cref="ResourceIdentifier" /> you can construct a <see cref="GuestConfigurationVmAssignmentResource" />
    /// from an instance of <see cref="ArmClient" /> using the GetGuestConfigurationVmAssignmentResource method.
    /// Otherwise you can get one from its parent resource <see cref="ResourceGroupResource" /> using the GetGuestConfigurationVmAssignment method.
    /// </summary>
    public partial class GuestConfigurationVmAssignmentResource : ArmResource
    {
        /// <summary> Generate the resource identifier of a <see cref="GuestConfigurationVmAssignmentResource"/> instance. </summary>
        public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string vmName, string guestConfigurationAssignmentName)
        {
            var resourceId = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/providers/Microsoft.GuestConfiguration/guestConfigurationAssignments/{guestConfigurationAssignmentName}";
            return new ResourceIdentifier(resourceId);
        }

        private readonly ClientDiagnostics _guestConfigurationVmAssignmentGuestConfigurationAssignmentsClientDiagnostics;
        private readonly GuestConfigurationAssignmentsRestOperations _guestConfigurationVmAssignmentGuestConfigurationAssignmentsRestClient;
        private readonly ClientDiagnostics _guestConfigurationAssignmentReportsClientDiagnostics;
        private readonly GuestConfigurationAssignmentReportsRestOperations _guestConfigurationAssignmentReportsRestClient;
        private readonly GuestConfigurationAssignmentData _data;

        /// <summary> Initializes a new instance of the <see cref="GuestConfigurationVmAssignmentResource"/> class for mocking. </summary>
        protected GuestConfigurationVmAssignmentResource()
        {
        }

        /// <summary> Initializes a new instance of the <see cref = "GuestConfigurationVmAssignmentResource"/> class. </summary>
        /// <param name="client"> The client parameters to use in these operations. </param>
        /// <param name="data"> The resource that is the target of operations. </param>
        internal GuestConfigurationVmAssignmentResource(ArmClient client, GuestConfigurationAssignmentData data) : this(client, data.Id)
        {
            HasData = true;
            _data = data;
        }

        /// <summary> Initializes a new instance of the <see cref="GuestConfigurationVmAssignmentResource"/> class. </summary>
        /// <param name="client"> The client parameters to use in these operations. </param>
        /// <param name="id"> The identifier of the resource that is the target of operations. </param>
        internal GuestConfigurationVmAssignmentResource(ArmClient client, ResourceIdentifier id) : base(client, id)
        {
            _guestConfigurationVmAssignmentGuestConfigurationAssignmentsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.GuestConfiguration", ResourceType.Namespace, Diagnostics);
            TryGetApiVersion(ResourceType, out string guestConfigurationVmAssignmentGuestConfigurationAssignmentsApiVersion);
            _guestConfigurationVmAssignmentGuestConfigurationAssignmentsRestClient = new GuestConfigurationAssignmentsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, guestConfigurationVmAssignmentGuestConfigurationAssignmentsApiVersion);
            _guestConfigurationAssignmentReportsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.GuestConfiguration", ProviderConstants.DefaultProviderNamespace, Diagnostics);
            _guestConfigurationAssignmentReportsRestClient = new GuestConfigurationAssignmentReportsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint);
#if DEBUG
			ValidateResourceId(Id);
#endif
        }

        /// <summary> Gets the resource type for the operations. </summary>
        public static readonly ResourceType ResourceType = "Microsoft.GuestConfiguration/guestConfigurationAssignments";

        /// <summary> Gets whether or not the current instance has data. </summary>
        public virtual bool HasData { get; }

        /// <summary> Gets the data representing this Feature. </summary>
        /// <exception cref="InvalidOperationException"> Throws if there is no data loaded in the current instance. </exception>
        public virtual GuestConfigurationAssignmentData Data
        {
            get
            {
                if (!HasData)
                    throw new InvalidOperationException("The current instance does not have data, you must call Get first.");
                return _data;
            }
        }

        internal static void ValidateResourceId(ResourceIdentifier id)
        {
            if (id.ResourceType != ResourceType)
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id));
        }

        /// <summary>
        /// Get information about a guest configuration assignment
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/providers/Microsoft.GuestConfiguration/guestConfigurationAssignments/{guestConfigurationAssignmentName}
        /// Operation Id: GuestConfigurationAssignments_Get
        /// </summary>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual async Task<Response<GuestConfigurationVmAssignmentResource>> GetAsync(CancellationToken cancellationToken = default)
        {
            using var scope = _guestConfigurationVmAssignmentGuestConfigurationAssignmentsClientDiagnostics.CreateScope("GuestConfigurationVmAssignmentResource.Get");
            scope.Start();
            try
            {
                var response = await _guestConfigurationVmAssignmentGuestConfigurationAssignmentsRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false);
                if (response.Value == null)
                    throw new RequestFailedException(response.GetRawResponse());
                return Response.FromValue(new GuestConfigurationVmAssignmentResource(Client, response.Value), response.GetRawResponse());
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Get information about a guest configuration assignment
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/providers/Microsoft.GuestConfiguration/guestConfigurationAssignments/{guestConfigurationAssignmentName}
        /// Operation Id: GuestConfigurationAssignments_Get
        /// </summary>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual Response<GuestConfigurationVmAssignmentResource> Get(CancellationToken cancellationToken = default)
        {
            using var scope = _guestConfigurationVmAssignmentGuestConfigurationAssignmentsClientDiagnostics.CreateScope("GuestConfigurationVmAssignmentResource.Get");
            scope.Start();
            try
            {
                var response = _guestConfigurationVmAssignmentGuestConfigurationAssignmentsRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken);
                if (response.Value == null)
                    throw new RequestFailedException(response.GetRawResponse());
                return Response.FromValue(new GuestConfigurationVmAssignmentResource(Client, response.Value), response.GetRawResponse());
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Delete a guest configuration assignment
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/providers/Microsoft.GuestConfiguration/guestConfigurationAssignments/{guestConfigurationAssignmentName}
        /// Operation Id: GuestConfigurationAssignments_Delete
        /// </summary>
        /// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual async Task<ArmOperation> DeleteAsync(WaitUntil waitUntil, CancellationToken cancellationToken = default)
        {
            using var scope = _guestConfigurationVmAssignmentGuestConfigurationAssignmentsClientDiagnostics.CreateScope("GuestConfigurationVmAssignmentResource.Delete");
            scope.Start();
            try
            {
                var response = await _guestConfigurationVmAssignmentGuestConfigurationAssignmentsRestClient.DeleteAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false);
                var operation = new GuestConfigurationArmOperation(response);
                if (waitUntil == WaitUntil.Completed)
                    await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false);
                return operation;
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Delete a guest configuration assignment
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/providers/Microsoft.GuestConfiguration/guestConfigurationAssignments/{guestConfigurationAssignmentName}
        /// Operation Id: GuestConfigurationAssignments_Delete
        /// </summary>
        /// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual ArmOperation Delete(WaitUntil waitUntil, CancellationToken cancellationToken = default)
        {
            using var scope = _guestConfigurationVmAssignmentGuestConfigurationAssignmentsClientDiagnostics.CreateScope("GuestConfigurationVmAssignmentResource.Delete");
            scope.Start();
            try
            {
                var response = _guestConfigurationVmAssignmentGuestConfigurationAssignmentsRestClient.Delete(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken);
                var operation = new GuestConfigurationArmOperation(response);
                if (waitUntil == WaitUntil.Completed)
                    operation.WaitForCompletionResponse(cancellationToken);
                return operation;
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Creates an association between a VM and guest configuration
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/providers/Microsoft.GuestConfiguration/guestConfigurationAssignments/{guestConfigurationAssignmentName}
        /// Operation Id: GuestConfigurationAssignments_CreateOrUpdate
        /// </summary>
        /// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
        /// <param name="data"> Parameters supplied to the create or update guest configuration assignment. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="data"/> is null. </exception>
        public virtual async Task<ArmOperation<GuestConfigurationVmAssignmentResource>> UpdateAsync(WaitUntil waitUntil, GuestConfigurationAssignmentData data, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(data, nameof(data));

            using var scope = _guestConfigurationVmAssignmentGuestConfigurationAssignmentsClientDiagnostics.CreateScope("GuestConfigurationVmAssignmentResource.Update");
            scope.Start();
            try
            {
                var response = await _guestConfigurationVmAssignmentGuestConfigurationAssignmentsRestClient.CreateOrUpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, data, cancellationToken).ConfigureAwait(false);
                var operation = new GuestConfigurationArmOperation<GuestConfigurationVmAssignmentResource>(Response.FromValue(new GuestConfigurationVmAssignmentResource(Client, response), response.GetRawResponse()));
                if (waitUntil == WaitUntil.Completed)
                    await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false);
                return operation;
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Creates an association between a VM and guest configuration
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/providers/Microsoft.GuestConfiguration/guestConfigurationAssignments/{guestConfigurationAssignmentName}
        /// Operation Id: GuestConfigurationAssignments_CreateOrUpdate
        /// </summary>
        /// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
        /// <param name="data"> Parameters supplied to the create or update guest configuration assignment. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="data"/> is null. </exception>
        public virtual ArmOperation<GuestConfigurationVmAssignmentResource> Update(WaitUntil waitUntil, GuestConfigurationAssignmentData data, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(data, nameof(data));

            using var scope = _guestConfigurationVmAssignmentGuestConfigurationAssignmentsClientDiagnostics.CreateScope("GuestConfigurationVmAssignmentResource.Update");
            scope.Start();
            try
            {
                var response = _guestConfigurationVmAssignmentGuestConfigurationAssignmentsRestClient.CreateOrUpdate(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, data, cancellationToken);
                var operation = new GuestConfigurationArmOperation<GuestConfigurationVmAssignmentResource>(Response.FromValue(new GuestConfigurationVmAssignmentResource(Client, response), response.GetRawResponse()));
                if (waitUntil == WaitUntil.Completed)
                    operation.WaitForCompletion(cancellationToken);
                return operation;
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// List all reports for the guest configuration assignment, latest report first.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/providers/Microsoft.GuestConfiguration/guestConfigurationAssignments/{guestConfigurationAssignmentName}/reports
        /// Operation Id: GuestConfigurationAssignmentReports_List
        /// </summary>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <returns> An async collection of <see cref="GuestConfigurationAssignmentReport" /> that may take multiple service requests to iterate over. </returns>
        public virtual AsyncPageable<GuestConfigurationAssignmentReport> GetReportsAsync(CancellationToken cancellationToken = default)
        {
            async Task<Page<GuestConfigurationAssignmentReport>> FirstPageFunc(int? pageSizeHint)
            {
                using var scope = _guestConfigurationAssignmentReportsClientDiagnostics.CreateScope("GuestConfigurationVmAssignmentResource.GetReports");
                scope.Start();
                try
                {
                    var response = await _guestConfigurationAssignmentReportsRestClient.ListAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken: cancellationToken).ConfigureAwait(false);
                    return Page.FromValues(response.Value.Value, null, response.GetRawResponse());
                }
                catch (Exception e)
                {
                    scope.Failed(e);
                    throw;
                }
            }
            return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, null);
        }

        /// <summary>
        /// List all reports for the guest configuration assignment, latest report first.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/providers/Microsoft.GuestConfiguration/guestConfigurationAssignments/{guestConfigurationAssignmentName}/reports
        /// Operation Id: GuestConfigurationAssignmentReports_List
        /// </summary>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <returns> A collection of <see cref="GuestConfigurationAssignmentReport" /> that may take multiple service requests to iterate over. </returns>
        public virtual Pageable<GuestConfigurationAssignmentReport> GetReports(CancellationToken cancellationToken = default)
        {
            Page<GuestConfigurationAssignmentReport> FirstPageFunc(int? pageSizeHint)
            {
                using var scope = _guestConfigurationAssignmentReportsClientDiagnostics.CreateScope("GuestConfigurationVmAssignmentResource.GetReports");
                scope.Start();
                try
                {
                    var response = _guestConfigurationAssignmentReportsRestClient.List(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken: cancellationToken);
                    return Page.FromValues(response.Value.Value, null, response.GetRawResponse());
                }
                catch (Exception e)
                {
                    scope.Failed(e);
                    throw;
                }
            }
            return PageableHelpers.CreateEnumerable(FirstPageFunc, null);
        }

        /// <summary>
        /// Get a report for the guest configuration assignment, by reportId.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/providers/Microsoft.GuestConfiguration/guestConfigurationAssignments/{guestConfigurationAssignmentName}/reports/{reportId}
        /// Operation Id: GuestConfigurationAssignmentReports_Get
        /// </summary>
        /// <param name="reportId"> The GUID for the guest configuration assignment report. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentException"> <paramref name="reportId"/> is an empty string, and was expected to be non-empty. </exception>
        /// <exception cref="ArgumentNullException"> <paramref name="reportId"/> is null. </exception>
        public virtual async Task<Response<GuestConfigurationAssignmentReport>> GetReportAsync(string reportId, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(reportId, nameof(reportId));

            using var scope = _guestConfigurationAssignmentReportsClientDiagnostics.CreateScope("GuestConfigurationVmAssignmentResource.GetReport");
            scope.Start();
            try
            {
                var response = await _guestConfigurationAssignmentReportsRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, reportId, cancellationToken).ConfigureAwait(false);
                return response;
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Get a report for the guest configuration assignment, by reportId.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/providers/Microsoft.GuestConfiguration/guestConfigurationAssignments/{guestConfigurationAssignmentName}/reports/{reportId}
        /// Operation Id: GuestConfigurationAssignmentReports_Get
        /// </summary>
        /// <param name="reportId"> The GUID for the guest configuration assignment report. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentException"> <paramref name="reportId"/> is an empty string, and was expected to be non-empty. </exception>
        /// <exception cref="ArgumentNullException"> <paramref name="reportId"/> is null. </exception>
        public virtual Response<GuestConfigurationAssignmentReport> GetReport(string reportId, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNullOrEmpty(reportId, nameof(reportId));

            using var scope = _guestConfigurationAssignmentReportsClientDiagnostics.CreateScope("GuestConfigurationVmAssignmentResource.GetReport");
            scope.Start();
            try
            {
                var response = _guestConfigurationAssignmentReportsRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, reportId, cancellationToken);
                return response;
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }
    }
}


text:
% runSaliency - compute and display saliency map and fixations.
%
% runSaliency(inputImage,saliencyParams)
%    Runs a demonstration of the entire process of computing
%    the saliency map, winner-take-all evolution with
%    inhibition of return, shape estimation, and fixation
%    to the attended region.
%       inputImage: the file name of the image,
%                   or the image data themselves,
%                   or an initialized Image structure (see initializeImage);
%       saliencyParams: the saliency parameter set for the operations.
%
% runSaliency(inputImage)
%    Uses defaultSaliencyParams as parameters.
%
% See also guiSaliency, batchSaliency, initializeGlobal, initializeImage,
%          makeSaliencyMap, initializeWTA, evolveWTA, applyIOR, estimateShape,
%          dataStructures, defaultSaliencyParams.

% This file is part of the SaliencyToolbox - Copyright (C) 2006-2013
% by Dirk B. Walther and the California Institute of Technology.
% See the enclosed LICENSE.TXT document for the license agreement.
% More information about this project is available at:
% http://www.saliencytoolbox.net

function runSaliency(inputImage,varargin)

declareGlobal;

% initialize the Image structure if necessary
if (isa(inputImage,'struct'))
  img = inputImage;
else
  img = initializeImage(inputImage);
end

% check that image isn't too huge
img = checkImageSize(img,'Prompt');

% use the default saliency parameters if the user didn't specify any
if isempty(varargin)
  params = defaultSaliencyParams(img.size,'dyadic');
else
  params = varargin{1};
end

% make sure that we don't use color features if we don't have a color image
if (img.dims == 2)
  params = removeColorFeatures(params);
end

% create the saliency map
[salmap,salData] = makeSaliencyMap(img,params);

% display the conspicuity maps
figure('Name','STB: conspicuity maps','NumberTitle','off');
displayMaps({salData.CM},2);

% initialize the winner-take-all network
wta = initializeWTA(salmap,params);

% display the input image
imgFig = showImage(img);

% display the current WTA
salFig = figure('Name','STB: Saliency Map and WTA','NumberTitle','off');
wtaMap = emptyMap(img.size(1:2),'Winner Take All');
wtaMap.data = imresize(wta.sm.V,img.size(1:2),'bilinear');
displayMaps([salmap,wtaMap],1);

shapeFig = -1;
lastWinner = [-1,-1];
reply = '';

% loop over the successive fixations, until user enters 'q' or 'Q'
while (~strcmp(reply,'q') & ~strcmp(reply,'Q'))
  winner = [-1,-1];

  % evolve WTA until we have a winner
  while (winner(1) == -1)
    [wta,winner] = evolveWTA(wta);
  end

  % update the WTA plot
  figure(salFig);
  wtaMap = emptyMap(img.size(1:2),'Winner Take All');
  wtaMap.data = imresize(wta.sm.V,img.size(1:2),'bilinear');
  displayMaps([salmap,wtaMap],1);

  % run the shape estimator to get proro-objects
  shapeData = estimateShape(salmap,salData,winner,params);

  % trigger inhibition of return
  wta = applyIOR(wta,winner,params,shapeData);

  % convert the winner's location to image coordinates
  win2 = winnerToImgCoords(winner,params);

  % plot the currently attended region into the image figure
  figure(imgFig);
  plotSalientLocation(win2,lastWinner,img,params,shapeData);

  lastWinner = win2;

  % in case we have shape data, create a plot
  % to display various processing steps
  if ~isempty(shapeData)

    % need to open a new figure or use the previous one?
    if (shapeFig == -1)
      shapeFig = figure('Name','STB: shape maps','NumberTitle','off');
    else
      figure(shapeFig);
    end

    % draw the various maps
    displayMaps({shapeData.winningMap,shapeData.segmentedMap,...
                 shapeData.binaryMap,shapeData.shapeMap});

    % find the right label for the figure window
    winLabel = [' - ' shapeData.winningMap.label];
    if any(isnan(img.filename))
      lab = winLabel;
    else
      lab = [img.filename winLabel];
    end
    set(imgFig,'Name',lab);
  else
    winLabel = '';
  end

  % make sure everything gets drawn
  drawnow;

  % write out the details for our winner
  txt = sprintf('winner: %i,%i; t = %4.1f ms%s',...
                win2(2),win2(1),wta.exc.time*1000,winLabel);

  % wait for user input - return for next fixation, 'q' to terminate
  reply = input(txt,'s');
end


text: select top(100) * from [dbo].[gunter_example] order by 1 desc


text:
using namespace std;

class computerPlayer : public Player
{

public:
  computerPlayer();
  virtual houseContainer* chooseHouse();

private:
  std::minstd_rand generator;

};

#endif


text:
import numpy as np
import re
import collections as coll
import itertools as it
import javabridge as jv
import bioformats as bf
from xml import etree as et

VM_STARTED = False
VM_KILLED = False
DEFAULT_DIM_ORDER = 'tzyxc'

BF2NP_DTYPE = {
    0: np.int8,
    1: np.uint8,
    2: np.int16,
    3: np.uint16,
    4: np.int32,
    5: np.uint32,
    6: np.float32,
    7: np.double
}

def start(max_heap_size='8G'):
    """Start the Java Virtual Machine, enabling bioformats IO.

    Parameters
    ----------
    max_heap_size : string, optional
        The maximum memory usage by the virtual machine. Valid strings
        include '256M', '64k', and '2G'. Expect to need a lot.
    """
    jv.start_vm(class_path=bf.JARS, max_heap_size=max_heap_size)
    global VM_STARTED
    VM_STARTED = True

def done():
    """Kill the JVM. Once killed, it cannot be restarted.

    Notes
    -----
    See the python-javabridge documentation for more information.
    """
    jv.kill_vm()
    global VM_KILLED
    VM_KILLED = True

def lif_metadata_string_size(filename):
    """Get the length in bytes of the metadata string of a LIF file.

    Parameters
    ----------
    filename : string
        Path to the LIF file.

    Returns
    -------
    length : int
        The length in bytes of the metadata string.

    Notes
    -----
    This is based on code by Lee Kamentsky. [1]

    References
    ----------
    [1] https://github.com/CellProfiler/python-bioformats/issues/8
    """
    with open(filename, 'rb') as fd:
        fd.read(9)
        length = np.frombuffer(fd.read(4), "<i4")[0]
        return length

def parse_xml_metadata(xml_string, array_order=DEFAULT_DIM_ORDER):
    """Get interesting metadata from the LIF file XML string.

    Parameters
    ----------
    xml_string : string
        The string containing the XML data.
    array_order : string
        The order of the dimensions in the multidimensional array.
        Valid orders are a permutation of "tzyxc" for time, the three
        spatial dimensions, and channels.

    Returns
    -------
    names : list of string
        The name of each image series.
    sizes : list of tuple of int
        The pixel size in the specified order of each series.
    resolutions : list of tuple of float
        The resolution of each series in the order given by
        `array_order`. Time and channel dimensions are ignored.
    """
    array_order = array_order.upper()
    names, sizes, resolutions = [], [], []
    spatial_array_order = [c for c in array_order if c in 'XYZ']
    size_tags = ['Size' + c for c in array_order]
    res_tags = ['PhysicalSize' + c for c in spatial_array_order]
    metadata_root = et.ElementTree.fromstring(xml_string)
    for child in metadata_root:
        if child.tag.endswith('Image'):
            names.append(child.attrib['Name'])
            for grandchild in child:
                if grandchild.tag.endswith('Pixels'):
                    att = grandchild.attrib
                    sizes.append(tuple([int(att[t]) for t in size_tags]))
                    resolutions.append(tuple([float(att[t])
                                              for t in res_tags]))
    return names, sizes, resolutions

def metadata(filename, array_order=DEFAULT_DIM_ORDER):
    """Get metadata from a BioFormats file.

    Parameters
    ----------
    filename : string
        The path to a BioFormats File.
    array_order : string
        The order of the dimensions in the multidimensional array.
        Valid orders are a permutation of "tzyxc" for time, the three
        spatial dimensions, and channels.

    Returns
    -------
    names : list of string
        The name of each image series.
    sizes : list of tuple of int
        The pixel size in the specified order of each series.
    resolutions : list of tuple of float
        The resolution of each series in the order given by
        `array_order`. Time and channel dimensions are ignored.
    """
    if not VM_STARTED:
        start()
    if VM_KILLED:
        raise RuntimeError("The Java Virtual Machine has already been "
                           "killed, and cannot be restarted. See the "
                           "python-javabridge documentation for more "
                           "information. You must restart your program "
                           "and try again.")
    md_string = bf.get_omexml_metadata(filename)
    return parse_xml_metadata(md_string, array_order)

def parse_series_name(name, interval=0.5):
    """Get series information (time points, embryo) from the name.

    Parameters
    ----------
    name : string
        The name of the image series.
    interval : float, optional
        The time interval between timepoints.

    Returns
    -------
    embryo : int
        The embryo ID / position number on the slide.
    times : array of float
        The timepoint corresponding to each image.

    Notes
    -----
    A "Pre" tag in the name is interpreted as ``t = -1``. A "Mark" tag
    is interpreted as ``t = -2``.

    Examples
    --------
    >>> name0 = "Pre lesion 2x/Pos008_S001"
    >>> e0, t0 = parse_series_name(name0)
    >>> e0, t0[:5]
    (8, array([-1.]))
    >>> name1 = "Mark_and_Find_001/Pos019_S001"
    >>> e1, t1 = parse_series_name(name1)
    >>> e1, t1[:5]
    (19, array([-2.]))
    >>> name2 = "22.5h to 41h pSCI/Pos013_S001"
    >>> e2, t2 = parse_series_name(name2)
    >>> e2, t2[:5]
    (13, array([ 22.5,  23. ,  23.5,  24. ,  24.5]))
    >>> name3 = "63 to 72.5hpSCI/Pos004_S001"
    >>> e3, t3 = parse_series_name(name3, interval=1)
    >>> e3, t3[:5]
    (4, array([ 63.,  64.,  65.,  66.,  67.]))
    """
    re_pre = r"Pre.*/Pos(\d+)_.*"
    re_mark = r"Mark.*/Pos(\d+)_.*"
    re_time = r"(\d+(\.\d+)?)h? to (\d+(\.\d+)?) ?h.*/Pos(\d+)_.*"
    m_pre = re.match(re_pre, name)
    m_mark = re.match(re_mark, name)
    m_time = re.match(re_time, name)
    if m_pre:
        return int(m_pre.groups()[0]), np.array([-1.])
    elif m_mark:
        return int(m_mark.groups()[0]), np.array([-2.])
    elif m_time:
        g = m_time.groups()
        t0 = float(g[0])
        t1 = float(g[2])
        embryo = int(g[4])
        times = np.arange(t0, t1 + float(interval)/2, interval)
        return embryo, times
    else:
        raise ValueError("Could not parse name string: %s" % name)

def image_reader(filelike):
    """Return a BioFormats ``ImageReader`` object from filelike.

    Parameters
    ----------
    filelike : string or bf.ImageReader
        If string, open the corresponding ImageReader. If ImageReader,
        this function is a no-op.

    Returns
    -------
    rdr : bf.ImageReader
        The relevant reader.

    Notes
    -----
    The purpose of this function is to provide a *robust* way to open
    a BioFormats file --- without having to start the JVM manually.
    """
    if not VM_STARTED:
        start()
    if VM_KILLED:
        raise RuntimeError("The Java Virtual Machine has already been "
                           "killed, and cannot be restarted. See the "
                           "python-javabridge documentation for more "
                           "information. You must restart your program "
                           "and try again.")
    if isinstance(filelike, bf.ImageReader):
        rdr = filelike
    else:
        rdr = bf.ImageReader(filelike)
    return rdr

def read_image_series(filelike, series_id=0, t=None, z=None, c=None,
                      desired_order=None):
    """Read an image volume from a file.

    Parameters
    ----------
    filelike : string or bf.ImageReader
        Either a filename containing a BioFormats image, or a
        `bioformats.ImageReader`.
    series_id : int, optional
        Load this series from the image file.
    t : int or list of int, optional
        Load this/these timepoint/s only from the image file. If
        `None`, load all timepoints.
    z : int or list of int, optional
        Load this/these z-plane/s only from the image file. If `None`,
        load all planes.
    c : int or list of int, optional
        Load this/these channel/s only from the image file. If `None`,
        load all channels.
    desired_order : string, optional
        Store the image dimensions in this order, such as "TZCYX". By
        default, the order will be the exact inverse of the image's
        native order, since (Leica) files use Fortran order, while
        NumPy uses C order.

    Returns
    -------
    image : numpy ndarray, 5 dimensions
        The read image.
    """
    rdr = image_reader(filelike)
    reader = rdr.rdr
    total_series = reader.getSeriesCount()
    if not 0 <= series_id < total_series:
        raise ValueError("Series ID %i is not between 0 and the total "
                         "number of series, %i." % (series_id, total_series))
    reader.setSeries(series_id)
    order = reader.getDimensionOrder()
    # we invert the shape because numpy uses C order and (most?) BF images use
    # Fortran order
    old_shape = [getattr(reader, "getSize" + s)() for s in order]
    czt_list, old_shape = _sanitize_czt(c, z, t, old_shape, order)
    if desired_order is not None:
        desired_order = desired_order.upper()
        transposition = _get_ordering(order, desired_order)
        new_shape = [old_shape[i] for i in transposition]
    else:
        new_shape = old_shape[::-1]
        desired_order = order[::-1]
    image = np.empty(new_shape, dtype=BF2NP_DTYPE[reader.getPixelType()])
    for c, z, t in czt_list:
        indices = []
        for d in desired_order:
            if d == 'C':
                indices.append(c)
            elif d == 'Z':
                indices.append(z)
            elif d == 'T':
                indices.append(t)
            else:
                indices.append(slice(None))
        image[indices] = rdr.read(z=z, t=t, c=c, series=series_id,
                                  rescale=False)
    return image

def series_iterator(filelike, series=None, **kwargs):
    """Iterate over all the series in a file.

    Parameters
    ----------
    filelike : string or bf.ImageReader
        The input file.
    series : iterable of int, optional
        Limit the iteration to the specified series.
    **kwargs : keyword arguments, optional
        Keyword arguments to be passed on to `read_image_series`.

    Returns
    -------
    seit : iterator
        Iterator over all series in `filelike`.
    """
    rdr = image_reader(filelike)
    if series is None:
        series = range(rdr.rdr.getSeriesCount())
    for series_id in series:
        yield read_image_series(rdr, series_id, **kwargs)

def _get_ordering(actual, desired):
    """Find an ordering of indices so that desired[i] == actual[ordering[i]].

    Parameters
    ----------
    actual, desired : string, same length
        Two strings differring only in the permutation of their characters.

    Returns
    -------
    ordering : list of int
        A list of indices into `actual` such that
        ``desired[i] == actual[ordering[i]]``.

    Examples
    --------
    >>> actual = "XYCZT"
    >>> desired = "TZYXC"
    >>> _get_ordering(actual, desired)
    [4, 3, 1, 0, 2]
    """
    ordering = []
    for elem in desired:
        ordering.append(actual.find(elem))
    return ordering

def _sanitize_czt(c, z, t, shape, order):
    """Ensure cs, zs, and ts are lists, and the correct shape is returned.

    Parameters
    ----------
    c, z, t : int, list of int, or None
        The desired c, z, and t values for the image. `None` means all values
        are desired.
    shape : list of int
        The shape of the final image. *Will be edited in-place.*
    order : string
        The order of the dimensions in the file being read.

    Returns
    -------
    czt_list : list of (c, z, t) tuple
        A list of tuples to read in sequentially from the file.
    shape : list of int
        The shape of the final image, taking into account the subset of c, z,
        and t that will be read in.
    """
    out = {}
    for dim, label in zip((c, z, t), ('C', 'Z', 'T')):
        dim_idx = order.find(label)
        if dim is None:
            out[label] = range(shape[dim_idx])
        else:
            if not isinstance(dim, coll.Iterable):
                out[label] = [dim]
            shape[dim_idx] = len(out[label])
    czt_order = filter(lambda x: x in 'CZT', order)
    c, z, t = _get_ordering(czt_order, 'CZT')
    czt_list = [(tup[c], tup[z], tup[t])
                for tup in it.product(*[out[char] for char in czt_order])]
    return czt_list, shape


text:
from polymorphic.manager import PolymorphicManager

class PaymentManager(PolymorphicManager):
    def get_queryset(self):
        return super(PaymentManager, self).get_queryset()


text:
console.log("\nThese are the 6 falsey statements: null, NaN, 0, undefined, \"\" and false\n");

var myArray = [5, "1", null, NaN, 0, undefined, "", false, "0"];

for(var index = 0; index < myArray.length; index++) {
    console.log("\n" + myArray[index] + " is truthy (Boolean): " + Boolean(myArray[index]));
    console.log("\n" + myArray[index] + " is truthy (===): " + (myArray[index] === true));
    console.log("\n" + myArray[index] + " is truth (==): " + (myArray[index] == true));
}


text:
.container {
    display: grid;
    grid-gap: 5px;
    grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));

    /* This means automatically created rows will be a minimum of 100 pixels tall,
     * and a maximum of auto. Using auto means that the size will look at the content size
     * and will stretch to give space for the tallest item in a cell, in this row.
     */
    grid-auto-rows: minmax(100px, auto);
    grid-auto-flow: dense;
}

.horizontal {
    grid-column: span 3;
}

.vertical {
    grid-row: span 3;
}

.big {
    grid-column: span 3;
    grid-row: span 3;
}


text:
package smtpd

import (
	"bufio"
	"bytes"
	"crypto/tls"
	"io"
	"io/ioutil"
	"net/textproto"
	"strconv"
	"strings"
	"time"
)

func (c *Connection) handleHELO(cmd *command) {
	if len(cmd.Fields) < 2 {
		c.reply(502, "Missing parameter")
		return
	}

	if c.HeloName != "" {
		// Reset the state if there's a duplicate helo
		c.reset()
	}

	// Checking HELO and denying connections depending on it is forbidden
	// in RFC1123
	c.HeloName = cmd.Fields[1]
	c.Protocol = SMTP
	c.reply(250, "Go ahead.")

	return
}

func (c *Connection) handleEHLO(cmd *command) {
	if len(cmd.Fields) < 2 {
		c.reply(502, "Missing parameter")
		return
	}

	if c.HeloName != "" {
		// Same as above
		c.reset()
	}

	c.HeloName = cmd.Fields[1]
	c.Protocol = ESMTP

	// First line is the hostname
	c.writer.WriteString("250-" + c.Server.Hostname + "\r\n")

	// Can we send STARTTLS?
	if c.Server.TLSConfig != nil && c.TLS == nil {
		// Send all extensions in server's extensions list
		for _, extension := range c.Server.extensions {
			c.writer.WriteString("250-" + extension + "\r\n")
		}

		// And send STARTTLS without a dash
		if c.Server.TLSConfig != nil && c.TLS == nil {
			c.reply(250, "STARTTLS")
		}
	} else {
		// Send all extensions except the last one
		for _, extension := range c.Server.extensions[:len(c.Server.extensions)-1] {
			c.writer.WriteString("250-" + extension + "\r\n")
		}
		// Send the last one seperately, without a dash
		c.reply(250, c.Server.extensions[len(c.Server.extensions)-1])
	}

	return
}

func (c *Connection) handleMAIL(cmd *command) {
	if c.HeloName == "" {
		c.reply(502, "Please introduce yourself first.")
		return
	}

	if c.TLS == nil && c.Server.ForceTLS {
		c.reply(502, "Please turn on TLS by using STARTTLS to proceed.")
		return
	}

	if len(cmd.Fields) < 2 {
		c.reply(502, "Missing parameter.")
		return
	}

	// Parse the first field
	params := strings.Split(cmd.Fields[1], ":")
	if len(params) < 2 {
		c.reply(502, "Invalid second parameter.")
		return
	}

	if c.Envelope != nil {
		c.reply(502, "Duplicate MAIL. Please reset the envelope.")
		return
	}

	// Parse the address
	address, err := parseAddress(params[1])
	if err != nil {
		c.reply(502, err.Error())
		return
	}

	// Execute the sender checking chain
	oh := func(_ *Connection) {
		c.Envelope = &Envelope{
			Sender:     address,
			Recipients: []string{},
		}

		c.reply(250, "Go ahead.")
	}

	for _, ha := range c.Server.SenderChain {
		oh = ha.HandleSender(oh)
	}

	oh(c)

	return
}

func (c *Connection) handleRCPT(cmd *command) {
	if c.Envelope == nil {
		c.reply(502, "Missing MAIL FROM command.")
		return
	}

	if len(c.Envelope.Recipients) >= c.Server.MaxRecipients {
		c.reply(452, "Too many recipients")
		return
	}

	if len(cmd.Fields) < 2 {
		c.reply(502, "Missing parameter.")
		return
	}

	// Parse the first field
	params := strings.Split(cmd.Fields[1], ":")
	if len(params) < 2 {
		c.reply(502, "Invalid second parameter.")
		return
	}

	// Parse the address
	address, err := parseAddress(params[1])
	if err != nil {
		c.reply(502, err.Error())
		return
	}

	// Add it to the recipients list
	c.Envelope.Recipients = append(c.Envelope.Recipients, address)

	// Execute the recipient checking chain
	oh := func(_ *Connection) {
		c.reply(250, "Go ahead.")
	}

	for _, ha := range c.Server.RecipientChain {
		oh = ha.HandleRecipient(oh)
	}

	oh(c)

	return
}

func (c *Connection) handleSTARTTLS(cmd *command) {
	if c.TLS != nil {
		c.reply(502, "Already running in TLS")
		return
	}

	if c.Server.TLSConfig == nil {
		c.reply(502, "TLS not supported")
		return
	}

	tlsConn := tls.Server(c.conn, c.Server.TLSConfig)
	c.reply(220, "Go ahead")

	// Perform a handshake
	if err := tlsConn.Handshake(); err != nil {
		c.reply(550, "Handshake error")
		return
	}

	// Reset envelope, new EHLO/HELO is required after STARTTLS
	c.reset()

	// Reset deadlines on the old connection - zero it out
	c.conn.SetDeadline(time.Time{})

	// Replace connection with a TLS connection
	c.conn = tlsConn
	c.reader = bufio.NewReader(c.conn)
	c.writer = bufio.NewWriter(c.conn)
	c.scanner = bufio.NewScanner(c.reader)

	state := tlsConn.ConnectionState()
	c.TLS = &state

	// Flush the connection to set up new timeout deadlines
	c.flush()

	return
}

func (c *Connection) handleDATA(cmd *command) {
	if c.Envelope == nil || len(c.Envelope.Recipients) == 0 {
		c.reply(502, "Missing RCPT TO command.")
		return
	}

	c.reply(354, "Go ahead. End your data with <CR><LF>.<CR><LF>")
	c.conn.SetDeadline(time.Now().Add(c.Server.DataTimeout))

	data := &bytes.Buffer{}
	reader := textproto.NewReader(c.reader).DotReader()

	_, err := io.CopyN(data, reader, int64(c.Server.MaxMessageSize))

	if err == io.EOF {
		// Message was smaller than MaxMessageSize - deliver the message
		c.Envelope.Data = data.Bytes()

		// Execute the delivery chain
		oh := func(_ *Connection) {
			c.reply(250, "Thank you.")
			c.reset()
		}

		for _, ha := range c.Server.DeliveryChain {
			oh = ha.HandleDelivery(oh)
		}

		oh(c)
	}

	if err != nil {
		// Network error, ignore
		return
	}

	// Discard the rest and report an error.
	io.Copy(ioutil.Discard, reader)
	c.reply(552, "Message exceeded max message size of "+strconv.Itoa(c.Server.MaxMessageSize)+" bytes.")
	c.reset()
	return
}

func (c *Connection) handleRSET(cmd *command) {
	c.reset()
	c.reply(250, "Go ahead.")
	return
}

func (c *Connection) handleNOOP(cmd *command) {
	c.reply(250, "Go ahead")
	return
}

func (c *Connection) handleQUIT(cmd *command) {
	c.reply(221, "OK, bye")
	c.close()
	return
}


text:
require 'pdf_forms'

module IRSForms
  class BaseForm
    class << self
      def fields
        @fields ||= {}
      end
    end

    extend(IRSForms::FormField)

    def to_pdf(path = nil)
      pdftk = EnhancedPdftkWrapper.new(pdftk_path)
      pdftk.fill_form template_file, path, collect_data
    end

    def collect_data
      data = {}
      self.class.fields.each do |field_name, pdf_field_editor|
        collected_data = pdf_field_editor.collect_data(instance_variable_get( "@#{field_name}" ))
        data.merge! collected_data unless collected_data.nil?
      end

      data
    end

    private
    def pdftk_path
      # '/usr/local/bin/pdftk'
      @pdftk_path ||= (defined?(Bundler::GemfileError) && File.exists?('Gemfile') ? `bundle exec which pdftk` : `which pdftk`).chomp
    end
  end
end


text:
For noun (plural to singular and singular to plural), verb (gerund, present & past) and adjective (comparative, superlative) transformations.

![npm](https://img.shields.io/npm/dm/en-inflectors.svg)
![npm](https://img.shields.io/npm/v/en-inflectors.svg)
![license](https://img.shields.io/github/license/FinNLP/en-inflectors.svg)
![David](https://img.shields.io/david/FinNLP/en-inflectors.svg)

## Demo
Here's a quick demo: [http://en-inflectors.surge.sh/](http://en-inflectors.surge.sh/)

## Installation

```
npm install en-inflectors --save
```

## Usage

*  **Import the library**
```javascript
// javascript
const Inflectors = require("en-inflectors").Inflectors;
```
```typescript
// typescript
import { Inflectors } from "en-inflectors";
```

* **Instantiate the class**
```javascript
let instance = new Inflectors("book");
```

* **Adjective Inflection**
```javascript
let instance = new Inflectors("big");
instance.comparative(); // bigger
instance.superlative(); // biggest
```

* **Verb Conjugation**
```javascript
new Inflectors("rallied").conjugate("VBP"); // rally
new Inflectors("fly").conjugate("VBD"); // flew
new Inflectors("throw").conjugate("VBN"); // thrown
new Inflectors("rally").conjugate("VBS"); // rallies
new Inflectors("die").conjugate("VBP"); // dying

// or you can use the aliases
new Inflectors("rallied").toPresent(); // rally
new Inflectors("fly").toPast(); // flew
new Inflectors("throw").toPastParticiple(); // thrown
new Inflectors("rally").toPresentS(); // rallies
new Inflectors("die").toGerund(); // dying
```

* **Noun Inflection**
```javascript
const instanceA = new Inflectors("bus");
const instanceB = new Inflectors("ellipses");
const instanceC = new Inflectors("money");

instanceA.isCountable(); // true
instanceB.isCountable(); // true
instanceC.isCountable(); // false

instanceA.isNotCountable(); // false
instanceB.isNotCountable(); // false
instanceC.isNotCountable(); // true

instanceA.isSingular(); // true
instanceB.isSingular(); // false
instanceC.isSingular(); // true

instanceA.isPlural(); // false
instanceB.isPlural(); // true
instanceC.isPlural(); // true

// note that uncountable words return true
// on both plural and singular checks

instanceA.toSingular(); // bus (no change)
instanceB.toSingular(); // ellipsis
instanceC.toSingular(); // money (no change)

instanceA.toPlural(); // buses
instanceB.toPlural(); // ellipses (no change)
instanceC.toPlural(); // money (no change)

```

## How does it work

* **Adjective inflection**
	1. Checks against a dictionary of known irregularities (e.g. little/less/least)
	2. Applies inflection based on:
		* Number of syllables
		* word ending

* **Noun inflection**
	1. Dictionary lookup (known irregularities e.g. octopus/octopi & uncountable words)
	2. Identifies whether the word is plural or singular based on:
		* Dictionary
		* Machine learned regular expressions
	3. Applies transformation based on ending and word pattern (vowels, consonants and word endings)

* **Verb conjugation**
	1. Dictionary lookup (known irregularities + 4000 common verbs)
	2. If the passed verb is identified as infinitive, it then applies regular expression transformations that are based on word endings, vowels and consonant phonetics.
	3. Tries to trim character from the beginning of the verb, thus solving prefixes (e.g. undergoes, overthrown)
	4. Tries to stem the word and get the infinitive form, then apply regular expression transformations.
	5. Applies regular expressions.

## How accurate is it?

First of all, unless you have a dictionary of all the words and verbs that exist in English, you can't really write a regular expression or an algorithm and expect to have a 100% success rate. English has been adopting words from a lot of different languages (French, Greek and Latin for example), and each one of these languages has its own rules of pluralization and singularization, let alone verb conjugation.

Even with dictionaries you'll have the problem of complex and made up words like `maskedlocation`, and you might have to add dictionaries for specialties (like medicine which does actually have its own dictionary).

However, I think what you'll find in this library is what can be achieved with the least amount of compromise.

I've used a set of rules (for detection/transformation) in combination with an exceptions list.

However, testing the library was more challenging than anticipated. If you have any case inaccuracy or false positives **please** submit an issue.

And of course, You can clone this repository, install `mocha` and test it for yourself, and you'll see how it passes the **9900** tests successfully.

## License

License: The MIT License (MIT) - Copyright (c) 2017 Alex Corvi


text:
package net.engin33r.luaspigot.lua.annotation;

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

import static java.lang.annotation.ElementType.TYPE;

/**
 * Annotation for quick registration of linked field mutators (setters).
 */
@Target(value=TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface LinkedFieldInterfaceDefinition {
    String value();
}


text:
package fabenc_test

import (
	"bytes"
	"fmt"
	"runtime"
	"strconv"
	"sync"
	"testing"
	"time"

	"github.com/hyperledger/fabric/common/flogging/fabenc"
	"github.com/stretchr/testify/assert"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

func TestParseFormat(t *testing.T) {
	var tests = []struct {
		desc       string
		spec       string
		formatters []fabenc.Formatter
	}{
		{
			desc:       "empty spec",
			spec:       "",
			formatters: []fabenc.Formatter{},
		},
		{
			desc: "simple verb",
			spec: "%{color}",
			formatters: []fabenc.Formatter{
				fabenc.ColorFormatter{},
			},
		},
		{
			desc: "with prefix",
			spec: "prefix %{color}",
			formatters: []fabenc.Formatter{
				fabenc.StringFormatter{Value: "prefix "},
				fabenc.ColorFormatter{},
			},
		},
		{
			desc: "with suffix",
			spec: "%{color} suffix",
			formatters: []fabenc.Formatter{
				fabenc.ColorFormatter{},
				fabenc.StringFormatter{Value: " suffix"}},
		},
		{
			desc: "with prefix and suffix",
			spec: "prefix %{color} suffix",
			formatters: []fabenc.Formatter{
				fabenc.StringFormatter{Value: "prefix "},
				fabenc.ColorFormatter{},
				fabenc.StringFormatter{Value: " suffix"},
			},
		},
		{
			desc: "with format",
			spec: "%{level:.4s} suffix",
			formatters: []fabenc.Formatter{
				fabenc.LevelFormatter{FormatVerb: "%.4s"},
				fabenc.StringFormatter{Value: " suffix"},
			},
		},
	}

	for _, tc := range tests {
		t.Run(fmt.Sprintf(tc.desc), func(t *testing.T) {
			formatters, err := fabenc.ParseFormat(tc.spec)
			assert.NoError(t, err)
			assert.Equal(t, tc.formatters, formatters)
		})
	}
}

func TestParseFormatError(t *testing.T) {
	_, err := fabenc.ParseFormat("%{color:bad}")
	assert.EqualError(t, err, "invalid color option: bad")
}

func TestNewFormatter(t *testing.T) {
	var tests = []struct {
		verb      string
		format    string
		formatter fabenc.Formatter
		errorMsg  string
	}{
		{verb: "color", format: "", formatter: fabenc.ColorFormatter{}},
		{verb: "color", format: "bold", formatter: fabenc.ColorFormatter{Bold: true}},
		{verb: "color", format: "reset", formatter: fabenc.ColorFormatter{Reset: true}},
		{verb: "color", format: "unknown", errorMsg: "invalid color option: unknown"},
		{verb: "id", format: "", formatter: fabenc.SequenceFormatter{FormatVerb: "%d"}},
		{verb: "id", format: "04x", formatter: fabenc.SequenceFormatter{FormatVerb: "%04x"}},
		{verb: "level", format: "", formatter: fabenc.LevelFormatter{FormatVerb: "%s"}},
		{verb: "level", format: ".4s", formatter: fabenc.LevelFormatter{FormatVerb: "%.4s"}},
		{verb: "message", format: "", formatter: fabenc.MessageFormatter{FormatVerb: "%s"}},
		{verb: "message", format: "#30s", formatter: fabenc.MessageFormatter{FormatVerb: "%#30s"}},
		{verb: "module", format: "", formatter: fabenc.ModuleFormatter{FormatVerb: "%s"}},
		{verb: "module", format: "ok", formatter: fabenc.ModuleFormatter{FormatVerb: "%ok"}},
		{verb: "shortfunc", format: "", formatter: fabenc.ShortFuncFormatter{FormatVerb: "%s"}},
		{verb: "shortfunc", format: "U", formatter: fabenc.ShortFuncFormatter{FormatVerb: "%U"}},
		{verb: "time", format: "", formatter: fabenc.TimeFormatter{Layout: "2006-01-02T15:04:05.999Z07:00"}},
		{verb: "time", format: "04:05.999999Z05:00", formatter: fabenc.TimeFormatter{Layout: "04:05.999999Z05:00"}},
		{verb: "unknown", format: "", errorMsg: "unknown verb: unknown"},
	}

	for i, tc := range tests {
		t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
			f, err := fabenc.NewFormatter(tc.verb, tc.format)
			if tc.errorMsg == "" {
				assert.NoError(t, err)
				assert.Equal(t, tc.formatter, f)
			} else {
				assert.EqualError(t, err, tc.errorMsg)
			}
		})
	}
}

func TestColorFormatter(t *testing.T) {
	var tests = []struct {
		f         fabenc.ColorFormatter
		level     zapcore.Level
		formatted string
	}{
		{f: fabenc.ColorFormatter{Reset: true}, level: zapcore.DebugLevel, formatted: fabenc.ResetColor()},
		{f: fabenc.ColorFormatter{}, level: zapcore.DebugLevel, formatted: fabenc.ColorCyan.Normal()},
		{f: fabenc.ColorFormatter{Bold: true}, level: zapcore.DebugLevel, formatted: fabenc.ColorCyan.Bold()},
		{f: fabenc.ColorFormatter{}, level: zapcore.InfoLevel, formatted: fabenc.ColorBlue.Normal()},
		{f: fabenc.ColorFormatter{Bold: true}, level: zapcore.InfoLevel, formatted: fabenc.ColorBlue.Bold()},
		{f: fabenc.ColorFormatter{}, level: zapcore.WarnLevel, formatted: fabenc.ColorYellow.Normal()},
		{f: fabenc.ColorFormatter{Bold: true}, level: zapcore.WarnLevel, formatted: fabenc.ColorYellow.Bold()},
		{f: fabenc.ColorFormatter{}, level: zapcore.ErrorLevel, formatted: fabenc.ColorRed.Normal()},
		{f: fabenc.ColorFormatter{Bold: true}, level: zapcore.ErrorLevel, formatted: fabenc.ColorRed.Bold()},
		{f: fabenc.ColorFormatter{}, level: zapcore.DPanicLevel, formatted: fabenc.ColorMagenta.Normal()},
		{f: fabenc.ColorFormatter{Bold: true}, level: zapcore.DPanicLevel, formatted: fabenc.ColorMagenta.Bold()},
		{f: fabenc.ColorFormatter{}, level: zapcore.PanicLevel, formatted: fabenc.ColorMagenta.Normal()},
		{f: fabenc.ColorFormatter{Bold: true}, level: zapcore.PanicLevel, formatted: fabenc.ColorMagenta.Bold()},
		{f: fabenc.ColorFormatter{}, level: zapcore.FatalLevel, formatted: fabenc.ColorMagenta.Normal()},
		{f: fabenc.ColorFormatter{Bold: true}, level: zapcore.FatalLevel, formatted: fabenc.ColorMagenta.Bold()},
		{f: fabenc.ColorFormatter{}, level: zapcore.Level(99), formatted: fabenc.ColorNone.Normal()},
		{f: fabenc.ColorFormatter{Bold: true}, level: zapcore.Level(99), formatted: fabenc.ColorNone.Normal()},
	}

	for i, tc := range tests {
		t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
			buf := &bytes.Buffer{}
			entry := zapcore.Entry{Level: tc.level}
			tc.f.Format(buf, entry, nil)
			assert.Equal(t, tc.formatted, buf.String())
		})
	}
}

func TestLevelFormatter(t *testing.T) {
	var tests = []struct {
		level     zapcore.Level
		formatted string
	}{
		{level: zapcore.DebugLevel, formatted: "DEBUG"},
		{level: zapcore.InfoLevel, formatted: "INFO"},
		{level: zapcore.WarnLevel, formatted: "WARN"},
		{level: zapcore.ErrorLevel, formatted: "ERROR"},
		{level: zapcore.DPanicLevel, formatted: "DPANIC"},
		{level: zapcore.PanicLevel, formatted: "PANIC"},
		{level: zapcore.FatalLevel, formatted: "FATAL"},
		{level: zapcore.Level(99), formatted: "LEVEL(99)"},
	}

	for i, tc := range tests {
		t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
			buf := &bytes.Buffer{}
			entry := zapcore.Entry{Level: tc.level}
			fabenc.LevelFormatter{FormatVerb: "%s"}.Format(buf, entry, nil)
			assert.Equal(t, tc.formatted, buf.String())
		})
	}
}

func TestMessageFormatter(t *testing.T) {
	buf := &bytes.Buffer{}
	entry := zapcore.Entry{Message: "some message text \n\n"}
	f := fabenc.MessageFormatter{FormatVerb: "%s"}
	f.Format(buf, entry, nil)
	assert.Equal(t, "some message text ", buf.String())
}

func TestModuleFormatter(t *testing.T) {
	buf := &bytes.Buffer{}
	entry := zapcore.Entry{LoggerName: "logger/name"}
	f := fabenc.ModuleFormatter{FormatVerb: "%s"}
	f.Format(buf, entry, nil)
	assert.Equal(t, "logger/name", buf.String())
}

func TestSequenceFormatter(t *testing.T) {
	mutex := &sync.Mutex{}
	results := map[string]struct{}{}

	ready := &sync.WaitGroup{}
	ready.Add(100)

	finished := &sync.WaitGroup{}
	finished.Add(100)

	fabenc.SetSequence(0)
	for i := 1; i <= 100; i++ {
		go func(i int) {
			buf := &bytes.Buffer{}
			entry := zapcore.Entry{Level: zapcore.DebugLevel}
			f := fabenc.SequenceFormatter{FormatVerb: "%d"}
			ready.Done() // setup complete
			ready.Wait() // wait for all go routines to be ready

			f.Format(buf, entry, nil) // format concurrently

			mutex.Lock()
			results[buf.String()] = struct{}{}
			mutex.Unlock()

			finished.Done()
		}(i)
	}

	finished.Wait()
	for i := 1; i <= 100; i++ {
		assert.Contains(t, results, strconv.Itoa(i))
	}
}

func TestShortFuncFormatter(t *testing.T) {
	callerpc, _, _, ok := runtime.Caller(0)
	assert.True(t, ok)
	buf := &bytes.Buffer{}
	entry := zapcore.Entry{Caller: zapcore.EntryCaller{PC: callerpc}}
	fabenc.ShortFuncFormatter{FormatVerb: "%s"}.Format(buf, entry, nil)
	assert.Equal(t, "TestShortFuncFormatter", buf.String())

	buf = &bytes.Buffer{}
	entry = zapcore.Entry{Caller: zapcore.EntryCaller{PC: 0}}
	fabenc.ShortFuncFormatter{FormatVerb: "%s"}.Format(buf, entry, nil)
	assert.Equal(t, "(unknown)", buf.String())
}

func TestTimeFormatter(t *testing.T) {
	buf := &bytes.Buffer{}
	entry := zapcore.Entry{Time: time.Date(1975, time.August, 15, 12, 0, 0, 333, time.UTC)}
	f := fabenc.TimeFormatter{Layout: time.RFC3339Nano}
	f.Format(buf, entry, nil)
	assert.Equal(t, "1975-08-15T12:00:00.000000333Z", buf.String())
}

func TestMultiFormatter(t *testing.T) {
	entry := zapcore.Entry{
		Message: "message",
		Level:   zapcore.InfoLevel,
	}
	fields := []zapcore.Field{
		zap.String("name", "value"),
	}

	var tests = []struct {
		desc     string
		initial  []fabenc.Formatter
		update   []fabenc.Formatter
		expected string
	}{
		{
			desc:     "no formatters",
			initial:  nil,
			update:   nil,
			expected: "",
		},
		{
			desc:     "initial formatters",
			initial:  []fabenc.Formatter{fabenc.StringFormatter{Value: "string1"}},
			update:   nil,
			expected: "string1",
		},
		{
			desc:    "set to formatters",
			initial: []fabenc.Formatter{fabenc.StringFormatter{Value: "string1"}},
			update: []fabenc.Formatter{
				fabenc.StringFormatter{Value: "string1"},
				fabenc.StringFormatter{Value: "-"},
				fabenc.StringFormatter{Value: "string2"},
			},
			expected: "string1-string2",
		},
		{
			desc:     "set to empty",
			initial:  []fabenc.Formatter{fabenc.StringFormatter{Value: "string1"}},
			update:   []fabenc.Formatter{},
			expected: "",
		},
	}

	for _, tc := range tests {
		mf := fabenc.NewMultiFormatter(tc.initial...)
		if tc.update != nil {
			mf.SetFormatters(tc.update)
		}

		buf := &bytes.Buffer{}
		mf.Format(buf, entry, fields)
		assert.Equal(t, tc.expected, buf.String())
	}
}


text:
OSUPPER = $(shell uname -s 2>/dev/null | tr "[:lower:]" "[:upper:]")
OSLOWER = $(shell uname -s 2>/dev/null | tr "[:upper:]" "[:lower:]")

OS_SIZE    = $(shell uname -m | sed -e "s/x86_64/64/" -e "s/armv7l/32/" -e "s/aarch64/64/")
OS_ARCH    = $(shell uname -m)
ARCH_FLAGS =

DARWIN = $(strip $(findstring DARWIN, $(OSUPPER)))

# Location of the CUDA Toolkit
ifneq ($(DARWIN),)
	CUDA_PATH       ?= /Developer/NVIDIA/CUDA-6.5
else
	# for Amazon EC2
	#CUDA_PATH       ?= /opt/nvidia/cuda

	# for Ubuntu Trusty
	CUDA_PATH       ?= /usr/local/cuda
endif

ifneq ($(DARWIN),)
	XCODE_GE_5 = $(shell expr `xcodebuild -version | grep -i xcode | awk '{print $$2}' | cut -d'.' -f1` \>= 5)
endif

# Take command line flags that override any of these settings
ifeq ($(x86_64),1)
	OS_SIZE = 64
	OS_ARCH = x86_64
endif
ifeq ($(ARMv7),1)
	OS_SIZE    = 32
	OS_ARCH    = armv7l
	ARCH_FLAGS = -target-cpu-arch ARM
endif
ifeq ($(aarch64),1)
	OS_SIZE    = 64
	OS_ARCH    = aarch64
	ARCH_FLAGS = -target-cpu-arch ARM
endif

# Common binaries
ifneq ($(DARWIN),)
ifeq ($(XCODE_GE_5),1)
  GCC ?= clang
  # GCC ?= clang++
else
  GCC ?= g++
endif
else
ifeq ($(ARMv7),1)
  GCC ?= arm-linux-gnueabihf-g++
else
  GCC ?= g++
endif
endif
NVCC := $(CUDA_PATH)/bin/nvcc -ccbin $(GCC)

# internal flags
NVCCFLAGS   := -m${OS_SIZE} ${ARCH_FLAGS}
CCFLAGS     :=
LDFLAGS     :=

# Extra user flags
EXTRA_NVCCFLAGS   ?=
EXTRA_LDFLAGS     ?=
EXTRA_CCFLAGS     ?=

# OS-specific build flags
ifneq ($(DARWIN),)
  LDFLAGS += -rpath $(CUDA_PATH)/lib
  #CCFLAGS += -arch $(OS_ARCH)
else
  # for Linux
  EXTRA_CCFLAGS     += -fPIC -shared -lstdc++
  EXTRA_NVCCFLAGS   += -Xcompiler -fPIC
endif

ifeq ($(ARMv7),1)
ifneq ($(TARGET_FS),)
GCCVERSIONLTEQ46 := $(shell expr `$(GCC) -dumpversion` \<= 4.6)
ifeq ($(GCCVERSIONLTEQ46),1)
CCFLAGS += --sysroot=$(TARGET_FS)
endif
LDFLAGS += --sysroot=$(TARGET_FS)
LDFLAGS += -rpath-link=$(TARGET_FS)/lib
LDFLAGS += -rpath-link=$(TARGET_FS)/usr/lib
LDFLAGS += -rpath-link=$(TARGET_FS)/usr/lib/arm-linux-$(abi)
endif
endif

# Debug build flags
ifeq ($(dbg),1)
      NVCCFLAGS += -g -G
      CCFLAGS += -g
      TARGET := debug
else
      TARGET := release
endif

ALL_CCFLAGS :=
ALL_CCFLAGS += $(NVCCFLAGS)
ALL_CCFLAGS += $(EXTRA_NVCCFLAGS)
ALL_CCFLAGS += $(addprefix -Xcompiler ,$(CCFLAGS))
ALL_CCFLAGS += $(addprefix -Xcompiler ,$(EXTRA_CCFLAGS))

ALL_LDFLAGS :=
ALL_LDFLAGS += $(ALL_CCFLAGS)
ALL_LDFLAGS += $(addprefix -Xlinker ,$(LDFLAGS))
ALL_LDFLAGS += $(addprefix -Xlinker ,$(EXTRA_LDFLAGS))

# Common includes and paths for CUDA
INCLUDES  :=
LIBRARIES :=

################################################################################

SAMPLE_ENABLED := 1

# Gencode arguments
ifeq ($(OS_ARCH),armv7l)
SMS ?= 20 30 32 35 37 50
else
SMS ?= 20 30 35 37 50
endif

ifeq ($(SMS),)
$(info >>> WARNING - no SM architectures have been specified - waiving sample <<<)
SAMPLE_ENABLED := 0
endif

ifeq ($(GENCODE_FLAGS),)
# Generate SASS code for each SM architecture listed in $(SMS)
$(foreach sm,$(SMS),$(eval GENCODE_FLAGS += -gencode arch=compute_$(sm),code=sm_$(sm)))

# Generate PTX code from the highest SM architecture in $(SMS) to guarantee forward-compatibility
HIGHEST_SM := $(lastword $(sort $(SMS)))
ifneq ($(HIGHEST_SM),)
GENCODE_FLAGS += -gencode arch=compute_$(HIGHEST_SM),code=compute_$(HIGHEST_SM)
endif
endif

ifeq ($(SAMPLE_ENABLED),0)
EXEC ?= @echo "[@]"
endif

################################################################################

OBJECTS := bulkem_cuda.o stream.o lp_sum.o cxx11.o

# Target rules
all: build

# build: libbulkem_cuda.a bulkem_cuda.so
build: libbulkem_cuda.a

check.deps:
ifeq ($(SAMPLE_ENABLED),0)
	@echo "Sample will be waived due to the above missing dependencies"
else
	@echo "Sample is ready - all dependencies have been met"
endif

cxx11.o: cxx11.cpp
	$(EXEC) $(GCC) $(INCLUDES) -std=c++11 -m64 -fPIC -rdynamic -shared -o $@ -c $<

lp_sum.o: lp_sum.cu
	$(EXEC) $(NVCC) $(INCLUDES) $(ALL_CCFLAGS) $(GENCODE_FLAGS) -o $@ -c $<

stream.o: stream.cu
	$(EXEC) $(NVCC) $(INCLUDES) $(ALL_CCFLAGS) $(GENCODE_FLAGS) -o $@ -c $<

bulkem_cuda.o: bulkem_cuda.cu
	$(EXEC) $(NVCC) $(INCLUDES) $(ALL_CCFLAGS) $(GENCODE_FLAGS) -o $@ -c $<

libbulkem_cuda.a: $(OBJECTS)
	ar cr libbulkem_cuda.a $(OBJECTS)
	ranlib libbulkem_cuda.a

clean:
	rm -f *.o *.so *.a

clobber: clean


text:
apt-get install -y fail2ban
echo -n "> Destination email [root@localhost]:"
read destination_email
jail_conf=/etc/fail2ban/jail.conf
sed -i -e "/destemail =/ s/= .*/= $destination_email/" $jail_conf

echo -n "Do you wish to use postfix (y/n)?"
read answer
if echo "$answer" | grep -iq "^y" ;then
    sed -i -e "/mta =/ s/= .*/= postfix/" $jail_conf
else
    sed -i -e "/mta =/ s/= .*/= sendmail/" $jail_conf
fi

/etc/init.d/fail2ban restart
echo "Waiting for restart ..."
sleep 20
/etc/init.d/fail2ban status


text:
author: robmyers
comments: true
date: 2009-03-25 20:47:22+00:00
layout: post
slug: lp-libre-planet-2009
title: LP - Libre Planet 2009
wordpress_id: 1743
categories:
- Free Culture
- Personal
---

[Libre Planet](http://groups.fsf.org/index.php/LibrePlanet2009) was great.

The FSF extended their annual get-together to two days this year and discussed free network services and their high priority projects as well as free software activism. It was held at Harward's science centre building, which was a great setting for rooms and for wifi but not so hot on food. ;-)

I met lots of cool people, and I'm going to blog about what I learnt over the next few days. Before that I need to say a massive thank you to Benjamin Mako Hill for letting me sleep on one of his sofas, to Matt Lee for suggesting I attend the convention, and to the rest of the FSF staff for running such a well-planned and successful event.


text:
package com.netflix.exhibitor.core.s3;

public class S3ClientFactoryImpl implements S3ClientFactory
{
    @Override
    public S3Client makeNewClient(final S3Credential credentials, String s3Region) throws Exception
    {
        return new S3ClientImpl(credentials, s3Region);
    }

    @Override
    public S3Client makeNewClient(final S3Credential credentials, final S3ClientConfig clientConfig, String s3Region) throws Exception
    {
        return new S3ClientImpl(credentials, clientConfig, s3Region);
    }

    @Override
    public S3Client makeNewClient(S3CredentialsProvider credentialsProvider, String s3Region) throws Exception
    {
        return new S3ClientImpl(credentialsProvider, s3Region);
    }

    @Override
    public S3Client makeNewClient(S3CredentialsProvider credentialsProvider, final S3ClientConfig clientConfig, String s3Region) throws Exception
    {
        return new S3ClientImpl(credentialsProvider, clientConfig, s3Region);
    }

}


text:
@testcase(NSProxy)

test(Alloc)
{
    testassert([NSProxy alloc] != nil);
    return YES;
}

test(RetainReleaseAutorelease)
{
    NSProxy *p = [NSProxy alloc];
    [p retain];
    [p release];
    [p autorelease];
    return YES;
}

test(BaseMethods)
{
    NSProxy *p = [NSProxy alloc];
    [p hash];
    [p isEqual:p];
    [p release];
    return YES;
}

test(Class)
{
    NSProxy *p = [NSProxy alloc];
    testassert([p class] == objc_getClass("NSProxy"));
    [p release];
    return YES;
}

test(ForwardingTarget)
{
    NSProxy *p = [NSProxy alloc];
    testassert([p forwardingTargetForSelector:@selector(test)] == nil);
    [p release];
    return YES;
}

test(ImplementsConformsToProtocol)
{
    Class cls = objc_getClass("NSProxy");
    testassert(class_getInstanceMethod(cls, @selector(conformsToProtocol:)) != NULL);
    return YES;
}

test(ImplementsMethodSignatureForSelector)
{
    Class cls = objc_getClass("NSProxy");
    testassert(class_getInstanceMethod(cls, @selector(methodSignatureForSelector:)) != NULL);
    return YES;
}

test(MethodSignatureForSelector)
{
    NSProxy *p = [NSProxy alloc];
    BOOL exceptionCaught = NO;
    @try {
        [p methodSignatureForSelector:@selector(init)];
    } @catch(NSException *e) {
        if ([[e name] isEqualToString:NSInvalidArgumentException])
        {
            exceptionCaught = YES;
        }
    }
    testassert(exceptionCaught == YES);
    [p release];
    return YES;
}

test(ImplementsIsKindOfClass)
{
    Class cls = objc_getClass("NSProxy");
    testassert(class_getInstanceMethod(cls, @selector(isKindOfClass:)) != NULL);
    return YES;
}

test(IsKindOfClass)
{
    NSProxy *p = [NSProxy alloc];
    BOOL exceptionCaught = NO;
    @try {
        [p isKindOfClass:[NSProxy class]];
    } @catch(NSException *e) {
        if ([[e name] isEqualToString:NSInvalidArgumentException])
        {
            exceptionCaught = YES;
        }
    }
    testassert(exceptionCaught == YES);
    [p release];
    return YES;
}

test(ImplementsIsMemberOfClass)
{
    Class cls = objc_getClass("NSProxy");
    testassert(class_getInstanceMethod(cls, @selector(isMemberOfClass:)) != NULL);
    return YES;
}

test(IsMemberOfClass)
{
    NSProxy *p = [NSProxy alloc];
    BOOL exceptionCaught = NO;
    @try {
        [p isMemberOfClass:[NSProxy class]];
    } @catch(NSException *e) {
        if ([[e name] isEqualToString:NSInvalidArgumentException])
        {
            exceptionCaught = YES;
        }
    }
    testassert(exceptionCaught == YES);
    [p release];
    return YES;
}

@end


text:
An interactive presentation framework.

## Requires

* [NPM](https://www.npmjs.com)
* [Bower](http://bower.io)
* [MongoDB](https://www.mongodb.org)

## Installation

Clone repository then run

    npm install
    bower install

## Start

Make sure MongoDB is running, then from the root directory run

    npm start

##  Build tools

Default `gulp` task will build Sass and front end js and jsx. `gulp watch` will watch for changes. See gulpfile for subtasks.

## Views

* Presenter: *base.url/presentation/presenter*
* Viewer: *base.url/presentation/*
* Stagehand: *base.url/presentation/stagehand*

## API

    base.url/api/presentations
    base.url/api/views

See [Feathers API Docs](http://feathersjs.com/docs/)

Use [Postman](https://www.getpostman.com) to input data. Put POST data in request body, make sure **x-www-form-urlencoded** is selected

## License

Copyright (c) 2016

Licensed under the [MIT license](LICENSE).