text:
package io.fabric8.forge.camel.commands.project.completer;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import org.apache.camel.builder.RouteBuilder;
import org.jboss.forge.addon.parser.java.facets.JavaSourceFacet;
import org.jboss.forge.addon.parser.java.resources.JavaResource;
import org.jboss.forge.addon.parser.java.resources.JavaResourceVisitor;
import org.jboss.forge.addon.resource.visit.VisitContext;
import org.jboss.forge.addon.ui.context.UIContext;
import org.jboss.forge.addon.ui.input.InputComponent;
import org.jboss.forge.addon.ui.input.UICompleter;
import org.jboss.forge.roaster.model.JavaClass;

public class RouteBuilderCompleter implements UICompleter<String> {

    private final Set<String> routeBuilders = new TreeSet<String>();

    public RouteBuilderCompleter(JavaSourceFacet facet) {
        // find package names in the source code
        facet.visitJavaSources(new JavaResourceVisitor() {
            @Override
            public void visit(VisitContext context, JavaResource javaResource) {
                try {
                    JavaClass clazz = javaResource.getJavaType();
                    String superType = clazz.getSuperType();
                    if (superType != null && RouteBuilder.class.getName().equals(superType) ) {
                        routeBuilders.add(clazz.getQualifiedName());
                    }
                } catch (FileNotFoundException e) {
                    // ignore
                }
            }
        });
    }

    public Set<String> getRouteBuilders() {
        return routeBuilders;
    }

    @Override
    public Iterable<String> getCompletionProposals(UIContext context, InputComponent input, String value) {
        List<String> answer = new ArrayList<String>();

        for (String name : routeBuilders) {
            if (value == null || name.startsWith(value)) {
                answer.add(name);
            }
        }

        return answer;
    }
}


text:
import { HorizontalRange } from 'vs/editor/common/view/renderingContext';
import { Constants } from 'vs/editor/common/core/uint';

class FloatHorizontalRange {
	_floatHorizontalRangeBrand: void;

	public readonly left: number;
	public readonly width: number;

	constructor(left: number, width: number) {
		this.left = left;
		this.width = width;
	}

	public toString(): string {
		return `[${this.left},${this.width}]`;
	}

	public static compare(a: FloatHorizontalRange, b: FloatHorizontalRange): number {
		return a.left - b.left;
	}
}

export class RangeUtil {

	/**
	 * Reusing the same range here
	 * because IE is buggy and constantly freezes when using a large number
	 * of ranges and calling .detach on them
	 */
	private static _handyReadyRange: Range;

	private static _createRange(): Range {
		if (!this._handyReadyRange) {
			this._handyReadyRange = document.createRange();
		}
		return this._handyReadyRange;
	}

	private static _detachRange(range: Range, endNode: HTMLElement): void {
		// Move range out of the span node, IE doesn't like having many ranges in
		// the same spot and will act badly for lines containing dashes ('-')
		range.selectNodeContents(endNode);
	}

	private static _readClientRects(startElement: Node, startOffset: number, endElement: Node, endOffset: number, endNode: HTMLElement): ClientRectList | DOMRectList | null {
		let range = this._createRange();
		try {
			range.setStart(startElement, startOffset);
			range.setEnd(endElement, endOffset);

			return range.getClientRects();
		} catch (e) {
			// This is life ...
			return null;
		} finally {
			this._detachRange(range, endNode);
		}
	}

	private static _mergeAdjacentRanges(ranges: FloatHorizontalRange[]): HorizontalRange[] {
		if (ranges.length === 1) {
			// There is nothing to merge
			return [new HorizontalRange(ranges[0].left, ranges[0].width)];
		}

		ranges.sort(FloatHorizontalRange.compare);

		let result: HorizontalRange[] = [], resultLen = 0;
		let prevLeft = ranges[0].left;
		let prevWidth = ranges[0].width;

		for (let i = 1, len = ranges.length; i < len; i++) {
			const range = ranges[i];
			const myLeft = range.left;
			const myWidth = range.width;

			if (prevLeft + prevWidth + 0.9 /* account for browser's rounding errors*/ >= myLeft) {
				prevWidth = Math.max(prevWidth, myLeft + myWidth - prevLeft);
			} else {
				result[resultLen++] = new HorizontalRange(prevLeft, prevWidth);
				prevLeft = myLeft;
				prevWidth = myWidth;
			}
		}

		result[resultLen++] = new HorizontalRange(prevLeft, prevWidth);

		return result;
	}

	private static _createHorizontalRangesFromClientRects(clientRects: ClientRectList | DOMRectList | null, clientRectDeltaLeft: number): HorizontalRange[] | null {
		if (!clientRects || clientRects.length === 0) {
			return null;
		}

		// We go through FloatHorizontalRange because it has been observed in bi-di text
		// that the clientRects are not coming in sorted from the browser

		let result: FloatHorizontalRange[] = [];
		for (let i = 0, len = clientRects.length; i < len; i++) {
			const clientRect = clientRects[i];
			result[i] = new FloatHorizontalRange(Math.max(0, clientRect.left - clientRectDeltaLeft), clientRect.width);
		}

		return this._mergeAdjacentRanges(result);
	}

	public static readHorizontalRanges(domNode: HTMLElement, startChildIndex: number, startOffset: number, endChildIndex: number, endOffset: number, clientRectDeltaLeft: number, endNode: HTMLElement): HorizontalRange[] | null {
		// Panic check
		let min = 0;
		let max = domNode.children.length - 1;
		if (min > max) {
			return null;
		}
		startChildIndex = Math.min(max, Math.max(min, startChildIndex));
		endChildIndex = Math.min(max, Math.max(min, endChildIndex));

		// If crossing over to a span only to select offset 0, then use the previous span's maximum offset
		// Chrome is buggy and doesn't handle 0 offsets well sometimes.
		if (startChildIndex !== endChildIndex) {
			if (endChildIndex > 0 && endOffset === 0) {
				endChildIndex--;
				endOffset = Number.MAX_VALUE;
			}
		}

		let startElement = domNode.children[startChildIndex].firstChild;
		let endElement = domNode.children[endChildIndex].firstChild;

		if (!startElement || !endElement) {
			// When having an empty <span> (without any text content), try to move to the previous <span>
			if (!startElement && startOffset === 0 && startChildIndex > 0) {
				startElement = domNode.children[startChildIndex - 1].firstChild;
				startOffset = Constants.MAX_SAFE_SMALL_INTEGER;
			}
			if (!endElement && endOffset === 0 && endChildIndex > 0) {
				endElement = domNode.children[endChildIndex - 1].firstChild;
				endOffset = Constants.MAX_SAFE_SMALL_INTEGER;
			}
		}

		if (!startElement || !endElement) {
			return null;
		}

		startOffset = Math.min(startElement.textContent!.length, Math.max(0, startOffset));
		endOffset = Math.min(endElement.textContent!.length, Math.max(0, endOffset));

		let clientRects = this._readClientRects(startElement, startOffset, endElement, endOffset, endNode);
		return this._createHorizontalRangesFromClientRects(clientRects, clientRectDeltaLeft);
	}
}

redpajama_set_name: RedPajamaGithub


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

using System.Collections.Generic;
using System.Reflection;
using Mosa.Runtime;

namespace System
{
	public sealed unsafe class RuntimeTypeInfo : TypeInfo
	{
		private MetadataTypeStruct* typeStruct;
		private Assembly assembly;

		//private RuntimeTypeHandle handle;
		private string assemblyQualifiedName;

		private string name;
		private string @namespace;
		private string fullname;
		private TypeCode typeCode;
		private TypeAttributes attributes;
		private Type baseType;
		private Type declaringType;
		private Type elementType;
		private Type asType;
		private LinkedList<CustomAttributeData> customAttributesData = null;

		internal readonly Type ValueType = typeof(ValueType);
		internal readonly Type EnumType = typeof(Enum);

		public override string AssemblyQualifiedName
		{
			get { return assemblyQualifiedName; }
		}

		public override Assembly Assembly
		{
			get { return assembly; }
		}

		public override TypeAttributes Attributes
		{
			get { return attributes; }
		}

		public override Type BaseType
		{
			get { return (IsInterface) ? null : baseType; }
		}

		public override bool ContainsGenericParameters
		{
			get { throw new NotImplementedException(); }
		}

		public override IEnumerable<CustomAttributeData> CustomAttributes
		{
			get
			{
				if (customAttributesData == null)
				{
					// Custom Attributes Data - Lazy load
					customAttributesData = new LinkedList<CustomAttributeData>();
					if (typeStruct->CustomAttributes != null)
					{
						var customAttributesTablePtr = typeStruct->CustomAttributes;
						var customAttributesCount = customAttributesTablePtr[0];
						customAttributesTablePtr++;
						for (uint i = 0; i < customAttributesCount; i++)
						{
							RuntimeCustomAttributeData cad = new RuntimeCustomAttributeData((MetadataCAStruct*)customAttributesTablePtr[i]);
							customAttributesData.AddLast(cad);
						}
					}
				}

				return customAttributesData;
			}
		}

		public override MethodBase DeclaringMethod
		{
			get { throw new NotImplementedException(); }
		}

		public override Type DeclaringType
		{
			get { return declaringType; }
		}

		public override string FullName
		{
			get { return fullname; }
		}

		public override int GenericParameterPosition
		{
			get { throw new NotSupportedException(); }
		}

		public override Type[] GenericTypeArguments
		{
			get { return new Type[0]; }
		}

		public override bool IsEnum
		{
			get { return BaseType == EnumType; }
		}

		public override bool IsGenericParameter
		{
			// We don't know so just return false
			get { return false; }
		}

		public override bool IsGenericType
		{
			// We don't know so just return false
			get { return false; }
		}

		public override bool IsGenericTypeDefinition
		{
			// We don't know so just return false
			get { return false; }
		}

		public override bool IsSerializable
		{
			// We don't know so just return false
			get { return false; }
		}

		public override string Name
		{
			get { return name; }
		}

		public override string Namespace
		{
			get { return @namespace; }
		}

		public RuntimeTypeInfo(RuntimeType type, Assembly assembly)
		{
			var handle = type.TypeHandle;
			asType = type;
			this.assembly = assembly;

			//this.handle = handle;
			typeStruct = (MetadataTypeStruct*)((uint**)&handle)[0];

			assemblyQualifiedName = Mosa.Runtime.Internal.InitializeMetadataString(typeStruct->Name);    // TODO
			name = Mosa.Runtime.Internal.InitializeMetadataString(typeStruct->Name);                 // TODO
			@namespace = Mosa.Runtime.Internal.InitializeMetadataString(typeStruct->Name);               // TODO
			fullname = Mosa.Runtime.Internal.InitializeMetadataString(typeStruct->Name);

			typeCode = (TypeCode)(typeStruct->Attributes >> 24);
			attributes = (TypeAttributes)(typeStruct->Attributes & 0x00FFFFFF);

			// Base Type
			if (typeStruct->ParentType != null)
			{
				RuntimeTypeHandle parentHandle = new RuntimeTypeHandle();
				((uint**)&parentHandle)[0] = (uint*)typeStruct->ParentType;
				baseType = Type.GetTypeFromHandle(parentHandle);
			}

			// Declaring Type
			if (typeStruct->DeclaringType != null)
			{
				RuntimeTypeHandle declaringHandle = new RuntimeTypeHandle();
				((uint**)&declaringHandle)[0] = (uint*)typeStruct->DeclaringType;
				declaringType = Type.GetTypeFromHandle(declaringHandle);
			}

			// Element Type
			if (typeStruct->ElementType != null)
			{
				RuntimeTypeHandle elementHandle = new RuntimeTypeHandle();
				((uint**)&elementHandle)[0] = (uint*)typeStruct->ElementType;
				elementType = Type.GetTypeFromHandle(elementHandle);
			}
		}

