text:
<?php
namespace izzum\statemachine;
use izzum\statemachine\loader\Loader;
use izzum\statemachine\persistence\Adapter;

/**
 * This class (or it's subclasses) should be the preferred way to get a
 * statemachine.
 * It's based on the AbstractFactory pattern.
 *
 * To fully use polymorphism for all your statemachines, you should instantiate
 * all your machines via factories.
 * Full polymorphism allows you to build tooling that is the same for every
 * statemachine you use in your program. The only thing you would need to do is
 * instantiate the different factories to produce the different machines.
 *
 * The different sql backends provided store a fully qualified factory class
 * name for a machine so you can instantiate factories dynamically.
 *
 *
 * implement the abstract methods in a factory subclass specific to your problem
 * domain.
 *
 * $factory = new MySpecificFactory($dependencies_injected_here);
 * $machine = $factory->getStateMachine($order->getId());
 * $factory->add($machine->getInitialState());
 * $machine->run();
 *
 * @author Rolf Vreijdenberger
 *
 * @link https://en.wikipedia.org/wiki/Abstract_factory_pattern
 * @link https://en.wikipedia.org/wiki/Template_method_pattern
 */
abstract class AbstractFactory {

    /**
     * Gets the concrete Loader.
     *
     * A simple implementation might use the LoaderArray
     *
     * @return Loader An implementation of a Loader class (might be implemented
     *         on the persistence adapter)
     */
    abstract protected function createLoader();

    /**
     * Returns an implementation of an Adapter class for the persistence layer
     *
     * @return Adapter
     */
    abstract protected function createAdapter();

    /**
     * Get a builder to build your domain objects
     *
     * @return EntityBuilder
     */
    abstract protected function createBuilder();

    /**
     * get the machine name for the machines that are produced by this factory.
     * will be used by the Identifier and Context
     *
     * @return string
     */
    abstract protected function getMachineName();

    /**
     * Factory method to get a correctly configured statemachine without
     * creating all the default objects in application code.
     *
     * TRICKY: When using this method it could lead to unoptimized creation
     * of different builders/loaders/persistence objects.
     * For example: a Loader can be reused, a databaseloader will only have
     * to access a database once for a specific machine to get all the
     * transitions.
     *
     *
     * When using this method when inside a loop of some sorts where multiple
     * statemachines for different entities are needed, it would be wise to
     * cache/reuse the different loaders, builders and persistence adapters.
     *
     * php's spl_object_hash() method would be a good way to cache a fully
     * loaded statemachine.
     *
     * Furthermore, once a Loader, ReferenceBuilder and Adapter for persistence
     * have been instantiated, they can be cached in a field of this class since
     * they can safely be reused and shared. Or just change the context on a
     * machine to have access to all the same transitions, builders etc. of the
     * machine.
     *
     * @param string $id
     *            the entity id for the Identifier
     * @return StateMachine a statemachine ready to go
     * @throws Exception
     * @link https://en.wikipedia.org/wiki/Abstract_factory_pattern
     * @link https://en.wikipedia.org/wiki/Template_method_pattern
     */
    public function getStateMachine($id)
    {
        $context = $this->createContext(new Identifier($id, $this->getMachineName()));
        $machine = $this->createMachine($context);
        $loader = $this->createLoader();
        $loader->load($machine);
        return $machine;
    }

    /**
     * create a statemachine
     *
     * @param Context $context
     * @return StateMachine
     */
    protected function createMachine(Context $context)
    {
        return new StateMachine($context);
    }

    /**
     * Factory method to get a configured Context with the default Builder
     * and persistence adapter for a concrete statemachine type.
     *
     *
     * @param Identifier $identifier
     * @return Context
     * @throws Exception
     * @link https://en.wikipedia.org/wiki/Abstract_factory_pattern
     * @link https://en.wikipedia.org/wiki/Template_method_pattern
     */
    protected function createContext(Identifier $identifier)
    {
        $context = new Context($identifier, $this->createBuilder(), $this->createAdapter());
        return $context;
    }
}


text:
<?php defined('SYSPATH') or die('No direct script access.');

return array(

	// Application defaults
	'default' => array(
		'current_page'      => array('source' => 'query_string', 'key' => 'p'), // source: "query_string" or "route"
		'total_items'       => 0,
		'items_per_page'    => 3,
		'view'              => 'pagination/basic',
		'auto_hide'         => TRUE,
		'first_page_in_url' => FALSE,
	),

);

redpajama_set_name: RedPajamaGithub


text:
#import <Foundation/Foundation.h>

/**
 *  @brief Provides access to the BCE credentials used for accessing BCE services: BCE access key ID and secret access key.
 *         These credentials are used to securely sign requests to BCE services.
 */
@interface BCECredentials : NSObject

/**
 *  @brief The BCE access key for this credentials object.
 */
@property(nonatomic, copy) NSString* accessKey;

/**
 *  @brief The BCE secret access key for this credentials object.
 */
@property(nonatomic, copy) NSString* secretKey;
@end


text:
using System;
using System.Collections.Generic;
using IdmNet.Models;
using Microsoft.VisualStudio.TestTools.UnitTesting;
// ReSharper disable ObjectCreationAsStatement
// ReSharper disable UseObjectOrCollectionInitializer

namespace IdmNet.Models.Tests
{
    [TestClass]
    public class ObjectTypeDescriptionTests
    {
        private ObjectTypeDescription _it;

        public ObjectTypeDescriptionTests()
        {
            _it = new ObjectTypeDescription();
        }

        [TestMethod]
        public void It_has_a_paremeterless_constructor()
        {
            Assert.AreEqual("ObjectTypeDescription", _it.ObjectType);
        }

        [TestMethod]
        public void It_has_a_constructor_that_takes_an_IdmResource()
        {
            var resource = new IdmResource
            {
                DisplayName = "My Display Name",
                Creator = new Person { DisplayName = "Creator Display Name", ObjectID = "Creator ObjectID"},
            };
            var it = new ObjectTypeDescription(resource);

            Assert.AreEqual("ObjectTypeDescription", it.ObjectType);
            Assert.AreEqual("My Display Name", it.DisplayName);
            Assert.AreEqual("Creator Display Name", it.Creator.DisplayName);
        }

        [TestMethod]
        public void It_has_a_constructor_that_takes_an_IdmResource_without_Creator()
        {
            var resource = new IdmResource
            {
                DisplayName = "My Display Name",
            };
            var it = new ObjectTypeDescription(resource);

            Assert.AreEqual("My Display Name", it.DisplayName);
            Assert.IsNull(it.Creator);
        }

        [TestMethod]
        [ExpectedException(typeof(InvalidOperationException))]
        public void It_throws_when_you_try_to_set_ObjectType_to_anything_other_than_its_primary_ObjectType()
        {
            _it.ObjectType = "Invalid Object Type";
        }

        [TestMethod]
        public void It_can_get_and_set_Name()
        {
            // Act
            _it.Name = "A string";

            // Assert
            Assert.AreEqual("A string", _it.Name);
        }

        [TestMethod]
        public void It_has_UsageKeyword_which_is_null_by_default()
        {
            // Assert
            Assert.IsNull(_it.UsageKeyword);
        }

        [TestMethod]
        public void It_has_UsageKeyword_which_can_be_set_back_to_null()
        {
            // Arrange
            var subObject1 = "foo1";
            var subObject2 = "foo2";
            var list = new List<string> { subObject1, subObject2 };
            _it.UsageKeyword = list;

            // Act
            _it.UsageKeyword = null;

            // Assert
            Assert.IsNull(_it.UsageKeyword);
        }

        [TestMethod]
        public void It_can_get_and_set_UsageKeyword()
        {
            var subObject1 = "foo1";
            var subObject2 = "foo2";
            var list = new List<string> { subObject1, subObject2 };

            // Act
            _it.UsageKeyword = list;

            // Assert
            Assert.AreEqual("foo1", _it.UsageKeyword[0]);
            Assert.AreEqual("foo2", _it.UsageKeyword[1]);
        }

    }
}


text:
package org.wso2.am.integration.tests.api.lifecycle;

import org.json.JSONObject;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.am.integration.test.utils.APIManagerIntegrationTestException;
import org.wso2.am.integration.test.utils.bean.APICreationRequestBean;
import org.wso2.am.integration.test.utils.bean.APIResourceBean;
import org.wso2.am.integration.test.utils.bean.ApplicationKeyBean;
import org.wso2.am.integration.test.utils.clients.APIPublisherRestClient;
import org.wso2.am.integration.test.utils.clients.APIStoreRestClient;
import org.wso2.carbon.apimgt.api.model.APIIdentifier;
import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil;
import org.wso2.carbon.automation.test.utils.http.client.HttpResponse;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;

/**
 * Change the Auth type of the Resource and invoke the APi
 */
public class ChangeAuthTypeOfResourceTestCase extends APIManagerLifecycleBaseTest {

    private static final String API_NAME = "ChangeAuthTypeOfResourceTest";
    private static final String API_CONTEXT = "ChangeAuthTypeOfResource";
    private static final String API_TAGS = "testTag1, testTag2, testTag3";
    private static final String API_END_POINT_POSTFIX_URL = "jaxrs_basic/services/customers/customerservice/";
    private static final String API_DESCRIPTION = "This is test API create by API manager integration test";
    private static final String API_VERSION_1_0_0 = "1.0.0";
    private static final String RESPONSE_GET = "<id>123</id><name>John</name></Customer>";
    private static final String API_GET_ENDPOINT_METHOD = "/customers/123";
    private String APPLICATION_NAME = "ChangeAuthTypeOfResourceTestCase";
    private APIPublisherRestClient apiPublisherClientUser1;
    private String apiEndPointUrl;
    private APIStoreRestClient apiStoreClientUser1;
    private String providerName;
    private APIIdentifier apiIdentifier;
    private ApplicationKeyBean applicationKeyBean;
    private HashMap<String, String> requestHeadersGet;

    @BeforeClass(alwaysRun = true)
    public void initialize() throws Exception {
        super.init();
        apiEndPointUrl = gatewayUrls.getWebAppURLHttp() + API_END_POINT_POSTFIX_URL;
        providerName = publisherContext.getContextTenant().getContextUser().getUserName();
        String publisherURLHttp = publisherUrls.getWebAppURLHttp();
        String storeURLHttp = storeUrls.getWebAppURLHttp();
        apiPublisherClientUser1 = new APIPublisherRestClient(publisherURLHttp);
        apiStoreClientUser1 = new APIStoreRestClient(storeURLHttp);
        //Login to API Publisher with  admin
        apiPublisherClientUser1.login(publisherContext.getContextTenant().getContextUser().getUserName(),
                publisherContext.getContextTenant().getContextUser().getPassword());
        //Login to API Store with  admin
        apiStoreClientUser1.login(storeContext.getContextTenant().getContextUser().getUserName(),
                storeContext.getContextTenant().getContextUser().getPassword());
        requestHeadersGet = new HashMap<String, String>();
        requestHeadersGet.put("accept", "text/xml");
    }

    @Test(groups = {"wso2.am"}, description = "Invoke a resource with auth type Application And Application User")
    public void testInvokeResourceWithAuthTypeApplicationAndApplicationUser() throws Exception {
        //Create application
        apiStoreClientUser1.addApplication(APPLICATION_NAME, TIER_GOLD, "", "");
        APICreationRequestBean apiCreationRequestBean =
                new APICreationRequestBean(API_NAME, API_CONTEXT, API_VERSION_1_0_0, providerName, new URL(apiEndPointUrl));
        apiCreationRequestBean.setTags(API_TAGS);
        apiCreationRequestBean.setDescription(API_DESCRIPTION);
        apiCreationRequestBean.setVisibility("public");
        List<APIResourceBean> apiResourceBeansList = new ArrayList<APIResourceBean>();
        APIResourceBean apiResourceBeanGET = new APIResourceBean("GET", "Application & Application User", "Unlimited", "/*");
        apiResourceBeansList.add(apiResourceBeanGET);
        apiCreationRequestBean.setResourceBeanList(apiResourceBeansList);
        //Create publish and subscribe a API
        apiIdentifier = new APIIdentifier(providerName, API_NAME, API_VERSION_1_0_0);
        createPublishAndSubscribeToAPI(apiIdentifier, apiCreationRequestBean, apiPublisherClientUser1,
                apiStoreClientUser1, APPLICATION_NAME);
        //get the  access token
        applicationKeyBean = generateApplicationKeys(apiStoreClientUser1, APPLICATION_NAME);
        String accessToken = applicationKeyBean.getAccessToken();
        requestHeadersGet.put("Authorization", "Bearer " + accessToken);
        //Send GET request
        HttpResponse httpResponseGet =
                HttpRequestUtil.doGet(gatewayWebAppUrl + API_CONTEXT + "/" + API_VERSION_1_0_0 + API_GET_ENDPOINT_METHOD,
                        requestHeadersGet);
        assertEquals(httpResponseGet.getResponseCode(), HTTP_RESPONSE_CODE_OK, "Invocation fails for GET request for " +
                "auth type Application & Application User");
        assertTrue(httpResponseGet.getData().contains(RESPONSE_GET), "Response Data not match for GET request for" +
                " auth type Application & Application User. Expected value :\"" + RESPONSE_GET + "\" not contains" +
                " in response data:\"" + httpResponseGet.getData() + "\"");

    }

