text:
// Code generated by client-gen. DO NOT EDIT.

package fake

import (
	"context"
	json "encoding/json"
	"fmt"

	v1beta1 "k8s.io/api/rbac/v1beta1"
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	labels "k8s.io/apimachinery/pkg/labels"
	schema "k8s.io/apimachinery/pkg/runtime/schema"
	types "k8s.io/apimachinery/pkg/types"
	watch "k8s.io/apimachinery/pkg/watch"
	rbacv1beta1 "k8s.io/client-go/applyconfigurations/rbac/v1beta1"
	testing "k8s.io/client-go/testing"
)

// FakeClusterRoleBindings implements ClusterRoleBindingInterface
type FakeClusterRoleBindings struct {
	Fake *FakeRbacV1beta1
}

var clusterrolebindingsResource = schema.GroupVersionResource{Group: "rbac.authorization.k8s.io", Version: "v1beta1", Resource: "clusterrolebindings"}

var clusterrolebindingsKind = schema.GroupVersionKind{Group: "rbac.authorization.k8s.io", Version: "v1beta1", Kind: "ClusterRoleBinding"}

// Get takes name of the clusterRoleBinding, and returns the corresponding clusterRoleBinding object, and an error if there is any.
func (c *FakeClusterRoleBindings) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.ClusterRoleBinding, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootGetAction(clusterrolebindingsResource, name), &v1beta1.ClusterRoleBinding{})
	if obj == nil {
		return nil, err
	}
	return obj.(*v1beta1.ClusterRoleBinding), err
}

// List takes label and field selectors, and returns the list of ClusterRoleBindings that match those selectors.
func (c *FakeClusterRoleBindings) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.ClusterRoleBindingList, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootListAction(clusterrolebindingsResource, clusterrolebindingsKind, opts), &v1beta1.ClusterRoleBindingList{})
	if obj == nil {
		return nil, err
	}

	label, _, _ := testing.ExtractFromListOptions(opts)
	if label == nil {
		label = labels.Everything()
	}
	list := &v1beta1.ClusterRoleBindingList{ListMeta: obj.(*v1beta1.ClusterRoleBindingList).ListMeta}
	for _, item := range obj.(*v1beta1.ClusterRoleBindingList).Items {
		if label.Matches(labels.Set(item.Labels)) {
			list.Items = append(list.Items, item)
		}
	}
	return list, err
}

// Watch returns a watch.Interface that watches the requested clusterRoleBindings.
func (c *FakeClusterRoleBindings) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {
	return c.Fake.
		InvokesWatch(testing.NewRootWatchAction(clusterrolebindingsResource, opts))
}

// Create takes the representation of a clusterRoleBinding and creates it.  Returns the server's representation of the clusterRoleBinding, and an error, if there is any.
func (c *FakeClusterRoleBindings) Create(ctx context.Context, clusterRoleBinding *v1beta1.ClusterRoleBinding, opts v1.CreateOptions) (result *v1beta1.ClusterRoleBinding, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootCreateAction(clusterrolebindingsResource, clusterRoleBinding), &v1beta1.ClusterRoleBinding{})
	if obj == nil {
		return nil, err
	}
	return obj.(*v1beta1.ClusterRoleBinding), err
}

// Update takes the representation of a clusterRoleBinding and updates it. Returns the server's representation of the clusterRoleBinding, and an error, if there is any.
func (c *FakeClusterRoleBindings) Update(ctx context.Context, clusterRoleBinding *v1beta1.ClusterRoleBinding, opts v1.UpdateOptions) (result *v1beta1.ClusterRoleBinding, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootUpdateAction(clusterrolebindingsResource, clusterRoleBinding), &v1beta1.ClusterRoleBinding{})
	if obj == nil {
		return nil, err
	}
	return obj.(*v1beta1.ClusterRoleBinding), err
}

// Delete takes name of the clusterRoleBinding and deletes it. Returns an error if one occurs.
func (c *FakeClusterRoleBindings) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {
	_, err := c.Fake.
		Invokes(testing.NewRootDeleteAction(clusterrolebindingsResource, name), &v1beta1.ClusterRoleBinding{})
	return err
}

// DeleteCollection deletes a collection of objects.
func (c *FakeClusterRoleBindings) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {
	action := testing.NewRootDeleteCollectionAction(clusterrolebindingsResource, listOpts)

	_, err := c.Fake.Invokes(action, &v1beta1.ClusterRoleBindingList{})
	return err
}

// Patch applies the patch and returns the patched clusterRoleBinding.
func (c *FakeClusterRoleBindings) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.ClusterRoleBinding, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootPatchSubresourceAction(clusterrolebindingsResource, name, pt, data, subresources...), &v1beta1.ClusterRoleBinding{})
	if obj == nil {
		return nil, err
	}
	return obj.(*v1beta1.ClusterRoleBinding), err
}

// Apply takes the given apply declarative configuration, applies it and returns the applied clusterRoleBinding.
func (c *FakeClusterRoleBindings) Apply(ctx context.Context, clusterRoleBinding *rbacv1beta1.ClusterRoleBindingApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.ClusterRoleBinding, err error) {
	if clusterRoleBinding == nil {
		return nil, fmt.Errorf("clusterRoleBinding provided to Apply must not be nil")
	}
	data, err := json.Marshal(clusterRoleBinding)
	if err != nil {
		return nil, err
	}
	name := clusterRoleBinding.Name
	if name == nil {
		return nil, fmt.Errorf("clusterRoleBinding.Name must be provided to Apply")
	}
	obj, err := c.Fake.
		Invokes(testing.NewRootPatchSubresourceAction(clusterrolebindingsResource, *name, types.ApplyPatchType, data), &v1beta1.ClusterRoleBinding{})
	if obj == nil {
		return nil, err
	}
	return obj.(*v1beta1.ClusterRoleBinding), err
}


text:
{% extends "base.html" %}

{% block content %}
{% if errors %}

    {% for error in errors %}

{{ error }}

    {% endfor %}

{% endif %}

SignUp

<form action="" method="POST">
    Username:
    <input type="text" name="username">

    Password:
    <input type="password" name="password">

    <input type="submit" value="Sign Up">
</form>

Already a user? login here

