text:
import unittest
from datetime import timedelta, date
from django.template import Template, Context, add_to_builtins
from django.utils.dateformat import DateFormat
from django.utils.translation import ugettext as _
from django.utils.html import escape

add_to_builtins('django.contrib.humanize.templatetags.humanize')

class HumanizeTests(unittest.TestCase):

    def humanize_tester(self, test_list, result_list, method):
        # Using max below ensures we go through both lists
        # However, if the lists are not equal length, this raises an exception
        for index in xrange(max(len(test_list), len(result_list))):
            test_content = test_list[index]
            t = Template('{{ test_content|%s }}' % method)
            rendered = t.render(Context(locals())).strip()
            self.assertEqual(rendered, escape(result_list[index]),
                             msg="%s test failed, produced %s, should've produced %s" % (method, rendered, result_list[index]))

    def test_ordinal(self):
        test_list = ('1','2','3','4','11','12',
                     '13','101','102','103','111',
                     'something else')
        result_list = ('1st', '2nd', '3rd', '4th', '11th',
                       '12th', '13th', '101st', '102nd', '103rd',
                       '111th', 'something else')

        self.humanize_tester(test_list, result_list, 'ordinal')

    def test_intcomma(self):
        test_list = (100, 1000, 10123, 10311, 1000000, 1234567.25,
                     '100', '1000', '10123', '10311', '1000000', '1234567.1234567')
        result_list = ('100', '1,000', '10,123', '10,311', '1,000,000', '1,234,567.25',
                       '100', '1,000', '10,123', '10,311', '1,000,000', '1,234,567.1234567')

        self.humanize_tester(test_list, result_list, 'intcomma')

    def test_intword(self):
        test_list = ('100', '1000000', '1200000', '1290000',
                     '1000000000','2000000000','6000000000000')
        result_list = ('100', '1.0 million', '1.2 million', '1.3 million',
                       '1.0 billion', '2.0 billion', '6.0 trillion')

        self.humanize_tester(test_list, result_list, 'intword')

    def test_apnumber(self):
        test_list = [str(x) for x in range(1, 11)]
        result_list = (u'one', u'two', u'three', u'four', u'five', u'six',
                       u'seven', u'eight', u'nine', u'10')

        self.humanize_tester(test_list, result_list, 'apnumber')

    def test_naturalday(self):
        from django.template import defaultfilters
        today = date.today()
        yesterday = today - timedelta(days=1)
        tomorrow = today + timedelta(days=1)
        someday = today - timedelta(days=10)
        notdate = u"I'm not a date value"

        test_list = (today, yesterday, tomorrow, someday, notdate)
        someday_result = defaultfilters.date(someday)
        result_list = (_(u'today'), _(u'yesterday'), _(u'tomorrow'),
                       someday_result, u"I'm not a date value")
        self.humanize_tester(test_list, result_list, 'naturalday')

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


text:
<?php

class RLUtil {

    /**
     * This is a handy function that replaces constants and variables inside a string.
     *
     * @param string The string.
     *
     * @return The modified string.
     */
    public static function replaceAll ($string) {

        $string = RLUtil::replaceEchoStatement($string);
        $string = RLUtil::replaceStaticVariables($string);
        $string = RLUtil::replacePHPVariables($string);
        $string = RLUtil::replaceConstants($string);

        return $string;

    }

    /**
     * Replace all PHP constants inside a string.
     *
     * Note: This replaces any {CONSTANT} with the constant value.
     *
     * @param string The string.
     *
     * @return string The modified string.
     */
    public static function replaceConstants ($string) {

        if (preg_match_all('#\{([^$}]+)\}#', $string, $matches)) {

            foreach ($matches[1] as $match) {

                if (defined($match)) {

                    $string = str_replace('{' . $match . '}', constant($match), $string);

                }

            }

        }

        return $string;

    }

    /**
     * Replace all echo statements inside a string.
     *
     * Note: This replaces any {{STATEMENT}} with an echo statement of that exact value.
     *
     * @param string The string.
     *
     * @return string The modified string.
     */
    public static function replaceEchoStatement ($string) {

        $string = preg_replace('#\{\{([^}]+)\}\}#', '<?php echo \1; ?>', $string);

        return $string;

    }

    /**
     * Replace all PHP variables inside a string.
     *
     * Note: This replaces any {$VARIABLE} with the variable value.
     *
     * @param string The string.
     *
     * @return string The modified string.
     */
    public static function replacePHPVariables ($string) {

        if (preg_match_all('#\{(\$[^}]+)\}#', $string, $matches)) {

            foreach ($matches[1] as $match) {

                eval("\$value = {$match};");

                $string = str_replace('{' . $match . '}', $value, $string);

            }

        }

        return $string;

    }

    /**
     * Replace all static template variables inside a string.
     *
     * Note: This replaces any {#VARIABLE} with the static variable value.
     *
     * @param string The string.
     *
     * @return string The modified string.
     */
    public static function replaceStaticVariables ($string) {

        if (preg_match_all('@\{#([^}]+)\}@', $string, $matches)) {

            foreach ($matches[1] as $match) {

                $string = str_replace('{#' . $match . '}', RLStaticTag::getStaticAttribute($match), $string);

            }

        }

        return $string;

    }

}

redpajama_set_name: RedPajamaGithub


text:
#ifndef SRC_GET_STRUCT_FROM_INCHI_WORKER_H_
#define SRC_GET_STRUCT_FROM_INCHI_WORKER_H_

#include <nan.h>

#include <string>

#include "./inchi_queue.h"

/**
   This class, derived from NanAsyncWorker, manages
   asynhronous calls to GetStructFromINCHI

   @module Internal
   @class GetStructFromINCHIWorker
*/
struct GetStructFromINCHIWorker : public NanAsyncWorker {
  GetStructFromINCHIData data_;

  /**
     @method GetStructFromINCHIWorker
     @constructor
     @param {NanCallback *} callback Callback function to call when finished
     @param {std::string} inchi InChI string to convert
  */
  GetStructFromINCHIWorker(NanCallback * callback, const std::string& inchi) :
    NanAsyncWorker(callback), data_(inchi) {
  }

  /**
     @method ~GetStructFromINCHIWorker
  */
  ~GetStructFromINCHIWorker() {
  }

  /**
     Calls GetStructFromINCHI with thread-safe data

     @method Execute
  */
  void Execute();

  /**
     Constructs result value, passes it to callback
     @method
  */
  void HandleOKCallback();
};

#endif  // SRC_GET_STRUCT_FROM_INCHI_WORKER_H_


text:
<?php

namespace Dami\Cli;

use Symfony\Component\Console\Application;
use Dami\Cli\Command\CreateCommand,
    Dami\Cli\Command\MigrateCommand,
    Dami\Cli\Command\RollbackCommand,
    Dami\Cli\Command\StatusCommand;

class DamiApplication extends Application
{
    public function __construct()
    {
        parent::__construct('Dami - [Da]tabase [mi]grations for PHP', '0.9.1');

        $dami = new Dami();
        $container = $dami->getContainer();

        $this->addCommands(array(
            new CreateCommand('create', $container),
            new MigrateCommand('migrate', $container),
            new RollbackCommand('rollback', $container),
            new StatusCommand('status', $container)
        ));
    }
}


text:
package org.apereo.cas.services;

import org.apereo.cas.ticket.TicketState;
import org.apereo.cas.util.model.TriStateBoolean;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.springframework.core.Ordered;

import java.io.Serializable;

/**
 * This is {@link RegisteredServiceSingleSignOnParticipationPolicy}.
 * This contract allows applications registered with CAS to define
 * an expiration policy for SSO sessions. For example, an application
 * may be decide to opt out of participating in SSO, if one exists,
 * if the existing SSO session is somewhat stale or idle given
 * certain timestamps. Likewise, validation events may start to issue
 * failures if the validated assertion is before/after a certain timestamp
 * or fails to pass other requirements for the specific registered service.
 *
 * @author Misagh Moayyed
 * @since 6.1.0
 */
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
@FunctionalInterface
public interface RegisteredServiceSingleSignOnParticipationPolicy extends Serializable, Ordered {

    /**
     * Should registered service participate in sso?
     *
     * @param registeredService the registered service
     * @param ticketState       the ticket state
     * @return true /false
     */
    @JsonIgnore
    boolean shouldParticipateInSso(RegisteredService registeredService, TicketState ticketState);

    @Override
    default int getOrder() {
        return 0;
    }

    /**
     * Flag that indicates whether to create SSO session on re-newed authentication event
     * when dealing with this service.
     *
     * @return true/false
     */
    default TriStateBoolean getCreateCookieOnRenewedAuthentication() {
        return TriStateBoolean.UNDEFINED;
    }
}


text:
using System;
using System.Collections.Generic;
using NLog.Common;
using NLog.Config;
using NLog.Slack.Models;
using NLog.Targets;

namespace NLog.Slack
{
    [Target("Slack")]
    public class SlackTarget : TargetWithContext
    {
        [RequiredParameter]
        public string WebHookUrl { get; set; }

        public bool Compact { get; set; }

        public override IList<TargetPropertyWithContext> ContextProperties { get; } = new List<TargetPropertyWithContext>();

        [ArrayParameter(typeof(TargetPropertyWithContext), "field")]
        public IList<TargetPropertyWithContext> Fields => ContextProperties;

        protected override void InitializeTarget()
        {
            if (String.IsNullOrWhiteSpace(this.WebHookUrl))
                throw new ArgumentOutOfRangeException("WebHookUrl", "Webhook URL cannot be empty.");

            Uri uriResult;
            if (!Uri.TryCreate(this.WebHookUrl, UriKind.Absolute, out uriResult))
                throw new ArgumentOutOfRangeException("WebHookUrl", "Webhook URL is an invalid URL.");

            if (!this.Compact && this.ContextProperties.Count == 0)
            {
                this.ContextProperties.Add(new TargetPropertyWithContext("Process Name", Layout = "${machinename}\\${processname}"));
                this.ContextProperties.Add(new TargetPropertyWithContext("Process PID", Layout = "${processid}"));
            }

            base.InitializeTarget();
        }

        protected override void Write(AsyncLogEventInfo info)
        {
            try
            {
                this.SendToSlack(info);
                info.Continuation(null);
            }
            catch (Exception e)
            {
                info.Continuation(e);
            }
        }