		public override Type AsType()
		{
			return asType;
		}

		public override int GetArrayRank()
		{
			// We don't know so just return 1 if array, 0 otherwise
			return (IsArrayImpl() == true) ? 1 : 0;
		}

		public override Type GetElementType()
		{
			return elementType;
		}

		public override Type[] GetGenericParameterConstraints()
		{
			// No planned support
			throw new NotSupportedException();
		}

		public override Type GetGenericTypeDefinition()
		{
			// No planned support
			throw new NotSupportedException();
		}

		protected override bool HasElementTypeImpl()
		{
			return (elementType != null);
		}

		protected override bool IsArrayImpl()
		{
			return typeCode == TypeCode.Array || typeCode == TypeCode.SZArray;
		}

		protected override bool IsByRefImpl()
		{
			// We don't know so just return false
			return false;
		}

		protected override bool IsNestedImpl()
		{
			return (attributes & TypeAttributes.VisibilityMask) > TypeAttributes.Public;
		}

		protected override bool IsPointerImpl()
		{
			return typeCode == TypeCode.ManagedPointer || typeCode == TypeCode.UnmanagedPointer;
		}

		protected override bool IsPrimitiveImpl()
		{
			return (typeCode == TypeCode.Boolean
				|| typeCode == TypeCode.Char
				|| (typeCode >= TypeCode.I && typeCode <= TypeCode.I8)
				|| (typeCode >= TypeCode.U && typeCode <= TypeCode.U8)
				|| typeCode == TypeCode.R4
				|| typeCode == TypeCode.R8);
		}

		protected override bool IsValueTypeImpl()
		{
			Type thisType = AsType();
			if (thisType == ValueType || thisType == EnumType)
				return false;

			return IsSubclassOf(ValueType);
		}

		public override Type MakeArrayType()
		{
			// No planned support
			throw new NotSupportedException();
		}

		public override Type MakeArrayType(int rank)
		{
			// No planned support
			throw new NotSupportedException();
		}

		public override Type MakeByRefType()
		{
			// No planned support
			throw new NotSupportedException();
		}

		public override Type MakeGenericType(params Type[] typeArguments)
		{
			// No planned support
			throw new NotSupportedException();
		}

		public override Type MakePointerType()
		{
			// No planned support
			throw new NotSupportedException();
		}
	}
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.UpdateProjectToAllowUnsafe;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;

namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UpdateProjectToAllowUnsafe
{
    [Trait(Traits.Feature, Traits.Features.CodeActionsUpdateProjectToAllowUnsafe)]
    public class UpdateProjectToAllowUnsafeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
    {
        internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
            => (null, new CSharpUpdateProjectToAllowUnsafeCodeFixProvider());

        private async Task TestAllowUnsafeEnabledIfDisabledAsync(string initialMarkup)
        {
            var parameters = new TestParameters();
            using (var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters))
            {
                var (_, action) = await GetCodeActionsAsync(workspace, parameters);
                var operations = await VerifyActionAndGetOperationsAsync(action, default);

                var (oldSolution, newSolution) = ApplyOperationsAndGetSolution(workspace, operations);
                Assert.True(((CSharpCompilationOptions)newSolution.Projects.Single().CompilationOptions).AllowUnsafe);
            }

            // no action offered if unsafe was already enabled
            await TestMissingAsync(initialMarkup, new TestParameters(compilationOptions:
                new CSharpCompilationOptions(outputKind: default, allowUnsafe: true)));
        }

        [Fact]
        public async Task OnUnsafeClass()
        {
            await TestAllowUnsafeEnabledIfDisabledAsync(
@"
unsafe class [|C|] // The compiler reports this on the name, not the 'unsafe' keyword.
{
}");
        }

        [Fact]
        public async Task OnUnsafeMethod()
        {
            await TestAllowUnsafeEnabledIfDisabledAsync(
@"
class C
{
    unsafe void [|M|]()
    {
    }
}");
        }

        [Fact]
        public async Task OnUnsafeLocalFunction()
        {
            await TestAllowUnsafeEnabledIfDisabledAsync(
@"
class C
{
    void M()
    {
        unsafe void [|F|]()
        {
        }
    }
}");
        }

        [Fact]
        public async Task OnUnsafeBlock()
        {
            await TestAllowUnsafeEnabledIfDisabledAsync(
@"
class C
{
    void M()
    {
        [|unsafe|]
        {
        }
    }
}");
        }

        [Fact]
        public async Task NotInsideUnsafeBlock()
        {
            await TestMissingAsync(
@"
class C
{
    void M()
    {
        unsafe
        {
            [|int * p;|]
        }
    }
}");
        }
    }
}


text:
package org.apache.camel.examples.master;

import java.io.IOException;
import java.net.ServerSocket;

import org.apache.camel.builder.RouteBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MasterNodeConfiguration {
    private static final Logger LOGGER = LoggerFactory.getLogger(MasterNodeConfiguration.class);

    @Bean
    public RouteBuilder routeBuilder() {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                // This route is configured to be local (see application.properties)
                // so it will be started regardless of the leadership status if
                // this node.
                from("timer:heartbeat?period=10s")
                    .routeId("heartbeat")
                    .log("HeartBeat route (timer) {{node.id}} ...");

                // This route is configured to be clustered so it will be started
                // by the controller only when this node is leader
                from("master:{{node.namespace}}:timer:clustered?period=5s")
                    .routeId("clustered")
                    .log("Clustered route (timer) {{node.id}} ...");
            }
        };
    }

    /**
     * A small hack to find out the a free port so you can run multiple instances
     * of the example without having to manually set the property: server.port
     */
    @Bean
    public EmbeddedServletContainerCustomizer containerCustomizer() {
        return container -> {
            try (ServerSocket socket = new ServerSocket(0)) {
                LOGGER.debug("server.port: {}", socket.getLocalPort());
                container.setPort(socket.getLocalPort());
            } catch (IOException ignored) {
            }
        };
    }
}


text:
<?php

namespace AppBundle\Admin;

use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;

/**
 * Class ReceiptLineAdmin.
 *
 * @category Admin
 */
class ReceiptLineAdmin extends AbstractBaseAdmin
{
    protected $classnameLabel = 'Receipt Line';
    protected $baseRoutePattern = 'billings/receipt-line';
    protected $datagridValues = array(
        '_sort_by' => 'description',
        '_sort_order' => 'asc',
    );

    /**
     * @param FormMapper $formMapper
     */
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->with('backend.admin.general', $this->getFormMdSuccessBoxArray(6))
            ->add(
                'description',
                null,
                array(
                    'label' => 'backend.admin.invoiceLine.description',
                )
            )
            ->add(
                'units',
                null,
                array(
                    'label' => 'backend.admin.invoiceLine.units',
                )
            )
            ->add(
                'priceUnit',
                null,
                array(
                    'label' => 'backend.admin.invoiceLine.priceUnit',
                )
            )
            ->add(
                'discount',
                null,
                array(
                    'label' => 'backend.admin.invoiceLine.discount',
                )
            )
            ->end()
            ->with('backend.admin.controls', $this->getFormMdSuccessBoxArray(6))
            ->add(
                'receipt',
                null,
                array(
                    'label' => 'backend.admin.receiptLine.receipt',
                    'attr' => array(
                        'hidden' => true,
                    ),
                    'required' => true,
                )
            )
            ->add(
                'enabled',
                CheckboxType::class,
                array(
                    'label' => 'backend.admin.enabled',
                    'required' => false,
                    'attr' => array(
                        'hidden' => true,
                    ),
                )
            )
            ->end()
        ;
    }

    /**
     * @param DatagridMapper $datagridMapper
     */
    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper
            ->add(
                'receipt',
                null,
                array(
                    'label' => 'backend.admin.receiptLine.receipt',
                )
            )
            ->add(
                'description',
                null,
                array(
                    'label' => 'backend.admin.invoiceLine.description',
                )
            )
            ->add(
                'units',
                null,
                array(
                    'label' => 'backend.admin.invoiceLine.units',
                )
            )
            ->add(
                'priceUnit',
                null,
                array(
                    'label' => 'backend.admin.invoiceLine.priceUnit',
                )
            )
            ->add(
                'discount',
                null,
                array(
                    'label' => 'backend.admin.invoiceLine.discount',
                )
            )
            ->add(
                'total',
                null,
                array(
                    'label' => 'backend.admin.invoiceLine.total',
                )
            )
            ->add(
                'enabled',
                null,
                array(
                    'label' => 'backend.admin.enabled',
                )
            )
        ;
    }

    /**
     * @param ListMapper $listMapper
     */
    protected function configureListFields(ListMapper $listMapper)
    {
        unset($this->listModes['mosaic']);
        $listMapper
            ->add(
                'receipt',
                null,
                array(
                    'label' => 'backend.admin.receiptLine.receipt',
                    'editable' => true,
                )
            )
            ->add(
                'description',
                null,
                array(
                    'label' => 'backend.admin.invoiceLine.description',
                    'editable' => true,
                )
            )
            ->add(
                'units',
                null,
                array(
                    'label' => 'backend.admin.invoiceLine.units',
                    'editable' => true,
                )
            )
            ->add(
                'priceUnit',
                null,
                array(
                    'label' => 'backend.admin.invoiceLine.priceUnit',
                    'editable' => true,
                )
            )
            ->add(
                'discount',
                null,
                array(
                    'label' => 'backend.admin.invoiceLine.discount',
                    'editable' => true,
                )
            )
            ->add(
                'total',
                null,
                array(
                    'label' => 'backend.admin.invoiceLine.total',
                    'editable' => true,
                )
            )
            ->add(
                'enabled',
                null,
                array(
                    'label' => 'backend.admin.enabled',
                    'editable' => true,
                )
            )
            ->add(
                '_action',
                'actions',
                array(
                    'actions' => array(
                        'show' => array('template' => '::Admin/Buttons/list__action_show_button.html.twig'),
                        'edit' => array('template' => '::Admin/Buttons/list__action_edit_button.html.twig'),
                        'delete' => array('template' => '::Admin/Buttons/list__action_delete_button.html.twig'),
                    ),
                    'label' => 'backend.admin.actions',
                )
            )
        ;
    }
}


text:
<!DOCTYPE HTML>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Werkzeug Documentation</title>
    <link rel="stylesheet" href="../_static/style.css" type="text/css">
    <link rel="stylesheet" href="../_static/print.css" type="text/css" media="print">
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css">