{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
import { storiesOf } from "@storybook/react";
import * as React from "react";
import { ChangeEventHandler, useCallback, useState } from "react";
import JsonDebug from "testing/JsonDebug";
import InlineSelect, { SelectOption } from "./InlineSelect";

const options: SelectOption[] = [
  { value: "leia", label: "Princess Leia" },
  { value: "han", label: "Han Solo" },
  { value: "jabba", label: "Jabba the Hut" },
  { value: "luke", label: "Luke Skywalker" },
  { value: "everyone", label: "everyone" },
];

storiesOf("General Purpose", module).add("InlineSelect", () => {
  const [empty, setEmpty] = useState<string>("");
  const onEmptyChangeHandler: ChangeEventHandler<HTMLSelectElement> =
    useCallback(({ target: { value } }) => setEmpty(value), [setEmpty]);

  const [single, setSingle] = useState<string>("han");
  const onSingleChangeHandler: ChangeEventHandler<HTMLSelectElement> =
    useCallback(({ target: { value } }) => setSingle(value), [setSingle]);

  const [placeholder, setPlaceholder] = useState<string>("leia");
  const onPlaceholderChangeHandler: ChangeEventHandler<HTMLSelectElement> =
    useCallback(
      ({ target: { value } }) => setPlaceholder(value),
      [setPlaceholder],
    );
  return (

InlineSelect

        An edit-in-place select, to be used inline with text.

      <form>

Simplest

        I would like to feed
        <InlineSelect
          options={options}
          selected={empty}
          onChange={onEmptyChangeHandler}
        />
         to the sarlacc.

With an existing value

        I would like to feed
        <InlineSelect
          options={options}
          selected={single}
          onChange={onSingleChangeHandler}
        />
         to the sarlacc.

With a placeholder

        I would like to feed
        <InlineSelect
          options={options}
          placeholder="+"
          selected={placeholder}
          onChange={onPlaceholderChangeHandler}
        />
         to the sarlacc.
      </form>
      <JsonDebug value={{ empty, single, placeholder }} />

  );
});


text:
namespace OgreBites {

SGTechniqueResolverListener::SGTechniqueResolverListener(Ogre::RTShader::ShaderGenerator *pShaderGenerator)
{
    mShaderGenerator = pShaderGenerator;
}

Ogre::Technique *SGTechniqueResolverListener::handleSchemeNotFound(unsigned short schemeIndex, const Ogre::String &schemeName, Ogre::Material *originalMaterial, unsigned short lodIndex, const Ogre::Renderable *rend) {
    if (!mShaderGenerator->hasRenderState(schemeName))
    {
        return NULL;
    }
    // Case this is the default shader generator scheme.

    // Create shader generated technique for this material.
    bool techniqueCreated = mShaderGenerator->createShaderBasedTechnique(
                *originalMaterial,
                Ogre::MaterialManager::DEFAULT_SCHEME_NAME,
                schemeName);

    if (!techniqueCreated)
    {
        return NULL;
    }
    // Case technique registration succeeded.

    // Force creating the shaders for the generated technique.
    mShaderGenerator->validateMaterial(schemeName, *originalMaterial);

    // Grab the generated technique.
    Ogre::Material::Techniques::const_iterator it;
    for(it = originalMaterial->getTechniques().begin(); it != originalMaterial->getTechniques().end(); ++it)
    {
        Ogre::Technique* curTech = *it;

        if (curTech->getSchemeName() == schemeName)
        {
            return curTech;
        }
    }

    return NULL;
}

bool SGTechniqueResolverListener::afterIlluminationPassesCreated(Ogre::Technique *tech)
{
    if(mShaderGenerator->hasRenderState(tech->getSchemeName()))
    {
        Ogre::Material* mat = tech->getParent();
        mShaderGenerator->validateMaterialIlluminationPasses(tech->getSchemeName(),
                                                             mat->getName(), mat->getGroup());
        return true;
    }
    return false;
}

bool SGTechniqueResolverListener::beforeIlluminationPassesCleared(Ogre::Technique *tech)
{
    if(mShaderGenerator->hasRenderState(tech->getSchemeName()))
    {
        Ogre::Material* mat = tech->getParent();
        mShaderGenerator->invalidateMaterialIlluminationPasses(tech->getSchemeName(),
                                                               mat->getName(), mat->getGroup());
        return true;
    }
    return false;
}

}


text:
module.exports = function() {
    return {
        getController: function(req, res, next) {
            res.render('about.html.twig', {
                foo: 'bar'
            });
        },
    }
};


text:
<?php

namespace Drupal\Component\Utility;

/**
 * Provides helper methods for manipulating numbers.
 *
 * @ingroup utility
 */
class Number {

  /**
   * Verifies that a number is a multiple of a given step.
   *
   * The implementation assumes it is dealing with IEEE 754 double precision
   * floating point numbers that are used by PHP on most systems.
   *
   * This is based on the number/range verification methods of webkit.
   *
   * @param float $value
   *   The value that needs to be checked.
   * @param float $step
   *   The step scale factor. Must be positive.
   * @param float $offset
   *   (optional) An offset, to which the difference must be a multiple of the
   *   given step.
   *
   * @return bool
   *   TRUE if no step mismatch has occurred, or FALSE otherwise.
   *
   * @see http://opensource.apple.com/source/WebCore/WebCore-1298/html/NumberInputType.cpp
   */
  public static function validStep($value, $step, $offset = 0.0) {
    $double_value = (double) abs($value - $offset);

    // The fractional part of a double has 53 bits. The greatest number that
    // could be represented with that is 2^53. If the given value is even bigger
    // than $step * 2^53, then dividing by $step will result in a very small
    // remainder. Since that remainder can't even be represented with a single
    // precision float the following computation of the remainder makes no sense
    // and we can safely ignore it instead.
    if ($double_value / pow(2.0, 53) > $step) {
      return TRUE;
    }

    // Now compute that remainder of a division by $step.
    $remainder = (double) abs($double_value - $step * round($double_value / $step));

    // $remainder is a double precision floating point number. Remainders that
    // can't be represented with single precision floats are acceptable. The
    // fractional part of a float has 24 bits. That means remainders smaller than
    // $step * 2^-24 are acceptable.
    $computed_acceptable_error = (double)($step / pow(2.0, 24));

    return $computed_acceptable_error >= $remainder || $remainder >= ($step - $computed_acceptable_error);
  }

  /**
   * Generates a sorting code from an integer.
   *
   * Consists of a leading character indicating length, followed by N digits
   * with a numerical value in base 36 (alphadecimal). These codes can be sorted
   * as strings without altering numerical order.
   *
   * It goes:
   * 00, 01, 02, ..., 0y, 0z,
   * 110, 111, ... , 1zy, 1zz,
   * 2100, 2101, ..., 2zzy, 2zzz,
   * 31000, 31001, ...
   *
   * @param int $i
   *   The integer value to convert.
   *
   * @return string
   *   The alpha decimal value.
   *
   * @see \Drupal\Component\Utility\Number::alphadecimalToInt
   */
  public static function intToAlphadecimal($i = 0) {
    $num = base_convert((int) $i, 10, 36);
    $length = strlen($num);

    return chr($length + ord('0') - 1) . $num;
  }

  /**
   * Decodes a sorting code back to an integer.
   *
   * @param string $string
   *   The alpha decimal value to convert
   *
   * @return int
   *   The integer value.
   *
   * @see \Drupal\Component\Utility\Number::intToAlphadecimal
   */
  public static function alphadecimalToInt($string = '00') {
    return (int) base_convert(substr($string, 1), 36, 10);
  }

}


text:
using CSReader.DB;
using System.Collections.Generic;
using System.Linq;

namespace CSReader.Command.Find
{
    /// <summary>
    /// 解析した情報を検索するコマンド
    /// </summary>
    public class FindCommand
    {
        public const string COMMAND_NAME = "find";

        public static ICommand Create(DataBaseBase dataBase, IEnumerable<string> args)
        {
            if (args.Count() == 0)
            {
                // 引数がなければ、ヘルプコマンドを返す
                return new FindHelpCommand();
            }

            dataBase.Connect(System.Environment.CurrentDirectory, true);

            string categoryOption = args.Take(1).Single();
            args = args.Skip(1);

            ICommand command = null;
            switch (categoryOption)
            {
            case "-m":
                command = new FindMethodCommand(dataBase, args);
                break;

            default:
                command = new FindHelpCommand();
                break;
            }

            return command;
        }
    }
}


text:
//
//  NAPinAnnotationView.h
//  NAMapKit
//
//  Created by Neil Ang on 21/07/10.
//  Copyright (c) 2010-14 neilang.com. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "NAPinAnnotation.h"
#import "NAMapView.h"

/**
 *  A pin annotation view the behaves like a button.
 */
@interface NAPinAnnotationView : UIButton

/// Associated NAPinAnnotation.
@property (readwrite, nonatomic, weak) NAPinAnnotation *annotation;
/// Animate the pin.
@property (readwrite, nonatomic, assign) BOOL animating;

/// Create a view for a pin annotation on a map.
- (id)initWithAnnotation:(NAPinAnnotation *)annotation onMapView:(NAMapView *)mapView;
/// Update the pin position when the map is zoomed in or zoomed out.
- (void)updatePosition;

@end


text:
WordPress plugin to override the default `[caption]` shortcode

## Usage

```
[caption src="IMAGEURL" width="WIDTH%"]CAPTION[/caption]
```

* Although the width is specified in percentages, the shortcode creates a `full` class that is added to the container if width is `100` or a `half` class if the width is anything else.
* If caption is empty (i.e. there is no content in the shortcode), only the images gets returned

## Example

```
[caption src="http://www.quandigital.com/uploads/2014/08/3_kaufprozess.png" width="100"]Unterschiedliche Kaufentscheidungsprozesse bei Männern und Frauen (<a href="http://webmagazin.de/business/ecommerce/Webdesign-E-Commerce-Frauen-shoppen-anders-Maenner-auch-Gender-Commerce?page=2">Marti Barletta, 2006</a>)[/caption]
```

## Output

```
<div class="content-image full">
    <img src="http://www.quandigital.com/uploads/2014/08/3_kaufprozess.png" />
    <div class="caption">
        Unterschiedliche Kaufentscheidungsprozesse bei Männern und Frauen (<a href="http://webmagazin.de/business/ecommerce/Webdesign-E-Commerce-Frauen-shoppen-anders-Maenner-auch-Gender-Commerce?page=2">Marti Barletta, 2006</a>)
    </div>
</div>
```


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Class org.springframework.jdbc.datasource.DelegatingDataSource (Spring Framework)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.springframework.jdbc.datasource.DelegatingDataSource

Packages that use DelegatingDataSource

org.springframework.jdbc.datasource
Provides a utility class for easy DataSource access,
a PlatformTransactionManager for a single DataSource,
and various simple DataSource implementations.

Uses of DelegatingDataSource in org.springframework.jdbc.datasource

Subclasses of DelegatingDataSource in org.springframework.jdbc.datasource

 class
TransactionAwareDataSourceProxy

          Proxy for a target DataSource that is aware of Spring-managed transactions.

 class
UserCredentialsDataSourceAdapter

          An adapter for a target DataSource, applying the given user credentials to
 every standard getConnection() call, that is, implicitly
 invoking getConnection(username, password) on the target.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright (C) 2003-2004 The Spring Framework Project.


text:
Kaprica Security (KPRCA)

## Description

House price suggestion / prediction service using cutting-edge neural network machine learning algorithm.

### Feature List

Given a sufficient training data set, the service can suggest a reasonable price for the house. The user can query with the following features:

  - Number of bedrooms
  - Number of bathrooms
  - Sq. Ft. of the house
  - Number of crimes per town

The size of training data set can be between 500 and 1000, for the time being.

## Vulnerability
### Vuln 1
In main function in service.cc, the service reads in user-controlled amount of data into a statically sized stack buffer when the predicted price of the house is $13,370,000. The attacker can train specifically such that one can get deterministic output.

#### Generic class of vulnerability

Stack buffer overflow

#### CWE classification

CWE-121: Stack-based Buffer Overflow

#### Challenges

 - Lots of floating point math computations

#### Difficulty

 - **Discovery**: easy
 - **Proving**: medium
 - **Patching**: easy


text:
cask "boop" do
  version "1.4.0"
  sha256 "8c4492baf6d5b1d26d157877f53d063259e615d784e8ab4d046d3ee67fb9b345"

  url "https://github.com/IvanMathy/Boop/releases/download/#{version}/Boop.zip",
      verified: "github.com/IvanMathy/Boop/"
  name "Boop"
  desc "Scriptable scratchpad for developers"
  homepage "https://boop.okat.best/"

  livecheck do
    url "https://boop.okat.best/version.json"
    strategy :page_match do |page|
      JSON.parse(page)["standalone"]["version"]
    end
  end

  depends_on macos: ">= :mojave"

  app "Boop.app"

  zap trash: [
    "~/Library/Application Scripts/com.okatbest.boop",
    "~/Library/Containers/com.okatbest.boop",
  ]
end


text:
Implement the abstract data type _list_ as a linked list. The class _LinkedList<T>_ has to implement the interface _IList<T>_.

A linked list consists of elements that have a value (called _Item_) and a reference to the next element in the list (called _Next_):

    class Element
    {
        public Element(T item) {
            Item = item;
        }

        public T Item { get; set; }

        public Element Next { get; set; }
    }

The list is internally built from these elements. But the public API does not show anything of this implementation details. The _LinkedList<T>_ behaves as other classes the implement the interface _IList<T>_:

    class LinkedList : IList {
        ...
    }

##Variation

The list may be double linked. In addition to the _Next_ property each element has a _Prev_ property that references the previous element in the list. This fastens the reverse traversal of the list from the last element backwards tot he first.

    class Element
    {
        public Element(T item) {
            Item = item;
        }

        public T Item { get; set; }

        public Element Next { get; set; }

        public Element Prev { get; set; }
    }

by [Clean Code Developer School](http://ccd-school.de/)


text:
#ifndef SVGPathSegListBuilder_h
#define SVGPathSegListBuilder_h

#include "core/svg/SVGPathConsumer.h"
#include "core/svg/SVGPathSegList.h"
#include "platform/geometry/FloatPoint.h"

namespace blink {

class SVGPathElement;

class SVGPathSegListBuilder final : public SVGPathConsumer {
public:
    SVGPathSegListBuilder();

    void setCurrentSVGPathElement(SVGPathElement* pathElement) { m_pathElement = pathElement; }
    void setCurrentSVGPathSegList(PassRefPtr<SVGPathSegList> pathSegList) { m_pathSegList = pathSegList; }

private:
    virtual void incrementPathSegmentCount() override { }
    virtual bool continueConsuming() override { return true; }
    virtual void cleanup() override
    {
        m_pathElement = 0;
        m_pathSegList = nullptr;
    }

    // Used in UnalteredParsing/NormalizedParsing modes.
    virtual void moveTo(const FloatPoint&, bool closed, PathCoordinateMode) override;
    virtual void lineTo(const FloatPoint&, PathCoordinateMode) override;
    virtual void curveToCubic(const FloatPoint&, const FloatPoint&, const FloatPoint&, PathCoordinateMode) override;
    virtual void closePath() override;

    // Only used in UnalteredParsing mode.
    virtual void lineToHorizontal(float, PathCoordinateMode) override;
    virtual void lineToVertical(float, PathCoordinateMode) override;
    virtual void curveToCubicSmooth(const FloatPoint&, const FloatPoint&, PathCoordinateMode) override;
    virtual void curveToQuadratic(const FloatPoint&, const FloatPoint&, PathCoordinateMode) override;
    virtual void curveToQuadraticSmooth(const FloatPoint&, PathCoordinateMode) override;
    virtual void arcTo(float, float, float, bool largeArcFlag, bool sweepFlag, const FloatPoint&, PathCoordinateMode) override;

    SVGPathElement* m_pathElement;
    RefPtr<SVGPathSegList> m_pathSegList;
};

} // namespace blink

#endif // SVGPathSegListBuilder_h


text:
//$Id: OptimisticTreeCacheProvider.java 9895 2006-05-05 19:27:17Z epbernard $
package org.hibernate.cache;

import java.util.Properties;
import javax.transaction.TransactionManager;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.cfg.Environment;
import org.hibernate.transaction.TransactionManagerLookup;
import org.hibernate.transaction.TransactionManagerLookupFactory;
import org.jboss.cache.PropertyConfigurator;

/**
 * Support for a standalone JBossCache TreeCache instance utilizing TreeCache's
 * optimistic locking capabilities.  This capability was added in JBossCache
 * version 1.3.0; as such this provider will only work with that version or
 * higher.
 * <p/>
 * The TreeCache instance is configured via a local config resource.  The
 * resource to be used for configuration can be controlled by specifying a value
 * for the {@link #CONFIG_RESOURCE} config property.
 *
 * @author Steve Ebersole
 */
public class OptimisticTreeCacheProvider implements CacheProvider {

	/**
	 * @deprecated use {@link Environment.CACHE_PROVIDER_CONFIG}
	 */
	public static final String CONFIG_RESOURCE = "hibernate.cache.opt_tree_cache.config";
	public static final String DEFAULT_CONFIG = "treecache.xml";

	private static final String NODE_LOCKING_SCHEME = "OPTIMISTIC";
	private static final Log log = LogFactory.getLog( OptimisticTreeCacheProvider.class );

	private org.jboss.cache.TreeCache cache;

	/**
	 * Construct and configure the Cache representation of a named cache region.
	 *
	 * @param regionName the name of the cache region
	 * @param properties configuration settings
	 * @return The Cache representation of the named cache region.
	 * @throws CacheException
	 *          Indicates an error building the cache region.
	 */
	public Cache buildCache(String regionName, Properties properties) throws CacheException {
		return new OptimisticTreeCache( cache, regionName );
	}

	public long nextTimestamp() {
		return System.currentTimeMillis() / 100;
	}

	/**
	 * Prepare the underlying JBossCache TreeCache instance.
	 *
	 * @param properties All current config settings.
	 * @throws CacheException
	 *          Indicates a problem preparing cache for use.
	 */
	public void start(Properties properties) {
		String resource = properties.getProperty( Environment.CACHE_PROVIDER_CONFIG );
		if (resource == null) {
			resource = properties.getProperty( CONFIG_RESOURCE );
		}
		if ( resource == null ) {
			resource = DEFAULT_CONFIG;
		}
		log.debug( "Configuring TreeCache from resource [" + resource + "]" );
		try {
			cache = new org.jboss.cache.TreeCache();
			PropertyConfigurator config = new PropertyConfigurator();
			config.configure( cache, resource );
			TransactionManagerLookup transactionManagerLookup =
					TransactionManagerLookupFactory.getTransactionManagerLookup( properties );
			if ( transactionManagerLookup == null ) {
				throw new CacheException(
						"JBossCache only supports optimisitc locking with a configured " +
						"TransactionManagerLookup (" + Environment.TRANSACTION_MANAGER_STRATEGY + ")"
				);
			}
			cache.setTransactionManagerLookup(
					new TransactionManagerLookupAdaptor(
							transactionManagerLookup,
							properties
					)
			);
			if ( ! NODE_LOCKING_SCHEME.equalsIgnoreCase( cache.getNodeLockingScheme() ) ) {
				log.info( "Overriding node-locking-scheme to : " + NODE_LOCKING_SCHEME );
				cache.setNodeLockingScheme( NODE_LOCKING_SCHEME );
			}
			cache.start();
		}
		catch ( Exception e ) {
			throw new CacheException( e );
		}
	}

	public void stop() {
		if ( cache != null ) {
			cache.stop();
			cache.destroy();
			cache = null;
		}
	}

	public boolean isMinimalPutsEnabledByDefault() {
		return true;
	}

	static final class TransactionManagerLookupAdaptor implements org.jboss.cache.TransactionManagerLookup {
		private final TransactionManagerLookup tml;
		private final Properties props;

		TransactionManagerLookupAdaptor(TransactionManagerLookup tml, Properties props) {
			this.tml = tml;
			this.props = props;
		}

		public TransactionManager getTransactionManager() throws Exception {
			return tml.getTransactionManager( props );
		}
	}

	public org.jboss.cache.TreeCache getUnderlyingCache() {
		return cache;
	}
}


text:
@interface UserCache : NSObject <UserCacheReader, UserCacheSetter>
{
    UserInfo * primaryUser;
    RecentHistoryCache * recentHistoryCache;
}

@end


text:
from ....testing import assert_equal
from ..preprocess import Automask

def test_Automask_inputs():
    input_map = dict(args=dict(argstr='%s',
    ),
    brain_file=dict(argstr='-apply_prefix %s',
    name_source='in_file',
    name_template='%s_masked',
    ),
    clfrac=dict(argstr='-clfrac %s',
    ),
    dilate=dict(argstr='-dilate %s',
    ),
    environ=dict(nohash=True,
    usedefault=True,
    ),
    erode=dict(argstr='-erode %s',
    ),
    ignore_exception=dict(nohash=True,
    usedefault=True,
    ),
    in_file=dict(argstr='%s',
    copyfile=False,
    mandatory=True,
    position=-1,
    ),
    out_file=dict(argstr='-prefix %s',
    name_source='in_file',
    name_template='%s_mask',
    ),
    outputtype=dict(),
    terminal_output=dict(nohash=True,
    ),
    )
    inputs = Automask.input_spec()

    for key, metadata in list(input_map.items()):
        for metakey, value in list(metadata.items()):
            yield assert_equal, getattr(inputs.traits()[key], metakey), value

def test_Automask_outputs():
    output_map = dict(brain_file=dict(),
    out_file=dict(),
    )
    outputs = Automask.output_spec()

    for key, metadata in list(output_map.items()):
        for metakey, value in list(metadata.items()):
            yield assert_equal, getattr(outputs.traits()[key], metakey), value


text:
import { AsyncIterableX } from '../asynciterablex';
import { OperatorAsyncFunction } from '../../interfaces';
import { wrapWithAbort } from './withabort';
import { throwIfAborted } from '../../aborterror';

export class TakeWhileAsyncIterable<TSource> extends AsyncIterableX<TSource> {
  private _source: AsyncIterable<TSource>;
  private _predicate: (
    value: TSource,
    index: number,
    signal?: AbortSignal
  ) => boolean | Promise<boolean>;

  constructor(
    source: AsyncIterable<TSource>,
    predicate: (value: TSource, index: number, signal?: AbortSignal) => boolean | Promise<boolean>
  ) {
    super();
    this._source = source;
    this._predicate = predicate;
  }

  async *[Symbol.asyncIterator](signal?: AbortSignal) {
    throwIfAborted(signal);
    let i = 0;
    for await (const item of wrapWithAbort(this._source, signal)) {
      if (!(await this._predicate(item, i++, signal))) {
        break;
      }
      yield item;
    }
  }
}

/**
 * Returns elements from an async-iterable sequence as long as a specified condition is true.
 *
 * @template T The type of the elements in the source sequence.
 * @template S The result of the predicate that is truthy/falsy.
 * @param {(value: T, index: number, signal?: AbortSignal) => value is S} predicate A function to test each element for a condition.
 * @returns {OperatorAsyncFunction<T, S>} An async-iterable sequence that contains the elements from the input sequence that occur
 * before the element at which the test no longer passes.
 */
export function takeWhile<T, S extends T>(
  predicate: (value: T, index: number, signal?: AbortSignal) => value is S
): OperatorAsyncFunction<T, S>;
/**
 * Returns elements from an async-iterable sequence as long as a specified condition is true.
 *
 * @template T The type of the elements in the source sequence.
 * @param {((value: T, index: number, signal?: AbortSignal) => boolean | Promise<boolean>)} predicate A function to test each element for a condition.
 * @returns {OperatorAsyncFunction<T, T>} An async-iterable sequence that contains the elements from the input sequence that occur
 * before the element at which the test no longer passes.
 */
export function takeWhile<T>(
  predicate: (value: T, index: number, signal?: AbortSignal) => boolean | Promise<boolean>
): OperatorAsyncFunction<T, T>;
/**
 * Returns elements from an async-iterable sequence as long as a specified condition is true.
 *
 * @template T The type of the elements in the source sequence.
 * @param {((value: T, index: number, signal?: AbortSignal) => boolean | Promise<boolean>)} predicate A function to test each element for a condition.
 * @returns {OperatorAsyncFunction<T, T>} An async-iterable sequence that contains the elements from the input sequence that occur
 * before the element at which the test no longer passes.
 */
export function takeWhile<T>(
  predicate: (value: T, index: number, signal?: AbortSignal) => boolean | Promise<boolean>
): OperatorAsyncFunction<T, T> {
  return function takeWhileOperatorFunction(source: AsyncIterable<T>): AsyncIterableX<T> {
    return new TakeWhileAsyncIterable<T>(source, predicate);
  };
}


text:
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef CHROME_BROWSER_PRINTING_CLOUD_PRINT_PRIVET_URL_LOADER_H_
#define CHROME_BROWSER_PRINTING_CLOUD_PRINT_PRIVET_URL_LOADER_H_

#include <memory>
#include <string>

#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "base/sequenced_task_runner.h"
#include "base/values.h"
#include "net/traffic_annotation/network_traffic_annotation.h"
#include "services/network/public/cpp/simple_url_loader.h"
#include "services/network/public/mojom/url_response_head.mojom-forward.h"
#include "url/gurl.h"

namespace network {
class SharedURLLoaderFactory;
}

namespace cloud_print {

// Privet-specific URLLoader adapter. Currently supports only the subset of
// HTTP features required by Privet for GCP 1.5 (/privet/info and
// /privet/register).
class PrivetURLLoader {
 public:
  enum ErrorType {
    JSON_PARSE_ERROR,
    REQUEST_CANCELED,
    RESPONSE_CODE_ERROR,
    TOKEN_ERROR,
    UNKNOWN_ERROR,
  };

  using TokenCallback = base::OnceCallback<void(const std::string& /*token*/)>;

  class Delegate {
   public:
    virtual ~Delegate() {}

    // If you do not implement this method for PrivetV1 callers, you will always
    // get a TOKEN_ERROR error when your token is invalid.
    virtual void OnNeedPrivetToken(TokenCallback callback);

    // |response_code| is only needed for RESPONSE_CODE_ERROR.
    virtual void OnError(int response_code, ErrorType error) = 0;
    virtual void OnParsedJson(int response_code,
                              const base::DictionaryValue& value,
                              bool has_error) = 0;

    // If this method returns true, the data will not be parsed as JSON, and
    // OnParsedJson() will not be called. Otherwise, OnParsedJson() will be
    // called. This only happens in tests.
    virtual bool OnRawData(bool response_is_file,
                           const std::string& data_string,
                           const base::FilePath& data_file);
  };

  PrivetURLLoader(
      const GURL& url,
      const std::string& request_type,
      scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
      const net::NetworkTrafficAnnotationTag& traffic_annotation,
      Delegate* delegate);

  virtual ~PrivetURLLoader();

  static void SetTokenForHost(const std::string& host,
                              const std::string& token);

  static void ResetTokenMapForTest();

  void SetMaxRetriesForTest(int max_retries);

  void DoNotRetryOnTransientError();

  void SendEmptyPrivetToken();

  // Set the contents of the Range header. OnRawData() must return true if this
  // is called.
  void SetByteRange(int start, int end);

  // Save the response to a file. OnRawData() must return true if this is
  // called.
  void SaveResponseToFile();

  void Start();

  void SetUploadData(const std::string& upload_content_type,
                     const std::string& upload_data);

  // A class that can be used in tests that want to bypass the delay when
  // retrying loading a URL. Create one of this object in your test, it will
  // disable the delay for retry on construction and revert it back on
  // destruction.
  // Note that you should not have more than one of these allocated at a time.
  class RetryImmediatelyForTest final {
   public:
    RetryImmediatelyForTest();
    ~RetryImmediatelyForTest();
  };

 private:
  std::string GetHostString();  // Get string representing the host.
  std::string GetPrivetAccessToken();
  void Try();
  void ScheduleRetry(int timeout_seconds);
  bool PrivetErrorTransient(const std::string& error);
  void RequestTokenRefresh();
  void RefreshToken(const std::string& token);
  void OnResponseStarted(const GURL& final_url,
                         const network::mojom::URLResponseHead& response_head);
  void OnDownloadedToString(std::unique_ptr<std::string> response_body);
  void OnDownloadedToFile(base::FilePath path);
  bool CheckURLLoaderForError();

  const GURL url_;
  const std::string request_type_;
  scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_;
  const net::NetworkTrafficAnnotationTag traffic_annotation_;
  Delegate* const delegate_;

  int max_retries_;
  bool do_not_retry_on_transient_error_ = false;
  bool send_empty_privet_token_ = false;
  bool has_byte_range_ = false;
  bool make_response_file_ = false;
  static bool skip_retry_timeouts_for_tests_;

  int byte_range_start_ = 0;
  int byte_range_end_ = 0;

  int tries_ = 0;
  std::string upload_data_;
  std::string upload_content_type_;
  std::unique_ptr<network::SimpleURLLoader> url_loader_;

  base::WeakPtrFactory<PrivetURLLoader> weak_factory_{this};
  DISALLOW_COPY_AND_ASSIGN(PrivetURLLoader);
};

}  // namespace cloud_print

#endif  // CHROME_BROWSER_PRINTING_CLOUD_PRINT_PRIVET_URL_LOADER_H_


text:
backlog.jp api client written by C#

see https://github.com/t-ashula/bl4n/


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycol. eur. Abbildungen Sämmtlicher Pilze Europa's 5-6: 11 (1869)

#### Original name
Sphaerella populi Auersw., 1869

### Remarks
null


text:
head.js("assets/js/clock/date.js");

//Date Range Picker for filtering data

var dateStart="2014-01-01", dateEnd="2014-12-31";
head.js("assets/js/datepicker/daterangepicker.js", "assets/js/datepicker/moment.min.js", function() {

    $(document).ready(function() {
      $('#daterange').daterangepicker({
          "startDate": dateStart,
          "endDate": dateEnd,
            "locale": {
              format: 'YYYY-MM-DD'
            }
      }, function(start, end, label) {
            dateStart = start;
            dateEnd = end;
            //console.log("New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')");
      });
    });
});

//NEWS STICKER
head.js("assets/js/newsticker/jquery.newsTicker.js", function() {
    var nt_title = $('#nt-title').newsTicker({
        row_height: 18,
        max_rows: 1,
        duration: 5000,
        pauseOnHover: 0
    });
});

//-------------------------------------------------------------

//SEARCH MENU
head.js("assets/js/search/jquery.quicksearch.js", function() {
    $('input.id_search').quicksearch('#menu-showhide li, .menu-left-nest li');
});
//-------------------------------------------------------------

//EASY PIE CHART
head.js("assets/js/gage/jquery.easypiechart.min.js", function() {

    $(function() {

        $('.chart').easyPieChart({
            easing: 'easeOutBounce',
            trackColor: '#ffffff',
            scaleColor: '#ffffff',
            barColor: '#FF0064',
            onStep: function(from, to, percent) {
                $(this.el).find('.percent').text(Math.round(percent));
            }
        });
        var chart = window.chart = $('.chart').data('easyPieChart');
        $('.js_update').on('click', function() {
            chart.update(Math.random() * 100);
        });

        $('.speed-car').easyPieChart({
            easing: 'easeOutBounce',
            trackColor: 'rgba(0,0,0,0.3)',
            scaleColor: 'transparent',
            barColor: '#0085DF',

            lineWidth: 8,
            onStep: function(from, to, percent) {
                $(this.el).find('.percent2').text(Math.round(percent));
            }
        });
        var chart = window.chart = $('.chart2').data('easyPieChart');
        $('.js_update').on('click', function() {
            chart.update(Math.random() * 100);
        });
        $('.overall').easyPieChart({
            easing: 'easeOutBounce',
            trackColor: 'rgba(0,0,0,0.3)',
            scaleColor: '#323A45',
            lineWidth: 35,
            lineCap: 'butt',
            barColor: '#FFB900',
            onStep: function(from, to, percent) {
                $(this.el).find('.percent3').text(Math.round(percent));
            }
        });
    });

});
//-------------------------------------------------------------

//TOOL TIP

head.js("assets/js/tip/jquery.tooltipster.js", function() {

    $('.tooltip-tip-x').tooltipster({
        position: 'right'

    });

    $('.tooltip-tip').tooltipster({
        position: 'right',
        animation: 'slide',
        theme: '.tooltipster-shadow',
        delay: 1,
        offsetX: '-12px',
        onlyOne: true

    });
    $('.tooltip-tip2').tooltipster({
        position: 'right',
        animation: 'slide',
        offsetX: '-12px',
        theme: '.tooltipster-shadow',
        onlyOne: true

    });
    $('.tooltip-top').tooltipster({
        position: 'top'
    });
    $('.tooltip-right').tooltipster({
        position: 'right'
    });
    $('.tooltip-left').tooltipster({
        position: 'left'
    });
    $('.tooltip-bottom').tooltipster({
        position: 'bottom'
    });
    $('.tooltip-reload').tooltipster({
        position: 'right',
        theme: '.tooltipster-white',
        animation: 'fade'
    });
    $('.tooltip-fullscreen').tooltipster({
        position: 'left',
        theme: '.tooltipster-white',
        animation: 'fade'
    });
    //For icon tooltip

});
//-------------------------------------------------------------

//DIGITAL CLOCK
head.js("assets/js/clock/jquery.clock.js", function() {
    //clock
    $('#digital-clock').clock({
        offset: '+8',
        type: 'digital'
    });
});

//Time of day select picker
$(".btn-tod").click(function(e) {
     $(this).removeClass('btn-default').addClass('active').addClass('btn-success').siblings().removeClass('active').removeClass('btn-success');
    $('#day').val($(this).val());
});

$('#getting-started').countdown('2015/01/01', function(event) {
    $(this).html(event.strftime('%M' + ':' + '%S'));
});

//Autocomplete search field (not working due to CSS)
//head.js("assets/js/bootstrap3-typeahead.min.js", function(){
    //$.get('http://get', function(data){
        //$("#locale").typeahead({ source:["new york","new jersey","Maryland"] });
   // },'json');
//});


text:
module Development.Shake.Install.GetBuildType
  ( GetBuildType(..)
  ) where

import Data.List (nub)
import Distribution.PackageDescription
import Distribution.Simple.LocalBuildInfo

class GetBuildType a where
  getBuildType :: a -> Maybe BuildType
  getBuildInfo :: a -> [BuildInfo]

instance GetBuildType LocalBuildInfo where
  getBuildType = buildType . localPkgDescr
  getBuildInfo = allBuildInfo . localPkgDescr

instance GetBuildType GenericPackageDescription where
  getBuildType = buildType . packageDescription
  getBuildInfo = nub . getGenericBuildInfo

getGenericBuildInfo :: GenericPackageDescription -> [BuildInfo]
getGenericBuildInfo x = allInfo x ++ regularInfo x where
  allInfo x = case condLibrary x of
    Just node -> (libBuildInfo . condTreeData $ node) : exeInfo x
    Nothing   -> exeInfo x

  exeInfo = fmap exeBuildInfo . condExecutables

  exeBuildInfo (_, node) =  buildInfo . condTreeData  $ node

  regularInfo = allBuildInfo . packageDescription


text:
Roundcube Framework
===================

INTRODUCTION
------------
The Roundcube Framework is the basic library used for the Roundcube Webmail
application. It is an extract of classes providing the core functionality for
an email system. They can be used individually or as package for the following
tasks:

- IMAP mailbox access with optional caching
- MIME message handling
- Email message creation and sending through SMTP
- General caching utilities using the local database
- Database abstraction using PDO
- VCard parsing and writing

INSTALLATION
------------
Copy all files of this directory to your project or install it in the default
include_path directory of your webserver. Some classes of the framework require
one or multiple of the following [PEAR][pear] libraries:

- Mail_Mime 1.8.1 or newer
- Mail_mimeDecode 1.5.5 or newer
- Net_SMTP (latest from https://github.com/pear/Net_SMTP/)
- Net_IDNA2 0.1.1 or newer
- Auth_SASL 1.0.6 or newer

USAGE
-----
The Roundcube Framework provides a bootstrapping file which registers an
autoloader and sets up the environment necessary for the Roundcube classes.
In order to make use of the framework, simply include the bootstrap.php file
from this directory in your application and start using the classes by simply
instantiating them.

If you wanna use more complex functionality like IMAP access with database
caching or plugins, the rcube singleton helps you loading the necessary files:

```php
<?php

define('RCUBE_CONFIG_DIR',  '<path-to-config-directory>');
define('RCUBE_PLUGINS_DIR', '<path-to-roundcube-plugins-directory');

require_once '<path-to-roundcube-framework/bootstrap.php';

$rcube = rcube::get_instance(rcube::INIT_WITH_DB | rcube::INIT_WITH_PLUGINS);
$imap = $rcube->get_storage();

// do cool stuff here...

?>
```

LICENSE
-------
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License (**with exceptions
for plugins**) as published by the Free Software Foundation, either
version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see [www.gnu.org/licenses/][gpl].

This file forms part of the Roundcube Webmail Framework for which the
following exception is added: Plugins which merely make function calls to the
Roundcube Webmail Framework, and for that purpose include it by reference
shall not be considered modifications of the software.

If you wish to use this file in another project or create a modified
version that will not be part of the Roundcube Webmail Framework, you
may remove the exception above and use this source code under the
original version of the license.

For more details about licensing and the exceptions for skins and plugins
see [roundcube.net/license][license]

CONTACT
-------
For any bug reports or feature requests please refer to the tracking system
at [trac.roundcube.net][tracreport] or subscribe to our mailing list.
See [roundcube.net/support][support] for details.

You're always welcome to send a message to the project admins:
hello(at)roundcube(dot)net

[pear]:         http://pear.php.net
[gpl]:          http://www.gnu.org/licenses/
[license]:      http://roundcube.net/license
[support]:      http://roundcube.net/support
[tracreport]:   http://trac.roundcube.net/wiki/Howto_ReportIssues


text:
typedef void* EGLContext;

namespace gfx {

class GLSurfaceEGL;

// Encapsulates an EGL OpenGL ES context.
class GLContextEGL : public GLContext {
 public:
  // Takes ownership of surface. TODO(apatrick): separate notion of surface
  // from context.
  explicit GLContextEGL(GLSurfaceEGL* surface);

  virtual ~GLContextEGL();

  // Initialize an EGL context.
  bool Initialize(GLContext* shared_context);

  // Implement GLContext.
  virtual void Destroy();
  virtual bool MakeCurrent();
  virtual void ReleaseCurrent();
  virtual bool IsCurrent();
  virtual bool IsOffscreen();
  virtual bool SwapBuffers();
  virtual gfx::Size GetSize();
  virtual GLSurface* GetSurface();
  virtual void* GetHandle();
  virtual void SetSwapInterval(int interval);
  virtual std::string GetExtensions();

 private:
  scoped_ptr<GLSurfaceEGL> surface_;
  EGLContext context_;

  DISALLOW_COPY_AND_ASSIGN(GLContextEGL);
};

}  // namespace gfx

#endif  // UI_GFX_GL_GL_CONTEXT_EGL_H_


text:
package com.facebook.buck.shell;

import com.facebook.buck.rules.BinaryBuildRule;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.HasRuntimeDeps;
import com.facebook.buck.rules.NoopBuildRule;
import com.facebook.buck.rules.SourcePathResolver;
import com.google.common.collect.ImmutableSortedSet;

public class WorkerTool extends NoopBuildRule implements HasRuntimeDeps {

  private final BinaryBuildRule exe;
  private final String args;

  protected WorkerTool(
      BuildRuleParams ruleParams,
      SourcePathResolver resolver,
      BinaryBuildRule exe,
      String args) {
    super(ruleParams, resolver);
    this.exe = exe;
    this.args = args;
  }

  public BinaryBuildRule getBinaryBuildRule() {
    return this.exe;
  }

  public String getArgs() {
    return this.args;
  }

  @Override
  public ImmutableSortedSet<BuildRule> getRuntimeDeps() {
    return ImmutableSortedSet.<BuildRule>naturalOrder()
        .add(exe)
        .addAll(exe.getExecutableCommand().getDeps(getResolver()))
        .build();
  }
}


text:
import os
import re
import time
from twisted.web import resource
from buildbot.status.builder import FAILURE

class XmlResource(resource.Resource):
    contentType = "text/xml; charset=UTF-8"
    docType = ''

    def getChild(self, name, request):
        return self

    def render(self, request):
        data = self.content(request)
        request.setHeader("content-type", self.contentType)
        if request.method == "HEAD":
            request.setHeader("content-length", len(data))
            return ''
        return data

_abbr_day = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
_abbr_mon = ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',
            'Sep', 'Oct', 'Nov', 'Dec']

def rfc822_time(tstamp):
    res = time.strftime("%%s, %d %%s %Y %H:%M:%S GMT",
                                       tstamp)
    res = res % (tstamp.tm_wday, tstamp.tm_mon)
    return res

class FeedResource(XmlResource):
    pageTitle = None
    link = 'http://dummylink'
    language = 'en-us'
    description = 'Dummy rss'
    status = None

    def __init__(self, status, categories=None, pageTitle=None):
        self.status = status
        self.categories = categories
        self.pageTitle = pageTitle
        self.title = self.status.getTitle()
        self.link = self.status.getBuildbotURL()
        self.description = 'List of builds'
        self.pubdate = time.gmtime(int(time.time()))
        self.user = self.getEnv(['USER', 'USERNAME'], 'buildmaster')
        self.hostname = self.getEnv(['HOSTNAME', 'COMPUTERNAME'],
                                    'buildmaster')
        self.children = {}

    def getEnv(self, keys, fallback):
        for key in keys:
            if key in os.environ:
                return os.environ[key]
        return fallback

    def getBuilds(self, request):
        builds = []
        # THIS is lifted straight from the WaterfallStatusResource Class in
        # status/web/waterfall.py
        #
        # we start with all Builders available to this Waterfall: this is
        # limited by the config-file -time categories= argument, and defaults
        # to all defined Builders.
        allBuilderNames = self.status.getBuilderNames(categories=self.categories)
        builders = [self.status.getBuilder(name) for name in allBuilderNames]

        # but if the URL has one or more builder= arguments (or the old show=
        # argument, which is still accepted for backwards compatibility), we
        # use that set of builders instead. We still don't show anything
        # outside the config-file time set limited by categories=.
        showBuilders = request.args.get("show", [])
        showBuilders.extend(request.args.get("builder", []))
        if showBuilders:
            builders = [b for b in builders if b.name in showBuilders]

        # now, if the URL has one or category= arguments, use them as a
        # filter: only show those builders which belong to one of the given
        # categories.
        showCategories = request.args.get("category", [])
        if showCategories:
            builders = [b for b in builders if b.category in showCategories]

        failures_only = request.args.get("failures_only", "false")

        maxFeeds = 25

        # Copy all failed builds in a new list.
        # This could clearly be implemented much better if we had
        # access to a global list of builds.
        for b in builders:
            lastbuild = b.getLastFinishedBuild()
            if lastbuild is None:
                continue

            lastnr = lastbuild.getNumber()

            totalbuilds = 0
            i = lastnr
            while i >= 0:
                build = b.getBuild(i)
                i -= 1
                if not build:
                    continue

                results = build.getResults()

                if failures_only == "false" or results == FAILURE:
                    totalbuilds += 1
                    builds.append(build)

                # stop for this builder when our total nr. of feeds is reached
                if totalbuilds >= maxFeeds:
                    break

        # Sort build list by date, youngest first.
        # To keep compatibility with python < 2.4, use this for sorting instead:
        # We apply Decorate-Sort-Undecorate
        deco = [(build.getTimes(), build) for build in builds]
        deco.sort()
        deco.reverse()
        builds = [build for (b1, build) in deco]

        if builds:
            builds = builds[:min(len(builds), maxFeeds)]
        return builds

    def content(self, request):
        builds = self.getBuilds(request)

        build_cxts = []

        for build in builds:
            start, finished = build.getTimes()
            finishedTime = time.gmtime(int(finished))
            link = re.sub(r'index.html', "", self.status.getURLForThing(build))

            # title: trunk r22191 (plus patch) failed on
            # 'i686-debian-sarge1 shared gcc-3.3.5'
            ss = build.getSourceStamp()
            source = ""
            if ss.branch:
                source += "Branch %s " % ss.branch
            if ss.revision:
                source += "Revision %s " % str(ss.revision)
            if ss.patch:
                source += " (plus patch)"
            if ss.changes:
                pass
            if (ss.branch is None and ss.revision is None and ss.patch is None
                and not ss.changes):
                source += "Latest revision "
            got_revision = None
            try:
                got_revision = build.getProperty("got_revision")
            except KeyError:
                pass
            if got_revision:
                got_revision = str(got_revision)
                if len(got_revision) > 40:
                    got_revision = "[revision string too long]"
                source += "(Got Revision: %s)" % got_revision
            failflag = (build.getResults() != FAILURE)
            pageTitle = ('%s %s on "%s"' %
                     (source, ["failed","succeeded"][failflag],
                      build.getBuilder().getName()))

            # Add information about the failing steps.
            failed_steps = []
            log_lines = []
            for s in build.getSteps():
                if s.getResults()[0] == FAILURE:
                    failed_steps.append(s.getName())

                    # Add the last 30 lines of each log.
                    for log in s.getLogs():
                        log_lines.append('Last lines of build log "%s":' %
                                         log.getName())
                        log_lines.append([])
                        try:
                            logdata = log.getText()
                        except IOError:
                            # Probably the log file has been removed
                            logdata ='** log file not available **'
                        unilist = list()
                        for line in logdata.split('\n')[-30:]:
                            unilist.append(unicode(line,'utf-8'))
                        log_lines.extend(unilist)

            bc = {}
            bc['date'] = rfc822_time(finishedTime)
            bc['summary_link'] = ('%sbuilders/%s' %
                                  (self.link,
                                   build.getBuilder().getName()))
            bc['name'] = build.getBuilder().getName()
            bc['number'] = build.getNumber()
            bc['responsible_users'] = build.getResponsibleUsers()
            bc['failed_steps'] = failed_steps
            bc['pageTitle'] = pageTitle
            bc['link'] = link
            bc['log_lines'] = log_lines

            if finishedTime is not None:
                bc['rfc822_pubdate'] = rfc822_time(finishedTime)
                bc['rfc3339_pubdate'] = time.strftime("%Y-%m-%dT%H:%M:%SZ",
                                               finishedTime)

                # Every RSS/Atom item must have a globally unique ID
                guid = ('tag:%s@%s,%s:%s' %
                        (self.user, self.hostname,
                         time.strftime("%Y-%m-%d", finishedTime),
                         time.strftime("%Y%m%d%H%M%S", finishedTime)))
                bc['guid'] = guid

            build_cxts.append(bc)

        pageTitle = self.pageTitle
        if not pageTitle:
            pageTitle = 'Build status of %s' % self.pageTitle

        cxt = {}
        cxt['pageTitle'] = pageTitle
        cxt['title_url'] = self.link
        cxt['title'] = self.title
        cxt['language'] = self.language
        cxt['description'] = self.description
        if self.pubdate is not None:
            cxt['rfc822_pubdate'] = rfc822_time( self.pubdate)
            cxt['rfc3339_pubdate'] = time.strftime("%Y-%m-%dT%H:%M:%SZ",
                                                   self.pubdate)

        cxt['builds'] = build_cxts
        template = request.site.buildbot_service.templates.get_template(self.template_file)
        return template.render(**cxt).encode('utf-8').strip()

class Rss20StatusResource(FeedResource):
    # contentType = 'application/rss+xml' (browser dependent)
    template_file = 'feed_rss20.xml'

    def __init__(self, status, categories=None, pageTitle=None):
        FeedResource.__init__(self, status, categories, pageTitle)

class Atom10StatusResource(FeedResource):
    # contentType = 'application/atom+xml' (browser dependent)
    template_file = 'feed_atom10.xml'

    def __init__(self, status, categories=None, pageTitle=None):
        FeedResource.__init__(self, status, categories, pageTitle)


text:
LaughingAdventure::Application.routes.draw do
    devise_for :views
    root :to => "home#index"

    get 'tags/:tag', to: 'posts#index', as: :tag
    match '/search', :to => "home#search" , :via => "get"
    devise_for :users, :controllers => {:registrations => "registrations"}
    resources :users
    resources :posts do
        resources :comments
    end

    resources :messages do
    collection do
      get 'compose', :to=>'messages#new', :as=>:compose
      get 'index', :to=> 'messages#index', :as=> :index
      get 'sent', :to=> 'messages#sent', :as=> :sent
      post 'reply', :to=> 'messages#reply', :as=> :reply
      post 'trash', :to=> 'messages#trash', :as=> :trash
    end
  end

    patch 'show', :to=> 'messages#show', :as=> :show

    #For AJAX
    get  "refresh"  => "home#refreshposts", :as => "refresh"
    get "votedup"  => "home#votedup", :as => "votedup"
    get  "voteddown"  => "home#voteddown", :as => "voteddown"
    get  "message"  => "messages#unreadcount", :as => "unreadmessages"

    post 'users/user_follow'
    post 'users/user_unfollow'
    post 'topics/user_follow'
    post 'topics/user_unfollow'

end


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

package org.activiti.engine.impl.persistence.entity;

import java.util.HashMap;
import java.util.Map;

import org.activiti.engine.delegate.event.ActivitiEventType;
import org.activiti.engine.delegate.event.impl.ActivitiEventBuilder;
import org.activiti.engine.impl.persistence.AbstractManager;

/**
 * @author Tom Baeyens
 */
public class MembershipEntityManager extends AbstractManager implements MembershipIdentityManager {

  public void createMembership(String userId, String groupId) {
    MembershipEntity membershipEntity = new MembershipEntity();
    membershipEntity.setUserId(userId);
    membershipEntity.setGroupId(groupId);
    getDbSqlSession().insert(membershipEntity);

    if(getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
    	getProcessEngineConfiguration().getEventDispatcher().dispatchEvent(
    			ActivitiEventBuilder.createMembershipEvent(ActivitiEventType.MEMBERSHIP_CREATED, groupId, userId));
    }
  }

  public void deleteMembership(String userId, String groupId) {
    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("userId", userId);
    parameters.put("groupId", groupId);
    getDbSqlSession().delete("deleteMembership", parameters);

    if(getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
    	getProcessEngineConfiguration().getEventDispatcher().dispatchEvent(
    			ActivitiEventBuilder.createMembershipEvent(ActivitiEventType.MEMBERSHIP_DELETED, groupId, userId));
    }
  }

}


text:
#ifndef SYMBIAN_BITMAP_DRAWING_INTERFACCE_H
#define SYMBIAN_BITMAP_DRAWING_INTERFACCE_H

class MC2Point;
class CFbsBitmap;

/**
 *    Interface used to draw bitmaps without flickering on a control.
 */
class SymbianBitmapDrawingInterface {
public:
   /**
    *    Virtual destructor.
    */
   virtual ~SymbianBitmapDrawingInterface() {}

   /**
    *    Add the bitmap at the specified position.
    *    The position is relative to the upper left corner,
    *    depending on the orientation of the phone (landscape, portrait).
    */
   virtual void addBitmap( const MC2Point& pos,
                           CFbsBitmap* bitmap,
                           CFbsBitmap* mask ) = 0;

   /**
    *    Remove the bitmap.
    *    The bitmap must already have been added using addBitmap.
    */
   virtual void removeBitmap( CFbsBitmap* bitmap ) = 0;

   /**
    *    Move the bitmap to the specified position.
    *    The position is relative to the upper left corner,
    *    depending on the orientation of the phone (landscape, portrait).
    *    The bitmap must already have been added using addBitmap.
    */
   virtual void moveBitmap( CFbsBitmap* bitmap, const MC2Point& pos ) = 0;

};

#endif


text:
namespace Microsoft.Azure.Search.Models
{
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// A single bucket of a facet query result. Reports the number of
    /// documents with a field value falling within a particular range or
    /// having a particular value or interval.
    /// </summary>
    public partial class FacetResult
    {
        /// <summary>
        /// Initializes a new instance of the FacetResult class.
        /// </summary>
        internal FacetResult()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the FacetResult class.
        /// </summary>
        /// <param name="additionalProperties">Unmatched properties from the
        /// message are deserialized this collection</param>
        /// <param name="count">The approximate count of documents falling
        /// within the bucket described by this facet.</param>
        internal FacetResult(IDictionary<string, object> additionalProperties = default(IDictionary<string, object>), long? count = default(long?))
        {
            AdditionalProperties = additionalProperties;
            Count = count;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets unmatched properties from the message are deserialized
        /// this collection
        /// </summary>
        [JsonExtensionData]
        internal IDictionary<string, object> AdditionalProperties { get; set; }

        /// <summary>
        /// Gets the approximate count of documents falling within the bucket
        /// described by this facet.
        /// </summary>
        [JsonProperty(PropertyName = "count")]
        public long? Count { get; private set; }

    }
}


text:
package com.gogocosmo.cosmoqiu.fire_sticker.Model;

import java.util.UUID;

public class Group {

    private int mGroupId;
    private String mUuid;
    private String mGroupName;

    public Group() {
    }

    public Group(String GroupName) {
        this.mGroupName = GroupName;
        this.mUuid = UUID.randomUUID().toString();
    }

    public int getGroupId() {
        return mGroupId;
    }

    public void setGroupId(int GroupId) {
        this.mGroupId = GroupId;
    }

    public String getGroupName() {
        return mGroupName;
    }

    public void setGroupName(String GroupName) {
        this.mGroupName = GroupName;
    }

    public String getUuid() {
        return mUuid;
    }

    public void setUuid(String Uuid) {
        this.mUuid = Uuid;
    }
}


text:
package org.nnsoft.trudeau.inmemory.labeled;

import java.io.Serializable;

import org.nnsoft.trudeau.api.Mapper;

public final class BaseWeightedEdge<W>
    implements Mapper<BaseLabeledWeightedEdge<W>, W>, Serializable
{

    private static final long serialVersionUID = -2024378704087762740L;

    public W map( BaseLabeledWeightedEdge<W> edge )
    {
        return edge.getWeight();
    }

}


text:
namespace sky {
namespace shell {

class RasterizerDirect : public Rasterizer {
 public:
  RasterizerDirect();

  ~RasterizerDirect() override;

  // sky::shell::Rasterizer override.
  void ConnectToRasterizer(
      mojo::InterfaceRequest<rasterizer::Rasterizer> request) override;

  // sky::shell::Rasterizer override.
  void Setup(PlatformView* platform_view,
             ftl::Closure continuation,
             ftl::AutoResetWaitableEvent* setup_completion_event) override;

  // sky::shell::Rasterizer override.
  void Teardown(
      ftl::AutoResetWaitableEvent* teardown_completion_event) override;

  // sky::shell::Rasterizer override.
  ftl::WeakPtr<sky::shell::Rasterizer> GetWeakRasterizerPtr() override;

  // sky::shell::Rasterizer override.
  flow::LayerTree* GetLastLayerTree() override;

 private:
  GaneshCanvas ganesh_canvas_;
  flow::CompositorContext compositor_context_;
  mojo::Binding<rasterizer::Rasterizer> binding_;
  std::unique_ptr<flow::LayerTree> last_layer_tree_;
  PlatformView* platform_view_;
  ftl::WeakPtrFactory<RasterizerDirect> weak_factory_;

  // sky::services::rasterizer::Rasterizer (from rasterizer.mojom) override.
  void Draw(uint64_t layer_tree_ptr, const DrawCallback& callback) override;

  FTL_DISALLOW_COPY_AND_ASSIGN(RasterizerDirect);
};

}  // namespace shell
}  // namespace sky

#endif  // SKY_SHELL_GPU_DIRECT_RASTERIZER_DIRECT_H_


text:
@class UIBarButtonItem, UILabel;

@interface WFHRBurnBurstFieldTestReadyVC : WFStaticTableViewController
{
    UILabel *_getReadyLabel;
    UILabel *_warmUpLabel;
    UILabel *_warmUpTimeLabel;
    UILabel *_moderateLabel;
    UILabel *_moderateTimeLabel;
    UILabel *_fastPaceLabel;
    UILabel *_fastPaceTimeLabel;
    UILabel *_walkLabel;
    UILabel *_walkTimeLabel;
    UIBarButtonItem *_nextButton;
}

@property(retain, nonatomic) UIBarButtonItem *nextButton; // @synthesize nextButton=_nextButton;
@property(retain, nonatomic) UILabel *walkTimeLabel; // @synthesize walkTimeLabel=_walkTimeLabel;
@property(retain, nonatomic) UILabel *walkLabel; // @synthesize walkLabel=_walkLabel;
@property(retain, nonatomic) UILabel *fastPaceTimeLabel; // @synthesize fastPaceTimeLabel=_fastPaceTimeLabel;
@property(retain, nonatomic) UILabel *fastPaceLabel; // @synthesize fastPaceLabel=_fastPaceLabel;
@property(retain, nonatomic) UILabel *moderateTimeLabel; // @synthesize moderateTimeLabel=_moderateTimeLabel;
@property(retain, nonatomic) UILabel *moderateLabel; // @synthesize moderateLabel=_moderateLabel;
@property(retain, nonatomic) UILabel *warmUpTimeLabel; // @synthesize warmUpTimeLabel=_warmUpTimeLabel;
@property(retain, nonatomic) UILabel *warmUpLabel; // @synthesize warmUpLabel=_warmUpLabel;
@property(retain, nonatomic) UILabel *getReadyLabel; // @synthesize getReadyLabel=_getReadyLabel;
- (void).cxx_destruct;
- (void)drawLines;
- (void)viewDidLoad;

@end


text:
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System.Collections.Generic;
using System.Linq;
using AutoRest.Core.ClientModel;
using AutoRest.Core.Utilities;
using AutoRest.CSharp.TemplateModels;
using AutoRest.Extensions.Azure;

namespace AutoRest.CSharp.Azure.TemplateModels
{
    public class AzureMethodGroupTemplateModel : MethodGroupTemplateModel
    {
        public AzureMethodGroupTemplateModel(ServiceClient serviceClient, string methodGroupName)
            : base(serviceClient, methodGroupName)
        {
            MethodGroupType = MethodGroupName + "Operations";
            // Clear base initialized MethodTemplateModels and re-populate with
            // AzureMethodTemplateModel
            MethodTemplateModels.Clear();
            Methods.Where(m => m.Group == methodGroupName)
                .ForEach(m => MethodTemplateModels.Add(new AzureMethodTemplateModel(m, serviceClient, SyncMethodsGenerationMode.None)));
        }

        /// <summary>
        /// Returns the using statements for the Operations.
        /// </summary>
        public override IEnumerable<string> Usings
        {
            get
            {
                if (MethodTemplateModels.Any(m =>
                    m.ParameterTemplateModels.Any(p => ((AzureParameterTemplateModel)p).IsODataFilterExpression)))
                {
                    yield return "Microsoft.Rest.Azure.OData";
                }
                yield return "Microsoft.Rest.Azure";

                if (this.ModelTypes.Any(m => !m.Extensions.ContainsKey(AzureExtensions.ExternalExtension)) || this.HeaderTypes.Any())
                {
                    yield return "Models";
                }
            }
        }
    }
}


text:
// Copyright (c) 2012-2014 José Carlos Nieto, https://menteslibres.net/xiam
//
// 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.

package host

import (
	"fmt"
	//"github.com/howeyc/fsnotify"
	"bytes"
	"errors"
	"html/template"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"path"
	"regexp"
	"strings"
	"time"

	"github.com/russross/blackfriday"
	"menteslibres.net/gosexy/to"
	"menteslibres.net/gosexy/yaml"
	"menteslibres.net/luminos/page"
	"menteslibres.net/luminos/watcher"
)

const (
	pathSeparator = string(os.PathSeparator)
	settingsFile  = "site.yaml"
)

var (
	// Used to guess when dealing with an external URL.
	isExternalLinkPattern = regexp.MustCompile(`^[a-zA-Z0-9]+:\/\/`)
)

// Host is the struct that represents virtual hosts.
type Host struct {
	// Host name
	Name string
	// Main directory
	DocumentRoot string
	// Main path
	Path string
	// Settings
	Settings *yaml.Yaml
	// Templates (not fully functional yet)
	Templates map[string]*template.Template
	// Function map for templates.
	template.FuncMap
	// Standard request.
	*http.Request
	// Standard response writer.
	http.ResponseWriter
	// Function map
	funcMap template.FuncMap
	// File watcher
	//Watcher *fsnotify.Watcher
	Watcher *watcher.Watcher
	// Template root
	TemplateRoot string
}

// Expected extensions. Elements on the left have precedence.
var extensions = []string{
	".md",
	".html",
	".txt",
	".md.tpl",
}

// fixDeprecatedSyntax fixes old template syntax.
func fixDeprecatedSyntax(s string) string {

	s = strings.Replace(s, "{{ link", "{{ anchor", -1)
	s = strings.Replace(s, "{{link", "{{anchor", -1)
	s = strings.Replace(s, ".link", ".URL", -1)
	s = strings.Replace(s, ".url", ".URL", -1)
	s = strings.Replace(s, ".text", ".Text", -1)
	s = strings.Replace(s, "jstext", "js", -1)
	s = strings.Replace(s, "htmltext", "html", -1)

	return s
}

func (host *Host) getContentPath() (string, error) {
	var directories []string

	contentdir := to.String(host.Settings.Get("content", "markdown"))
	if contentdir == "" {
		directories = []string{
			"content",
			"markdown",
		}
	} else {
		directories = []string{contentdir}
	}

	for _, directory := range directories {
		path := host.DocumentRoot + pathSeparator + directory
		if _, err := os.Stat(path); err == nil {
			return path, nil
		}
	}

	return "", errors.New(`Content directory was not found.`)
}

// readFile attempts to read a file from disk and returns its contents.
func readFile(file string) (string, error) {
	var buf []byte
	var err error

	if buf, err = ioutil.ReadFile(file); err != nil {
		return "", fmt.Errorf("Could not read file %s: %s", file, err.Error())
	}

	return string(buf), nil
}

// Close removes the watcher that is currently associated with the host.
func (host *Host) Close() {
	host.Watcher.Close()
}

// asset returns a relative URL.
func (host *Host) asset(assetURL string) string {
	if !host.isExternalLink(assetURL) {
		assetURL = strings.TrimLeft(assetURL, "/")
		p := strings.Trim(host.Path, "/")
		if p == "" {
			return "/" + assetURL
		}
		return "/" + p + "/" + assetURL
	}
	return assetURL
}

// url returns an absolute URL.
func (host *Host) url(url string) string {
	if host.isExternalLink(url) == false {
		return "//" + host.Request.Host + "/" + strings.TrimLeft(url, "/")
	}
	return url
}

// isExternalLink returns true if the given URL is outside this host.
func (host *Host) isExternalLink(url string) bool {
	return isExternalLinkPattern.MatchString(url)
}

// setting function returns a setting value.
func (host *Host) setting(path string) interface{} {
	route := strings.Split(path, "/")
	args := make([]interface{}, len(route))
	for i := range route {
		args[i] = route[i]
	}
	setting := host.Settings.Get(args...)
	return fixSetting(setting)
}

// fixSetting returns additional keys to make certain maps act like anchors.
func fixSetting(setting interface{}) interface{} {

	if m, ok := setting.(map[interface{}]interface{}); ok {
		for k, v := range m {
			switch k {
			case "text":
				m["Text"] = v
			case "link", "url":
				m["URL"] = v
			}
		}
	}

	return setting
}

// settings is a function that returns an array of settings.
func (host *Host) settings(path string) []interface{} {
	route := strings.Split(path, "/")
	args := make([]interface{}, len(route))
	for i := range route {
		args[i] = route[i]
	}
	val := host.Settings.Get(args...)
	if val == nil {
		return nil
	}

	ival := val.([]interface{})

	for i := range ival {
		ival[i] = fixSetting(ival[i])
	}

	return ival
}

// javascriptText is a function for funcMap that writes text as Javascript.
func javascriptText(text string) template.JS {
	return template.JS(text)
}

// htmlText is a function for funcMap that writes text as plain HTML.
func htmlText(text string) template.HTML {
	return template.HTML(text)
}

// Function for funcMap that writes links.
func (host *Host) anchor(url, text string) template.HTML {
	if host.isExternalLink(url) {
		return template.HTML(fmt.Sprintf(`<a target="_blank" href="%s">%s</a>`, host.asset(url), text))
	}
	return template.HTML(fmt.Sprintf(`<a href="%s">%s</a>`, host.asset(url), text))
}

// guessFile checks for files names and returns a guessed name.
func guessFile(file string, descend bool) (string, os.FileInfo) {
	stat, err := os.Stat(file)

	file = strings.TrimRight(file, pathSeparator)

	if descend {
		if err == nil {
			if stat.IsDir() {
				f, s := guessFile(file+pathSeparator+"index", true)
				if s != nil {
					return f, s
				}
			}
			return file, stat
		}
		for _, extension := range extensions {
			f, s := guessFile(file+extension, false)
			if s != nil {
				return f, s
			}
		}
	}

	if err == nil {
		return file, stat
	}

	return "", nil
}

// readFile opens a file and reads its contents, if the file has the .md
// extension the contents are parsed and HTML is returned.
func (host *Host) readFile(file string) ([]byte, error) {
	var buf []byte
	var err error

	if buf, err = ioutil.ReadFile(file); err != nil {
		return nil, err
	}

	if strings.HasSuffix(file, ".tpl") {
		var out bytes.Buffer
		tpl, err := template.New("").Funcs(host.funcMap).Parse(string(buf))
		if err != nil {
			return nil, err
		}
		if err := tpl.Execute(&out, nil); err != nil {
			return nil, err
		}
		file = file[:len(file)-4]
		buf = out.Bytes()
	}

	if strings.HasSuffix(file, ".md") {
		buf = blackfriday.MarkdownCommon(buf)
	}

	return buf, nil
}

func chunk(value string) string {
	if value == "" {
		return "-"
	}
	return value
}

// ServeHTTP reads a request and creates an appropriate response.
func (host *Host) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	var localFile string

	// TODO: Fix this non-critical race condition.  We need to save some
	// variables in a per request basis, in particular the hostname. It may not
	// always match the host name we gave to it (i.e: the "default" hostname). A
	// per-request context would be useful.
	host.Request = req

	// Settings default status as not found.
	status := http.StatusNotFound

	// Default size is no size (-1).
	size := -1

	// Requested path
	reqpath := strings.TrimRight(req.URL.Path, "/")

	// Stripping path
	index := len(host.Path)

	// If the hosts contains a path and the request begins with the same path, it
	// is ignored for the matches.
	if reqpath[0:index] == host.Path {
		reqpath = reqpath[index:]
	}

	reqpath = strings.TrimRight(reqpath, "/")

	// Trying to match a file on webroot/
	webrootdir := to.String(host.Settings.Get("content", "webroot"))

	if webrootdir == "" {
		webrootdir = "webroot"
	}

	// Absolute local webroot.
	webroot := host.DocumentRoot + pathSeparator + webrootdir

	// Attempt to match a request with a file in webroot/.
	localFile = webroot + pathSeparator + reqpath

	stat, err := os.Stat(localFile)

	if err == nil {
		// File exists
		if stat.IsDir() == false {
			// Exists and it's not a directory, let's serve it.
			status = http.StatusOK // Changing status.
			http.ServeFile(w, req, localFile)
			size = int(stat.Size())
		}
	}

	// Was the status already changed?
	if status == http.StatusNotFound {

		// Absolute document root.
		var docroot string
		if docroot, err = host.getContentPath(); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		// Defining a filename to look for.
		testFile := docroot + pathSeparator + reqpath

		localFile, stat = guessFile(testFile, true)

		if stat != nil {

			if reqpath != "" {
				// Let's not accept paths ending in "/".
				if stat.IsDir() == false {
					if strings.HasSuffix(req.URL.Path, "/") == true {
						http.Redirect(w, req, "/"+host.Path+"/"+reqpath, 301)
						w.Write([]byte(http.StatusText(301)))
						return
					}
				} else {
					if strings.HasSuffix(req.URL.Path, "/") == false {
						http.Redirect(w, req, req.URL.Path+"/", 301)
						w.Write([]byte(http.StatusText(301)))
						return
					}
				}
			}

			// Creating a page.
			p := &page.Page{}

			p.FilePath = localFile
			p.BasePath = req.URL.Path

			relPath := localFile[len(docroot):]

			if stat.IsDir() == false {
				p.FileDir = path.Dir(localFile)
				p.BasePath = path.Dir(relPath)
			} else {
				p.FileDir = localFile
				p.BasePath = relPath
			}

			// Reading contents.
			content, err := host.readFile(localFile)

			if err == nil {
				p.Content = template.HTML(content)
			}

			p.FileDir = strings.TrimRight(p.FileDir, pathSeparator) + pathSeparator
			p.BasePath = strings.TrimRight(p.BasePath, pathSeparator) + pathSeparator

			// werc-like header and footer.
			hfile, hstat := guessFile(p.FileDir+"_header", true)

			if hstat != nil {
				hcontent, herr := host.readFile(hfile)
				if herr == nil {
					p.ContentHeader = template.HTML(hcontent)
				}
			}

			if strings.Trim(host.Path, pathSeparator) == strings.Trim(req.URL.Path, pathSeparator) {
				p.IsHome = true
			}

			// werc-like header and footer.
			ffile, fstat := guessFile(p.FileDir+"_footer", true)

			if fstat != nil {
				fcontent, ferr := host.readFile(ffile)
				if ferr == nil {
					p.ContentFooter = template.HTML(fcontent)
				}
			}

			p.CreateBreadCrumb()
			p.CreateMenu()
			p.CreateSideMenu()

			p.ProcessContent()

			// Applying template.
			if err = host.Templates["index.tpl"].Execute(w, p); err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				status = http.StatusInternalServerError
			} else {
				status = http.StatusOK
			}

		}
	}

	if status == http.StatusNotFound {
		http.Error(w, "Not found", http.StatusNotFound)
	}

	// Log line.
	logLine := []string{
		chunk(req.RemoteAddr),
		chunk(""),
		chunk(""),
		chunk("[" + time.Now().Format("02/Jan/2006:15:04:05 -0700") + "]"),
		chunk("\"" + fmt.Sprintf("%s %s %s", req.Method, req.RequestURI, req.Proto) + "\""),
		chunk(fmt.Sprintf("%d", status)),
		chunk(fmt.Sprintf("%d", size)),
	}

	fmt.Println(strings.Join(logLine, " "))
}

func (host *Host) loadTemplate(file string) error {
	var err error

	// Reading template file.
	var text string
	if text, err = readFile(file); err != nil {
		return err
	}

	// Fixing template.
	text = fixDeprecatedSyntax(text)

	// Allocating name.
	name := path.Base(file)
	parsed := template.New(name).Funcs(host.funcMap)

	if _, err = parsed.Parse(text); err != nil {
		return err
	}

	host.Templates[name] = parsed

	if host.Watcher != nil {
		host.Watcher.RemoveWatch(file)
		host.Watcher.Watch(file)
	}

	return nil
}

// loadTemplates loads templates with .tpl extension from the templates
// directory. At this moment only index.tpl is expected.
func (host *Host) loadTemplates() error {
	var err error
	var fp *os.File

	tpldir := to.String(host.Settings.Get("content", "templates"))

	if tpldir == "" {
		tpldir = "templates"
	}

	tplroot := host.DocumentRoot + pathSeparator + tpldir

	if fp, err = os.Open(tplroot); err != nil {
		return fmt.Errorf("Error trying to open %s: %q", tplroot, err)
	}

	defer fp.Close()

	host.TemplateRoot = tplroot

	var files []os.FileInfo
	if files, err = fp.Readdir(-1); err != nil {
		return fmt.Errorf("Error reading directory %s: %q", tplroot, err)
	}

	for _, fp := range files {

		if strings.HasSuffix(fp.Name(), ".tpl") == true {

			file := host.TemplateRoot + pathSeparator + fp.Name()

			err := host.loadTemplate(file)

			if err != nil {
				log.Printf("%s: Template error in file %s: %q\n", host.Name, file, err)
			}

		}
	}

	if _, ok := host.Templates["index.tpl"]; ok == false {
		return fmt.Errorf("Template %s could not be found.", "index.tpl")
	}

	return nil

}

func (host *Host) fileWatcher() error {

	var err error

	/*
		// File watcher.
		host.Watcher, err = fsnotify.NewWatcher()

		if err == nil {

			go func() {

				for {

					select {

					case ev := <-host.Watcher.Event:

						fmt.Printf("%s: got ev: %v\n", host.Name, ev)

						if ev == nil {
							return
						}

						if ev.IsModify() {
							// Is settings file?
							if ev.Name == host.DocumentRoot+pathSeparator+settingsFile {
								log.Printf("%s: Reloading host settings %s...\n", host.Name, ev.Name)
								err := host.loadSettings()

								if err != nil {
									log.Printf("%s: Could not reload host settings: %s\n", host.Name, host.DocumentRoot+pathSeparator+settingsFile)
								}
							}

							// Is a template?
							if strings.HasPrefix(ev.Name, host.TemplateRoot) == true {

								if strings.HasSuffix(ev.Name, ".tpl") == true {
									log.Printf("%s: Reloading template %s\n", host.Name, ev.Name)
									host.loadTemplate(ev.Name)

									if err != nil {
										log.Printf("%s: Could not reload template %s: %q\n", host.Name, ev.Name, err)
									}

								}
							}

						} else if ev.IsDelete() {
							// Attemping to re-add watcher.
							host.Watcher.RemoveWatch(ev.Name)
							host.Watcher.Watch(ev.Name)
						}

					}
				}

			}()

		}
	*/

	// (Stupid) file modification watcher.
	host.Watcher, err = watcher.New()

	if err == nil {

		go func() {

			for {
				select {
				case ev := <-host.Watcher.Event:

					if ev.IsModify() {
						// Is settings file?
						if ev.Name == host.DocumentRoot+pathSeparator+settingsFile {
							log.Printf("%s: Reloading host settings %s...\n", host.Name, ev.Name)
							err := host.loadSettings()

							if err != nil {
								log.Printf("%s: Could not reload host settings: %s\n", host.Name, host.DocumentRoot+pathSeparator+settingsFile)
							}
						}

						// Is a template?
						if strings.HasPrefix(ev.Name, host.TemplateRoot) == true {
							if strings.HasSuffix(ev.Name, ".tpl") == true {
								log.Printf("%s: Reloading template %s\n", host.Name, ev.Name)
								host.loadTemplate(ev.Name)
								if err != nil {
									log.Printf("%s: Could not reload template %s: %q\n", host.Name, ev.Name, err)
								}
							}
						}
					}
				}
			}
		}()
	}

	return err

}

// loadSettings loads settings for the host.
func (host *Host) loadSettings() error {

	var settings *yaml.Yaml

	file := host.DocumentRoot + pathSeparator + settingsFile

	_, err := os.Stat(file)

	if err == nil {
		settings, err = yaml.Open(file)
		if err != nil {
			return fmt.Errorf(`Could not parse settings file (%s): %q`, file, err)
		}
	} else {
		return fmt.Errorf(`Error trying to open settings file (%s): %q.`, file, err)
	}

	if host.Watcher != nil {
		host.Watcher.RemoveWatch(file)
		host.Watcher.Watch(file)
	}

	host.Settings = settings

	return nil
}

// New creates and returns a host.
func New(name string, root string) (*Host, error) {

	_, err := os.Stat(root)

	if err != nil {
		log.Printf("Error reading directory %s: %q\n", root, err)
		log.Printf("Checkout an example directory at https://github.com/xiam/luminos/tree/master/default\n")

		return nil, err
	}

	route := "/"
	name = strings.TrimRight(name, "/")

	index := strings.Index(name, "/")
	if index > -1 {
		route = name[index:]
	}

	host := &Host{
		Name:         strings.TrimRight(name, "/"),
		Path:         strings.TrimRight(route, "/"),
		DocumentRoot: root,
		Templates:    make(map[string]*template.Template),
	}

	host.funcMap = template.FuncMap{
		"url":    func(s string) string { return host.url(s) },
		"anchor": func(a, b string) template.HTML { return host.anchor(a, b) },
		"asset":  func(s string) string { return host.asset(s) },
		"include": func(f string) string {
			s, err := readFile(host.DocumentRoot + "/" + f)
			if err != nil {
				log.Printf("readFile: %q", err)
			}
			return s
		},
		"setting":  func(s string) interface{} { return host.setting(s) },
		"settings": func(s string) []interface{} { return host.settings(s) },
		"js":       javascriptText,
		"html":     htmlText,
	}

	// Watcher
	host.fileWatcher()

	// Loading host settings
	if err = host.loadSettings(); err != nil {
		log.Printf("Could not start host: %s\n", name)
		return nil, err
	}

	// Loading templates.
	if err = host.loadTemplates(); err != nil {
		log.Printf("Could not start host: %s\n", name)
		return nil, err
	}

	log.Printf("Routing: %s -> %s\n", name, root)

	return host, nil

}


text:
import unittest
import IECore

class MarschnerLookupTableOpTest( unittest.TestCase ) :

	def testMarschnerLookupTable( self ) :

		m = IECore.MarschnerParameter( "marschner", "model parameters", True )

		# Make sure that we don't fail just because the defaults have changed.
		m["refraction"] = 1.55
		m["color"] =  IECore.Color3f( 0.7, 0.5, 0.1 )
		m["eccentricity"] = 1.0
		m["shiftR"] = -8.0
		m["shiftTT"] = 4.0
		m["shiftTRT"] = 12.0
		m["widthR"] = 10.0
		m["widthTT"] = 5.0
		m["widthTRT"] = 20.0
		m["glint"] = 1.0
		m["causticWidth"] = 20.0
		m["causticFade"] = 0.2
		m["causticLimit"] = 0.5

		result = IECore.MarschnerLookupTableOp()( model = m.getValue(), resolution = 128 )

		expectedResult = IECore.Reader.create( "test/IECore/data/expectedResults/marschnerLookup.exr" ).read()

		diffOp = IECore.ImageDiffOp()
		diff = diffOp( imageA = result, imageB = expectedResult ).value

		self.failIf( diff )

	def testInit( self ) :

		op = IECore.MarschnerLookupTableOp()
		self.failUnless( "color" in op.parameters()["model"] )

		op = IECore.MarschnerLookupTableOp( False )
		self.failUnless( "absorption" in op.parameters()["model"] )

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


text:
from __future__ import absolute_import, unicode_literals

import functools
import logging
import os
import socket

import tornado.escape
import tornado.ioloop
import tornado.web
import tornado.websocket

import mopidy
from mopidy import core, models
from mopidy.internal import encoding, jsonrpc

logger = logging.getLogger(__name__)

def make_mopidy_app_factory(apps, statics):
    def mopidy_app_factory(config, core):
        return [
            (r'/ws/?', WebSocketHandler, {
                'core': core,
            }),
            (r'/rpc', JsonRpcHandler, {
                'core': core,
            }),
            (r'/(.+)', StaticFileHandler, {
                'path': os.path.join(os.path.dirname(__file__), 'data'),
            }),
            (r'/', ClientListHandler, {
                'apps': apps,
                'statics': statics,
            }),
        ]
    return mopidy_app_factory

def make_jsonrpc_wrapper(core_actor):
    inspector = jsonrpc.JsonRpcInspector(
        objects={
            'core.get_uri_schemes': core.Core.get_uri_schemes,
            'core.get_version': core.Core.get_version,
            'core.history': core.HistoryController,
            'core.library': core.LibraryController,
            'core.mixer': core.MixerController,
            'core.playback': core.PlaybackController,
            'core.playlists': core.PlaylistsController,
            'core.tracklist': core.TracklistController,
        })
    return jsonrpc.JsonRpcWrapper(
        objects={
            'core.describe': inspector.describe,
            'core.get_uri_schemes': core_actor.get_uri_schemes,
            'core.get_version': core_actor.get_version,
            'core.history': core_actor.history,
            'core.library': core_actor.library,
            'core.mixer': core_actor.mixer,
            'core.playback': core_actor.playback,
            'core.playlists': core_actor.playlists,
            'core.tracklist': core_actor.tracklist,
        },
        decoders=[models.model_json_decoder],
        encoders=[models.ModelJSONEncoder]
    )

def _send_broadcast(client, msg):
    # We could check for client.ws_connection, but we don't really
    # care why the broadcast failed, we just want the rest of them
    # to succeed, so catch everything.
    try:
        client.write_message(msg)
    except Exception as e:
        error_msg = encoding.locale_decode(e)
        logger.debug('Broadcast of WebSocket message to %s failed: %s',
                     client.request.remote_ip, error_msg)
        # TODO: should this do the same cleanup as the on_message code?

class WebSocketHandler(tornado.websocket.WebSocketHandler):

    # XXX This set is shared by all WebSocketHandler objects. This isn't
    # optimal, but there's currently no use case for having more than one of
    # these anyway.
    clients = set()

    @classmethod
    def broadcast(cls, msg):
        if hasattr(tornado.ioloop.IOLoop, 'current'):
            loop = tornado.ioloop.IOLoop.current()
        else:
            loop = tornado.ioloop.IOLoop.instance()  # Fallback for pre 3.0

        # This can be called from outside the Tornado ioloop, so we need to
        # safely cross the thread boundary by adding a callback to the loop.
        for client in cls.clients:
            # One callback per client to keep time we hold up the loop short
            # NOTE: Pre 3.0 does not support *args or **kwargs...
            loop.add_callback(functools.partial(_send_broadcast, client, msg))

    def initialize(self, core):
        self.jsonrpc = make_jsonrpc_wrapper(core)

    def open(self):
        if hasattr(self, 'set_nodelay'):
            # New in Tornado 3.1
            self.set_nodelay(True)
        else:
            self.stream.socket.setsockopt(
                socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        self.clients.add(self)
        logger.debug(
            'New WebSocket connection from %s', self.request.remote_ip)

    def on_close(self):
        self.clients.discard(self)
        logger.debug(
            'Closed WebSocket connection from %s',
            self.request.remote_ip)

    def on_message(self, message):
        if not message:
            return

        logger.debug(
            'Received WebSocket message from %s: %r',
            self.request.remote_ip, message)

        try:
            response = self.jsonrpc.handle_json(
                tornado.escape.native_str(message))
            if response and self.write_message(response):
                logger.debug(
                    'Sent WebSocket message to %s: %r',
                    self.request.remote_ip, response)
        except Exception as e:
            error_msg = encoding.locale_decode(e)
            logger.error('WebSocket request error: %s', error_msg)
            if self.ws_connection:
                # Tornado 3.2+ checks if self.ws_connection is None before
                # using it, but not older versions.
                self.close()

    def check_origin(self, origin):
        # Allow cross-origin WebSocket connections, like Tornado before 4.0
        # defaulted to.
        return True

def set_mopidy_headers(request_handler):
    request_handler.set_header('Cache-Control', 'no-cache')
    request_handler.set_header(
        'X-Mopidy-Version', mopidy.__version__.encode('utf-8'))

class JsonRpcHandler(tornado.web.RequestHandler):

    def initialize(self, core):
        self.jsonrpc = make_jsonrpc_wrapper(core)

    def head(self):
        self.set_extra_headers()
        self.finish()

    def post(self):
        data = self.request.body
        if not data:
            return

        logger.debug(
            'Received RPC message from %s: %r', self.request.remote_ip, data)

        try:
            self.set_extra_headers()
            response = self.jsonrpc.handle_json(
                tornado.escape.native_str(data))
            if response and self.write(response):
                logger.debug(
                    'Sent RPC message to %s: %r',
                    self.request.remote_ip, response)
        except Exception as e:
            logger.error('HTTP JSON-RPC request error: %s', e)
            self.write_error(500)

    def set_extra_headers(self):
        set_mopidy_headers(self)
        self.set_header('Accept', 'application/json')
        self.set_header('Content-Type', 'application/json; utf-8')

class ClientListHandler(tornado.web.RequestHandler):

    def initialize(self, apps, statics):
        self.apps = apps
        self.statics = statics

    def get_template_path(self):
        return os.path.dirname(__file__)

    def get(self):
        set_mopidy_headers(self)

        names = set()
        for app in self.apps:
            names.add(app['name'])
        for static in self.statics:
            names.add(static['name'])
        names.discard('mopidy')

        self.render('data/clients.html', apps=sorted(list(names)))

class StaticFileHandler(tornado.web.StaticFileHandler):

    def set_extra_headers(self, path):
        set_mopidy_headers(self)

class AddSlashHandler(tornado.web.RequestHandler):

    @tornado.web.addslash
    def prepare(self):
        return super(AddSlashHandler, self).prepare()