        private void SendToSlack(AsyncLogEventInfo info)
        {
            var message = RenderLogEvent(Layout, info.LogEvent);

            var slack = SlackMessageBuilder
                .Build(this.WebHookUrl)
                .OnError(e => info.Continuation(e))
                .WithMessage(message);

            if (this.ShouldIncludeProperties(info.LogEvent) || this.ContextProperties.Count > 0)
            {
                var color = this.GetSlackColorFromLogLevel(info.LogEvent.Level);
                Attachment attachment = new Attachment(info.LogEvent.Message) { Color = color };
                var allProperties = this.GetAllProperties(info.LogEvent);
                foreach (var property in allProperties)
                {
                    if (string.IsNullOrEmpty(property.Key))
                        continue;

                    var propertyValue = property.Value?.ToString();
                    if (string.IsNullOrEmpty(propertyValue))
                        continue;

                    attachment.Fields.Add(new Field(property.Key) { Value = propertyValue, Short = true });
                }
                if (attachment.Fields.Count > 0)
                    slack.AddAttachment(attachment);
            }

            var exception = info.LogEvent.Exception;
            if (!this.Compact && exception != null)
            {
                var color = this.GetSlackColorFromLogLevel(info.LogEvent.Level);
                var exceptionAttachment = new Attachment(exception.Message) { Color = color };
                exceptionAttachment.Fields.Add(new Field("StackTrace") {
                    Title = $"Type: {exception.GetType().ToString()}",
                    Value = exception.StackTrace ?? "N/A"
                });

                slack.AddAttachment(exceptionAttachment);
            }

            slack.Send();
        }

        private string GetSlackColorFromLogLevel(LogLevel level)
        {
            if (LogLevelSlackColorMap.TryGetValue(level, out var color))
                return color;
            else
                return "#cccccc";
        }

        private static readonly Dictionary<LogLevel, string> LogLevelSlackColorMap = new Dictionary<LogLevel, string>()
        {
            { LogLevel.Warn, "warning" },
            { LogLevel.Error, "danger" },
            { LogLevel.Fatal, "danger" },
            { LogLevel.Info, "#2a80b9" },
        };
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link rel="stylesheet" type="text/css" href="../styles/main.css">

Loading...

filter_shield.js

filter_table.js

Searching...

No Matches


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.

Imports System.Threading
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.CommandHandlers
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces

Public Class VisualBasicGoToAdjacentMemberTests
    <Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
    <WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
    Public Async Function EmptyFile() As Task
        Assert.Null(Await GetTargetPositionAsync("$$", next:=True))
    End Function

    <Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
    <WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
    Public Async Function ClassWithNoMembers() As Task
        Dim code = "Class C
$$
End Class"
        Assert.Null(Await GetTargetPositionAsync(code, next:=True))
    End Function

    <Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
    <WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
    Public Async Function BeforeClassWithMember() As Task
        Dim code = "$$
Class C
    [||]Sub M()
    End Sub
End Class"

        Await AssertNavigatedAsync(code, next:=True)
    End Function

    <Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
    <WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
    Public Async Function AfterClassWithMember() As Task
        Dim code = "
Class C
    [||]Sub M()
    End Sub
End Class

$$"

        Await AssertNavigatedAsync(code, next:=True)
    End Function

    <Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
    <WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
    Public Async Function BetweenClasses() As Task
        Dim code = "
Class C1
    Sub M()
    End Sub
End Class

$$

Class C2
    [||]Sub M()
    End Sub
End Class"

        Await AssertNavigatedAsync(code, next:=True)
    End Function

    <Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
    <WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
    Public Async Function BetweenClassesPrevious() As Task
        Dim code = "
Class C1
    [||]Sub M()
    End Sub
End Class

$$

Class C2
    Sub M()
    End Sub
End Class"

        Await AssertNavigatedAsync(code, next:=False)
    End Function

    <Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
    <WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
    Public Async Function FromFirstMemberToSecond() As Task
        Dim code = "
Class C
    $$Sub M1()
    End Sub
    [||]Sub M2()
    End Sub
End Class"

        Await AssertNavigatedAsync(code, next:=True)
    End Function

    <Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
    <WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
    Public Async Function FromSecondToFirst() As Task
        Dim code = "
Class C
    [||]Sub M1()
    End Sub
    $$Sub M2()
    End Sub
End Class"

        Await AssertNavigatedAsync(code, next:=False)
    End Function

    <Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
    <WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
    Public Async Function NextWraps() As Task
        Dim code = "
Class C
    [||]Sub M1()
    End Sub
    $$Sub M2()
    End Sub
End Class"

        Await AssertNavigatedAsync(code, next:=True)
    End Function

    <Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
    <WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
    Public Async Function PreviousWraps() As Task
        Dim code = "
Class C
    $$Sub M1()
    End Sub
    [||]Sub M2()
    End Sub
End Class"

        Await AssertNavigatedAsync(code, next:=False)
    End Function

    <Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
    <WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
    Public Async Function DescendsIntoNestedType() As Task
        Dim code = "
Class C
    $$Sub M1()
    End Sub

    Class N
        [||]Sub M2()
        End Sub
    End Class
End Class"

        Await AssertNavigatedAsync(code, next:=True)
    End Function

    <Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
    <WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
    Public Async Function StopsAtConstructor() As Task
        Dim code = "
Class C
    $$Sub M1()
    End Sub

    [||]Public Sub New()
    End Sub
End Class"
        Await AssertNavigatedAsync(code, next:=True)
    End Function

    <Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
    <WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
    Public Async Function StopsAtOperator() As Task
        Dim code = "
Class C
    $$Sub M1()
    End Sub
    [||]Shared Operator +(left As C, right As C) As C
        Throw New System.NotImplementedException()
    End Operator
End Class"
        Await AssertNavigatedAsync(code, next:=True)
    End Function

    Shared Operator +(left As VisualBasicGoToAdjacentMemberTests, right As VisualBasicGoToAdjacentMemberTests) As VisualBasicGoToAdjacentMemberTests
        Throw New System.NotImplementedException()
    End Operator

    <Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
    <WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
    Public Async Function StopsAtField() As Task
        Dim code = "
Class C
    $$Sub M1()
    End Sub

    [||]Dim f as Integer
End Class"
        Await AssertNavigatedAsync(code, next:=True)
    End Function

    <Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
    <WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
    Public Async Function StopsAtFieldlikeEvent() As Task
        Dim code = "
Class C
    $$Sub M1()
    End Sub

    [||]Event E As System.EventHandler
End Class"
        Await AssertNavigatedAsync(code, next:=True)
    End Function

    <Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
    <WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
    Public Async Function StopsAtAutoProperty() As Task
        Dim code = "
Class C
    $$Sub M1()
    End Sub
    [||]Property P As Integer
End Class"
        Await AssertNavigatedAsync(code, next:=True)
    End Function

    <Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
    <WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
    Public Async Function StopsAtPropertyWithAccessors() As Task
        Dim code = "
Class C
    $$Sub M1()
    End Sub

    [||]Property P As Integer
        Get
            Return 42
        End Get
        Set(value As Integer)
        End Set
    End Property
End Class"

        Await AssertNavigatedAsync(code, next:=True)
    End Function

    <Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
    <WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
    Public Async Function SkipsPropertyAccessors() As Task
        Dim code = "
Class C
    Sub M1()
    End Sub

    $$Property P As Integer
        Get
            Return 42
        End Get
        Set(value As Integer)
        End Set
    End Property

    [||]Sub M2()
    End Sub
End Class"

        Await AssertNavigatedAsync(code, next:=True)
    End Function

    <Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
    <WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
    Public Async Function FromInsidePropertyAccessor() As Task
        Dim code = "
Class C
    Sub M1()
    End Sub

    Property P As Integer
        Get
            Return $$42
        End Get
        Set(value As Integer)
        End Set
    End Property

    [||]Sub M2()
    End Sub
End Class"

        Await AssertNavigatedAsync(code, next:=True)
    End Function

    <Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
    <WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
    Public Async Function StopsAtEventWithAddRemove() As Task
        Dim code = "
Class C
    $$Sub M1()
    End Sub

    [||]Custom Event E As EventHandler
        AddHandler(value As EventHandler)

        End AddHandler
        RemoveHandler(value As EventHandler)

        End RemoveHandler
        RaiseEvent(sender As Object, e As EventArgs)

        End RaiseEvent
    End Event
End Class"

        Await AssertNavigatedAsync(code, next:=True)
    End Function

    <Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
    <WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
    Public Async Function SkipsEventAddRemove() As Task
        Dim code = "
Class C
    Sub M1()
    End Sub

    $$Custom Event E As EventHandler
        AddHandler(value As EventHandler)

        End AddHandler
        RemoveHandler(value As EventHandler)

        End RemoveHandler
        RaiseEvent(sender As Object, e As EventArgs)

        End RaiseEvent
    End Event

    [||]Sub M2()
    End Sub
End Class"

        Await AssertNavigatedAsync(code, next:=True)
    End Function

    <Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
    <WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
    Public Async Function FromInsideMethod() As Task
        Dim code = "
Class C
    Sub M1()
        $$System.Console.WriteLine()
    End Sub

    [||]Sub M2()
    End Sub
End Class"

        Await AssertNavigatedAsync(code, next:=True)
    End Function

    <Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
    <WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
    Public Async Function NextFromBetweenMethods() As Task
        Dim code = "
Class C
    Sub M1()
    End Sub

    $$

    [||]Sub M2()
    End Sub
End Class"

        Await AssertNavigatedAsync(code, next:=True)
    End Function

    <Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
    <WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
    Public Async Function PreviousFromBetweenMethods() As Task
        Dim code = "
Class C
    [||]Sub M1()
    End Sub

    $$

    Sub M2()
    End Sub
End Class"

        Await AssertNavigatedAsync(code, next:=False)
    End Function

    <Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
    <WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
    Public Async Function NextFromBetweenMethodsInTrailingTrivia() As Task
        Dim code = "
Class C
    Sub M1()
    End Sub $$

    [||]Sub M2()
    End Sub
End Class"

        Await AssertNavigatedAsync(code, next:=True)
    End Function

    <Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
    <WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
    Public Async Function PreviousFromBetweenMethodsInTrailingTrivia() As Task
        Dim code = "
Class C
    [||]Sub M1()
    End Sub $$

    Sub M2()
    End Sub
End Class"

        Await AssertNavigatedAsync(code, next:=False)
    End Function

    <Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
    <WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
    Public Async Function NextInScript() As Task
        Dim code = "
$$Sub M1()
End Sub

[||]Sub M2()
End Sub"

        Await AssertNavigatedAsync(code, next:=True, kind:=SourceCodeKind.Script)
    End Function

    <Fact, Trait(Traits.Feature, Traits.Features.GoToAdjacentMember)>
    <WorkItem(4311, "https://github.com/dotnet/roslyn/issues/4311")>
    Public Async Function PrevInScript() As Task
        Dim code = "
[||]Sub M1()
End Sub

$$Sub M2()
End Sub"