    @Test(groups = {"wso2.am"}, description = "Invoke a resource with auth type Application",
            dependsOnMethods = "testInvokeResourceWithAuthTypeApplicationAndApplicationUser")
    public void testInvokeResourceWithAuthTypeApplication() throws Exception {
        APICreationRequestBean apiCreationRequestBean =
                new APICreationRequestBean(API_NAME, API_CONTEXT, API_VERSION_1_0_0, providerName,
                        new URL(apiEndPointUrl));
        apiCreationRequestBean.setTags(API_TAGS);
        apiCreationRequestBean.setDescription(API_DESCRIPTION);
        apiCreationRequestBean.setVisibility("public");
        List<APIResourceBean> apiResourceBeansList = new ArrayList<APIResourceBean>();
        APIResourceBean apiResourceBeanGET = new APIResourceBean("GET", "Application", "Unlimited", "/*");
        apiResourceBeansList.add(apiResourceBeanGET);
        apiCreationRequestBean.setResourceBeanList(apiResourceBeansList);
        //Update API with Edited information
        HttpResponse updateAPIHTTPResponse = apiPublisherClientUser1.updateAPI(apiCreationRequestBean);
        assertEquals(updateAPIHTTPResponse.getResponseCode(), HTTP_RESPONSE_CODE_OK,
                "Update APi with new Resource information fail");
        assertEquals(getValueFromJSON(updateAPIHTTPResponse, "error"), "false", "Update APi with new Resource information fail");
        //Send GET request
        HttpResponse httpResponseGet =
                HttpRequestUtil.doGet(gatewayWebAppUrl + API_CONTEXT + "/" + API_VERSION_1_0_0 + API_GET_ENDPOINT_METHOD,
                        requestHeadersGet);
        assertEquals(httpResponseGet.getResponseCode(), HTTP_RESPONSE_CODE_OK, "Invocation fails for GET request for " +
                "auth type Application");
        assertTrue(httpResponseGet.getData().contains(RESPONSE_GET), "Response Data not match for GET request for" +
                " auth type Application. Expected value :\"" + RESPONSE_GET + "\" not contains in response data:\"" +
                httpResponseGet.getData() + "\"");

    }

    @Test(groups = {"wso2.am"}, description = "Invoke a resource with auth type Application User",
            dependsOnMethods = "testInvokeResourceWithAuthTypeApplication")
    public void testInvokeGETResourceWithAuthTypeApplicationUser() throws Exception {

        APICreationRequestBean apiCreationRequestBean =
                new APICreationRequestBean(API_NAME, API_CONTEXT, API_VERSION_1_0_0, providerName, new URL(apiEndPointUrl));
        apiCreationRequestBean.setTags(API_TAGS);
        apiCreationRequestBean.setDescription(API_DESCRIPTION);

        apiCreationRequestBean.setVisibility("public");
        List<APIResourceBean> apiResourceBeansList = new ArrayList<APIResourceBean>();
        APIResourceBean apiResourceBeanGET = new APIResourceBean("GET", "Application User", "Unlimited", "/*");
        apiResourceBeansList.add(apiResourceBeanGET);
        apiCreationRequestBean.setResourceBeanList(apiResourceBeansList);
        //Update API with Edited information
        HttpResponse updateAPIHTTPResponse = apiPublisherClientUser1.updateAPI(apiCreationRequestBean);
        assertEquals(updateAPIHTTPResponse.getResponseCode(), HTTP_RESPONSE_CODE_OK, "Update APi with new Resource information fail");
        assertEquals(getValueFromJSON(updateAPIHTTPResponse, "error"), "false", "Update APi with new Resource information fail");
        //Generate User Access Key
        String requestBody = "grant_type=password&username=admin&password=admin&scope=PRODUCTION";
        URL tokenEndpointURL = new URL(gatewayUrls.getWebAppURLNhttp() + "token");
        JSONObject accessTokenGenerationResponse = new JSONObject(
                apiStoreClientUser1.generateUserAccessKey(applicationKeyBean.getConsumerKey(),
                        applicationKeyBean.getConsumerSecret(), requestBody, tokenEndpointURL).getData());
        requestHeadersGet.put("Authorization", "Bearer " + accessTokenGenerationResponse.getString("access_token"));
        //Send GET request
        HttpResponse httpResponseGet =
                HttpRequestUtil.doGet(gatewayWebAppUrl + API_CONTEXT + "/" + API_VERSION_1_0_0 + API_GET_ENDPOINT_METHOD,
                        requestHeadersGet);
        assertEquals(httpResponseGet.getResponseCode(), HTTP_RESPONSE_CODE_OK, "Invocation fails for GET request for " +
                "auth type Application User");
        assertTrue(httpResponseGet.getData().contains(RESPONSE_GET), "Response Data not match for GET request for" +
                " auth type Application User. Expected value :\"" + RESPONSE_GET + "\" not contains in response data:\"" +
                httpResponseGet.getData() + "\"");

    }

    @Test(groups = {"wso2.am"}, description = "Invoke a resource with auth type None",
            dependsOnMethods = "testInvokeGETResourceWithAuthTypeApplicationUser")
    public void testInvokeGETResourceWithAuthTypeNone() throws Exception {

        APICreationRequestBean apiCreationRequestBean =
                new APICreationRequestBean(API_NAME, API_CONTEXT, API_VERSION_1_0_0, providerName, new URL(apiEndPointUrl));
        apiCreationRequestBean.setTags(API_TAGS);
        apiCreationRequestBean.setDescription(API_DESCRIPTION);
        apiCreationRequestBean.setVisibility("public");
        List<APIResourceBean> apiResourceBeansList = new ArrayList<APIResourceBean>();
        APIResourceBean apiResourceBeanGET = new APIResourceBean("GET", "None", "Unlimited", "/*");
        apiResourceBeansList.add(apiResourceBeanGET);
        apiCreationRequestBean.setResourceBeanList(apiResourceBeansList);
        //Update API with Edited information
        HttpResponse updateAPIHTTPResponse = apiPublisherClientUser1.updateAPI(apiCreationRequestBean);
        assertEquals(updateAPIHTTPResponse.getResponseCode(), HTTP_RESPONSE_CODE_OK, "Update APi with new Resource information fail");
        assertEquals(getValueFromJSON(updateAPIHTTPResponse, "error"), "false", "Update APi with new Resource information fail");
        //Send GET request
        HttpResponse httpResponseGet =
                HttpRequestUtil.doGet(gatewayWebAppUrl + API_CONTEXT + "/" + API_VERSION_1_0_0 + API_GET_ENDPOINT_METHOD,
                        requestHeadersGet);
        assertEquals(httpResponseGet.getResponseCode(), HTTP_RESPONSE_CODE_OK, "Invocation fails for GET request for " +
                "auth type None");
        assertTrue(httpResponseGet.getData().contains(RESPONSE_GET), "Response Data not match for GET request for" +
                " auth type Non3. Expected value :\"" + RESPONSE_GET + "\" not contains in response data:\"" +
                httpResponseGet.getData() + "\"");
    }

    @AfterClass(alwaysRun = true)
    public void cleanUpArtifacts() throws APIManagerIntegrationTestException {
        apiStoreClientUser1.removeApplication(APPLICATION_NAME);
        deleteAPI(apiIdentifier, apiPublisherClientUser1);
    }

}


text:
import leon.lang._
import leon.lang.synthesis._

object MergeSort {
  sealed abstract class List
  case class Cons(head : Int, tail : List) extends List
  case class Nil() extends List

  sealed abstract class PairAbs
  case class Pair(fst : List, snd : List) extends PairAbs

  def contents(l : List) : Set[Int] = l match {
    case Nil() => Set.empty
    case Cons(x,xs) => contents(xs) ++ Set(x)
  }

  def isSorted(l : List) : Boolean = l match {
    case Nil() => true
    case Cons(x,xs) => xs match {
      case Nil() => true
      case Cons(y, ys) => x <= y && isSorted(Cons(y, ys))
    }
  }

  def size(list : List) : Int = list match {
    case Nil() => 0
    case Cons(x,xs) => 1 + size(xs)
  }

  def splithelper(aList : List, bList : List, n : Int) : Pair = {
    if (n <= 0) Pair(aList,bList)
    else
	bList match {
    	      case Nil() => Pair(aList,bList)
    	      case Cons(x,xs) => splithelper(Cons(x,aList),xs,n-1)
	}
  } ensuring(res => contents(aList) ++ contents(bList) == contents(res.fst) ++ contents(res.snd))

//  def split(list : List, n : Int): Pair = {
//    splithelper(Nil(),list,n)
//  } ensuring(res => contents(list) == contents(res.fst) ++ contents(res.snd))

  def split(list: List): Pair = {
    splithelper(Nil(),list,size(list)/2)
  } ensuring(res => contents(list) == contents(res.fst) ++ contents(res.snd))

  def merge(aList : List, bList : List) : List = {
    require(isSorted(aList) && isSorted(bList))
    bList match {
      case Nil() => aList
      case Cons(x,xs) =>
        aList match {
              case Nil() => bList
              case Cons(y,ys) =>
               if (y < x)
                  Cons(y,merge(ys, bList))
               else
                  Cons(x,merge(aList, xs))
        }
    }
  } ensuring(res => contents(res) == contents(aList) ++ contents(bList) && isSorted(res))

  def isEmpty(list: List) : Boolean = list match {
    case Nil() => true
    case Cons(x,xs) => false
  }

  def sort(list : List) : List =
      list match {
    case Nil() => list
    case Cons(_,Nil()) => list
    case _ => {
    	 val p = split(list)
	    choose {(res : List) =>
	      contents(res) == contents(list) && isSorted(res)
    	 }
    }
  }

//      merge(mergeSort(split(list).fst), mergeSort(split(list).snd))

  //ensuring(res => contents(res) == contents(list) && isSorted(res))

}


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.catchingnow.tinyclipboardmanager.ActivityBackup">
    <!--
    <item android:id="@+id/action_settings" android:title="@string/action_settings"
        android:orderInCategory="100" app:showAsAction="never" />
        -->
    <item
        android:id="@+id/action_refresh"
        android:title="@string/action_refresh"
        android:icon="@drawable/ic_action_refresh"
        app:showAsAction="always"
        />
</menu>


text:
/* global requirejs */
/* jshint browser:true */
var tests = [];
for (var file in window.__karma__.files) {
    if (/Spec\.js$/.test(file)) {
        tests.push(file);
    }
}

requirejs.config({
    // Karma serves files from '/base'
    baseUrl: '/base/web/bundles',

    // ask Require.js to load these files (all our tests)
    deps: tests,

    // start test run, once Require.js is done
    callback: window.__karma__.start
});


