text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See License.txt in the project root.

package com.microsoft.alm.plugin.context;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
import com.microsoft.alm.plugin.authentication.AuthHelper;
import com.microsoft.alm.plugin.authentication.AuthenticationInfo;
import com.microsoft.alm.plugin.services.HttpProxyService;
import com.microsoft.alm.plugin.services.PluginServiceProvider;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.VersionInfo;
import org.glassfish.jersey.apache.connector.ApacheClientProperties;
import org.glassfish.jersey.apache.connector.ApacheConnectorProvider;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.ClientProperties;
import org.glassfish.jersey.client.RequestEntityProcessing;
import org.glassfish.jersey.client.spi.ConnectorProvider;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.core.HttpHeaders;
import java.io.IOException;

/**
 * JAXRS Rest Client helper
 */
public class RestClientHelper {

    private static Client createNewClient(ClientConfig clientConfig) {
        return ClientBuilder.newBuilder()
                .withConfig(clientConfig)
                .sslContext(PluginServiceProvider.getInstance().getCertificateService().getSSLContext())
                .build();
    }

    public static Client getClient(final String serverUri, final String accessTokenValue) {
        final Credentials credentials = new UsernamePasswordCredentials("accessToken", accessTokenValue);
        final ClientConfig clientConfig = getClientConfig(ServerContext.Type.VSO_DEPLOYMENT, credentials, serverUri,
                PluginServiceProvider.getInstance().getHttpProxyService().useHttpProxy());

        return createNewClient(clientConfig);
    }

    public static Client getClient(final ServerContext.Type type, final AuthenticationInfo authenticationInfo) {
        final ClientConfig clientConfig = getClientConfig(type, authenticationInfo,
                PluginServiceProvider.getInstance().getHttpProxyService().useHttpProxy());
        return createNewClient(clientConfig);
    }

    public static ClientConfig getClientConfig(final ServerContext.Type type,
                                               final Credentials credentials,
                                               final String serverUri,
                                               final boolean includeProxySettings) {

        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, credentials);

        final ConnectorProvider connectorProvider = new ApacheConnectorProvider();
        // custom json provider ignores new fields that aren't recognized
        final JacksonJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider()
                .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        final ClientConfig clientConfig = new ClientConfig(jacksonJsonProvider).connectorProvider(connectorProvider);
        clientConfig.property(ApacheClientProperties.CREDENTIALS_PROVIDER, credentialsProvider);
        clientConfig.property(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.BUFFERED);

        // For TFS OnPrem we only support NTLM authentication right now. Since 2016 servers support Basic as well,
        // we need to let the server and client negotiate the protocol instead of preemptively assuming Basic.
        // TODO: This prevents PATs from being used OnPrem. We need to fix this soon to support PATs onPrem.
        clientConfig.property(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION, type != ServerContext.Type.TFS);

        //Define a local HTTP proxy
        if (includeProxySettings) {
            final HttpProxyService proxyService = PluginServiceProvider.getInstance().getHttpProxyService();
            final String proxyUrl = proxyService.getProxyURL();
            clientConfig.property(ClientProperties.PROXY_URI, proxyUrl);
            if (proxyService.isAuthenticationRequired()) {
                // To work with authenticated proxies and TFS, we provide the proxy credentials if they are registered
                final AuthScope ntlmAuthScope =
                        new AuthScope(proxyService.getProxyHost(), proxyService.getProxyPort(),
                                AuthScope.ANY_REALM, AuthScope.ANY_SCHEME);
                credentialsProvider.setCredentials(ntlmAuthScope,
                        new UsernamePasswordCredentials(proxyService.getUserName(), proxyService.getPassword()));
            }
        }

        // register a filter to set the User Agent header
        clientConfig.register(new ClientRequestFilter() {
            @Override
            public void filter(final ClientRequestContext requestContext) throws IOException {
                // The default user agent is something like "Jersey/2.6"
                final String userAgent = VersionInfo.getUserAgent("Apache-HttpClient", "org.apache.http.client", HttpClientBuilder.class);
                // Finally, we can add the header
                requestContext.getHeaders().add(HttpHeaders.USER_AGENT, userAgent);
            }
        });

        return clientConfig;
    }

    public static ClientConfig getClientConfig(final ServerContext.Type type,
                                               final AuthenticationInfo authenticationInfo,
                                               final boolean includeProxySettings) {
        final Credentials credentials = AuthHelper.getCredentials(type, authenticationInfo);

        return getClientConfig(type, credentials, authenticationInfo.getServerUri(), includeProxySettings);
    }
}


text:
package ast;

public class Minus extends Unary{
	public Minus (Exp factor){
		super(factor);
	}
}

redpajama_set_name: RedPajamaGithub


text:
import { version } from '../../package.json';
import { Router } from 'express';

export default (config, db) => {
	let api = Router();

	// perhaps expose some API metadata at the root
	api.get('/', (req, res) => {
		res.json({ version });
	});

	var endpoint = config.endpoint;
	if (config.method == 'GET') {
		console.log(`[bombay.js] Configuring GET endpoint at ${config.url}`);
		api.get('/' + config.url, makeFunction(endpoint.getBody.bind(endpoint)));
	} else if (config.method == 'POST') {
		console.log(`[bombay.js] Configuring POST endpoint at ${config.url}`);
		api.post('/' + config.url, makeFunction(endpoint.getBody.bind(endpoint)));
	}
	return api;
}

function makeFunction(endpointbody) {
	var fn = function (req, res) {
		endpointbody(req, res);
	};
	return fn;
}


text:
package org.apache.geode.codeAnalysis.decode.cp;

import java.io.DataInputStream;
import java.io.IOException;

import org.apache.geode.codeAnalysis.decode.CompiledClass;

public class CpMethodType extends Cp {
  int descriptor_index;

  CpMethodType(DataInputStream source) throws IOException {
    descriptor_index = source.readUnsignedShort();
  }

  public String returnType(CompiledClass info) {
    return "not yet implemented";
  }
}


text:
package ru.shestakov.models;

/**
 * Init Task class
 */
public class Task extends Item {

    /**
     * Initializes a newly created Task
     */
    public Task() {

    }

    /**
     * Initializes a newly created Task with params
     * @param name
     * @param desc
     * @param create
     */
    public Task(String name, String desc, long create) {
        this.name = name;
        this.description = desc;
        this.create = create;
    }

    /**
     * Some kind of method
     * @return
     */
    public String calculatePrice() {
        return "100%";
    }

}


text:
using System;
using System.Linq;

class LargerThanNeighbours
{
   static void Main()
   {
      //input
      int size = int.Parse(Console.ReadLine());
      int[] numbers = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
      //logic
      int counter = 0;
      for (int i = 1; i < size-1; i++)
      {
         if (HigherThanNeighbours(numbers,i))
         {
            counter++;
         }
      }
      //output
      Console.WriteLine(counter);
   }
   public static bool HigherThanNeighbours(int[] array, int index)
   {
      if (array[index]>array[index-1] && array[index]>array[index+1])
      {
         return true;
      }
      else
      {
         return false;
      }
   }
}


text:
import template from "./dynamic-section.html";
import {initialiseData} from "../../../common/index";
import {kindToViewState} from "../../../common/link-utils";
import {CORE_API} from "../../../common/services/core-api-utils";

const bindings = {
    parentEntityRef: "<",
    section: "<",
    onRemove: "<",
};

const initialState = {
    embedded: false,
    backLink: {
        state: "",
        params: {}
    },
    help: null
};

function controller($state, serviceBroker) {
    const vm = initialiseData(this, initialState);
    vm.embedded = _.startsWith($state.current.name, "embed");

    vm.$onChanges = () => {
        if (vm.parentEntityRef !== null) {
            vm.backLink = {
                state: kindToViewState(vm.parentEntityRef.kind),
                params: { id: vm.parentEntityRef.id },
            };
            serviceBroker
                .loadAppData(CORE_API.StaticPanelStore.findAll)
                .then(r => {
                    const byId = _.keyBy(r.data, d => d.group);
                    const exact = `SECTION.HELP.${vm.section.componentId}.${vm.parentEntityRef.kind}`;
                    const vague = `SECTION.HELP.${vm.section.componentId}`;
                    const panel = byId[exact] || byId[vague] ;
                    if (panel) {
                        vm.help = panel.content;
                    }
                });
        }
    };

}

controller.$inject = [
    "$state",
    "ServiceBroker"
];

const component = {
    controller,
    template,
    bindings,
    transclude: true
};

const id = "waltzDynamicSection";

export default {
    id,
    component
};


text:
RecycleBin.Options
==================

This is a .NET Framework library providing a method dynamic typing of command-line arguments.

Examples
--------

Suppose you want to construct an instance of OptionArgument below from command-line arguments like
"program.exe -seed=12345"