    <link rel="contents" title="Global table of contents" href="../contents.html">
    <link rel="index" title="Global index" href="../genindex.html">
    <link rel="search" title="Search" href="../search.html">
    <link rel="top" title="Werkzeug v0.6.1 documentation" href="../index.html">
    <link rel="up" title="Application Deployment" href="index.html">
    <link rel="next" title="FastCGI" href="fastcgi.html">
    <link rel="prev" title="CGI" href="cgi.html">

Werkzeug

Overview

« CGI

mod_wsgi (Apache)

FastCGI »

Table Of Contents

mod_wsgi (Apache)

Installing mod_wsgi

Creating a .wsgi file

Configuring Apache

mod_wsgi (Apache)¶

If you are using the Apache webserver you should consider using mod_wsgi.

Installing mod_wsgi¶

If you don’t have mod_wsgi installed yet you have to either install it using
a package manager or compile it yourself.

The mod_wsgi installation instructions cover installation instructions for
source installations on UNIX systems.

If you are using ubuntu / debian you can apt-get it and activate it as follows:

# apt-get install libapache2-mod-wsgi

On FreeBSD install mod_wsgi by compiling the www/mod_wsgi port or by using
pkg_add:

# pkg_add -r mod_wsgi

If you are using pkgsrc you can install mod_wsgi by compiling the
www/ap2-wsgi package.

If you encounter segfaulting child processes after the first apache reload you
can safely ignore them.  Just restart the server.

Creating a .wsgi file¶

To run your application you need a yourapplication.wsgi file.  This file
contains the code mod_wsgi is executing on startup to get the application
object.  The object called application in that file is then used as
application.

For most applications the following file should be sufficient:

from yourapplication import make_app
application = make_app()

If you don’t have a factory function for application creation but a singleton
instance you can directly import that one as application.

Store that file somewhere where you will find it again (eg:
/var/www/yourapplication) and make sure that yourapplication and all
the libraries that are in use are on the python load path.  If you don’t
want to install it system wide consider using a virtual python instance.

Configuring Apache¶

The last thing you have to do is to create an Apache configuration file for
your application.  In this example we are telling mod_wsgi to execute the
application under a different user for security reasons:

<VirtualHost *>
    ServerName example.com

    WSGIDaemonProcess yourapplication user=user1 group=group1 processes=2 threads=5
    WSGIScriptAlias / /var/www/yourapplication/yourapplication.wsgi

    <Directory /var/www/yourapplication>
        WSGIProcessGroup yourapplication
        WSGIApplicationGroup %{GLOBAL}
        Order deny,allow
        Allow from all
    </Directory>
</VirtualHost>

For more information consult the mod_wsgi wiki.

        © Copyright 2008 by the Pocoo Team,
        documentation generated by Sphinx


text:
"use strict";

const isStandardSyntaxMediaFeatureName = require("../isStandardSyntaxMediaFeatureName");

describe("isStandardSyntaxMediaFeatureName", () => {
  it("keyword", () => {
    expect(isStandardSyntaxMediaFeatureName("min-width")).toBeTruthy();
  });
  it("keyword", () => {
    expect(
      isStandardSyntaxMediaFeatureName("-webkit-min-device-pixel-ratio")
    ).toBeTruthy();
  });
  it("custom media query", () => {
    expect(isStandardSyntaxMediaFeatureName("--viewport-medium")).toBeTruthy();
  });
  it("scss var", () => {
    expect(isStandardSyntaxMediaFeatureName("$sass-variable")).toBeFalsy();
  });
  it("scss var", () => {
    expect(isStandardSyntaxMediaFeatureName("min-width + $value")).toBeFalsy();
  });
  it("scss var", () => {
    expect(isStandardSyntaxMediaFeatureName("$value + min-width")).toBeFalsy();
  });
  it("scss var", () => {
    expect(
      isStandardSyntaxMediaFeatureName("'min-width + $value'")
    ).toBeFalsy();
  });
  it("scss var", () => {
    expect(
      isStandardSyntaxMediaFeatureName("'$value + min-width'")
    ).toBeFalsy();
  });
  it("scss var", () => {
    expect(
      isStandardSyntaxMediaFeatureName('"min-width + $value"')
    ).toBeFalsy();
  });
  it("scss var", () => {
    expect(
      isStandardSyntaxMediaFeatureName('"$value + min-width"')
    ).toBeFalsy();
  });
  it("scss interpolation", () => {
    expect(isStandardSyntaxMediaFeatureName("min-width#{$value}")).toBeFalsy();
  });
  it("scss interpolation", () => {
    expect(isStandardSyntaxMediaFeatureName("#{$value}min-width")).toBeFalsy();
  });
  it("scss interpolation", () => {
    expect(
      isStandardSyntaxMediaFeatureName("'min-width#{$value}'")
    ).toBeFalsy();
  });
  it("scss interpolation", () => {
    expect(
      isStandardSyntaxMediaFeatureName("'#{$value}min-width'")
    ).toBeFalsy();
  });
  it("scss interpolation", () => {
    expect(
      isStandardSyntaxMediaFeatureName('"min-width#{$value}"')
    ).toBeFalsy();
  });
  it("scss interpolation", () => {
    expect(
      isStandardSyntaxMediaFeatureName('"#{$value}min-width"')
    ).toBeFalsy();
  });
});


text:
var gulp = require('gulp');

gulp.task('build', ['stylus', 'browserify']);


text:
<!--

WsGreenWall -- Guild chat bridging for WildStar.

The MIT License (MIT)

Copyright (c) 2014 Mark Rogaski

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

-->
<?xml version="1.0" encoding="UTF-8"?>
<Addon Author="Mark Rogaski" APIVersion="9" Name="WsGreenWall" Version="1.1.0" Description="Guild chat bridging for WildStar.">
    <Script Name="WsGreenWall.lua"/>
    <Form Name="WsGreenWall.xml"/>
    <Script Name="Libs\Base64.lua"/>
    <Script Name="Libs\Salsa20.lua"/>
    <Script Name="Libs\SHA256.lua"/>
</Addon>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Cat. Champ. Marn. no. 1647 (1889)

#### Original name
Coniothyrium populi Richon

### Remarks
null


text:
package nam.model.messagingProvider;

import java.io.Serializable;
import java.util.Collection;

import javax.enterprise.context.ApplicationScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import javax.inject.Named;

import org.aries.ui.validate.AbstractValidator;

import nam.model.MessagingProvider;
import nam.model.util.MessagingProviderUtil;

@ApplicationScoped
@Named("messagingProviderValidator")
public class MessagingProviderValidator extends AbstractValidator implements Validator, Serializable {

	@Override
	public void validate(FacesContext facesContext, UIComponent uiComponent, Object value) throws ValidatorException {
		resetState();
		if (value != null) {
			if (value instanceof MessagingProvider == false)
				throwError("Unexpected value: "+value);
			MessagingProvider messagingProvider = (MessagingProvider) value;
			if (MessagingProviderUtil.validate(messagingProvider) == false) {
				Collection<String> messages = getValidator().getMessages();
				getDisplay().addErrors(messages);
				throwErrors(messages);
			}
		}
	}

}


text:
OneWay Encryptor
================

Android implementation of AsymmetricCrypt (https://github.com/galets/AsymmetricCrypt) file encryption tool

Purpose:
--------

Sometimes, a user of device is going through places, where his device could be taken and examined for
prohibited data. In some cases, the adversary could even decrypt encrypted files, by inspecting memory of
device.

This tool is used to encrypt files on user device in such way that it cannot be decrypted. Device never
gets to know the private key. Therefore, none of the files encrypted using the OneWay application could
possibly be decrypted using only information on device.

Usage:
------

Use AsymmetricCrypt (https://github.com/galets/AsymmetricCrypt) to generate public/private keypair. Store
private key safely. Upload public key to device using copy/paste or by generating QR code

Files encrypted with OneWay could only be decrypted by AsymmetricCrypt using private key


text:
package com.icfcc.cache.util;

import org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator;
import org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator;
import org.springframework.aop.config.AopNamespaceUtils;
import org.springframework.aop.framework.autoproxy.InfrastructureAdvisorAutoProxyCreator;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.core.Ordered;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;

/**
 * Utility class for handling registration of AOP auto-proxy creators.
 *
 *
Only a single auto-proxy creator can be registered yet multiple concrete
 * implementations are available. Therefore this class wraps a simple escalation
 * protocol, allowing classes to request a particular auto-proxy creator and know
 * that class, or a subclass thereof, will eventually be resident
 * in the application context.
 *
 * @author Rob Harrop
 * @author Juergen Hoeller
 * @author Mark Fisher
 * @since 2.5
 * @see AopNamespaceUtils
 */
public abstract class AopConfigUtils {

    /**
     * The bean name of the internally managed auto-proxy creator.
     */
    public static final String AUTO_PROXY_CREATOR_BEAN_NAME =
            "org.springframework.aop.config.internalAutoProxyCreator";

    /**
     * Stores the auto proxy creator classes in escalation order.
     */
    private static final List<Class> APC_PRIORITY_LIST = new ArrayList<Class>();

    /**
     * Setup the escalation list.
     */
    static {
        APC_PRIORITY_LIST.add(InfrastructureAdvisorAutoProxyCreator.class);
        APC_PRIORITY_LIST.add(AspectJAwareAdvisorAutoProxyCreator.class);
        APC_PRIORITY_LIST.add(AnnotationAwareAspectJAutoProxyCreator.class);
    }

    public static BeanDefinition registerAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry) {
        return registerAutoProxyCreatorIfNecessary(registry, null);
    }

    public static BeanDefinition registerAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry, Object source) {
        return registerOrEscalateApcAsRequired(InfrastructureAdvisorAutoProxyCreator.class, registry, source);
    }

    public static BeanDefinition registerAspectJAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry) {
        return registerAspectJAutoProxyCreatorIfNecessary(registry, null);
    }

    public static BeanDefinition registerAspectJAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry, Object source) {
        return registerOrEscalateApcAsRequired(AspectJAwareAdvisorAutoProxyCreator.class, registry, source);
    }

    public static BeanDefinition registerAspectJAnnotationAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry) {
        return registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry, null);
    }

    public static BeanDefinition registerAspectJAnnotationAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry, Object source) {
        return registerOrEscalateApcAsRequired(AnnotationAwareAspectJAutoProxyCreator.class, registry, source);
    }

    public static void forceAutoProxyCreatorToUseClassProxying(BeanDefinitionRegistry registry) {
        if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) {
            BeanDefinition definition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME);
            definition.getPropertyValues().addPropertyValue(new PropertyValue("proxyTargetClass", Boolean.TRUE));
        }
    }

    static void forceAutoProxyCreatorToExposeProxy(BeanDefinitionRegistry registry) {
        if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) {
            BeanDefinition definition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME);
            definition.getPropertyValues().addPropertyValue(new PropertyValue("exposeProxy", Boolean.TRUE));
        }
    }

    private static BeanDefinition registerOrEscalateApcAsRequired(Class cls, BeanDefinitionRegistry registry, Object source) {
        Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
        if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) {
            BeanDefinition apcDefinition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME);
            if (!cls.getName().equals(apcDefinition.getBeanClassName())) {
                int currentPriority = findPriorityForClass(apcDefinition.getBeanClassName());
                int requiredPriority = findPriorityForClass(cls);
                if (currentPriority < requiredPriority) {
                    apcDefinition.setBeanClassName(cls.getName());
                }
            }
            return null;
        }
        RootBeanDefinition beanDefinition = new RootBeanDefinition(cls);
        beanDefinition.setSource(source);
        beanDefinition.getPropertyValues().addPropertyValue(new PropertyValue("order", Ordered.HIGHEST_PRECEDENCE));
        beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
        registry.registerBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME, beanDefinition);
        return beanDefinition;
    }

    private static int findPriorityForClass(Class clazz) {
        return APC_PRIORITY_LIST.indexOf(clazz);
    }

    private static int findPriorityForClass(String className) {
        for (int i = 0; i < APC_PRIORITY_LIST.size(); i++) {
            Class clazz = APC_PRIORITY_LIST.get(i);
            if (clazz.getName().equals(className)) {
                return i;
            }
        }
        throw new IllegalArgumentException(
                "Class name [" + className + "] is not a known auto-proxy creator class");
    }

}


