text:
static const char
LIBPROJ_ID[] = "Id";
/*
** Permission is hereby granted, free of charge, to any person obtaining
** a copy of this software and associated documentation files (the
** "Software"), to deal in the Software without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Software, and to
** permit persons to whom the Software is furnished to do so, subject to
** the following conditions:
**
** The above copyright notice and this permission notice shall be
** included in all copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#define PROJ_PARMS__ \
  double ap;
#define EPS10 1.e-10
#define PROJ_LIB__
#include  <lib_proj.h>
PROJ_HEAD(tcc, "Transverse Central Cylindrical") "\n\tCyl, Sph, no inv.";
FORWARD(s_forward); /* spheroid */
  double b, bt;
  (void) P; /* avoid warning */

  b = cos(lp.phi) * sin(lp.lam);
  if ((bt = 1. - b * b) < EPS10) F_ERROR;
  xy.x = b / sqrt(bt);
  xy.y = atan2(tan(lp.phi) , cos(lp.lam));
  return (xy);
}
FREEUP; if (P) free(P); }
ENTRY0(tcc) P->es = 0.; P->fwd = s_forward; ENDENTRY(P)
/*
** Log: proj_tcc.c
** Revision 3.1  2006/01/11 01:38:18  gie
** Initial
**
*/


text:
package com.viesis.viescraft.common.items.modules;

import java.util.List;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.EnumRarity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

import com.viesis.viescraft.common.items.ItemHelper;

public class ItemModuleStealth extends Item {

	public ItemModuleStealth()
	{
		ItemHelper.setItemName(this, "module_stealth");
		this.setMaxStackSize(1);
	}

	@SideOnly(Side.CLIENT)
    public void addInformation(ItemStack stack, EntityPlayer playerIn, List toolTip, boolean advanced)
	{
		toolTip.add(" ");
		toolTip.add(TextFormatting.GOLD + "Effects when activated:");
		toolTip.add(TextFormatting.GREEN + "Pro - Vanish for 18 seconds.");
		toolTip.add(TextFormatting.RED + "Con - 2 Minute Cooldown.");
		toolTip.add(" ");
	}

	public EnumRarity getRarity(ItemStack stack)
    {
        return EnumRarity.RARE;
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace OpenGD.Logic
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using OpenGD.Model;

    public class Game
    {
        public Game()
        {
            Init();
        }

        protected GameState GameState { get; set; }

        private void Init()
        {
            GameState = new GameState();
        }

        public void SetName(string gameName)
        {
            GameState.Name = gameName;
        }

        public void Start(int difficulty, int humanPlayerCount, int cpuPlayerCount)
        {
            GameState.Difficulty = difficulty;
        }

        public bool PlacesInitialized()
        {
            return GameState.Places?.Any() ?? false;
        }

        public void PopulateLocations(IList<Location> locations)
        {
            GameState.Locations = locations;
        }
    }
}


text:
import sys
import re

class DocoptLanguageError(Exception):

    """Error in construction of usage-message by developer."""

class DocoptExit(SystemExit):

    """Exit in case user invoked program with incorrect arguments."""

    usage = ''

    def __init__(self, message=''):
        SystemExit.__init__(self, (message + '\n' + self.usage).strip())

class Pattern(object):

    def __eq__(self, other):
        return repr(self) == repr(other)

    def __hash__(self):
        return hash(repr(self))

    def fix(self):
        self.fix_identities()
        self.fix_list_arguments()
        return self

    def fix_identities(self, uniq=None):
        """Make pattern-tree tips point to same object if they are equal."""
        if not hasattr(self, 'children'):
            return self
        uniq = list(set(self.flat)) if uniq == None else uniq
        for i, c in enumerate(self.children):
            if not hasattr(c, 'children'):
                assert c in uniq
                self.children[i] = uniq[uniq.index(c)]
            else:
                c.fix_identities(uniq)

    def fix_list_arguments(self):
        """Find arguments that should accumulate values and fix them."""
        either = [list(c.children) for c in self.either.children]
        for case in either:
            for e in [c for c in case if case.count(c) > 1]:
                if type(e) is Argument or type(e) is Option and e.argcount:
                    e.value = []
                if type(e) is Command or type(e) is Option and e.argcount == 0:
                    e.value = 0
        return self

    @property
    def either(self):
        """Transform pattern into an equivalent, with only top-level Either."""
        # Currently the pattern will not be equivalent, but more "narrow",
        # although good enough to reason about list arguments.
        ret = []
        groups = [[self]]
        while groups:
            children = groups.pop(0)
            types = [type(c) for c in children]
            if Either in types:
                either = [c for c in children if type(c) is Either][0]
                children.pop(children.index(either))
                for c in either.children:
                    groups.append([c] + children)
            elif Required in types:
                required = [c for c in children if type(c) is Required][0]
                children.pop(children.index(required))
                groups.append(list(required.children) + children)
            elif Optional in types:
                optional = [c for c in children if type(c) is Optional][0]
                children.pop(children.index(optional))
                groups.append(list(optional.children) + children)
            elif OneOrMore in types:
                oneormore = [c for c in children if type(c) is OneOrMore][0]
                children.pop(children.index(oneormore))
                groups.append(list(oneormore.children) * 2 + children)
            else:
                ret.append(children)
        return Either(*[Required(*e) for e in ret])

class ChildPattern(Pattern):

    def __init__(self, name, value=None):
        self.name = name
        self.value = value

    def __repr__(self):
        return '%s(%r, %r)' % (self.__class__.__name__, self.name, self.value)

    @property
    def flat(self):
        return [self]

    def match(self, left, collected=None):
        collected = [] if collected is None else collected
        pos, match = self.single_match(left)
        if match is None:
            return False, left, collected
        left_ = left[:pos] + left[pos+1:]
        same_name = [a for a in collected if a.name == self.name]
        if type(self.value) in (int, list):
            increment = 1 if type(self.value) is int else [match.value]
            if not same_name:
                match.value = increment
                return True, left_, collected + [match]
            same_name[0].value += increment
            return True, left_, collected
        return True, left_, collected + [match]

class ParrentPattern(Pattern):

    def __init__(self, *children):
        self.children = list(children)

    def __repr__(self):
        return '%s(%s)' % (self.__class__.__name__,
                           ', '.join(repr(a) for a in self.children))

    @property
    def flat(self):
        return sum([c.flat for c in self.children], [])

class Argument(ChildPattern):

    def single_match(self, left):
        for n, p in enumerate(left):
            if type(p) is Argument:
                return n, Argument(self.name, p.value)
        return None, None

class Command(Argument):

    def __init__(self, name, value=False):
        self.name = name
        self.value = value

    def single_match(self, left):
        for n, p in enumerate(left):
            if type(p) is Argument:
                if p.value == self.name:
                    return n, Command(self.name, True)
                else:
                    break
        return None, None

class Option(ChildPattern):

    def __init__(self, short=None, long=None, argcount=0, value=False):
        assert argcount in (0, 1)
        self.short, self.long = short, long
        self.argcount, self.value = argcount, value
        self.value = None if value == False and argcount else value  # HACK

    @classmethod
    def parse(class_, option_description):
        short, long, argcount, value = None, None, 0, False
        options, _, description = option_description.strip().partition('  ')
        options = options.replace(',', ' ').replace('=', ' ')
        for s in options.split():
            if s.startswith('--'):
                long = s
            elif s.startswith('-'):
                short = s
            else:
                argcount = 1
        if argcount:
            matched = re.findall('\[default: (.*)\]', description, flags=re.I)
            value = matched[0] if matched else None
        return class_(short, long, argcount, value)

    def single_match(self, left):
        for n, p in enumerate(left):
            if self.name == p.name:
                return n, p
        return None, None

    @property
    def name(self):
        return self.long or self.short

    def __repr__(self):
        return 'Option(%r, %r, %r, %r)' % (self.short, self.long,
                                           self.argcount, self.value)

class Required(ParrentPattern):

    def match(self, left, collected=None):
        collected = [] if collected is None else collected
        l = left
        c = collected
        for p in self.children:
            matched, l, c = p.match(l, c)
            if not matched:
                return False, left, collected
        return True, l, c

class Optional(ParrentPattern):

    def match(self, left, collected=None):
        collected = [] if collected is None else collected
        for p in self.children:
            m, left, collected = p.match(left, collected)
        return True, left, collected

class OneOrMore(ParrentPattern):

    def match(self, left, collected=None):
        assert len(self.children) == 1
        collected = [] if collected is None else collected
        l = left
        c = collected
        l_ = None
        matched = True
        times = 0
        while matched:
            # could it be that something didn't match but changed l or c?
            matched, l, c = self.children[0].match(l, c)
            times += 1 if matched else 0
            if l_ == l:
                break
            l_ = l
        if times >= 1:
            return True, l, c
        return False, left, collected

class Either(ParrentPattern):

    def match(self, left, collected=None):
        collected = [] if collected is None else collected
        outcomes = []
        for p in self.children:
            matched, _, _ = outcome = p.match(left, collected)
            if matched:
                outcomes.append(outcome)
        if outcomes:
            return min(outcomes, key=lambda outcome: len(outcome[1]))
        return False, left, collected

class TokenStream(list):

    def __init__(self, source, error):
        self += source.split() if hasattr(source, 'split') else source
        self.error = error

    def move(self):
        return self.pop(0) if len(self) else None