```csharp
public class OptionArgument
{
   public int RandomSeed { get; set; }
}
```

You just need to add OptionAttribute onto the property.

```csharp
public class OptionArgument
{
   [Option("seed")]
   public int RandomSeed { get; set; }
}
```

And you can retreive the RandomSeed with the following code.

```csharp
var parser = new CommandLineParser('-', '=');
var argument = parser.Parse<OptionArgument>();
int seed = argument.Option.RandomSeed;
```

For flag option (requires Boolean value), you can use OptionFlagAttribute.

```csharp
public class OptionArgument
{
   [OptionFlag("?")]
   [OptionFlag("h")]
   [OptionFlag("help")]
   public bool ShowHelp { get; set; }
}
```

OptionFlagAttribute can take an argument only when the argument is combined by a separator in such form like "/help:true"; besides, it allows input with suffix of "+" (for true) or "-" (for false) like "/help+" or "/help-".


text:
layout: post
title: Learning HTML from the perspective of a designer
header: My journey from illustrator to HTML
category: Interview
author: yasmin
---

This blog will document the journey of a totally code-naive designer(me) as I attempt to learn to
code. My attempts will no doubt be laughable to any one who has any experience in the digital
realm.

## Code 101: Learning the basics ###

To give a brief overview of myself; I recently completed my Bachelor of Design Innovation (what
does that even mean??) at Victoria University of Wellington, New Zealand. I majored in Industrial
Design which was mostly product design & manufacture based. My final university project ever
involved doing some branding & identity and designing an app, and it was then that I finally was like
'damn, this is fun! I want to do more of this type of thing.' Since then I have been working with
various small-scale business helping them with their branding, UI and UX design. Very quickly I
found out that it was not enough for me to just to pretty photoshop layouts, I actually had to learn to
code them. So here it goes..

Where to begin

A developer friend had mentioned Codecademy to me so I thought I'd jump on that. First (of
many) surprises; there was more than one type of code to learn, in fact on the main page there are
six and all of them are described as the 'most popular' or 'building blocks of web development' or
'powerful yet beginner-friendly' or 'learn the fundamentals' aka they are ALL the easiest, most
important, best language for a beginner to learn. Instead of taking a lucky dip I went back to
aforementioned friend and asked for their advice. Important note: what I want to achieve by
learning to code is to be able to code my own websites and apps on a basic level so I can
demonstrate what I want to a client or show it to a kickass developer who could understand it
enough to then turn it into a super fast, fully functional product. And so it was decided I would start
with HTML.

![Headings & Paragraphs](/img/blog/yasmin-post-1/first.png)

Color not Colour

First tutorials were pretty easy to follow, I learnt how to make words link to different webpages,
insert images and make images link to webpages. This was a pretty big thing for me cause I
thought it would take me a couple of weeks of practice but actually it only took about 45min of
Codecademy tutorials. One thing that did annoy my designer side was that what I was making was
super ugly; the font style/size/colour etc but I do realise this is what CSS is for. Also I got really
frustrated when one tutorial would not let me advance because I had made an error and I redid it
about ten times to no avail, eventually someone pointed out to me that I had spelt 'colour' wrong,
because HTML is written in American English.

![Working with Pictures](/img/blog/yasmin-post-1/second.png)

After making my own shitty 90's style webpage about myself with clickable images and links, and
proudly showing it to my flatmates I moved on to the List Making tutorials which were not as
interesting because I don't want to make lists, but perhaps that is is actually something developers
frequently use? I'm unsure because I started listing things on my mind, the numero uno thing was
food and so I got hungry and stopped my tutorials.

![Lists](/img/blog/yasmin-post-1/third.png)

Final thoughts

Overall, much easier to understand than I had thought big ups to Codecademy for making such
great (and FREE) lessons that can make novices feel like pros. Next step, making my site live in
60 seconds with CloudCannon!


text:
speaker: lex
title: "Ethics, Reviewing and Discussion Culture at VIS"
# paper | invited | keynote | tutorial | panel
type: panel
slides-key:
slides-pdf:
slides-ppt:
# Anything you want to say about this talk
note:
date: 2022-10-21

held:
 - "[Panel: Is This (Panel) Good Enough for IEEE VIS?](https://sites.google.com/view/goodenoughforvis/home), IEEE VIS, 2022-10-21."

---


text:
<?php

namespace BSUIR\AdminBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class BSUIRAdminBundle extends Bundle
{
}


text:
<?php

namespace Model;

/**
 * Model\TextTextElement document.
 */
class TextTextElement extends \Model\Base\TextTextElement
{
    protected function textTextElementPreInsert()
    {
        $this->events[] = 'TextTextElementPreInsert';
    }
}


text:
import pycurl
import cStringIO as StringIO
from urllib import urlencode

import time
import datetime

class BrowserError(Exception):
    def __init__(self, inner_exception):
        self.inner_exception = inner_exception
    def __str__(self):
        return "<Browser `%s'>" % self.inner_exception

class Browser:
    def __init__(self, userAgent, ratelimit=datetime.timedelta(seconds=1)):
        self.userAgent = userAgent
        self.cookies = dict()
        self.sslVersion = pycurl.SSLVERSION_TLSv1  # SSLv23 / SSLv3
	self.ratelimit = ratelimit
	self.lastRequest = datetime.datetime.now() - ratelimit

    ''' Parse string with headers to a list of key-value-pairs. '''
    def parseHeaders(self, headerStr):
        headers = []

        for line in headerStr.split('\r\n'):
            elements = line.split(": ")

            if len(elements) != 2 or elements[0] == "":
                continue

            headers.append((elements[0], elements[1]))
        return headers

    ''' Parses headers and sets cookies if applicable; return headers. '''
    def processHeaders(self, headerStr):
        headers = self.parseHeaders(headerStr)

        for key, value in headers:
            if key == "Set-Cookie":
                cookie = value.split(";")[0]
                cookieKey, cookieValue = cookie.split("=")
                self.cookies[cookieKey] = cookieValue

        return headers

    def wait_ratelimit(self):
        diff = datetime.datetime.now() - self.lastRequest
	if(diff < self.ratelimit):
            time.sleep((self.ratelimit - diff).total_seconds())

    ''' Open a url with the current browser setup;
        setting postVars will make it a POST request. '''
    def open_url(self, url, postVars=None):
	self.wait_ratelimit()

        try:
            headers = []
            headers.append("User-Agent: %s" % self.userAgent)

            for key, value in self.cookies.items():
                headers.append("Cookie: %s" % "; ".join(["%s=%s" % (key, value) for (key, value) in self.cookies.items()]))

            c = pycurl.Curl()
            c.setopt(pycurl.FAILONERROR, True)
            c.setopt(pycurl.URL, url)
            c.setopt(pycurl.HTTPHEADER, headers)

            bodyBuffer = StringIO.StringIO()
            headerBuffer = StringIO.StringIO()

            c.setopt(pycurl.WRITEFUNCTION, bodyBuffer.write)
            c.setopt(pycurl.HEADERFUNCTION, headerBuffer.write)

            c.setopt(pycurl.FOLLOWLOCATION, 1)
            c.setopt(pycurl.MAXREDIRS, 5)
            c.setopt(pycurl.SSLVERSION, self.sslVersion)
            c.setopt(pycurl.SSL_VERIFYPEER, 1)
            # Verify that domain in URL matches to the Common Name Field or
            # a Subject Alternate Name field in the certificate.
            # (0 will not check it; 1 is an invalid value)
            c.setopt(pycurl.SSL_VERIFYHOST, 2)

            # c.setopt(pycurl.PROXY, "localhost")
            # c.setopt(pycurl.PROXYPORT, 23456)
            # c.setopt(pycurl.PROXYTYPE, pycurl.PROXYTYPE_SOCKS5)

            if postVars is not None:
                c.setopt(pycurl.POSTFIELDS, urlencode(postVars))

            c.perform()
	    self.lastRequest = datetime.datetime.now()

            return bodyBuffer.getvalue(), self.processHeaders(headerBuffer.getvalue())
        except pycurl.error, e:
            raise BrowserError(e)


text:
/*
 * @(#)TableConfig.java
 *
 * @project    : org.fugerit.java.core.db
 * @package    : org.fugerit.java.core.db.backup
 * @creation   : 25/set/06
 * @license	   : META-INF/LICENSE.TXT
 */
package org.fugerit.java.core.db.backup;

/**
 *

 *
 * @author mfranci
 *
 */
public class TableConfig {

	private String table;

	private String select;

	private String meta;

	private BackupAdaptor adaptorFrom;

	private BackupAdaptor adaptorTo;

	/**
	 * @return the select
	 */
	public String getSelect() {
		return select;
	}

	/**
	 * @param select the select to set
	 */
	public void setSelect(String select) {
		this.select = select;
	}

