text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Portfolio – Emma Grisot</title>

    <link rel="stylesheet" href="css/bootstrap.min.css" type="text/css">

    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
    <link href="https://fonts.googleapis.com/css?family=Oswald:500" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Cutive+Mono" rel="stylesheet">
    <link href='https://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="font-awesome/css/font-awesome.min.css" type="text/css">

    <link rel="stylesheet" href="css/magnific-popup.css" type="text/css">

    <link rel="stylesheet" href="css/creative.css" type="text/css">

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Emma Grisot

                        Portfolio

                        About

TANOSHI

Student project
Redesign of the visual identity of a Tanoshi product (japanese brand).
Creation of a physically interactive packaging.
Paperwork allowing the packaging to have a second life.

Moodboard

Pattern repetition - chinese ink

Typographic research

Interaction

Prototype of the final product

Presentation book with japanese binding

© Tous droits réservés. Emma Grisot 2017


text:
<?php

namespace root\server\sys\srv\tipo_sanguineo\controller;

class TipoSanguineoCtrl {
    use pesquisar;
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

/**
 * Logout action
 */
module.exports = function (req, res){
  connectorLock.cycle.logout(req, res);
};


text:
// Write a function that returns the index of the first element in array that is bigger than its neighbors,
// or -1, if there's no such element.
// Use the function from the previous exercise.
function firstElementThatIsBiggerThanTwoNeighbors(arr) {
    for (var i = 1; i < arr.length - 1; i++) {
        var result = biggerThanTwoNeighbors(arr, i);
        if (result > 0) {
            return result;
        }
    }

    return -1;
}

function biggerThanTwoNeighbors(arr, position) {
    if (position < 0 || position >= arr.length) {
        return -1;
    }
    else if (position + 1 < arr.length && position - 1 >= 0) {
        var leftElement = arr[position - 1];
        var rightElement = arr[position + 1];
        if (arr[position] > leftElement && arr[position] > rightElement) {
            return position;
        }
        else {
            return -2;
        }
    }
    return -1;
}
var arr = [1, 1, 2, 155, 4, 7, 1, 76, 18];
var result = firstElementThatIsBiggerThanTwoNeighbors(arr);
console.log(result);


text:
Inline HTML Heading {MD033}

More inline HTML {MD033}
but this time on multiple lines

This shouldn't trigger as it's inside a code block

```text
<p>Neither should this as it's also in a code block {MD046:11}</p>
```

## Elements in code spans

Text `<code>` text \` text
Text \` text `` text
Text \` text \` text `<code>` text
Text \` text `` text `` text
Text \` text `` text \` text `<code>` text
Text \`\` text `<code>` text
Text `<code>` text \` text `` text

## Elements in multiple line code spans

Text `code
<element/>`

`code
<element/>`

`code
<element/>` text

Text `code
code
<element/>
<element/>`

``code ``` ```` `
code
``

Text `code
</element>
code` text

Text `code code
code <element>` text

Text `code <element>
code code` text

Text `code code
code <element> code
code code` text

Text ````code code
code <element> code
code code```` text

Text `code code
code <element>` text
text `code code
code code` text

Text `code code
code code` text
text `code code
code <element>` text

Text `code code
code <element>` text
text `code code
code <element>` text

Text `code code
code` text <element> text `code {MD033}
code code` text

## Slash in element name

Text **\<base directory>\another\directory\\<slash/directory>** text

## Self-closing elements

 {MD033}

 {MD033}

## Links

Google {MD033}

Google {MD033}

Google {MD033}

## Unterminated code span followed by element in code span

Text text `text text

Text `<element>` text

Text
text `text
text

Text `code <element> code` text

Text `code <element ` `attribute="value"/> code` text {MD038}

```lang
code {MD046:114}

<element>
```

Text `code <element> code` text

Text <element> text {MD033}


text:
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010-2013 FUJIWARA, Yusuke
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
//
#endregion -- License Terms --
#if !UNITY_IOS
using System;
using System.Linq;
using System.Reflection.Emit;
using MsgPack.Serialization.Reflection;

namespace MsgPack.Serialization.EmittingSerializers
{
	/// <summary>
	///		Implements common features code generation based serializer builders.
	/// </summary>
	/// <typeparam name="TObject">The type of the serialization target.</typeparam>
	internal abstract class EmittingSerializerBuilder<TObject> : SerializerBuilder<TObject>
	{
		private readonly EmitterFlavor _emitterFlavor;

		private SerializationMethodGeneratorManager _generatorManager;

		internal SerializationMethodGeneratorManager GeneratorManager
		{
			get { return this._generatorManager; }
			set { this._generatorManager = value; }
		}

		/// <summary>
		///		Initializes a new instance of the <see cref="EmittingSerializerBuilder<TObject>"/> class.
		/// </summary>
		/// <param name="context">The <see cref="SerializationContext"/>.</param>
		protected EmittingSerializerBuilder( SerializationContext context )
			: base( context )
		{
			this._emitterFlavor = context.EmitterFlavor;
			this._generatorManager = SerializationMethodGeneratorManager.Get( context.GeneratorOption );
		}

		/// <summary>
		///		Creates serializer for <typeparamref name="TObject"/>.
		/// </summary>
		/// <param name="entries">Serialization target members. This will not be <c>null</c> nor empty.</param>
		/// <returns>
		///		<see cref="MessagePackSerializer{T}"/>. This value will not be <c>null</c>.
		/// </returns>
		protected sealed override MessagePackSerializer<TObject> CreateSerializer( SerializingMember[] entries )
		{
			using ( var emitter = this._generatorManager.CreateEmitter( typeof( TObject ), this._emitterFlavor ) )
			{
				try
				{
					var packerIL = emitter.GetPackToMethodILGenerator();
					try
					{
						if ( typeof( IPackable ).IsAssignableFrom( typeof( TObject ) ) )
						{
							if ( typeof( TObject ).IsValueType )
							{
								packerIL.EmitAnyLdarga( 2 );
							}
							else
							{
								packerIL.EmitAnyLdarg( 2 );
							}

							packerIL.EmitAnyLdarg( 1 );
							packerIL.EmitLdnull();

							packerIL.EmitCall( typeof( TObject ).GetInterfaceMap( typeof( IPackable ) ).TargetMethods.Single() );
							packerIL.EmitRet();
						}
						else
						{
							this.EmitPackMembers( emitter, packerIL, entries );
						}
					}
					finally
					{
						packerIL.FlushTrace();
					}

					var unpackerIL = emitter.GetUnpackFromMethodILGenerator();
					try
					{
						// TODO: For big struct, use Dictionary<String,SM>
						var result = unpackerIL.DeclareLocal( typeof( TObject ), "result" );
						Emittion.EmitConstruction( unpackerIL, result, null );

						if ( typeof( IUnpackable ).IsAssignableFrom( typeof( TObject ) ) )
						{
							if ( typeof( TObject ).GetIsValueType() )
							{
								unpackerIL.EmitAnyLdloca( result );
							}
							else
							{
								unpackerIL.EmitAnyLdloc( result );
							}

							unpackerIL.EmitAnyLdarg( 1 );
							unpackerIL.EmitCall( typeof( TObject ).GetInterfaceMap( typeof( IUnpackable ) ).TargetMethods.Single() );
						}
						else
						{
							EmitUnpackMembers( emitter, unpackerIL, entries, result );
						}

						unpackerIL.EmitAnyLdloc( result );
						unpackerIL.EmitRet();
					}
					finally
					{
						unpackerIL.FlushTrace();
					}

					return emitter.CreateInstance<TObject>( this.Context );
				}
				finally
				{
					emitter.FlushTrace();
				}
			}
		}

		/// <summary>
		///		Emits the ILs to pack the members of the current type.
		/// </summary>
		/// <param name="emitter"><see cref="SerializerEmitter"/> holding emittion context information.</param>
		/// <param name="packerIL"><see cref="TracingILGenerator"/> to emit IL.</param>
		/// <param name="entries">The array of <see cref="SerializingMember"/>s where each represents the member to be (de)serialized.</param>
		protected abstract void EmitPackMembers( SerializerEmitter emitter, TracingILGenerator packerIL, SerializingMember[] entries );

		private static void EmitUnpackMembers( SerializerEmitter emitter, TracingILGenerator unpackerIL, SerializingMember[] entries, LocalBuilder result )
		{
			/*
			 * #if T is IUnpackable
			 *  result.UnpackFromMessage( unpacker );
			 * #else
			 *	if( unpacker.IsArrayHeader )
			 *	{
			 *		...
			 *	}
			 *	else
			 *	{
			 *		...
			 *	}
			 * #endif
			 */

			var localHolder = new LocalVariableHolder( unpackerIL );

			unpackerIL.EmitAnyLdarg( 1 );
			unpackerIL.EmitGetProperty( Metadata._Unpacker.IsArrayHeader );
			var @else = unpackerIL.DefineLabel( "ELSE" );
			var endif = unpackerIL.DefineLabel( "END_IF" );
			unpackerIL.EmitBrfalse( @else );
			EmitUnpackMembersFromArray( emitter, unpackerIL, entries, result, localHolder, endif );
			unpackerIL.EmitBr( endif );
			unpackerIL.MarkLabel( @else );
			EmitUnpackMembersFromMap( emitter, unpackerIL, entries, result, localHolder );
			unpackerIL.MarkLabel( endif );
		}

		private static void EmitUnpackMembersFromArray( SerializerEmitter emitter, TracingILGenerator unpackerIL, SerializingMember[] entries, LocalBuilder result, LocalVariableHolder localHolder, Label endOfDeserialization )
		{
			/*
			 *  int unpacked = 0;
			 *  int itemsCount = unpacker.ItemsCount;
			 *
			 *  :
			 *  if( unpacked >= itemsCount )
			 *  {
			 *		HandleNilImplication(...);
			 *  }
			 *  else
			 *  {
			 *  #if PRIMITIVE
			 *		if( !unpacker.ReadT( out local1 ) )
			 *		{
			 *			throw SerializationExceptions.NewUnexpectedEndOfStreamMethod();
			 *		}
			 *  #else
			 *		if( !unpacker.Read() )
			 *		{
			 *			throw SerializationExceptions.NewUnexpectedEndOfStreamMethod();
			 *		}
			 *
			 *		local1 = this._serializer1.Unpack
			 *	#endif
			 *		unpacked++;
			 *	}
			 *	:
			 */

			// TODO: Supports ExtensionObject like round-tripping.

			var itemsCount = localHolder.ItemsCount;
			var unpacked = unpackerIL.DeclareLocal( typeof( int ), "unpacked" );
			Emittion.EmitGetUnpackerItemsCountAsInt32( unpackerIL, 1, localHolder );
			unpackerIL.EmitAnyStloc( itemsCount );

			for ( int i = 0; i < entries.Length; i++ )
			{
				var endIf0 = unpackerIL.DefineLabel( "END_IF" );
				var else0 = unpackerIL.DefineLabel( "ELSE" );

				unpackerIL.EmitAnyLdloc( unpacked );
				unpackerIL.EmitAnyLdloc( itemsCount );
				unpackerIL.EmitBge( else0 );

				if ( entries[ i ].Member == null )
				{
					Emittion.EmitGeneralRead( unpackerIL, 1 );
					// Ignore undefined member -- Nop.
				}
				else if ( UnpackHelpers.IsReadOnlyAppendableCollectionMember( entries[ i ].Member ) )
				{
					Emittion.EmitDeserializeCollectionValue(
						emitter,
						unpackerIL,
						1,
						result,
						entries[ i ].Member,
						entries[ i ].Member.GetMemberValueType(),
						entries[ i ].Contract.NilImplication,
						localHolder
					);
				}
				else
				{
					Emittion.EmitDeserializeValue(
						emitter,
						unpackerIL,
						1,
						result,
						entries[ i ],
						localHolder
					);
				}

				unpackerIL.EmitAnyLdloc( unpacked );
				unpackerIL.EmitLdc_I4_1();
				unpackerIL.EmitAdd();
				unpackerIL.EmitAnyStloc( unpacked );

				unpackerIL.EmitBr( endIf0 );

				unpackerIL.MarkLabel( else0 );

				if ( entries[ i ].Member != null )
				{
					// Respect nil implication.
					switch ( entries[ i ].Contract.NilImplication )
					{
						case NilImplication.MemberDefault:
						{
							unpackerIL.EmitBr( endOfDeserialization );
							break;
						}
						case NilImplication.Null:
						{
							if( entries[ i ].Member.GetMemberValueType().GetIsValueType() )
							{
								if( Nullable.GetUnderlyingType( entries[ i ].Member.GetMemberValueType() ) == null )
								{
									// val type
									/*
									 * if( value == null )
									 * {
									 *		throw SerializationEceptions.NewValueTypeCannotBeNull( "...", typeof( MEMBER ), typeof( TYPE ) );
									 * }
									 */
									unpackerIL.EmitLdstr( entries[ i ].Contract.Name );
									unpackerIL.EmitLdtoken( entries[ i ].Member.GetMemberValueType() );
									unpackerIL.EmitAnyCall( Metadata._Type.GetTypeFromHandle );
									unpackerIL.EmitLdtoken( entries[ i ].Member.DeclaringType );
									unpackerIL.EmitAnyCall( Metadata._Type.GetTypeFromHandle );
									unpackerIL.EmitAnyCall( SerializationExceptions.NewValueTypeCannotBeNull3Method );
									unpackerIL.EmitThrow();
								}
								else
								{
									// nullable
									unpackerIL.EmitAnyLdloca( localHolder.GetDeserializedValue( entries[ i ].Member.GetMemberValueType() ) );
									unpackerIL.EmitInitobj( entries[ i ].Member.GetMemberValueType() );
									unpackerIL.EmitAnyLdloc( result );
									unpackerIL.EmitAnyLdloc( localHolder.GetDeserializedValue( entries[ i ].Member.GetMemberValueType() ) );
									Emittion.EmitStoreValue( unpackerIL, entries[ i ].Member );
								}
							}
							else
							{
								// ref type
								unpackerIL.EmitAnyLdloc( result );
								unpackerIL.EmitLdnull();
								Emittion.EmitStoreValue( unpackerIL, entries[ i ].Member );
							}

							break;
						}
						case NilImplication.Prohibit:
						{
							unpackerIL.EmitLdstr( entries[ i ].Contract.Name );
							unpackerIL.EmitAnyCall( SerializationExceptions.NewNullIsProhibitedMethod );
							unpackerIL.EmitThrow();
							break;
						}
					}
				}

				unpackerIL.MarkLabel( endIf0 );
			}
		}

		private static void EmitUnpackMembersFromMap( SerializerEmitter emitter, TracingILGenerator unpackerIL, SerializingMember[] entries, LocalBuilder result, LocalVariableHolder localHolder )
		{
			/*
			 *		var memberName = unpacker.Data.AsString();
			 *		if( memberName == "A" )
			 *		{
			 *			if( !unpacker.Read() )
			 *			{
			 *				throw SerializationExceptions.NewUnexpectedStreamEndsException();
			 *			}
			 *
			 *			isAFound = true;
			 *		}
			 *		:
			 */

			var beginLoop = unpackerIL.DefineLabel( "BEGIN_LOOP" );
			var endLoop = unpackerIL.DefineLabel( "END_LOOP" );
			unpackerIL.MarkLabel( beginLoop );
			var memberName = localHolder.MemberName;
			unpackerIL.EmitAnyLdarg( 1 );
			unpackerIL.EmitAnyLdloca( memberName );
			unpackerIL.EmitAnyCall( Metadata._Unpacker.ReadString );
			unpackerIL.EmitBrfalse( endLoop );

			for ( int i = 0; i < entries.Length; i++ )
			{
				if ( entries[ i ].Contract.Name == null )
				{
					// skip undefined member
					continue;
				}

				// TODO: binary comparison

				// Is it current member?
				unpackerIL.EmitAnyLdloc( memberName );
				unpackerIL.EmitLdstr( entries[ i ].Contract.Name );
				unpackerIL.EmitAnyCall( Metadata._String.op_Equality );
				var endIfCurrentMember = unpackerIL.DefineLabel( "END_IF_MEMBER_" + i );
				unpackerIL.EmitBrfalse( endIfCurrentMember );

				// Deserialize value
				if ( entries[ i ].Member == null )
				{
					Emittion.EmitGeneralRead( unpackerIL, 1 );
					// Ignore undefined member -- Nop.
				}
				else if ( UnpackHelpers.IsReadOnlyAppendableCollectionMember( entries[ i ].Member ) )
				{
					Emittion.EmitDeserializeCollectionValue(
						emitter,
						unpackerIL,
						1,
						result,
						entries[ i ].Member,
						entries[ i ].Member.GetMemberValueType(),
						entries[ i ].Contract.NilImplication,
						localHolder
					);
				}
				else
				{
					Emittion.EmitDeserializeValue(
						emitter,
						unpackerIL,
						1,
						result,
						entries[ i ],
						localHolder
					);
				}

				// TOOD: Record for missing check

				unpackerIL.EmitBr( beginLoop );
				unpackerIL.MarkLabel( endIfCurrentMember );
			}

			// Drain next value with unpacker.Read()
			unpackerIL.EmitAnyLdarg( 1 );
			unpackerIL.EmitCallvirt( Metadata._Unpacker.Read );
			unpackerIL.EmitPop();
			unpackerIL.EmitBr( beginLoop );
			unpackerIL.MarkLabel( endLoop );
		}

		/// <summary>
		///		Creates serializer as <typeparamref name="TObject"/> is array type.
		/// </summary>
		/// <returns>
		///		<see cref="MessagePackSerializer{T}"/>.
		///		This value will not be <c>null</c>.
		/// </returns>
		public sealed override MessagePackSerializer<TObject> CreateArraySerializer()
		{
			using ( var emitter = EmittingSerializerBuilderLogics.CreateArraySerializerCore( this.Context, typeof( TObject ), this._emitterFlavor ) )
			{
				try
				{
					return emitter.CreateInstance<TObject>( this.Context );
				}
				finally
				{
					emitter.FlushTrace();
				}
			}
		}

		/// <summary>
		///		Creates serializer as <typeparamref name="TObject"/> is map type.
		/// </summary>
		/// <returns>
		///		<see cref="MessagePackSerializer{T}"/>.
		///		This value will not be <c>null</c>.
		/// </returns>
		public sealed override MessagePackSerializer<TObject> CreateMapSerializer()
		{
			using ( var emitter = EmittingSerializerBuilderLogics.CreateMapSerializerCore( this.Context, typeof( TObject ), this._emitterFlavor ) )
			{
				try
				{
					return emitter.CreateInstance<TObject>( this.Context );
				}
				finally
				{
					emitter.FlushTrace();
				}
			}
		}

		/// <summary>
		///		Creates serializer as <typeparamref name="TObject"/> is tuple type.
		/// </summary>
		/// <returns>
		///		<see cref="MessagePackSerializer{T}"/>.
		///		This value will not be <c>null</c>.
		/// </returns>
		public sealed override MessagePackSerializer<TObject> CreateTupleSerializer()
		{
			throw new PlatformNotSupportedException();
		}
	}
}
#endif


text:
namespace Microsoft.Azure.Management.KeyVault.Fluent
{

    using Microsoft.Azure.Management.KeyVault.Fluent.Models;
    using Microsoft.Azure.Management.ResourceManager.Fluent.Core;

    /// <summary>
    /// An immutable client-side representation of a key vault access policy.
    /// </summary>
    public interface IAccessPolicy :
        IChildResource<Microsoft.Azure.Management.KeyVault.Fluent.IVault>,
        IHasInner<Microsoft.Azure.Management.KeyVault.Fluent.Models.AccessPolicyEntry>
    {
        /// <summary>
        /// Gets The Azure Active Directory tenant ID that should be used for
        /// authenticating requests to the key vault.
        /// </summary>
        string TenantId { get; }

        /// <summary>
        /// Gets The object ID of a user or service principal in the Azure Active
        /// Directory tenant for the vault.
        /// </summary>
        string ObjectId { get; }

        /// <summary>
        /// Gets Application ID of the client making request on behalf of a principal.
        /// </summary>
        string ApplicationId { get; }

        /// <summary>
        /// Gets Permissions the identity has for keys and secrets.
        /// </summary>
        Microsoft.Azure.Management.KeyVault.Fluent.Models.Permissions Permissions { get; }
    }
}


text:
using System.Diagnostics.CodeAnalysis;
using System.Linq;

namespace NuGet {
    public interface IPackageRepository {
        string Source { get; }
        [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "This call might be expensive")]
        IQueryable<IPackage> GetPackages();
        void AddPackage(IPackage package);
        void RemovePackage(IPackage package);
    }
}


text:
module SoupCMS
  module Api
    module Enricher

      class PageEnricher < Base

        def enrich(page)
          return unless context.model_name == 'pages'

          enricher_page = fetch_enricher_page(context)
          return if enricher_page.nil?

          enrich_layout(enricher_page, page)
          enrich_areas(enricher_page, page)
        end

        def fetch_enricher_page(context)
          repo = SoupCMS::Api::DocumentRepository.new(context)
          repo.model_name = 'pages'
          context.drafts? ? repo.drafts : repo.published
          repo.with({'meta.name' => 'enricher'}).fetch_one
        end

        private

        def enrich_areas(enricher_page, page)
          enricher_page['areas'].each do |area|
            unless page['areas'].index { |a| a['name'] == area['name'] }
              page['areas'] << area
            end
          end
        end

        def enrich_layout(enricher_page, page)
          if page['layout'].nil? || page['layout'].empty?
            page.merge!({'layout' => enricher_page['layout']}) if enricher_page['layout']
          end
        end

      end

    end
  end
end


text:
#include <unistd.h>
#include <iostream>
#include <sstream>
#include <iostream>
#include <chrono>
#include <thread>
#include <atomic>
#include <future>

#include "ksync/logging.h"
#include "ksync/client.h"
#include "ksync/messages.h"
#include "ksync/utilities.h"
#include "ksync/comm/interface.h"
#include "ksync/comm/factory.h"

#include "ksync/ArgParseStandalone.h"

int main(int argc, char** argv) {
	std::string log_dir;
	std::string gateway_socket_url;
	bool gateway_socket_url_defined;
	bool nanomsg;

	ArgParse::ArgParser arg_parser("KSync Server - Client side of a Client-Server synchonization system using rsync.");
	KSync::Utilities::set_up_common_arguments_and_defaults(arg_parser, log_dir, gateway_socket_url, gateway_socket_url_defined, nanomsg);

	if(arg_parser.ParseArgs(argc, argv) < 0) {
		LOGF(SEVERE, "Problem parsing arguments");
		arg_parser.PrintHelp();
		return -1;
	}

	if(arg_parser.HelpPrinted()) {
		return 0;
	}

	if (log_dir == "") {
		if(KSync::Utilities::get_user_ksync_dir(log_dir) < 0) {
			printf("There was a problem getting the ksync user directory!\n");
			return -2;
		}
	}

	//Initialize logging:
	std::unique_ptr<g3::LogWorker> logworker;
	KSync::InitializeLogger(logworker, true, "KSync Client", log_dir);

	//Get Default gateway socket url
	if (!gateway_socket_url_defined) {
		if(KSync::Utilities::get_default_ipc_connection_url(gateway_socket_url) < 0) {
			LOGF(SEVERE, "There was a problem getitng the default IPC connection URL.");
			return -2;
		}
	} else {
		if(gateway_socket_url.substr(0, 3) != "icp") {
			LOGF(SEVERE, "Non icp sockets are not properly implemented at this time.");
			return -2;
		}
	}

	LOGF(INFO, "Using the following socket url: %s", gateway_socket_url.c_str());

	//Initialize Comm System
	std::shared_ptr<KSync::Comm::CommSystemInterface> comm_system;
	if (!nanomsg) {
		if (KSync::Comm::GetZeromqCommSystem(comm_system) < 0) {
			LOGF(SEVERE, "There was a problem initializing the ZeroMQ communication system!");
			return -2;
		}
	} else {
		if (KSync::Comm::GetNanomsgCommSystem(comm_system) < 0) {
			LOGF(SEVERE, "There was a problem initializing the Nanomsg communication system!");
			return -2;
		}
	}

	//Connect to gateway socket
	std::shared_ptr<KSync::Comm::CommSystemSocket> gateway_socket;
	if (comm_system->Create_Gateway_Req_Socket(gateway_socket) < 0) {
		LOGF(SEVERE, "There was a problem creating the gateway socket!");
		return -3;
	}

	if(gateway_socket->SetRecvTimeout(20000) < 0) {
		LOGF(SEVERE, "There was a problem setting the receive timeout!");
		return -4;
	}

	if (gateway_socket->Connect(gateway_socket_url) < 0) {
		LOGF(SEVERE, "There was a problem connecting to the gateway socket!");
		return -4;
	}

	std::shared_ptr<KSync::Comm::CommSystemSocket> client_socket;
	std::shared_ptr<KSync::Comm::CommSystemSocket> broadcast_socket;
	int status = 0;
	//Request client socket connection
	while (!client_socket) {
		KSync::Comm::GatewaySocketInitializationRequest request(KSync::Utilities::GenerateNewClientId());
		std::shared_ptr<KSync::Comm::CommObject> request_obj = request.GetCommObject();
		status = gateway_socket->Send(request_obj);
		if(status == KSync::Comm::CommSystemSocket::Other) {
			LOGF(WARNING, "There was a problem sending the message!!");
		} else if (status == KSync::Comm::CommSystemSocket::Timeout) {
			LOGF(WARNING, "Sending the message timed out!");
		} else {
			std::shared_ptr<KSync::Comm::CommObject> recv_obj;
			status = gateway_socket->Recv(recv_obj);
			if(status == KSync::Comm::CommSystemSocket::Other) {
				LOGF(WARNING, "Problem receiving response");
			} else if (status == KSync::Comm::CommSystemSocket::Timeout) {
				LOGF(WARNING, "Receiving response timed out!");
			} else {
				if(recv_obj->GetType() == KSync::Comm::ClientSocketCreation::Type) {
					std::shared_ptr<KSync::Comm::ClientSocketCreation> creation_response;
					KSync::Comm::CommCreator(creation_response, recv_obj);
					//Start and connect to client socket
					if(comm_system->Create_Pair_Socket(client_socket) < 0) {
						LOGF(SEVERE, "There was a problem creating the pair socket!");
						return -1;
					}
					if(client_socket->SetRecvTimeout(1000) < 0) {
						LOGF(SEVERE, "There was a problem setting the client socket timeout!");
						return -2;
					}
					if(client_socket->Connect(creation_response->GetClientUrl()) < 0) {
						LOGF(SEVERE, "Couldn't connect to the new client socket address!!");
						return -3;
					}

					//Start and connect to broadcast socket
					if(comm_system->Create_Sub_Socket(broadcast_socket) < 0) {
						LOGF(SEVERE, "There was a problem creating the broadcast socket!");
						return -4;
					}
					if(broadcast_socket->SetRecvTimeout(1000) < 0) {
						LOGF(SEVERE, "Couldn't set the timeout of the broadcast socket!");
						return -5;
					}
					if(broadcast_socket->Connect(creation_response->GetBroadcastUrl()) < 0) {
						LOGF(SEVERE, "There was a problem connecting to the broadcast socket!");
						return -5;
					}
				} else if(recv_obj->GetType() == KSync::Comm::GatewaySocketInitializationChangeId::Type) {
					LOGF(WARNING, "Received a ChangeId Request!!");
				} else {
					LOGF(WARNING, "Unrecognized Message!");
				}
			}
		}
	}

	//Close gateway socket connection
	gateway_socket.reset();

	std::shared_ptr<std::thread> io_thread;
	std::shared_ptr<std::promise<std::string>> io_result;
	std::future<std::string> io_future;
	bool finished = false;
	while (!finished) {
		//restart thread if it's stopped
		if(!io_thread) {
			//Flush and clear cin buffer and item string
			if(std::cin.rdbuf()->in_avail() > 0) {
				std::cin.ignore(std::cin.rdbuf()->in_avail());
			}
			std::cin.clear();
			//Restart IO thread
			//Reset finished bool
			io_result.reset(new std::promise<std::string>);
			io_future = io_result->get_future();
			io_thread.reset(new std::thread([&io_result] {
				std::string item;
				printf("Print message to send to the server:\n");
				std::getline(std::cin, item);
				if(item == "quit") {
					std::string item2;
					int action_selection_state = 2;
					while (action_selection_state == 2) {
						printf("Are you sure you want to quit? (Y/n)\n");
						item2.clear();
						std::getline(std::cin, item2);
						if ((item2 == "y")||(item2 == "Y")) {
							action_selection_state = 0;
						} else if ((item2 == "n") || (item2 == "N")) {
							action_selection_state = 1;
						} else {
							printf("Please choose either Y or n.\n");
						}
					}
				}
				io_result->set_value(item);
			}));
		}

		//Test if result is ready
		if(io_result) {
			std::future_status fut_stat;
			try {
				fut_stat = io_future.wait_for(std::chrono::milliseconds(0));
			} catch (std::future_error e) {
				LOGF(SEVERE, "There was a futures error!!! (%s)", e.what());
				return -100;
			}
			if((fut_stat== std::future_status::ready)&&(!finished)) {
				//Result is ready
				KSync::Comm::CommString message_to_send = io_future.get();
				if (message_to_send == "quit") {
					KSync::Comm::ShutdownRequest shutdown_req;
					std::shared_ptr<KSync::Comm::CommObject> shutdown_obj = shutdown_req.GetCommObject();
					status = client_socket->Send(shutdown_obj);
					if(status == KSync::Comm::CommSystemSocket::Other) {
						LOGF(WARNING, "There was an error sending the shutdown request!");
					} else if (status == KSync::Comm::CommSystemSocket::Timeout) {
						LOGF(WARNING, "There was a timeout sending the shutdown request!");
					} else {
						std::shared_ptr<KSync::Comm::CommObject> rep_obj;
						status = client_socket->ForceRecv(rep_obj);
						if(status == KSync::Comm::CommSystemSocket::Other) {
							LOGF(WARNING, "There was a problem getting a response to the shutdown request!");
						} else {
							if(rep_obj->GetType() != KSync::Comm::ShutdownAck::Type) {
								LOGF(WARNING, "Shutdown Acknowledgement not received!");
								break;
							}
						}
					}
				} else if (message_to_send.substr(0,8) == "command:") {
					std::string extracted_command = message_to_send.substr(8);
					extracted_command = KSync::Utilities::trim(extracted_command);
					KSync::Comm::ExecuteCommand command = extracted_command;
					std::shared_ptr<KSync::Comm::CommObject> send_obj = command.GetCommObject();
					status = client_socket->Send(send_obj);
					if(status == KSync::Comm::CommSystemSocket::Other) {
						LOGF(WARNING, "There was a problem sending the command!");
					} else if (status == KSync::Comm::CommSystemSocket::Timeout) {
					} else {
						std::shared_ptr<KSync::Comm::CommObject> ret_obj;
						status = client_socket->ForceRecv(ret_obj);
						if(status == KSync::Comm::CommSystemSocket::Other) {
							LOGF(WARNING, "There was a problem receiving the reply!");
						} else if (status == KSync::Comm::CommSystemSocket::Success) {
							if(ret_obj->GetType() == KSync::Comm::CommandOutput::Type) {
								std::shared_ptr<KSync::Comm::CommandOutput> com_output;
								KSync::Comm::CommCreator(com_output, ret_obj);
								printf("Output:\n");
								printf("%s\n", com_output->GetStdout().c_str());
								printf("Error:\n");
								printf("%s\n", com_output->GetStderr().c_str());
								printf("Return Code: (%i)\n", com_output->GetReturnCode());
							} else {
								LOGF(WARNING, "Other object types are not supported here");
							}
						}
					}
				} else {
					std::shared_ptr<KSync::Comm::CommObject> send_obj;
					LOGF(INFO, "Sending message: (%s)", message_to_send.c_str());
					send_obj = message_to_send.GetCommObject();
					status = client_socket->Send(send_obj);
					if(status == KSync::Comm::CommSystemSocket::Other) {
						LOGF(SEVERE, "There was a problem sending the string to the server!");
						return -1;
					} else if (status == KSync::Comm::CommSystemSocket::Timeout) {
						LOGF(SEVERE, "Sending the message timed out!!");
						return -2;
					} else {
						std::shared_ptr<KSync::Comm::CommObject> recv_obj;
						status = client_socket->ForceRecv(recv_obj);
						if(status == KSync::Comm::CommSystemSocket::Other) {
							LOGF(SEVERE, "There was a problem receiving a response!");
							return -3;
						} else if ((status == KSync::Comm::CommSystemSocket::Timeout)||(status == KSync::Comm::CommSystemSocket::EmptyMessage)) {
						} else {
							if(recv_obj->GetType() == KSync::Comm::CommString::Type) {
								std::shared_ptr<KSync::Comm::CommString> received_string;
								KSync::Comm::CommCreator(received_string, recv_obj);
								LOGF(INFO, "Received(%s)", received_string->c_str());
								if (*received_string != message_to_send) {
									LOGF(SEVERE, "Received message was different!");
								}
							}
						}
					}
				}
				//Cleanup IO thread stuff
				if(io_thread) {
					if(io_thread->joinable()) {
						io_thread->join();
					}
					io_thread.reset();
				}
			}
		}

		//Test broadcast socket
		std::shared_ptr<KSync::Comm::CommObject> broad_obj;
		status = broadcast_socket->Recv(broad_obj);
		if(status == KSync::Comm::CommSystemSocket::Other) {
			LOGF(WARNING, "There was a problem reading from the broadcast socket!");
		} else if ((status == KSync::Comm::CommSystemSocket::Timeout)||(status == KSync::Comm::CommSystemSocket::EmptyMessage)) {
		} else {
			if(broad_obj->GetType() == KSync::Comm::ServerShuttingDown::Type) {
				LOGF(WARNING, "Server shutdown detected, Shutting down.");
				finished = true;
			} else {
				LOGF(WARNING, "Other message types unsupported here!");
			}
		}
	}

	//Join io_thread;
	if(io_thread) {
		if(io_thread->joinable()) {
			io_thread->join();
		}
	}
	return 0;
}


text:
<!doctype html>

		<meta charset="utf-8">

		<title>Ptoceti's obix SPA</title>

		<meta name="description" content="How I moved to a backbone stack for Ptoceti's UX">
		<meta name="author" content="Hakim El Hattab">

		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

		<link rel="stylesheet" href="css/reveal.min.css">
		<link rel="stylesheet" href="css/theme/night.css" id="theme">

		<link rel="stylesheet" href="lib/css/zenburn.css">

Ptoceti's SPA

From GWT to a JS stack

						https://github.com/lathil/Ptoceti

What is it ?

a Obix server

a Single Page Application UI

Runs on ...

an OSGI R4 container (Felix, ...)

a JRE 7

a HTML5 browser

Deploy on ...

my powermac G4 ... ?

Deploy on ...

probably more something like this ...

What does it do ?

Open Building Infomation eXchange

 an OASIS standard since 2006

IBM provide an implementation in  Tivoli Power management suite

 in Tridium Niagara AX framwork ...

 Dubai airport, Olympic village & district at Beijing...

A simple Rest service

						very open

Obix: a web service ...

.. inspired from Rest and HATEOAS

Small object model that can be combined to describe the domain

Resources identified by URL

Links between resources

No fixed url, resources are navigated thought links and hypermedia

Root entry point: the Lobby

								<obj href="http://localhost:8080/obix/rest/" is="obix:Lobby">
									<op name="batch" href="/batch/" is="obix:Op" in="obix:BatchIn" out="obix:BatchOut"></op>
									<ref name="about" href="/about/" is="obix:About"></ref>
									<ref name="watchService" href="/watchservice/" is="obix:WatchService"></ref>
								</obj>

/about/ leads to :

								<obj name="about" href="http://localhost:8080/obix/rest/about/" status="ok" is="obix:About">
									<abstime name="serverBootTime" val="2014-04-07T19:31:30+02:00"></abstime>
									<abstime name="serverTime" val="2014-04-07T21:58:42+02:00"></abstime>
									<str name="obixVersion" val=""></str>
									<str name="productName" val="Obix-Lib"></str>
									<uri name="productUrl" val="www.ptoceti.com"></uri>
									<str name="productVersion" val="1.0.0.SNAPSHOT"></str>
									<str name="vendorName" val="ptoceti"></str>
									<uri name="vendorUrl" val="www.ptoceti.com"></uri>
									<str name="serverName" val="org.ops4j.pax.web.pax-web-jetty-bundle"></str>
								</obj>

Ptoceti's SPA stack:

						Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.

Backbone's approach:

There's more than one way do do it

Minimalistic by design

Does not force a top level pattern for the application architecture

MVC, MVP, MVVM, .. YOU choose your fix

Backbone provides these objects

Backbone.Model

Backbone.Collection

Backbone.View

Backbone.Event

Backbone.Router

Backbone.History

For every thing else, there's ...

Github

Using Backbone: challenge 1

No support for parsing nested models

Backbone provides only for Models or Collection of Models structures.

override model : function(attrs, option) in Backbone.Collection

and override parse() & implements initialise() in Backbone.Collection

Why do we need nested models ?

 Obix responses are structured by Entities :

								<obj href="http://localhost:8080/obix/rest/" is="obix:Lobby">
									<op name="batch" href="/batch/" is="obix:Op" in="obix:BatchIn" out="obix:BatchOut"/>
									<ref name="about" href="/about/" is="obix:About"/>
									<ref name="watchService" href="/watchservice/" is="obix:WatchService"/>
								</obj>

We map each entity to a model, that allows us to define and use helper functions :

								var aboutRef = this.lobby.getAbout().getHref());

For each Model of known type, re-assigne proper Obix Model

								var Objs = Backbone.Collection.extend({
									...
								    model : function(attrs, option) {
								        switch (attrs.type) {
								             case "abstime":
								                 return new Abstime(attrs, option);
								             ...
								        }
								    }
									...
								})

By default parse() convert response to a hash of attributes, here, we convert it into a Model when appropriate.

								var Obj = Backbone.Model.extend({
								    ...
								    parse : function(response, options) {
								       if (response !== null) {
								            ...
								            if (response.childrens !== null)
								               response.childrens = new Objs(response.childrens, {
								               urlRoot : _.result(this, 'urlRoot'),
								               parent : this
								            });
								            ...
								        }
								        return response;
								    },
								    ...
								})

Using Backbone: challenge 2

No support for nested models event

Events are not generated on nested attributes

uses backbone-deep-model

or override set() in Backbone.Model

last solution chosen because of the nested nature of Obix models

For each attribute property that is an Model, invoke set() to generate the events.

								var Obj = Backbone.Model.extend({
									set: function(key, val, options) {
										...
										 // For each `set` attribute, update or delete the current value.
									     for (attr in attrs) {
									        val = attrs[attr];

									        var type = Object.prototype.toString.call(current[attr]);
									        if( current[attr] instanceof Objs && val instanceof Objs){
									            current[attr].set(val.models,options);
									        } else {
										       ...
									        }
									     }
									     ...
									}
								})

Using Backbone: challenge 3

Two-way binding

No binding mechanism for generated events betwen DOM element and model

Backbone let it to you to install your handlers

Many plugins availables from Epoxy.js

to Bacbone.ModelBinder to ease the pain

On model initialisation, create a new binder.

							initialize : function() {
							    ...
							    // initialize Backbone.ModelBinder for dual binding
							    this.modelbinder = new ModelBinder();
							    ...
							}

once the view is rendered, bind models attributes to dom elements

							onRender : function() {
						        this.modelbinder.bind(this.model, this.el, {
							        count: {selector: '[name=count]'},
							    });
							    ...
							},

Using Backbone: challenge 4

Nested Views

View management is very light in Backbone

To avoid re-creating the wheel, use a third part plugin such as Chaplin, or ...

Enter ...

Marionette

Marionnette is ...

An library on top of Backbone that provides bricks to build large scale web app.

View component: ItemView, CollectionView, CompositeView, Layout

View management: Region, Renderer, TemplateCache

Application structure: Application, Controller, AppRouter, EventAgregator, Command, ...

Nested Views becomes trivial

Use Marionnette's region for subviews placement

								regions : {
								    header : '#header',
								    content : '#content',
								    footer : '#footer'
								},

Insert subview when ready

								layout.header.show(new HeaderView({
								    model : about
								}));

								layout.footer.show(new FooterView({
								    model : about
								}));

Templating handled by ..

Support expressions, helpers, model attribute mappings, ...

{{displayName}}

{{#if ... }} {{/if}} -> expression with if helper

{{displayname}} -> mapping of attached model's 'displayName' attribute.

Integration with Marionnette

Marrionette provides a template cache for compiled templates

Templates are compiled on demand on the browser and stored in the cache

Facilitate development, as just need to do refresh on the browser to get a new compiled template

Give your application structure ...

Event driven architecture

 Reactive programming

Favor loose coupling between the application components

Use a event mediator to handle application messages

use Publish / Subscribe event communication

One main controller for booting up and application level control

Lighter messaging using Courier  between nested views

Ease scalability

Example

In header subview, generate event to go to history display ...

								var HeaderView = Marionette.ItemView.extend({
								...
								    historyMenuClicked : function() {
								        this.ui.lobbyMenu.parent().removeClass('active');
								        this.ui.watchesMenu.parent().removeClass('active');
								        this.ui.historyMenu.parent().addClass('active');
								        ventAggr.trigger("app:goToHistory");
								...
								});

						headerview.js is controller of the header, listen to history tab being click. We need to 'activate' through css the menu, Bootstrap failing to do this in our setup.

 ... in main app, event is caught and we ask the controller to do something in response

								var app = new Marionette.Application();

								app.on('start', function() {
								    ...
								    ventAggr.on("app:goToHistory", function() {
								        if( Backbone.history.fragment != "history" ) {
								            Backbone.history.navigate("history", {});
								            app.controller.goToHistory();
								        }
								    });
								    ...
								});

Modular Application

All components (views, controllers, ..) are AMD modules

Require.js used to link them at runtime and optimization phase

Application loaded peace-meal

Most important first - user don't have to wait too long

Resilience

Why AMD ?

I've got big walls ..

... wi-fi don't go well throught them

Modular Application

Example: module declaration

								define(['backbone', 'marionette', 'underscore', 'eventaggr', 'views/obixview','models/obix', 'models/watcheslocal', 'models/watches'], function(
		Backbone, Marionette, _, ventAggr, ObixView, Obix, WatchesLocal, Watches) {

								    var AppController = Marionette.Controller.extend({
								    ...
								    });

								    return AppController;
								});

Modular Application

Example: loading a module asynchronously

								goToHistory : function() {
								    var controller = this;
								    require(['views/historyview'], function(HistoryView) {
								        controller.obixView.content.show(new HistoryView());
								    });
								}

AMD loading

No optimisation

each module loaded separatly

perfect for dev phase

AMD loading

Redefine your modules contents

Enter your modules definitions in require.js config inside your grunt.js file (if your are using Grunt)

								requirejs: {
								    compile_build: {
								        options: {
								            optimize:"uglify",
								            optimizeCss: "standard",
								            modules : [
								                {name: 'main', include: ["i18n", "text",'courier','moment','mediaenquire','jquery.enterkeyevent']},
								                {name:'views/headerview', exclude: [...]},
								                {name:'views/footerview', exclude: [...]},
								                ...
								            ]
								        }
								    }
								}

AMD loading

with optimisation

1st module: common libs + core

each subview as own module

modules are loaded as needed

Make the application responsive

Bootstrap 3 handle responsive grid and css

Modernizr detect device capabilities ( svg,mq,websocket...) and provides polyfil in some case

Javascript media queries ( enquire.js) gives the application opportunites to present alternatives components

Example: using Modernizer to test for svg support

						(we use d3.js to display graph - not supported on gingerbread default browser)

								if( Modernizr.svg) {
								    var region = this.historyRegion;
								    require(['views/historyrollupchartview'], function(HistoryRollupChartView){
								        ...
								    });
								}

This avoid sending d3.js + xcharts.js + xcharts.css to the browser if it can't use it.

Project building

we use:

Bower for javacript dependencies

Grunt for scheduling building of ihm project

Maven for builing the osgi Bundle

Project layout

in bower_component the dependencides loaded by bower

in js/app the application code

in js/lib the cleaned up dependencies

in js_optimized, the application uglified and modularized by require.js

Maven launch Grunt, which in turn launch Bower, Modernizr an then RequireJs

Build in a CI environment

We make use of a Jenkins platform at

Simply need to add and configure the NodeJS plugin in 'Administer Jenkins'

Develoment, debugging ...

Locally Osgi server is started with pax runner

Embedded Jetty is configured to serve dev portion of js application ( build is minified )

Then we use Chrome dev tools to map application to source folder. Development and debugging made in Chrome

Develoment, debugging on remote

Server is deployed on target using

see docker-felix

and docker-ptoceti

Application js served with npm serve on developemnt machine, make access through CORS to remote server.

Summary

Positive sides of a Backbone stack:

Communauty around it still vibrant

Plenty of choices for plugins

Lightweight library does not get into your way -> very flexible

Force you to build your application structure

Integrate well with an AMD structure

Imperative style vs Declarative (depends where you stand)

Summary

Not so positive sides of a Backbone stack:

Needs to select your plugins depending on your need ( or use yeoman for a standard stack)

Backbone force 1 Model per View structure; ( With Angular you can have N Controller/Model per View)

Model.toJson() used for serialisation to view and to server ( via REST ). Difficulties to display extrat attributes

No separation between Models and provider. Would be nice to have disconnected Models

Backbone is not RAD ( if you are in this kind of thing).

Summary

Compare to Angular ?

Main advantage here is the possibility to load modules asynchronously and on demand.

Angular actually does not support if ( see Angular.js 2 with Durandal), you need to define new provider:
								Lazy Loading In AngularJS and
								Load a module on demand with AngularJS


text:
package org.apache.ignite.internal.processors.cache.persistence;

import org.apache.ignite.internal.processors.cache.persistence.file.AlignedBuffersDirectFileIOFactory;
import org.apache.ignite.internal.processors.cache.persistence.file.FileIOFactory;
import org.apache.ignite.internal.processors.compress.DiskPageCompressionIntegrationTest;

/**
 */
public class DiskPageCompressionIntegrationDirectIOTest extends DiskPageCompressionIntegrationTest {
    /** {@inheritDoc} */
    @Override protected void checkFileIOFactory(FileIOFactory f) {
        assertTrue(f instanceof AlignedBuffersDirectFileIOFactory);
    }
}


text:
"""
    stars_automater.py

    Functions to launch and manipulate a Stars! game using Wine and xdotool.

    The resolutions of windows and mouse positions are shamelessly hard-coded.
    Use xprop, xwininfo and xmousepos to get mouse coordinates and resolutions.

    :author: Brandon Arrendondo
    :license: MIT
"""
import subprocess
import time
import logging

STARS_SPLASH_GEOMETRY = "2560x1600"
#STARS_SPLASH_GEOMETRY = "2222x1348"
NEW_GAME_SAVE_GEOMETRY = "413x218"
#STARS_GAME_GEOMETRY = "1535x1161"
STARS_GAME_GEOMETRY = "2540x1569"

class UniverseSize:
    Tiny = 1
    Small = 2
    Medium = 3
    Large = 4
    Huge = 5

class UniverseDensity:
    Sparse = 1
    Normal = 2
    Dense = 3
    Packed = 4

def launch_stars(stars_executable):
    process = subprocess.Popen(["/usr/bin/wine", stars_executable])

    cmd = "xdotool search stars"
    while True:
        try:
            result = subprocess.check_output(cmd, shell=True)
            break
        except subprocess.CalledProcessError:
            logging.warning("Failed to find window. Trying again.")
            time.sleep(1)

    for line in result.splitlines():
        discovered_geometry = get_window_geometry(line)
        logging.debug("Discovered geometry: {0!s}".format(discovered_geometry))
        if discovered_geometry == STARS_SPLASH_GEOMETRY:
            return (True, line, process)

    return (False, None, None)

def get_window_geometry(id):
    cmd = "xdotool getwindowgeometry {0!s}".format(id)
    result = subprocess.check_output(cmd, shell=True)

    for line in result.splitlines():
        actual_line = line.strip()
        if actual_line.startswith("Geometry"):
            geometry = actual_line.replace("Geometry: ", "")
            return geometry

def select_new_game():
    logging.debug("Selecting New Game...")

    cmd = "xdotool mousemove 306 1536 click 1"
    result = subprocess.check_output(cmd, shell=True)

def select_universe_size(size):
    if (size == UniverseSize.Tiny):
        logging.debug("Choosing Tiny universe size.")
        cmd = "xdotool mousemove 1132 810 click 1"
    elif (size == UniverseSize.Small):
        logging.debug("Choosing Small universe size.")
        cmd = "xdotool mousemove 1132 830 click 1"
    elif (size == UniverseSize.Medium):
        logging.debug("Choosing Medium universe size.")
        cmd = "xdotool mousemove 1132 860 click 1"
    elif (size == UniverseSize.Large):
        logging.debug("Choosing Large universe size.")
        cmd = "xdotool mousemove 1132 880 click 1"
    elif (size == UniverseSize.Huge):
        logging.debug("Choosing Huge universe size.")
        cmd = "xdotool mousemove 1132 900 click 1"
    else:
        raise Exception("Invalid universe size.")

    result = subprocess.check_output(cmd, shell=True)

def select_advanced_game():
    logging.debug("Selecting Advanced Game...")

    cmd = "xdotool mousemove 1340 880 click 1"
    result = subprocess.check_output(cmd, shell=True)

def select_universe_density(density):
    if (density == UniverseDensity.Sparse):
        logging.debug("Choosing Sparse universe density.")
        cmd = "xdotool mousemove 1143 865 click 1"
    elif (density == UniverseDensity.Normal):
        logging.debug("Choosing Normal universe density.")
        cmd = "xdotool mousemove 1143 890 click 1"
    elif (density == UniverseDensity.Dense):
        logging.debug("Choosing Dense universe density.")
        cmd = "xdotool mousemove 1143 905 click 1"
    elif (density == UniverseDensity.Packed):
        logging.debug("Choosing Packed universe density.")
        cmd = "xdotool mousemove 1143 925 click 1"
    else:
        raise Exception("Invalid universe density.")

    result = subprocess.check_output(cmd, shell=True)

def select_finish_advanced_game():
    logging.debug("Selecting Finish...")

    cmd = "xdotool mousemove 1434 972 click 1"
    result = subprocess.check_output(cmd, shell=True)

def default_ok_new_game():
    cmd = "xdotool search stars"
    result = subprocess.check_output(cmd, shell=True)
    for line in result.splitlines():
        discovered_geometry = get_window_geometry(line)
        logging.debug("Discovered geometry: {0!s}".format(discovered_geometry))
        if (discovered_geometry == NEW_GAME_SAVE_GEOMETRY):
            window_id = int(line.strip())
            cmd = "xdotool key Return {0!s}".format(window_id)
            result = subprocess.check_output(cmd, shell=True)
            return

    raise Exception("Could not find new game save window.")

def dump_universe_map():
    cmd = "xdotool search stars"
    result = subprocess.check_output(cmd, shell=True)
    for line in result.splitlines():
        discovered_geometry = get_window_geometry(line)
        logging.debug("Discovered geometry: {0!s}".format(discovered_geometry))
        if (discovered_geometry == STARS_GAME_GEOMETRY):
            window_id = int(line.strip())
            logging.debug("Pressing Alt R")
            cmd = "xdotool windowactivate {0!s} key Alt key R".format(window_id)
            result = subprocess.check_output(cmd, shell=True)

            time.sleep(.5)
            cmd = "xdotool windowactivate {0!s} key D".format(window_id)
            result = subprocess.check_output(cmd, shell=True)

            time.sleep(.5)
            cmd = "xdotool windowactivate {0!s} key U".format(window_id)
            result = subprocess.check_output(cmd, shell=True)

            time.sleep(.5)

            return

    raise Exception("Could not find main game window.")


text:
package com.microsoft.bingads.v12.api.test.entities.adgroup.read;

import java.util.Arrays;
import java.util.Collection;

import org.junit.Test;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;

import com.microsoft.bingads.internal.functionalinterfaces.Function;
import com.microsoft.bingads.v12.api.test.entities.adgroup.BulkAdGroupTest;
import com.microsoft.bingads.v12.bulk.entities.BulkAdGroup;

public class BulkAdGroupReadFromRowValuesTrackingTemplateTest extends BulkAdGroupTest{

	@Parameter(value = 1)
	public String expectedResult;

	@Parameters
	public static Collection<Object[]> data() {
		return Arrays.asList(new Object[][] {
			{"", ""},
			{"template", "template"},
		});
	}

	@Test
	public void testRead() {
		this.<String>testReadProperty("Tracking Template", this.datum, this.expectedResult, new Function<BulkAdGroup, String>() {
			@Override
			public String apply(BulkAdGroup c) {
				return c.getAdGroup().getTrackingUrlTemplate();
			}
		});
	}
}


text:
Dispatcher is a front controller of whole api.

Its responsibility is matching request via [router](router.md), invoking [endpoint](endpoints.md) through handler and returning response from that endpoint.

Also sends 404 response if request is not matched with an endpoint.

## CoreDispatcher

Basic implementation of dispatcher - do exactly what is described in [the previous section](#dispatcher).

## DecoratedDispatcher

Adds decorators for advanced handling of request and response transformations.

For more information see chapter about [decorators](decorators.md)

## JsonDispatcher

Adds possibility to return scalar or array from endpoint - raw data are transformed into response with status 200 and Content-Type application/json.

Used by default (but could be overriden by decorator plugin)

> Incompatible with [decorators](decorators.md), alternative solution is available in [apitte/negotiation transformers](https://github.com/apitte/negotiation)


text:
`Allegro` is an advanced Swift reflection utility that allows you to create classes and structs at run-time:
```swift
struct Person {
   var name: String
   var age: Int
   var friends: [Person]
}
// Returns fields for Person
let fields = try fieldsForType(Person)
// Constructs Person
let person: Person = try constructType { field in
  // return value for field
}
```
Be aware that every property of the type you'd like to construct must conform to `Property`.

## Installation

### CocoaPods

`Allegro` is available through [CocoaPods](http://cocoapods.org). To install, simply include the following lines in your podfile:
```ruby
use_frameworks!
pod 'Allegro'
```
Be sure to import the module at the top of your .swift files:
```swift
import Allegro
```
### Carthage
`Allegro` is also available through [Carthage](https://github.com/Carthage/Carthage). Just add the following to your cartfile:
```
github "bradhilton/Allegro"
```
Be sure to import the module at the top of your .swift files:
```swift
import Allegro
```
### Swift Package Manager
You can also build `Allegro` using the [Swift Package Manager](https://github.com/apple/swift-package-manager). Just include `Allegro` as a package in your dependencies:
```
.Package(url: "https://github.com/bradhilton/Allegro.git", majorVersion: 1)
```
Be sure to import the module at the top of your .swift files:
```swift
import Allegro
```

## Revision History

* 1.0.0 - Initial Release

## Author

Brad Hilton, brad@skyvive.com

## License

`Allegro` is available under the MIT license. See the LICENSE file for more info.


text:
{-# LANGUAGE Arrows #-}
module Types where

import FRP.Yampa
import FRP.Yampa.Vector3

import Graphics.UI.GLUT hiding (Level,Vector3(..),normalize)
import qualified Graphics.UI.GLUT as G(Vector3(..))

type R = GLdouble

data Point3D = P3D { x :: Integer, y :: Integer, z :: Integer } deriving (Show)

data Level = Level { startingPoint :: Point3D,
                     endPoint      :: Point3D,
                     obstacles     :: [Point3D] }

data Input = Keyboard { key       :: Key,
                        keyState  :: KeyState,
                        modifiers :: Modifiers }

data GameState = Game { level     :: Level,
                        rotX      :: R,
                        playerPos :: Vector3 R }

data ParsedInput =
    ParsedInput { wCount :: Double, aCount :: Double,
                  sCount :: Double, dCount :: Double,
                  upEvs  :: Event Input, downEvs :: Event Input,
                  rightEvs :: Event Input, leftEvs :: Event Input }


text:
package org.osmdroid.tileprovider;

import android.content.Context;
import android.os.Build;

import org.osmdroid.tileprovider.modules.IFilesystemCache;
import org.osmdroid.tileprovider.modules.INetworkAvailablityCheck;
import org.osmdroid.tileprovider.modules.MapTileApproximater;
import org.osmdroid.tileprovider.modules.MapTileAssetsProvider;
import org.osmdroid.tileprovider.modules.MapTileDownloader;
import org.osmdroid.tileprovider.modules.MapTileFileArchiveProvider;
import org.osmdroid.tileprovider.modules.MapTileFileStorageProviderBase;
import org.osmdroid.tileprovider.modules.MapTileFilesystemProvider;
import org.osmdroid.tileprovider.modules.MapTileModuleProviderBase;
import org.osmdroid.tileprovider.modules.MapTileSqlCacheProvider;
import org.osmdroid.tileprovider.modules.NetworkAvailabliltyCheck;
import org.osmdroid.tileprovider.modules.SqlTileWriter;
import org.osmdroid.tileprovider.modules.TileWriter;
import org.osmdroid.tileprovider.tilesource.ITileSource;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.tileprovider.util.SimpleRegisterReceiver;
import org.osmdroid.util.MapTileAreaBorderComputer;
import org.osmdroid.util.MapTileAreaZoomComputer;
import org.osmdroid.util.MapTileIndex;

/**
 * This top-level tile provider implements a basic tile request chain which includes a
 * {@link MapTileFilesystemProvider} (a file-system cache), a {@link MapTileFileArchiveProvider}
 * (archive provider), and a {@link MapTileDownloader} (downloads map tiles via tile source).
 * <p>
 * Behavior change since osmdroid 5.3: If the device is less than API 10, the file system based cache and writer are used
 * otherwise, the sqlite based
 *
 * @author Marc Kurtz
 * @see TileWriter
 * @see SqlTileWriter
 * @see MapTileFilesystemProvider
 * @see MapTileSqlCacheProvider
 */
public class MapTileProviderBasic extends MapTileProviderArray implements IMapTileProviderCallback {

	protected IFilesystemCache tileWriter;
	final private INetworkAvailablityCheck mNetworkAvailabilityCheck;

	/**
	 * @since 6.1.0
	 */
	final private MapTileDownloader mDownloaderProvider;
	final private MapTileApproximater mApproximationProvider;

	/**
	 * Creates a {@link MapTileProviderBasic}.
	 */
	public MapTileProviderBasic(final Context pContext) {
		this(pContext, TileSourceFactory.DEFAULT_TILE_SOURCE);
	}

	/**
	 * Creates a {@link MapTileProviderBasic}.
	 */
	public MapTileProviderBasic(final Context pContext, final ITileSource pTileSource) {
		this(pContext, pTileSource, null);
	}

	/**
	 * Creates a {@link MapTileProviderBasic}.
	 */
	public MapTileProviderBasic(final Context pContext, final ITileSource pTileSource, final IFilesystemCache cacheWriter) {
		this(new SimpleRegisterReceiver(pContext), new NetworkAvailabliltyCheck(pContext),
				pTileSource, pContext,cacheWriter);
	}

	/**
	 * Creates a {@link MapTileProviderBasic}.
	 */
	public MapTileProviderBasic(final IRegisterReceiver pRegisterReceiver,
			final INetworkAvailablityCheck aNetworkAvailablityCheck, final ITileSource pTileSource,
			final Context pContext, final IFilesystemCache cacheWriter) {
		super(pTileSource, pRegisterReceiver);

		mNetworkAvailabilityCheck = aNetworkAvailablityCheck;

		if (cacheWriter != null) {
			tileWriter = cacheWriter;
		} else {
			if (Build.VERSION.SDK_INT < 10) {
				tileWriter = new TileWriter();
			} else {
				tileWriter = new SqlTileWriter();
			}
		}
		final MapTileFileStorageProviderBase assetsProvider =
				createAssetsProvider(pRegisterReceiver, pTileSource, pContext);
		mTileProviderList.add(assetsProvider);

		final MapTileFileStorageProviderBase cacheProvider =
				getMapTileFileStorageProviderBase(pRegisterReceiver, pTileSource, tileWriter);
		mTileProviderList.add(cacheProvider);

		final MapTileFileStorageProviderBase archiveProvider =
				createArchiveProvider(pRegisterReceiver, pTileSource);
		mTileProviderList.add(archiveProvider);

		mApproximationProvider =
				createApproximater(assetsProvider, cacheProvider, archiveProvider);
		mTileProviderList.add(mApproximationProvider);

		mDownloaderProvider =
				createDownloaderProvider(aNetworkAvailablityCheck, pTileSource);
		mTileProviderList.add(mDownloaderProvider);

		// protected-cache-tile computers
		getTileCache().getProtectedTileComputers().add(new MapTileAreaZoomComputer(-1));
		getTileCache().getProtectedTileComputers().add(new MapTileAreaBorderComputer(1));
		getTileCache().setAutoEnsureCapacity(false);
		getTileCache().setStressedMemory(false);

		// pre-cache providers
		getTileCache().getPreCache().addProvider(assetsProvider);
		getTileCache().getPreCache().addProvider(cacheProvider);
		getTileCache().getPreCache().addProvider(archiveProvider);
		getTileCache().getPreCache().addProvider(mDownloaderProvider);

		// tiles currently being processed
		getTileCache().getProtectedTileContainers().add(this);

		setOfflineFirst(true);
	}

	protected MapTileApproximater createApproximater(MapTileFileStorageProviderBase assetsProvider, MapTileFileStorageProviderBase cacheProvider, MapTileFileStorageProviderBase archiveProvider) {
		MapTileApproximater approximationProvider = new MapTileApproximater();
		approximationProvider.addProvider(assetsProvider);
		approximationProvider.addProvider(cacheProvider);
		approximationProvider.addProvider(archiveProvider);
		return approximationProvider;
	}

	protected MapTileFileStorageProviderBase createArchiveProvider(IRegisterReceiver pRegisterReceiver, ITileSource pTileSource) {
		return new MapTileFileArchiveProvider(
				pRegisterReceiver, pTileSource);
	}

	protected MapTileFileStorageProviderBase createAssetsProvider(IRegisterReceiver pRegisterReceiver, ITileSource pTileSource, Context pContext) {
		return new MapTileAssetsProvider(
				pRegisterReceiver, pContext.getAssets(), pTileSource);
	}

	@Override
	public IFilesystemCache getTileWriter() {
		return tileWriter;
	}

	/**
	 * @since 6.1.7
	 * allow customization of tile downloader per tile source
	 */
	protected MapTileDownloader createDownloaderProvider(INetworkAvailablityCheck aNetworkAvailablityCheck, ITileSource pTileSource) {
		return new MapTileDownloader(pTileSource, this.tileWriter, aNetworkAvailablityCheck);
	}

	@Override
	public void detach(){
		//https://github.com/osmdroid/osmdroid/issues/213
		//close the writer
		if (tileWriter!=null)
			tileWriter.onDetach();
		tileWriter=null;
		super.detach();
	}

	/**
	 * @since 6.0.3
	 */
	@Override
	protected boolean isDowngradedMode(final long pMapTileIndex) {
		if ((mNetworkAvailabilityCheck != null && !mNetworkAvailabilityCheck.getNetworkAvailable())
				|| !useDataConnection()) {
			return true;
		}
		int zoomMin = -1;
		int zoomMax = -1;
		for(final MapTileModuleProviderBase provider : mTileProviderList) {
			if (provider.getUsesDataConnection()) {
				int tmp;
				tmp = provider.getMinimumZoomLevel();
				if (zoomMin == -1 || zoomMin > tmp) {
					zoomMin = tmp;
				}
				tmp = provider.getMaximumZoomLevel();
				if (zoomMax == -1 || zoomMax < tmp) {
					zoomMax = tmp;
				}
			}
		}
		if (zoomMin == -1 || zoomMax == -1) {
			return true;
		}
		final int zoom = MapTileIndex.getZoom(pMapTileIndex);
		return zoom < zoomMin || zoom > zoomMax;
	}

	/**
	 * @since 6.0.3
	 * cf. https://github.com/osmdroid/osmdroid/issues/1172
	 */
	public static MapTileFileStorageProviderBase getMapTileFileStorageProviderBase(
			final IRegisterReceiver pRegisterReceiver,
			final ITileSource pTileSource,
			final IFilesystemCache pTileWriter
	) {
		if (pTileWriter instanceof TileWriter) {
			return new MapTileFilesystemProvider(pRegisterReceiver, pTileSource);
		}
		return new MapTileSqlCacheProvider(pRegisterReceiver, pTileSource);
	}

	/**
	 * @since 6.1.0
	 * @return true if possible and done
	 */
	public boolean setOfflineFirst(final boolean pOfflineFirst) {
		int downloaderIndex = -1;
		int approximationIndex = -1;
		int i = 0;
		for(final MapTileModuleProviderBase provider : mTileProviderList) {
			if (downloaderIndex == -1 && provider == mDownloaderProvider) {
				downloaderIndex = i;
			}
			if (approximationIndex == -1 && provider == mApproximationProvider) {
				approximationIndex = i;
			}
			i++;
		}
		if (downloaderIndex == -1 || approximationIndex == -1) {
			return false;
		}
		if (approximationIndex < downloaderIndex && pOfflineFirst) {
			return true;
		}
		if (approximationIndex > downloaderIndex && !pOfflineFirst) {
			return true;
		}
		mTileProviderList.set(downloaderIndex, mApproximationProvider);
		mTileProviderList.set(approximationIndex, mDownloaderProvider);
		return true;
	}
}


text:
- [About](#about)
- [Settings](#settings)
- [Development](#development)
 - [Requirements](#requirements)
 - [Setup](#setup)
 - [Run with development mode](#run-with-development-mode)
 - [Release Build](#release-build)
- [License](#license)

## About

**Bitbucket Browser** is a Viewer for [Atlassian Bitbucket (formerly Stash)](https://bitbucket.org/).

![Bitbucket Browser](./images/browser.png)

## Deploy
**Bitbucket Browser** is made by static files only and **it's not Bitbucket plugins**. You can deploy the files to the reverse proxy web server which is in front of your Bitbucket server.

### Notes
You must setup the web server to proxy Bitbucket server and configure cookie path converting correctly in order to use the Bitbucket server cookie.

For example, if your web server proxy Bitbucket server to `/bitbucket` and you deploy **Bitbucket Browser** under `/bitbucket-browser`, you should configure to convert the cookie path from `/bitbucket` to `/`.

## Settings

1. Rename `settings.json.sample` file to `settings.json`.
2. Edit `settings.json`. You can customize the column's displayName and enabled options.

```
{
    "title": "Bitbucket Browser",
    "baseUrl": "/bitbucket-browser/bitbucket",
    "linkBaseUrl": "http://your-bitbucket-host/bitbucket",
    "debug": false,
    "items": {
        "project": {
            "displayName": "Project"
        },
        "repo": {
            "displayName": "Repository"
        },
        "branch": {
            "displayName": "Branch"
        },
        "branchAuthor": {
            "enabled": false,
            "displayName": "Branch Author"
        },
        "branchCreated": {
            "enabled": true,
            "displayName": "Branch Created"
        },
        "latestCommitDate": {
            "enabled": true,
            "displayName": "Updated"
        },
        "behindAheadBranch": {
            "enabled": true,
            "displayName": "Behind/Ahead Branch"
        },
        "pullRequestStatus": {
            "enabled": true,
            "displayName": "Pull Request Status"
        },
        "buildStatus": {
            "enabled": true,
            "displayName": "Build Status"
        },
        "sonarForBitbucketStatus": {
            "enabled": false,
            "displayName": "Sonar for Stash Metric",
            "resolver": {
                "fields": [
                    {
                        "key": "duplicatedLines",
                        "displayName": "Dupl. lines",
                        "enabled": true
                    },
                    {
                        "key": "coverage",
                        "displayName": "Coverage",
                        "enabled": true
                    },
                    {
                        "key": "violations",
                        "displayName": "Issues",
                        "enabled": false
                    },
                    {
                        "key": "technicalDebt",
                        "displayName": "Tech. dept",
                        "enabled": true
                    }
                ]
            }
        },
        "sonarQubeMetrics": {
            "enabled": false,
            "displayName": "SonarQube Metrics",
            "resolver": {
                "baseUrl": "/sonar",
                "projectBaseKey": "foo.bar",
                "__comment__": "see http://docs.sonarqube.org/display/SONARQUBE43/Metric+definitions",
                "fields": [
                    {
                        "key": "lines",
                        "displayName": "Lines",
                        "enabled": true
                    },
                    {
                        "key": "duplicated_lines",
                        "displayName": "Dupl. lines",
                        "enabled": false
                    },
                    {
                        "key": "blocker_violations",
                        "displayName": "Blocker issues",
                        "enabled": true
                    },
                    {
                        "key": "critical_violations",
                        "displayName": "Critical issues",
                        "enabled": true
                    },
                    {
                        "key": "mejor_violations",
                        "displayName": "Major issues",
                        "enabled": false
                    },
                    {
                        "key": "minor_violations",
                        "displayName": "Minor issues",
                        "enabled": false
                    },
                    {
                        "key": "info_violations",
                        "displayName": "Info issues",
                        "enabled": false
                    },
                    {
                        "key": "sqale_index",
                        "displayName": "Tech. dept",
                        "enabled": false
                    }
                ]
            }
        },
        "branchNameLink": {
            "enabled": true,
            "displayName": "JIRA Ticket",
            "resolver": {
                "pattern": "ISSUE\\-[0-9]+",
                "baseUrl": "http://jira.example.org/browse",
                "displayName": "JIRA Ticket"
            }
        },
        "jiraIssue": {
            "enabled": true,
            "displayName": "JIRA Ticket",
            "resolver": {
                "pattern": "ISSUE\\-[0-9]+",
                "baseUrl": "/jira",
                "linkBaseUrl": "http://jira.example.org/jira/browse",
                "fields": [
                    {
                        "key": "status.name",
                        "displayName": "Status",
                        "enabled": true
                    },
                    {
                        "key": "created",
                        "displayName": "Created",
                        "datePattern": "YYYY/MM/DD",
                        "enabled": true
                    }
                ]
            }
        }
    }
}
```

## Development

### Requirements

* [Node.js](https://nodejs.org/)

### Setup

1. Install JavaScript dependencies.

 ```bash
npm install
 ```

### Run with development mode

1. Run dummy bitbucket server for development.

 ```bash
npm run server
 ```

2. Run webpack dev server.

 ```bash
npm start
 ```

3. Create `public/settings.json` for development environment.

 ```bash
cp settings.json.sample public/
 ```

4. Edit `baseUrl` in `public/settings.json` as follows.

 ```
{
    "title": "Bitbucket Browser",
    "baseUrl": "/bitbucket",
 ```

5. Open http://localhost:9000

### Release Build

Run webpack with production mode. All you have to do is run `npm run build`. The artifacts are created under `./public` directory.

```bash
npm run build
```

## License

Licensed under the [MIT](/LICENSE.txt) license.


text:
using System;

namespace Vici.Core.Parser
{
    internal class MacroDefinitionTemplateNode : ExpressionTemplateNode
    {
        public MacroDefinitionTemplateNode(TemplateToken templateToken) : base(templateToken)
        {
        }
    }
}


text:
package hr.foi.air.foirun.fragments;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import butterknife.BindView;
import butterknife.ButterKnife;
import hr.foi.air.database.entities.ActivityType;
import hr.foi.air.foirun.R;

/**
 * A simple {@link Fragment} subclass.
 */
public class StopActivityFragment extends Fragment {

    @BindView(R.id.distance)
    TextView distanceTxt;

    @BindView(R.id.activity)
    TextView activityTxt;

    @BindView(R.id.time)
    TextView timeTxt;

    public StopActivityFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.stop_activity, container, false);

        ButterKnife.bind(this, view);

        // Inflate the layout for this fragment
        return view;
    }

    public void setDistanceTxt(double distance) {
        this.distanceTxt.setText(String.format( "Distance:\t\t %.2f m", distance ));
    }

    public void setTimeTxt(long milis) {
        int seconds = (int) (milis / 1000) % 60 ;
        int minutes = (int) ((milis / (1000*60)) % 60);
        int hours   = (int) ((milis / (1000*60*60)) % 24);

        this.timeTxt.setText( String.format( "Time:\t\t %02d h %02d min %02d sec", hours, minutes, seconds ) );
    }

    public void setActivityTxt(int typeId) {
        ActivityType type = ActivityType.getById(typeId);

        this.activityTxt.setText(String.format( "Activity:\t\t %s", type.getName() ));
    }
}


text:
/**
 *  @namespace GeometryTools
 *  @memberof SQR
 *
 *  @description Tools to work with geometries/buffers.
 */
SQR.GeometryTools = (function() {

	var geoTools = {};
	var MAX_BUFFER_SIZE = 65535;

	/**
	 *	@method batch
	 *	@memberof SQR.GeometryTools
	 *
	 *	@description Combines all the geometries in a tree into one geometry. It assumes (but does not check)
	 *	that all the children can be rendered using the same shader and that all their buffers have the same
	 *	layout.
	 *
	 *	@param {SQR.Transform} container - the root of the tree to combine.
	 *	This object and all it's children will be combined.
	 *
	 *	@returns {SQR.Transform} the same object as passed in the argument. It will have no children
	 *	and will have a buffer containing all the combine geometries. If the container shader was not set
	 *	it will inherit the shader from the first child that had one.
	 */
	geoTools.batch = function(container) {
		var batchObjects = [], size = 0;

		var updateTransform = function(t) {

			t.transformWorld();

			if (t.numChildren > 0) {
	            for (var i = 0; i < t.numChildren; i++) {
	                updateTransform(t.children[i]);
	            }
	        }

	        if(t.buffer) {
	        	if(t.buffer.isIndexed()) {
	        		console.warn("> SQR.GeometryTools.batch - indexed buffers can't be batched (yet)");
	        	} else {
	        		batchObjects.push(t);
	        		size += t.buffer.size;
	        	}
	        }

	        if(t.shader && !container.shader) {
	        	container.shader = t.shader;
	        }
		}

		updateTransform(container);

		var cb = SQR.Buffer().layout(batchObjects[0].buffer.layout, size);

		var offset = 0, base = 0, tmp = new SQR.V3(), tmpMat = new SQR.Matrix33(), c = 0;

		for(var i = 0; i < batchObjects.length; i++) {
				var bo = batchObjects[i];
				var b = batchObjects[i].buffer;
				var tb = new Float32Array(b.size * b.strideSize);
				tb.set(b.getDataArray());

				b.iterate('aPosition', function(i, d, c) {
					tmp.set(d[i+0], d[i+1], d[i+2], 1);
					bo.globalMatrix.transformVector(tmp);
					tb[i+0] = tmp.x;
					tb[i+1] = tmp.y;
					tb[i+2] = tmp.z;
				});

				b.iterate('aNormal', function(i, d, c) {
					tmp.set(d[i+0], d[i+1], d[i+2]);
					bo.globalMatrix.inverseMat3(tmpMat);
					tmpMat.transformVector(tmp);
					tb[i+0] = tmp.x;
					tb[i+1] = tmp.y;
					tb[i+2] = tmp.z;
				});

				cb.setRawData(tb, offset - base);

				offset += b.size * b.strideSize;

				c++;
		}

		// console.log('batched ' + container.numChildren + ' geometries, ' + size + ' vertices, ' + offset + ' elements in array');

		container.removeAll();
		container.buffer = cb.update();

		return container;
	}

	return geoTools;

})();


text:
module m_handlers

  use FoX_common
  use FoX_sax

  implicit none
  private

    public :: error_handler
    public :: fatalError_handler

contains

  subroutine error_handler(msg)
    character(len=*), intent(in) :: msg
    write(*,'(a)') "Error encountered and caught"
    write(*,'(a)') msg
  end subroutine error_handler

  subroutine fatalError_handler(msg)
    character(len=*), intent(in) :: msg
    write(*,'(a)') "Fatal error encountered and caught"
    write(*,'(a)') msg
  end subroutine fatalError_handler

end module m_handlers

program sax_well_formed
  !
  ! Check for well-formedness - nothing happens on success;
  ! error message omitted and execution halt on any failure.
  !
  use FoX_sax
  use m_handlers
  implicit none

  integer :: iostat
  type(xml_t)  :: fxml

  call open_xml_file(fxml, "test.xml", iostat=iostat)
  if (iostat /= 0) then
    write(*,*) "Cannot open file."
    stop
  endif

  call parse(fxml,&
    error_handler=error_handler,                 &
    fatalError_handler=fatalError_handler, &
    namespaces=.false.,  &
    validate=.true.)

  call close_xml_t(fxml)

  print*, "Finished"

end program sax_well_formed


text:
title: Apache Mesos - Committers
layout: documentation
---

# Committers

An Apache Mesos committer is a contributor who has been given write access to the Apache Mesos code repository and related Apache infrastructure. In the Mesos project, each committer is also a voting member of the PMC.

## Becoming a committer

Every new committer has to be proposed by a current committer and then voted in by the members of the Mesos PMC. For details about this process and for candidate requirements see the general [Apache guidelines for assessing new candidates for committership](https://community.apache.org/newcommitter.html). Candidates prepare for their nomination as committer by contributing to the Mesos project and its community, by acting according to the [Apache Way](http://theapacheway.com), and by generally following the path [from contributor to committer](https://community.apache.org/contributors/) for Apache projects. Specifically for the Mesos project, you can make use of the [Apache Mesos Committer Candidate Checklist](committer-candidate-checklist.md) for suggestions of what kind of contributions and demonstrated behaviors can be instrumental, and to keep track of your progress.

## Current Committers

We'd like to thank the following committers to the Apache Mesos project who have helped get the project to where it is today. This list might be stale, the canonical list is located on [Apache's website](http://people.apache.org/committers-by-project.html#mesos).

      Timezone GMT
      Full Name
      Company/Organization
      IRC Handle
      Email Address

      -8
      Ross Allen
      Facebook

      ssorallen@apache.org

      -5
      Kapil Arya
      Mesosphere / Northeastern University

      kapil@apache.org

      -8
      Adam B
      Mesosphere
      adam-mesos
      me@apache.org

      -8
      Tim Chen
      Mesosphere
      tnachen
      tnachen@apache.org

      -8
      Ian Downes
      Twitter
      idownes
      idownes@apache.org

      -8
      Ali Ghodsi
      UC Berkeley

      alig@apache.org

      -8
      Dominic Hamon
      YouTube

      dma@apache.org

      -8
      Benjamin Hindman
      Mesosphere
      _benh_
      benh@apache.org

      -8
      Ian Holsman

      ianh@apache.org

      -8
      Vinod Kone
      Mesosphere
      vinodkone
      vinodkone@apache.org

      -8
      Andy Konwinski
      Databricks

      andrew@apache.org

      -8
      Dave Lester
      Apple
      dlester
      dlester@apache.org

      -8
      Benjamin Mahler
      Mesosphere
      bmahler
      bmahler@apache.org

      -8
      Thomas Marshall
      Carnegie Mellon University

      tmarshall@apache.org

      +1
      Bernd Mathiske
      Mesosphere
      bernd
      bernd@apache.org

      -8
      Brenden Matthews
      Mesosphere
      brenden_
      brenden@apache.org

      -8
      Chris Mattmann
      NASA JPL

      mattmann@apache.org

      -8
      Anand Mazumdar
      Mesosphere
      anandm
      anand@apache.org

      -8
      Brian McCallister
      Groupon

      brianm@apache.org

      -8
      Niklas Quarfot Nielsen
      Intel
      niq_
      nnielsen@apache.org

      -5
      Michael Park
      Mesosphere
      mpark
      mpark@apache.org

      +1
      Alex R
      Mesosphere
      alexr
      alexr@apache.org

      -8
      Charles Reiss
      UC Berkeley

      woggle@apache.org

      -8
      Joris Van Remoortere
      Mesosphere
      joris
      joris@apache.org

      -5
      Timothy St Clair
      Redhat
      tstclair
      tstclair@apache.org

      +1
      Till Toenshoff
      Mesosphere
      tillt
      tillt@apache.org

      -8
      Thomas White
      Cloudera

      tomwhite@apache.org

      -8
      Joseph Wu
      Mesosphere

      josephwu@apache.org

      -8
      Yan Xu
      Apple
      xujyan
      yan@apache.org

      -8
      Jie Yu
      Mesosphere
      jieyu
      jieyu@apache.org

      -8
      Matei Alexandru Zaharia
      Databricks

      matei@apache.org

If you're interested in becoming a committer yourself, the best way to do so is by participating in developer discussions and contributing patches to the project.

## Component Maintainers

We currently make no distinction between committers and PMC members. As such, **every committer is responsible for the quality of the entire codebase**. Some components are widely maintained (e.g. build and support tooling, tests, etc), whereas some components are inherently more critical / complex and have committers with increased context, interest, and long-term perspective.

We aim to have more than one maintainer for each component, in order to ensure that contributors can obtain timely feedback. To avoid information silos, we encourage committers to learn about areas of the code that they are unfamiliar with.

When sending reviews, it can be valuable to consult the component maintainers, as specified below. Component maintainers do not have any special "ownership" over the code, but merely serve as a resource for obtaining valuable feedback in a timely manner. We trust every committer to use good judgement to determine when to obtain feedback from component maintainers.

      Component
      Maintainers (alphabetical)

      Master / Agent
      Benjamin Hindman, Vinod Kone, Benjamin Mahler, Jie Yu

      Framework API
      Benjamin Hindman, Vinod Kone, Benjamin Mahler, Jie Yu

      State Libraries
      Benjamin Hindman, Benjamin Mahler

      Replicated Log
      Benjamin Hindman, Jie Yu

      ZooKeeper Bindings
      Benjamin Hindman, Vinod Kone, Benjamin Mahler, Yan Xu

      Authentication / Authorization
      Adam B, Vinod Kone, Till Toenshoff

      Modules / Hooks
      Kapil Arya, Benjamin Hindman, Niklas Nielsen

      Oversubscription
      Vinod Kone, Niklas Nielsen, Jie Yu

      CLI
      maintainers needed

      WebUI
      maintainers needed

      Project Website
      Dave Lester

#### Containerization

      Component
      Maintainers (alphabetical)

        Mesos Containerizer
        Ian Downes, Jie Yu

        Docker Containerizer
        Tim Chen, Benjamin Hindman

        External Containerizer
        Till Toenshoff, Benjamin Hindman

#### C++ Libraries

      Component
      Maintainers (alphabetical)

      Libprocess
      Benjamin Hindman, Benjamin Mahler, Jie Yu

      Stout
      Benjamin Hindman, Vinod Kone, Benjamin Mahler, Jie Yu


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

using System;
using System.Linq;
using Org.Apache.REEF.Common.Context;
using Org.Apache.REEF.Common.Events;
using Org.Apache.REEF.Common.Tasks;
using Org.Apache.REEF.Driver;
using Org.Apache.REEF.Driver.Context;
using Org.Apache.REEF.Driver.Evaluator;
using Org.Apache.REEF.Driver.Task;
using Org.Apache.REEF.Tang.Annotations;
using Org.Apache.REEF.Tang.Interface;
using Org.Apache.REEF.Tang.Util;
using Org.Apache.REEF.Tests.Functional.Bridge.Exceptions;
using Org.Apache.REEF.Tests.Functional.Common.Task;
using Org.Apache.REEF.Utilities.Logging;
using Xunit;

namespace Org.Apache.REEF.Tests.Functional.Failure.User
{
    /// <summary>
    /// This class contains a test that tests whether throwing an Exception in ContextStopHandler behaves correctly.
    /// </summary>
    [Collection("FunctionalTests")]
    public sealed class ContextStopExceptionTest : ReefFunctionalTest
    {
        private static readonly Logger Logger = Logger.GetLogger(typeof(ContextStopExceptionTest));

        private static readonly string ExpectedException = "ExpectedException";
        private static readonly string FailEvaluatorContextId = "FailEvaluatorContextId";
        private static readonly string ContextId0 = "ContextId0";
        private static readonly string ContextId1 = "ContextId1";
        private static readonly string TaskId = "TaskId";
        private static readonly string CompletedTaskReceived = "CompletedTaskReceived";
        private static readonly string FailedContextReceived = "FailedContextReceived";
        private static readonly string FailedEvaluatorReceived = "FailedEvaluatorReceived";

        /// <summary>
        /// This test tests whether throwing an Exception in ContextStopHandler behaves correctly.
        /// The test requests two Evaluators, the first Evaluator will only have a Root Context on which
        /// will throw an Exception upon calling ActiveContext.Dispose. The second Evaluator will have two
        /// stacked Contexts - ContextId1 will be stacked on top of ContextId0. ContextId1 will contain the
        /// failing ContextStopHandler, in which the Evaluator will pop the Context and submit a Task to ContextId0,
        /// verify that the Task completes successfully, and verify that the Context is disposed without an Exception.
        /// </summary>
        [Fact]
        [Trait("Priority", "1")]
        [Trait("Category", "FunctionalGated")]
        [Trait("Description", "Test throwing an Exception in ContextStopHandler should cause the Driver to receive a ContextFailed event." +
                              "In the case of the Root Context, the Driver should receive a FailedEvaluator event.")]
        public void TestContextStopException()
        {
            string testFolder = DefaultRuntimeFolder + TestId;
            TestRun(
                DriverConfiguration.ConfigurationModule
                    .Set(DriverConfiguration.OnDriverStarted, GenericType<ContextStopExceptionDriver>.Class)
                    .Set(DriverConfiguration.OnEvaluatorAllocated, GenericType<ContextStopExceptionDriver>.Class)
                    .Set(DriverConfiguration.OnEvaluatorFailed, GenericType<ContextStopExceptionDriver>.Class)
                    .Set(DriverConfiguration.OnContextActive, GenericType<ContextStopExceptionDriver>.Class)
                    .Set(DriverConfiguration.OnContextFailed, GenericType<ContextStopExceptionDriver>.Class)
                    .Set(DriverConfiguration.OnTaskCompleted, GenericType<ContextStopExceptionDriver>.Class)
                    .Build(),
                typeof(ContextStopExceptionDriver), 1, "ContextStopExceptionTest", "local", testFolder);

            ValidateSuccessForLocalRuntime(numberOfContextsToClose: 3, numberOfTasksToFail: 0, numberOfEvaluatorsToFail: 1, testFolder: testFolder);
            var driverMessages = new[]
            {
                CompletedTaskReceived,
                FailedContextReceived,
                FailedEvaluatorReceived
            };

            ValidateMessagesSuccessfullyLoggedForDriver(driverMessages, testFolder);
            CleanUp(testFolder);
        }

        private sealed class ContextStopExceptionDriver :
            IObserver<IDriverStarted>,
            IObserver<IAllocatedEvaluator>,
            IObserver<IActiveContext>,
            IObserver<IFailedContext>,
            IObserver<IFailedEvaluator>,
            IObserver<ICompletedTask>
        {
            private readonly IEvaluatorRequestor _requestor;
            private readonly object _lock = new object();
            private bool _shouldSubmitFailEvaluatorContext = true;

            [Inject]
            private ContextStopExceptionDriver(IEvaluatorRequestor requestor)
            {
                _requestor = requestor;
            }

            public void OnNext(IDriverStarted value)
            {
                _requestor.Submit(_requestor.NewBuilder().SetNumber(2).Build());
            }

            public void OnNext(IAllocatedEvaluator value)
            {
                lock (_lock)
                {
                    if (_shouldSubmitFailEvaluatorContext)
                    {
                        // This context should fail the Evaluator upon calling ActiveContext.Dispose().
                        value.SubmitContext(
                            GetContextStopExceptionContextConfiguration(FailEvaluatorContextId));
                        _shouldSubmitFailEvaluatorContext = false;
                    }
                    else
                    {
                        // This is the Context that will be stacked upon by ContextId1.
                        value.SubmitContext(
                            ContextConfiguration.ConfigurationModule
                                .Set(ContextConfiguration.Identifier, ContextId0)
                                .Build());
                    }
                }
            }

            /// <summary>
            /// This will be ContextId1.
            /// It will submit a Task to the parent of Context with ContextId1.
            /// </summary>
            public void OnNext(IFailedContext value)
            {
                Assert.Equal(ContextId1, value.Id);
                Assert.True(value.ParentContext.IsPresent());
                Assert.Equal(ContextId0, value.ParentContext.Value.Id);

                // TODO[JIRA REEF-1468]: Validate that Exception is properly serialized.
                Logger.Log(Level.Info, FailedContextReceived);

                value.ParentContext.Value.SubmitTask(
                    TaskConfiguration.ConfigurationModule
                        .Set(TaskConfiguration.Identifier, TaskId)
                        .Set(TaskConfiguration.Task, GenericType<NullTask>.Class)
                        .Build());
            }

            /// <summary>
            /// This will be a FailedEvaluator generated by the Context with ID as FailEvaluatorContextId.
            /// </summary>
            public void OnNext(IFailedEvaluator value)
            {
                Assert.Equal(1, value.FailedContexts.Count);
                Assert.Equal(FailEvaluatorContextId, value.FailedContexts.First().Id);
                Assert.NotNull(value.EvaluatorException.InnerException);
                Assert.True(value.EvaluatorException.InnerException is TestSerializableException);
                Assert.Equal(ExpectedException, value.EvaluatorException.InnerException.Message);
                Logger.Log(Level.Info, FailedEvaluatorReceived);
            }

            public void OnNext(IActiveContext value)
            {
                if (value.Id.Equals(FailEvaluatorContextId))
                {
                    // Close context and trigger failure immediately.
                    value.Dispose();
                }
                else
                {
                    if (value.Id.Equals(ContextId0))
                    {
                        // Stack Context with ContextId1 on top of Context with ContextId0.
                        value.SubmitContext(GetContextStopExceptionContextConfiguration(ContextId1));
                    }
                    else
                    {
                        // Verify the stacked Context and close it.
                        Assert.Equal(ContextId1, value.Id);
                        value.Dispose();
                    }
                }
            }

            public void OnNext(ICompletedTask value)
            {
                // Verify the completion of Task on Context with ContextId0.
                Assert.Equal(TaskId, value.Id);
                Assert.Equal(ContextId0, value.ActiveContext.Id);
                Logger.Log(Level.Info, CompletedTaskReceived);
                value.ActiveContext.Dispose();
            }

            public void OnError(Exception error)
            {
                throw new NotImplementedException();
            }

            public void OnCompleted()
            {
                throw new NotImplementedException();
            }

            private static IConfiguration GetContextStopExceptionContextConfiguration(string contextId)
            {
                return ContextConfiguration.ConfigurationModule
                    .Set(ContextConfiguration.Identifier, contextId)
                    .Set(ContextConfiguration.OnContextStop, GenericType<ContextStopExceptionHandler>.Class)
                    .Build();
            }
        }

        /// <summary>
        /// A ContextStopHandler that throws a Serializable Exception.
        /// </summary>
        private sealed class ContextStopExceptionHandler : IObserver<IContextStop>
        {
            [Inject]
            private ContextStopExceptionHandler()
            {
            }

            public void OnNext(IContextStop value)
            {
                throw new TestSerializableException(ExpectedException);
            }

            public void OnError(Exception error)
            {
                throw new NotImplementedException();
            }

            public void OnCompleted()
            {
                throw new NotImplementedException();
            }
        }
    }
}