text:
<title>.::SISTEM MAKLUMAT PROJEK PELAJAR TAHUN AKHIR::.</title>

<?php
session_start();
if(!$_SESSION['matrik']){header("location:SilaloginPelajar.php");}
?>

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

          <?php include("footer/matrik.php"); ?>

				<?php include("footer/menu2.php"); ?>

					<?php

						include('connection/con_db.php');

						$student_id = isset($_SESSION['matrik']) ? $_SESSION['matrik'] : "";

						$query = mysql_query("SELECT * FROM maklumatpelajar WHERE matrik ='".$student_id."'");
						$row = mysql_fetch_assoc($query);

						// get student list
						function get_student($supervisor){
							$output = "";
							$query = mysql_query("	SELECT 	maklumatpelajar.nama,
															maklumatpelajar.matrik
													FROM maklumatpenyelia
													LEFT JOIN maklumatpelajar ON maklumatpenyelia.staffId = maklumatpelajar.penyelia_id
													WHERE maklumatpenyelia.staffId = '".$supervisor."'");

							$no = 1;

								while($result = mysql_fetch_assoc($query)){
									$output .= $no . ") " .$result['matrik'] . " - " . $result['nama'] . "
";
									$no++;
								}

								return $output;

						}

						if(isset($_GET['add'])){

							$svId = isset($_GET['add']) ? $_GET['add']  : "";

							mysql_query("UPDATE maklumatpelajar SET penyelia_id = '".$svId."' WHERE matrik = '".$student_id."'")or die(mysql_error());
							// update quota
							$query = mysql_query("SELECT * FROM maklumatpenyelia WHERE staffId = '".$svId."'");
							$row1 = mysql_fetch_assoc($query);
							$curr_quota = $row1['noOfStudent'];
							// Add
							$curr_quota = $curr_quota + 1;
							mysql_query("UPDATE maklumatpenyelia SET noOfStudent = '".$curr_quota."' WHERE staffId = '".$svId."'");

							echo "";
							echo "<meta http-equiv='Refresh' content='1;url=std_supervisor.php'/>";
						}

					?>

Supervisor Information

					<?php if($row['penyelia_id'] == 0){ ?>

You don't have any supervisor. Please choose your supervisor.

										Supervisor Name
										No Of Student
										Total Quota
										Status
										Action

										<?php

											include('connection/con_db.php');

											// Create pagination to filter results
											$display_page = 10;
											// Create page count
											$pages_query = mysql_query("SELECT COUNT('staffId') FROM maklumatpenyelia");
											$pages = ceil(mysql_result($pages_query, 0) / $display_page);

											// Create page link
											$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
											$start = ($page - 1) * $display_page;

											// Create Query
											$sql = "SELECT * FROM maklumatpenyelia ORDER BY id ASC LIMIT $start, $display_page";
											$query = mysql_query($sql);

											$records = mysql_num_rows($query);

											while($result = mysql_fetch_array($query)){
												$id = $result['staffId'];
												echo "
";
												echo "".$result['namaPenyelia']."	";
												echo "";
												if($result['noOfStudent'] > 0){
													echo "
".$result['noOfStudent']."";
													echo "
".get_student($id)."

";
												} else {
													echo "".$result['noOfStudent']."";
												}
												echo "	";
												echo "".$result['kuota']."	";
												echo "";

													if($result['noOfStudent'] == $result['kuota'])
														echo "Unavailable";
													else
														echo "Available";

												echo "	";

												echo "";
												if($result['noOfStudent'] == $result['kuota']){
													echo " ";
												}else{
													echo "[ Select ]";
												}
												echo "	";
												echo "
";
											}

										?>

							<?php
								// Display Pagination
								echo "
";

								if( $pages >= 1 && $page <= $pages ){
									for ( $x = 1; $x <= $pages; $x++ ){

										echo ( $x == $page ) ? "

".$x."

" : "
".$x."
" ;
									}
									echo "
Total Record(s):  ".$records."
";
									echo "
";
								} else { echo ""; }

							?>

					<?php } else{ ?>
						<?php

							include('connection/con_db.php');

							$query = mysql_query("	SELECT 	maklumatpenyelia.namaPenyelia,
															maklumatpenyelia.notelefon,
															maklumatpenyelia.emel,
															maklumatpenyelia.nobilik,
															maklumatpenyelia.kepakaran
													FROM maklumatpelajar
													LEFT JOIN maklumatpenyelia ON maklumatpelajar.penyelia_id = maklumatpenyelia.staffId
													WHERE matrik = '".$student_id."'");

							$result = mysql_fetch_assoc($query);
						?>

									Supervisor:
									<?php echo $result['namaPenyelia']; ?>

									Phone No:
									<?php echo $result['notelefon']; ?>

									Email:
									<?php echo $result['emel']; ?>

									Room No:
									<?php echo $result['nobilik']; ?>

									Expertise:
									<?php echo $result['kepakaran']; ?>

Student Progress

Note: Please update current status/progress to your supervisor

								<?php
									include('connection/con_db.php');
									date_default_timezone_set('Asia/Kuala_Lumpur');
									// get data
									$query1 = mysql_query("SELECT * FROM progress_report ORDER BY id ASC");

									if(isset($_GET['submit']) ){

										$student_id = isset($_GET['submit']) ? $_GET['submit'] : "";
										$time = date('H:i');
										$date = date('Y-m-d');

										mysql_query("UPDATE  addproject SET progress_status = 'Pending',
																			progress_date = '".$date."',
																			progress_time = '".$time."'
													 WHERE  matrik = '".$student_id."'")or die(mysql_error());

										echo "";
										echo "<meta http-equiv='Refresh' content='1;url=std_supervisor.php'/>";

									}

								?>

											Progress

										<?php

											$student_id = isset($_SESSION['matrik']) ? $_SESSION['matrik'] : "";

											$query2 = mysql_query("SELECT * FROM addproject WHERE matrik = '".$student_id."'");
											$result = mysql_fetch_assoc($query2);
											$staffids = $result['staffIId'];
											$stage = 0;
											$no = 1;
											$progress_level = 0;
											while($result_progress = mysql_fetch_assoc($query1)){
												echo "
";
												echo "
".$no." - ".$result_progress['progress_name']."
	";
												if(($result['progress_id'] == $progress_level) && $result['progress_status'] == NULL && $stage == 0){
													echo "Submit	";
													$stage = 1;
												}else if(($result['progress_id'] == $progress_level) && $result['progress_status'] == 'Pending' && $stage == 0){
													echo "

Waiting for approval

																";
													$stage = 1;
												}else{
													echo "Submit</stron>	";
												}
												echo "
";
												$progress_level++;
												$no++;
											}

										?>

					<?php } ?>

  <?php include("footer/footer.php"); ?>


text:
using System.Threading.Tasks;
using BibleNote.Providers.Word.Contracts;
using BibleNote.Services.Contracts;

namespace BibleNote.Providers.Word
{
    public class WordDocumentConnector : IWordDocumentConnector
    {
        public async Task<IWordDocumentHandler> ConnectAsync(IDocumentId documentId)
        {
            var pageHandler = new WordDocumentHandler(documentId);
            pageHandler.LoadPageContent();
            return pageHandler;
        }
    }
}


text:
using cert_trans::Notification;
using cert_trans::ThreadPool;
using std::atomic_fetch_add;
using std::atomic_int;
using std::bind;
using std::chrono::milliseconds;
using std::placeholders::_1;
using std::this_thread::sleep_for;
using std::unique_ptr;

DEFINE_int32(task_test_jiffy_ms, 100,
             "amount of time (in milliseconds) after which \"things ought to "
             "be done\"");

namespace {

class InlineExecutor : public util::Executor {
  void Add(const std::function<void()>& closure) override {
    closure();
  }
  void Delay(const std::chrono::duration<double>& delay,
             util::Task* task) override {
    LOG(FATAL) << "Not Implemented.";
  }
};

void Delay() {
  sleep_for(milliseconds(FLAGS_task_test_jiffy_ms));
}

class DeleteMarker {
 public:
  explicit DeleteMarker(Notification* notifier)
      : notifier_(CHECK_NOTNULL(notifier)) {
  }
  ~DeleteMarker() {
    notifier_->Notify();
  }

 private:
  Notification* const notifier_;

  DISALLOW_COPY_AND_ASSIGN(DeleteMarker);
};

template <class T>
class TaskTest : public ::testing::Test {};

typedef ::testing::Test TaskDeathTest;

template <class TestExecutor, bool sync_done>
class TaskTester {
 public:
  TaskTester()
      : executor_(new TestExecutor),
        task_(bind(&TaskTester::DoneCallback, this, _1), executor_.get()) {
    if (sync_done) {
      ContinueDone();
    }
  }

  ~TaskTester() {
    EXPECT_TRUE(done_started_.WaitForNotificationWithTimeout(
        milliseconds(FLAGS_task_test_jiffy_ms)));
    if (!done_continue_.HasBeenNotified()) {
      done_continue_.Notify();
    }
    EXPECT_TRUE(done_finished_.WaitForNotificationWithTimeout(
        milliseconds(FLAGS_task_test_jiffy_ms)));
  }

  util::Task* task() {
    return &task_;
  }

  void WaitForDoneToStart() {
    EXPECT_TRUE(done_started_.WaitForNotificationWithTimeout(
        milliseconds(FLAGS_task_test_jiffy_ms)));
  }

  bool HasDoneStarted() {
    return done_started_.HasBeenNotified();
  }

  void ContinueDone() {
    if (!done_continue_.HasBeenNotified()) {
      done_continue_.Notify();
    }
  }

  void WaitForDoneToFinish() {
    EXPECT_TRUE(done_finished_.WaitForNotificationWithTimeout(
        milliseconds(FLAGS_task_test_jiffy_ms)));
  }

 private:
  void DoneCallback(util::Task* task) {
    CHECK(!task->IsActive());
    CHECK(task->IsDone());
    done_started_.Notify();
    EXPECT_TRUE(done_continue_.WaitForNotificationWithTimeout(
        milliseconds(FLAGS_task_test_jiffy_ms)));
    done_finished_.Notify();
  }

  const unique_ptr<TestExecutor> executor_;
  util::Task task_;
  Notification done_started_;
  Notification done_continue_;
  Notification done_finished_;

  DISALLOW_COPY_AND_ASSIGN(TaskTester);
};

typedef ::testing::Types<TaskTester<ThreadPool, false>,
                         TaskTester<InlineExecutor, true>> MyTypes;
TYPED_TEST_CASE(TaskTest, MyTypes);

void DoNothing(util::Task* task) {
}

TEST_F(TaskDeathTest, DestroyIncompleteTask) {
  InlineExecutor executor;

  EXPECT_DEATH(util::Task(DoNothing, &executor),
               "Check failed: state_ == DONE");
}

template <class TypeParam>
void WaitForReturnCallback(TypeParam* s, Notification* notifier) {
  s->WaitForDoneToStart();
  EXPECT_FALSE(s->task()->IsActive());
  EXPECT_TRUE(s->task()->IsDone());
  EXPECT_FALSE(s->task()->CancelRequested());
  EXPECT_EQ(util::Status::OK, s->task()->status());
  s->ContinueDone();
  notifier->Notify();
}

TYPED_TEST(TaskTest, StateChanges) {
  ThreadPool pool;
  TypeParam s;

  EXPECT_TRUE(s.task()->IsActive());
  EXPECT_FALSE(s.task()->IsDone());
  EXPECT_FALSE(s.task()->CancelRequested());

  Notification notifier;
  pool.Add(bind(&WaitForReturnCallback<TypeParam>, &s, &notifier));
  EXPECT_TRUE(s.task()->Return());

  EXPECT_TRUE(notifier.WaitForNotificationWithTimeout(
      milliseconds(FLAGS_task_test_jiffy_ms)));
}

TYPED_TEST(TaskTest, DeleteWhenDone) {
  Notification n1;
  Notification n2;
  TypeParam s;

  s.task()->DeleteWhenDone(new DeleteMarker(&n1));
  s.task()->DeleteWhenDone(new DeleteMarker(&n2));

  EXPECT_FALSE(n1.HasBeenNotified());
  EXPECT_FALSE(n2.HasBeenNotified());
  s.task()->Return();
  s.ContinueDone();
  EXPECT_TRUE(n1.WaitForNotificationWithTimeout(
      milliseconds(FLAGS_task_test_jiffy_ms)));
  EXPECT_TRUE(n2.WaitForNotificationWithTimeout(
      milliseconds(FLAGS_task_test_jiffy_ms)));
}

TYPED_TEST(TaskTest, Return) {
  TypeParam s;
  util::Status status(util::error::INVALID_ARGUMENT, "expected status");

  EXPECT_TRUE(s.task()->Return(status));
  EXPECT_FALSE(s.task()->IsActive());

  s.WaitForDoneToStart();
  EXPECT_EQ(status, s.task()->status());
}

TYPED_TEST(TaskTest, HoldBlocksDone) {
  TypeParam s;
  EXPECT_TRUE(s.task()->IsActive());
  EXPECT_FALSE(s.task()->IsDone());

  s.task()->AddHold();
  EXPECT_TRUE(s.task()->IsActive());
  EXPECT_FALSE(s.task()->IsDone());

  s.task()->Return();
  EXPECT_FALSE(s.task()->IsActive());
  EXPECT_FALSE(s.task()->IsDone());

  s.task()->RemoveHold();
  EXPECT_FALSE(s.task()->IsActive());
  EXPECT_TRUE(s.task()->IsDone());
}

TYPED_TEST(TaskTest, MultipleReturn) {
  TypeParam s;
  util::Status status1(util::error::INVALID_ARGUMENT, "expected status");
  util::Status status2(util::error::DEADLINE_EXCEEDED, "unexpected status");
  EXPECT_NE(status1, status2);

  EXPECT_TRUE(s.task()->Return(status1));
  EXPECT_FALSE(s.task()->Return(status2));
  EXPECT_FALSE(s.task()->IsActive());

  s.WaitForDoneToStart();
  EXPECT_EQ(status1, s.task()->status());
}

TYPED_TEST(TaskTest, Cancel) {
  TypeParam s;
  EXPECT_FALSE(s.task()->CancelRequested());
  s.task()->Cancel();
  EXPECT_TRUE(s.task()->CancelRequested());
  s.task()->Return();
}

TYPED_TEST(TaskTest, CancelAfterReturn) {
  TypeParam s;
  EXPECT_FALSE(s.task()->CancelRequested());
  s.task()->Return();
  s.task()->Cancel();
  EXPECT_FALSE(s.task()->CancelRequested());
}

TYPED_TEST(TaskTest, MultipleCancels) {
  TypeParam s;
  EXPECT_FALSE(s.task()->CancelRequested());
  s.task()->Cancel();
  s.task()->Cancel();
  EXPECT_TRUE(s.task()->CancelRequested());
  s.task()->Return();
}

TYPED_TEST(TaskTest, CancelCallback) {
  TypeParam s;
  Notification notifier;

  s.task()->WhenCancelled(bind(&Notification::Notify, &notifier));

  Delay();
  EXPECT_FALSE(notifier.HasBeenNotified());

  s.task()->Cancel();
  EXPECT_TRUE(notifier.WaitForNotificationWithTimeout(
      milliseconds(FLAGS_task_test_jiffy_ms)));
  EXPECT_TRUE(notifier.HasBeenNotified());

  s.task()->Return();
}

void NotifyAndWait(Notification* cancelled, Notification* finish_cancel) {
  cancelled->Notify();
  // Wait for up to two jiffies, because there's a delay of one jiffy
  // in WaitForCancelAndReturn().
  EXPECT_TRUE(finish_cancel->WaitForNotificationWithTimeout(
      milliseconds(FLAGS_task_test_jiffy_ms) * 2));
}

template <class TypeParam>
void WaitForCancelAndReturn(TypeParam* s, Notification* cancelled,
                            Notification* finish_cancel) {
  EXPECT_TRUE(cancelled->WaitForNotificationWithTimeout(
      milliseconds(FLAGS_task_test_jiffy_ms)));
  s->task()->Return();
  Delay();
  EXPECT_FALSE(s->task()->IsDone());
  EXPECT_FALSE(s->HasDoneStarted());
  finish_cancel->Notify();
  s->ContinueDone();
}

TYPED_TEST(TaskTest, CancelCallbackBlocksDone) {
  ThreadPool pool;
  Notification cancelled;
  Notification finish_cancel;
  // This object must be defined after the two Notification above,
  // because it will be using them all (so they should live at least
  // as long).
  TypeParam s;

  s.task()->WhenCancelled(bind(NotifyAndWait, &cancelled, &finish_cancel));
  pool.Add(
      bind(WaitForCancelAndReturn<TypeParam>, &s, &cancelled, &finish_cancel));
  s.task()->Cancel();

  // Make sure everything is completed.
  Delay();
}

TYPED_TEST(TaskTest, CancelCallbackNotCalledOnReturn) {
  TypeParam s;
  Notification notifier;

  s.task()->WhenCancelled(bind(&Notification::Notify, &notifier));

  s.task()->Return();
  s.ContinueDone();
  s.WaitForDoneToFinish();

  EXPECT_FALSE(notifier.HasBeenNotified());
}

TYPED_TEST(TaskTest, CancelCallbackNotCalledAfterReturn) {
  TypeParam s;
  Notification notifier;

  s.task()->Return();
  s.task()->WhenCancelled(bind(&Notification::Notify, &notifier));
  s.ContinueDone();
  s.WaitForDoneToFinish();

  EXPECT_FALSE(notifier.HasBeenNotified());
}

TYPED_TEST(TaskTest, CancelCallbackAfterCancel) {
  TypeParam s;
  Notification notifier;

  s.task()->Cancel();
  s.task()->WhenCancelled(bind(&Notification::Notify, &notifier));
  Delay();
  s.task()->Return();

  EXPECT_TRUE(notifier.WaitForNotificationWithTimeout(
      milliseconds(FLAGS_task_test_jiffy_ms)));
}

TYPED_TEST(TaskTest, ReturnStillRunsCancelCallbacks) {
  TypeParam s;
  Notification notifier;

  s.task()->Cancel();
  s.task()->WhenCancelled(bind(&Notification::Notify, &notifier));
  s.task()->Return();

  EXPECT_TRUE(notifier.WaitForNotificationWithTimeout(
      milliseconds(FLAGS_task_test_jiffy_ms)));
}

void Increment(atomic_int* atomic) {
  atomic->fetch_add(1);
}

TYPED_TEST(TaskTest, MultiCancel) {
  TypeParam s;
  atomic_int count(0);
  const int kRuns(3);

  for (int i = 0; i < kRuns; ++i) {
    s.task()->WhenCancelled(bind(Increment, &count));
  }

  s.task()->Cancel();
  s.task()->Return();
  s.WaitForDoneToStart();
  EXPECT_EQ(kRuns, count.load());
}

TYPED_TEST(TaskTest, ChildBlocksDone) {
  TypeParam s;

  util::Task* const child_task(s.task()->AddChild(DoNothing));
  EXPECT_FALSE(s.task()->CancelRequested());
  EXPECT_TRUE(s.task()->IsActive());
  EXPECT_FALSE(s.task()->IsDone());
  EXPECT_FALSE(child_task->IsDone());

  s.task()->Return();
  EXPECT_FALSE(s.task()->IsActive());
  EXPECT_FALSE(s.task()->IsDone());

  child_task->Return();
}

TYPED_TEST(TaskTest, ChildCancel) {
  TypeParam s;

  util::Task* const child_task(s.task()->AddChild(DoNothing));
  EXPECT_FALSE(s.task()->CancelRequested());
  EXPECT_FALSE(child_task->CancelRequested());

  s.task()->Cancel();
  EXPECT_TRUE(s.task()->CancelRequested());
  EXPECT_TRUE(child_task->CancelRequested());

  child_task->Return();
  s.task()->Return();
}

TYPED_TEST(TaskTest, ChildReturn) {
  TypeParam s;

  util::Task* const child_task(s.task()->AddChild(DoNothing));
  EXPECT_FALSE(s.task()->CancelRequested());
  EXPECT_FALSE(child_task->CancelRequested());

  s.task()->Return();
  EXPECT_FALSE(s.task()->CancelRequested());
  EXPECT_TRUE(child_task->CancelRequested());

  child_task->Return();
}

}  // namespace

int main(int argc, char** argv) {
  cert_trans::test::InitTesting(argv[0], &argc, &argv, true);
  return RUN_ALL_TESTS();
}


text:
//******************************************************************************************
// Copyright (c) 2021 Gorka Suárez García
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//******************************************************************************************
using Console;
using Engine.Data;
using Engine.Script;
using Engine.Util;
using UnityEngine;
using System.Collections.Generic;

namespace Engine {
    /// <summary>
    /// This class represents the adventure engine behaviour.
    /// </summary>
    public class EngineBehaviour : MonoBehaviour {
        //********************************************************************************
        // Constants
        //********************************************************************************

        #region float MAX_FINISH_PAUSE
        /// <summary>
        /// The maximum finish time interval.
        /// </summary>
        public const float MAX_FINISH_PAUSE = 0.5f;
        #endregion

        //********************************************************************************
        // Properties
        //********************************************************************************

        #region EngineBehaviour Instance
        /// <summary>
        /// The main instance of the class.
        /// </summary>
        private static EngineBehaviour _instance;

        /// <summary>
        /// Gets the main instance of the class.
        /// </summary>
        public static EngineBehaviour Instance {
            get { return _instance; }
        }
        #endregion

        #region IOutputDevice Output
        /// <summary>
        /// The output device of the engine.
        /// </summary>
        private IOutputDevice _output = null;

        /// <summary>
        /// Gets the output device of the engine.
        /// </summary>
        public IOutputDevice Output {
            get { return _output; }
        }
        #endregion

        #region IInputDevice Input
        /// <summary>
        /// The input device of the engine.
        /// </summary>
        private IInputDevice _input = null;

        /// <summary>
        /// Gets the input device of the engine.
        /// </summary>
        public IInputDevice Input {
            get { return _input; }
        }
        #endregion

        #region GameObject _device
        /// <summary>
        /// The game object device of the game.
        /// </summary>
        [SerializeField]
        private GameObject _device = null;
        #endregion

        #region string _startScript
        /// <summary>
        /// The start script file path of the game.
        /// </summary>
        [SerializeField]
        private string _startScript = null;
        #endregion

        #region AdventureGame Game
        /// <summary>
        /// The adventure descriptor of the game.
        /// </summary>
        private AdventureGame _game;

        /// <summary>
        /// Gets the adventure descriptor of the game.
        /// </summary>
        public AdventureGame Game {
            get { return _game; }
        }
        #endregion

        #region AdventureContext Context
        /// <summary>
        /// The current context of the game.
        /// </summary>
        private AdventureContext _context = null;

        /// <summary>
        /// Gets the current context of the game.
        /// </summary>
        public AdventureContext Context {
            get { return _context; }
        }
        #endregion

        #region float _finishPause
        /// <summary>
        /// The finish pause delta time counter.
        /// </summary>
        private float _finishPause;
        #endregion

        #region CurrentColor
        /// <summary>
        /// The current foreground color for the text.
        /// </summary>
        public Color CurrentForegroundColor { get; set; }
        #endregion

        #region CurrentBackgroundColor
        /// <summary>
        /// The current background color for the text.
        /// </summary>
        public Color CurrentBackgroundColor { get; set; }
        #endregion

        //********************************************************************************
        // Methods
        //********************************************************************************

        #region void Awake ()
        /// <summary>
        /// Handles the "awake" event and is used for initialization.
        /// </summary>
        public void Awake () {
            _instance = this;
        }
        #endregion

        #region void Start ()
        /// <summary>
        /// Handles the "start" event and is used for initialization.
        /// </summary>
        public void Start () {
            _output = _device.GetComponent<IOutputDevice>();
            _input = _device.GetComponent<IInputDevice>();
            var text = FileUtil.LoadTextFromResources(_startScript);
            _game = ScriptParser.Parse(text);
            Reset();
        }
        #endregion

        #region void Update ()
        /// <summary>
        /// Handles the "update" event and is called once per frame,
        /// to update the component.
        /// </summary>
        public void Update () {
            if (_context.UpdateChangeRoom()) {
                StartReadLine();
            }
            if (_context.Reset) {
                Reset();
            } else if (_context.Finished) {
                if (_finishPause > MAX_FINISH_PAUSE) {
                    if (UnityEngine.Input.anyKeyDown) {
                        Reset();
                    }
                } else {
                    _finishPause += Time.deltaTime;
                }
            }
        }
        #endregion

        #region void Reset ()
        /// <summary>
        /// Resets the current game.
        /// </summary>
        public void Reset () {
            _finishPause = 0.0f;
            _context = new AdventureContext();
            if (_game != null) {
                CurrentBackgroundColor = EgaPalette.Black;
                CurrentForegroundColor = EgaPalette.White;
                Clear();
                _output.WriteLine("Zrukall Text Adventure Engine 0.2\n");
                _context.ChangeRoom(AdventureContext.DEFAULT_ROOM);
                _input.OnNextLine = EndReadLine;
                StartReadLine();
            }
        }
        #endregion

        #region void StartReadLine ()
        /// <summary>
        /// Starts the read line process.
        /// </summary>
        public void StartReadLine () {
            if (!_context.Finished && _context.NextRoom == null) {
                _output.WriteLine();
                _output.ForegroundColor = EgaPalette.Red;
                _output.Write("> ");
                _output.ForegroundColor = EgaPalette.White;
                _input.EnableTextInput = true;
            }
        }
        #endregion

        #region void EndReadLine (string)
        /// <summary>
        /// Ends the read line process.
        /// </summary>
        /// <param name="line">The readed line.</param>
        public void EndReadLine (string line) {
            _output.WriteLine();
            if (line == ":q" || line == ":quit") {
                Exit();
            } else {
                _context.ExecuteAction(line);
            }
            StartReadLine();
        }
        #endregion

        private void updateFontColors() {
            _output.BackgroundColor = CurrentBackgroundColor;
            _output.ForegroundColor = CurrentForegroundColor;
        }

        #region void Write (IEnumerable<ConsoleString>)
        /// <summary>
        /// Writes a message in the console.
        /// </summary>
        /// <param name="messages">The messages to write.</param>
        public void Write (IEnumerable<ConsoleString> messages) {
            if (messages != null) {
                updateFontColors();
                foreach (var item in messages) {
                    _output.Write(item);
                }
            }
        }
        #endregion

        #region void WriteLine (IEnumerable<ConsoleString>)
        /// <summary>
        /// Writes a line in the console.
        /// </summary>
        /// <param name="messages">The messages to write.</param>
        public void WriteLine (IEnumerable<ConsoleString> messages) {
            if (messages != null) {
                Write(messages);
                _output.WriteLine();
            }
        }
        #endregion

        #region void Clear()
        /// <summary>
        /// Clears the screen of the game.
        /// </summary>
        public void Clear () {
            updateFontColors();
            _output.Clear();
        }
        #endregion

        #region void Exit()
        /// <summary>
        /// Exits the game application.
        /// </summary>
        public void Exit() {
#if UNITY_EDITOR
            UnityEditor.EditorApplication.isPlaying = false;
#endif
            Application.Quit();
        }
        #endregion
    }
}


text:
package net.hofrichter.javamag.javadoc.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.nio.file.Path;

import org.apache.log4j.chainsaw.Main;

public final class FileUtil {

    /**
     * Diese Methode implementiert das Lesen einer Datei.
     *
     * @param path ist der Pfad zur Datei
     * @return den Inhalt der Datei als String
     * @throws IOException wird bei Fehlern geworfen, die beim Zugriff auf die
     *             Datei entstehen künnen
     */
    public static String read(Path path) throws IOException {
        URL url = new URL(path.toString());
        try (BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()))) {
            StringBuilder sb = new StringBuilder();
            String line = null;
            String nl = System.lineSeparator();
            while ((line = br.readLine()) != null) {
                sb.append(line).append(nl);
            }
            return sb.toString();
        } catch (IOException e) {
            // anti pattern, aber es ist nur ein Beispiel!
            throw e;
        }
    }

    /**
     * Diese Methode schreibt die übergebenen Daten in die angegebene
     * Datei.
     *
     * @param targetFile ist die Zieldatei
     * @param data sind die Daten, die in die Datei geschrieben werden sollen
     * @return {@code true}, bei Erfolg, andernfalls {@code false}
     * @throws IOException wird bei Fehlern geworfen, die beim Zugriff auf die
     *             Datei entstehen künnen
     */
    public static boolean write(Path targetFile, String data) throws IOException {
        File file = targetFile.toFile();
        if (file.getParentFile().exists() || file.getParentFile().mkdirs()) {
            try (FileWriter writer = new FileWriter(targetFile.toUri().toURL().getPath());) {
                writer.write(data);
                writer.flush();
            }
            // Files.write(targetFile, data.getBytes());
            return true;
        }
        return false;
    }

    /**
     * Diese Methode kopiert interne Dateien in das Dateisystem. Sie wird
     * verwendet, um die zu den internen Templates gehörenden Dateien dem apidoc
     * beizustellen.
     *
     * @param source ist der Name der Datei im JAR
     * @param target ist der Name der Datei im Dateisystem
     */
    public static void copy(String resource, String destination) {
        File resDestFile = new File(destination);
        resDestFile.getParentFile().mkdirs();
        try (InputStream in = Main.class.getClassLoader().getResourceAsStream(resource);
                OutputStream out = new FileOutputStream(resDestFile);) {
            int readBytes;
            byte[] buffer = new byte[4096];
            while ((readBytes = in.read(buffer)) > 0) {
                out.write(buffer, 0, readBytes);
            }
        } catch (Exception ex) {

        }
    }
}


text:
© 2014 PHP Hampshire. All website source code available under MIT license from PHPH Github.

GitHub

Google+

Twitter

Facebook


text:
var init = {
    api: require(__dirname + '/../api')
};

module.exports = function (logger, config) {

    return new Promise((resolve, reject) => {
        var di = {};

        logger.debug('init di');

        di.logger = logger;
        di.config = config;

        init.api(logger.getLogger('api'), di)
            .then((api) => {
                resolve(api);
            })
            .catch((error) => {
                reject(error);
            });

        return di;
    });

};


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<script src="task-1.js"></script>
<body>
<div>Task Description */
    Create a module for a Telerik Academy course
    The course has a title and presentations
    Each presentation also has a title
    There is a homework for each presentation
    There is a set of students listed for the course
    Each student has firstname, lastname and an ID
    IDs must be unique integer numbers which are at least 1
    Each student can submit a homework for each presentation in the course
    Create method init
    Accepts a string - course title
    Accepts an array of strings - presentation titles
    Throws if there is an invalid title
    Titles do not start or end with spaces
    Titles do not have consecutive spaces
    Titles have at least one character
    Throws if there are no presentations
    Create method addStudent which lists a student for the course
    Accepts a string in the format 'Firstname Lastname'
    Throws if any of the names are not valid
    Names start with an upper case letter
    All other symbols in the name (if any) are lowercase letters
    Generates a unique student ID and returns it
    Create method getAllStudents that returns an array of students in the format:
    {firstname: 'string', lastname: 'string', id: StudentID}
    Create method submitHomework
    Accepts studentID and homeworkID
    homeworkID 1 is for the first presentation
    homeworkID 2 is for the second one
    ...
    Throws if any of the IDs are invalid
    Create method pushExamResults
    Accepts an array of items in the format {StudentID: ..., Score: ...}
    StudentIDs which are not listed get 0 points
    Throw if there is an invalid StudentID
    Throw if same StudentID is given more than once ( he tried to cheat (: )
    Throw if Score is not a number
    Create method getTopStudents which returns an array of the top 10 performing students
    Array must be sorted from best to worst
    If there are less than 10, return them all
    The final score that is used to calculate the top performing students is done as follows:
    75% of the exam result
    25% the submitted homework (count of submitted homeworks / count of all homeworks) for the course
    Course.init('test',['test test']
</div>

</body>
</html>


text:
<?php

namespace AppBundle\DataFixtures\ORM;

use AppBundle\Entity\City;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;

/**
 * Class LoadCitiesData
 *
 * @package AppBundle\DataFixtures\ORM
 * @author Boris MALEZYK <contact@borismalezyk.com>
 */
class LoadCitiesData extends AbstractFixture implements OrderedFixtureInterface
{
    /**
     * @param \Doctrine\Common\Persistence\ObjectManager $manager
     */
    public function load(ObjectManager $manager)
    {
        $citiesName = ['Marseille', 'Paris', 'Londre', 'Berlin', 'Madrid', 'Nice', 'Lyon', 'Montpellier'];
        foreach ($citiesName as $name) {
            $city = new City();
            $city->setName($name);
            $manager->persist($city);
        }

        $manager->flush();
    }

    /**
     * @return int
     */
    public function getOrder()
    {
        // the order in which fixtures will be loaded
        // the lower the number, the sooner that this fixture is loaded
        return 1;
    }
}


text:
require 'spec_helper'

require 'shared_examples_for_get_resource.rb'
require 'shared_examples_for_get_resources.rb'
require 'shared_examples_for_post_resource.rb'

RSpec.describe OiApi::Client::Subscriptions do

  let(:api) { Factory.api_client }

end


text:
function v = entropy_mole(tp)
% ENTROPY_MOLE  Get the mole specific entropy.
% v = entropy_mole(tp)
% :param tp:
%     Instance of class :mat:func:`ThermoPhase` (or another
%     object that derives from ThermoPhase)
% :return:
%     Vector of molar specific entropies of the species. Units: J/kg
%

v = thermo_get(tp.tp_id, 4);


text:
#pragma once

#include <iostream>
#include <string>

#include "modules/localization/msf/local_pyramid_map/base_map/base_map_config.h"
#include "modules/localization/msf/local_pyramid_map/base_map/base_map_fwd.h"

namespace apollo {
namespace localization {
namespace msf {
namespace pyramid_map {

class MapNodeIndex;

std::ostream& operator<<(std::ostream& cout, const MapNodeIndex& index);

class MapNodeIndex {
 public:
  /**@brief The constructor. */
  MapNodeIndex();
  /**@brief Overload the less than operator. */
  bool operator<(const MapNodeIndex& index) const;
  /**@brief Overload the equal operator. */
  bool operator==(const MapNodeIndex& index) const;
  /**@brief Overload the unequal operator. */
  bool operator!=(const MapNodeIndex& index) const;
  std::string ToString() const;

  /**@brief Construct a map node index, given a global coordinate, eigen
   * version. */
  static MapNodeIndex GetMapNodeIndex(const BaseMapConfig& option,
                                      const Eigen::Vector3d& coordinate,
                                      unsigned int resolution_id, int zone_id);
  static MapNodeIndex GetMapNodeIndex(const BaseMapConfig& option,
                                      const Eigen::Vector2d& coordinate,
                                      unsigned int resolution_id, int zone_id);

  /**@brief Get the index range (maximum possible index + 1) in the east
   * direction. */
  static unsigned int GetMapIndexRangeEast(const BaseMapConfig& option,
                                           unsigned int resolution_id);
  /**@brief Get the index range (maximum possible index + 1) in the north
   * direction. */
  static unsigned int GetMapIndexRangeNorth(const BaseMapConfig& option,
                                            unsigned int resolution_id);

  friend std::ostream& operator<<(std::ostream& cout,
                                  const MapNodeIndex& index);

  /**@brief The ID of the resolution.
   * Should be less than BaseMapConfig::_map_resolutions.size(). */
  unsigned int resolution_id_ = 0;
  /**@brief The zone ID. 1 - 60 and -1 - -60.
   * The positive value is the zone at the north hemisphere. */
  int zone_id_ = 10;
  /**@brief The map node ID at the northing direction. */
  unsigned int m_ = 0;
  /**@brief The map node ID at the easting direction. */
  unsigned int n_ = 0;
};

}  // namespace pyramid_map
}  // namespace msf
}  // namespace localization
}  // namespace apollo


text:
require 'httpclient'
require 'json'

module Autobahn
  module RestClient
    module InstanceMethods
      def configure_rest_client(base_url, user, password)
        @base_url = base_url
        @http_client = HTTPClient.new
        @http_client.set_auth(nil, user, password)
      end

      def api_call(entity, id=nil)
        url = "#@base_url/#{entity}"
        url << "/#{id}" if id
        if @base_url
          content = @http_client.get_content(url)
        else
          begin
            @base_url = 'http://localhost:15672/api'.freeze
            content = @http_client.get_content(@base_url + url)
          rescue Errno::ECONNREFUSED
            @base_url = 'http://localhost:55672/api'.freeze
            content = @http_client.get_content(@base_url + url)
          end
        end
        JSON.parse(content)
      end
    end

    module ClassMethods
      def entity(name, options={})
        if options[:singleton]
          define_method(name) { api_call(name) }
        else
          plural = "#{name}s".to_sym
          define_method(plural) { api_call(plural) }
          define_method(name) { |id| api_call(plural, id) }
        end
      end
    end

    def self.included(m)
      m.send(:include, InstanceMethods)
      m.send(:extend, ClassMethods)
    end
  end

  class Cluster
    include RestClient

    entity :node
    entity :channel
    entity :exchange
    entity :queue
    entity :binding
    entity :overview, :singleton => true

    def initialize(api_uri, options={})
      user = options[:user] || 'guest'
      password = options[:password] || 'guest'
      configure_rest_client(api_uri, user, password)
    end
  end
end


text:
namespace tainicom
{
	namespace Aether
	{
		namespace Native
		{
			namespace Animation
			{
				namespace Data
				{
					public value struct Vector4Data
					{
					public:
						float X, Y, Z, W;
					};
				}
			}
		}
	}
}


text:
<?php

namespace StaticCallOnExpression;

class Foo
{

	public static function doFoo(): self
	{
		return new static();
	}

}

function () {
	Foo::doFoo()::doBar();
};


text:
class AddTypeToPost < ActiveRecord::Migration
  def self.up
    add_column :posts, :type, :string
  end

  def self.down
    remove_column :posts, :type
  end
end


text:
'''
Updated on September, 2017
@author: Todd Baumeister <tbaumeist@gmail.com>

API for getting experiment metrics
'''
import os
import json
from flask_restful import Resource
from flask import jsonify, current_app

class SummaryGraphs(Resource):
    '''
    Graph metrics
    '''

    def get(self, variable):
        '''
        Only supports get operation
        '''
        experiment_config_file = os.path.join(
            current_app.config['DATA_DIRECTORY'], 'metrics.json')

        summary_data = {}
        if os.path.exists(experiment_config_file):
            with open(experiment_config_file, 'r') as c_file:
                summary_data = json.loads(c_file.read())
        variable_data = {}
        variable_data['graphs'] = summary_data['graphs'][variable]
        variable_data['data'] = summary_data['data'][variable]
        return jsonify(variable_data)

class SummaryDataAll(Resource):
    '''
    All summary data
    '''

    def get(self):
        '''
        Only supports get operation
        '''
        experiment_config_file = os.path.join(
            current_app.config['DATA_DIRECTORY'], 'metrics.json')

        summary_data = {}
        if os.path.exists(experiment_config_file):
            with open(experiment_config_file, 'r') as c_file:
                summary_data = json.loads(c_file.read())
        return jsonify({'data': summary_data['data']['all']})


text:
var Atom = require("./atom");
var Predicate = require("./predicate");
var List = require("./list");
var Statements = require("./statements");
var Variable = require("./variable");
var {HornClause, UnionStatement, PredicateStatement, OrStatements, AndStatements} = Statements;
//var RuntimeEngine = require("../grammar/runtime-engine")

var dummyVars = ["A", "B", "C", "D", "E", "F"].map((v) => {
  return new Variable({name:v});
})

var freeVariables = ["__A", "__B", "__C", "__D", "__E"].map((v) => {
  return new Variable({name:v});
})

//memberOf(X, Y) :- Y = [A | _], X = A ; (Y = [_ | T],  memberOf(X, T)).
function createMemberClause(){
  var varA = dummyVars[0];
  var varB = dummyVars[1];
  var tailVar = dummyVars[2];
  var memberOfHornClauses = {member:{"2":[]}};
  var memberPredicateHead = new Predicate({name:"member", argsList:[varA, varB]});
  var listMatchPredicate = new List({argsList:[varA, freeVariables[1]]});
  var listMatchUnion = new UnionStatement({subject:varB, object:listMatchPredicate});
  var listFailedMatchPredicate = new List({argsList:[freeVariables[0], tailVar]});
  var listFailedMatchUnion = new UnionStatement({subject:varB, object:listFailedMatchPredicate});
  var memberPredicateRecurse = new Predicate({name:"member", argsList:[varA, tailVar]});
  var memberPredicateRecurseStatement = new PredicateStatement({hornClauses:memberOfHornClauses, predicate:memberPredicateRecurse});
  var failedStatements = new AndStatements({subStatements:[listFailedMatchUnion,memberPredicateRecurseStatement]});
  var orStatement = new OrStatements({subStatements:[listMatchUnion, failedStatements]});
  var bodyStatement = new AndStatements({subStatements:[orStatement]});

  var memberOfHornClause = new HornClause({head:memberPredicateHead, body:bodyStatement});
  memberOfHornClauses.member[2].push(memberOfHornClause); // <-- allow for recursion

  return [memberOfHornClause];
}

//intersect(X, Y, I) :- X = [], I = [].
//intersect(X, Y, I) :- X = [A | B], memberOf(A, Y), I = [A | Res], intersect(B, Y, Res).
//intersect(X, Y, I) :- X = [_ | B], I = [_ | Res], intersect(B, Y, Res).

//subset([], []).
//subset([X|L],[X|S]) :- subset(L,S).
//subset(L, [_|S]) :- subset(L,S).
function createSubsetClause(){
  var varX = dummyVars[0];
  var varY = dummyVars[1];
  var varL = dummyVars[2];
  var varS = dummyVars[3];
  var varM = dummyVars[4];

  var freeVar = freeVariables[0];

  var horns = {"subset":{"2":[]}};
  var subsetPredicate = new Predicate({name:"subset", argsList:[varX, varY]});

  //First
  var emptyXUnion = new UnionStatement({subject: varX, object:List.getEmptyList()});
  var emptyYUnion = new UnionStatement({subject: varY, object:List.getEmptyList()});
  var andsStatements = new AndStatements({subStatements: [emptyXUnion, emptyYUnion]});
  var firstHorn = new HornClause({head:subsetPredicate, body:andsStatements});
  horns.subset[2].push(firstHorn);
  //Second
  var listMatch = new List({argsList:[varM, varL]});
  var secondMatch = new List({argsList:[varM, varS]});
  var xUnion = new UnionStatement({subject:varX, object:listMatch});
  var yUnion = new UnionStatement({subject:varY, object:secondMatch});
  var predicateRecurse = new Predicate({name:"subset", argsList:[varL, varS]});
  var predicateRecurseStatement = new PredicateStatement({predicate:predicateRecurse, hornClauses:horns});
  var secondBody = new AndStatements({subStatements:[xUnion, yUnion, predicateRecurseStatement]});
  var secondHorn = new HornClause({head:subsetPredicate, body:secondBody});
  horns.subset[2].push(secondHorn);
  //Third
  var secondMatch = new List({argsList:[freeVar, varS]});
  var yUnion = new UnionStatement({subject:varY, object:secondMatch});
  var predicateRecurse = new Predicate({name:"subset", argsList:[varX, varS]});
  var predicateRecurseStatement = new PredicateStatement({predicate:predicateRecurse, hornClauses:horns});
  var thirdBody = new AndStatements({subStatements:[yUnion, predicateRecurseStatement]});
  var thirdHorn = new HornClause({head:subsetPredicate, body:thirdBody});
  horns.subset[2].push(thirdHorn);

  return [firstHorn, secondHorn, thirdHorn];
}

//empty([]).
//notEmpty(X) :- X = [_ | B].

//commonElement([], _, []).
//commonElement(_, [], []).
//commonElement(X, Y, Z) :- memberOf(A, X), memberOf(A, Y), Z = [A].

//noCommonElement(X, Y, true) :- commonElement(X, Y, Z), isEmpty(Z, true).
//notCommonElement(X, Y, A) :- commonElement(X, Y)

//remove(_,[],[]).
//remove(A, X, Y) :- X = [A | Y].
//remove(A, X, Y) :- X = [B | Y],

//unique(X, Y)

module.exports = {createMemberClause:createMemberClause, createSubsetClause};


text:
from luigi_td.targets.result import ResultTarget

from six.moves.urllib.parse import urlencode
from six.moves.urllib.parse import quote as url_quote

import logging
logger = logging.getLogger('luigi-interface')

class S3ResultTarget(ResultTarget):
    aws_access_key_id = None
    aws_secret_access_key = None
    bucket = None
    path = None
    format = 'tsv'
    delimiter = None
    quote = None
    escape = None
    null = None
    newline = None
    header = None

    def get_result_url(self):
        reqs = {}
        # required
        reqs['access_key'] = url_quote(self.aws_access_key_id)
        reqs['secret_key'] = url_quote(self.aws_secret_access_key)
        reqs['bucket'] = self.bucket
        reqs['path'] = self.path
        # optional
        params = {}
        for name in ['format']:
            if hasattr(self, name):
                params[name] = getattr(self, name)
        reqs['params'] = urlencode([(key, params[key]) for key in params if params[key]])
        return "s3://{access_key}:{secret_key}@/{bucket}/{path}?{params}".format(**reqs)


text:
package org.apache.helix.messaging.handling;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import com.google.common.collect.ImmutableList;
import org.apache.helix.HelixException;
import org.apache.helix.NotificationContext;
import org.apache.helix.messaging.AsyncCallback;
import org.apache.helix.model.Message;
import org.apache.helix.model.Message.MessageType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AsyncCallbackService implements MultiTypeMessageHandlerFactory {
  private final ConcurrentHashMap<String, AsyncCallback> _callbackMap =
      new ConcurrentHashMap<String, AsyncCallback>();
  private static Logger _logger = LoggerFactory.getLogger(AsyncCallbackService.class);

  public AsyncCallbackService() {
  }

  public void registerAsyncCallback(String correlationId, AsyncCallback callback) {
    if (_callbackMap.containsKey(correlationId)) {
      _logger.warn("correlation id " + correlationId + " already registered");
    }
    _logger.info("registering correlation id " + correlationId);
    _callbackMap.put(correlationId, callback);
  }

  void verifyMessage(Message message) {
    if (!message.getMsgType().toString().equalsIgnoreCase(MessageType.TASK_REPLY.name())) {
      String errorMsg =
          "Unexpected msg type for message " + message.getMsgId() + " type:" + message.getMsgType()
              + " Expected : " + MessageType.TASK_REPLY;
      _logger.error(errorMsg);
      throw new HelixException(errorMsg);
    }
    String correlationId = message.getCorrelationId();
    if (correlationId == null) {
      String errorMsg = "Message " + message.getMsgId() + " does not have correlation id";
      _logger.error(errorMsg);
      throw new HelixException(errorMsg);
    }

    if (!_callbackMap.containsKey(correlationId)) {
      String errorMsg =
          "Message "
              + message.getMsgId()
              + " does not have correponding callback. Probably timed out already. Correlation id: "
              + correlationId;
      _logger.error(errorMsg);
      throw new HelixException(errorMsg, false);
    }
    _logger.info("Verified reply message " + message.getMsgId() + " correlation:" + correlationId);
  }

  @Override
  public MessageHandler createHandler(Message message, NotificationContext context) {
    verifyMessage(message);
    return new AsyncCallbackMessageHandler(message.getCorrelationId(), message, context);
  }

  @Override
  public String getMessageType() {
    return MessageType.TASK_REPLY.name();
  }

  @Override
  public List<String> getMessageTypes() {
    return ImmutableList.of(MessageType.TASK_REPLY.name());
  }

  @Override
  public void reset() {

  }

  public class AsyncCallbackMessageHandler extends MessageHandler {
    private final String _correlationId;

    public AsyncCallbackMessageHandler(String correlationId, Message message,
        NotificationContext context) {
      super(message, context);
      _correlationId = correlationId;
    }

    @Override
    public HelixTaskResult handleMessage() throws InterruptedException {
      verifyMessage(_message);
      HelixTaskResult result = new HelixTaskResult();
      assert (_correlationId.equalsIgnoreCase(_message.getCorrelationId()));
      _logger.info("invoking reply message " + _message.getMsgId() + ", correlationid:"
          + _correlationId);

      AsyncCallback callback = _callbackMap.get(_correlationId);
      synchronized (callback) {
        callback.onReply(_message);
        if (callback.isDone()) {
          _logger.info("Removing finished callback, correlationid:" + _correlationId);
          _callbackMap.remove(_correlationId);
        }
      }
      result.setSuccess(true);
      return result;
    }

    @Override
    public void onError(Exception e, ErrorCode code, ErrorType type) {
      _logger.error("Message handling pipeline get an exception. MsgId:" + _message.getMsgId(), e);
    }
  }
}


text:
require File.join(File.dirname(__FILE__), 'spec_helper')

describe Screw::Driver::Rails do
  before(:each) do
    Dir.stub!(:pwd).and_return(FIXTURE_PATH)
  end

  it "can be railsy" do
    suite = create_suite '--rails'
    suite.should be_rails
  end

  it "should find rails js files" do
    suite = create_suite '--rails'
    suite.rails_urls.length.should == 2
    suite.rails_urls.should include(File.expand_path(File.join(FIXTURE_PATH, 'public', 'javascripts', 'application.js')))
    suite.rails_urls.should include(File.expand_path(File.join(FIXTURE_PATH, 'public', 'javascripts', 'lib.js')))
  end

  it "should serve rails javascripts" do
    suite = create_suite do |context|
      context.should_receive(:get).with('/javascripts/application.js')
      context.should_receive(:get).with('/javascripts/lib.js')
    end

    suite.generate_rails_urls
  end
end


text:
package org.apache.cassandra.db;

import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.Iterator;
import java.util.SortedSet;

import com.google.common.base.Function;
import com.google.common.base.Functions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.io.util.IIterableColumns;
import org.apache.cassandra.utils.Allocator;
import org.apache.cassandra.utils.HeapAllocator;

public abstract class AbstractColumnContainer implements IColumnContainer, IIterableColumns
{
    private static Logger logger = LoggerFactory.getLogger(AbstractColumnContainer.class);

    protected final ISortedColumns columns;

    protected AbstractColumnContainer(ISortedColumns columns)
    {
        this.columns = columns;
    }

    @Deprecated // TODO this is a hack to set initial value outside constructor
    public void delete(int localtime, long timestamp)
    {
        columns.delete(new ISortedColumns.DeletionInfo(timestamp, localtime));
    }

    public void delete(AbstractColumnContainer cc2)
    {
        columns.delete(cc2.columns.getDeletionInfo());
    }

    public boolean isMarkedForDelete()
    {
        return getMarkedForDeleteAt() > Long.MIN_VALUE;
    }

    public long getMarkedForDeleteAt()
    {
        return columns.getDeletionInfo().markedForDeleteAt;
    }

    public int getLocalDeletionTime()
    {
        return columns.getDeletionInfo().localDeletionTime;
    }

    public AbstractType<?> getComparator()
    {
        return columns.getComparator();
    }

    /**
     * Drops expired row-level tombstones.  Normally, these are dropped once the row no longer exists, but
     * if new columns are inserted into the row post-deletion, they can keep the row tombstone alive indefinitely,
     * with non-intuitive results.  See https://issues.apache.org/jira/browse/CASSANDRA-2317
     */
    public void maybeResetDeletionTimes(int gcBefore)
    {
        columns.maybeResetDeletionTimes(gcBefore);
    }

    /**
     * We need to go through each column in the column container and resolve it before adding
     */
    public void addAll(AbstractColumnContainer cc, Allocator allocator, Function<IColumn, IColumn> transformation)
    {
        columns.addAll(cc.columns, allocator, transformation);
    }

    public void addAll(AbstractColumnContainer cc, Allocator allocator)
    {
        addAll(cc, allocator, Functions.<IColumn>identity());
    }

    public void addColumn(IColumn column)
    {
        addColumn(column, HeapAllocator.instance);
    }

    public void addColumn(IColumn column, Allocator allocator)
    {
        columns.addColumn(column, allocator);
    }

    public IColumn getColumn(ByteBuffer name)
    {
        return columns.getColumn(name);
    }

    public boolean replace(IColumn oldColumn, IColumn newColumn)
    {
        return columns.replace(oldColumn, newColumn);
    }

    /*
     * Note that for some of the implementation backing the container, the
     * return set may not have implementation for tailSet, headSet and subSet.
     * See ColumnNamesSet in ArrayBackedSortedColumns for more details.
     */
    public SortedSet<ByteBuffer> getColumnNames()
    {
        return columns.getColumnNames();
    }

    public Collection<IColumn> getSortedColumns()
    {
        return columns.getSortedColumns();
    }

    public Collection<IColumn> getReverseSortedColumns()
    {
        return columns.getReverseSortedColumns();
    }

    public void remove(ByteBuffer columnName)
    {
        columns.removeColumn(columnName);
    }

    public void retainAll(AbstractColumnContainer container)
    {
        columns.retainAll(container.columns);
    }

    public int getColumnCount()
    {
        return columns.size();
    }

    public boolean isEmpty()
    {
        return columns.isEmpty();
    }

    public int getEstimatedColumnCount()
    {
        return getColumnCount();
    }

    public int getLiveColumnCount()
    {
        int count = 0;

        for (IColumn column : columns)
        {
            if (column.isLive())
                count++;
        }

        return count;
    }

    public Iterator<IColumn> iterator()
    {
        return columns.iterator();
    }

    public Iterator<IColumn> reverseIterator()
    {
        return columns.reverseIterator();
    }

    public Iterator<IColumn> iterator(ByteBuffer start)
    {
        return columns.iterator(start);
    }

    public Iterator<IColumn> reverseIterator(ByteBuffer start)
    {
        return columns.reverseIterator(start);
    }

    public boolean hasExpiredTombstones(int gcBefore)
    {
        if (getLocalDeletionTime() < gcBefore)
            return true;

        for (IColumn column : columns)
            if (column.hasExpiredTombstones(gcBefore))
                return true;

        return false;
    }
}


text:
require File.join(File.dirname(__FILE__), '..', 'spec_helper')
require 'yogo/model/schema'

# Testing the data model model
describe 'Data Model' do

  before(:all) do
    @schema = Factory.create(:schema)
    @data_model = @schema.data_model
  end

  after(:all) do
    @schema.destroy
  end

  it "should point to the schema it came from" do
    @data_model.schema.should eql @schema
  end

  describe "default properties" do

    it "should have a yogo_id property" do
      @data_model.properties.map(&:name).should include :yogo_id
    end

    it "should have a created_at property" do
      @data_model.properties.map(&:name).should include :created_at
    end

    it "should have a updated_at property" do
      @data_model.properties.map(&:name).should include :updated_at
    end

  end

  describe "labeled properties" do
    it "should respond to labeled_properties" do
      @data_model.should respond_to :labeled_properties
    end

    it "should be a subset of the properties" do
      subset = (@data_model.properties & @data_model.labeled_properties)
      subset.should eql @data_model.labeled_properties
    end

    it "should contain the option 'label'" do
      @data_model.labeled_properties.each{|p| p.options.keys.should include 'label'}
    end
  end

end


text:
| Evidential Claim  | Artifact or Evidence |
| ------------- | ------------- |
| ADSI API and UI are Deployed to Separate Docker Containers  | [Link] (/metadata/container/Running_Docker_Containers.jpg)  |
| ADSI API and UI Docker Images are Published to the DockerHub Repository | [Link] (/metadata/container/Published_ADSI_Docker_Images.jpg)  |