	/**
	 * @return the table
	 */
	public String getTable() {
		return table;
	}

	/**
	 * @param table the table to set
	 */
	public void setTable(String table) {
		this.table = table;
	}

	public String getMeta() {
		return meta;
	}

	public void setMeta(String meta) {
		this.meta = meta;
	}

	public BackupAdaptor getAdaptorFrom() {
		return adaptorFrom;
	}

	public void setAdaptorFrom(BackupAdaptor adaptorFrom) {
		this.adaptorFrom = adaptorFrom;
	}

	public BackupAdaptor getAdaptorTo() {
		return adaptorTo;
	}

	public void setAdaptorTo(BackupAdaptor adaptorTo) {
		this.adaptorTo = adaptorTo;
	}

}


text:
namespace BrowserAutomationStudioFramework
{
    ResourceModelScript::ResourceModelScript(QObject *parent) :
        ResourceModelAbstract(parent)
    {
        dont_give_up = false;
    }

    int ResourceModelScript::GetSuccessAttempts()
    {
        return success;
    }
    void ResourceModelScript::SetSuccessAttempts(int val)
    {
        success = val;
    }

    int ResourceModelScript::GetFailAttempts()
    {
        return fails;
    }
    void ResourceModelScript::SetFailAttempts(int val)
    {
        fails = val;
    }

    int ResourceModelScript::GetNumberSimultaneousUse()
    {
        return number_simultaneous_use;
    }
    void ResourceModelScript::SetNumberSimultaneousUse(int val)
    {
        number_simultaneous_use = val;
    }

    int ResourceModelScript::GetIntervalBetweenUsage()
    {
        return interval_between_usage;
    }
    void ResourceModelScript::SetIntervalBetweenUsage(int val)
    {
        interval_between_usage = val;
    }

    QString ResourceModelScript::GetTypeId()
    {
        return QString("LinesFromScript");
    }

    bool ResourceModelScript::GetGreedy()
    {
        return greedy;
    }

    void ResourceModelScript::SetGreedy(bool Greedy)
    {
        this->greedy = Greedy;
    }

    bool ResourceModelScript::GetDontGiveUp()
    {
        return dont_give_up;
    }

    void ResourceModelScript::SetDontGiveUp(bool dont_give_up)
    {
        this->dont_give_up = dont_give_up;
    }

}


text:
from __future__ import with_statement
import pytest

from aredis.utils import b
from aredis.exceptions import (WatchError,
                               ResponseError)

class TestPipeline:

    @pytest.mark.asyncio(forbid_global_loop=True)
    async def test_pipeline(self, r):
        await r.flushdb()
        async with await r.pipeline() as pipe:
            await pipe.set('a', 'a1')
            await pipe.get('a')
            await pipe.zadd('z', z1=1)
            await pipe.zadd('z', z2=4)
            await pipe.zincrby('z', 'z1')
            await pipe.zrange('z', 0, 5, withscores=True)
            assert await pipe.execute() == \
                [
                    True,
                    b('a1'),
                    1,
                    1,
                    2.0,
                    [(b('z1'), 2.0), (b('z2'), 4)],
                ]

    @pytest.mark.asyncio(forbid_global_loop=True)
    async def test_pipeline_length(self, r):
        await r.flushdb()
        async with await r.pipeline() as pipe:
            # Initially empty.
            assert len(pipe) == 0
            assert not pipe

            # Fill 'er up!
            await pipe.set('a', 'a1')
            await pipe.set('b', 'b1')
            await pipe.set('c', 'c1')
            assert len(pipe) == 3
            assert pipe

            # Execute calls reset(), so empty once again.
            await pipe.execute()
            assert len(pipe) == 0
            assert not pipe

    @pytest.mark.asyncio(forbid_global_loop=True)
    async def test_pipeline_no_transaction(self, r):
        await r.flushdb()
        async with await r.pipeline(transaction=False) as pipe:
            await pipe.set('a', 'a1')
            await pipe.set('b', 'b1')
            await pipe.set('c', 'c1')
            assert await pipe.execute() == [True, True, True]
            assert await r.get('a') == b('a1')
            assert await r.get('b') == b('b1')
            assert await r.get('c') == b('c1')

    @pytest.mark.asyncio(forbid_global_loop=True)
    async def test_pipeline_no_transaction_watch(self, r):
        await r.flushdb()
        await r.set('a', 0)

        async with await r.pipeline(transaction=False) as pipe:
            await pipe.watch('a')
            a = await pipe.get('a')

            pipe.multi()
            await pipe.set('a', int(a) + 1)
            assert await pipe.execute() == [True]

    @pytest.mark.asyncio(forbid_global_loop=True)
    async def test_pipeline_no_transaction_watch_failure(self, r):
        await r.flushdb()
        await r.set('a', 0)

        async with await r.pipeline(transaction=False) as pipe:
            await pipe.watch('a')
            a = await pipe.get('a')

            await r.set('a', 'bad')

            pipe.multi()
            await pipe.set('a', int(a) + 1)

            with pytest.raises(WatchError):
                await pipe.execute()

            assert await r.get('a') == b('bad')

    @pytest.mark.asyncio(forbid_global_loop=True)
    async def test_exec_error_in_response(self, r):
        """
        an invalid pipeline command at exec time adds the exception instance
        to the list of returned values
        """
        await r.flushdb()
        await r.set('c', 'a')
        async with await r.pipeline() as pipe:
            await pipe.set('a', 1)
            await pipe.set('b', 2)
            await pipe.lpush('c', 3)
            await pipe.set('d', 4)
            result = await pipe.execute(raise_on_error=False)

            assert result[0]
            assert await r.get('a') == b('1')
            assert result[1]
            assert await r.get('b') == b('2')

            # we can't lpush to a key that's a string value, so this should
            # be a ResponseError exception
            assert isinstance(result[2], ResponseError)
            assert await r.get('c') == b('a')

            # since this isn't a transaction, the other commands after the
            # error are still executed
            assert result[3]
            assert await r.get('d') == b('4')

            # make sure the pipe was restored to a working state
            await pipe.set('z', 'zzz')
            assert await pipe.execute() == [True]
            assert await r.get('z') == b('zzz')

    @pytest.mark.asyncio(forbid_global_loop=True)
    async def test_exec_error_raised(self, r):
        await r.flushdb()
        await r.set('c', 'a')
        async with await r.pipeline() as pipe:
            await pipe.set('a', 1)
            await pipe.set('b', 2)
            await pipe.lpush('c', 3)
            await pipe.set('d', 4)
            with pytest.raises(ResponseError) as ex:
                await pipe.execute()

            # make sure the pipe was restored to a working state
            await pipe.set('z', 'zzz')
            assert await pipe.execute() == [True]
            assert await r.get('z') == b('zzz')

    @pytest.mark.asyncio(forbid_global_loop=True)
    async def test_parse_error_raised(self, r):
        await r.flushdb()
        async with await r.pipeline() as pipe:
            # the zrem is invalid because we don't pass any keys to it
            await pipe.set('a', 1)
            await pipe.zrem('b')
            await pipe.set('b', 2)
            with pytest.raises(ResponseError) as ex:
                await pipe.execute()

            # make sure the pipe was restored to a working state
            await pipe.set('z', 'zzz')
            assert await pipe.execute() == [True]
            assert await r.get('z') == b('zzz')

    @pytest.mark.asyncio(forbid_global_loop=True)
    async def test_watch_succeed(self, r):
        await r.flushdb()
        await r.set('a', 1)
        await r.set('b', 2)

        async with await r.pipeline() as pipe:
            await pipe.watch('a', 'b')
            assert pipe.watching
            a_value = await pipe.get('a')
            b_value = await pipe.get('b')
            assert a_value == b('1')
            assert b_value == b('2')
            pipe.multi()

            await pipe.set('c', 3)
            assert await pipe.execute() == [True]
            assert not pipe.watching

    @pytest.mark.asyncio(forbid_global_loop=True)
    async def test_watch_failure(self, r):
        await r.flushdb()
        await r.set('a', 1)
        await r.set('b', 2)

        async with await r.pipeline() as pipe:
            await pipe.watch('a', 'b')
            await r.set('b', 3)
            pipe.multi()
            await pipe.get('a')
            with pytest.raises(WatchError):
                await pipe.execute()

            assert not pipe.watching

    @pytest.mark.asyncio(forbid_global_loop=True)
    async def test_unwatch(self, r):
        await r.flushdb()
        await r.set('a', 1)
        await r.set('b', 2)

        async with await r.pipeline() as pipe:
            await pipe.watch('a', 'b')
            await r.set('b', 3)
            await pipe.unwatch()
            assert not pipe.watching
            await pipe.get('a')
            assert await pipe.execute() == [b('1')]

    @pytest.mark.asyncio(forbid_global_loop=True)
    async def test_transaction_callable(self, r):
        await r.flushdb()
        await r.set('a', 1)
        await r.set('b', 2)
        has_run = []

        async def my_transaction(pipe):
            a_value = await pipe.get('a')
            assert a_value in (b('1'), b('2'))
            b_value = await pipe.get('b')
            assert b_value == b('2')

            # silly run-once code... incr's "a" so WatchError should be raised
            # forcing this all to run again. this should incr "a" once to "2"
            if not has_run:
                await r.incr('a')
                has_run.append('it has')

            pipe.multi()
            await pipe.set('c', int(a_value) + int(b_value))

        result = await r.transaction(my_transaction, 'a', 'b',
                                     watch_delay=0.01)
        assert result == [True]
        assert await r.get('c') == b('4')

    @pytest.mark.asyncio(forbid_global_loop=True)
    async def test_exec_error_in_no_transaction_pipeline(self, r):
        await r.flushdb()
        await r.set('a', 1)
        async with await r.pipeline(transaction=False) as pipe:
            await pipe.llen('a')
            await pipe.expire('a', 100)

            with pytest.raises(ResponseError) as ex:
                await pipe.execute()

        assert await r.get('a') == b('1')

    @pytest.mark.asyncio(forbid_global_loop=True)
    async def test_exec_error_in_no_transaction_pipeline_unicode_command(self, r):
        key = chr(11) + 'abcd' + chr(23)
        await r.set(key, 1)
        async with await r.pipeline(transaction=False) as pipe:
            await pipe.llen(key)
            await pipe.expire(key, 100)

            with pytest.raises(ResponseError) as ex:
                await pipe.execute()

        assert await r.get(key) == b('1')