        Await AssertNavigatedAsync(code, next:=False, kind:=SourceCodeKind.Script)
    End Function

    Private Async Function AssertNavigatedAsync(code As String, [next] As Boolean, Optional kind As SourceCodeKind? = Nothing) As Task

        Dim kinds = If(kind IsNot Nothing,
                SpecializedCollections.SingletonEnumerable(kind.Value),
                 {SourceCodeKind.Regular, SourceCodeKind.Script})
        For Each currentKind In kinds
            Using workspace = Await TestWorkspaceFactory.CreateWorkspaceFromLinesAsync(
                LanguageNames.VisualBasic,
                New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
                VisualBasicParseOptions.Default.WithKind(currentKind),
                code)
                Dim hostDocument = workspace.DocumentWithCursor
                Dim document As Document = workspace.CurrentSolution.GetDocument(hostDocument.Id)
                Assert.Empty((Await document.GetSyntaxTreeAsync()).GetDiagnostics())
                Dim targetPosition = Await GoToAdjacentMemberCommandHandler.GetTargetPositionAsync(
                        document,
                        hostDocument.CursorPosition.Value,
                        [next],
                        CancellationToken.None)

                Assert.NotNull(targetPosition)
                Assert.Equal(hostDocument.SelectedSpans.Single().Start, targetPosition.Value)
            End Using
        Next
    End Function

    Private Async Function GetTargetPositionAsync(code As String, [next] As Boolean) As Task(Of Integer?)
        Using workspace = Await TestWorkspaceFactory.CreateWorkspaceFromLinesAsync(
                LanguageNames.VisualBasic,
                New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
                VisualBasicParseOptions.Default,
                code)
            Dim hostDocument = workspace.DocumentWithCursor
            Dim document As Document = workspace.CurrentSolution.GetDocument(hostDocument.Id)
            Assert.Empty((Await document.GetSyntaxTreeAsync()).GetDiagnostics())
            Return Await GoToAdjacentMemberCommandHandler.GetTargetPositionAsync(
                    document,
                    hostDocument.CursorPosition.Value,
                    [next],
                    CancellationToken.None)
        End Using
    End Function

End Class


text:
<!doctype html>

    <title>Code coverage report for thinkjs/lib/Lib/Util/</title>
    <meta charset="utf-8">

    <link rel="stylesheet" href="../../../../prettify.css">

Code coverage report for thinkjs/lib/Lib/Util/

        Statements: 100% (391 / 391)

        Branches: 100% (231 / 231)

        Functions: 98.67% (74 / 75)

        Lines: 100% (391 / 391)

        Ignored: none

All files » thinkjs/lib/Lib/Util/

   File

   Statements

   Branches

   Functions

   Lines

	Behavior.js

	100%
	(6 / 6)
	100%
	(2 / 2)
	66.67%
	(2 / 3)
	100%
	(6 / 6)

	Cache.js

	100%
	(58 / 58)
	100%
	(51 / 51)
	100%
	(8 / 8)
	100%
	(58 / 58)

	Cookie.js

	100%
	(33 / 33)
	100%
	(22 / 22)
	100%
	(3 / 3)
	100%
	(33 / 33)

	Filter.js

	100%
	(50 / 50)
	100%
	(36 / 36)
	100%
	(9 / 9)
	100%
	(50 / 50)

	Session.js

	100%
	(48 / 48)
	100%
	(22 / 22)
	100%
	(7 / 7)
	100%
	(48 / 48)

	Valid.js

	100%
	(81 / 81)
	100%
	(46 / 46)
	100%
	(22 / 22)
	100%
	(81 / 81)

	WebSocket.js