    def current(self):
        return self[0] if len(self) else None

def parse_long(tokens, options):
    raw, eq, value = tokens.move().partition('=')
    value = None if eq == value == '' else value
    opt = [o for o in options if o.long and o.long == raw]
    if tokens.error is DocoptExit and opt == []:
        opt = [o for o in options if o.long and o.long.startswith(raw)]
    if len(opt) < 1:
        if tokens.error is DocoptExit:
            raise tokens.error('%s is not recognized' % raw)
        else:
            o = Option(None, raw, (1 if eq == '=' else 0))
            options.append(o)
            return [o]
    if len(opt) > 1:
        raise tokens.error('%s is not a unique prefix: %s?' %
                         (raw, ', '.join('%s' % o.long for o in opt)))
    o = opt[0]
    opt = Option(o.short, o.long, o.argcount, o.value)
    if opt.argcount == 1:
        if value is None:
            if tokens.current() is None:
                raise tokens.error('%s requires argument' % opt.name)
            value = tokens.move()
    elif value is not None:
        raise tokens.error('%s must not have an argument' % opt.name)
    if tokens.error is DocoptExit:
        opt.value = value or True
    else:
        opt.value = None if value else False
    return [opt]

def parse_shorts(tokens, options):
    raw = tokens.move()[1:]
    parsed = []
    while raw != '':
        opt = [o for o in options
               if o.short and o.short.lstrip('-').startswith(raw[0])]
        if len(opt) > 1:
            raise tokens.error('-%s is specified ambiguously %d times' %
                              (raw[0], len(opt)))
        if len(opt) < 1:
            if tokens.error is DocoptExit:
                raise tokens.error('-%s is not recognized' % raw[0])
            else:
                o = Option('-' + raw[0], None)
                options.append(o)
                parsed.append(o)
                raw = raw[1:]
                continue
        o = opt[0]
        opt = Option(o.short, o.long, o.argcount, o.value)
        raw = raw[1:]
        if opt.argcount == 0:
            value = True if tokens.error is DocoptExit else False
        else:
            if raw == '':
                if tokens.current() is None:
                    raise tokens.error('-%s requires argument' % opt.short[0])
                raw = tokens.move()
            value, raw = raw, ''
        if tokens.error is DocoptExit:
            opt.value = value
        else:
            opt.value = None if value else False
        parsed.append(opt)
    return parsed

def parse_pattern(source, options):
    tokens = TokenStream(re.sub(r'([\[\]\(\)\|]|\.\.\.)', r' \1 ', source),
                         DocoptLanguageError)
    result = parse_expr(tokens, options)
    if tokens.current() is not None:
        raise tokens.error('unexpected ending: %r' % ' '.join(tokens))
    return Required(*result)

def parse_expr(tokens, options):
    """expr ::= seq ( '|' seq )* ;"""
    seq = parse_seq(tokens, options)
    if tokens.current() != '|':
        return seq
    result = [Required(*seq)] if len(seq) > 1 else seq
    while tokens.current() == '|':
        tokens.move()
        seq = parse_seq(tokens, options)
        result += [Required(*seq)] if len(seq) > 1 else seq
    return [Either(*result)] if len(result) > 1 else result

def parse_seq(tokens, options):
    """seq ::= ( atom [ '...' ] )* ;"""
    result = []
    while tokens.current() not in [None, ']', ')', '|']:
        atom = parse_atom(tokens, options)
        if tokens.current() == '...':
            atom = [OneOrMore(*atom)]
            tokens.move()
        result += atom
    return result

def parse_atom(tokens, options):
    """atom ::= '(' expr ')' | '[' expr ']' | 'options'
             | long | shorts | argument | command ;
    """
    token = tokens.current()
    result = []
    if token in '([':
        tokens.move()
        matching, pattern = {'(': [')', Required], '[': [']', Optional]}[token]
        result = pattern(*parse_expr(tokens, options))
        if tokens.move() != matching:
            raise tokens.error("unmatched '%s'" % token)
        return [result]
    elif token == 'options':
        tokens.move()
        return options
    elif token.startswith('--') and token != '--':
        return parse_long(tokens, options)
    elif token.startswith('-') and token not in ('-', '--'):
        return parse_shorts(tokens, options)
    elif token.startswith('<') and token.endswith('>') or token.isupper():
        return [Argument(tokens.move())]
    else:
        return [Command(tokens.move())]

def parse_argv(source, options):
    tokens = TokenStream(source, DocoptExit)
    parsed = []
    while tokens.current() is not None:
        if tokens.current() == '--':
            return parsed + [Argument(None, v) for v in tokens]
        elif tokens.current().startswith('--'):
            parsed += parse_long(tokens, options)
        elif tokens.current().startswith('-') and tokens.current() != '-':
            parsed += parse_shorts(tokens, options)
        else:
            parsed.append(Argument(None, tokens.move()))
    return parsed

def parse_doc_options(doc):
    return [Option.parse('-' + s) for s in re.split('^ *-|\n *-', doc)[1:]]

def printable_usage(doc):
    usage_split = re.split(r'([Uu][Ss][Aa][Gg][Ee]:)', doc)
    if len(usage_split) < 3:
        raise DocoptLanguageError('"usage:" (case-insensitive) not found.')
    if len(usage_split) > 3:
        raise DocoptLanguageError('More than one "usage:" (case-insensitive).')
    return re.split(r'\n\s*\n', ''.join(usage_split[1:]))[0].strip()

def formal_usage(printable_usage):
    pu = printable_usage.split()[1:]  # split and drop "usage:"
    return '( ' + ' '.join(') | (' if s == pu[0] else s for s in pu[1:]) + ' )'

def extras(help, version, options, doc):
    if help and any((o.name in ('-h', '--help')) and o.value for o in options):
        print(doc.strip())
        exit()
    if version and any(o.name == '--version' and o.value for o in options):
        print(version)
        exit()

class Dict(dict):
    def __repr__(self):
        return '{%s}' % ',\n '.join('%r: %r' % i for i in sorted(self.items()))

def docopt(doc, argv=sys.argv[1:], help=True, version=None):
    DocoptExit.usage = printable_usage(doc)
    options = parse_doc_options(doc)
    pattern = parse_pattern(formal_usage(DocoptExit.usage), options)
    argv = parse_argv(argv, options)
    extras(help, version, argv, doc)
    matched, left, collected = pattern.fix().match(argv)
    if matched and left == []:  # better error message if left?
        return Dict((a.name, a.value) for a in (pattern.flat + options + collected))
    raise DocoptExit()


text:
[![License](http://img.shields.io/:license-mit-blue.svg)](http://tonekk.mit-license.org)

Syntax highlighting for binding.pry and binding.remote-pry

## Install

Install with [vundle](https://github.com/gmarik/Vundle.vim) or [neobundle](https://github.com/Shougo/neobundle.vim).


text:
layout: project-layout
bg-url: /img/background-project4.png
permalink: /projects/rubbish/
title: ₹ubbish!
intended: Residential Welfare Associations, Bulk generators of waste, Policymakers, Students.
keywords: Solid Waste Management
type: Bi-lingual board game
duration: 1.5 - 2 hours
players: 4 - 6 players
video: https://www.youtube.com/embed/rhKCXakQbIk
brochure: /brochures/Rubbish.pdf
intro: Recently Bangalore adopted a decentralized approach to address its waste crisis with Dry Waste Collection Centers (DWCCs) being setup in every ward. How can we address some of the challenges faced by DWCCs and help strengthen the infrastructure for waste management in the city? It is this question we explored in ₹ubbish!, a cross-cultural design collaboration between Bangalore and Amsterdam.
description:
Some of the challenges faced by the DWCCs include apathy of citizens toward dealing with waste and a lack of knowledge about the new decentralized system for waste management. Our objective was to address knowledge gaps and behaviour to promote understanding of the waste management system at both the micro and macro levels.

A combination of the methodology followed at Fields of View and mediaLab Amsterdam, involving framing the problem in consultation with stakeholders, field visits, discussions and interviews with experts, game design, and user tests.

collaborations: The project was a collaboration between mediaLAB Amsterdam, IIIT-B, and Fields of View with Nalini Shekar and the team at Hasirudala.
img1: /img/rubbish-img-2.jpg
img2: /img/rubbish-img-1.jpg
donate: Donate to make ₹ubbish!
ide: rubbish
categories: project
thread: Policy in Play
tag: game
---


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Xunit;
using System;
using System.Collections.Generic;

namespace System.Globalization.Extensions.Tests
{
    /// <summary>
    /// This suite of tests enumerate a set of input and outputs provided by the Unicode consortium.
    /// For more information, see the files within Data\[Unicode version].  This tests positive
    /// and negative test cases for both GetASCII and GetUnicode methods.
    /// </summary>
    public class IdnaConformanceTests
    {
        /// <summary>
        /// Tests whether the expected object is equal to the actual object as determined by
        /// the supplied comparer and throws an exception if it is not.
        /// </summary>
        /// <param name="expected">Expected object.</param>
        /// <param name="actual">Actual object.</param>
        /// <param name="comparer">Comparer to be used to determine equality of objects.</param>
        /// <param name="message">Message to display upon failure.</param>
        public static void CompareResult<T>(T expected, T actual, IComparer<T> comparer, string message)
        {
            if (comparer.Compare(expected, actual) != 0)
            {
                Assert.False(true, string.Format(@"Expected: <{1}>. Actual:<{2}>. {0}", message, expected, actual));
            }
        }

        /// <summary>
        /// Tests positive cases for GetAscii.
        /// </summary>
        [Fact]
        public void TestAsciiPositive()
        {
            foreach (var entry in Factory.GetDataset())
            {
                if (entry.GetASCIIResult.Success)
                {
                    var map = new System.Globalization.IdnMapping();
                    var asciiResult = map.GetAscii(entry.Source);

                    CompareResult(entry.GetASCIIResult.Value, asciiResult, StringComparer.OrdinalIgnoreCase, "Error on line number " + entry.LineNumber);
                }
            }
        }

        /// <summary>
        /// Tests positive cases for GetUnicode.  Windows fails by design on some entries that should pass.  The recommendation is to take the source input
        /// for this if needed.
        ///
        /// There are some others that failed which have been commented out and marked in the dataset as "GETUNICODE DOES FAILS ON WINDOWS 8.1"
        /// </summary>
        [Fact]
        public void TestUnicodePositive()
        {
            foreach (var entry in Factory.GetDataset())
            {
                if (entry.GetUnicodeResult.Success)
                {
                    try
                    {
                        var map = new System.Globalization.IdnMapping { UseStd3AsciiRules = true, AllowUnassigned = true };
                        var unicodeResult = map.GetUnicode(entry.Source);

                        CompareResult(entry.GetUnicodeResult.Value, unicodeResult, StringComparer.OrdinalIgnoreCase, "Error on line number " + entry.LineNumber);
                    }
                    catch (ArgumentException)
                    {
                        CompareResult(entry.GetUnicodeResult.Value, entry.Source, StringComparer.OrdinalIgnoreCase, "Error on line number " + entry.LineNumber);
                    }
                }
            }
        }

        /// <summary>
        /// Tests negative cases for GetAscii.
        /// </summary>
        /// <remarks>
        /// There are some failures on Windows 8.1 that have been commented out
        /// from the 6.0\IdnaTest.txt.  To find them, search for "GETASCII DOES NOT FAIL ON WINDOWS 8.1"
        /// </remarks>
        [Fact]
        public void TestAsciiNegative()
        {
            foreach (var entry in Factory.GetDataset())
            {
                if (!entry.GetASCIIResult.Success)
                {
                    var map = new System.Globalization.IdnMapping();
                    Assert.Throws<ArgumentException>(() => map.GetAscii(entry.Source));
                }
            }
        }

        /// <summary>
        /// Tests negative cases for GetUnicode.
        /// </summary>
        /// <remarks>
        /// There are some failures on Windows 8.1 that have been commented out
        /// from the 6.0\IdnaTest.txt.  To find them, search for "GETUNICODE DOES NOT FAIL ON WINDOWS 8.1"
        /// </remarks>
        [Fact]
        public void TestUnicodeNegative()
        {
            foreach (var entry in Factory.GetDataset())
            {
                if (!entry.GetUnicodeResult.Success)
                {
                    var map = new System.Globalization.IdnMapping();
                    Assert.Throws<ArgumentException>(() => map.GetUnicode(entry.Source));
                }
            }
        }
    }
}


text:
> Adapter for the [Jasmine](http://pivotal.github.io/jasmine/) testing framework.

## Installation

**This plugin ships with Karma by default, so you don't need to install it, it should just work ;-)**

The easiest way is to keep `karma-jasmine` as a devDependency in your `package.json`.
```json
{
  "devDependencies": {
    "karma": "~0.9",
    "karma-jasmine": "~0.0.1"
  }
}
```

You can simple do it by:
```bash
npm install karma-jasmine --save-dev
```

## Configuration
```js
// karma.conf.js
module.exports = function(config) {
  config.set({
    frameworks: ['jasmine'],

    files: [
      '*.js'
    ]
  });
};
```

----

For more information on Karma see the [homepage].

[homepage]: http://karma-runner.github.com


text:
package zooowner
package impl

import zooowner.ZKPath._

import org.parboiled2._

import scala.util.{Failure, Success}
import scala.language.postfixOps

import java.util.regex.Pattern

private[zooowner] trait PathSuffixMatcher {
  private type Match = Option[(ZKPath, String)]

  def unapply(input: String): Match = {
    val path = ZKPath.parse(input)
    unapply(path)
  }

  def unapply(path: ZKPath): Match = {
    if (path.isRoot) None
    else Some(path.parent -> path.child)
  }
}

private[zooowner] trait PathPrefixMatcher {
  private type Match = Option[(String, ZKPath)]

  def unapply(input: String): Match = {
    val path = ZKPath.parse(input)
    unapply(path)
  }

  def unapply(path: ZKPath): Match = {
    if (path.isRoot) None
    else Some(path.head -> path.tail)
  }
}

private[zooowner] abstract class ZKStringInterpolator(context: StringContext) {
  // `s` stands for default Scala string interpolation
  def apply(args: Any*) = ZKPath(context.s(args: _*))

  def unapplySeq(path: ZKPath) = {
    val pseudoPath = ZKPath(context.parts.mkString("match"))

    if (pseudoPath.depth != path.depth) None else {
      val quotedParts = context.parts map Pattern.quote
      val regex = quotedParts.mkString("(.+)").r
      regex.unapplySeq(path.asString)
    }
  }
}

private[zooowner] object ZKPathUtils {
  def isComponentValid(component: String) = {
    val noSlash = !(component contains '/')

    noSlash && {
      val parser = new ZKPathParser(component)
      parser.Token.run().isSuccess
    }
  }

  def validateComponent(component: String) = {
    require(
      isComponentValid(component),
      "Invalid path component: " + component)
  }

  def parse(input: String): ZKPath = {
    val parser = new ZKPathParser(input)
    val result = parser.Path.run()

    result match {
      case Success(path) => path
      case Failure(error: ParseError) =>
        throw new InvalidPathException(parser.formatError(error))
      case Failure(other) =>
        throw new InvalidPathException(other.getMessage)
    }
  }
}

private[zooowner] case class ZKPathImpl(components: Seq[String])
  extends ZKPath
{
  def / (child: String) = {
    ZKPathUtils.validateComponent(child)
    this.copy(components :+ child)
  }

  def / (subpath: ZKPath) = this.copy(components ++ subpath.components)

  override def toString = "ZKPath(%s)".format(asString)
  def asString = components.mkString("/", "/", "")

  def isRoot = components.isEmpty

  def child = components.last
  def parent = this.copy(components.init)

  private[zooowner] def tail = this.copy(components.tail)
  private[zooowner] def head = components.head
}

private[zooowner] class ZKPathParser(val input: ParserInput) extends Parser {
  import CharPredicate._

  val ForbiddenToken = Set(".", "..")

  def Check(token: String) = rule {
    test(!(ForbiddenToken contains token)) ~ push(token)
  }

  def Path = rule { (ComponentList | Root) ~ EOI ~> ZKPathImpl }

  def ComponentList = rule { Component + }
  def Component = rule { Slash ~ Token }

  def Token = rule { capture(TokenValue) ~> Check _ }
  def TokenValue = rule { TokenChar + }
  def TokenChar = rule { !Slash ~ Printable }

  def Slash = rule { '/' }
  def Root = rule { capture(Slash) ~> ( _ => Nil ) }
}

// vim: set ts=2 sw=2 et sts=2:


text:
/*global define*/
define([
        '../../Core/Cartesian3',
        '../../Core/defaultValue',
        '../../Core/defined',
        '../../Core/defineProperties',
        '../../Core/DeveloperError',
        '../../Core/Ellipsoid',
        '../../Core/Matrix4',
        '../../Core/Rectangle',
        '../../Scene/Camera',
        '../../Scene/SceneMode',
        '../../ThirdParty/knockout',
        '../createCommand'
    ], function(
        Cartesian3,
        defaultValue,
        defined,
        defineProperties,
        DeveloperError,
        Ellipsoid,
        Matrix4,
        Rectangle,
        Camera,
        SceneMode,
        knockout,
        createCommand) {
    "use strict";

    function viewHome(scene, ellipsoid, duration) {
        var mode = scene.mode;
        var controller = scene.screenSpaceCameraController;

        controller.ellipsoid = ellipsoid;

        if (defined(scene) && mode === SceneMode.MORPHING) {
            scene.completeMorph();
        }

        if (mode === SceneMode.SCENE2D) {
            scene.camera.flyToRectangle({
                destination : Rectangle.MAX_VALUE,
                duration : duration,
                endTransform : Matrix4.IDENTITY
            });
        } else if (mode === SceneMode.SCENE3D) {
            var defaultCamera = new Camera(scene);
            scene.camera.flyTo({
                destination : defaultCamera.position,
                duration : duration,
                up : defaultCamera.up,
                direction : defaultCamera.direction,
                endTransform : Matrix4.IDENTITY
            });
        } else if (mode === SceneMode.COLUMBUS_VIEW) {
            var maxRadii = ellipsoid.maximumRadius;
            var position = new Cartesian3(0.0, -1.0, 1.0);
            position = Cartesian3.multiplyByScalar(Cartesian3.normalize(position, position), 5.0 * maxRadii, position);
            var direction = new Cartesian3();
            direction = Cartesian3.normalize(Cartesian3.subtract(Cartesian3.ZERO, position, direction), direction);
            var right = Cartesian3.cross(direction, Cartesian3.UNIT_Z, new Cartesian3());
            var up = Cartesian3.cross(right, direction, new Cartesian3());

            scene.camera.flyTo({
                destination : position,
                duration : duration,
                up : up,
                direction : direction,
                endTransform : Matrix4.IDENTITY,
                convert : false
            });
        }
    }

    /**
     * The view model for {@link HomeButton}.
     * @alias HomeButtonViewModel
     * @constructor
     *
     * @param {Scene} scene The scene instance to use.
     * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid to be viewed when in home position.
     * @param {Number} [duration=1.5] The duration of the camera flight in seconds.
     */
    var HomeButtonViewModel = function(scene, ellipsoid, duration) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(scene)) {
            throw new DeveloperError('scene is required.');
        }
        //>>includeEnd('debug');

        ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
        duration = defaultValue(duration, 1.5);

        this._scene = scene;
        this._ellipsoid = ellipsoid;
        this._duration = duration;

        var that = this;
        this._command = createCommand(function() {
            viewHome(that._scene, that._ellipsoid, that._duration);
        });

        /**
         * Gets or sets the tooltip.  This property is observable.
         *
         * @type {String}
         */
        this.tooltip = 'View Home';

        knockout.track(this, ['tooltip']);
    };

    defineProperties(HomeButtonViewModel.prototype, {
        /**
         * Gets the scene to control.
         * @memberof HomeButtonViewModel.prototype
         *
         * @type {Scene}
         */
        scene : {
            get : function() {
                return this._scene;
            }
        },

        /**
         * Gets the ellipsoid to be viewed when in home position.
         * @memberof HomeButtonViewModel.prototype
         *
         * @type {Ellipsoid}
         */
        ellipsoid : {
            get : function() {
                return this._ellipsoid;
            }
        },

        /**
         * Gets the Command that is executed when the button is clicked.
         * @memberof HomeButtonViewModel.prototype
         *
         * @type {Command}
         */
        command : {
            get : function() {
                return this._command;
            }
        },

        /**
         * Gets or sets the the duration of the camera flight in seconds.
         * A value of zero causes the camera to instantly switch to home view.
         * @memberof HomeButtonViewModel.prototype
         *
         * @type {Number}
         */
        duration : {
            get : function() {
                return this._duration;
            },
            set : function(value) {
                //>>includeStart('debug', pragmas.debug);
                if (value < 0) {
                    throw new DeveloperError('value must be positive.');
                }
                //>>includeEnd('debug');

                this._duration = value;
            }
        }
    });

    return HomeButtonViewModel;
});


text:
@interface MSTableAuthorItem : TTTableImageItem {
	MSUser *_author;
}

@property (nonatomic, retain) MSUser *author;

+ (id)itemWithAuthor:(MSUser *)author;

@end


text:
require File.dirname(__FILE__) + "/helper"

class ConnectionTest < MiniTest::Unit::TestCase

  def setup
    @directory = Redis::Directory.new(:url => (ENV["REDIS_DIRECTORY"] || "redis://localhost"))

    @redis = @directory.redis
    @redis.hset Redis::Directory::SERVICES_KEY, "cache", [ "redis://localhost" ].to_json
    @redis.hset Redis::Directory::SERVICES_KEY, "sessions", [ "redis://localhost" ].to_json
    @redis.hset Redis::Directory::SERVICES_KEY, "queue", [ "redis://localhost" ].to_json
  end

  def teardown
    @redis.flushall
    @redis.quit
  end

  # Our first test verifies that the "services" key (populated here in #setup) is not empty.
  # Since we can't know the hostname(s) and ports for the Redis members you've setup, you
  # must pre-populate this.
  # This can be as easy as using the redis-cli on the command-line to populate your directory:
  #
  #   redis-cli -h redis.example.com -p 8440 hset services cache '["redis.example.com:9100", "redis.example.com:9101"]'
  #   redis-cli -h redis.example.com -p 8440 hset services sessions '["redis.example.com:9200", "redis.example.com:9201"]'
  #   redis-cli -h redis.example.com -p 8440 hset services queue '["redis.example.com:9300"]'
  #
  # Then +@directory.services+ would be equal to:
  #
  #   {
  #     "cache"     => ["redis.example.com:9100", "redis.example.com:9101"],
  #     "sessions"  => ["redis.example.com:9200", "redis.example.com:9201"],
  #     "queue"     => ["redis.example.com:9300"]
  #   }
  #
  # These are the definitions for your cluster(s) of services.
  # It's recommended that you dedicate individual use-cases to individual clusters.
  # This helps you balance your loads more evenly across multi-core machines
  # (since Redis is single-threaded) as well as allowing you to tune memory limits,
  # flush-to-disk intervals, etc on a per-cluster basis.
  def test_services_are_staticly_assigned
    refute_empty @directory.services
  end

  def test_services_is_a_hash_of_connection_strings
    assert_kind_of Hash, @directory.services
  end

  # Because we use a Redis::Distributed connection, you should consistently
  # use Arrays for your cluster connections even if there is only one item
  # in the cluster.
  def test_service_value_is_an_array
    assert_kind_of Array, @directory.services["queue"]
  end

  # Here we're just confirming that when we ask for it, the next availble
  # database number for a given service is retrieved.
  def test_database_number_is_retrieved
    assert_kind_of Fixnum, @directory.next_db("sessions")
  end

  # If the service/cluster is undefined, then we should raise a
  # UndefinedServiceError when requesting it's next database number.
  def test_database_number_errors_for_service_not_exist
    assert_raises(Redis::Directory::UndefinedServiceError) do
      @directory.next_db("quack")
    end
  end

  # Once we've made a connection (+Redis::Directory#get+), we should be able
  # to confirm that the database we've connected to is for this name.
  def test_database_contains_connection_name
    assert_equal "acme", @directory.get("cache", "acme").get("connection-name")
  end

  # If we reserve a database, it should be tracked in a Hash describing the
  # currently reserved services for that name. That way we can look it up later
  # and re-use it instead of always provisioning new databases every time you
  # make a new request.
  def test_database_is_reserved
    @directory.reserve("cache", "acme")
    assert @redis.hexists("cache-service", "acme")
    refute_nil @redis.hget("cache-service", "acme")
  end

  # This test confirms an internal implementation detail, ensuring that we don't
  # have collisions between multiple database names for a given service.
  def test_additional_cache_connection_increments
    @directory.reserve("cache", "acme")
    @directory.reserve("cache", "trioptimum")
    assert_equal @redis.hlen("cache-service"), @redis.hget("cache-service", "trioptimum").to_i
  end

  # When there are "gaps" in the list of tracked databases for a service, those
  # should be filled to keep the maximum database number as low as possible.
  # This way as long as you clean up disused databases by removing them from the
  # service keys, eg:
  #
  #   redis-cli hdel cache-service acme
  #
  # Then we'll re-use that database number, meaning that as long as you've set
  # (in your redis.conf) your maximum databases equal to or great than the number
  # you plan to use, +Redis::Directory+ should not exceed that number.
  def test_sparse_ids_are_filled
    @redis.hset("cache-service", "corporatron", 5)

    @directory.reserve("cache", "bnl")
    assert_equal 1, @redis.hget("cache-service", "bnl").to_i

    @directory.reserve("cache", "axiom")
    assert_equal 2, @redis.hget("cache-service", "axiom").to_i
  end

  # In order to use as few database numbers as possible, and again, allowing you
  # to tune Redis configuration settings like +databases+ on a per service/cluster
  # basis, database numbers may not be consistent across services/clusters for a
  # given client/name. This is especially true if not all clients consume all services,
  # as the example below demonstrates.
  def test_database_ids_are_unbalanced
    bnl     = @directory.reserve("cache", "bnl")
    hacker  = @directory.reserve("cache", "trioptimum")
    acme    = @directory.reserve("cache", "acme")

    shodan  = @directory.reserve("sessions", "trioptimum")

    refute_equal hacker, shodan
  end

end


text:
<!DOCTYPE html>

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

    <title>Full Slider - Start Bootstrap Template</title>

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

    <link href="css/full-slider.css" rel="stylesheet">

    <audio controls autoplay hidden>
  <source src="horse.ogg" type="audio/ogg">
  <source src="media/sample.mp3" type="audio/mpeg">
  Your browser does not support the audio element.
</audio>

    <audio><source src="media/sample.mp3" type="audio/mpeg" /></audio>

Recipe Credits to Live Love Pasta.

Designed by Andrea Deng.


text:
package com.anpmech.mpd.concurrent;

import com.anpmech.mpd.commandresponse.CommandResponse;
import com.anpmech.mpd.connection.CommandResult;

/**
 * This class returns a {@link CommandResponse} in the future.
 */
public class ResponseFuture extends MPDFuture<CommandResponse> {

    /**
     * The sole constructor.
     *
     * @param future The ResultFuture to wrap with the {@link CommandResponse} future.
     */
    public ResponseFuture(final ResultFuture future) {
        super(future);
    }

    /**
     * This method is used to construct the Future object for this result.
     *
     * @param result The result to create the MPDFuture from.
     * @return A MPDFuture subclass.
     */
    @Override
    CommandResponse instantiate(final CommandResult result) {
        return new CommandResponse(result);
    }
}


text:
$ErrorActionPreference = 'Stop'

$toolsPath = Split-Path $MyInvocation.MyCommand.Definition

$fileName = 'Composer-Setup.6.1.0.exe'

$packageArgs = @{
  packageName  = 'composer'
  fileType     = 'exe'
  file         = Get-Item $toolsPath\$fileName
  checksum     = 'F3FE32CCCDF21E0E58DAF505823D2B9426AF6A4F754318217F9E6E23744AF781'
  checksumType = 'sha256'
  silentArgs   = '/VERYSILENT /SUPPRESSMSGBOXES /NORESTART'
  softwareName = 'composer*'
}

try {
  Install-ChocolateyInstallPackage @packageArgs
  Get-ChildItem $toolsPath\*.exe | ForEach-Object { Remove-Item $_ -ea 0; if (Test-Path $_) { Set-Content "$_.ignore" '' } }
}
catch {

  if ($env:ChocolateyExitCode -eq '1') {
    Write-Host ""
    Write-Host "*** IMPORTANT ***"
    Write-Host "The installation failed. Your PHP or other settings are incorrect."
    Write-Host "  Use the --notsilent option to run the installer interactively."
    Write-Host ""
  }
}


text:
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using AvansApp.ViewModels.Pages;

namespace AvansApp.Views
{
    public sealed partial class AnnouncementsPage : Page
    {
        private AnnouncementPageViewModel ViewModel
        {
            get { return DataContext as AnnouncementPageViewModel; }
        }

        public AnnouncementsPage()
        {
            InitializeComponent();
        }

        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            ViewModel.Initialize();
            await ViewModel.LoadDataAsync(WindowStates.CurrentState);
        }
    }
}


text:
#include "ODataService.h"
#include "ODataConstants.h"

#include "ODataNetworkManager.h"

/*
 * CONSTRUCTORS / DESCTRUCTORS
 */

ODataService::ODataService(QObject* parent) : QObject(parent)
{
}

ODataService::ODataService(QString source, Format f, QObject* parent) : QObject(parent)
{
    setFormat(f);
    setSource(source);
}

ODataService::~ODataService() {
}

/*
 * PROPERTIES
 */

QString ODataService::getSource(){
    return mSource;
}
void ODataService::setSource(const QString& newSource){
    mSource = newSource;

    mServiceDefinition.clear();
    mMetadata.clear();
    loadData();

    emit sourceChanged();
}

ODataService::Format ODataService::getFormat() {
    return mFormat;
}

void ODataService::setFormat(Format f) {
    mFormat = f;
}

/*
 * FUNCTIONS
 */

void ODataService::loadData(){
    ODataNetworkManager* manager = new ODataNetworkManager();
    manager->setFormat(mFormat);
    manager->read(mSource);

    connect(manager, SIGNAL(jsonReady(const QVariant&)), this, SLOT(jsonDefinitionReadComplete(const QVariant&)));
    connect(manager, SIGNAL(atomReady(const QVariant&)), this, SLOT(xmlDefinitionReadComplete(const QVariant&)));
    connect(manager, SIGNAL(xmlReady(const QVariant&)), this, SLOT(xmlDefinitionReadComplete(const QVariant&)));

    // we want to connect this to a different SLOT so we need a new one
    ODataNetworkManager* metaManager = new ODataNetworkManager();
    metaManager->setFormat(ODataService::XML);
    metaManager->read(mSource + "/" + OData::METADATA);

    connect(metaManager, SIGNAL(atomReady(const QVariant&)), this, SLOT(metadataReadComplete(const QVariant&)));
    connect(metaManager, SIGNAL(xmlReady(const QVariant&)), this, SLOT(metadataReadComplete(const QVariant&)));
}

QVariant ODataService::getServiceDefinition() {
    return mServiceDefinition;
}

QVariant ODataService::getMetadata() {
    return mMetadata;
}

/*
 * SLOTS
 */

// for now lets just store the values we get back

void ODataService::jsonDefinitionReadComplete(const QVariant& response){
    mServiceDefinition = response.toMap()["value"];
    emit definitionReady();
}

void ODataService::xmlDefinitionReadComplete(const QVariant& response){
    mServiceDefinition = response.toMap()[OData::WORKSPACE];
    emit definitionReady();
}

void ODataService::metadataReadComplete(const QVariant& response){
    mMetadata = response.toMap()[OData::EDMX_DATASERVICES].toMap()[OData::SCHEMA];

    emit metadataReady();
}


text:
/* Media controls for Chromium on Android */

/* WARNING: This css file can only style <audio> and <video> elements */

audio {
    height: 48px;
}

audio::-webkit-media-controls-enclosure, video::-webkit-media-controls-enclosure {
    height: 48px;
}

audio::-webkit-media-controls-panel, video::-webkit-media-controls-panel {
    height: 48px;
    min-width: 48px;
    line-height: 48px;
    font-size: 14px;
}

audio::-webkit-media-controls-mute-button, video::-webkit-media-controls-mute-button {
    padding: 8px;
    width: 48px;
    height: 48px;
}

video::-internal-media-controls-overlay-cast-button {
    width: 48px;
    height: 48px;
}

audio::-webkit-media-controls-play-button, video::-webkit-media-controls-play-button {
    padding: 8px;
    width: 48px;
    height: 48px;
}

audio::-webkit-media-controls-timeline-container, video::-webkit-media-controls-timeline-container {
    height: 48px;
}

audio::-webkit-media-controls-current-time-display, video::-webkit-media-controls-current-time-display {
    height: 48px;
}

audio::-webkit-media-controls-time-remaining-display, video::-webkit-media-controls-time-remaining-display {
    height: 48px;
}

audio::-webkit-media-controls-fullscreen-button, video::-webkit-media-controls-fullscreen-button {
    padding: 8px;
    width: 48px;
    height: 48px;
}

audio::-internal-media-controls-cast-button, video::-internal-media-controls-cast-button {
    padding: 8px;
    width: 48px;
    height: 48px;
}

video::-webkit-media-controls-toggle-closed-captions-button {
    padding: 8px;
    width: 48px;
    height: 48px;
}


text:
CREATE OR REPLACE TEMPORARY VIEW testData AS SELECT * FROM VALUES
(null, "a"), (1, "a"), (1, "a"), (2, "a"), (1, "b"), (2, "b"), (3, "b"), (null, null), (3, null)
AS testData(val, cate);

-- RowsBetween
SELECT val, cate, count(val) OVER(PARTITION BY cate ORDER BY val ROWS CURRENT ROW) FROM testData
ORDER BY cate, val;
SELECT val, cate, sum(val) OVER(PARTITION BY cate ORDER BY val
ROWS BETWEEN UNBOUNDED PRECEDING AND 1 FOLLOWING) FROM testData ORDER BY cate, val;

-- RangeBetween
SELECT val, cate, count(val) OVER(PARTITION BY cate ORDER BY val RANGE 1 PRECEDING) FROM testData
ORDER BY cate, val;
SELECT val, cate, sum(val) OVER(PARTITION BY cate ORDER BY val
RANGE BETWEEN CURRENT ROW AND 1 FOLLOWING) FROM testData ORDER BY cate, val;

-- RangeBetween with reverse OrderBy
SELECT val, cate, sum(val) OVER(PARTITION BY cate ORDER BY val DESC
RANGE BETWEEN CURRENT ROW AND 1 FOLLOWING) FROM testData ORDER BY cate, val;

-- Window functions
SELECT val, cate,
max(val) OVER w AS max,
min(val) OVER w AS min,
min(val) OVER w AS min,
count(val) OVER w AS count,
sum(val) OVER w AS sum,
avg(val) OVER w AS avg,
stddev(val) OVER w AS stddev,
first_value(val) OVER w AS first_value,
first_value(val, true) OVER w AS first_value_ignore_null,
first_value(val, false) OVER w AS first_value_contain_null,
last_value(val) OVER w AS last_value,
last_value(val, true) OVER w AS last_value_ignore_null,
last_value(val, false) OVER w AS last_value_contain_null,
rank() OVER w AS rank,
dense_rank() OVER w AS dense_rank,
cume_dist() OVER w AS cume_dist,
percent_rank() OVER w AS percent_rank,
ntile(2) OVER w AS ntile,
row_number() OVER w AS row_number,
var_pop(val) OVER w AS var_pop,
var_samp(val) OVER w AS var_samp,
approx_count_distinct(val) OVER w AS approx_count_distinct
FROM testData
WINDOW w AS (PARTITION BY cate ORDER BY val)
ORDER BY cate, val;

-- Null inputs
SELECT val, cate, avg(null) OVER(PARTITION BY cate ORDER BY val) FROM testData ORDER BY cate, val;

-- OrderBy not specified
SELECT val, cate, row_number() OVER(PARTITION BY cate) FROM testData ORDER BY cate, val;

-- Over clause is empty
SELECT val, cate, sum(val) OVER(), avg(val) OVER() FROM testData ORDER BY cate, val;

-- first_value()/last_value() over ()
SELECT val, cate,
first_value(false) OVER w AS first_value,
first_value(true, true) OVER w AS first_value_ignore_null,
first_value(false, false) OVER w AS first_value_contain_null,
last_value(false) OVER w AS last_value,
last_value(true, true) OVER w AS last_value_ignore_null,
last_value(false, false) OVER w AS last_value_contain_null
FROM testData
WINDOW w AS ()
ORDER BY cate, val;


text:
/*
 * ply_source.h
 *
 *  Created on: Mar 9, 2012
 *      Author: aitor
 */

#ifndef REC_FRAMEWORK_MESH_SOURCE_H_
#define REC_FRAMEWORK_MESH_SOURCE_H_

#include <pcl/apps/3d_rec_framework/pc_source/source.h>
#include <pcl/io/io.h>
#include <pcl/io/pcd_io.h>
#include <pcl/visualization/pcl_visualizer.h>

namespace pcl
{
  namespace rec_3d_framework
  {

    /**
     * \brief Data source class based on partial views from sensor.
     * In this case, the training data is obtained directly from a depth sensor.
     * The filesystem should contain pcd files (representing a view of an object in
     * camera coordinates) and each view needs to be associated with a txt file
     * containing a 4x4 matrix representing the transformation from camera coordinates
     * to a global object coordinates frame.
     * \author Aitor Aldoma
     */

    template<typename PointInT>
      class RegisteredViewsSource : public Source<PointInT>
      {
        typedef Source<PointInT> SourceT;
        typedef Model<PointInT> ModelT;

        using SourceT::path_;
        using SourceT::models_;
        using SourceT::createTrainingDir;
        using SourceT::getModelsInDirectory;
        using SourceT::model_scale_;

        std::string view_prefix_;
        int pose_files_order_; //0 is row, 1 is column

      public:
        RegisteredViewsSource ()
        {
          view_prefix_ = std::string ("view");
          pose_files_order_ = 0;
        }

        void
        setPrefix (std::string & pre)
        {
          view_prefix_ = pre;
        }

        void
        setPoseRowOrder (int o)
        {
          pose_files_order_ = o;
        }

        void
        getViewsFilenames (bf::path & path_with_views, std::vector<std::string> & view_filenames)
        {
          int number_of_views = 0;
          bf::directory_iterator end_itr;
          for (bf::directory_iterator itr (path_with_views); itr != end_itr; ++itr)
          {
            if (!(bf::is_directory (*itr)))
            {
              std::vector < std::string > strs;
              std::vector < std::string > strs_;

#if BOOST_FILESYSTEM_VERSION == 3
              std::string file = (itr->path ().filename ()).string();
#else
              std::string file = (itr->path ()).filename ();
#endif

              boost::split (strs, file, boost::is_any_of ("."));
              boost::split (strs_, file, boost::is_any_of ("_"));

              std::string extension = strs[strs.size () - 1];

              if (extension == "pcd" && (strs_[0].compare (view_prefix_) == 0))
              {
#if BOOST_FILESYSTEM_VERSION == 3
                view_filenames.push_back ((itr->path ().filename ()).string());
#else
                view_filenames.push_back ((itr->path ()).filename ());
#endif

                number_of_views++;
              }
            }
          }
        }

        void
        assembleModelFromViewsAndPoses(ModelT & model, std::vector<Eigen::Matrix4f, Eigen::aligned_allocator<Eigen::Matrix4f> > & poses) {
          for(size_t i=0; i < model.views_->size(); i++) {
            Eigen::Matrix4f inv = poses[i];
            typename pcl::PointCloud<PointInT>::Ptr global_cloud(new pcl::PointCloud<PointInT>);
            pcl::transformPointCloud(*(model.views_->at(i)),*global_cloud, inv);
            *(model.assembled_) += *global_cloud;
          }
        }

        void
        loadOrGenerate (std::string & dir, std::string & model_path, ModelT & model)
        {
          std::stringstream pathmodel;
          pathmodel << dir << "/" << model.class_ << "/" << model.id_;
          bf::path trained_dir = pathmodel.str ();

          model.views_.reset (new std::vector<typename pcl::PointCloud<PointInT>::Ptr>);
          model.poses_.reset (new std::vector<Eigen::Matrix4f, Eigen::aligned_allocator<Eigen::Matrix4f> >);
          model.self_occlusions_.reset (new std::vector<float>);

          if (bf::exists (trained_dir))
          {
            //load views and poses
            std::vector < std::string > view_filenames;
            int number_of_views = 0;
            bf::directory_iterator end_itr;
            for (bf::directory_iterator itr (trained_dir); itr != end_itr; ++itr)
            {
              //check if its a directory, then get models in it
              if (!(bf::is_directory (*itr)))
              {
                //check that it is a ply file and then add, otherwise ignore..
                std::vector < std::string > strs;
                std::vector < std::string > strs_;

#if BOOST_FILESYSTEM_VERSION == 3
                std::string file = (itr->path ().filename ()).string();
#else
                std::string file = (itr->path ()).filename ();
#endif

                boost::split (strs, file, boost::is_any_of ("."));
                boost::split (strs_, file, boost::is_any_of ("_"));

                std::string extension = strs[strs.size () - 1];

                if (extension == "pcd" && strs_[0] == "view")
                {
#if BOOST_FILESYSTEM_VERSION == 3
                  view_filenames.push_back ((itr->path ().filename ()).string());
#else
                  view_filenames.push_back ((itr->path ()).filename ());
#endif

                  number_of_views++;
                }
              }
            }

            std::vector<Eigen::Matrix4f, Eigen::aligned_allocator<Eigen::Matrix4f> > poses_to_assemble_;

            for (size_t i = 0; i < view_filenames.size (); i++)
            {
              std::stringstream view_file;
              view_file << pathmodel.str () << "/" << view_filenames[i];
              typename pcl::PointCloud<PointInT>::Ptr cloud (new pcl::PointCloud<PointInT> ());
              pcl::io::loadPCDFile (view_file.str (), *cloud);

              model.views_->push_back (cloud);

              std::string file_replaced1 (view_filenames[i]);
              boost::replace_all (file_replaced1, "view", "pose");
              boost::replace_all (file_replaced1, ".pcd", ".txt");

              //read pose as well
              std::stringstream pose_file;
              pose_file << pathmodel.str () << "/" << file_replaced1;
              Eigen::Matrix4f pose;
              PersistenceUtils::readMatrixFromFile (pose_file.str (), pose);

              if(pose_files_order_ != 0) {
                //std::cout << "Transpose..." << std::endl;

                Eigen::Matrix4f pose_trans = pose.transpose();
                poses_to_assemble_.push_back(pose_trans);
                //pose = pose_trans;
                //std::cout << pose << std::endl;
              }

              //std::cout << "pose being push backed to model" << std::endl;
              std::cout << pose << std::endl;

              //the recognizer assumes transformation from M to CC
              Eigen::Matrix4f inv = pose.inverse();
              model.poses_->push_back (inv);

              model.self_occlusions_->push_back (-1.f);

            }

            model.assembled_.reset (new pcl::PointCloud<PointInT>);
            assembleModelFromViewsAndPoses(model, poses_to_assemble_);

            /*pcl::visualization::PCLVisualizer vis ("results");
            pcl::visualization::PointCloudColorHandlerCustom<PointInT> random_handler (model.assembled_, 255, 0, 0);
            vis.addPointCloud<PointInT> (model.assembled_, random_handler, "points");

            Eigen::Matrix4f view_transformation = model.poses_->at(0).inverse();
            typename pcl::PointCloud<PointInT>::Ptr view_trans(new pcl::PointCloud<PointInT>);
            pcl::transformPointCloud(*(model.views_->at(0)), *view_trans, view_transformation);

            pcl::visualization::PointCloudColorHandlerCustom<PointInT> random_handler2 (view_trans, 0, 255, 0);
            vis.addPointCloud<PointInT> (view_trans, random_handler2, "view");

            vis.addCoordinateSystem(0.1);
            vis.spin ();*/

          }
          else
          {

            //we just need to copy the views to the training directory
            std::stringstream direc;
            direc << dir << "/" << model.class_ << "/" << model.id_;
            createClassAndModelDirectories (dir, model.class_, model.id_);

            std::vector < std::string > view_filenames;
            bf::path model_dir = model_path;

            getViewsFilenames (model_dir, view_filenames);
            std::cout << view_filenames.size () << std::endl;

            for (size_t i = 0; i < view_filenames.size (); i++)
            {
              std::stringstream view_file;
              view_file << model_path << "/" << view_filenames[i];
              typename pcl::PointCloud<PointInT>::Ptr cloud (new pcl::PointCloud<PointInT> ());
              pcl::io::loadPCDFile (view_file.str (), *cloud);

              std::cout << view_file.str () << std::endl;

              std::stringstream path_view;
              path_view << direc.str () << "/view_" << i << ".pcd";
              pcl::io::savePCDFileBinary (path_view.str (), *cloud);

              std::string file_replaced1 (view_file.str ());
              boost::replace_all (file_replaced1, view_prefix_, "pose");
              boost::replace_all (file_replaced1, ".pcd", ".txt");

              Eigen::Matrix4f pose;
              PersistenceUtils::readMatrixFromFile (file_replaced1, pose);

              std::cout << pose << std::endl;

              if(pose_files_order_ == 0) {
                std::cout << "Transpose..." << std::endl;
                Eigen::Matrix4f pose_trans = pose.transpose();
                pose = pose_trans;
                std::cout << pose << std::endl;
              }

              std::stringstream path_pose;
              path_pose << direc.str () << "/pose_" << i << ".txt";
              pcl::rec_3d_framework::PersistenceUtils::writeMatrixToFile (path_pose.str (), pose);
            }

            loadOrGenerate (dir, model_path, model);

          }
        }

        bool
        isleafDirectory (bf::path & path)
        {
          bf::directory_iterator end_itr;
          bool no_dirs_inside = true;
          for (bf::directory_iterator itr (path); itr != end_itr; ++itr)
          {
            if (bf::is_directory (*itr))
            {
              no_dirs_inside = false;
            }
          }

          return no_dirs_inside;
        }

        void
        getModelsInDirectory (bf::path & dir, std::string & rel_path_so_far, std::vector<std::string> & relative_paths)
        {
          bf::directory_iterator end_itr;
          for (bf::directory_iterator itr (dir); itr != end_itr; ++itr)
          {
            //check if its a directory, then get models in it
            if (bf::is_directory (*itr))
            {
#if BOOST_FILESYSTEM_VERSION == 3
              std::string so_far = rel_path_so_far + (itr->path ().filename ()).string() + "/";
#else
              std::string so_far = rel_path_so_far + (itr->path ()).filename () + "/";
#endif

              bf::path curr_path = itr->path ();

              if (isleafDirectory (curr_path))
              {
#if BOOST_FILESYSTEM_VERSION == 3
                std::string path = rel_path_so_far + (itr->path ().filename ()).string();
#else
                std::string path = rel_path_so_far + (itr->path ()).filename ();
#endif
                relative_paths.push_back (path);

              }
              else
              {
                getModelsInDirectory (curr_path, so_far, relative_paths);
              }
            }
          }
        }

        /**
         * \brief Creates the model representation of the training set, generating views if needed
         */
        void
        generate (std::string & training_dir)
        {

          //create training dir fs if not existent
          createTrainingDir (training_dir);

          //get models in directory
          std::vector < std::string > files;
          std::string start = "";
          bf::path dir = path_;
          getModelsInDirectory (dir, start, files);

          models_.reset (new std::vector<ModelT>);

          for (size_t i = 0; i < files.size (); i++)
          {
            ModelT m;

            std::vector < std::string > strs;
            boost::split (strs, files[i], boost::is_any_of ("/\\"));
            std::string name = strs[strs.size () - 1];

            if (strs.size () == 1)
            {
              m.id_ = strs[0];
            }
            else
            {
              std::stringstream ss;
              for (int i = 0; i < (static_cast<int> (strs.size ()) - 1); i++)
              {
                ss << strs[i];
                if (i != (static_cast<int> (strs.size ()) - 1))
                  ss << "/";
              }

              m.class_ = ss.str ();
              m.id_ = strs[strs.size () - 1];
            }

            std::cout << m.class_ << " . " << m.id_ << std::endl;
            //check which of them have been trained using training_dir and the model_id_
            //load views, poses and self-occlusions for those that exist
            //generate otherwise

            std::stringstream model_path;
            model_path << path_ << "/" << files[i];
            std::string path_model = model_path.str ();
            loadOrGenerate (training_dir, path_model, m);

            models_->push_back (m);

            //std::cout << files[i] << std::endl;
          }
        }
      };
  }
}

#endif /* REC_FRAMEWORK_MESH_SOURCE_H_ */


text:
package main

import (
	"fmt"
	"net/http"
	"time"

	"github.com/antongulenko/http-isolation-proxy/services"
	"github.com/antongulenko/http-isolation-proxy/services/service_catalog/catalogApi"
	"github.com/antongulenko/http-isolation-proxy/services/service_payment/paymentApi"
)

const (
	order_lock_prefix           = "order_lock/"
	order_scan_interval         = 1 * time.Second
	order_processing_expiration = 10 * time.Second
)

func (shop *Shop) LoopScanOrders(ids chan<- string) {
	for {
		start := time.Now()
		shop.scanOrders(ids)
		if delta := time.Now().Sub(start); delta < order_scan_interval {
			// Some delay to avoid constant load on Redis
			time.Sleep(order_scan_interval - delta)
		}
	}
}

func (shop *Shop) scanOrders(ids chan<- string) (result uint) {
	open_orders, err := shop.redis.Cmd("smembers", open_orders_key).List()
	if err != nil {
		services.L.Logf("Error retrieving list of open orders: %v", err)
		return
	}
	for _, order_id := range open_orders {
		ids <- order_id
		result++
	}
	return
}

func (shop *Shop) LoopProcessOrders(ids <-chan string) {
	for order_id := range ids {
		shop.processOrder(order_id)
	}
}

func (shop *Shop) processOrder(order_id string) {
	lock := services.RedisLock{
		Client:     shop.redis,
		LockName:   order_lock_prefix + order_id,
		LockValue:  shop.redisLockValue,
		Expiration: order_processing_expiration,
	}
	order := shop.MakeOrder(order_id)

	if err := lock.TryLock(); err != nil {
		// Somebody processing this order already
		return
	}
	defer func() {
		if err := lock.Unlock(); err != nil {
			services.L.Logf("Error unlocking order %v after processing: %v", order_id, err)
		}
	}()

	// Loading once is enough: all further calls are completely idempontent
	// The locking is purely for performance, to avoid unnecessary HTTP calls from multiple shop instances
	existed, err := order.LoadExisting()
	if err != nil {
		services.L.Logf("Error retrieving order: %v", err)
	} else if !existed {
		services.L.Warnf("Locked order %v does not exist", order_id)
	}

	item, err := catalogApi.GetItem(shop.catalogEndpoint, order.Item)
	if err != nil {
		services.L.Warnf("Failed to retrieve item '%s' for order processing: %v", order.Item, err)
	}
	shop.doProcessOrder(order, item)
}

func (shop *Shop) doProcessOrder(order *Order, item *catalogApi.Item) {
	if order.assertShipment(item) &&
		order.assertPayment(item) &&
		order.commitShipment() &&
		order.commitPayment() &&
		order.deliverShipment() {
		order.Finalize()
	}
}

func (order *Order) assertShipment(item *catalogApi.Item) bool {
	if order.ShipmentId == "" {
		id, err := catalogApi.ShipItem(order.shop.catalogEndpoint, order.Item, order.User, order.Quantity, order.Timestamp)
		if err != nil {
			services.L.Logf("Failed to create item shipment: %v", err)
			return false
		}
		order.ShipmentId = id
		if err := order.Save(); err != nil {
			services.L.Logf("Failed to store shipment ID for order: %v", err)
			return false
		}
	}
	return true
}

func (order *Order) assertPayment(item *catalogApi.Item) bool {
	if order.PaymentId == "" {
		totalCost := float64(order.Quantity) * item.Cost
		id, err := paymentApi.CreatePayment(order.shop.paymentEndpoint, order.User, totalCost, order.Timestamp)
		if err != nil {
			services.L.Logf("Failed to create payment: %v", err)
			return false
		}
		order.PaymentId = id
		if err := order.Save(); err != nil {
			services.L.Logf("Failed to store payment ID for order: %v", err)
			return false
		}
	}
	return true
}

func (order *Order) shipmentStatus() catalogApi.ShipmentStatus {
	shipment, err := catalogApi.GetShipment(order.shop.catalogEndpoint, order.ShipmentId)
	if order.checkError(err) {
		return ""
	}
	return shipment.Status
}

func (order *Order) checkShipmentStatus(expectedStatus catalogApi.ShipmentStatus) bool {
	if shipmentStatus := order.shipmentStatus(); shipmentStatus == "" {
		return false
	} else if shipmentStatus != expectedStatus {
		services.L.Logf("Shipment %v did not change to status %v (instead %v)", order.ShipmentId, expectedStatus, shipmentStatus)
		return false
	}
	return true
}

func (order *Order) commitShipment() bool {
	shipmentStatus := order.shipmentStatus()
	if shipmentStatus == "" {
		return false
	}
	switch shipmentStatus {
	case catalogApi.ShipmentCreated:
		err := catalogApi.CommitShipment(order.shop.catalogEndpoint, order.ShipmentId)
		if order.checkError(err) {
			return false
		}
		return order.checkShipmentStatus(catalogApi.ShipmentCommitted)
	case catalogApi.ShipmentCommitted, catalogApi.ShipmentDelivered:
		return true
	default:
		order.Cancel(fmt.Errorf("Shipment has status %v", shipmentStatus))
		return false
	}
}

func (order *Order) commitPayment() bool {
	payment, err := paymentApi.FetchPayment(order.shop.paymentEndpoint, order.PaymentId)
	if order.checkError(err) {
		return false
	}
	switch payment.Status {
	case paymentApi.PaymentCreated, paymentApi.PaymentPending:
		err := paymentApi.CommitPayment(order.shop.paymentEndpoint, order.PaymentId)
		_ = order.checkError(err)
		// TODO maybe check that state changed to committed?
		return false
	case paymentApi.PaymentCommitted:
		// Waiting for payment to be processed
		return false
	case paymentApi.PaymentProcessed:
		return true
	default:
		order.Cancel(fmt.Errorf("Payment has status %v", payment.Status))
		return false
	}
}

func (order *Order) deliverShipment() bool {
	err := catalogApi.DeliverShipment(order.shop.catalogEndpoint, order.ShipmentId)
	if order.checkError(err) {
		return false
	}
	return order.checkShipmentStatus(catalogApi.ShipmentDelivered)
}

func isConflictError(err error) bool {
	if httpErr, ok := err.(*services.HttpStatusError); ok {
		return httpErr.Code == http.StatusConflict
	}
	return false
}

// Return true, if we should retry later.
// In case of a CONFLICT 408 status, cancel the order.
func (order *Order) checkError(err error) bool {
	if err == nil {
		return false
	}
	if isConflictError(err) {
		order.Cancel(err)
		return true
	}
	services.L.Logf("Error processing order %v: %v", order.id, err)
	return true
}

func (order *Order) Finalize() {
	services.L.Logf("Finalizing order %v", order.id)
	logStr := "Order processed successfully"
	if err := order.doCancel(true, logStr); err != nil {
		services.L.Logf("Finalizing order %v failed: %v", order.id, err)
	}
}

func (order *Order) Cancel(cause error) {
	services.L.Logf("Cancelling order %v because of: %v", order.id, cause)
	logStr := fmt.Sprintf("Cancelling because of: %v", cause)
	if err := order.doCancel(false, logStr); err != nil {
		services.L.Logf("Cancelling order %v failed: %v", order.id, err)
	}
}

// On non-conflict errors, retry cancelling the order later
func (order *Order) doCancel(success bool, log string) error {
	cancelLog := log

	// Try to cancel the shipment, if necessary
	shipment, err := catalogApi.GetShipment(order.shop.catalogEndpoint, order.ShipmentId)
	if err != nil {
		return err
	}
	if !success && shipment.Status != catalogApi.ShipmentCancelled {
		err := catalogApi.CancelShipment(order.shop.catalogEndpoint, order.ShipmentId)
		if err != nil {
			if isConflictError(err) {
				cancelLog += fmt.Sprintf("\nError cancelling shipment: %v", err)
			} else {
				return err
			}
		} else {
			cancelLog += "\nShipment cancelled"
		}
	} else {
		cancelLog += "\nShipment " + string(shipment.Status)
	}

	// Try to cancel the payment, if necessary
	payment, err := paymentApi.FetchPayment(order.shop.paymentEndpoint, order.PaymentId)
	if err != nil {
		return err
	}
	if !success && payment.Status != paymentApi.PaymentFailed {
		err := paymentApi.CancelPayment(order.shop.paymentEndpoint, order.PaymentId)
		if err != nil {
			if isConflictError(err) {
				cancelLog += fmt.Sprintf("\nError cancelling payment: %v", err)
			} else {
				return err
			}
		} else {
			cancelLog += "\nPayment cancelled"
		}
	}
	cancelLog += "\nPayment was " + payment.Status
	if payment.Error != "" {
		cancelLog += ", error: " + payment.Error
	}

	// Remove the order from the list of open orders & store cancel log
	return order.shop.redis.Transaction(func(redis services.Redis) error {
		order.Status = cancelLog
		err := redis.Cmd("srem", open_orders_key, order.id).Err()
		if err != nil {
			return err
		}
		return order.SaveIn(redis)
	})
}


text:
import path from "path";

import _ from "lodash";
import Promise from "bluebird";
import request from "request";

import jsonDiff from "../util/json-diff";
import * as Errors from "../errors";

function getSelectedHandler (drydock, routeName) {
  const route = _.find(drydock.routes, { name: routeName });
  return route.handlers[route.selectedHandler];
}

function filterRequest (req) {
  return _.chain(req)
    .pick("headers", "payload", "params", "query")
    .cloneDeep()
    .value();
}

function getHandlerContext (drydock, req) {
  return {
    state: drydock.state,
    cookies: _.cloneDeep(req.state) || {},
    headers: {},
    cookieDomain: null
  };
}

function updateCookieState (reply, originalCookies, modifiedCookies, settings) {
  const cookiesDiff = jsonDiff(originalCookies, modifiedCookies);
  // jsonDiff does deep-diff; we just want shallow modifiedCookies[key]
  _.each(cookiesDiff.add, (val, key) => reply.state(key, modifiedCookies[key], settings));
  _.each(cookiesDiff.del, (val, key) => reply.state(key, "", settings));
}

function getHandlerArgs (req, handler) {
  const handlerArgs = [ filterRequest(req) ];

  if (handler.optionsType === "selectOne") {
    handlerArgs.push(handler.options[handler.selectedOption]);
  } else if (handler.optionsType === "selectMany") {
    handlerArgs.push(_.map(handler.selectedOptions, optionName => handler.options[optionName]));
  }

  return handlerArgs;
}

function getStatusCode(defaultCode, handlerCxt, handlerArgs) {
  return (typeof defaultCode === 'function') ?
            defaultCode.apply(handlerCxt, handlerArgs) :
            defaultCode;
}

function defineDynamicRoutes (drydock) {
  drydock._initial.routes.forEach(routeCfg => {
    drydock.server.route({
      method: routeCfg.method,
      path: routeCfg.path,
      vhost: routeCfg.hostname,
      handler: (req, reply) => {
        const drydockHandler = getSelectedHandler(drydock, routeCfg.name);
        const handlerCxt = getHandlerContext(drydock, req);
        const handlerArgs = getHandlerArgs(req, drydockHandler);

        Promise.resolve()
          .then(() => drydockHandler.handler.apply(handlerCxt, handlerArgs))
          .then(response => {
            return {
              payload: response,
              type: routeCfg.type,
              code: getStatusCode(routeCfg.defaultCode, handlerCxt, handlerArgs) || 200
            };
          })
          .catch(Errors.HttpError, err => ({
            payload: err.payload,
            type: err.type,
            code: err.code
          }))
          .then(responseOptions => setTimeout(() => {
            const r = reply(responseOptions.payload)
              .type(responseOptions.type)
              .code(responseOptions.code);

            updateCookieState(r, req.state, handlerCxt.cookies, {
              encoding: drydock.cookieEncoding,
              domain: handlerCxt.cookieDomain
            });

            _.each(handlerCxt.headers, (val, key) => r.header(key, val));

          }, drydock.delay || 0));
      }
    });
  });
}

function defineHapiRoutes (drydock) {
  drydock._initial.hapiRoutes.forEach(drydock.server.route.bind(drydock.server));
}

function defineStaticRoutes (drydock) {
  drydock._initial.staticRoutes.forEach(routeCfg => {
    if (routeCfg.type === "directory") {
      drydock.server.route({
        method: "GET",
        path: path.join(routeCfg.urlPath, "{param*}"),
        handler: {
          directory: {
            path: routeCfg.filePath
          }
        }
      });
    } else if (routeCfg.type === "file") {
      drydock.server.route({
        method: "GET",
        path: routeCfg.urlPath,
        handler: (req, reply) => reply.file(routeCfg.filePath)
      });
    }
  });
}

function defineProxyRoutes (drydock) {
  drydock._initial.proxyRoutes.forEach(proxyRoute => {
    drydock.server.route({
      method: proxyRoute.method,
      path: proxyRoute.path,
      handler: (req, reply) => {
        const { method, headers, payload } = req;

        delete headers.host;

        const url = _.isFunction(proxyRoute.forwardTo) ?
          proxyRoute.forwardTo(req) :
          proxyRoute.forwardTo;

        request({
          url,
          method,
          headers,
          body: payload,
          encoding: null
        }, (err, { statusCode, body, headers: responseHeaders }) => {
          if (err) {
            // eslint-disable-next-line no-console
            console.log(`Unable to proxy HTTP request: ${err.stack}`);
            reply("Unknown failure.").code(500);
            return;
          }

          let r = reply(body).code(statusCode);
          Object.keys(responseHeaders).forEach(header => {
            r = r.header(header, responseHeaders[header]);
          });
        });

      }
    });

  });
}

export default function (drydock) {
  defineDynamicRoutes(drydock);
  defineHapiRoutes(drydock);
  defineStaticRoutes(drydock);
  defineProxyRoutes(drydock);
}


text:
dictionary_package = "w%s" % [
    node['dictionary']['language']
]

if node['dictionary']['size']
  dictionary_package = "%s-%s" % [
      dictionary_package,
      node['dictionary']['size']
  ]
end

package dictionary_package do
  action :install
end


text:
<? $page_title = "Mobile Visibility" ?>
<?php include("includes/_header.php"); ?>

Mobile Visibility

Foundation is designed to quickly prototype, and one thing we've found very helpful is a series of visibility classes that can be applied to turn things on and off for different device characteristics. On this page, you'll see different elements on different screen sizes or orientations.

Larger Interface

Homepage

Secondary Page

Tertiary Page

As an example, you'll only see this interface if you're on a desktop machine (something with a resolution higher than 768px wide, and not matching specific tablet resolutions). On a desktop we might make more use of columns for layout, as well as show more information for content.

Example Download

Since downloads only work on desktops (well, or with Dropbox on mobile devices) we only show this for desktops.

Example Download

Longer Portrait Page

This section only shows on a portrait orientation of a device with a larger screen than, say, a phone.

Small Interface

As an example, you'll only see this interface if you're on a phone (something with a resolution lower than desktops or tablets). On a phone our columns will all stack, and we would place navigation at the bottom of the page.

Homepage

Secondary Page

Tertiary Page

<?php include("includes/_footer.php");  ?>


text:
import {HttpResponseMessage} from './http-response-message';
import {join, buildQueryString} from 'aurelia-path';

function buildFullUri(message){
  var uri = join(message.baseUrl, message.uri),
      qs;

  if(message.params){
    qs = buildQueryString(message.params);
    uri = qs ? `${uri}?${qs}` : uri;
  }

  message.fullUri = uri;
}

export class RequestMessageProcessor {
  XHRType;
  transformers;
  xhr;
  constructor(xhrType, transformers){
    this.XHRType = xhrType;
    this.transformers = transformers;
  }

  abort(){
    //The logic here is if the xhr object is not set then there is nothing to abort so the intent was carried out
    if(this.xhr){
      this.xhr.abort();
    }
  }

  process(client, message){
    return new Promise((resolve, reject) => {
      var xhr = this.xhr = new this.XHRType(),
          transformers = this.transformers,
          i, ii;

      buildFullUri(message);
      xhr.open(message.method, message.fullUri, true);

      for(i = 0, ii = transformers.length; i < ii; ++i){
        transformers[i](client, this, message, xhr);
      }

      xhr.onload = (e) => {
        var response = new HttpResponseMessage(message, xhr, message.responseType, message.reviver);
        if(response.isSuccess){
          resolve(response);
        }else{
          reject(response);
        }
      };

      xhr.ontimeout = (e) => {
        reject(new HttpResponseMessage(message, {
          response:e,
          status:xhr.status,
          statusText:xhr.statusText
        }, 'timeout'));
      };

      xhr.onerror = (e) => {
        reject(new HttpResponseMessage(message, {
          response:e,
          status:xhr.status,
          statusText:xhr.statusText
        }, 'error'));
      };

      xhr.onabort = (e) => {
        reject(new HttpResponseMessage(message, {
          response:e,
          status:xhr.status,
          statusText:xhr.statusText
        }, 'abort'));
      };

      xhr.send(message.content);
    });
  }
}