text:
var hive = require('hive');
var view = hive.view;
var redirect = hive.redirect;
var User = hive.models.User;
var Session = hive.models.Session;
var Users = hive.queries.Users;

// ### hive.at(context)
// **context** A ```String``` preceded by a ```/``` followed by the location which all following routes will live under.

// This will set the context of all following routes to ```http://localhost:3000/user```.
hive.at('/user')

// ### hive.get(route, [_handler_])
// **context** A ```String``` preceded by a ```/``` followed by the location which the route will responde to. Route paths can include parameters such as ```/user/:id```.

// **handler** [_optional_] A handler can be a [model](model.example.html), a query, or a ```function```.

// * **model** If a handler is a model, _hive_ will create an instance of it, call ```model.fetch()``` and return its ```model.toJSON()``` as the result.
// * **query** If a handler is a query, _hive_ will create an instance of it, pass it the request body, route parameters, and querystring parameters to its ```myQuery.get('query')``` property.
// * **function** If a handler is a ```function```, _hive_ will call this function and pass the **request** and the **response** objects as first and second arguments. This function can _optionally_ return a **result**.
//   * **request** Is an express.js [req](http://expressjs.com/guide.html) object
//   * **response** Is an express.js [res](http://expressjs.com/guide.html) object
//	 * **result** Is either a ```model```, ```query```, ```view(name, model)```, or ```redirect(url)```.
.get('/all', Users)
.post('/new', User)

// Routes are implicitely bound to a view by their name. For example. ```hive.at('/user').get('/new')``` will look for the view ```new.haml``` in the folder ```/views/user/```.
.get('/new')
.get('/login')

// ### hive.post(route, [_handler_])
// **context** A ```String``` preceded by a ```/``` followed by the location which the route will responde to.

// **handler** [_optional_] A handler can be a [model](model.example.html), a query, or a ```function```.

// * **model** If a handler is a model, _hive_ will create an instance of it, call ```model.fetch()``` and return its ```model.toJSON()``` as the result.
// * **query** If a handler is a query, _hive_ will create an instance of it, pass it the request body, route parameters, and querystring parameters to its ```myQuery.get('query')``` property.
// * **function** If a handler is a ```function```, _hive_ will call this function and pass the **request** and the **response** objects as first and second arguments. This function can _optionally_ return a **result**.
//   * **request** Is an express.js [req](http://expressjs.com/guide.html) object
//   * **response** Is an express.js [res](http://expressjs.com/guide.html) object
//	 * **result** Is either a ```model```, ```query```, ```view(name, model)```, ```redirect(url)```, or custom ```object```.
.post('/login', function(req, res) {
	var model = new Session(req.body);
	var result = {
		model: model,
		redirect: '/dashboard',
		success: function() {
			res.cookie('auth', model.get('auth'), {httpOnly: true});
		}
	};
	return result;
})
// This route will respond to ```http://localhost:3000/register``` and redirect to ```/user/new```.
.at('/register')
.get('/', function () {
	return redirect('/user/new');
})
.at('/dashboard')
.get('/', function(req, res) {
	return view('user/dashboard.haml');
});


text:
const test = require('tape');
const formatter = require('./index.js');

test('Test First name with Last initial', (t) => {
	t.plan(5);

	t.equal(formatter.firstWithLastInitial('John', 'Smith'), 'John S', 'First with last initial');
	t.equal(formatter.firstWithLastInitial('Jim'), 'Jim', 'First only');
	t.equal(formatter.firstWithLastInitial('Jim', null), 'Jim', 'First only');
	t.equal(formatter.firstWithLastInitial(undefined, 'Jimburger'), 'Jimburger', 'Last only');
	t.equal(formatter.firstWithLastInitial(null, 'Jimburger'), 'Jimburger', 'Last only');
});


text:
The SDK currently supports Android only. Java support is coming soon.

### Installation

#### Library Project Installation
The LIFX SDK will be published as a JAR archive when it is released publicly, but until then you can still use the SDK by cloning the repository and importing it into your project as an Android Library Project.
Users should note that the library is currently in an early Beta stage, so the API itself could change in the future.

#### Eclipse Sub-Project Installation
1. Clone the SDK repository into a directory on your local machine.
2. Open Eclipse and choose to import a "existing android code"
3. Import the library project.
4. Open the project properties for your application, select android then add the library project.

### Quick Examples

Initializing the library:

Before using the Library functions, a connection must be established with the LIFX lights that are on the current network.
First a reference to local network is gathered, then a connection is requested.
```java
LFXNetworkContext localNetworkContext = LFXClient.getSharedInstance( this).getLocalNetworkContext();
localNetworkContext.connect();
```

Turn off all lights:
```java
LFXNetworkContext localNetworkContext = LFXClient.getSharedInstance( this).getLocalNetworkContext();
localNetworkContext.getAllLightsCollection().setPowerState( LFXPowerState.OFF);
```

Turn on the light named "Hallway":
```java
LFXNetworkContext localNetworkContext = LFXClient.getSharedInstance( this).getLocalNetworkContext();
LFXLight hallway = localNetworkContext.getAllLightsCollection().getFirstLightForLabel( "Hallway");
hallway.setPowerState( LFXPowerState.ON);
```

Turn on all lights that are tagged "Kitchen":
```java
LFXNetworkContext localNetworkContext = LFXClient.getSharedInstance( this).getLocalNetworkContext();
LFXTaggedLightCollection kitchen = localNetworkContext.getTaggedLightCollectionForTag( "Kitchen");
kitchen.setPowerState( LFXPowerState.ON);
```

Set every light to a random color:
```java
LFXNetworkContext localNetworkContext = LFXClient.getSharedInstance( this).getLocalNetworkContext();

for( LFXLight aLight : localNetworkContext.getAllLightsCollection().getLights())
{
	LFXHSBKColor color = LFXHSBKColor.getColor( (float)(Math.random() * 360), 1.0f, 1.0f, 3500);
	aLight.setColor( color);
}
```

Disconnect:

When the application is finished with the LIFX bulbs, you will need to signal the Library to end it's connections.
```java
LFXNetworkContext localNetworkContext = LFXClient.getSharedInstance( this).getLocalNetworkContext();
localNetworkContext.disconnect();
```

---------------

## Quick overview of LIFX SDK terminology

### Network Context

A Network Context (`LFXNetworkContext`) denotes a context within which you will be accessing LIFX devices. The SDK currently only has support for a "Local Network Context", which refers to devices accessible on your LAN. We plan on adding Network Contexts for accessing LIFX devices via the upcoming cloud service.

### Lights, Light Collections and Addressing

The underlying LIFX system has three types of internal address: device, tag and broadcast. Device addressing will target an individual device, tag addressing will target all devices that have a particular tag, and broadcast addressing addressing will target all devices. Due to the way the underlying LIFX Binary Protocol works, you'll see much faster responses by targetting a tag (using a Tagged Light Collection) rather than targetting every device within that tag individually. The same goes for targetting all lights - if you want to change the state on all lights, you'll see much faster performance targetting `LFXNetworkContext.getAllLightsCollection()` instead of targetting each device individually.

### Lights