	100%
	(115 / 115)
	100%
	(52 / 52)
	100%
	(23 / 23)
	100%
	(115 / 115)

Generated by istanbul at Tue Sep 23 2014 16:53:49 GMT+0800 (CST)


text:
\hypertarget{category_n_s_array_07_null_stripper_08}{}\section{N\+S\+Array(Null\+Stripper) Category Reference}
\label{category_n_s_array_07_null_stripper_08}\index{N\+S\+Array(\+Null\+Stripper)@{N\+S\+Array(\+Null\+Stripper)}}
\subsection*{Instance Methods}
\begin{DoxyCompactItemize}
\item
(N\+S\+Array $\ast$) -\/ {\bfseries array\+By\+Replacing\+Nulls\+With\+Blanks}\hypertarget{category_n_s_array_07_null_stripper_08_a5e9a9528c57629c07901ed53e60ad90e}{}\label{category_n_s_array_07_null_stripper_08_a5e9a9528c57629c07901ed53e60ad90e}

\end{DoxyCompactItemize}

The documentation for this category was generated from the following files\+:\begin{DoxyCompactItemize}
\item
Pod/\+Classes/\+Categories/N\+S\+Array+\+Null\+Stripper.\+h\item
Pod/\+Classes/\+Categories/N\+S\+Array+\+Null\+Stripper.\+m\end{DoxyCompactItemize}


text:
#include <cstdint>
#include <cstring>

#include <iostream>
#include <stdexcept>

#include <adios2.h>

#include <gtest/gtest.h>

class SstParamFailTest : public ::testing::Test
{
public:
    SstParamFailTest() = default;
};

int TimeGapExpected = 0;
std::string fname = "ADIOS2Sst";

static std::string Trim(std::string &str)
{
    size_t first = str.find_first_not_of(' ');
    size_t last = str.find_last_not_of(' ');
    return str.substr(first, (last - first + 1));
}

/*
 * Engine parameters spec is a poor-man's JSON.  name:value pairs are separated
 * by commas.  White space is trimmed off front and back.  No quotes or anything
 * fancy allowed.
 */
static adios2::Params ParseEngineParams(std::string Input)
{
    std::istringstream ss(Input);
    std::string Param;
    adios2::Params Ret = {};

    while (std::getline(ss, Param, ','))
    {
        std::istringstream ss2(Param);
        std::string ParamName;
        std::string ParamValue;
        std::getline(ss2, ParamName, ':');
        if (!std::getline(ss2, ParamValue, ':'))
        {
            throw std::invalid_argument("Engine parameter \"" + Param +
                                        "\" missing value");
        }
        Ret[Trim(ParamName)] = Trim(ParamValue);
    }
    return Ret;
}

// ADIOS2 Sst param fail
TEST_F(SstParamFailTest, ParamNoValue)
{
    EXPECT_THROW(adios2::Params engineParams =
                     ParseEngineParams("MarshalMethod:"),
                 std::invalid_argument);
}

// ADIOS2 Sst param fail
TEST_F(SstParamFailTest, ParamNoValue2)
{
    EXPECT_THROW(adios2::Params engineParams =
                     ParseEngineParams("MarshalMethod"),
                 std::invalid_argument);
}

// ADIOS2 Sst param fail
TEST_F(SstParamFailTest, MarshalMethodUnknown)
{
    adios2::Params engineParams = ParseEngineParams("MarshalMethod:unknown");

#if ADIOS2_USE_MPI
    adios2::ADIOS adios(MPI_COMM_WORLD);
#else
    adios2::ADIOS adios;
#endif

    adios2::IO io = adios.DeclareIO("TestIO");

    // Create the Engine
    io.SetEngine("Sst");
    io.SetParameters(engineParams);

    adios2::Engine engine;
    EXPECT_THROW(engine = io.Open(fname, adios2::Mode::Write),
                 std::invalid_argument);
    // Close the file
    EXPECT_FALSE(engine);
}

// ADIOS2 Sst param fail
TEST_F(SstParamFailTest, CompressionMethodUnknown)
{
    adios2::Params engineParams =
        ParseEngineParams("CompressionMethod:unknown");

#if ADIOS2_USE_MPI
    adios2::ADIOS adios(MPI_COMM_WORLD);
#else
    adios2::ADIOS adios;
#endif

    adios2::IO io = adios.DeclareIO("TestIO");

    // Create the Engine
    io.SetEngine("Sst");
    io.SetParameters(engineParams);

    adios2::Engine engine;
    EXPECT_THROW(engine = io.Open(fname, adios2::Mode::Write),
                 std::invalid_argument);
    // Close the file
    EXPECT_FALSE(engine);
}

// ADIOS2 Sst param fail
TEST_F(SstParamFailTest, QueueFullPolicyUnknown)
{
    adios2::Params engineParams = ParseEngineParams("QueueFullPolicy:unknown");

#if ADIOS2_USE_MPI
    adios2::ADIOS adios(MPI_COMM_WORLD);
#else
    adios2::ADIOS adios;
#endif

    adios2::IO io = adios.DeclareIO("TestIO");

    // Create the Engine
    io.SetEngine("Sst");
    io.SetParameters(engineParams);

    adios2::Engine engine;
    EXPECT_THROW(engine = io.Open(fname, adios2::Mode::Write),
                 std::invalid_argument);
    // Close the file
    EXPECT_FALSE(engine);
}

// ADIOS2 Sst param fail
TEST_F(SstParamFailTest, RendezvousReaderCountBad)
{
    adios2::Params engineParams =
        ParseEngineParams("RendezvousReaderCount:unknown");

#if ADIOS2_USE_MPI
    adios2::ADIOS adios(MPI_COMM_WORLD);
#else
    adios2::ADIOS adios;
#endif

    adios2::IO io = adios.DeclareIO("TestIO");

    // Create the Engine
    io.SetEngine("Sst");
    io.SetParameters(engineParams);

    adios2::Engine engine;
    EXPECT_THROW(engine = io.Open(fname, adios2::Mode::Write),
                 std::invalid_argument);
    // Close the file
    EXPECT_FALSE(engine);
}

// ADIOS2 Sst param fail
TEST_F(SstParamFailTest, QueueLimitBad)
{
    adios2::Params engineParams = ParseEngineParams("QueueLimit:unknown");

#if ADIOS2_USE_MPI
    adios2::ADIOS adios(MPI_COMM_WORLD);
#else
    adios2::ADIOS adios;
#endif

    adios2::IO io = adios.DeclareIO("TestIO");

    // Create the Engine
    io.SetEngine("Sst");
    io.SetParameters(engineParams);

    adios2::Engine engine;
    EXPECT_THROW(engine = io.Open(fname, adios2::Mode::Write),
                 std::invalid_argument);
    // Close the file
    EXPECT_FALSE(engine);
}

// ADIOS2 Sst param fail
TEST_F(SstParamFailTest, PreciousFirstTimestepParamTest)
{
    adios2::Params engineParams =
        ParseEngineParams("FirstTimestepPrecious:unknown");

#if ADIOS2_USE_MPI
    adios2::ADIOS adios(MPI_COMM_WORLD);
#else
    adios2::ADIOS adios;
#endif

    adios2::IO io = adios.DeclareIO("TestIO");
    adios2::Engine engine;

    // Create the Engine
    io.SetEngine("Sst");
    io.SetParameters(engineParams);

    EXPECT_THROW(engine = io.Open(fname, adios2::Mode::Write),
                 std::invalid_argument);
    // Close the file
    EXPECT_FALSE(engine);
}

//******************************************************************************
// main
//******************************************************************************

int main(int argc, char **argv)
{
#if ADIOS2_USE_MPI
    int provided;

    // MPI_THREAD_MULTIPLE is only required if you enable the SST MPI_DP
    MPI_Init_thread(nullptr, nullptr, MPI_THREAD_MULTIPLE, &provided);
#endif

    int result;
    ::testing::InitGoogleTest(&argc, argv);

    result = RUN_ALL_TESTS();

#if ADIOS2_USE_MPI
    MPI_Finalize();
#endif

    return result;
}


text:
"""
Django settings for oecloud_dashboard project.

Generated by 'django-admin startproject' using Django 1.8.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
import sys
import django
from local_settings import *
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '_m#^f+gh32j7_fdfs#43t#59$2@nm5$vedgcm25ar$xkb9sk-o'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.contenttypes',
    'django.contrib.auth',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.humanize',
    'django_pyscss',
    # 'openstack_dashboard.django_pyscss_fix',
    # 'compressor',
    # 'horizon',
    'openstack_auth',
    'oecloud_dashboard',
    'utils',

]
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
AUTHENTICATION_BACKENDS = ('openstack_auth.backend.KeystoneBackend',)
AUTHENTICATION_URLS = ['openstack_auth.urls']
MESSAGE_STORAGE = 'django.contrib.messages.storage.fallback.FallbackStorage'

SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies'
SESSION_COOKIE_HTTPONLY = True
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_COOKIE_SECURE = False
SESSION_TIMEOUT = 1800
# A token can be near the end of validity when a page starts loading, and
# invalid during the rendering which can cause errors when a page load.
# TOKEN_TIMEOUT_MARGIN defines a time in seconds we retrieve from token
# validity to avoid this issue. You can adjust this time depending on the
# performance of the infrastructure.
TOKEN_TIMEOUT_MARGIN = 10

# When using cookie-based sessions, log error when the session cookie exceeds
# the following size (common browsers drop cookies above a certain size):
SESSION_COOKIE_MAX_SIZE = 4093

# when doing upgrades, it may be wise to stick to PickleSerializer
# NOTE(berendt): Check during the K-cycle if this variable can be removed.
#                https://bugs.launchpad.net/horizon/+bug/1349463
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'utils.middleware.JsonResponseMiddleware',
)
if django.VERSION >= (1, 8, 0):
    MIDDLEWARE_CLASSES += (
        'django.contrib.auth.middleware.SessionAuthenticationMiddleware',)
else:
    MIDDLEWARE_CLASSES += ('django.middleware.doc.XViewMiddleware',)
ROOT_URLCONF = 'oecloud_dashboard.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['',
            os.path.join(BASE_DIR, 'templates'),
            'django.template.loaders.filesystem.Loader',],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
    'horizon.loaders.TemplateLoader',
)

TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, 'templates'),
)
WSGI_APPLICATION = 'oecloud_dashboard.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': DATABASE_NAME,
        'HOST': DATABASE_HOST,
        'PORT': DATABASE_PORT,
        'USER': DATABASE_USER,
        'PASSWORD': DATABASE_PASS,
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

STATIC_URL = '/static/'
if DEBUG:
    STATICFILES_DIRS = ('', os.path.join(BASE_DIR, 'static'))
else:
    STATIC_ROOT = os.path.join(BASE_DIR, 'static')


text:
package galaxyspace.systems.SolarSystem.planets.haumea.blocks;

import java.util.Random;

import micdoodle8.mods.galacticraft.core.blocks.ISortableBlock;
import micdoodle8.mods.galacticraft.core.util.EnumSortCategoryBlock;
import net.minecraft.block.Block;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.PropertyEnum;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IStringSerializable;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

public class HaumeaBlocks extends Block implements ISortableBlock{

	public static final PropertyEnum<EnumHaumeaBlocks> BASIC_TYPE = PropertyEnum.create("type", EnumHaumeaBlocks.class);

	public HaumeaBlocks()
    {
        super(Material.ROCK);
        this.setUnlocalizedName("haumeablocks");
        this.setSoundType(SoundType.STONE);
        this.setHarvestLevel("pickaxe", 2);
    }

	@SideOnly(Side.CLIENT)
    @Override
    public void getSubBlocks(CreativeTabs tab, NonNullList<ItemStack> list)
    {
        for (EnumHaumeaBlocks blockBasic : EnumHaumeaBlocks.values())
        {
            list.add(new ItemStack(this, 1, blockBasic.getMeta()));
        }
    }

	@Override
	public ItemStack getPickBlock(IBlockState state, RayTraceResult target, World world, BlockPos pos, EntityPlayer player) {
		return new ItemStack(Item.getItemFromBlock(this), 1, this.getMetaFromState(state));
	}

	@Override
	public EnumSortCategoryBlock getCategory(int meta) {
		return EnumSortCategoryBlock.GENERAL;
	}

	@Override
    public Item getItemDropped(IBlockState state, Random rand, int fortune)
    {
        switch (getMetaFromState(state))
        {
        	/*case 0:
        		return Items.DIAMOND;
        	case 2:
        		return Items.COAL;
        	case 3:
        		return Items.REDSTONE;
        	case 4:
        		return GCItems.basicItem;*/
        	default:
        		return Item.getItemFromBlock(this);
        }
    }

    @Override
    public int damageDropped(IBlockState state)
    {
        switch (getMetaFromState(state))
        {
	       	case 1:
	            return 2;
	        /*case 2:
	            return 0;
	        case 3:
	            return 0;
	        case 4:
	        	return 2;*/
	        default:
	            return getMetaFromState(state);
        }
    }

    @Override
    public int quantityDropped(IBlockState state, int fortune, Random random)
    {
        int bonus = 0;
/*
        if(this.getMetaFromState(state) == 3)
        {
        	bonus = 4;
        }

        if (this.getMetaFromState(state) == 4)
        {
            bonus = 2;
        }

        if (fortune > 0 && Item.getItemFromBlock(this) != this.getItemDropped(state, random, fortune))
        {
            int j = random.nextInt(fortune + 2) - 1;

            if (j < 0)
            {
                j = 0;
            }

            return this.quantityDropped(random) * (j + 1) + bonus;
        }
        else*/
        {
            return this.quantityDropped(random) + bonus;
        }
    }

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	public enum EnumHaumeaBlocks implements IStringSerializable
	{
		GROUND(0, "haumea_ground"),
		STONE(1, "haumea_stone"),
		COBBLESTONE(2, "haumea_cobblestone"),
		ALUMINUM_ORE(3, "haumea_aluminum_ore");

		private final int meta;
		private final String name;

		private EnumHaumeaBlocks(int meta, String name)
		{
			this.meta = meta;
			this.name = name;
		}

		public int getMeta() { return this.meta; }

		private final static EnumHaumeaBlocks[] values = values();
		public static EnumHaumeaBlocks byMetadata(int meta) { return values[meta % values.length]; }

		@Override
		public String getName() { return this.name; }

	}

	@Override
	public IBlockState getStateFromMeta(int meta)
	{
		return this.getDefaultState().withProperty(BASIC_TYPE, EnumHaumeaBlocks.byMetadata(meta));
	}

	@Override
	public int getMetaFromState(IBlockState state) {
		return state.getValue(BASIC_TYPE).getMeta();
	}

	@Override
	protected BlockStateContainer createBlockState()
	{
		return new BlockStateContainer(this, BASIC_TYPE);
	}

}


text:
<?php
/**
 * Group element that can be used as a container for elements.
 *
 * $Id: Group.php,v 1.1 2006/04/03 20:41:04 eric Exp $
 *
 * @package		patForms
 * @subpackage	Element
 */

/**
 * Group element that can be used as a container for elements.
 *
 * $Id: Group.php,v 1.1 2006/04/03 20:41:04 eric Exp $
 *
 * @access		public
 * @package		patForms
 * @subpackage	Element
 * @author		Stephan Schmidt <schst@php-tools.net>
 * @license		LGPL
 */
class patForms_Element_Group extends patForms_Element
{
   /**
	* Stores the name of the element - this is used mainly by the patForms
	* error management and should be set in every element class.
	* @access	public
	*/
	var $elementName	=	'Group';

   /**
	* The radio element uses a renderer to serialize its content, so we set the flag
	* to true here
	*
	* @access	private
	* @var		array
	*/
	var $usesRenderer	=	true;

   /**
	* set here which attributes you want to include in the element if you want to use
	* the {@link patForms_Element::convertDefinition2Attributes()} method to automatically
	* convert the values from your element definition into element attributes.
	*
	* @access	protected
	* @see		patForms_Element::convertDefinition2Attribute()
	*/
	var	$attributeDefinition	=	array(

		'id' => array(
			'required'		=>	false,
			'format'		=>	'string',
			'outputFormats'	=>	array( 'html' ),
		),
		'name' => array(
			'required'		=>	true,
			'format'		=>	'string',
			'outputFormats'	=>	array( 'html' ),
			'modifiers'		=>	array( 'insertSpecials' => array() ),
		),
		'title' => array(
			'required'		=>	false,
			'format'		=>	'string',
			'outputFormats'	=>	array( 'html' ),
			'modifiers'		=>	array( 'insertSpecials' => array() ),
		),
		'description' => array(
			'required'		=>	false,
			'format'		=>	'string',
			'outputFormats'	=>	array(),
			'modifiers'		=>	array( 'insertSpecials' => array() ),
		),
		'label' => array(
			'required'		=>	false,
			'format'		=>	'string',
			'outputFormats'	=>	array(),
		),
		'display' => array(
			'required'		=>	false,
			'format'		=>	'string',
			'default'		=>	'yes',
			'outputFormats'	=>	array(),
		),
		'edit' => array(
			'required'		=>	false,
			'format'		=>	'string',
			'default'		=>	'yes',
			'outputFormats'	=>	array(),
		),
		'style' => array(
			'required'		=>	false,
			'outputFormats'	=>	array( 'html' ),
			'format'		=>	'string',
		),
		'class' => array(
			'required'		=>	false,
			'outputFormats'	=>	array( 'html' ),
			'format'		=>	'string',
		),
		'position' => array(
			'required'		=>	false,
			'format'		=>	'int',
			'outputFormats'	=>	array(),
		),
		'disabled' => array(
		 	'required'		=>	false,
			'format'		=>	'string',
			'default'		=>	'no',
			'outputFormats'	=>	array( 'html' )
		)
	);

   /**
	* stores the element objects of this form.
	* @access	protected
	* @see		addElement()
	*/
	var $elements	=	array();

   /**
	* stores a renderer
	* @access	protected
	* @see		setRenderer()
	*/
	var $renderer		=	null;

    /**
     *	define error codes an messages for each form element
     *
     *  @access private
     *  @var	array	$validatorErrorCodes
     */
	var	$validatorErrorCodes  =   array(
										"C"	=>	array(
														),
										"de" =>	array(
													)
										);

   /**
	* stores the current element count for this form, used to generate the ids for each element
	* @access	protected
	* @see		getElementId()
	*/
	var $elementCounter	=	0;

   /**
    * flag to indicate, whether the element is a container element
    *
    * @access private
    * @var    boolean
    */
    var $containerElement = false;

   /**
	* sets the locale (language) to use for the validation error messages of the form.
	*
	* @access	public
	* @param	string	$lang
	* @return	bool	$result	True on success
	* @see		$locale
	*/
    function setLocale( $lang )
    {
		$this->locale = $lang;
		$cnt = count($this->elements);
    	for ($i = 0; $i < $cnt; $i++) {
    		$this->elements[$i]->setLocale($lang);
    	}
        return  true;
    }

   /**
	* sets the format of the element - this defines which method will be called in your
	* element class, along with the {@link mode} property.
	*
	* @access	public
	* @param	string	$format	The name of the format you have implemented in your element(s). Default is 'html'
	* @see		setFormat()
	* @see		format
	* @see		serialize()
	*/
	function setFormat( $format )
	{
		$this->format = strtolower($format);
		$cnt = count($this->elements);
    	for ($i = 0; $i < $cnt; $i++) {
    		$this->elements[$i]->setFormat($format);
    	}
	}

   /**
	* sets the mode of the element that defines which methods will be called in your
	* element class, along with the {@link format} property.
	*
	* @access	public
	* @param	string	$mode	The mode to set the element to: default|readonly or any other mode you have implemented in your element class(es). Default is 'default'.
	* @see		setFormat()
	* @see		mode
	* @see		serialize()
	*/
	function setMode( $mode )
	{
		$this->mode	= strtolower( $mode );
		$cnt = count($this->elements);
    	for ($i = 0; $i < $cnt; $i++) {
    		$this->elements[$i]->setMode($mode);
    	}
	}

   /**
	* set the element's namespace
	*
	* @static
	* @access	public
	* @param	string		namespace
	* @return	null
	*/
	function setNamespace($namespace)
	{
		$this->namespace = $namespace;
		$cnt = count($this->elements);
    	for ($i = 0; $i < $cnt; $i++) {
    		$this->elements[$i]->setNamespace($namespace);
    	}
	}

   /**
    * sets a renderer object that will be used to render
	* the form.
	*
	* @access	public
	* @param	object	renderer object
	* @see		renderForm()
	*/
	function setRenderer( &$renderer )
	{
		if (!is_object($renderer)) {
			return patErrorManager::raiseError(
				PATFORMS_ERROR_INVALID_RENDERER,
				"No patForms_Renderer object supplied"
			);
		}

		$this->renderer = &$renderer;
	}

   /**
	* adds an observer to the element
	*
	* @access	public
	* @param	object patForms_Observer	observer
	* @return	boolean						currently always true
	*/
	function attachObserver( &$observer )
	{
		$this->observers[] = &$observer;
		$cnt = count($this->elements);
    	for ($i = 0; $i < $cnt; $i++) {
    		$this->elements[$i]->attachObserver($observer);
    	}
		return true;
	}

   /**
	* adds an element to the form - has to be a patForms_Element object. Use the {@link createElement()}
	* method to create a new element object. Also takes care of passing on the form's configuration
	* including the mode, format and submitted flags to the element.
	*
	* @access	public
	* @param	object	&$element	The patForms_Element object to add to this form.
	* @return	bool	$success	True if everythng went well, false otherwise.
	* @see		patForms_Element
	* @see		createElement()
	*/
	function addElement(&$element)
	{
		if (!is_object($element)) {
			return patErrorManager::raiseError(
				PATFORMS_ERROR_ELEMENT_IS_NO_OBJECT,
				"Given element is not an object"
			);
		}

		if (patErrorManager::isError($element)) {
			return patErrorManager::raiseError(
				PATFORMS_ERROR_UNEXPECTED_ERROR,
				"Unexpected Error Object!"
			);
		}

		if (!$element->getId()) {
			$element->setId($this->getElementId());
		}
		$element->setMode($this->getMode());
		$element->setFormat($this->getFormat());
		$element->setSubmitted($this->getSubmitted());
		$element->setNamespace($this->getNamespace());

		$this->elements[] = &$element;
		return true;
	}

   /**
	* retreives a new element id, used to give each added element a unique id for this
	* form (id can be overwritten by setting the id attribute specifically).
	*
	* @access	private
	* @return	int	$elementId	The new element id.
	*/
	function getElementId()
	{
		$this->elementCounter++;
		return "pfo" . $this->getName() . $this->elementCounter;
	}

   /**
	* element creation method for the 'HTML' format in the 'default' form mode.
	*
	* @access	public
	* @param	mixed	value of the element
	* @return	mixed	$element	The element, or false if failed.
	*/
	function serializeHtmlDefault( $value )
	{
		// manage display attribute. If set, only the needed hidden
		// elements for the subelements will be created.
		if( $this->attributes['display'] == 'no' )
		{
			return $this->createDisplaylessTag( $value );
		}

		if( $this->renderer === null )
		{
			return patErrorManager::raiseError(
				PATFORMS_ERROR_NO_RENDERER_SET,
				"No renderer has been set."
			);
		}

		// edit attribute is inherited by all subelements
		if( $this->attributes['edit'] == 'no' )
		{
			$cnt = count( $this->elements );

			for( $i=0; $i < $cnt; $i++ )
			{
				$this->elements[$i]->setAttribute( 'edit', 'no' );
			}
		}

		return $this->renderer->render( $this );
	}

   /**
	* rewritten for the speciality of the group - creates a collection
	* of hidden elements for all subelements of the group.
	*
	* @access	public
	* @param	mixed	value of the element
	* @return	string	$value	The element's value
	*/
	function createDisplaylessTag( $value )
	{
		$this->getAttributesFor( $this->getFormat() );

		$tag = '';
		$cnt = count( $this->elements );

		for( $i=0; $i < $cnt; $i++ )
		{
			$this->elements[$i]->setAttribute( 'display', 'no' );
			$tag .= $this->elements[$i]->serialize();
		}

		return $tag;
	}

   /**
	* element creation method for the 'HTML' format in the 'readonly' form mode.
	* Very simple; just returns the stored element value.
	*
	* @access	public
	* @param	mixed	value of the element
	* @return	string	$value	The element's value
	*/
	function serializeHtmlReadonly( $value )
	{
		// manage display attribute.
		if( $this->attributes['display'] == 'no' )
		{
			return $this->createDisplaylessTag( $value );
		}

		return $this->renderer->render( $this );
	}

   /**
	* validates the element.
	*
	* @access	public
	* @param	mixed	value of the element
	* @return	bool	$isValid	True if element could be validated, false otherwise.
	*/
	function validateElement( $value )
	{
		$valid = true;

		$cnt = count($this->elements);
		for ($i = 0; $i < $cnt; ++$i) {
			if (!$this->elements[$i]->validate()) {
				$valid = false;
			}
		}
		return $valid;
	}

   /**
	* Get an element by its name.
	*
	* @access	public
	* @param	string	$name	name of the element
	* @return	mixed			either a patForms element or an array containing patForms elements
	* @see		getElementById()
	*/
	function &getElementByName( $name )
	{
		if( $name == '__form' ) {
			return $this;
		}

		$elements = array();
		$cnt      = count( $this->elements );
		for ($i = 0; $i < $cnt; $i++) {
			if ($this->elements[$i]->getName() == $name) {
				$elements[]	= &$this->elements[$i];
				continue;
			}
			if (method_exists($this->elements[$i], 'getElementById')) {
				patErrorManager::pushExpect(PATFORMS_ERROR_ELEMENT_NOT_FOUND);
				$result = &$this->elements[$i]->getElementByName($name);
				patErrorManager::popExpect();
				if (!patErrorManager::isError($result)) {
					if (is_array($result)) {
						$cnt2 = count( $result );
						for ($j = 0; $j < $cnt2; $j++) {
							$elements[]	= &$result[$j];
						}
					} else {
						$elements[]	= &$result;
					}
				}
			}
		}

		switch( count( $elements ) )
		{
			case	0:
				return patErrorManager::raiseError(
					PATFORMS_ERROR_ELEMENT_NOT_FOUND,
					'Element '.$name.' could not be found.'
				);
				break;
			case	1:
				return	$elements[0];
				break;
			default:
				return	$elements;
				break;
		}
	}

   /**
	* Get an element by its id.
	*
	* @access	public
	* @param	string	$id		id of the element
	* @return	object			patForms element
	*/
	function &getElementById( $id )
	{
		$cnt	=	count( $this->elements );
		for( $i = 0; $i < $cnt; $i++ )
		{
			if( $this->elements[$i]->getId() == $id ) {
				return $this->elements[$i];
			}
			if (method_exists($this->elements[$i], 'getElementById')) {
				patErrorManager::pushExpect(PATFORMS_ERROR_ELEMENT_NOT_FOUND);
				$result = &$this->elements[$i]->getElementById($id);
				patErrorManager::popExpect();
				if (!patErrorManager::isError($result)) {
					return $result;
				}
			}
		}
		return patErrorManager::raiseError(
			PATFORMS_ERROR_ELEMENT_NOT_FOUND,
			'Element '.$name.' could not be found.'
		);
	}

   /**
	* Get all elements of the group
	*
	* @access	public
	* @return	array	all elements of the group
	*/
	function &getElements()
	{
		return	$this->elements;
	}

   /**
	* serialize start of group
	*
	* @return	null
	*/
	function serializeStart()
	{
		return null;
	}

   /**
	* serialize end of group
	*
	* @return	null
	*/
	function serializeEnd()
	{
		return null;
	}

	/**
	* getValidationErrors
	*
	* @access	public
	* @return 	array	errors that occured during the validation
	*/
    function getValidationErrors()
    {
    	$this->validationErrors = array();
    	foreach ($this->elements as $element) {
    		$childErrors = $element->getValidationErrors();
    		$this->validationErrors = array_merge($this->validationErrors, $childErrors);
    	}
    	return parent::getValidationErrors();
    }

   /**
	* sets the current submitted state of the element. Set this to true if you want the element
	* to pick up its submitted data.
	*
	* @access	public
	* @param	bool	$state	True if it has been submitted, false otherwise (default).
	* @see		getSubmitted()
	* @see		$submitted
	*/
	function setSubmitted( $state )
	{
		$this->submitted = $state;
		$cnt = count($this->elements);
    	for ($i = 0; $i < $cnt; $i++) {
    		$this->elements[$i]->setSubmitted($state);
    	}
	}

   /**
	* retrieves the current value of the element. If none is set, will try to retrieve the
	* value from submitted form data.
	*
	* @access	public
	* @param	boolean		Determines whether the method is used from an external script
	* @return	mixed		The value, or an empty string if none found.
	* @see		setValue()
	* @see		value
	* @see		resolveValue()
	*/
	function getValue($external = true)
	{
		$value = array();
		$cnt = count($this->elements);
		for ($i = 0; $i < $cnt; $i++) {
			$elName = $this->elements[$i]->getName();
			$elVal  = $this->elements[$i]->getValue($external);
			$value[$elName] = $elVal;
		}
		return $value;
	}

   /**
	* sets the value of the element, which will be used to fill the element with. If none is
	* set and the element needs a value, it will load it using the {@link resolveValue()} method.
	*
	* @access	public
	* @param	mixed	$value	The value to set
	* @see		$value
	* @see		resolveValue()
	* @see		getValue()
	*/
	function setValue($value)
	{
		patErrorManager::pushExpect(PATFORMS_ERROR_ELEMENT_NOT_FOUND);
		foreach ($values as $elName => $value) {
			$el = &$this->getElementByName($elName);
			if (patErrorManager::isError($el)) {
				continue;
			}
			$el->setValue($value);
		}
		patErrorManager::popExpect();
		return true;
	}

   /**
	* sets the default value of the element, which will be used to fill the element with.
	*
	* @access	public
	* @param	mixed	$value	The value to set
	* @see		$value
	* @see		resolveValue()
	* @see		getValue()
	*/
	function setDefaultValue($value)
	{
		patErrorManager::pushExpect(PATFORMS_ERROR_ELEMENT_NOT_FOUND);
		foreach ($values as $elName => $value) {
			$el = &$this->getElementByName($elName);
			if (patErrorManager::isError($el)) {
				continue;
			}
			$el->setDefaultValue($value);
		}
		patErrorManager::popExpect();
		return true;
	}

   /**
	* replaces an element in the form
	*
	* @access	public
	* @param	object	$element	The patForms_Element object to be replaced
	* @param	object	&$replace	The element that will replace the old element
	* @return	bool	$success	True if everything went well, false otherwise.
	* @see		patForms_Element
	* @see		addElement()
	*/
	function replaceElement( $element, &$replace )
	{
		if (is_object($element)) {
			$element = $element->getId();
		}

		$cnt = count($this->elements);
		for ($i = 0; $i < $cnt; $i++) {
			if ($this->elements[$i]->getId() !== $element) {
				continue;
			}

			if( !$replace->getId() ) {
				$replace->setId( $this->getElementId() );
			}
			$replace->setMode( $this->getMode() );
			$replace->setFormat( $this->getFormat() );
			$replace->setSubmitted( $this->isSubmitted() );
			$replace->setLocale( $this->getLocale() );

			$this->elements[$i] = &$replace;
			return true;
		}
		return false;
	}
}
?>


text:
package mediabrowser.model.configuration;

import mediabrowser.model.entities.*;

public class MetadataPluginSummary
{
	/**
	 Gets or sets the type of the item.

	 <value>The type of the item.</value>
	*/
	private String ItemType;
	public final String getItemType()
	{
		return ItemType;
	}
	public final void setItemType(String value)
	{
		ItemType = value;
	}

	/**
	 Gets or sets the plugins.

	 <value>The plugins.</value>
	*/
	private java.util.ArrayList<MetadataPlugin> Plugins;
	public final java.util.ArrayList<MetadataPlugin> getPlugins()
	{
		return Plugins;
	}
	public final void setPlugins(java.util.ArrayList<MetadataPlugin> value)
	{
		Plugins = value;
	}

	/**
	 Gets or sets the supported image types.

	 <value>The supported image types.</value>
	*/
	private java.util.ArrayList<ImageType> SupportedImageTypes;
	public final java.util.ArrayList<ImageType> getSupportedImageTypes()
	{
		return SupportedImageTypes;
	}
	public final void setSupportedImageTypes(java.util.ArrayList<ImageType> value)
	{
		SupportedImageTypes = value;
	}

	public MetadataPluginSummary()
	{
		setSupportedImageTypes(new java.util.ArrayList<ImageType>());
		setPlugins(new java.util.ArrayList<MetadataPlugin>());
	}
}


text:
package com.selenium.training.day1;

import org.openqa.selenium.firefox.FirefoxDriver;

public class FirefoxDriverExample {

	public static void main(String[] args) {
		FirefoxDriver driver = new FirefoxDriver();
		driver.get("http://www.google.com");
		System.out.println("Page Title :" + driver.getTitle());
		driver.quit();
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@color/widgets_emo_pannel_bg"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/message_layout_container_emotes"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="200.0dip" >

            <GridView
                android:id="@+id/message_facebar_gv_emotes"
                style="@style/Style_Scrollable"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:listSelector="@null"
                android:numColumns="7" />
        </LinearLayout>

        <RadioGroup
            android:id="@+id/message_facebar_radiobutton_type"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:background="@drawable/selector_emo_group"
            android:gravity="center_vertical"
            android:orientation="horizontal" >

            <RadioButton
                android:id="@+id/emote_radio_1"
                style="@style/Emote_RadioB_style.Text"
                android:text="@string/emote_type_1" />

            <View
                android:layout_width="1.0dip"
                android:layout_height="fill_parent"
                android:background="@color/widgets_general_row_line"
                android:focusable="false" />

            <RadioButton
                android:id="@+id/emote_radio_2"
                style="@style/Emote_RadioB_style.Text"
                android:text="@string/emote_type_2" />

            <View
                android:layout_width="1.0dip"
                android:layout_height="fill_parent"
                android:background="@color/widgets_general_row_line"
                android:focusable="false" />

            <RadioButton
                android:id="@+id/emote_radio_3"
                style="@style/Emote_RadioB_style.Text"
                android:text="@string/emote_type_3" />

            <View
                android:layout_width="1.0dip"
                android:layout_height="fill_parent"
                android:background="@color/widgets_general_row_line"
                android:focusable="false" />

            <RadioButton
                android:id="@+id/emote_radio_4"
                style="@style/Emote_RadioB_style.Text"
                android:text="@string/emote_type_4" />

            <View
                android:layout_width="1.0dip"
                android:layout_height="fill_parent"
                android:background="@color/widgets_general_row_line"
                android:focusable="false" />

            <RadioButton
                android:id="@+id/emote_radio_5"
                style="@style/Emote_RadioB_style.Text"
                android:text="@string/emote_type_5" />

            <View
                android:layout_width="1.0dip"
                android:layout_height="fill_parent"
                android:background="@color/widgets_general_row_line"
                android:focusable="false" />

            <ImageView
                android:id="@+id/emote_radio_delete"
                style="@style/Emote_RadioB_style"
                android:clickable="true"
                android:src="@drawable/ic_topbar_back_normal" />
        </RadioGroup>
    </LinearLayout>
</LinearLayout>


text:
SPF module performs checks of the sender's [SPF](http://www.openspf.org/) policy.
Many mail providers uses SPF records to define which hosts are eligible to send email
for this specific domain. In fact, there are many possibilities to create and use
SPF records, however, all they check merely the sender's domain and the sender's IP.

The specific case are automated messages from the special mailer daemon address:
`<>`. In this case rspamd uses `HELO` to grab domain information as specified in the
standart.

## Principles of work

`SPF` can be a powerfull tool when properly used. However, it is very fragile in many
cases: when a message is somehow redirected or reconstructed by mailing lists software.

Moreover, many mail providers have no clear understanding of this technology and
misuse the SPF technique. Hence, the scores for SPF symbols are relatively small
in rspamd.

SPF uses DNS service extensively, therefore rspamd maintain the cache of SPF records.
This caches operates on principle of `least recently used` expiration. All cached items
lifetimes is accordingly limited by the matching DNS record time to live.

You can manually specify the size of this cache by configuring SPF module:

~~~nginx
spf {
	spf_cache_size = 1k; # cache up to 1000 of the most recent SPF records
}
~~~

Currently, rspamd supports the full set of SPF elements, macroes and has internal
protection from DNS recursion.


text:
/*
 ONOS GUI -- Topology Node Position Module.
 Module that helps position nodes in the topology
 */

(function () {
    'use strict';

    // Injected vars
    var rs, t2mcs;

    // Internal state;
    var nearDist = 15;

    function positionNode(node, forUpdate) {
        var meta = node.get('metaUi'),
            x = meta && meta.x,
            y = meta && meta.y,
            dim = [800, 600],
            xy;

        // If the device contains explicit LONG/LAT data, use that to position
        if (setLongLat(node)) {
            // Indicate we want to update cached meta data...
            return true;
        }

        // else if we have [x,y] cached in meta data, use that...
        if (x !== undefined && y !== undefined) {
            node.fixed = true;
            node.px = node.x = x;
            node.py = node.y = y;
            return;
        }

        // if this is a node update (not a node add).. skip randomizer
        if (forUpdate) {
            return;
        }

        // Note: Placing incoming unpinned nodes at exactly the same point
        //        (center of the view) causes them to explode outwards when
        //        the force layout kicks in. So, we spread them out a bit
        //        initially, to provide a more serene layout convergence.
        //       Additionally, if the node is a host, we place it near
        //        the device it is connected to.

        function rand() {
            return {
                x: rs.randDim(dim[0]),
                y: rs.randDim(dim[1])
            };
        }

        function near(node) {
            return {
                x: node.x + nearDist + rs.spread(nearDist),
                y: node.y + nearDist + rs.spread(nearDist)
            };
        }

        function getDevice(cp) {
            return rand();
        }

        xy = (node.class === 'host') ? near(getDevice(node.cp)) : rand();

        if (node.class === 'sub-region') {
            xy = rand();
            node.x = node.px = xy.x;
            node.y = node.py = xy.y;
        }
        angular.extend(node, xy);
    }

    function setLongLat(el) {
        var loc = el.get('location'),
            coord;

        if (loc && loc.type === 'lnglat') {

            if (loc.lat === 0 && loc.lng === 0) {
                return false;
            }

            coord = coordFromLngLat(loc);
            el.fixed = true;
            el.x = el.px = coord[0];
            el.y = el.py = coord[1];

            return true;
        }
    }

    function coordFromLngLat(loc) {
        var p = t2mcs.projection();
        return p ? p([loc.lng, loc.lat]) : [0, 0];
    }

    angular.module('ovTopo2')
    .factory('Topo2NodePositionService',
        ['RandomService', 'Topo2MapConfigService',
            function (_rs_, _t2mcs_) {

                rs = _rs_;
                t2mcs = _t2mcs_;

                return {
                    positionNode: positionNode,
                    setLongLat: setLongLat
                };
            }
        ]);
})();


text:
- http://blog.trackets.com/2014/05/17/ssh-tunnel-local-and-remote-port-forwarding-explained-with-examples.html
- http://lifepluslinux.blogspot.com/2017/01/look-before-you-paste-from-website-to.html

## Sign / Verify ##

```
openssl genrsa -out private.pem 2048
openssl rsa -in private.pem -out public.pem -outform PEM -pubout
```

```
  echo -n "data-to-sign" | openssl dgst -RSA-SHA256 -sign private.pem > signed
  base64 signed
```

```
  openssl dgst -RSA-SHA256 -verify public.pem -signature signed
```

ssh-keygen

## Upload SSH Keys ##

```
  ssh-keygen -t rsa -b 4096 -f ~/.ssh/{mykey} -P ''
  mv !!:6 !!:6.key

  ssh-copy-id -i ~/.ssh/{mykey} {user}@{hostname}
```

## Run Script ##

Running a script on a remote server

```bash
ssh user@host 'bash -s' < /path/script.sh
```
Or

```bash
cat /path/script.sh | ssh user@host 'bash -s'
```

```bash
ssh root@192.168.1.1 'bash -s' -- < script.sh --argument
```

## Port Forwarding ##

Remote Port Forwarding

````
  ssh -nNR 80:localhost:8080 hostname &
  echo $!

  kill $!
```

Check for existing SSH tunnels

```
  ps aux | grep ssh
```

### Port forwarding on remote server

~/.ssh/config
```ssh
Host remotehost-proxy
  HostName remotehost
  ControlPath ~/.ssh/remotehost-proxy.ctl
```

Start the forwarding
```sh
ssh -f -N -T -M -L 3306:localhost:3306 remotehost-proxy
```

Stop the forwarding
```
ssh -T -O "exit" remotehost-proxy
```

## Gitlab Setup ##
`git clone gitlab:user/repo.git`

```ssh
  Host gitlab
    User git
    HostName gitlab.com
    IdentityFile ~/.ssh/gitlab.pem
  #  IdentitiesOnly yes
```

## SSH Config ##

```
  LocalForward 5433 localhost:5432
  ProxyCommand ssh gateway -W %h:%p

  # Speed up ssh connections
  GSSAPIAuthentication no
  IdentitiesOnly yes
```

## Setup LDAP SSH Access ##

- https://eng.ucmerced.edu/soe/computing/services/ssh-based-service/ldap-ssh-access

GPG Multikey

```
git archive --remote=$REMOTE_URL HEAD $SECRETS_FILENAME.gpg | tar -Ox | gpg --decrypt -q 2>>$LOG_LOCATION | xargs -I{} echo "export "\{\}
```

## Control Path ##

List keys in SSH Agent
```
ssh-add -L
```

Setup control path
```
mkdir -p ~/.ssh/cp
chmod 700 ~/.ssh/cp
```

### ~/.ssh/config ###

```
  # Protected Server
  Host server01
  	ForwardAgent yes
    HostName server01.domain.com
  	ProxyCommand ssh -A -q -W %h:%p jumpbox01

  # Jumpbox
  Host jumpbox01
  	ControlMaster auto
  	ControlPath ~/.ssh/cp/%r@%h:%p
  	ControlPersist 5m
  	ForwardAgent yes
    HostName jumpbox01.domain.com
```

```
ssh -O check jumpbox01
ssh -O stop jumpbox01
```

# Keys #

Generate a self-signed certificate
```
openssl req -x509 -new -newkey rsa:2048 -nodes -subj '/C=US/ST=California/L=San Francisco/O=JankyCo/CN=Test Identity Provider' -keyout idp-private-key.pem -out idp-public-cert.pem -days 7300
```

Convert DER to PEM
```
openssl x509 -inform der -in to-convert.der -out converted.pem
```

Convert Cert to Public Key
```
openssl x509 -pubkey -noout -in cert.pem > pub.key
```


text:
import logging
import os
from random import choice
import re
import shlex
import string
import subprocess

LOG = logging.getLogger(__name__)

def genmac(start=None):
    LOG.debug('Generating mac address')
    if start is None:
        start = u'00:16:3e:'
    chars = string.digits + 'abcdef'
    mac = start + u':'.join([
        '{0}{1}'.format(choice(chars), choice(chars)) for _ in xrange(3)])
    LOG.debug('Generated mac: %s' % mac)
    return mac

class ExecResult(object):
    def __init__(self, stdout, stderr='', return_code=0):
        self.stdout = stdout
        self.stderr = stderr
        self.return_code = return_code

    def __str__(self):
        return self.stdout

    def __repr__(self):
        return self.stdout

def execute(command, to_filename=None, cwd=None):
    LOG.debug('Trying to execute command: %s', command)
    commands = [c.strip() for c in re.split(ur'\|', command)]

    to_file = None
    if to_filename:
        to_file = open(to_filename, 'wb')

    process = []
    for c in commands:
        try:
            # NOTE(eli): Python's shlex implementation doesn't like unicode.
            # We have to convert to ascii before shlex'ing the command.
            # http://bugs.python.org/issue6988
            encoded_command = c.encode('ascii')

            process.append(subprocess.Popen(
                shlex.split(encoded_command),
                env=os.environ,
                stdin=(process[-1].stdout if process else None),
                stdout=(to_file
                        if (len(process) == len(commands) - 1) and to_file
                        else subprocess.PIPE),
                stderr=(subprocess.PIPE),
                cwd=cwd
            ))
        except OSError as e:
            return (1, '', '{0}\n'.format(e))

        if len(process) >= 2:
            process[-2].stdout.close()
    stdout, stderr = process[-1].communicate()
    out = ExecResult(stdout, stderr=stderr, return_code=process[-1].returncode)
    return out


text:
#include <cassert>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
#include <sstream>

#include <sys/signal.h>

#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
#include <grpc/support/histogram.h>
#include <grpc/support/log.h>
#include <grpc/support/host_port.h>
#include <gflags/gflags.h>
#include <grpc++/client_context.h>
#include <grpc++/server.h>
#include <grpc++/server_builder.h>
#include <grpc++/status.h>
#include <grpc++/stream.h>
#include <gtest/gtest.h>
#include "test/cpp/util/create_test_channel.h"
#include "test/cpp/qps/client.h"
#include "test/cpp/qps/qpstest.grpc.pb.h"
#include "test/cpp/qps/histogram.h"
#include "test/cpp/qps/timer.h"

namespace grpc {
namespace testing {

class SynchronousClient : public Client {
 public:
  SynchronousClient(const ClientConfig& config) : Client(config) {
    num_threads_ =
        config.outstanding_rpcs_per_channel() * config.client_channels();
    responses_.resize(num_threads_);
  }

  virtual ~SynchronousClient(){};

 protected:
  size_t num_threads_;
  std::vector<SimpleResponse> responses_;
};

class SynchronousUnaryClient GRPC_FINAL : public SynchronousClient {
 public:
  SynchronousUnaryClient(const ClientConfig& config)
      : SynchronousClient(config) {
    StartThreads(num_threads_);
  }
  ~SynchronousUnaryClient() { EndThreads(); }

  bool ThreadFunc(Histogram* histogram, size_t thread_idx) GRPC_OVERRIDE {
    auto* stub = channels_[thread_idx % channels_.size()].get_stub();
    double start = Timer::Now();
    grpc::ClientContext context;
    grpc::Status s =
        stub->UnaryCall(&context, request_, &responses_[thread_idx]);
    histogram->Add((Timer::Now() - start) * 1e9);
    return s.IsOk();
  }
};

class SynchronousStreamingClient GRPC_FINAL : public SynchronousClient {
 public:
  SynchronousStreamingClient(const ClientConfig& config)
      : SynchronousClient(config),
        context_(num_threads_),
        stream_(num_threads_) {
    for (size_t thread_idx = 0; thread_idx < num_threads_; thread_idx++) {
      auto* stub = channels_[thread_idx % channels_.size()].get_stub();
      stream_[thread_idx] = stub->StreamingCall(&context_[thread_idx]);
    }
    StartThreads(num_threads_);
  }
  ~SynchronousStreamingClient() {
    EndThreads();
    for (auto stream = stream_.begin(); stream != stream_.end(); stream++) {
      if (*stream) {
        (*stream)->WritesDone();
        EXPECT_TRUE((*stream)->Finish().IsOk());
      }
    }
  }

  bool ThreadFunc(Histogram* histogram, size_t thread_idx) GRPC_OVERRIDE {
    double start = Timer::Now();
    if (stream_[thread_idx]->Write(request_) &&
        stream_[thread_idx]->Read(&responses_[thread_idx])) {
      histogram->Add((Timer::Now() - start) * 1e9);
      return true;
    }
    return false;
  }

 private:
  std::vector<grpc::ClientContext> context_;
  std::vector<std::unique_ptr<
      grpc::ClientReaderWriter<SimpleRequest, SimpleResponse>>> stream_;
};

std::unique_ptr<Client> CreateSynchronousUnaryClient(
    const ClientConfig& config) {
  return std::unique_ptr<Client>(new SynchronousUnaryClient(config));
}
std::unique_ptr<Client> CreateSynchronousStreamingClient(
    const ClientConfig& config) {
  return std::unique_ptr<Client>(new SynchronousStreamingClient(config));
}

}  // namespace testing
}  // namespace grpc


text:
package org.apache.usergrid.batch;

import java.util.UUID;

import org.apache.usergrid.batch.repository.JobDescriptor;
import org.apache.usergrid.batch.service.JobRuntimeService;
import org.apache.usergrid.persistence.entities.JobData;
import org.apache.usergrid.persistence.entities.JobStat;

import com.google.common.base.Preconditions;

/**
 * Models the execution context of the {@link Job} with state transition methods for job status.
 *
 * @author zznate
 * @author tnine
 */
public class JobExecutionImpl implements JobExecution, JobRuntime {

    private final UUID jobId;
    private final UUID runId;
    private final String jobName;
    private long duration;
    private Status status = Status.NOT_STARTED;
    private long startTime;
    private JobRuntimeService runtime;
    private UUID transactionId;
    private JobData data;
    private JobStat stats;
    private long delay = -1;

    public JobExecutionImpl( JobDescriptor jobDescriptor ) {
        this.runId = UUID.randomUUID();
        this.jobId = jobDescriptor.getJobId();
        this.runtime = jobDescriptor.getRuntime();
        this.jobName = jobDescriptor.getJobName();
        this.transactionId = jobDescriptor.getTransactionId();
        this.data = jobDescriptor.getData();
        this.stats = jobDescriptor.getStats();
    }

    public UUID getRunId() {
        return runId;
    }

    public long getDuration() {
        return duration;
    }

    /** @param transactionId the transactionId to set */
    public void setTransactionId( UUID transactionId ) {
        this.transactionId = transactionId;
    }

    public UUID getJobId() {
        return jobId;
    }

    /** @return the data */
    public JobData getJobData() {
        return data;
    }

    /*
     * (non-Javadoc)
     *
     * @see org.apache.usergrid.batch.JobExecution#getJobStats()
     */
    @Override
    public JobStat getJobStats() {
        return stats;
    }

    public void start( int maxFailures ) {
        Preconditions.checkState( this.status.equals( Status.NOT_STARTED ) || this.status.equals( Status.FAILED ),
                "Attempted to start job in progress" );
        this.status = Status.IN_PROGRESS;

        stats.incrementRuns();

        // use >= in case the threshold lowers after the job has passed the failure
        // mark
        if ( maxFailures != FOREVER && stats.getTotalAttempts() > maxFailures ) {
            status = Status.DEAD;
        }

        startTime = System.currentTimeMillis();
        stats.setStartTime( startTime );
    }

    public void completed() {
        updateState( Status.IN_PROGRESS, "Attempted to complete job not in progress", Status.COMPLETED );
        stats.setDuration( duration );
    }

    /**
     * Mark this execution as failed. Also pass the maximum number of possible failures. Set to JobExecution.FOREVER for
     * no limit
     */
    public void failed() {
        updateState( Status.IN_PROGRESS, "Attempted to fail job not in progress", Status.FAILED );
    }

    /** This job should be killed and not retried */
    public void killed() {
        updateState( Status.IN_PROGRESS, "Attempted to fail job not in progress", Status.DEAD );
    }

    /*
     * (non-Javadoc)
     *
     * @see org.apache.usergrid.batch.JobExecution#delay(long)
     */
    @Override
    public void delay( long delay ) {
        updateState( Status.IN_PROGRESS, "Attempted to delay a job not in progress", Status.DELAYED );
        stats.incrementDelays();
        this.delay = delay;
        runtime.delay( this );
    }

    /** Update our state */
    private void updateState( Status expected, String message, Status newStatus ) {
        Preconditions.checkState( this.status.equals( expected ), message );
        this.status = newStatus;
        duration = System.currentTimeMillis() - startTime;
    }

    /** Make sure we're in progress and notifiy the scheduler we're still running */
    public void heartbeat() {
        Preconditions
                .checkState( this.status.equals( Status.IN_PROGRESS ), "Attempted to heartbeat job not in progress" );
        runtime.heartbeat( this );
    }

    /* (non-Javadoc)
     * @see org.apache.usergrid.batch.JobExecution#heartbeat(long)
     */
    @Override
    public void heartbeat( long milliseconds ) {
        Preconditions
                .checkState( this.status.equals( Status.IN_PROGRESS ), "Attempted to heartbeat job not in progress" );
        runtime.heartbeat( this, milliseconds );
        this.delay = milliseconds;
    }

    /** @return the startTime */
    public long getStartTime() {
        return startTime;
    }

    /** @return the transactionId */
    public UUID getTransactionId() {
        return transactionId;
    }

    public Status getStatus() {
        return this.status;
    }

    /** @return the delay */
    public long getDelay() {
        return delay;
    }

    /** @return the jobName */
    public String getJobName() {
        return jobName;
    }

    /* (non-Javadoc)
     * @see org.apache.usergrid.batch.JobRuntime#getExecution()
     */
    @Override
    public JobExecution getExecution() {
        return this;
    }
}


text:
require('../configfile').watch_files = false;
var vm_harness = require('./fixtures/vm_harness');

vm_harness.add_tests(__dirname + '/../smtp_client.js',
    __dirname + '/smtp_client/', exports);

var smtp_client = require('../smtp_client');
var path         = require('path');
var fixtures     = require('haraka-test-fixtures');

exports.testUpgradeIsCalledOnSTARTTLS = function (test) {
    test.expect(1);

    var plugin = new fixtures.plugin('queue/smtp_forward');
    // switch config directory to 'tests/config'
    plugin.config = plugin.config.module_config(path.resolve('tests'));

    plugin.net_utils.config =
        plugin.net_utils.config.module_config(path.resolve('tests'));

    plugin.register();

    var cmds = {};
    var upgradeArgs = {};

    var socket = {
        setTimeout: function (arg) {  },
        setKeepAlive: function (arg) {  },
        on: function (eventName, callback) {
            cmds[eventName] = callback;
        },
        upgrade: function (arg) {
            upgradeArgs = arg;
        }
    };

    var client = new smtp_client.smtp_client(25, 'localhost', 30, 30, socket);
    client.load_tls_config(plugin.tls_options);

    client.command = 'starttls';
    cmds.line('250 Hello client.example.com\r\n');

    var StringDecoder = require('string_decoder').StringDecoder;
    var decoder = new StringDecoder('utf8');

    var cent = Buffer.from(upgradeArgs.key);
    test.equal(decoder.write(cent), 'OutboundTlsKeyLoaded');

    test.done();
}

exports.startTLS = function (test) {
    test.expect(1);

    var cmd = '';

    var socket = {
        setTimeout: function (arg) {  },
        setKeepAlive: function (arg) {  },
        on: function (eventName, callback) {  },
        upgrade: function (arg) {  },
        write: function (arg) { cmd = arg; }
    };

    var client = new smtp_client.smtp_client(25, 'localhost', 30, 30, socket);
    client.tls_options = {};

    client.secured = false;
    client.response = [ 'STARTTLS' ]

    smtp_client.onCapabilitiesOutbound(client, false, undefined, { 'enable_tls': true });

    test.equal(cmd, 'STARTTLS\r\n');
    test.done();
}


text:
package wikiinfo;

import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "points")
public class PointEntry {

	@Id
    private final String _id;

    @NotEmpty
    private final String title;
    private final String url;

    @NotEmpty
    private final String source;

    @NotEmpty
    @Indexed
    public String loc;

    public PointEntry(String _id, String title, String url, String source, String loc) {
    	this._id = _id;
        this.title = title;
        this.url = url;
        this.source = source;
        this.loc = loc;
    }

    public String getId() {
        return _id;
    }

    public String getTitle() {
        return title;
    }

    public String getUrl() {
        return url;
    }

    public String getSource() {
        return source;
    }

    public String getLoc() {
        return loc;
    }

}


text:
package universe.constellation.orion.viewer.device;

import android.content.Context;
import android.graphics.Point;
import android.os.PowerManager;
import android.view.Display;
import android.view.KeyEvent;
import universe.constellation.orion.viewer.*;
import universe.constellation.orion.viewer.prefs.GlobalOptions;

/**
 * User: mike
 * Date: 17.12.11
 * Time: 17:02
 */
public class AndroidDevice implements Device {

    private PowerManager.WakeLock screenLock;

    protected OrionBaseActivity activity;

    private int delay = DELAY;

    public GlobalOptions options;

    public GlobalOptions keyBinding;

    private final int wakeLockType;

    public AndroidDevice() {
        this(PowerManager.SCREEN_BRIGHT_WAKE_LOCK);
    }

    public AndroidDevice(int wakeLockType) {
        this.wakeLockType = wakeLockType;
    }

    public void updateTitle(String title) {

    }

    public void updatePageNumber(int current, int max) {

    }

    public boolean onKeyUp(int keyCode, KeyEvent event, OperationHolder holder) {
        //check mapped keys
        if (Info.SONY_PRS_T1_T2) {
            if (keyCode == 0) {
                 switch (event.getScanCode()) {
                    case 105:
                        holder.value = PREV;
                        return true;
                    case 106:
                        holder.value = NEXT;
                        return true;
                    }
            }

        }

        switch (keyCode) {
            case KeyEvent.KEYCODE_SOFT_LEFT:
            case KeyEvent.KEYCODE_DPAD_LEFT:
            case KeyEvent.KEYCODE_DPAD_UP:
            case KeyEvent.KEYCODE_PAGE_UP:
            case KeyEvent.KEYCODE_VOLUME_UP:
                holder.value = PREV;
                return true;
            case KeyEvent.KEYCODE_SOFT_RIGHT:
            case KeyEvent.KEYCODE_DPAD_RIGHT:
            case KeyEvent.KEYCODE_DPAD_DOWN:
            case KeyEvent.KEYCODE_PAGE_DOWN:
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                holder.value = NEXT;
                return true;
        }
        return false;
    }

    public void onCreate(OrionBaseActivity activity) {
        options = activity.getOrionContext().getOptions();
        keyBinding = activity.getOrionContext().getKeyBinding();

        if (activity.getViewerType() == VIEWER_ACTIVITY) {
            delay = activity.getOrionContext().getOptions().getScreenBacklightTimeout(VIEWER_DELAY) * 1000 * 60;
        }
        this.activity = activity;
        PowerManager power = (PowerManager) activity.getSystemService(Context.POWER_SERVICE);
        screenLock = power.newWakeLock(wakeLockType, "OrionViewer" + hashCode());
        screenLock.setReferenceCounted(false);
    }

    public void onDestroy() {

    }

    public void onPause() {
        if (screenLock != null) {
            screenLock.release();
        }
    }

    public void onWindowGainFocus() {
        if (screenLock != null) {
            screenLock.acquire(delay);
        }
    }

    public void onUserInteraction() {
        if (screenLock != null) {
            screenLock.acquire(delay);
        }
    }

    public void flushBitmap() {
        if (activity.getView() != null) {
            activity.getView().invalidate();
        }
    }

    public int getLayoutId() {
        return R.layout.android_main;
    }

    public String getDefaultDirectory() {
        return "";
    }

    public int getFileManagerLayoutId() {
        return R.layout.android_file_manager;
    }

    public void onSetContentView() {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public Point getDeviceSize() {
        Display display = activity.getWindowManager().getDefaultDisplay();
        return new Point(display.getWidth(), display.getHeight());

    }

    @Override
    public boolean isDefaultDarkTheme() {
        return true;
    }

    @Override
    public void onNewBook(LastPageInfo info, DocumentWrapper document) {

    }

    @Override
    public void onBookClose(LastPageInfo info) {

    }
}