text:
This is Dockerfile for [nghttp2](https://github.com/tatsuhiro-t/nghttp2).

Build it,

```bash
$ docker build -t tcnksm/nghttp2 .
```

Run it,

```bash
$ docker run --rm -it -p <port>:<port> nghttp2 <port>
```


text:
<?php

namespace figdice\classes\lexer;

use Exception;
use figdice\classes\Context;
use figdice\classes\ViewElementTag;
use figdice\exceptions\LexerUnexpectedCharException;
use figdice\exceptions\LexerSyntaxErrorException;
use figdice\exceptions\LexerUnbalancedParenthesesException;

class Lexer {

    /** @var Context */
    private $context;

	/**
	 * @var ViewElementTag
	 */
	private $viewElement;

	/**
	 * @var string
	 */
	private $expression;

	/**
	 * @var DFAState
	 */
	private $currentState;

	/**
	 * @var DFAStateEmpty
	 */
	private static $stateEmpty = null;
	/**
	 * @var DFAStateSymbol
	 */
	private static $stateSymbol = null;
	/**
	 * @var DFAStateInteger
	 */
	private static $stateInteger = null;
	/**
	 * @var DFAStateDecimal
	 */
	private static $stateDecimal = null;
	/**
	 * @var DFAStateFunction
	 */
	private static $stateFunction = null;
	/**
	 * @var DFAStateComparison
	 */
	private static $stateComparison = null;
	/**
	 * @var DFAStateString
	 */
	private static $stateString = null;
	/**
	 * @var DFAStateClosedExpression
	 */
	private static $stateClosedExpression = null;
	/**
	 * @var DFAStatePath
	 */
	private static $statePath = null;
	/**
	 * @var DFAStateDot
	 */
	private static $stateDot = null;
	/**
	 * @var DFAStateDotdot
	 */
	private static $stateDotdot = null;

	/**
	 * @var array
	 */
	private $stackOperators = [];
	/**
	 * @var array
	 */
	private $stackFunctions = [];

	/**
	 * @var Token[]
	 */
	private $stackRP = [];

	/**
	 * The position of the character being parsed, in expression,
	 * during parse-time.
	 * @var integer
	 */
	private $parsingPosition;

	public function __construct($expression) {
		$this->expression = $expression;

		if(! self::$stateEmpty) {
			self::$stateEmpty = new DFAStateEmpty();
			self::$stateSymbol = new DFAStateSymbol();
			self::$stateInteger = new DFAStateInteger();
			self::$stateDecimal = new DFAStateDecimal();
			self::$stateFunction = new DFAStateFunction();
			self::$stateComparison = new DFAStateComparison();
			self::$stateString = new DFAStateString();
			self::$stateClosedExpression = new DFAStateClosedExpression();
			self::$statePath = new DFAStatePath();
			self::$stateDot = new DFAStateDot();
			self::$stateDotdot = new DFAStateDotdot();
		}

		$this->currentState = self::$stateEmpty;
	}

	/**
	 * Returns the tree representing the parsed expression.
	 * @return array
	 */
	public function getTree() {
		return $this->stackRP[0];
	}

    /**
     * @param Context $context
     *
     * @return bool
     * @throws LexerSyntaxErrorException
     * @throws LexerUnbalancedParenthesesException
     * @throws LexerUnexpectedCharException
     */
	public function parse(Context $context) {
	    $this->context = $context;
		$this->viewElement = $context->tag;

		//Interpret an empty expression as boolean false.
		if(trim($this->expression) == '') {
		  $this->pushOperand(new TokenLiteral(false));
		  return true;
		}

		$char = '';

		try {
			$expressionSize = strlen($this->expression);
			for($this->parsingPosition = 0; $this->parsingPosition < $expressionSize; ++ $this->parsingPosition) {
				$char = $this->expression[$this->parsingPosition];
				$this->currentState->input($this, $char);
			}

			$this->currentState->endOfInput($this);

			while(count($this->stackOperators)) {
				$operator = array_pop($this->stackOperators);
				$nbOperands = $operator->getNumOperands();
				if($nbOperands) {
					// Check that we have enough operands on the stack.
					if (count($this->stackRP) < $nbOperands) {
						throw new LexerSyntaxErrorException('Missing operand', $this->getViewFile(), $this->getViewLine());
					}
					$operator->setOperands(array_splice($this->stackRP, count($this->stackRP) - $nbOperands, $nbOperands));
				}
				$this->stackRP[] = $operator;
				if($operator instanceof TokenFunction) {
									array_pop($this->stackFunctions);
				}
			}
		}

		// Enrich the Lexer parsing and tokenizing exceptions with template file and line
		catch (LexerUnbalancedParenthesesException $exception) {
		    throw new LexerUnbalancedParenthesesException($exception->getMessage(), $this->getViewFile(), $this->getViewLine());
        } catch (LexerSyntaxErrorException $exception) {
		    throw new LexerSyntaxErrorException($exception->getMessage(), $this->getViewFile(), $this->getViewLine());
        } catch (Exception $exception) {
			$errorMsg = "Unexpected character: $char at position: {$this->parsingPosition} in expression: {$this->expression}.";
			throw new LexerUnexpectedCharException($errorMsg, $this->getViewFile(), $this->getViewLine());
		}

		if( (count($this->stackOperators) > 0) ||
				(count($this->stackFunctions) > 0) ||
				(count($this->stackRP) != 1)
			)
		{
			$message = $this->getViewFile() . '(' . $this->getViewLine() . '): Syntax error in expression: ' . $this->expression;
			throw new LexerSyntaxErrorException($message,
					$this->getViewFile(),
					$this->getViewLine());
		}

		// Check for unbalanced parentheses:
		if( ($this->stackRP[0] instanceof TokenFunction) &&
		    (! $this->stackRP[0]->isClosed())
		)
		{
		  $message = $this->getViewFile() . '(' . $this->getViewLine() . '): Unbalanced parentheses in expression: ' . $this->expression;
		  throw new LexerUnbalancedParenthesesException($message,
		    $this->getViewFile(),
		    $this->getViewLine());
		}

		return true;
	}

	/**
	 * @param string $char
	 */
	public function setStateSymbol($char)
	{
		$this->currentState = self::$stateSymbol;
		$this->currentState->setBuffer($char);
	}
	public function setStateDot() {
		$this->currentState = self::$stateDot;
	}
	/**
	 * @param string $char
	 */
	public function setStateInteger($char)
	{
		$this->currentState = self::$stateInteger;
		$this->currentState->setBuffer($char);
	}

	public function setStateDecimal($buffer)
	{
		$this->currentState = self::$stateDecimal;
		$this->currentState->setBuffer($buffer);
	}
	public function setStateEmpty() {
		$this->currentState = self::$stateEmpty;
	}

	public function setStateFunction($name) {
		$this->currentState = self::$stateFunction;
		$this->currentState->setBuffer($name);
	}

	public function setStatePath($separated = true, $closedSubpath = false) {
		$this->currentState = self::$statePath;
		$this->currentState->separate($separated);
		$this->currentState->setBuffer('');
		$this->currentState->setClosedSubpath($closedSubpath);
	}
	public function setStateDotdot() {
		$this->currentState = self::$stateDotdot;
	}
	/**
	 * @param string $string
	 */
	public function setStateComparison($string) {
		$this->currentState = self::$stateComparison;
		$this->currentState->setBuffer($string);
	}

	public function setStateString() {
		$this->currentState = self::$stateString;
		$this->currentState->setBuffer('');
	}
	public function setStateClosedExpression() {
		$this->currentState = self::$stateClosedExpression;
	}

	/**
	 * @param Token $tokenOperand
	 */
	public function pushOperand($tokenOperand) {
		$this->stackRP[] = $tokenOperand;
	}

    /**
     * @param TokenOperator $tokenOperator
     *
     * @throws LexerSyntaxErrorException
     */
	public function pushOperator($tokenOperator) {
		//If priority of the new operator
		//is lower than or equal to that of the previous, if any,
		//then pop the stack up to the nearest operator
		//of lower priority strictly, or up to left parenthesis.

		if( (! $tokenOperator instanceof TokenLParen) &&
		 		(! $tokenOperator instanceof TokenFunction) &&
		 		(! $tokenOperator instanceof TokenLBracket)
			) {
			while(count($this->stackOperators) > 0) {
				$operator = $this->stackOperators[count($this->stackOperators) - 1];
				if($operator instanceof TokenLParen) {
					break;
				}

				if( ($operator instanceof TokenFunction) && (! $operator->isClosed()) ) {
					break;
				}

				if( $tokenOperator->getPriority() <= $operator->getPriority() ) {
					array_pop($this->stackOperators);

					$nbOperands = $operator->getNumOperands();
					if($nbOperands) {
            // Check that we have enough operands on the stack.
            if (count($this->stackRP) < $nbOperands) {
              $message = 'Missing operand in expression: ' . $this->expression;
              throw new LexerSyntaxErrorException($message, $this->getViewFile(), $this->getViewLine());
            }
						$operator->setOperands(array_splice($this->stackRP, count($this->stackRP) - $nbOperands, $nbOperands));
					}
					$this->stackRP[] = $operator;

					if($operator instanceof TokenFunction) {
						array_pop($this->stackFunctions);
						break;
					}
				} else {
					break;
				}
			}
		}

		$this->stackOperators[] = $tokenOperator;
		if($tokenOperator instanceof TokenFunction) {
			$this->stackFunctions[] = &$tokenOperator;
		}
		$this->setStateEmpty();
	}

	public function closeParenthesis() {
		while(0 < count($this->stackOperators)) {
			$operator = array_pop($this->stackOperators);
			if($operator instanceof TokenLParen) {
				break;
			}

			$nbOperands = $operator->getNumOperands();
			if($nbOperands) {
				if (count($this->stackRP) < $nbOperands) {
					throw new LexerSyntaxErrorException('Not enough arguments in: ' . $this->getExpression(), $this->getViewFile(), $this->getViewLine());
				}
				$operator->setOperands(array_splice($this->stackRP, count($this->stackRP) - $nbOperands, $nbOperands));
			}
			$this->stackRP[] = $operator;

			if($operator instanceof TokenFunction) {
				$operator->close();
				array_pop($this->stackFunctions);
				break;
			}
		}

		$this->setStateClosedExpression();
	}

	/**
	 * Create a wrappable Expression out of what's inside the [],
	 * and append it as a path element to current path.
	 * @throws Exception
	 */
	public function closeSquareBracket() {
		while(0 < count($this->stackOperators)) {
			$operator = array_pop($this->stackOperators);
			if($operator instanceof TokenLBracket) {
				break;
			}

			// The square bracket expression contains operators. ex: [i + 1]
			$nbOperands = $operator->getNumOperands();
			if($nbOperands) {
				$operator->setOperands(array_splice($this->stackRP, count($this->stackRP) - $nbOperands, $nbOperands));
			}
			$this->stackRP[] = $operator;

		}

		$operand = array_pop($this->stackRP);
		$path = new Expression($operand);
		$this->pushPathElement($path);
		$this->setStatePath(false, true);
	}

	/**
	 * @param PathElement|string $path
	 */
	public function pushPath($path) {
		$this->pushOperand(new TokenPath($path));
		$this->setStatePath();
	}

	/**
	 * Prerequisite to this function: the last element in stack
	 * MUST be a TokenPath. It is normally always the case, given the usage of
	 * this function. If you think you need to call Lexer::pushPathElement by
	 * yourself from somewhere, make sure your last stack elt is a TokenPath.
	 * @param $buffer
	 */
	public function pushPathElement($buffer) {
		/** @var TokenPath $tokenPath */
		$tokenPath = $this->stackRP[count($this->stackRP) - 1];
		$tokenPath->appendElement($buffer);
	}

	public function incrementLastFunctionArity() {

		if ( ($funcStackCount = count($this->stackFunctions)) == 0) {
			// There isn't a function to which we're incrementing arity!
			$errorMsg = $this->getViewFile() . '(' . $this->getViewLine() . '): Unbalanced parentheses in expression: "' . $this->expression . '"';
			throw new LexerUnbalancedParenthesesException($errorMsg,
				$this->getViewFile(),
				$this->getViewLine());
		}

    // Grab the topmost function on the stack. That's the one we're dealing with.
		$tokenFunction = $this->stackFunctions[$funcStackCount - 1];
		$this->setStateEmpty();

		//Pop operators up to the function:
    //the function of interest (the one to which we're pushing a comma) is the topmost TokenFunction
    //in the stack of operators. Every other operator must be popped and his operands popped+attached.
		//An intermediate function ( example: func2 in "func1(func2(x),y)"   ) is no longer a TokenFunction in
		//the stack of operators at this stage. It already became an operand at the ")" before the ",".
		while( (! ($this->stackOperators[count($this->stackOperators) - 1]) instanceof TokenFunction) ) {
			$operator = array_pop($this->stackOperators);
			$nbOperands = $operator->getNumOperands();
			if($nbOperands) {
				$operator->setOperands(array_splice($this->stackRP, count($this->stackRP) - $nbOperands, $nbOperands));
			}
			$this->stackRP[] = $operator;
		}
		$tokenFunction->incrementArity();
	}

	public function forwardInput($char) {
		$this->currentState->input($this, $char);
	}

	/**
	 * @param Context $context
	 * @return mixed
	 */
	public function evaluate(Context $context) {
	    $this->context = $context;
		$this->viewElement = $context->tag;
		return $this->stackRP[0]->evaluate($context);
	}

	/**
	 * @return string
	 */
	public function getExpression() {
		return $this->expression;
	}

	/**
	 * Returns the file containing the current
	 * expression to evaluate.
	 *
	 * @return string
	 */
	public function getViewFile() {
		return $this->context->getFilename();
	}
	public function getViewLine() {
		return $this->viewElement->getLineNumber();
	}
}


text:
A light UI theme for Atom.

Light ui theme with icons based on the atom-light theme

Icon made by Freepik from www.flaticon.com
http://www.flaticon.com/free-icon/js-file-format-symbol_29582


text:
class CreateProductLines < ActiveRecord::Migration
  def change
    create_table :product_lines do |t|
      t.references :container, :polymorphic => true
      t.integer :product_id
      t.text :description
      t.decimal :quantity, :precision => 10, :scale => 2, :default => 0
      t.decimal :tax, :precision => 6, :scale => 4
      t.decimal :discount, :precision => 6, :scale => 4
      t.decimal :price, :precision => 10, :scale => 2, :default => 0
      t.integer :position
    end
    add_index :product_lines, [:product_id]
    add_index :product_lines, [:container_id, :container_type]
    add_index :product_lines, [:position]
  end
end


text:
package net.neosum.android.nastore.felix;

import java.util.Properties;

public class FelixProperties extends Properties
{
	private static final long serialVersionUID = 1L;

	private String m_felixAbsolutePath;

	public FelixProperties(String rootpath)
	{
		m_felixAbsolutePath = rootpath;

		put("org.osgi.framework.storage", m_felixAbsolutePath+"/felix/cache");
		put("felix.cache.rootdir",m_felixAbsolutePath+"/felix");
		put("felix.log.level", "4");
		put("felix.startlevel.bundle", "1");

		put("org.osgi.framework.system.packages.extra", ANDROID_PACKAGES_FOR_EXPORT);
	}

	private final String ANDROID_PACKAGES_FOR_EXPORT=
		// ANDROID (here starts semicolon as separator -> Why?
        "android, " +
        "android.app," +
        "android.content," +
        "android.database," +
        "android.database.sqlite," +
        "android.graphics, " +
        "android.graphics.drawable, " +
        "android.graphics.glutils, " +
        "android.hardware, " +
        "android.location, " +
        "android.media, " +
        "android.net, " +
        "android.opengl, " +
        "android.os, " +
        "android.provider, " +
        "android.sax, " +
        "android.speech.recognition, " +
        "android.telephony, " +
        "android.telephony.gsm, " +
        "android.text, " +
        "android.text.method, " +
        "android.text.style, " +
        "android.text.util, " +
        "android.util, " +
        "android.view, " +
        "android.view.animation, " +
        "android.webkit, " +
        "android.widget, " +
        // JAVAx
        "javax.crypto; " +
        "javax.crypto.interfaces; " +
        "javax.crypto.spec; " +
        "javax.microedition.khronos.opengles; " +
        "javax.net; " +
        "javax.net.ssl; " +
        "javax.security.auth; " +
        "javax.security.auth.callback; " +
        "javax.security.auth.login; " +
        "javax.security.auth.x500; " +
        "javax.security.cert; " +
        "javax.sound.midi; " +
        "javax.sound.midi.spi; " +
        "javax.sound.sampled; " +
        "javax.sound.sampled.spi; " +
        "javax.sql; " +
        "javax.xml.parsers; " +
        //JUNIT
        "junit.extensions; " +
        "junit.framework; " +
        //APACHE
        "org.apache.commons.codec; " +
        "org.apache.commons.codec.binary; " +
        "org.apache.commons.codec.language; " +
        "org.apache.commons.codec.net; " +
        "org.apache.commons.httpclient; " +
        "org.apache.commons.httpclient.auth; " +
        "org.apache.commons.httpclient.cookie; " +
        "org.apache.commons.httpclient.methods; " +
        "org.apache.commons.httpclient.methods.multipart; " +
        "org.apache.commons.httpclient.params; " +
        "org.apache.commons.httpclient.protocol; " +
        "org.apache.commons.httpclient.util; " +

        //OTHERS
        "org.bluez; " +
        "org.json; " +
        "org.w3c.dom; " +
        "org.xml.sax; " +
        "org.xml.sax.ext; " +
        "org.xml.sax.helpers; " +
        "net.neosum.android.view;";

}


text:
package org.apache.ignite.internal.pagemem.wal.record;

import org.apache.ignite.internal.util.tostring.GridToStringExclude;
import org.apache.ignite.internal.util.typedef.internal.S;

/**
 * Log entry abstract class.
 */
public abstract class WALRecord {
    /**
     * Record type.
     */
    public enum RecordType {
        /** */
        TX_RECORD,

        /** */
        PAGE_RECORD,

        /** */
        DATA_RECORD,

        /** */
        STORE_OPERATION_RECORD,

        /** */
        CHECKPOINT_RECORD,

        /** */
        HEADER_RECORD,

        // Delta records.

        /** */
        INIT_NEW_PAGE_RECORD,

        /** */
        DATA_PAGE_INSERT_RECORD,

        /** */
        DATA_PAGE_INSERT_FRAGMENT_RECORD,

        /** */
        DATA_PAGE_REMOVE_RECORD,

        /** */
        DATA_PAGE_SET_FREE_LIST_PAGE,

        /** */
        BTREE_META_PAGE_INIT_ROOT,

        /** */
        BTREE_META_PAGE_ADD_ROOT,

        /** */
        BTREE_META_PAGE_CUT_ROOT,

        /** */
        BTREE_INIT_NEW_ROOT,

        /** */
        BTREE_PAGE_RECYCLE,

        /** */
        BTREE_PAGE_INSERT,

        /** */
        BTREE_FIX_LEFTMOST_CHILD,

        /** */
        BTREE_FIX_COUNT,

        /** */
        BTREE_PAGE_REPLACE,

        /** */
        BTREE_PAGE_REMOVE,

        /** */
        BTREE_PAGE_INNER_REPLACE,

        /** */
        BTREE_FIX_REMOVE_ID,

        /** */
        BTREE_FORWARD_PAGE_SPLIT,

        /** */
        BTREE_EXISTING_PAGE_SPLIT,

        /** */
        BTREE_PAGE_MERGE,

        /** */
        PAGES_LIST_SET_NEXT,

        /** */
        PAGES_LIST_SET_PREVIOUS,

        /** */
        PAGES_LIST_INIT_NEW_PAGE,

        /** */
        PAGES_LIST_ADD_PAGE,

        /** */
        PAGES_LIST_REMOVE_PAGE,

        /** */
        META_PAGE_INIT,

        /** */
        PARTITION_META_PAGE_UPDATE_COUNTERS,

        /** */
        MEMORY_RECOVERY,

        /** */
        TRACKING_PAGE_DELTA,

        /** Meta page update last successful snapshot id. */
        META_PAGE_UPDATE_LAST_SUCCESSFUL_SNAPSHOT_ID,

        /** Meta page update last successful full snapshot id. */
        META_PAGE_UPDATE_LAST_SUCCESSFUL_FULL_SNAPSHOT_ID,

        /** Meta page update next snapshot id. */
        META_PAGE_UPDATE_NEXT_SNAPSHOT_ID,

        /** Meta page update last allocated index. */
        META_PAGE_UPDATE_LAST_ALLOCATED_INDEX,

        /** Partition meta update state. */
        PART_META_UPDATE_STATE,

        /** Page list meta reset count record. */
        PAGE_LIST_META_RESET_COUNT_RECORD,

        /** Switch segment record. */
        SWITCH_SEGMENT_RECORD,

        /** */
        DATA_PAGE_UPDATE_RECORD,

        /** init */
        BTREE_META_PAGE_INIT_ROOT2
        ;

        /** */
        private static final RecordType[] VALS = RecordType.values();

        /** */
        public static RecordType fromOrdinal(int ord) {
            return ord < 0 || ord >= VALS.length ? null : VALS[ord];
        }
    }

    /** */
    private int size;

    /** */
    private int chainSize;

    /** */
    @GridToStringExclude
    private WALRecord prev;

    /** */
    private long pos;

    /**
     * @param chainSize Chain size in bytes.
     */
    public void chainSize(int chainSize) {
        this.chainSize = chainSize;
    }

    /**
     * @return Get chain size in bytes.
     */
    public int chainSize() {
        return chainSize;
    }

    /**
     * @return Previous record in chain.
     */
    public WALRecord previous() {
        return prev;
    }

    /**
     * @param prev Previous record in chain.
     */
    public void previous(WALRecord prev) {
        this.prev = prev;
    }

    /**
     * @return Position in file.
     */
    public long position() {
        return pos;
    }

    /**
     * @param pos Position in file.
     */
    public void position(long pos) {
        assert pos >= 0: pos;

        this.pos = pos;
    }

    /**
     * @return Size of this record in bytes.
     */
    public int size() {
        return size;
    }

    /**
     * @param size Size of this record in bytes.
     */
    public void size(int size) {
        assert size >= 0: size;

        this.size = size;
    }

    /**
     * @return Entry type.
     */
    public abstract RecordType type();

    /** {@inheritDoc} */
    @Override public String toString() {
        return S.toString(WALRecord.class, this, "type", type());
    }
}


text:
import sys

try:
	from setuptools import setup, Extension
except ImportError:
	from distutils.core import setup, Extension

#extra_compile_args = ['-I./leveldb/include', '-fPIC', '-Wall', '-g2', '-D_GNU_SOURCE', '-O2', '-DNDEBUG']
#extra_link_args = ['-L./leveldb', '-Bstatic', '-lleveldb', '-L./snappy-read-only/.libs/', '-Bstatic', '-lsnappy']
extra_compile_args = ['-fPIC', '-Wall', '-g2', '-D_GNU_SOURCE', '-O2', '-DNDEBUG']
extra_link_args = ['-Bstatic', '-lhyperleveldb', '-Bstatic', '-lsnappy']

setup(
	name = 'hyperleveldb',
	version = '0.1',
	maintainer = 'Arni Mar Jonsson',
	maintainer_email = 'arnimarj@gmail.com',
	url = 'http://code.google.com/p/py-leveldb/',

	classifiers = [
		'Development Status :: 4 - Beta',
		'Environment :: Other Environment',
		'Intended Audience :: Developers',
		'License :: OSI Approved :: BSD License',
		'Operating System :: POSIX',
		'Programming Language :: C++',
		'Programming Language :: Python',
		'Programming Language :: Python :: 2.4',
		'Programming Language :: Python :: 2.5',
		'Programming Language :: Python :: 2.6',
		'Programming Language :: Python :: 2.7',
		'Programming Language :: Python :: 3.0',
		'Programming Language :: Python :: 3.1',
		'Programming Language :: Python :: 3.2',
		'Programming Language :: Python :: 3.3',
		'Topic :: Database',
		'Topic :: Software Development :: Libraries'
	],

	description = 'Python bindings for leveldb database library',

	packages = ['hyperleveldb'],
	package_dir = {'hyperleveldb': ''},

	ext_modules = [
		Extension('hyperleveldb',
			sources = [
				# python stuff
				'leveldb_ext.cc',
				'leveldb_object.cc',
			],
			libraries = ['stdc++'],

			extra_compile_args = extra_compile_args,
			extra_link_args = extra_link_args
		)
	]
)


text:
  Saint-Calais-du-Désert est
       un village
       localisé dans le département de Mayenne en Pays de la Loire. Elle totalisait 360 habitants en 2008.

Si vous pensez emmenager à Saint-Calais-du-Désert, vous pourrez aisément trouver une maison à acheter.

Le nombre de logements, à Saint-Calais-du-Désert, était réparti en 2011 en deux appartements et 251 maisons soit
 un marché plutôt équilibré.

À coté de Saint-Calais-du-Désert sont localisées les villes de
Pré-en-Pail à 5 km, 2 120 habitants,
Saint-Ouen-le-Brisoult à 6 km, 134 habitants,
Lignières-Orgères située à 7 km, 731 habitants,
Neuilly-le-Vendin localisée à 5 km, 364 habitants,
Saint-Aignan-de-Couptrain localisée à 4 km, 375 habitants,
Saint-Patrice-du-Désert localisée à 7 km, 181 habitants,
 entre autres. De plus, Saint-Calais-du-Désert est située à seulement 26 km de Alençon.


text:
from datetime import datetime

import numpy as np
import pandas as pd
try:
    import pandas.tseries.holiday  # noqa
except ImportError:
    pass

hcal = pd.tseries.holiday.USFederalHolidayCalendar()
# These offests currently raise a NotImplimentedError with .apply_index()
non_apply = [pd.offsets.Day(),
             pd.offsets.BYearEnd(),
             pd.offsets.BYearBegin(),
             pd.offsets.BQuarterEnd(),
             pd.offsets.BQuarterBegin(),
             pd.offsets.BMonthEnd(),
             pd.offsets.BMonthBegin(),
             pd.offsets.CustomBusinessDay(),
             pd.offsets.CustomBusinessDay(calendar=hcal),
             pd.offsets.CustomBusinessMonthBegin(calendar=hcal),
             pd.offsets.CustomBusinessMonthEnd(calendar=hcal),
             pd.offsets.CustomBusinessMonthEnd(calendar=hcal)]
other_offsets = [pd.offsets.YearEnd(), pd.offsets.YearBegin(),
                 pd.offsets.QuarterEnd(), pd.offsets.QuarterBegin(),
                 pd.offsets.MonthEnd(), pd.offsets.MonthBegin(),
                 pd.offsets.DateOffset(months=2, days=2),
                 pd.offsets.BusinessDay(), pd.offsets.SemiMonthEnd(),
                 pd.offsets.SemiMonthBegin()]
offsets = non_apply + other_offsets

class ApplyIndex(object):

    goal_time = 0.2

    params = other_offsets
    param_names = ['offset']

    def setup(self, offset):
        N = 10000
        self.rng = pd.date_range(start='1/1/2000', periods=N, freq='T')

    def time_apply_index(self, offset):
        offset.apply_index(self.rng)

class OnOffset(object):

    goal_time = 0.2

    params = offsets
    param_names = ['offset']

    def setup(self, offset):
        self.dates = [datetime(2016, m, d)
                      for m in [10, 11, 12]
                      for d in [1, 2, 3, 28, 29, 30, 31]
                      if not (m == 11 and d == 31)]

    def time_on_offset(self, offset):
        for date in self.dates:
            offset.onOffset(date)

class OffsetSeriesArithmetic(object):

    goal_time = 0.2
    params = offsets
    param_names = ['offset']

    def setup(self, offset):
        N = 1000
        rng = pd.date_range(start='1/1/2000', periods=N, freq='T')
        self.data = pd.Series(rng)

    def time_add_offset(self, offset):
        self.data + offset

class OffsetDatetimeIndexArithmetic(object):

    goal_time = 0.2
    params = offsets
    param_names = ['offset']

    def setup(self, offset):
        N = 1000
        self.data = pd.date_range(start='1/1/2000', periods=N, freq='T')

    def time_add_offset(self, offset):
        self.data + offset

class OffestDatetimeArithmetic(object):

    goal_time = 0.2
    params = offsets
    param_names = ['offset']

    def setup(self, offset):
        self.date = datetime(2011, 1, 1)
        self.dt64 = np.datetime64('2011-01-01 09:00Z')

    def time_apply(self, offset):
        offset.apply(self.date)

    def time_apply_np_dt64(self, offset):
        offset.apply(self.dt64)

    def time_add(self, offset):
        self.date + offset

    def time_add_10(self, offset):
        self.date + (10 * offset)

    def time_subtract(self, offset):
        self.date - offset

    def time_subtract_10(self, offset):
        self.date - (10 * offset)


text:
VS_SCC_LOCALPATH
----------------

Visual Studio Source Code Control Local Path.

Can be set to change the visual studio source code control local path
property.


text:
//===----------------------------------------------------------------------===//
//
//                         PelotonDB
//
// aggregator.cpp
//
// Identification: src/backend/executor/aggregator.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include <set>

#include "backend/executor/aggregator.h"
#include "backend/executor/executor_context.h"
#include "backend/common/logger.h"
#include "backend/storage/data_table.h"

namespace peloton {
namespace executor {

/*
 * Create an instance of an aggregator for the specified aggregate
 * type, column type, and result type. The object is constructed in
 * memory from the provided memrory pool.
 */
Agg *GetAggInstance(ExpressionType agg_type) {
  Agg *aggregator;

  switch (agg_type) {
    case EXPRESSION_TYPE_AGGREGATE_COUNT:
      aggregator = new CountAgg();
      break;
    case EXPRESSION_TYPE_AGGREGATE_COUNT_STAR:
      aggregator = new CountStarAgg();
      break;
    case EXPRESSION_TYPE_AGGREGATE_SUM:
      aggregator = new SumAgg();
      break;
    case EXPRESSION_TYPE_AGGREGATE_AVG:
      aggregator = new AvgAgg(false);
      break;
    case EXPRESSION_TYPE_AGGREGATE_MIN:
      aggregator = new MinAgg();
      break;
    case EXPRESSION_TYPE_AGGREGATE_MAX:
      aggregator = new MaxAgg();
      break;
    default: {
      std::string message =
          "Unknown aggregate type " + std::to_string(agg_type);
      throw UnknownTypeException(agg_type, message);
    }
  }

  return aggregator;
}

/* Handle distinct */
Agg::~Agg() {}

void Agg::Advance(const Value val) {
  if (is_distinct_) {
    // Insert a deep copy
    distinct_set_.insert(ValueFactory::Clone(val, nullptr));
  } else {
    DAdvance(val);
  }
}

Value Agg::Finalize() {
  if (is_distinct_) {
    for (auto val : distinct_set_) {
      DAdvance(val);
    }
  }
  return DFinalize();
}

/*
 * Helper method responsible for inserting the results of the aggregation
 * into a new tuple in the output tile group as well as passing through any
 * additional columns from the input tile group.
 *
 * Output tuple is projected from two tuples:
 * Left is the 'delegate' tuple, which is usually the first tuple in the group,
 * used to retrieve pass-through values;
 * Right is the tuple holding all aggregated values.
 */
bool Helper(const planner::AggregatePlan *node, Agg **aggregates,
            storage::DataTable *output_table,
            const AbstractTuple *delegate_tuple,
            executor::ExecutorContext *econtext) {
  auto schema = output_table->GetSchema();
  std::unique_ptr<storage::Tuple> tuple(new storage::Tuple(schema, true));

  /*
   * 1) Construct a vector of aggregated values
   */
  std::vector<Value> aggregate_values;
  auto &aggregate_terms = node->GetUniqueAggTerms();
  for (oid_t column_itr = 0; column_itr < aggregate_terms.size();
       column_itr++) {
    if (aggregates[column_itr] != nullptr) {
      Value final_val = aggregates[column_itr]->Finalize();
      aggregate_values.push_back(final_val);
    }
  }

  /*
   * 2) Evaluate filter predicate;
   * if fail, just return
   */
  std::unique_ptr<expression::ContainerTuple<std::vector<Value>>> aggref_tuple(
      new expression::ContainerTuple<std::vector<Value>>(&aggregate_values));

  auto predicate = node->GetPredicate();
  if (nullptr != predicate &&
      predicate->Evaluate(delegate_tuple, aggref_tuple.get(), econtext)
          .IsFalse()) {
    return true;  // Qual fails, do nothing
  }

  /*
   * 3) Construct the tuple to insert using projectInfo
   */
  node->GetProjectInfo()->Evaluate(tuple.get(), delegate_tuple,
                                   aggref_tuple.get(), econtext);

  LOG_TRACE("Tuple to Output :");
  LOG_TRACE("GROUP TUPLE :: %s", tuple->GetInfo().c_str());

  auto location =
      output_table->InsertTuple(econtext->GetTransaction(), tuple.get());
  if (location.block == INVALID_OID) {
    LOG_ERROR("Failed to insert tuple \n");
    return false;
  }

  return true;
}

//===--------------------------------------------------------------------===//
// Hash Aggregator
//===--------------------------------------------------------------------===//
HashAggregator::HashAggregator(const planner::AggregatePlan *node,
                               storage::DataTable *output_table,
                               executor::ExecutorContext *econtext,
                               size_t num_input_columns)
    : AbstractAggregator(node, output_table, econtext),
      num_input_columns(num_input_columns) {
  group_by_key_values.resize(node->GetGroupbyColIds().size(),
                             ValueFactory::GetNullValue());
}

HashAggregator::~HashAggregator() {
  for (auto entry : aggregates_map) {
    // Clean up allocated storage
    for (size_t aggno = 0; aggno < node->GetUniqueAggTerms().size(); aggno++) {
      delete entry.second->aggregates[aggno];
    }
    delete[] entry.second->aggregates;

    delete entry.second;
  }
}

bool HashAggregator::Advance(AbstractTuple *cur_tuple) {
  AggregateList *aggregate_list;

  // Configure a group-by-key and search for the required group.
  group_by_key_values.clear();
  for (oid_t column_itr = 0; column_itr < node->GetGroupbyColIds().size();
       column_itr++) {
    Value cur_tuple_val =
        cur_tuple->GetValue(node->GetGroupbyColIds()[column_itr]);
    group_by_key_values.push_back(cur_tuple_val);
  }

  auto map_itr = aggregates_map.find(group_by_key_values);

  // Group not found. Make a new entry in the hash for this new group.
  if (map_itr == aggregates_map.end()) {
    LOG_TRACE("Group-by key not found. Start a new group.");
    // Allocate new aggregate list
    aggregate_list = new AggregateList();
    aggregate_list->aggregates = new Agg *[node->GetUniqueAggTerms().size()];
    // Make a deep copy of the first tuple we meet
    for (size_t col_id = 0; col_id < num_input_columns; col_id++) {
      aggregate_list->first_tuple_values.push_back(
          ValueFactory::Clone(cur_tuple->GetValue(col_id), nullptr));
    };

    for (oid_t aggno = 0; aggno < node->GetUniqueAggTerms().size(); aggno++) {
      aggregate_list->aggregates[aggno] =
          GetAggInstance(node->GetUniqueAggTerms()[aggno].aggtype);

      bool distinct = node->GetUniqueAggTerms()[aggno].distinct;
      aggregate_list->aggregates[aggno]->SetDistinct(distinct);
    }

    aggregates_map.insert(
        HashAggregateMapType::value_type(group_by_key_values, aggregate_list));
  }
  // Otherwise, the list is the second item of the pair.
  else {
    aggregate_list = map_itr->second;
  }

  // Update the aggregation calculation
  for (oid_t aggno = 0; aggno < node->GetUniqueAggTerms().size(); aggno++) {
    auto predicate = node->GetUniqueAggTerms()[aggno].expression;
    Value value = ValueFactory::GetIntegerValue(1);
    if (predicate) {
      value = node->GetUniqueAggTerms()[aggno].expression->Evaluate(
          cur_tuple, nullptr, this->executor_context);
    }
    aggregate_list->aggregates[aggno]->Advance(value);
  }

  return true;
}

bool HashAggregator::Finalize() {
  for (auto entry : aggregates_map) {
    // Construct a container for the first tuple
    expression::ContainerTuple<std::vector<Value>> first_tuple(
        &entry.second->first_tuple_values);
    if (Helper(node, entry.second->aggregates, output_table, &first_tuple,
               this->executor_context) == false) {
      return false;
    }
  }

  return true;
}

//===--------------------------------------------------------------------===//
// Sort Aggregator
//===--------------------------------------------------------------------===//

SortedAggregator::SortedAggregator(const planner::AggregatePlan *node,
                                   storage::DataTable *output_table,
                                   executor::ExecutorContext *econtext,
                                   size_t num_input_columns)
    : AbstractAggregator(node, output_table, econtext),
      delegate_tuple_(&delegate_tuple_values_),  // Bind value vector to wrapper
                                                 // container tuple
      num_input_columns_(num_input_columns) {
  aggregates = new Agg *[node->GetUniqueAggTerms().size()];
  ::memset(aggregates, 0, sizeof(Agg *) * node->GetUniqueAggTerms().size());

  assert(delegate_tuple_values_.empty());
}

SortedAggregator::~SortedAggregator() {
  // Clean up aggregators
  for (oid_t column_itr = 0; column_itr < node->GetUniqueAggTerms().size();
       column_itr++) {
    delete aggregates[column_itr];
  }
  delete[] aggregates;
}

bool SortedAggregator::Advance(AbstractTuple *next_tuple) {
  bool start_new_agg = false;

  // Check if we are starting a new aggregate tuple
  if (delegate_tuple_values_.empty()) {  // No current group
    LOG_TRACE("Current group keys are empty!");
    start_new_agg = true;
  } else {  // Current group exists
    assert(delegate_tuple_values_.size() == num_input_columns_);
    // Check whether crossed group boundary
    for (oid_t grpColOffset = 0; grpColOffset < node->GetGroupbyColIds().size();
         grpColOffset++) {
      Value lval = next_tuple->GetValue(node->GetGroupbyColIds()[grpColOffset]);
      Value rval =
          delegate_tuple_.GetValue(node->GetGroupbyColIds()[grpColOffset]);
      bool not_equal = lval.OpNotEquals(rval).IsTrue();

      if (not_equal) {
        LOG_TRACE("Group-by columns changed.");

        // Call helper to output the current group result
        if (!Helper(node, aggregates, output_table, &delegate_tuple_,
                    this->executor_context)) {
          return false;
        }

        start_new_agg = true;
        break;
      }
    }
  }

  // If we have started a new aggregate tuple
  if (start_new_agg) {
    LOG_TRACE("Started a new group!");

    // Create aggregate
    for (oid_t aggno = 0; aggno < node->GetUniqueAggTerms().size(); aggno++) {
      // Clean up previous aggregate
      delete aggregates[aggno];
      aggregates[aggno] =
          GetAggInstance(node->GetUniqueAggTerms()[aggno].aggtype);

      bool distinct = node->GetUniqueAggTerms()[aggno].distinct;
      aggregates[aggno]->SetDistinct(distinct);
    }

    // Update delegate tuple values
    delegate_tuple_values_.clear();

    for (oid_t col_id = 0; col_id < num_input_columns_; col_id++) {
      Value val = next_tuple->GetValue(col_id);
      delegate_tuple_values_.push_back(ValueFactory::Clone(val, nullptr));
    }
  }

  // Update the aggregation calculation
  for (oid_t aggno = 0; aggno < node->GetUniqueAggTerms().size(); aggno++) {
    auto predicate = node->GetUniqueAggTerms()[aggno].expression;
    Value value = ValueFactory::GetIntegerValue(1);
    if (predicate) {
      value = node->GetUniqueAggTerms()[aggno].expression->Evaluate(
          next_tuple, nullptr, this->executor_context);
    }
    aggregates[aggno]->Advance(value);
  }

  return true;
}

bool SortedAggregator::Finalize() {
  // Call helper to output the current group result
  if (!delegate_tuple_values_.empty() &&
      !Helper(node, aggregates, output_table, &delegate_tuple_,
              this->executor_context)) {
    return false;
  }

  return true;
}

//===--------------------------------------------------------------------===//
// Plain Aggregator
//===--------------------------------------------------------------------===//
PlainAggregator::PlainAggregator(const planner::AggregatePlan *node,
                                 storage::DataTable *output_table,
                                 executor::ExecutorContext *econtext)
    : AbstractAggregator(node, output_table, econtext) {
  // allocate aggregators
  aggregates = new Agg *[node->GetUniqueAggTerms().size()];
  ::memset(aggregates, 0, sizeof(Agg *) * node->GetUniqueAggTerms().size());

  // initialize aggregators
  for (oid_t aggno = 0; aggno < node->GetUniqueAggTerms().size(); aggno++) {
    aggregates[aggno] =
        GetAggInstance(node->GetUniqueAggTerms()[aggno].aggtype);

    bool distinct = node->GetUniqueAggTerms()[aggno].distinct;
    aggregates[aggno]->SetDistinct(distinct);
  }
}

bool PlainAggregator::Advance(AbstractTuple *next_tuple) {
  // Update the aggregation calculation
  for (oid_t aggno = 0; aggno < node->GetUniqueAggTerms().size(); aggno++) {
    auto predicate = node->GetUniqueAggTerms()[aggno].expression;
    Value value = ValueFactory::GetIntegerValue(1);
    if (predicate) {
      value = node->GetUniqueAggTerms()[aggno].expression->Evaluate(
          next_tuple, nullptr, this->executor_context);
    }
    aggregates[aggno]->Advance(value);
  }
  return true;
}

bool PlainAggregator::Finalize() {
  if (!Helper(node, aggregates, output_table, nullptr,
              this->executor_context)) {
    return false;
  }

  // TODO: if no record exists in input_table, we have to output a null record
  // only when it doesn't have GROUP BY. See difference of these cases:
  //   SELECT SUM(A) FROM BBB ,   when BBB has no tuple
  //   SELECT SUM(A) FROM BBB GROUP BY C,   when BBB has no tuple

  return true;
}

PlainAggregator::~PlainAggregator() {
  // Clean up aggregators
  for (oid_t column_itr = 0; column_itr < node->GetUniqueAggTerms().size();
       column_itr++) {
    delete aggregates[column_itr];
  }

  delete[] aggregates;
}

}  // namespace executor
}  // namespace peloton


text:
package nlb

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

// HealthCheck is a nested struct in nlb response
type HealthCheck struct {
	HealthCheckEnabled        bool     `json:"HealthCheckEnabled" xml:"HealthCheckEnabled"`
	HealthCheckType           string   `json:"HealthCheckType" xml:"HealthCheckType"`
	HealthCheckConnectPort    int      `json:"HealthCheckConnectPort" xml:"HealthCheckConnectPort"`
	HealthyThreshold          int      `json:"HealthyThreshold" xml:"HealthyThreshold"`
	UnhealthyThreshold        int      `json:"UnhealthyThreshold" xml:"UnhealthyThreshold"`
	HealthCheckConnectTimeout int      `json:"HealthCheckConnectTimeout" xml:"HealthCheckConnectTimeout"`
	HealthCheckInterval       int      `json:"HealthCheckInterval" xml:"HealthCheckInterval"`
	HealthCheckDomain         string   `json:"HealthCheckDomain" xml:"HealthCheckDomain"`
	HealthCheckUrl            string   `json:"HealthCheckUrl" xml:"HealthCheckUrl"`
	HttpCheckMethod           string   `json:"HttpCheckMethod" xml:"HttpCheckMethod"`
	HealthCheckHttpCode       []string `json:"HealthCheckHttpCode" xml:"HealthCheckHttpCode"`
}


text:
package org.springframework.boot.docs.jdbc;

import javax.sql.DataSource;

import com.zaxxer.hikari.HikariDataSource;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Example configuration for configuring a simple {@link DataSource}.
 *
 * @author Stephane Nicoll
 */
public class SimpleDataSourceExample {

	/**
	 * A simple configuration that exposes dedicated settings.
	 */
	@Configuration
	static class SimpleDataSourceConfiguration {

		// tag::configuration[]
		@Bean
		@ConfigurationProperties("app.datasource")
		public HikariDataSource dataSource() {
			return DataSourceBuilder.create().type(HikariDataSource.class).build();
		}
		// end::configuration[]

	}

}


text: <label{% for attr, val in attrs if val %} {{ attr }}="{{ val }}"{% endfor %}>{{ text|raw }}</label>


text:
typedef NS_ENUM(NSInteger, GlideBorderType) {
    GlideBorderOverlay,
    GlideBorderShrink,
    GlideBorderExpand
};

@interface GlideClient (Border)

- (void) setBorderWithWidth:(NSUInteger)width color:(nonnull NSString*)color andType:(GlideBorderType)type;

@end


text:
require "cases/helper"
require 'models/developer'
require 'models/computer'

module ActiveRecord
  module ConnectionAdapters
    class Mysql2Adapter
      class ExplainTest < ActiveRecord::TestCase
        fixtures :developers

        def test_explain_for_one_query
          explain = Developer.where(:id => 1).explain
          assert_match %(EXPLAIN for: SELECT `developers`.* FROM `developers` WHERE `developers`.`id` = 1), explain
          assert_match %r(developers |.* const), explain
        end

        def test_explain_with_eager_loading
          explain = Developer.where(:id => 1).includes(:audit_logs).explain
          assert_match %(EXPLAIN for: SELECT `developers`.* FROM `developers` WHERE `developers`.`id` = 1), explain
          assert_match %r(developers |.* const), explain
          assert_match %(EXPLAIN for: SELECT `audit_logs`.* FROM `audit_logs` WHERE `audit_logs`.`developer_id` IN (1)), explain
          assert_match %r(audit_logs |.* ALL), explain
        end
      end
    end
  end
end


text:
backup_file() {
  cp a.js a.js.bak
}

restore_file() {
  cp a.js.bak a.js
}

coverage() {
  echo "-----------------------------"
  echo "restart server"
  echo "-----------------------------"
  assert_ok "$FLOW" stop
  assert_ok "$FLOW" start
  echo "-----------------------------"
  echo "root"
  echo "-----------------------------"
  assert_ok "$FLOW" batch-coverage --strip-root .
  echo "-----------------------------"
  echo "folder"
  echo "-----------------------------"
  assert_ok "$FLOW" batch-coverage --strip-root folder
  echo "-----------------------------"
  echo "cycle"
  echo "-----------------------------"
  assert_ok "$FLOW" batch-coverage --strip-root cycle
  echo "-----------------------------"
  echo "match_coverage"
  echo "-----------------------------"
  assert_ok "$FLOW" batch-coverage --strip-root match_coverage
  echo "-----------------------------"
  echo "other_folder"
  echo "-----------------------------"
  assert_ok "$FLOW" batch-coverage --strip-root other_folder
  echo "-----------------------------"
  echo "folder/subfolder"
  echo "-----------------------------"
  assert_ok "$FLOW" batch-coverage --strip-root folder/subfolder
  echo "-----------------------------"
  echo "file list"
  echo "-----------------------------"
  assert_ok "$FLOW" batch-coverage --strip-root a.js folder/d.js folder/subfolder/j.js
  echo "-----------------------------"
  echo "file and dir list"
  echo "-----------------------------"
  assert_ok "$FLOW" batch-coverage --strip-root a.js folder folder/d.js
  echo "-----------------------------"
  echo "files"
  echo "-----------------------------"
  assert_ok "$FLOW" batch-coverage --strip-root --input-file files.txt
  echo "-----------------------------"
  echo "json"
  echo "-----------------------------"
  assert_ok "$FLOW" batch-coverage --strip-root --json --pretty --input-file files.txt
  echo "-----------------------------"
  echo "root info survives recheck"
  echo "-----------------------------"
  assert_ok cp a.js.ignored a.js
  assert_ok "$FLOW" force-recheck a.js
  assert_ok "$FLOW" batch-coverage --strip-root --wait-for-recheck true .
  echo "-----------------------------"
  echo "delete file"
  echo "-----------------------------"
  assert_ok rm a.js
  assert_ok "$FLOW" batch-coverage --strip-root --wait-for-recheck true .
  echo "-----------------------------"
  echo "trust"
  echo "-----------------------------"
  assert_ok "$FLOW" stop
  assert_ok "$FLOW" start --trust-mode=check
  assert_ok "$FLOW" batch-coverage --strip-root --show-trust .
  assert_ok "$FLOW" batch-coverage --strip-root --json --pretty --show-trust .
}

backup_file

# Run in classic
echo "============================="
echo "CLASSIC"
echo "============================="

coverage > classic-coverage.log

cat classic-coverage.log

restore_file

# Run in types-first
echo "============================="
echo "TYPES-FIRST"
echo "============================="
assert_ok mv .flowconfig.types-first .flowconfig
coverage > types-first-coverage.log

echo "==== DIFF BETWEEN CLASSIC AND TYPES-FIRST ====="
assert_ok diff --strip-trailing-cr classic-coverage.log types-first-coverage.log > diff.log
cat diff.log


text:
namespace urde {

CAudioSys* CAudioSys::g_SharedSys = nullptr;
static std::unordered_map<std::string, TLockedToken<CAudioGroupSet>> mpGroupSetDB;
static std::unordered_map<CAssetId, std::string> mpGroupSetResNameDB;
static const std::string mpDefaultInvalidString = "NULL";

TLockedToken<CAudioGroupSet> CAudioSys::FindGroupSet(std::string_view name) {
  auto search = mpGroupSetDB.find(name.data());
  if (search == mpGroupSetDB.cend())
    return {};
  return search->second;
}

std::string_view CAudioSys::SysGetGroupSetName(CAssetId id) {
  auto search = mpGroupSetResNameDB.find(id);
  if (search == mpGroupSetResNameDB.cend())
    return mpDefaultInvalidString;
  return search->second;
}

bool CAudioSys::SysLoadGroupSet(CSimplePool* pool, CAssetId id) {
  if (!FindGroupSet(SysGetGroupSetName(id))) {
    TLockedToken<CAudioGroupSet> set = pool->GetObj(SObjectTag{FOURCC('AGSC'), id});
    mpGroupSetDB.emplace(std::make_pair(set->GetName(), set));
    mpGroupSetResNameDB.emplace(std::make_pair(id, set->GetName()));
    return false;
  } else {
    return true;
  }
}

bool CAudioSys::SysLoadGroupSet(const TLockedToken<CAudioGroupSet>& set, std::string_view name, CAssetId id) {
  if (!FindGroupSet(name)) {
    mpGroupSetDB.emplace(std::make_pair(set->GetName(), set));
    mpGroupSetResNameDB.emplace(std::make_pair(id, set->GetName()));
    return false;
  } else {
    return true;
  }
}

void CAudioSys::SysUnloadAudioGroupSet(std::string_view name) {
  auto set = FindGroupSet(name);
  if (!set)
    return;

  mpGroupSetDB.erase(name.data());
  mpGroupSetResNameDB.erase(set.GetObjectTag()->id);
}

bool CAudioSys::SysIsGroupSetLoaded(std::string_view name) { return FindGroupSet(name).operator bool(); }

void CAudioSys::SysAddGroupIntoAmuse(std::string_view name) {
  if (auto set = FindGroupSet(name))
    AddAudioGroup(set->GetAudioGroupData());
}

void CAudioSys::SysRemoveGroupFromAmuse(std::string_view name) {
  if (auto set = FindGroupSet(name))
    RemoveAudioGroup(set->GetAudioGroupData());
}

static float s_MasterVol = 1.f;
static float s_SfxVol = 1.f;
void CAudioSys::_UpdateVolume() { GetAmuseEngine().setVolume(s_MasterVol * s_SfxVol); }

void CAudioSys::SysSetVolume(u8 volume) {
  s_MasterVol = volume / 127.f;
  _UpdateVolume();
}

void CAudioSys::SysSetSfxVolume(u8 volume, u16 time, bool music, bool fx) {
  s_SfxVol = volume / 127.f;
  _UpdateVolume();
}

static s16 s_VolumeScale = 0x7f;
static s16 s_DefaultVolumeScale = 0x7f;

s16 CAudioSys::GetDefaultVolumeScale() { return s_DefaultVolumeScale; }

void CAudioSys::SetDefaultVolumeScale(s16 scale) { s_DefaultVolumeScale = scale; }

void CAudioSys::SetVolumeScale(s16 scale) { s_VolumeScale = scale; }

} // namespace urde


text:
using System.IO;
using Content.Shared.CCVar;
using Robust.Client.AutoGenerated;
using Robust.Client.ResourceManagement;
using Robust.Client.UserInterface.Controls;
using Robust.Client.UserInterface.XAML;
using Robust.Shared.Configuration;

namespace Content.Client.Info;

[GenerateTypedNameReferences]
public sealed partial class RulesControl : BoxContainer
{
    [Dependency] private readonly RulesManager _rules = default!;

    public RulesControl()
    {
        RobustXamlLoader.Load(this);
        IoCManager.InjectDependencies(this);
        AddChild(_rules.RulesSection());
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="content-type" content="text/html; charset=utf-8" >
<title>Silicon Valley 2013
 -  Proposal</title>
<meta name="author" content="Javier Turegano" >

<link rel="alternate" type="application/rss+xml" title="devopsdays RSS Feed" href="http://www.devopsdays.org/feed/" >

<link rel="stylesheet" href="/css/devops.min.css" type="text/css" media="screen, projection">
<link rel="stylesheet" href="/css/blueprint/print.css" type="text/css" media="print">

      Home

      Contact

      Events

      Presentations

      Blog

Silicon Valley 2013
 -  Proposal

Gold sponsors

welcome
propose
program
location
register
sponsor
contact

Back to proposals overview - program

The Devops Journey that Transformed REA

Abstract:

REA group, which runs between others realestate.com.au, casa.it and
athome.lu websites focused on realestate advertising in different
countries, has been involved in an interesting transformation process
following the Devops principles in the last years that has changed
completely the way we face operations.

From completed isolated worlds, delivery and operations, to a much
more efficient approach which continues to evolve every day in this
talk we will cover some of the key elements for this transformation
including cultural and technical aspects that helped us during the
journey and which ones made it hard.

Speaker:

Javier Turegano is working as infrastructure manager in REA Group in
Australia where he manages the Infrastructure Platform team and has
been involved in the transformation of the company's operations in the
last year. Previously helped to create an architecture team and leaded
infrastructure projects in Andago, Spanish open source company focused
on public administration and leaded the sysadmin team in an emerging
ISP in his home city.

His passions are open source, web operations, devops and IT management
and keeps himself active in the communities associated with those
topics (Madrid Devops, Melbourne's Infrastructure Coders and founded
the Linux Albacete LUG during my university period)

Please enable JavaScript to view the comments powered by Disqus.
blog comments powered by Disqus

Special sponsors

Gold sponsors

Silver sponsors

Media sponsors


text:
template <typename Service, bool expect_connection>
class ScopedConnectionCheckerBase {
 public:
  explicit ScopedConnectionCheckerBase(
      sys::OutgoingDirectory* outgoing_directory) {
    zx_status_t status = outgoing_directory->AddPublicService(
        std::make_unique<vfs::Service>(
            [this](zx::channel channel, async_dispatcher_t*) {
              pending_channels_.push_back(std::move(channel));
            }),
        std::string(Service::Name_));

    ZX_CHECK(status == ZX_OK, status) << "OutgoingDirectory::AddPublicService";
  }

  ~ScopedConnectionCheckerBase() {
    if ((expect_connection && pending_channels_.empty()) ||
        (!expect_connection && !pending_channels_.empty())) {
      ADD_FAILURE();
    }
  }

  ScopedConnectionCheckerBase(const ScopedConnectionCheckerBase&) = delete;
  ScopedConnectionCheckerBase& operator=(const ScopedConnectionCheckerBase&) =
      delete;

 private:
  // Client channels are held in a pending (unconnected) state for the
  // lifetime of |this|, so that the client never sees a disconnection event.
  std::vector<zx::channel> pending_channels_;
};

// Checks that no client attempted to connect to |Service|.
template <typename Service>
using NeverConnectedChecker = ScopedConnectionCheckerBase<Service, false>;

// Checks that at least one client attempted to connect to |Service|.
template <typename Service>
using EnsureConnectedChecker = ScopedConnectionCheckerBase<Service, true>;

#endif  // FUCHSIA_WEB_WEBENGINE_TEST_SCOPED_CONNECTION_CHECKER_H_


text:
<?php

namespace Majora\Framework\Model;

use Doctrine\Common\Collections\Collection;

/**
 * Trait for collectionable objects.
 */
trait CollectionableTrait
{
    /**
     * helper method to use for cast arrays to
     * collections of entities.
     *
     * @param Collection|array $data
     * @param string           $collectionClass
     *
     * @return EntityCollection
     */
    protected function toCollection($data, $collectionClass)
    {
        if ($data instanceof $collectionClass) {
            return $data;
        }

        $data = $data ?: array();
        if (!is_array($data) && !$data instanceof Collection) {
            throw new \InvalidArgumentException('Can transform only Collections or arrays.');
        }

        return new $collectionClass(
            is_array($data) ? $data : $data->toArray()
        );
    }
}


text:
#include "vice.h"

#ifdef HAVE_PARSID
#include <windows.h>
#include <fcntl.h>
#include <stdio.h>
#include <conio.h>
#include <assert.h>

#include "alarm.h"
#include "parsid.h"
#include "log.h"
#include "sid-resources.h"
#include "types.h"

/* control register bits */
#define parsid_STROBE   0x01
#define parsid_AUTOFEED 0x02
#define parsid_nINIT    0x04
#define parsid_SELECTIN 0x08
#define parsid_PCD      0x20

static unsigned short parsid_ctrport;
static int parsid_use_lib = 0;
static int parsid_port_address[4];

#define sleep(x) Sleep(x * 1000)

#ifndef MSVC_RC
typedef short _stdcall (*inpfuncPtr)(short portaddr);
typedef void _stdcall (*oupfuncPtr)(short portaddr, short datum);

inpfuncPtr inp32fp;
oupfuncPtr oup32fp;
#else
typedef short (CALLBACK* Inp32_t)(short);
typedef void (CALLBACK* Out32_t)(short, short);

static Inp32_t Inp32;
static Out32_t Out32;
#endif

/* input/output functions */
static void parsid_outb(unsigned int addrint, short value)
{
    WORD addr = (WORD)addrint;

    /* make sure the above conversion did not loose any details */
    assert(addr == addrint);

    if (parsid_use_lib) {
#ifndef MSVC_RC
        (oup32fp)(addr, value);
#else
        Out32(addr, value);
#endif
    } else {
#ifdef  _M_IX86
        _outp(addr, value);
#endif
    }
}

static short parsid_inb(unsigned int addrint)
{
    WORD addr = (WORD)addrint;

    /* make sure the above conversion did not loose any details */
    assert(addr == addrint);

    if (parsid_use_lib) {
#ifndef MSVC_RC
        return (inp32fp)(addr);
#else
        return Inp32(addr);
#endif
    } else {
#ifdef  _M_IX86
        return _inp(addr);
#endif
    }
}

/* pin functions */
static void parsid_chip_select(void)
{
    parsid_ctrport |= parsid_STROBE;
    parsid_outb(parsid_port_address[parsid_port] + 2, parsid_ctrport);
}

static void parsid_chip_deselect(void)
{
    parsid_ctrport &= ~parsid_STROBE;
    parsid_outb(parsid_port_address[parsid_port] + 2, parsid_ctrport);
}

static void parsid_reset_start(void)
{
    parsid_ctrport |= parsid_SELECTIN;
    parsid_outb(parsid_port_address[parsid_port] + 2, parsid_ctrport);
}

static void parsid_reset_end(void)
{
    parsid_ctrport &= ~parsid_SELECTIN;
    parsid_outb(parsid_port_address[parsid_port] + 2, parsid_ctrport);
}

static void parsid_latch_open(void)
{
    parsid_ctrport &= ~parsid_AUTOFEED;
    parsid_outb(parsid_port_address[parsid_port] + 2, parsid_ctrport);
}

static void parsid_latch_lock(void)
{
    parsid_ctrport |= parsid_AUTOFEED;
    parsid_outb(parsid_port_address[parsid_port] + 2, parsid_ctrport);
}

static void parsid_RW_write(void)
{
    parsid_ctrport &= ~parsid_nINIT;
    parsid_outb(parsid_port_address[parsid_port] + 2, parsid_ctrport);
}

static void parsid_RW_read(void)
{
    parsid_ctrport |= parsid_nINIT;
    parsid_outb(parsid_port_address[parsid_port] + 2, parsid_ctrport);
}

/* parallel port direction control */
static void parsid_port_write(void)
{
    parsid_ctrport &= ~parsid_PCD;
    parsid_outb(parsid_port_address[parsid_port] + 2, parsid_ctrport);
}

static void parsid_port_read(void)
{
    parsid_ctrport |= parsid_PCD;
    parsid_outb(parsid_port_address[parsid_port] + 2, parsid_ctrport);
}

#define TEST_WINDOWS_NT (!(GetVersion() & 0x80000000))

/*----------------------------------------------------------------------*/

static void parsid_sidwait(void)
{
}

/* original code by Peter Burke, modified by me. */
static int parsid_GetParallelControllerKey(char *parKey)
{
    HKEY hKey, hKey1, hKey2;
    char myData[255];
    LONG res;
    DWORD mySize, dwIndex1, dwIndex2, dwIndex3;
    FILETIME ftLastWriteTime;
    char myKey[255], myKey1[255], myKey2[255];

    if (NULL == parKey) {
        return -1;
    }

    *parKey = 0;

    sprintf(myKey, "HARDWARE\\DESCRIPTION\\System");

    res = RegOpenKeyEx(HKEY_LOCAL_MACHINE, myKey, 0, KEY_READ, &hKey);

    if (res != ERROR_SUCCESS) {
        return -1;
    }

    for (dwIndex1 = 0; dwIndex1 <= 10; dwIndex1++) {
        mySize = sizeof(myData);
        res = RegEnumKeyEx(hKey, dwIndex1, myData, &mySize, NULL, NULL, NULL, &ftLastWriteTime);

        if (res == ERROR_SUCCESS) {
            strcpy(myKey1, myKey);
            strcat(myKey1, "\\");
            strcat(myKey1, myData);

            res = RegOpenKeyEx(HKEY_LOCAL_MACHINE, myKey1, 0, KEY_READ, &hKey1);

            if (res != ERROR_SUCCESS) {
                return -1;
            }

            for (dwIndex2 = 0; dwIndex2 <= 10; dwIndex2++) {
                mySize = sizeof(myData);
                res = RegEnumKeyEx(hKey1, dwIndex2, myData, &mySize, NULL, NULL, NULL, &ftLastWriteTime);

                if (res == ERROR_SUCCESS) {
                    strcpy(myKey2, myKey1);
                    strcat(myKey2, "\\");
                    strcat(myKey2, myData);

                    res = RegOpenKeyEx(HKEY_LOCAL_MACHINE, myKey2, 0, KEY_READ, &hKey2);

                    if (res != ERROR_SUCCESS) {
                        return -1;
                    }

                    for (dwIndex3 = 0; dwIndex3 <= 10; dwIndex3++) {
                        mySize = sizeof(myData);
                        res = RegEnumKeyEx(hKey2, dwIndex3, myData, &mySize, NULL, NULL, NULL, &ftLastWriteTime);

                        if (res == ERROR_SUCCESS) {
                            if (0 == strcmp(myData, "ParallelController")) {
                                strcpy(parKey, myKey2);
                                strcat(parKey, "\\");
                                strcat(parKey, myData);
                                return 0;
                            }
                        }
                    }
                }
            }
        }
    }
    return -1;
}

static int parsid_GetAddressLptPortInTheRegistry(int myPort)
{
    HKEY phkResult;
    char myKey[255], myData[255];
    LONG res;
    DWORD mySize, myType;

    res = parsid_GetParallelControllerKey(myKey);
    if (res < 0) {
        return -1;
    }

    sprintf(myData, "%s\\%d", myKey, myPort - 1);

    res = RegOpenKeyEx(HKEY_LOCAL_MACHINE, myData, 0, KEY_READ, &phkResult);
    if (res != ERROR_SUCCESS) {
        return -1;
    }

    mySize = sizeof(myData);
    myType = REG_BINARY;

    res = RegQueryValueEx(phkResult, "Configuration Data", NULL, &myType, (unsigned char *)myData, &mySize);
    if (res != ERROR_SUCCESS) {
        return -1;
    }

    return (myData[0x14] | myData[0x15] << 8);
}

typedef BOOL (CALLBACK * PROCTYPE_Toolhelp32ReadProcessMemory)(DWORD, LPCVOID, LPVOID, DWORD, LPDWORD);

static int parsid_GetAddressLptPortInTheMemory(int myPort)
{
    HINSTANCE hDLL = NULL;
    PROCTYPE_Toolhelp32ReadProcessMemory myProcPointer = NULL;
    int portAddresses[] = { 0, 0, 0, 0, 0 };
    BOOL rtn = 0;
    DWORD cbLen = 0;

    hDLL = LoadLibrary("kernel32");
    if (hDLL == NULL) {
        return -1;
    }

    myProcPointer = (PROCTYPE_Toolhelp32ReadProcessMemory)GetProcAddress(hDLL, "Toolhelp32ReadProcessMemory");
    if (myProcPointer == NULL) {
        FreeLibrary(hDLL);
        return -1;
    }

    rtn = myProcPointer(0, (LPCVOID *)0x408, portAddresses, 8, NULL);
    FreeLibrary(hDLL);

    if (rtn == 0) {
        return -1;
    }

    if (portAddresses[myPort - 1] <= 0 || portAddresses[myPort - 1] >= 0x1000) {
        return -1;
    }

    return portAddresses[myPort - 1];
}

static int parsid_GetAddressLptPort(int myPort)
{
    if (myPort < 1 || myPort > 3) {
        return -1;
    }

    if (!(GetVersion() & 0x80000000)) {
        return parsid_GetAddressLptPortInTheRegistry(myPort);
    }
    return parsid_GetAddressLptPortInTheMemory(myPort);
}

/*----------------------------------------------------------------------*/

int parsid_check_port(int port)
{
    if (port < 1 || port > 3) {
        return -1;
    }

    if (parsid_port_address[port - 1] <= 0) {
        return -1;
    }

    return 0;
}

HINSTANCE hLib = NULL;

static int parsid_init(void)
{
    int j;
    int ports = 0;

    if (hLib == NULL) {
        hLib = LoadLibrary("inpout32.dll");
    }

    parsid_use_lib = 0;

    if (hLib != NULL) {
#ifndef MSVC_RC
        inp32fp = (inpfuncPtr)GetProcAddress(hLib, "Inp32");
        if (inp32fp != NULL) {
            oup32fp = (oupfuncPtr)GetProcAddress(hLib, "Out32");
            if (oup32fp != NULL) {
                parsid_use_lib = 1;
            }
        }
#else
        Inp32 = (Inp32_t)GetProcAddress(hLib, "Inp32");
        if (Inp32 != NULL) {
            Out32 = (Out32_t)GetProcAddress(hLib, "Out32");
            if (Out32 != NULL) {
                parsid_use_lib = 1;
            }
        }
#endif
    }

    for (j = 0; j < 3; j++) {
        parsid_port_address[j] = parsid_GetAddressLptPort(j + 1);
        if (parsid_port_address[j] > 0) {
            ports++;
        }
    }
    if (ports == 0) {
        return -1;
    }

    if (!(GetVersion() & 0x80000000) && parsid_use_lib == 0) {
        return -1;
    }

    parsid_ctrport = parsid_inb(parsid_port_address[parsid_port] + 2);
    return 0;
}

void parsid_reset(void)
{
    parsid_RW_write();
    parsid_port_write();
    parsid_chip_select();
    parsid_latch_open();
    parsid_outb(parsid_port_address[parsid_port], 0);
    parsid_reset_start();
    sleep(1);
    parsid_reset_end();
    parsid_latch_lock();
    parsid_chip_deselect();
}

int parsid_open(int port)
{
    if (parsid_init() < 0) {
        return -1;
    }
    if (parsid_check_port(port) < 0) {
        return -1;
    }
    parsid_reset();
    return 0;
}

int parsid_close(void)
{
    parsid_reset();
    if (parsid_use_lib) {
       FreeLibrary(hLib);
       hLib = NULL;
    }
    return 0;
}

int parsid_read(WORD addr, int chipno)
{
    int value;

    parsid_outb(parsid_port_address[parsid_port], addr);
    parsid_latch_open();
    parsid_sidwait();
    parsid_latch_lock();
    parsid_port_read();
    parsid_RW_read();
    parsid_chip_select();
    parsid_sidwait();
    value = parsid_inb(parsid_port_address[parsid_port]);
    parsid_chip_deselect();
    return value;
}

void parsid_store(WORD addr, BYTE outval, int chipno)
{
    parsid_outb(parsid_port_address[parsid_port], addr);
    parsid_latch_open();
    parsid_sidwait();
    parsid_latch_lock();
    parsid_outb(parsid_port_address[parsid_port], outval);
    parsid_chip_select();
    parsid_sidwait();
    parsid_chip_deselect();
}
#endif


text:
namespace blackhole {
inline namespace v1 {
namespace sink {
namespace socket {

udp_t::udp_t(const std::string& host, std::uint16_t port) :
    socket(io_service)
{
    boost::asio::ip::udp::resolver resolver(io_service);
    boost::asio::ip::udp::resolver::query query(host, boost::lexical_cast<std::string>(port),
        boost::asio::ip::udp::resolver::query::flags::numeric_service);
    endpoint_ = *resolver.resolve(query);

    socket.open(endpoint_.protocol());
}

auto udp_t::endpoint() const -> const endpoint_type& {
    return endpoint_;
}

auto udp_t::emit(const record_t&, const string_view& formatted) -> void {
    socket.send_to(boost::asio::buffer(formatted.data(), formatted.size()), endpoint_);
}

}  // namespace socket
}  // namespace sink

using sink::socket::udp_t;

using util::value_or;

auto factory<udp_t>::type() const noexcept -> const char* {
    return "udp";
}

auto factory<udp_t>::from(const config::node_t& config) const -> std::unique_ptr<sink_t> {
    (void)registry;
    const auto host = value_or(config["host"].to_string(), []() -> std::string {
        throw std::invalid_argument(R"(parameter "host" is required)");
    });

    const auto port = value_or(config["port"].to_uint64(), []() -> std::uint64_t {
        throw std::invalid_argument(R"(parameter "port" is required)");
    });

    return blackhole::make_unique<udp_t>(host, static_cast<std::uint16_t>(port));
}

}  // namespace v1
}  // namespace blackhole


text:
// Copyright 2013 ESRI
//
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
//
// You may freely redistribute and use this sample code, with or
// without modification, provided you include the original copyright
// notice and use restrictions.
//
// See the use restrictions http://help.arcgis.com/en/sdk/10.0/usageRestrictions.htm.
//
using System;
using System.Windows;
using System.Windows.Controls;
using System.ComponentModel.Composition;
using System.Runtime.Serialization;
using ESRI.ArcGIS.OperationsDashboard;

namespace OperationsDashboardAddIns
{
  [Export("ESRI.ArcGIS.OperationsDashboard.MapTool")]
  [ExportMetadata("DisplayName", "Zoom In/out")]
  [ExportMetadata("Description", "Custom zoom to extent map tool")]
  [ExportMetadata("ImagePath", "/OperationsDashboardAddIns;component/Images/ZoomBox16.png")]
  [DataContract]
  public partial class ZoomExtentMapTool : UserControl, IMapTool
  {
    // This map tool uses a custom toolbar to help implement cancelation.
    private CancelationToolbar _cancelToolbar = null;

    public ZoomExtentMapTool()
    {
      InitializeComponent();
    }

    #region IMapTool
    // IMapTool MapWidget property just saves a reference to the map that the tool is hosted in.
    public MapWidget MapWidget { get; set; }

    public void OnActivated()
    {
      // No actions required when this tool is activated.
    }

    public void OnDeactivated()
    {
      // Clean up any objects if still set.
      if (_cancelToolbar != null)
      {
        _cancelToolbar = null;
      }
    }

    public bool CanConfigure
    {
      // No configuration required for this tool.
      get { return false; }
    }

    public bool Configure(System.Windows.Window owner)
    {
      // Not implemented as CanConfigure returned false.
      throw new NotImplementedException();
    }
    #endregion

    private void Button_Click(object sender, RoutedEventArgs e)
    {
      // When the user clicks the map tool button, begin installing zoom code.
      // Ensure the tool has a valid map to work with.
      if ((MapWidget != null) && (MapWidget.Map != null))
      {
        // Provide a way for the user to cancel the operation, by installing a temporary toolbar.
        // This also prevents other tools from being used in the meantime.
        _cancelToolbar = new CancelationToolbar(MapWidget);
        MapWidget.SetToolbar(_cancelToolbar);
      }

    }
  }
}


text:
package org.axonframework.messaging.interceptors;

import org.axonframework.messaging.InterceptorChain;
import org.axonframework.messaging.Message;
import org.axonframework.messaging.MessageDispatchInterceptor;
import org.axonframework.messaging.MessageHandlerInterceptor;
import org.axonframework.messaging.unitofwork.UnitOfWork;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.function.BiFunction;
import javax.annotation.Nonnull;

import static java.lang.String.format;

/**
 * {@link MessageDispatchInterceptor} and {@link MessageHandlerInterceptor} implementation that logs dispatched and
 * incoming messages, and their result, to a SLF4J logger. Allows configuration of the name under which the logger
 * should log the statements.
 * <p/>
 * Dispatched, incoming messages and successful executions are logged at the {@code INFO} level. Processing errors are
 * logged using the {@code WARN} level.
 *
 * @author Allard Buijze
 * @since 0.6
 */
public class LoggingInterceptor<T extends Message<?>>
        implements MessageDispatchInterceptor<T>, MessageHandlerInterceptor<T> {

    private final Logger logger;

    /**
     * Initialize the LoggingInterceptor with the given {@code loggerName}. The actual logging implementation will
     * use this name to decide the appropriate log level and location. See the documentation of your logging
     * implementation for more information.
     *
     * @param loggerName the name of the logger
     */
    public LoggingInterceptor(String loggerName) {
        this.logger = LoggerFactory.getLogger(loggerName);
    }

    /**
     * Initialize the LoggingInterceptor with the default logger name, which is the fully qualified class name of this
     * logger.
     *
     * @see LoggingInterceptor#LoggingInterceptor(String)
     */
    public LoggingInterceptor() {
        this.logger = LoggerFactory.getLogger(LoggingInterceptor.class);
    }

    @Override
    @Nonnull
    public BiFunction<Integer, T, T> handle(@Nonnull List<? extends T> messages) {
        return (i, message) -> {
            logger.info("Dispatched messages: [{}]", message.getPayloadType().getSimpleName());
            return message;
        };
    }

    @Override
    public Object handle(@Nonnull UnitOfWork<? extends T> unitOfWork, @Nonnull InterceptorChain interceptorChain)
            throws Exception {
        T message = unitOfWork.getMessage();
        logger.info("Incoming message: [{}]", message.getPayloadType().getSimpleName());
        try {
            Object returnValue = interceptorChain.proceed();
            logger.info("[{}] executed successfully with a [{}] return value",
                        message.getPayloadType().getSimpleName(),
                        returnValue == null ? "null" : returnValue.getClass().getSimpleName());
            return returnValue;
        } catch (Exception t) {
            logger.warn(format("[%s] execution failed:", message.getPayloadType().getSimpleName()), t);
            throw t;
        }
    }
}


text:
from __future__ import unicode_literals
import time
from netmiko.base_connection import BaseConnection

class F5LtmSSH(BaseConnection):

    def session_preparation(self):
        """Prepare the session after the connection has been established."""
        delay_factor = self.select_delay_factor(delay_factor=0)
        self._test_channel_read()
        self.set_base_prompt()
        command = "{}set length 0{}".format(self.RETURN, self.RETURN)
        self.disable_paging(command=command)
        time.sleep(1 * delay_factor)
        self.tmsh_mode()
        self.set_base_prompt()
        # Clear the read buffer
        time.sleep(.3 * self.global_delay_factor)
        self.clear_buffer()

    def tmsh_mode(self, delay_factor=1):
        """tmsh command is equivalent to config command on F5."""
        delay_factor = self.select_delay_factor(delay_factor)
        self.clear_buffer()
        command = "{}tmsh{}".format(self.RETURN, self.RETURN)
        self.write_channel(command)
        time.sleep(1 * delay_factor)
        self.clear_buffer()
        return None