A `LFXLight` object represents an individual LIFX Light, and there will be only one `LFXLight` corresponding to each device per Network Context.

### Light Collections

Light Collections (`LFXLightCollection`) are classes that encapsulate a group of LIFX lights. They can have their light state manipulated in the same way that an individual light can. You can access the lights within a Light Collection through the `.getLights()` method.

### The All Lights Collection

Each `LFXNetworkContext` has an `.getAllLightCollections()` method, which is how you get the list of lights. If you want to manipulate every light in the same way (e.g. to turn every light off), you should use the All Lights Collection property directly, instead of targetting each device individually.

### Tagged Light Collections

A Tagged Light Collection (`LFXTaggedLightCollection`) represents the lights contained within a particular tag. If you want to manipulate every device within a tag, you should always use the Tagged Light Collection instead of dealing with each Light individually. Tagged Light Collections are unique within a Network Context.

### HSBK Color

LIFX makes use of a "HSBK" color representation. The "HSB" part refers to the [HSB](http://en.wikipedia.org/wiki/HSB_color_space) color space, and the "K" part refers to the [Color Temperature](http://en.wikipedia.org/wiki/Color_temperature) of the white point, in Kelvin. At full saturation, HSBK colors will correspond to the edge of the realisable color gamut, and at zero saturation, HSBK colors will correspond to the color described by the Color Temperature in the K component.


text:
<?php

require_once 'Modules/Commands/Command.php';

use Nuwani \ Bot;
use Nuwani \ SecurityManager;

class Commands extends ModuleBase implements ArrayAccess, Countable, IteratorAggregate
{
        /**
         * This property contains an array with all commands which have been registered with
         * this bot. Various information will be included as well.
         */

        private $m_aCommands;

        /**
         * A single character which defines the prefix of all commands that will be used. Do
         * NOT use multiple characters in here, seeing everything will totally break.
         */

        private $m_sPrefix;

        /**
         * A boolean which indicates whether all commands should be handled with case
         * sensitivity. If true, then !hello and !Hello are considered different commands.
         */

        private $m_bCaseSensitive;

        /**
         * In the constructor of this function we'll attempt to load the data file associated
         * with this module, containing all its current commands.
         */

        public function __construct ()
        {
                $this -> m_aCommands            = array ();
                $this -> m_sPrefix              = '!';
                $this -> m_bCaseSensitive       = true;

                /** Make the module somewhat useful by introducing some basic commands. **/
                $this -> registerInternalCommands ();

                /** Load up the user's commands. **/
                if (file_exists ('Data/Commands.dat'))
                {
                        $aInformation = unserialize (file_get_contents ('Data/Commands.dat'));

                        foreach ($aInformation [0] as $sName => $pCommand)
                        {
                                if ($pCommand instanceof Command)
                                {
                                        $pCommand ['Save'] = true;

                                        $sName = $this -> getCommandName ($sName);
                                        $this -> m_aCommands [$sName] = $pCommand;
                                }
                        }

                        $this -> m_sPrefix = $aInformation [1];
                        if (isset ($aInformation [2]))
                        {
                                $this -> m_bCaseSensitive = $aInformation [2];
                        }
                }

                /** Save any changes or create the file if it doesn't exist. **/
                $this -> save ();
        }

        /**
         * The save function will serialize all this bot's data into a file, so it can be
         * retrieved for later use without any inconvenience. No need to call this
         * manually; it'll be done after each modification to the m_aCommands array.
         *
         * @return boolean Indicates whether everything could be saved.
         */

        public function save ()
        {
                $aStorageList = array ();

                foreach ($this -> m_aCommands as $sName => $pCommandInfo)
                {
                        if ($pCommandInfo ['Save'] == false)
                        {
                                continue;
                        }

                        $sName = $this -> getCommandName ($sName);
                        $aStorageList [$sName] = $pCommandInfo;
                }

                return (file_put_contents ('Data/Commands.dat', serialize (array (
                        $aStorageList, $this -> m_sPrefix, $this -> m_bCaseSensitive))) !== false);
        }

        /**
         * This method registers a couple of commands which can be used by the
         * bot owner to control one another from IRC, like adding, removing and
         * renaming, changing properties of commands, (un)loading modules, etc.
         * Just have a skim through this method and you'll figure it out.
         */

        private function registerInternalCommands ()
        {
                $this -> registerCommand (new Command ('cmdadd',
                        function ($pBot, $sDestination, $sChannel, $sNickname, $aParams, $sMessage) {
                                if (count ($aParams) < 2) {
                                        echo '!cmdadd CommandName Code';
                                        return Command :: OUTPUT_USAGE;
                                } else {
                                        Nuwani \ ModuleManager :: getInstance () -> offsetGet ('Commands')
                                                -> addCommand (array_shift ($aParams), implode (' ', $aParams));
                                        echo 'The command has been added.';
                                        return Command :: OUTPUT_SUCCESS;
                                }
                        },
                        SecurityManager :: PERMISSION_BOT_OWNER
                ))
                -> registerCommand (new Command ('cmdremove',
                        function ($pBot, $sDestination, $sChannel, $sNickname, $aParams, $sMessage) {
                                if (count ($aParams) != 1) {
                                        echo '!cmdremove CommandName';
                                        return Command :: OUTPUT_USAGE;
                                } else {
                                        if (Nuwani \ ModuleManager :: getInstance () -> offsetGet ('Commands') -> deleteCommand ($aParams [0])) {
                                                echo 'The command has been deleted successfully.';
                                                return Command :: OUTPUT_SUCCESS;
                                        } else {
                                                echo 'The command has not been found.';
                                                return Command :: OUTPUT_ERROR;
                                        }
                                }
                        },
                        SecurityManager :: PERMISSION_BOT_OWNER
                ))
                -> registerCommand (new Command ('cmdrename',
                        function ($pBot, $sDestination, $sChannel, $sNickname, $aParams, $sMessage) {
                                if (count ($aParams) != 2) {
                                        echo '!cmdrename OldName NewName';
                                        return Command :: OUTPUT_USAGE;
                                } else {
                                        if (Nuwani \ ModuleManager :: getInstance () -> offsetGet ('Commands') -> renameCommand ($aParams [0], $aParams [1])) {
                                                echo 'The command has been renamed successfully.';
                                                return Command :: OUTPUT_SUCCESS;
                                        } else {
                                                echo 'The command has not been found.';
                                                return Command :: OUTPUT_ERROR;
                                        }
                                }
                        },
                        SecurityManager :: PERMISSION_BOT_OWNER
                ))
                -> registerCommand (new Command ('cmdchannel',
                        function ($pBot, $sDestination, $sChannel, $sNickname, $aParams, $sMessage) {
                                if (count ($aParams) < 2) {
                                        echo '!cmdchannel CommandName [- / Channel1 14ChannelN]';
                                        return Command :: OUTPUT_USAGE;
                                } else {
                                        $c = Nuwani \ ModuleManager :: getInstance () -> offsetGet ('Commands') -> offsetGet ($aParams [0]);
                                        if ($c) {
                                                $c -> setChannels (array_slice ($aParams, 1));
                                                echo 'The channels have been updated successfully.';
                                                return Command :: OUTPUT_SUCCESS;
                                        }
                                        else {
                                                echo 'The command has not been found.';
                                                return Command :: OUTPUT_ERROR;
                                        }
                                }
                        },
                        SecurityManager :: PERMISSION_BOT_OWNER
                ))
                -> registerCommand (new Command ('cmdnetwork',
                        function ($pBot, $sDestination, $sChannel, $sNickname, $aParams, $sMessage) {
                                if (count ($aParams) < 2) {
                                        echo '!cmdnetwork CommandName [- / Network1 14NetworkN]';
                                        return Command :: OUTPUT_USAGE;
                                } else {
                                        $c = Nuwani \ ModuleManager :: getInstance () -> offsetGet ('Commands') -> offsetGet ($aParams [0]);
                                        if ($c) {
                                                $c -> setNetworks (array_slice ($aParams, 1));
                                                echo 'The networks have been updated successfully.';
                                                return Command :: OUTPUT_SUCCESS;
                                        } else {
                                                echo 'The command has not been found.';
                                                return Command :: OUTPUT_ERROR;
                                        }
                                }
                        },
                        SecurityManager :: PERMISSION_BOT_OWNER
                ))
                -> registerCommand (new Command ('cmdcode',
                        function ($pBot, $sDestination, $sChannel, $sNickname, $aParams, $sMessage) {
                                if (count ($aParams) != 1) {
                                        echo '!cmdcode CommandName';
                                        return Command :: OUTPUT_USAGE;
                                } else {
                                        $c = Nuwani \ ModuleManager :: getInstance () -> offsetGet ('Commands') -> offsetGet ($aParams [0]);
                                        if ($c) {
                                                if (is_string ($c -> getCode ())) {
                                                        echo $c -> getCode ();
                                                        return Command :: OUTPUT_NORMAL;
                                                } else {
                                                        echo 'The command is a function call, no code can be displayed.';
                                                        return Command :: OUTPUT_ERROR;
                                                }
                                        } else {
                                                echo 'The command has not been found.';
                                                return Command :: OUTPUT_ERROR;
                                        }
                                }
                        },
                        SecurityManager :: PERMISSION_BOT_OWNER
                ))
                -> registerCommand (new Command ('cmdlist',
                        function ($pBot, $sDestination, $sChannel, $sNickname, $aParams, $sMessage) {
                                $aCmd = array ();
                                foreach (Nuwani \ ModuleManager :: getInstance () -> offsetGet ('Commands') -> getIterator () as $sName => $pCommand)
                                        $aCmd [] = $sName;

                                echo wordwrap ('10* Commands (' . count (Nuwani \ ModuleManager :: getInstance () -> offsetGet ('Commands')) . '): !' . implode (', !', $aCmd), 400);
                        },
                        SecurityManager :: PERMISSION_BOT_OWNER
                ))
                -> registerCommand (new Command ('moduleload',
                        function ($pBot, $sDestination, $sChannel, $sNickname, $aParams, $sMessage) {
                                if (count ($aParams) != 1) {
                                        echo '!moduleload ModuleName';
                                        return Command :: OUTPUT_USAGE;
                                } else {
                                        if (Nuwani \ ModuleManager :: getInstance () -> loadModule ($aParams [0])) {
                                                echo 'The module has been loaded.';
                                                return Command :: OUTPUT_SUCCESS;
                                        } else {
                                                echo 'The module could not be loaded.';
                                                return Command :: OUTPUT_ERROR;
                                        }
                                }
                        },
                        SecurityManager :: PERMISSION_BOT_OWNER
                ))
                -> registerCommand (new Command ('moduleunload',
                        function ($pBot, $sDestination, $sChannel, $sNickname, $aParams, $sMessage) {
                                if (count ($aParams) != 1) {
                                        echo '!moduleunload ModuleName';
                                        return Command :: OUTPUT_USAGE;
                                } else {
                                        if (Nuwani \ ModuleManager :: getInstance () -> unloadModule ($aParams [0])) {
                                                echo 'The module has been unloaded.';
                                                return Command :: OUTPUT_SUCCESS;
                                        } else {
                                                echo 'The module could not be unloaded.';
                                                return Command :: OUTPUT_ERROR;
                                        }
                                }
                        },
                        SecurityManager :: PERMISSION_BOT_OWNER
                ))
                -> registerCommand (new Command ('modulereload',
                        function ($pBot, $sDestination, $sChannel, $sNickname, $aParams, $sMessage) {
                                if (count ($aParams) != 1) {
                                        echo '!modulereload ModuleName';
                                        return Command :: OUTPUT_USAGE;
                                } else {
                                        if (Nuwani \ ModuleManager :: getInstance () -> reloadModule ($aParams [0])) {
                                                echo 'The module has been reloaded.';
                                                return Command :: OUTPUT_SUCCESS;
                                        } else {
                                                echo 'The module could not be reloaded.';
                                                return Command :: OUTPUT_ERROR;
                                        }
                                }
                        },
                        SecurityManager :: PERMISSION_BOT_OWNER
                ))
                -> registerCommand (new Command ('modulelist',
                        function ($pBot, $sDestination, $sChannel, $sNickname, $aParams, $sMessage) {
                                $c = Nuwani \ ModuleManager :: getInstance ();
                                $aModules = array ();
                                foreach ($c as $sName => $pModule)
                                        $aModules [] = $sName;

                                echo '10* Modules (' . count ($c) . '): ' . implode (', ', $aModules);
                        },
                        SecurityManager :: PERMISSION_BOT_OWNER
                ))
                -> registerCommand (new Command ('botlist',
                        function ($pBot, $sDestination, $sChannel, $sNickname, $aParams, $sMessage) {
                                $c = Nuwani \ BotManager :: getInstance () -> getBotList ();
                                $aBots = array ();
                                foreach ($c as $sName => $Bot)
                                        $aBots [] = $sName . ' (' . $Bot ['Network'] . ')';

                                echo '10* Bots (' . count ($c) . '): ' . implode (', ', $aBots);
                        },
                        SecurityManager :: PERMISSION_BOT_OWNER
                ))
                -> registerCommand (new Command ('meminfo',
                        function ($pBot, $sDestination, $sChannel, $sNickname, $aParams, $sMessage) {
                                $aGarbage = Nuwani \ Memory :: getStatistics ();
                                echo '10* Current usage: ', sprintf ('%.2f MB', memory_get_usage () / 1024 / 1024),
                                        ' | 10Top usage: ', sprintf ('%.2f MB', memory_get_peak_usage () / 1024 / 1024),
                                        ' | 10Garbage: ', sprintf ('%.2f kB', $aGarbage ['Memory']);
                        },
                        SecurityManager :: PERMISSION_BOT_OWNER
                ))
                -> registerCommand (new Command ('restart',
                        function ($pBot, $sDestination, $sChannel, $sNickname, $aParams, $sMessage) {
                                Nuwani \ BotManager :: getInstance () -> getBotList () -> send ('QUIT :Restart requested by ' . $sNickname);
                                usleep (150000);

                                die (exec ($_SERVER ['_'] . ' LVMbot.php restart > /dev/null &'));
                        },
                        SecurityManager :: PERMISSION_BOT_OWNER
                ))
                -> registerCommand (new Command ('cmdpermission',
                        function ($pBot, $sDestination, $sChannel, $sNickname, $aParams, $sMessage) {
                                if (count ($aParams) != 2) {
                                        echo '!cmdpermission command level';
                                        return Command :: OUTPUT_USAGE;
                                } else {
                                        if (!Nuwani \ ModuleManager :: getInstance () -> offsetGet ('Commands') -> setCommandPermission ($aParams [0], $aParams [1])) {
                                                echo 'The command has not been found.';
                                                return Command :: OUTPUT_ERROR;
                                        } else {
                                                echo 'The required permission has been updated successfully.';
                                                return Command :: OUTPUT_SUCCESS;
                                        }
                                }
                        },
                        SecurityManager :: PERMISSION_BOT_OWNER
                ))
                -> registerCommand (new Command ('useradd',
                        function (Bot $pBot, $sDestination, $sChannel, $sNickname, $aParams, $sMessage) {
                                if (count ($aParams) != 1) {
                                        echo '!useradd usermask';
                                        return Command :: OUTPUT_USAGE;
                                } else {
                                        if ($pBot -> getSecurityManager() -> isUserKnown($aParams[0])) {
                                                echo 'Given user mask is already known.';
                                                return Command :: OUTPUT_ERROR;
                                        }

                                        $pBot -> getSecurityManager() -> addUser($aParams[0]);

                                        echo 'User ' . $aParams[0] . ' has been added.';
                                        return Command :: OUTPUT_SUCCESS;
                                }
                        },
                        SecurityManager :: PERMISSION_BOT_OWNER
                ))
                -> registerCommand (new Command ('permissiongrant',
                        function (Bot $pBot, $sDestination, $sChannel, $sNickname, $aParams, $sMessage) {
                                if (count ($aParams) != 2) {
                                        echo '!permissiongrant usermask permission';
                                        return Command :: OUTPUT_USAGE;
                                } else {
                                        if (!$pBot -> getSecurityManager() -> isUserKnown($aParams[0])) {
                                                echo 'Given user mask does not match any known users.';
                                                return Command :: OUTPUT_ERROR;
                                        }

                                        $user = new Nuwani \ User ($pBot['Network'], $aParams[0]);
                                        if ($pBot -> getSecurityManager() -> grantPermission($user, $aParams[1])) {
                                                echo 'User ' . (string) $user . ' has been granted the "' . $aParams [1] . '" permission.';
                                                return Command :: OUTPUT_SUCCESS;
                                        } else {
                                                echo 'User ' . (string) $user . ' already has the "' . $aParams [1] . '" permission.';
                                                return Command :: OUTPUT_NOTICE;
                                        }
                                }
                        },
                        SecurityManager :: PERMISSION_BOT_OWNER
                ))
                -> registerCommand (new Command ('permissionrevoke',
                        function (Bot $pBot, $sDestination, $sChannel, $sNickname, $aParams, $sMessage) {
                                if (count ($aParams) != 2) {
                                        echo '!permissionrevoke usermask permission';
                                        return Command :: OUTPUT_USAGE;
                                } else {
                                        if (!$pBot -> getSecurityManager() -> isUserKnown($aParams[0])) {
                                                echo 'Given user mask does not match any known users.';
                                                return Command :: OUTPUT_ERROR;
                                        }

                                        $user = new Nuwani \ User ($pBot['Network'], $aParams[0]);
                                        if ($pBot -> getSecurityManager() -> revokePermission($user, $aParams[1])) {
                                                echo 'The "' . $aParams [1] . '" permission has been revoked from user ' . (string) $user . '.';
                                                return Command :: OUTPUT_SUCCESS;
                                        } else {
                                                echo 'User ' . (string) $user . ' doesn\'t have the "' . $aParams [1] . '" permission.';
                                                return Command :: OUTPUT_NOTICE;
                                        }
                                }
                        },
                        SecurityManager :: PERMISSION_BOT_OWNER
                ))
                -> registerCommand (new Command ('permissionshow',
                        function (Bot $pBot, $sDestination, $sChannel, $sNickname, $aParams, $sMessage) {
                                if (count ($aParams) != 1) {
                                        echo '!permissionshow usermask';
                                        return Command :: OUTPUT_USAGE;
                                } else {
                                        $user = null;
                                        if ($aParams[0] == 'me' || $aParams[0] == 'self') {
                                                $user = $pBot -> In -> User;
                                        } else {
                                                $user = new Nuwani \ User ($pBot['Network'], $aParams[0]);
                                        }

                                        $permissions = $pBot -> getSecurityManager() -> getPermissionList($user);

                                        if (empty ($permissions)) {
                                                echo 'User ' . (string) $user . ' doesn\'t have any permissions.';
                                                return Command :: OUTPUT_INFO;
                                        } else {
                                                echo 'User ' . (string) $user . ' has the following permissions: ' . implode (', ', $permissions);
                                                return Command :: OUTPUT_INFO;
                                        }
                                }
                        },
                        null
                ))
                -> registerCommand (new Command ('runningtimers',
                        function ($pBot, $sDestination, $sChannel, $sNickname, $sParams, $sMessage) {
                                echo '10* Running timers: ';
                                $message = '';

                                foreach (Nuwani \ Timer :: getActiveTimers () as $timerInfo) {
                                        $message .= $timerInfo ['name'];
                                        $message .= ' 14(ID: ' . $timerInfo ['id'];
                                        $message .= ', in ' . Util :: formatTime ($timerInfo ['next_run'] - microtime (true), true);
                                        $message .= ($timerInfo ['type'] == Nuwani \ Timer :: TIMEOUT ? ', once' : '');
                                        $message .= '), ';
                                }

                                echo wordwrap (substr ($message, 0, -2), 400);
                        },
                        SecurityManager :: PERMISSION_BOT_OWNER
                ));
        }

        /**
         * To instantly shift all commands from "!time" to "?time", this is the function that
         * has to be used. It'll automatically serialize the new prefix too.
         *
         * @param string $sPrefix Prefix to assign to the commands.
         * @return boolean Indicates whether everything could be saved.
         */

        public function setPrefix ($sPrefix)
        {
                if (strlen ($sPrefix) != 1)
                {
                        return false;
                }

                $this -> m_sPrefix = $sPrefix;

                return $this -> save ();
        }

        /**
         * Sets whether this module should handle all commands with case sensitivity or not.
         * If set to false, all commands will be re-added so that case insensitivity
         * immediately works. The Command :: m_sCommand property is deliberately left as-is;
         * this makes the case sensitivity reversible (which is done when bCaseSensitive is
         * set to true).
         *
         * @param boolean $bCaseSensitive Case sensitive, true or false.
         * @return boolean Indicates whether everything could be saved.
         */

        public function setCaseSensitive ($bCaseSensitive)
        {
                $this -> m_bCaseSensitive = $bCaseSensitive;

                $aNewCommands = array ();
                foreach ($this -> m_aCommands as $sCommand => $pCommand)
                {
                        if ($bCaseSensitive)
                        {
                                $sCommand = $pCommand -> getCommand ();
                        }
                        else
                        {
                                $sCommand = strtolower ($sCommand);
                        }

                        $aNewCommands [$sCommand] = $pCommand;
                }

                $this -> m_aCommands = $aNewCommands;

                return $this -> save ();
        }

        /**
         * The function which allows you to create a new command with the handler,
         * so new fancy features can be added to the bot system.
         *
         * @param string $sCommand Name of the command that you wish to implement.
         * @param string $sCode Code to be associated with this command.
         * @return boolean Indicates whether everything could be saved.
         */

        public function addCommand ($sCommand, $sCode)
        {
                $sCommand = $this -> getCommandName ($sCommand);

                $this -> m_aCommands [$sCommand] = new Command ($sCommand, $sCode, null, true);

                return $this -> save ();
        }

        /**
         * This method will allow an external source (most likely a module) to
         * register a predefined Command object with this module. This will be
         * added to the main commands array and executed as any other.
         *
         * @param Command $pCommand Command object with the code that should be executed when invoked.
         * @return Commands Pointer to this module, to enable method chaining.
         */

        public function registerCommand (Command $pCommand)
        {
                $sCommand = $this -> getCommandName ($pCommand ['Command']);

                $this -> m_aCommands [$sCommand] = $pCommand;

                if ($pCommand ['Save'])
                {
                        $this -> save ();
                }

                return $this;
        }

        /**
         * This function will rename a currently listed command into something new,
         * so it can be used properly.
         *
         * @param string $sOldCommand Current name of the command.
         * @param string $sNewCommand New name of the command.
         * @return boolean Indicates whether everything could be saved.
         */

        public function renameCommand ($sOldCommand, $sNewCommand)
        {
                $sOldCommand = $this -> getCommandName ($sOldCommand);
                $sNewCommand = $this -> getCommandName ($sNewCommand);

                if (!isset ($this -> m_aCommands [$sOldCommand]))
                {
                        return false;
                }

                $this -> m_aCommands [$sNewCommand] = $this -> m_aCommands [$sOldCommand];
                unset ($this -> m_aCommands [$sOldCommand]);

                return $this -> save ();
        }

        /**
         * This function can be used to totally remove a command from our system.
         * Mind that no backups are made and that this is being applied immediately.
         *
         * @param string $sCommand Command that you want to completely remove.
         * @return boolean Indicates whether everything could be saved.
         */

        public function deleteCommand ($sCommand)
        {
                $sCommand = $this -> getCommandName ($sCommand);

                if (!isset ($this -> m_aCommands [$sCommand]))
                {
                        return false;
                }

                unset ($this -> m_aCommands [$sCommand]);
                return $this -> save ();
        }

        /**
         * This function lets you retrieve the object of a command. Returns false
         * if the command does not exist.
         *
         * @param string $sCommand The command of which you want the object.
         * @return Command|false
         */

        public function getCommand ($sCommand)
        {
                $sCommand = $this -> getCommandName ($sCommand);

                if (isset ($this -> m_aCommands [$sCommand]))
                {
                        return $this -> m_aCommands [$sCommand];
                }

                return false;
        }

        /**
         * This method check whether perhaps the given command has been prefixed
         * by the prefix ($this -> m_sPrefix), and if so, removes it, and returns
         * the commandname without it.
         *
         * @param string $sCommand The command of which you want the name.
         * @return string The clean command name.
         */

        private function getCommandName ($sCommand)
        {
                if ($sCommand [0] == $this -> m_sPrefix)
                {
                        // Common mistake to include the prefix in the Command.
                        $sCommand = substr ($sCommand, 1);
                }

                if (!$this -> m_bCaseSensitive)
                {
                        $sCommand = strtolower ($sCommand);
                }

                return $sCommand;
        }

        /**
         * This function can be used to update the required permission of the given
         * command.
         *
         * @param string $sCommand Command to update the permission of.
         * @param string $sPermission Required permission for executing this command.
         */

        public function setCommandPermission ($sCommand, $sPermission)
        {
                $sCommand = $this -> getCommandName ($sCommand);

                if (isset ($this -> m_aCommands [$sCommand]))
                {
                        $this -> m_aCommands [$sCommand] -> setPermission ($sPermission);
                        return $this -> save ();
                }

                return false;
        }

        /**
         * PHP Code evaluations may occur in public channels, such as #Sonium which
         * is frequently used for testing. This function will check whether we're
         * allowed to evaluate anything here.
         *
         * @param Bot $pBot The bot who received the public channel message.
         * @param string $sChannel Channel in which we received the message.
         * @param string $sNickname The nickname associated with this message.
         * @param string $sMessage And of course the actual message we received.
         */

        public function onChannelPrivmsg (Bot $pBot, $sChannel, $sNickname, $sMessage)
        {
                if ($sMessage [0] == $this -> m_sPrefix)
                {
                        return $this -> handleCommand ($pBot, $sChannel, $sNickname, $sMessage);
                }
        }

        /**
         * People are free to send private messages to the bot, which gets
         * handled right here. This function does the same as onChannelPrivmsg.
         *
         * @param string $pBot Bot that received this private message.
         * @param string $sNickname Source of the message.
         * @param string $sMessage The message that got PM'ed to us.
         */

        public function onPrivmsg (Bot $pBot, $sNickname, $sMessage)
        {
                if ($sMessage [0] == $this -> m_sPrefix)
                {
                        return $this -> handleCommand ($pBot, false, $sNickname, $sMessage);
                }
        }

        /**
         * This function determines whether we have to execute this command,
         * or not. The only hardcoded command is !addcmd.
         *
         * @param Bot $pBot The bot who received the public channel message.
         * @param string $sChannel Channel in which we received the message.
         * @param string $sNickname The nickname associated with this message.
         * @param string $sMessage And of course the actual message we received.
         */

        private function handleCommand (Bot $pBot, $sChannel, $sNickname, $sMessage)
        {
                $aArguments = preg_split ('/(\s+)/', $sMessage);
                $sCommand   = $this -> getCommandName (array_shift ($aArguments));

                if (isset ($this -> m_aCommands [$sCommand]))
                {
                        $sDestination = $sChannel === false ? $sNickname : $sChannel;
                        $sMessage = trim (substr ($sMessage, strlen ($sCommand) + 2));
                        if (strlen ($sMessage) == 0)
                        {
                                $sMessage = null;
                        }

                        $this -> m_aCommands [$sCommand] ($pBot, $sDestination, $sChannel, $sNickname, $aArguments, $sMessage);

                        return true;
                }

                return false;
        }

        /**
         * This method returns the number of commands currently loaded.
         *
         * @return integer
         */

        public function count ()
        {
                return count ($this -> m_aCommands);
        }

        /**
         * Returns an ArrayIterator for m_aCommands, which can be used in a
         * foreach statement.
         *
         * @return ArrayIterator
         */

        public function getIterator ()
        {
                return new ArrayIterator ($this -> m_aCommands);
        }

        // -------------------------------------------------------------------//
        // Region: ArrayAccess                                                //
        // -------------------------------------------------------------------//

        /**
         * Check whether the offset exists within this module.
         *
         * @param string $sOffset The command or setting to check.
         * @return boolean Indicating whether the offset exists.
         */

        public function offsetExists ($sOffset)
        {
                if ($sOffset == 'Prefix')
                {
                        return true;
                }

                if ($sOffset == 'CaseSensitive')
                {
                        return true;
                }

                return isset ($this -> m_aCommands [$sOffset]);
        }

        /**
         * Gets a specific setting of this module or the object of a command.
         * If no bots are found, then this function tries to match patterns.
         * Returns false if nothing has been found.
         *
         * @param string $sOffset The command or setting to get.
         * @return mixed|false The value of the command or setting.
         */

        public function offsetGet ($sOffset)
        {
                if ($sOffset == 'Prefix')
                {
                        return $this -> m_sPrefix;
                }

                if ($sOffset == 'CaseSensitive')
                {
                        return $this -> m_bCaseSensitive;
                }

                if (isset ($this -> m_aCommands [$sOffset]))
                {
                        return $this -> getCommand ($sOffset);
                }

                if ($sOffset[0] == $this -> m_sPrefix && isset ($this -> m_aCommands [substr ($sOffset, 1)]))
                {
                        return $this -> getCommand (substr ($sOffset, 1));
                }

                $aChunks = explode(' ', strtolower ($sOffset));
                $aMatch  = $aReq = array ();

                /** Extract information from the pattern **/
                foreach ($aChunks as $sChunk)
                {
                        if (strpos ($sChunk, ':') !== false)
                        {
                                list ($sKey, $sValue) = explode (':', $sChunk);
                                $aReq [$sKey] = $sValue;
                        }
                }

                /** Let's see if there are commands which match **/
                foreach ($this -> m_aCommands as $sName => $pCmd)
                {
                        // FIXME Does this even work? I bet it doesn't. Refactor. Or remove, my guts tell me this is never used.
                        if (isset ($aReq ['permission']) && $pCmd -> getPermission () == $aReq ['permission'])
                        {
                                $aMatch [] = $this -> m_aCommands [$sName];
                        }

                        if (isset ($aReq ['name']) && strpos ($pCmd, $aReq ['name']) !== false)
                        {
                                $aMatch [] = $this -> m_aCommands [$sName];
                        }

                        if (isset ($aReq ['network']) && $pCmd -> checkNetwork ($aReq ['network']))
                        {
                                $aMatch [] = $this -> m_aCommands [$sName];
                        }
                }

                if (empty ($aMatch))
                {
                        return false;
                }

                return $aMatch;
        }

        /**
         * This is a shortcut to addCommand().
         *
         * @param string $sOffset The command to set.
         * @param mixed $mValue The value.
         */

        public function offsetSet ($sOffset, $mValue)
        {
                if ($sOffset == 'Prefix')
                {
                        return $this -> setPrefix ($mValue);
                }

                if ($sOffset == 'CaseSensitive')
                {
                        return $this -> setCaseSensitive ($mValue);
                }

                $this -> addCommand ($sOffset, $mValue);
        }

        /**
         * This is a shortcut to deleteCommand().
         *
         * @param string $sOffset The command to unset.
         */

        public function offsetUnset ($sOffset)
        {
                $this -> deleteCommand ($sOffset);
        }

};

?>


text:
#ifndef _SYS_COALITION_H_
#define _SYS_COALITION_H_

#include <stdint.h>
#include <sys/cdefs.h>
#include <sys/types.h>

#include <mach/coalition.h>

__BEGIN_DECLS

/* Userspace syscall prototypes */

/* Syscalls */
int coalition_create(uint64_t *cid_out, uint32_t flags);
int coalition_terminate(uint64_t cid, uint32_t flags);
int coalition_reap(uint64_t cid, uint32_t flags);

/* Wrappers around __coalition_info syscall (with proper struct types) */
int coalition_info_resource_usage(uint64_t cid, struct coalition_resource_usage *cru, size_t sz);

__END_DECLS

#endif /* _SYS_COALITION_H_ */


text:
dojo.provide("t.unit.plugins.apps.module");

try{
    dojo.require("t.unit.plugins.request.search.test");
    dojo.require("t.unit.plugins.request.grid.test");
}
catch(e) {
    doh.debug(e);
}


text:
(function() {
    'use strict';

    angular
        .module('bibalDenisApp')
        .controller('UsagerDialogController', UsagerDialogController);

    UsagerDialogController.$inject = ['$timeout', '$scope', '$stateParams', '$uibModalInstance', 'entity', 'Usager', 'Emprunt'];

    function UsagerDialogController ($timeout, $scope, $stateParams, $uibModalInstance, entity, Usager, Emprunt) {
        var vm = this;

        vm.usager = entity;
        vm.clear = clear;
        vm.save = save;
        vm.emprunts = Emprunt.query();

        $timeout(function (){
            angular.element('.form-group:eq(1)>input').focus();
        });

        function clear () {
            $uibModalInstance.dismiss('cancel');
        }

        function save () {
            vm.isSaving = true;
            if (vm.usager.id !== null) {
                Usager.update(vm.usager, onSaveSuccess, onSaveError);
            } else {
                Usager.save(vm.usager, onSaveSuccess, onSaveError);
            }
        }

        function onSaveSuccess (result) {
            $scope.$emit('bibalDenisApp:usagerUpdate', result);
            $uibModalInstance.close(result);
            vm.isSaving = false;
        }

        function onSaveError () {
            vm.isSaving = false;
        }

    }
})();


text:
package com.jtbdevelopment.games.stringimpl;

import com.jtbdevelopment.games.state.AbstractSinglePlayerGame;

/**
 * Date: 11/8/14 Time: 9:09 AM
 */
public class StringSPGame extends AbstractSinglePlayerGame<String, Object> {

  private String id;
  private String previousId;

  @Override
  public String getIdAsString() {
    return id;
  }

  @Override
  public String getPreviousIdAsString() {
    return previousId;
  }

  public String getId() {
    return id;
  }

  public void setId(String id) {
    this.id = id;
  }

  public String getPreviousId() {
    return previousId;
  }

  public void setPreviousId(String previousId) {
    this.previousId = previousId;
  }
}


text:
function xhrGet(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200)
      callback(xhr.responseText);
  }
  xhr.open("GET", url, true);
  xhr.send(null);
};

var url = 'https://ydo07btybj.execute-api.eu-west-1.amazonaws.com/dev/ramblings/';

xhrGet(url, function(response) {
  var data = JSON.parse(response);
  var itemsDiv = document.getElementById('items')
  for(var i=0; i < data.length; i++) {
    var item = '
' + data[i]['text'] + '
';
    itemsDiv.innerHTML = itemsDiv.innerHTML + item;
  }
});