text:
/**
 * The Store of our example app, which allows you to search for and display GitHub users.
 *
 * Based on the initial state and the actions alone present on this page,
 * you should be able to determine what this app does.
 */

"use strict";

import 'whatwg-fetch';
import _debounce from 'lodash.debounce';
import { createStore } from 'redu'; // will create a StoreComponent wrapping the top-most component.

import Page from '../components/Page'; // our top-most component.

/**
 * Create our PageStore StoreComponent.
 *
 * @type {StoreComponent}
 */
const PageStore = createStore(Page);

/**
 * These are the props that we'd like our StoreComponent to have.
 * Consequently, all our actions and our SubscriberComponents
 * will also gain access to these props.
 *
 * This is a handy place to put utilities and config that will be used across the application.
 */
PageStore.defaultProps = {
    utils: {
        searchApi(query) {
            return fetch(`https://api.github.com/search/users?q=${encodeURIComponent(query)}`)
                .then((resp) => resp.json());
        }
    }
};

/**
 * This is the full representation of the application-level state that we would like to keep track of
 * across all components.
 */
PageStore.initialState = {
    searchQuery: '',
    userToDisplay: null,
    usersListItems: null
};

/**
 * The actions you can perform to change the StoreComponent's state.
 *
 * They are all bound to the StoreComponent, so you have access to it's setState function,
 * props, and other action functions.
 */
PageStore.actions = {

    /**
     * Select a user to display on the right hand side.
     *
     * @param {{}} userToDisplay
     */
    displayUser(userToDisplay) {

        this.setState({ userToDisplay });
    },

    /**
     * Reset the search.
     *
     */
    reset() {

        this.setState(PageStore.initialState);
    },
    /**
     * Search for a GitHub user.
     *
     * Notice that this action calls another action.
     * All actions are available in the "actions" property of the StoreComponent,
     * so you can simply call this.actions[actionName] to access one
     * action from another.
     *
     * @param {string} searchQuery
     */
    search(searchQuery) {

        this.setState({ searchQuery }); // using the StoreComponent's this.setState

        this.actions.debouncedSearch(searchQuery); // call another action from this action.
    },

    /**
     * Only starts a search 500ms after typing.
     *
     * Notice that this action is asynchronous.
     *
     * Since you have access to the StoreComponent's this.setState,
     * you can perform an async operations and call setState before and after easily.
     *
     * @param {string} searchQuery
     */
    debouncedSearch: _debounce(function debouncedSearch(searchQuery) {

        this.setState({
            searchQuery,
            usersListItems: null // indicates that we're currently fetching these
        });

        /**
         * Using the StoreComponent's props.utils.searchApi.
         */
        this.props.utils.searchApi(searchQuery).then((results) => {

            this.setState({
                usersListItems: results.items || []
            });
        });

    }, 500)
};

export default PageStore;


text:
package protectedblob

import (
	"crypto/aes"
	"crypto/rand"
	"crypto/sha256"
	"golang.org/x/crypto/pbkdf2"
)

type KDF interface {
	Name() string
	Validate(src ProtectedKey) error
	Encrypt(key []byte, passphrase string, rounds int32) (ProtectedKey, error)
	Decrypt(src ProtectedKey, passphrase string) ([]byte, error)
}

type _PBKDF2SHA256AES256 struct {
}

var PBKDF2SHA256AES256 = _PBKDF2SHA256AES256{}

func (kdf _PBKDF2SHA256AES256) Name() string {
	return "PBKDF2-SHA256-AES256"
}

func (kdf _PBKDF2SHA256AES256) Validate(src ProtectedKey) error {
	if len(src.Salt) != sha256.Size {
		return blobError("Invalid Salt")
	}

	if src.Rounds < 1 {
		return blobError("Invalid Rounds")
	}

	if len(src.EncryptedKey) != 32 {
		return blobError("Invalid EncryptedKey")
	}

	return nil
}

func (kdf _PBKDF2SHA256AES256) Decrypt(src ProtectedKey, passphrase string) ([]byte, error) {
	key := pbkdf2.Key([]byte(passphrase), src.Salt, int(src.Rounds), 32, sha256.New)
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	decryptedKey := make([]byte, aes.BlockSize*2)
	block.Decrypt(decryptedKey[:aes.BlockSize], src.EncryptedKey[:aes.BlockSize])
	block.Decrypt(decryptedKey[aes.BlockSize:], src.EncryptedKey[aes.BlockSize:])
	return decryptedKey, nil
}

func (kdf _PBKDF2SHA256AES256) Encrypt(key []byte, passphrase string, rounds int32) (ProtectedKey, error) {
	if len(key) != 32 {
		return ProtectedKey{}, blobError("Invalid key size")
	}

	if rounds < 1 {
		return ProtectedKey{}, blobError("Invalid Rounds")
	}

	salt := make([]byte, sha256.Size)
	if _, err := rand.Read(salt); err != nil {
		return ProtectedKey{}, err
	}

	encryptionKey := pbkdf2.Key([]byte(passphrase), salt, int(rounds), 32, sha256.New)
	block, err := aes.NewCipher(encryptionKey)
	if err != nil {
		return ProtectedKey{}, err
	}

	encryptedKey := make([]byte, 32)
	block.Encrypt(encryptedKey[:aes.BlockSize], key[:aes.BlockSize])
	block.Encrypt(encryptedKey[aes.BlockSize:], key[aes.BlockSize:])
	return ProtectedKey{Salt: salt, Rounds: rounds, EncryptedKey: encryptedKey}, nil
}

redpajama_set_name: RedPajamaGithub


text:
define({
  "_widgetLabel": "Shrnutí informací",
  "title": "Widget InfoSummary",
  "helpText": "Text nápovědy shrnutí informací",
  "expand": "Zapnout seznam prvků",
  "logoPrefix": "Logo "
});


text:
var C = require( '../constants/constants' ),
	EventEmitter = require( 'component-emitter' );

/**
 * Subscriptions to events are in a pending state until deepstream acknowledges
 * them. This is a pattern that's used by numerour classes. This registry aims
 * to centralise the functionality necessary to keep track of subscriptions and
 * their respective timeouts.
 *
 * @param {Client} client          The deepstream client
 * @param {String} topic           Constant. One of C.TOPIC
 * @param {Number} timeoutDuration The duration of the timeout in milliseconds
 *
 * @extends {EventEmitter}
 * @constructor
 */
var AckTimeoutRegistry = function( client, topic, timeoutDuration ) {
	this._client = client;
	this._topic = topic;
	this._timeoutDuration = timeoutDuration;
	this._register = {};
};

EventEmitter( AckTimeoutRegistry.prototype );

/**
 * Add an entry
 *
 * @param {String} name An identifier for the subscription, e.g. a record name or an event name.
 *
 * @public
 * @returns {void}
 */
AckTimeoutRegistry.prototype.add = function( name, action ) {
	var uniqueName = action ? action + name : name;

	this.remove( name, action );
	this._register[ uniqueName ] = setTimeout( this._onTimeout.bind( this, uniqueName, name ), this._timeoutDuration );
};

/**
 * Remove an entry
 *
 * @param {String} name An identifier for the subscription, e.g. a record name or an event name.
 *
 * @public
 * @returns {void}
 */
AckTimeoutRegistry.prototype.remove = function( name, action ) {
	var uniqueName = action ? action + name : name;

	if( this._register[ uniqueName ] ) {
		this.clear( {
			data: [ action, name ]
		} );
	}
};

/**
 * Processes an incoming ACK-message and removes the corresponding subscription
 *
 * @param   {Object} message A parsed deepstream ACK message
 *
 * @public
 * @returns {void}
 */
AckTimeoutRegistry.prototype.clear = function( message ) {
	var name = message.data[ 1 ];
	var uniqueName = message.data[ 0 ] + name;
	var timeout =  this._register[ uniqueName ] || this._register[ name ];

	if( timeout ) {
		clearTimeout( timeout );
	} else {
		this._client._$onError( this._topic, C.EVENT.UNSOLICITED_MESSAGE, message.raw );
	}
};

/**
 * Will be invoked if the timeout has occured before the ack message was received
 *
 * @param {String} name An identifier for the subscription, e.g. a record name or an event name.
 *
 * @private
 * @returns {void}
 */
AckTimeoutRegistry.prototype._onTimeout = function( uniqueName, name ) {
	delete this._register[ uniqueName ];
	var msg = 'No ACK message received in time for ' + name;
	this._client._$onError( this._topic, C.EVENT.ACK_TIMEOUT, msg );
	this.emit( 'timeout', name );
};

module.exports = AckTimeoutRegistry;


text:
<?php

/**
 * component actions.
 *
 * @package    sf_sandbox
 * @subpackage component
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 2692 2006-11-15 21:03:55Z fabien $
 */
class componentActions extends sfActions
{
  /**
   * Executes index action
   *
   */
  public function executeIndex()
  {
    $this->forward('default', 'module');
  }
}


text:
Introduction
================
Nous parlerons ici de l'installation sous Linux. Pour l'installer sous windows, il faudra aller voir http://www.siteduzero.com/forum-83-785145-p1-jeu-video-astropong.html.

Téléchargement
================
Vous devez tout d'abord télécharger l'archive. Si vous utilisez git, vous pouvez faire :
git clone git://github.com/lucas8/astropong.git
Sinon, vous devez faire :
wget https://github.com/lucas8/astropong/archive/master.zip
unzip master.zip

Compilation
================
Vous devez ensuite vous placer dans le dossier des sources. Pour compiler, il faut que vous ayez sfml 1.6 d'installée.
Ouvrez le Makefile avec votre editeur de texte préféré et modifiez les deux lignes suivantes en fonction de votre système :

CXXFLAGS=-I/path/vers/includes/de/sfml

LDFLAGS=-lnom_sfml1.6-{audio,graphics,system,window,network}

Ensuite tapez 'make'. Normalement, vous devriez avoir un programme astropong. Si non, vous avez du vous tromper lors de la modification des deux lignes précédentes.

Les ressources
================
Afin de pouvoir lancer le jeu, vous devez télécharger les ressources. Vous pouvez les obtenir avec la commande suivante :
wget https://github.com/downloads/lucas8/astropong/res.tar.gz
Vous obtenez une archive .tar.gz qui contient un dossier res. Vous devez placer ce dossier dans le même dossier que le programme astropong.

Enjoy
================
Vous pouvez maintenant lancer astropong de cette manière :
./astropong
N'hésitez pas à faire part de vos retour à l'adresse suivante : http://www.siteduzero.com/forum-83-785145-p2-jeu-video-astropong.html


text:
@interface RefreshView ()
@property (nonatomic, strong) UIActivityIndicatorView *indicatorView;
@property (nonatomic, strong) CAShapeLayer *whiteCircleLayer;
@property (nonatomic, strong) CAShapeLayer *grayCircleLayer;

@end

@implementation RefreshView

- (id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        _indicatorView = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
        [self addSubview:_indicatorView];

        CGFloat radius = MIN(frame.size.width, frame.size.height)/2 - 3;
        _grayCircleLayer = [[CAShapeLayer alloc]init];
        _grayCircleLayer.lineWidth = 0.5f;
        _grayCircleLayer.strokeColor = [UIColor grayColor].CGColor;
        _grayCircleLayer.fillColor = [UIColor clearColor].CGColor;
        _grayCircleLayer.opacity = 0.f;
        _grayCircleLayer.path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(frame.size.width/2-radius, frame.size.height/2-radius, 2*radius, 2*radius)].CGPath;
        [self.layer addSublayer:_grayCircleLayer];

        _whiteCircleLayer = [[CAShapeLayer alloc]init];
        _whiteCircleLayer.lineWidth = 1.0f;
        _whiteCircleLayer.strokeColor = [UIColor whiteColor].CGColor;
        _whiteCircleLayer.fillColor = [UIColor clearColor].CGColor;
        _whiteCircleLayer.strokeEnd = 0.f;
        _whiteCircleLayer.path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(self.frame.size.width / 2, self.frame.size.height /2 ) radius:radius startAngle:M_PI_2 endAngle:M_PI * 5/2 clockwise:YES].CGPath;
        [self.layer addSublayer:_whiteCircleLayer];
    }
    return self;
}

- (void)RedrawFromProgress:(CGFloat)progress{
    if (progress > 0) {
        _whiteCircleLayer.opacity = 1.f;
        _grayCircleLayer.opacity = 1.f;
        _whiteCircleLayer.strokeEnd = progress;
        if (progress == 1) {
            _whiteCircleLayer.opacity = 0.f;
            _grayCircleLayer.opacity = 0.f;
        }
    }else if (progress <= 0){
        _whiteCircleLayer.opacity = 0.f;
        _grayCircleLayer.opacity = 0.f;
    }
}
- (void)startAnimation{
    [_indicatorView startAnimating];
}
- (void)stopAnimation{
    [_indicatorView stopAnimating];
}

@end


text:
/**
 * Handles read/write for flat GeoJSON files like those from MongoDB.
 * Considered creating a custom OL format inheriting from GeoJSON, but
 * loadingstrategy needs non-exported values, and generally more trouble than worth.
 */
import Feature from "ol/Feature.js";
import GeoJSON from "ol/format/GeoJSON.js";

// import { Feature, GeoJSON } from './deps.js';

export default {
  /**
   * params: input: array of Mongo documents (or stringified version);
   *         opts: like Format with FeatureProjection
   * returns: array of ol features
   */
  readFeatures: function(input, opts) {
    if (typeof input === 'string') {
      input = JSON.parse(input);
    }
    const features = [];
    input.forEach(r => {
      const feature = new Feature();
      for (const key in r) {
        if (key == 'id') {
          feature.setId(r[key]);
        // geometry not necessarily called 'geometry' but has type/coordinates
        } else if (r[key] && r[key].type && r[key].coordinates) {
          let geom = new ol[r[key].type](r[key].coordinates);
          if (opts && opts.featureProjection) {
            geom.transform('EPSG:4326', opts.featureProjection);
          }
          feature.setGeometry(geom);
        } else {
          feature.set(key, r[key]);
        }
      }
      features.push(feature);
    });
    return features;
  },

  /**
   * uses GeoJSON to output features, and then rearranges so properties top-level
   * params: input: array of ol features; opts: like Format with FeatureProjection
   * returns: stringified array of Mongo documents (always in 4326)
   */
  writeFeatures: function(input, opts) {
    const out = [];
    const geojson = new GeoJSON();
    const features = JSON.parse(geojson.writeFeatures(input, opts)).features;
    features.forEach(f => {
      const feature = {
        id: f.id,
        geometry: f.geometry
      };
      for (const key in f.properties) {
        feature[key] = f.properties[key];
      }
      out.push(feature);
    });
    return JSON.stringify(out);
  }
};


text:
import { useRouter } from 'next/router'

const Page = () => {
  const router = useRouter()
  const { post, id } = router.query

  return (
    <>
      <p>{`Blog post ${post} comment ${id || '(all)'}`}</p>
    </>
  )
}

Page.getInitialProps = () => ({})

export default Page


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ExamMaster.Frontend
{
    public partial class RoundProgress : UserControl
    {

        private float time = 0;
        private float easing = 0;
        private float _reachedPercent = 0f;

        public RoundProgress()
        {
            InitializeComponent();
            DoubleBuffered = true;
        }

        private void RoundProgress_Paint(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;

            int width = Width / 8;
            int innerWidth = width * 2;

            g.FillEllipse(Brushes.LightGray, 0, 0, Width, Height);
            Color lerped;
            float currentPercentage = easing * (ReachedPercent / 100f);
            if (currentPercentage > 0.75f)
            {
                lerped = Lerp(Color.Yellow, Color.Green, (currentPercentage - 0.75f) * 4f);
            }
            else
            {
                lerped = Lerp(Color.Red, Color.Yellow, currentPercentage * 4f);
            }
            using (SolidBrush lerpedBrush = new SolidBrush(lerped), darklerpedBrush = new SolidBrush(Color.FromArgb(255,lerped.R / 2, lerped.G / 2, lerped.B / 2)))
            {
                g.FillPie(lerpedBrush, 0, 0, Width, Height, -90, easing * (ReachedPercent / 100f * 360f));
                g.FillEllipse(Brushes.MintCream, width, width, Width - innerWidth, Height - innerWidth);

                string reachedString = "" + (int) Math.Round(easing * ReachedPercent) + "%";
                SizeF size = g.MeasureString(reachedString, Font);
                g.DrawString(reachedString, Font, darklerpedBrush, Width / 2 - size.Width / 2,
                             Height / 2 - size.Height / 2 + 2);
            }
        }

        private Color Lerp(Color a, Color b, float factor)
        {
            float f = Math.Max(Math.Min(factor, 1), 0);
            int A = (int)((b.A - a.A) * f + a.A);
            int R = (int)((b.R - a.R) * f + a.R);
            int G = (int)((b.G - a.G) * f + a.G);
            int B = (int)((b.B - a.B) * f + a.B);
            return Color.FromArgb(A, R, G, B);
        }

        private float EaseInOut(float t, float b, float c, float d)
        {
            t /= d / 2;
            if (t < 1) return c / 2 * t * t * t * t + b;
            t -= 2;
            return -c / 2 * (t * t * t * t - 2) + b;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            time += timer1.Interval * 0.001f * 0.5f; // interval * (1/1000) * (1/duration);
            if (time > 1) time = 1;
            easing = EaseInOut(time, 0, 1, 1);
            Refresh();
        }

        public float ReachedPercent
        {
            get
            {
                return _reachedPercent;
            }

            set
            {
                _reachedPercent = value;
                time = 0;
                easing = 0;
                timer1.Enabled = true;
            }
        }
    }
}


text:
package org.apache.nutch.indexer;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import org.apache.hadoop.io.*;

/**
 * This class represents a multi-valued field with a weight.
 * Values are arbitrary objects.
 */
public class NutchField implements Writable {
  private float weight;
  private List<Object> values = new ArrayList<Object>();

  public NutchField() { }

  public NutchField(Object value) {
    this(value, 1.0f);
  }

  public NutchField(Object value, float weight) {
    this.weight = weight;
    if (value instanceof Collection) {
      values.addAll((Collection<?>)value);
    } else {
      values.add(value);
    }
  }

  public void add(Object value) {
    values.add(value);
  }

  public float getWeight() {
    return weight;
  }

  public void setWeight(float weight) {
    this.weight = weight;
  }

  public List<Object> getValues() {
    return values;
  }

  public void reset() {
    weight = 1.0f;
    values.clear();
  }

  @Override
  public Object clone() throws CloneNotSupportedException {
    NutchField result = (NutchField)super.clone();
    result.weight = weight;
    result.values = values;

    return result;
  }

  @Override
  public void readFields(DataInput in) throws IOException {
    weight = in.readFloat();
    int count = in.readInt();
    values = new ArrayList<Object>();
    for (int i = 0; i < count; i++) {
      String type = Text.readString(in);

      if (type.equals("java.lang.String")) {
        values.add(Text.readString(in));
      } else if (type.equals("java.lang.Boolean")) {
        values.add(in.readBoolean());
      } else if (type.equals("java.lang.Integer")) {
        values.add(in.readInt());
      } else if (type.equals("java.lang.Float")) {
        values.add(in.readFloat());
      } else if (type.equals("java.util.Date")) {
        values.add(new Date(in.readLong()));
      }
    }
  }

  @Override
  public void write(DataOutput out) throws IOException {
    out.writeFloat(weight);
    out.writeInt(values.size());
    for (Object value : values) {

      Text.writeString(out, value.getClass().getName());

      if (value instanceof Boolean) {
        out.writeBoolean((Boolean)value);
      } else if (value instanceof Integer) {
        out.writeInt((Integer)value);
      } else if (value instanceof Long) {
        out.writeLong((Long)value);
      } else if (value instanceof Float) {
        out.writeFloat((Float)value);
      } else if (value instanceof String) {
        Text.writeString(out, (String)value);
      } else if (value instanceof Date) {
        Date date = (Date)value;
        out.writeLong(date.getTime());
      }
    }
  }

  public String toString() {
    return values.toString();
  }

}


text:
ENV["RAILS_ENV"] = "test"
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
require 'test_help'

class Test::Unit::TestCase
  include AuthenticatedTestHelper
  # Transactional fixtures accelerate your tests by wrapping each test method
  # in a transaction that's rolled back on completion.  This ensures that the
  # test database remains unchanged so your fixtures don't have to be reloaded
  # between every test method.  Fewer database queries means faster tests.
  #
  # Read Mike Clark's excellent walkthrough at
  #   http://clarkware.com/cgi/blosxom/2005/10/24#Rails10FastTesting
  #
  # Every Active Record database supports transactions except MyISAM tables
  # in MySQL.  Turn off transactional fixtures in this case; however, if you
  # don't care one way or the other, switching from MyISAM to InnoDB tables
  # is recommended.
  self.use_transactional_fixtures = true

  # Instantiated fixtures are slow, but give you @david where otherwise you
  # would need people(:david).  If you don't want to migrate your existing
  # test cases which use the @david style and don't mind the speed hit (each
  # instantiated fixtures translates to a database query per test method),
  # then set this back to true.
  self.use_instantiated_fixtures  = false

  # Add more helper methods to be used by all tests here...
end

module ActionController
  class TestRequest < AbstractRequest
    attr_accessor :user_agent
    def referer; return "http://www.test.com"; end
  end
end
module ApplicationHelper
  @@country_choices = [['España',71]]
  @@spain_id        = 71
end
module SecureActions
  protected
  # Called when URLs are generated.
  def default_url_options(options)
    defaults      = {}
    options.delete :override_only_path
    return defaults
  end
end


text:
layout: post
date: 2018-03-14
title: "Amelia Sposa Wedding dress Emilia Sleeveless Chapel Train Mermaid/Trumpet"
category: Amelia Sposa
tags: [Amelia Sposa,Mermaid/Trumpet,Sweetheart,Chapel Train,Sleeveless]
---
### Amelia Sposa Wedding dress Emilia
Just **$329.99**
###   Sleeveless Chapel Train Mermaid/Trumpet

BRANDS	Amelia Sposa

Silhouette	Mermaid/Trumpet

Neckline	Sweetheart

Hemline/Train	Chapel Train

Sleeve	Sleeveless

Buy it: [https://www.readybrides.com/en/amelia-sposa/379-wedding-dress-emilia.html](https://www.readybrides.com/en/amelia-sposa/379-wedding-dress-emilia.html)


text:
package resources

import "github.com/awslabs/goformation/cloudformation/policies"

// AWSECSTaskDefinition_HostVolumeProperties AWS CloudFormation Resource (AWS::ECS::TaskDefinition.HostVolumeProperties)
// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-volumes-host.html
type AWSECSTaskDefinition_HostVolumeProperties struct {

	// SourcePath AWS CloudFormation Property
	// Required: false
	// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-volumes-host.html#cfn-ecs-taskdefinition-volumes-host-sourcepath
	SourcePath string `json:"SourcePath,omitempty"`

	// _deletionPolicy represents a CloudFormation DeletionPolicy
	_deletionPolicy policies.DeletionPolicy

	// _dependsOn stores the logical ID of the resources to be created before this resource
	_dependsOn []string

	// _metadata stores structured data associated with this resource
	_metadata map[string]interface{}
}

// AWSCloudFormationType returns the AWS CloudFormation resource type
func (r *AWSECSTaskDefinition_HostVolumeProperties) AWSCloudFormationType() string {
	return "AWS::ECS::TaskDefinition.HostVolumeProperties"
}

// DependsOn returns a slice of logical ID names this resource depends on.
// see: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-dependson.html
func (r *AWSECSTaskDefinition_HostVolumeProperties) DependsOn() []string {
	return r._dependsOn
}

// SetDependsOn specify that the creation of this resource follows another.
// see: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-dependson.html
func (r *AWSECSTaskDefinition_HostVolumeProperties) SetDependsOn(dependencies []string) {
	r._dependsOn = dependencies
}

// Metadata returns the metadata associated with this resource.
// see: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-metadata.html
func (r *AWSECSTaskDefinition_HostVolumeProperties) Metadata() map[string]interface{} {
	return r._metadata
}

// SetMetadata enables you to associate structured data with this resource.
// see: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-metadata.html
func (r *AWSECSTaskDefinition_HostVolumeProperties) SetMetadata(metadata map[string]interface{}) {
	r._metadata = metadata
}

// SetDeletionPolicy applies an AWS CloudFormation DeletionPolicy to this resource
// see: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-deletionpolicy.html
func (r *AWSECSTaskDefinition_HostVolumeProperties) SetDeletionPolicy(policy policies.DeletionPolicy) {
	r._deletionPolicy = policy
}


text:
#ifndef RenderTreeUpdater_h
#define RenderTreeUpdater_h

#include "RenderTreePosition.h"
#include "StyleChange.h"
#include "StyleUpdate.h"
#include <wtf/HashMap.h>
#include <wtf/HashSet.h>
#include <wtf/ListHashSet.h>
#include <wtf/RefPtr.h>
#include <wtf/Vector.h>

namespace WebCore {

class ContainerNode;
class Document;
class Element;
class Node;
class RenderStyle;
class Text;

class RenderTreeUpdater {
public:
    RenderTreeUpdater(Document&);

    void commit(std::unique_ptr<Style::Update>);

    enum class TeardownType { Normal, KeepHoverAndActive };
    static void tearDownRenderers(Element&, TeardownType = TeardownType::Normal);
    static void tearDownRenderer(Text&);

private:
    void updateRenderTree(ContainerNode& root);
    void updateTextRenderer(Text&);
    void updateElementRenderer(Element&, Style::ElementUpdate&);
    void createRenderer(Element&, RenderStyle&&);
    void invalidateWhitespaceOnlyTextSiblingsAfterAttachIfNeeded(Node&);
    void updateBeforeOrAfterPseudoElement(Element&, PseudoId);

    struct Parent {
        Element* element { nullptr };
        Style::Change styleChange { Style::NoChange };
        Optional<RenderTreePosition> renderTreePosition;

        Parent(ContainerNode& root);
        Parent(Element&, Style::Change);
    };
    Parent& parent() { return m_parentStack.last(); }
    RenderTreePosition& renderTreePosition();

    void pushParent(Element&, Style::Change);
    void popParent();
    void popParentsToDepth(unsigned depth);

    Document& m_document;
    std::unique_ptr<Style::Update> m_styleUpdate;

    Vector<Parent> m_parentStack;

    HashSet<Text*> m_invalidatedWhitespaceOnlyTextSiblings;
};

}
#endif


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.04.20 at 03:09:04 PM EDT
//

package org.slc.sli.sample.entities;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for CourseAttemptResultType.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="CourseAttemptResultType">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}token">
 *     <enumeration value="Pass"/>
 *     <enumeration value="Fail"/>
 *     <enumeration value="Incomplete"/>
 *     <enumeration value="Withdrawn"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "CourseAttemptResultType")
@XmlEnum
public enum CourseAttemptResultType {

    @XmlEnumValue("Pass")
    PASS("Pass"),
    @XmlEnumValue("Fail")
    FAIL("Fail"),
    @XmlEnumValue("Incomplete")
    INCOMPLETE("Incomplete"),
    @XmlEnumValue("Withdrawn")
    WITHDRAWN("Withdrawn");
    private final String value;

    CourseAttemptResultType(String v) {
        value = v;
    }

    public String value() {
        return value;
    }

    public static CourseAttemptResultType fromValue(String v) {
        for (CourseAttemptResultType c: CourseAttemptResultType.values()) {
            if (c.value.equals(v)) {
                return c;
            }
        }
        throw new IllegalArgumentException(v);
    }

}


text:
This repo contains a sample app for implementing OAuth with Slack for new granular permission Slack apps. Checkout `app.js`. The code includes a few different options which have been commented out. As you play around with the app, you can uncomment some of these options to get a deeper understanding of how to use this library.

Local development requires a public URL where Slack can send requests. In this guide, we'll be using [`ngrok`](https://ngrok.com/download). Checkout [this guide](https://api.slack.com/tutorials/tunneling-with-ngrok) for setting it up.

Before we get started, make sure you have a development workspace where you have permissions to install apps. If you don't have one setup, go ahead and [create one](https://slack.com/create). You also need to [create a new app](https://api.slack.com/apps?new_app=1) if you haven't already.

This example uses the [Keyv](https://github.com/lukechilds/keyv) library as a database solution. Keyv has adaptors for many popular database solutions. You can use whatever database or wrapper you wish to.

## Install Dependencies

```
npm install
```

## Setup Environment Variables

This app requires you setup a few environment variables. You can get these values by navigating to your app's [**BASIC INFORMATION** Page](https://api.slack.com/apps).

```
export SLACK_CLIENT_ID=YOUR_SLACK_CLIENT_ID
export SLACK_CLIENT_SECRET=YOUR_SLACK_CLIENT_SECRET
export SLACK_SIGNING_SECRET=YOUR_SLACK_SIGNING_SECRET
```

## Run the App

Start the app with the following command:

```
npm start
```

This will start the app on port `3000`.

Now lets start `ngrok` so we can access the app on an external network and create a `redirect url` for OAuth.

```
ngrok http 3000
```

This should output a forwarding address for `http` and `https`. Take note of the `https` one. It should look something like the following:

```
Forwarding   https://3cb89939.ngrok.io -> http://localhost:3000
```

Go to your app on https://api.slack.com/apps and navigate to your apps **OAuth & Permissions** page. Under **Redirect URLs**, add your `ngrok` forwarding address with the `/slack/oauth_redirect` path appended. ex:

```
https://3cb89939.ngrok.io/slack/oauth_redirect
```

This app also listens to the `app_home_opened` event to illustrate fetching the saved token from the database and using it to publish a view on the home tab. Navigate to the **App Home** page in your app settings and enable it. Then navigate to **Event Subscriptions** to enable it. The request URL should be set to your `ngrok` forwarding address with the `slack/events` path appended. ex:

```
https://3cb89939.ngrok.io/slack/events
```

Lastly, in the **Events Subscription** page, click **Subscribe to bot events** and add `app_home_opened`.

Everything is now setup. In your browser, navigate to http://localhost:3000/slack/install to initiate the oAuth flow. Once you install the app, it should redirect you back to your native slack app. Click on the home tab of your app in slack to see the message `Welcome to the App Home!`.


text:
using System;
using KaVE.JetBrains.Annotations;

namespace KaVE.Commons.Utils.Assertion
{
    public class AssertException : Exception
    {
        public AssertException([NotNull] string message)
            : base(message) {}

        public AssertException([NotNull] string message, [NotNull] Exception innerException)
            : base(message, innerException) {}
    }
}


text:
from sympy.core import Basic, S, Add, Mul, Symbol
from sympy.core.methods import NoRelMeths, ArithMeths

from sympy.polynomials import quo, roots
from sympy.simplify import powsimp

class Product(Basic, NoRelMeths, ArithMeths):
    """Represents unevaluated product.

    """

    precedence = Basic.Apply_precedence

    def __new__(cls, term, *symbols, **assumptions):
        term = Basic.sympify(term)

        if isinstance(term, Basic.Number):
            if isinstance(term, Basic.NaN):
                return S.NaN
            elif isinstance(term, Basic.Infinity):
                return S.NaN
            elif isinstance(term, Basic.NegativeInfinity):
                return S.NaN
            elif isinstance(term, Basic.Zero):
                return S.Zero
            elif isinstance(term, Basic.One):
                return S.One

        if len(symbols) == 1:
            symbol = symbols[0]

            if isinstance(symbol, Basic.Equality):
                k = symbol.lhs
                a = symbol.rhs.start
                n = symbol.rhs.end
            elif isinstance(symbol, (tuple, list)):
                k, a, n = symbol
            else:
                raise ValueError("Invalid arguments")

            k, a, n = map(Basic.sympify, (k, a, n))

            if isinstance(a, Basic.Number) and isinstance(n, Basic.Number):
                return Mul(*[term.subs(k, i) for i in xrange(int(a), int(n)+1)])
        else:
            raise NotImplementedError

        obj = Basic.__new__(cls, **assumptions)
        obj._args = (term, k, a, n)

        return obj

    @property
    def term(self):
        return self._args[0]

    @property
    def index(self):
        return self._args[1]

    @property
    def lower(self):
        return self._args[2]

    @property
    def upper(self):
        return self._args[3]

    def tostr(self, level=0):
        r = 'Product(%s)' % ', '.join([a.tostr() for a in self._args])

        if self.precedence <= level:
            return '(%s)' % (r)
        else:
            return r

    def doit(self):
        prod = self._eval_product()

        if prod is not None:
            return powsimp(prod)
        else:
            return self

    def _eval_product(self, term=None):
        k = self.index
        a = self.lower
        n = self.upper

        if term is None:
            term = self.term

        if not term.has(k):
            return term**(n-a+1)
        elif term.is_polynomial(k):
            poly = term.as_polynomial(k)

            A = B = Q = S.One
            C = poly.leading_coeff()

            all_roots = roots(poly)

            for r in all_roots:
                A *= Basic.RisingFactorial(a-r, n-a+1)
                Q *= n - r

            if len(all_roots) < poly.degree():
                B = Product(quo(poly, Q, k), (k, a, n))

            return C**(n-a+1) * A * B
        elif isinstance(term, Basic.Add):
            p, q = term.as_numer_denom()

            p = self._eval_product(p)
            q = self._eval_product(q)

            return p / q
        elif isinstance(term, Basic.Mul):
            exclude, include = [], []

            for t in term:
                p = self._eval_product(t)

                if p is not None:
                    exclude.append(p)
                else:
                    include.append(p)

            if not exclude:
                return None
            else:
                A, B = Mul(*exclude), Mul(*include)
                return A * Product(B, (k, a, n))
        elif isinstance(term, Basic.Pow):
            if not term.base.has(k):
                s = sum(term.exp, (k, a, n))

                if not isinstance(s, Sum):
                    return term.base**s
            elif not term.exp.has(k):
                p = self._eval_product(term.base)

                if p is not None:
                    return p**term.exp

def product(*args, **kwargs):
    prod = Product(*args, **kwargs)

    if isinstance(prod, Product):
        return prod.doit()
    else:
        return prod


text:
//
//  BRSimpleMovingAverageFilter.h
//  BlueRangeSDK
//
// Copyright (c) 2016-2017, M-Way Solutions GmbH
// All rights reserved.
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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.
//

#import <Foundation/Foundation.h>
#import "BRMovingAverageFilter.h"

/**
 * This class implements the {@link BRMovingAverageFilter} interface and computes the average value
 * by just calculating the average value of all values without considering their time points.
 */
@interface BRSimpleMovingAverageFilter : NSObject<BRMovingAverageFilter>

- /* Override */ (float) getAverageWithStartTime: (double) startTime andEndTime: (double) endTime andTimePoints: (NSArray*) timePoints andValues: (NSArray*) values;

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="private">Privado</string>
  <string name="myStudies">Mis estudios</string>
  <string name="studiesIContributeTo">Estudios en los que colaboro</string>
  <string name="myPublicStudies">Mis estudios públicos</string>
  <string name="myPrivateStudies">Mis estudios privados</string>
  <string name="myFavoriteStudies">Mis estudios favoritos</string>
  <string name="whatAreStudies">¿Qué son los estudios?</string>
  <string name="allStudies">Todos los estudios</string>
  <string name="studiesCreatedByX">Estudios creados por %s</string>
  <string name="noneYet">Ninguno por ahora.</string>
  <string name="hot">De interés actualmente</string>
  <string name="dateAddedNewest">Fecha (más recientes)</string>
  <string name="dateAddedOldest">Fecha (más antiguos)</string>
  <string name="recentlyUpdated">Actualizados recientemente</string>
  <string name="mostPopular">Más populares</string>
  <string name="alphabetical">Alfabético</string>
  <string name="addNewChapter">Añadir nuevo capítulo</string>
  <plurals name="nbChapters">
    <item quantity="one">%s Capítulo</item>
    <item quantity="other">%s Capítulos</item>
  </plurals>
  <plurals name="nbGames">
    <item quantity="one">%s Partida</item>
    <item quantity="other">%s Partidas</item>
  </plurals>
  <string name="addMembers">Añadir miembros</string>
  <plurals name="nbMembers">
    <item quantity="one">%s Miembro</item>
    <item quantity="other">%s Miembros</item>
  </plurals>
  <string name="inviteToTheStudy">Invitar al estudio</string>
  <string name="pleaseOnlyInvitePeopleYouKnow">Por favor, invita sólo a personas que conozcas y que deseen unirse a este estudio.</string>
  <string name="searchByUsername">Buscar por nombre de usuario</string>
  <string name="spectator">Espectador</string>
  <string name="contributor">Colaborador</string>
  <string name="kick">Expulsar</string>
  <string name="leaveTheStudy">Dejar el estudio</string>
  <string name="youAreNowAContributor">Ahora eres un colaborador</string>
  <string name="youAreNowASpectator">Ahora eres un espectador</string>
  <string name="pgnTags">Etiquetas PGN</string>
  <string name="like">Me gusta</string>
  <string name="newTag">Nueva etiqueta</string>
  <string name="commentThisPosition">Comentar esta posición</string>
  <string name="commentThisMove">Comentar este movimiento</string>
  <string name="annotateWithGlyphs">Anotar con iconos</string>
  <string name="theChapterIsTooShortToBeAnalysed">El capítulo es demasiado corto para analizarlo.</string>
  <string name="onlyContributorsCanRequestAnalysis">Sólo los colaboradores del estudio pueden solicitar un análisis por ordenador.</string>
  <string name="getAFullComputerAnalysis">Obtén un análisis completo de la línea principal en el servidor.</string>
  <string name="makeSureTheChapterIsComplete">Asegúrate de que el capítulo está completo. Sólo puede solicitar el análisis una vez.</string>
  <string name="allSyncMembersRemainOnTheSamePosition">Todos los miembros de SYNC permanecen en la misma posición</string>
  <string name="shareChanges">Comparte cambios con los espectadores y guárdalos en el servidor</string>
  <string name="playing">Jugando</string>
  <string name="first">Primero</string>
  <string name="previous">Anterior</string>
  <string name="next">Siguiente</string>
  <string name="last">Último</string>
  <string name="shareAndExport">Compartir y exportar</string>
  <string name="cloneStudy">Clonar</string>
  <string name="studyPgn">PGN del estudio</string>
  <string name="downloadAllGames">Descargar todas las partidas</string>
  <string name="chapterPgn">PGN del capítulo</string>
  <string name="downloadGame">Descargar partida</string>
  <string name="studyUrl">URL del estudio</string>
  <string name="currentChapterUrl">URL del capítulo actual</string>
  <string name="youCanPasteThisInTheForumToEmbed">Puedes pegar esto en el foro para insertar la partida</string>
  <string name="startAtInitialPosition">Comenzar desde la posición inicial</string>
  <string name="startAtX">Comenzar en %s</string>
  <string name="embedInYourWebsite">Insértalo en tu página o blog</string>
  <string name="readMoreAboutEmbedding">Leer más sobre insertar contenido</string>
  <string name="onlyPublicStudiesCanBeEmbedded">¡Solo los estudios públicos pueden ser insertados!</string>
  <string name="open">Abrir</string>
  <string name="xBroughtToYouByY">%1$s, proporcionado por %2$s</string>
  <string name="studyNotFound">No se encontró el estudio</string>
  <string name="editChapter">Editar capítulo</string>
  <string name="newChapter">Capítulo nuevo</string>
  <string name="orientation">Orientación</string>
  <string name="analysisMode">Modo de análisis</string>
  <string name="pinnedChapterComment">Comentario fijo para el capítulo</string>
  <string name="saveChapter">Guardar capítulo</string>
  <string name="clearAnnotations">Borrar anotaciones</string>
  <string name="deleteChapter">Borrar capítulo</string>
  <string name="deleteThisChapter">¿Realmente quieres borrar el capítulo? ¡Esta acción no se puede deshacer!</string>
  <string name="clearAllCommentsInThisChapter">¿Borrar todos los comentarios, iconos y marcas de este capítulo?</string>
  <string name="rightUnderTheBoard">Justo debajo del tablero</string>
  <string name="noPinnedComment">Ninguno</string>
  <string name="normalAnalysis">Análisis normal</string>
  <string name="hideNextMoves">Ocultar los siguientes movimientos</string>
  <string name="interactiveLesson">Lección interactiva</string>
  <string name="chapterX">Capítulo %s</string>
  <string name="empty">Vacío</string>
  <string name="startFromInitialPosition">Comenzar desde la posición inicial</string>
  <string name="editor">Editor</string>
  <string name="startFromCustomPosition">Comenzar desde una posición personalizada</string>
  <string name="loadAGameByUrl">Cargar una partida desde una URL</string>
  <string name="loadAPositionFromFen">Cargar una posición vía código FEN</string>
  <string name="loadAGameFromPgn">Cargar una partida vía código PGN</string>
  <string name="automatic">Automática</string>
  <plurals name="pasteYourPgnTextHereUpToNbGames">
    <item quantity="one">Pega aquí el código PGN, %s partida como máximo</item>
    <item quantity="other">Pega aquí el código PGN, %s partidas como máximo</item>
  </plurals>
  <string name="urlOfTheGame">URL de la partida</string>
  <string name="loadAGameFromXOrY">Cargar una partida desde %1$s o %2$s</string>
  <string name="createChapter">Crear capítulo</string>
  <string name="configureLiveBroadcast">Configurar la emisión en directo</string>
  <string name="createStudy">Crear estudio</string>
  <string name="editStudy">Editar estudio</string>
  <string name="visibility">Visibilidad</string>
  <string name="public">Público</string>
  <string name="unlisted">Sin listar</string>
  <string name="inviteOnly">Acceso mediante invitación</string>
  <string name="allowCloning">Permitir clonado</string>
  <string name="nobody">Nadie</string>
  <string name="onlyMe">Sólo yo</string>
  <string name="contributors">Colaboradores</string>
  <string name="members">Miembros</string>
  <string name="everyone">Todo el mundo</string>
  <string name="enableSync">Habilitar sincronización</string>
  <string name="yesKeepEveryoneOnTheSamePosition">Sí: todo el mundo ve la misma posición</string>
  <string name="noLetPeopleBrowseFreely">No: permitir que la gente navegue libremente</string>
  <string name="pinnedStudyComment">Comentario fijado del estudio</string>
  <string name="start">Comenzar</string>
  <string name="save">Guardar</string>
  <string name="clearChat">Limpiar el chat</string>
  <string name="deleteTheStudyChatHistory">¿Realmente quieres borrar el historial de chat? ¡Esta acción no se puede deshacer!</string>
  <string name="deleteStudy">Borrar estudio</string>
  <string name="confirmDeleteStudy" comment="%s is replaced with the name of the study">¿Seguro que quieres eliminar el estudio? Ten en cuenta que esta acción no se puede deshacer. Para confirmar, escribe el nombre del estudio: %s</string>
  <string name="whereDoYouWantToStudyThat">¿Dónde quieres estudiar eso?</string>
  <string name="goodMove">Jugada buena</string>
  <string name="mistake">Error</string>
  <string name="brilliantMove">Jugada muy buena</string>
  <string name="blunder">Error grave</string>
  <string name="interestingMove">Jugada interesante</string>
  <string name="dubiousMove" comment="dubiousMove
A questionable move.">Jugada dudosa</string>
  <string name="onlyMove" comment="onlyMove
The only possible move. This is a label that can be placed in a study of a past game. It may not technically be the only move, but the only feasible one.">Movimiento único</string>
  <string name="zugzwang" comment="zugzwang
What zugzwang is: https://lichess.org/practice/intermediate-tactics/zugzwang/9cKgYrHb/ybYJ9gNa

This specific string is a label that can be applied to a position in a study, to indicate one side is in zugzwang.">Zugzwang</string>
  <string name="equalPosition">Posición igualada</string>
  <string name="unclearPosition" comment="unclearPosition
It is unclear who is winning or losing.">Posición poco clara</string>
  <string name="whiteIsSlightlyBetter">Las blancas están ligeramente mejor</string>
  <string name="blackIsSlightlyBetter">Las negras están ligeramente mejor</string>
  <string name="whiteIsBetter">Las blancas están mejor</string>
  <string name="blackIsBetter">Las negras están mejor</string>
  <string name="whiteIsWinning">Las blancas están ganando</string>
  <string name="blackIsWinning">Las negras están ganando</string>
  <string name="novelty" comment="novelty

A move in the opening that has not been played before.
https://en.wikipedia.org/wiki/Glossary_of_chess#theoretical_novelty">Novedad</string>
  <string name="development" comment="development
Used in studies - shows that the player made a developing move (e.g. pushing pawns to open their bishops in the opening).">Desarrollo</string>
  <string name="initiative">Iniciativa</string>
  <string name="attack" comment="attack
A label that can be applied to a position in a Lichess study. Noun.">Ataque</string>
  <string name="counterplay" comment="counterplay
A label that can be applied to a position in a Lichess study. Noun.

Generally describes a defending player who is under attack, and makes an attacking move elsewhere.">Contrajuego</string>
  <string name="timeTrouble" comment="timeTrouble
A label that can be applied to a position in a Lichess study. Noun. Indicates that a player had little time to think and make this move (clock was running low).">Problema de tiempo</string>
  <string name="withCompensation" comment="withCompensation

Compensation is the short-term positional advantage a player has in exchange for typically material disadvantage. Short term advantages involve initiative and attack.
https://en.wikipedia.org/wiki/Compensation_(chess)">Con compensación</string>
  <string name="withTheIdea" comment="withTheIdea
A label that can be applied to a position in a Lichess study. Noun.

Shows that the player was following the theory around an opening, even after the initial opening moves.">Con la idea</string>
  <string name="nextChapter">Capítulo siguiente</string>
  <string name="prevChapter">Capítulo anterior</string>
  <string name="studyActions">Acciones de estudio</string>
</resources>


text:
using System;
using System.Collections.Generic;
using Core.Common;
using System.Linq;

namespace Core.IO
{
	public static class PathHelper
	{
		public static readonly char[] PathSeparatorChars = new char[] { '/', '\\' };

		public static string GetFileName (string path)
		{
			if (string.IsNullOrEmpty (path))
				return null;

			//if (path.IndexOfAny (InvalidPathChars) != -1)
			//	throw new ArgumentException ("Illegal characters in path.");

			int nLast = path.LastIndexOfAny (PathSeparatorChars);
			if (nLast >= 0)
				return path.Substring (nLast + 1);

			return path;
		}

		public static string GetFileName (string[] path)
		{
			if (path.Length == 0)
				return string.Empty;

			return path.Last ();
		}

		public static string NormalizePath (string path)
		{
			//Log.Debug ("PathHelper.NormalizePath: path=", path);
			if (string.IsNullOrWhiteSpace (path))
				return string.Empty;

			// no windows file separators!
			path = path.Replace ('\\', '/');

			bool startsWithSlash = path.StartsWith ("/");

			string[] oldParts = path.Split (new []{ '/' }, StringSplitOptions.RemoveEmptyEntries);
			List<string> newParts = new List<string> ();
			foreach (string part in oldParts) {
				if (part == ".") {
					// ignore
				} else if (part == "..") {
					// go one up!
					//Log.Debug ("PathHelper.NormalizePath: go up from ", newParts.Join ("/"));
					if (newParts.Count > 0) {
						newParts.RemoveAt (newParts.Count - 1);
					}
				} else if (string.IsNullOrEmpty (part)) {
					// empty path part!
				} else {
					// normal path part
					newParts.Add (part);
				}
			}

			path = (startsWithSlash ? "/" : string.Empty) + newParts.Join ("/");

			return path;
		}

		public static string[] NormalizePath (string[] pathParts)
		{
			return NormalizePath (pathParts.Join ("/")).Split ('/');
		}

		public static string CombinePath (params string[] parts)
		{
			if (parts == null || parts.Length == 0) {
				return string.Empty;
			}

			return NormalizePath (path: string.Join ("/", parts.Where (p => p.Length > 0)));
		}

		public static string CombinePath (string firstPart, params string[] otherParts)
		{
			if (firstPart == null || otherParts == null) {
				return string.Empty;
			}

			string[] parts = new[]{ firstPart }.Extend (otherParts);

			return CombinePath (parts: parts);
		}
	}
}


text:
<?php

namespace	cs\modules\Static_pages;
use			h,
			cs\Config,
			cs\Index,
			cs\Language,
			cs\Page;
$Index						= Index::instance();
$L							= Language::instance();
$id							= (int)Config::instance()->route[1];
$title						= Static_pages::instance()->get($id)['title'];
Page::instance()->title($L->deletion_of_page($title));
$Index->buttons				= false;
$Index->cancel_button_back	= true;
$Index->action				= 'admin/Static_pages';
$Index->content(
	h::{'p.lead.cs-center'}(
		$L->sure_to_delete_page($title)
	).
	h::{'button[type=submit]'}($L->yes).
	h::{'input[type=hidden][name=id]'}([
		'value'	=> $id
	]).
	h::{'input[type=hidden][name=mode][value=delete_page]'}()
);


text:
<?php
class MainMenu extends CWidget
{
	public function init()
	{

	}
    public function run()
	{
		$this->render('mainmenu');
    }
}
?>


text:
package de.tuberlin.dima.ti.analysis;

import de.tuberlin.dima.ti.pcb.CBUtil;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple8;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.util.Collector;

import java.util.Collection;
import java.util.HashMap;
import java.util.Random;

/**
 * Parser for preprocessed DB1BMarket data in CSV format
 * that discards some of the records and emits them as MIDT tuples
 */
public class DB1B2MIDTParser extends RichFlatMapFunction<String, MIDT> {

    private static final String[] DAYSTRINGS = {"05052014", "06052014", "07052014", "08052014", "09052014", "10052014", "11052014"};

    private static final String SEPARATOR = ",";

    private static final String SEPARATOR2 = ",";

    private HashMap<String, AirportInfo> airportsInfo;

    private Random rng;

    private static final double AVG_CRUISE_SPEED = 800.0;

    private static final int TL_OVERHEAD = 20;

    private static final int AVG_WAITING_TIME = 60;

    // if true randomly assigns day of the week, otherwise emits one MIDT entry for each day
    private boolean spreadOverWeek;

    public DB1B2MIDTParser(boolean spreadOverWeek) {
        this.spreadOverWeek = spreadOverWeek;
    }

    @Override
    public void open(Configuration parameters) {
        Collection<Tuple8<String, String, String, String, String, Double, Double, String>> broadcastSet =
                this.getRuntimeContext().getBroadcastVariable(TrafficAnalysis.AP_GEO_DATA);
        this.airportsInfo = new HashMap<String, AirportInfo>(broadcastSet.size());
        for(Tuple8<String, String, String, String, String, Double, Double, String> tuple8 : broadcastSet) {
            this.airportsInfo.put(tuple8.f0, new AirportInfo(tuple8));
        }
        if(spreadOverWeek) {
            this.rng = new Random(System.currentTimeMillis());
        }
    }

    @Override
    public void flatMap(String s, Collector<MIDT> collector) throws Exception {
        String[] tmp = s.split(SEPARATOR);
        String[] airports = tmp[0].split(SEPARATOR2);
        String[] airlines = tmp[1].split(SEPARATOR2);
        Integer pax = Integer.parseInt(tmp[2].trim());
        if(airports.length > 4 || airports.length < 2) {
            return;
        }
        if(airports.length != airlines.length+1) {
            // should be impossible
            return;
        }
        if(pax < 1) {
            return;
        }
        String origin = airports[0].trim();
        if(!this.airportsInfo.containsKey(origin)) {
            return;
        }
        String hub1 = "";
        String hub2 = "";
        String destination = "";
        String al1 = airlines[0].trim();
        String al2 = "";
        String al3 = "";
        int travelTime = 1;
        int waitingTime = 0;
        int legCount = 1;
        double geoDetour = 1.0;
        int numCountries = 1;
        if(airports.length == 2) {
            destination = airports[1].trim();
            if(!this.airportsInfo.containsKey(destination)) {
                return;
            }
            travelTime = estimateTravelTime(origin, destination);
        } else if(airports.length == 3) {
            hub1 = airports[1].trim();
            destination = airports[2].trim();
            if(!this.airportsInfo.containsKey(hub1) ||
               !this.airportsInfo.containsKey(destination)) {
                return;
            }
            al2 = airlines[1].trim();
            travelTime = estimateTravelTime(origin, hub1, destination);
            waitingTime = AVG_WAITING_TIME;
            legCount = 2;
            geoDetour = getGeoDetour(origin, hub1, destination);
        } else if(airports.length == 4) {
            hub1 = airports[1].trim();
            hub2 = airports[2].trim();
            destination = airports[3].trim();
            if(!this.airportsInfo.containsKey(hub1) ||
               !this.airportsInfo.containsKey(hub2) ||
               !this.airportsInfo.containsKey(destination)) {
                return;
            }
            al2 = airlines[1].trim();
            al3 = airlines[2].trim();
            travelTime = estimateTravelTime(origin, hub1, hub2, destination);
            waitingTime = 2*AVG_WAITING_TIME;
            legCount = 3;
            geoDetour = getGeoDetour(origin, hub1, hub2, destination);
        } else {
            return;
        }
        if(spreadOverWeek) {
            int randomDay = rng.nextInt(DAYSTRINGS.length);
            String dayString = DAYSTRINGS[randomDay];
            collector.collect(new MIDT(origin, destination, dayString, al1, al2, al3, "", "", travelTime, waitingTime, legCount, pax, geoDetour, numCountries, hub1, hub2));
        } else {
            for (int i = 0; i < DAYSTRINGS.length; i++) {
                String dayString = DAYSTRINGS[i];
                collector.collect(new MIDT(origin, destination, dayString, al1, al2, al3, "", "", travelTime, waitingTime, legCount, pax, geoDetour, numCountries, hub1, hub2));
            }
        }
    }

    private int estimateTravelTime(String origin, String destination) {
        AirportInfo o = airportsInfo.get(origin);
        AirportInfo d = airportsInfo.get(destination);
        double directDistance = CBUtil.dist(o.latitude, o.longitude, d.latitude, d.longitude);
        int flightInMinutes = (int)((directDistance*60.0)/AVG_CRUISE_SPEED);
        return flightInMinutes + TL_OVERHEAD;
    }

    private int estimateTravelTime(String origin, String hub1, String destination) {
        AirportInfo o = airportsInfo.get(origin);
        AirportInfo h = airportsInfo.get(hub1);
        AirportInfo d = airportsInfo.get(destination);
        double leg1 = CBUtil.dist(o.latitude, o.longitude, h.latitude, h.longitude);
        double leg2 = CBUtil.dist(h.latitude, h.longitude, d.latitude, d.longitude);
        int leg1InMinutes = (int)((leg1*60.0)/AVG_CRUISE_SPEED);
        int leg2InMinutes = (int)((leg2*60.0)/AVG_CRUISE_SPEED);
        return leg1InMinutes + TL_OVERHEAD + AVG_WAITING_TIME + leg2InMinutes + TL_OVERHEAD;
    }

    private int estimateTravelTime(String origin, String hub1, String hub2, String destination) {
        AirportInfo o = airportsInfo.get(origin);
        AirportInfo h1 = airportsInfo.get(hub1);
        AirportInfo h2 = airportsInfo.get(hub2);
        AirportInfo d = airportsInfo.get(destination);
        double leg1 = CBUtil.dist(o.latitude, o.longitude, h1.latitude, h1.longitude);
        double leg2 = CBUtil.dist(h1.latitude, h1.longitude, h2.latitude, h2.longitude);
        double leg3 = CBUtil.dist(h2.latitude, h2.longitude, d.latitude, d.longitude);
        int leg1InMinutes = (int)((leg1*60.0)/AVG_CRUISE_SPEED);
        int leg2InMinutes = (int)((leg2*60.0)/AVG_CRUISE_SPEED);
        int leg3InMinutes = (int)((leg3*60.0)/AVG_CRUISE_SPEED);
        return leg1InMinutes + TL_OVERHEAD + AVG_WAITING_TIME + leg2InMinutes + TL_OVERHEAD + AVG_WAITING_TIME + leg3InMinutes + TL_OVERHEAD;
    }

    private double getGeoDetour(String origin, String hub1, String destination) {
        AirportInfo o = airportsInfo.get(origin);
        AirportInfo h = airportsInfo.get(hub1);
        AirportInfo d = airportsInfo.get(destination);
        double directDistance = CBUtil.dist(o.latitude, o.longitude, d.latitude, d.longitude);
        double leg1 = CBUtil.dist(o.latitude, o.longitude, h.latitude, h.longitude);
        double leg2 = CBUtil.dist(h.latitude, h.longitude, d.latitude, d.longitude);
        return (leg1+leg2)/directDistance;
    }

    private double getGeoDetour(String origin, String hub1, String hub2, String destination) {
        AirportInfo o = airportsInfo.get(origin);
        AirportInfo h1 = airportsInfo.get(hub1);
        AirportInfo h2 = airportsInfo.get(hub2);
        AirportInfo d = airportsInfo.get(destination);
        double directDistance = CBUtil.dist(o.latitude, o.longitude, d.latitude, d.longitude);
        double leg1 = CBUtil.dist(o.latitude, o.longitude, h1.latitude, h1.longitude);
        double leg2 = CBUtil.dist(h1.latitude, h1.longitude, h2.latitude, h2.longitude);
        double leg3 = CBUtil.dist(h2.latitude, h2.longitude, d.latitude, d.longitude);
        return (leg1+leg2+leg3)/directDistance;
    }

    private class AirportInfo {

        String iata;
        String city;
        String state;
        String country;
        String region;
        double latitude;
        double longitude;
        String icao;

        public AirportInfo(Tuple8<String, String, String, String, String, Double, Double, String> tuple8) {
            this.iata = tuple8.f0;
            this.city = tuple8.f1;
            this.state = tuple8.f2;
            this.country = tuple8.f3;
            this.region = tuple8.f4;
            this.latitude = tuple8.f5;
            this.longitude = tuple8.f6;
            this.icao = tuple8.f7;
        }
    }
}


text:
<!DOCTYPE html>

		<title>three.js webgl - materials - normal map [Lee Perry-Smith]</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

			three.js - webgl normalmap demo.
			Lee Perry-Smith head.

displacement mapping needs vertex textures (GPU with Shader Model 3.0)

			on Windows use Chrome --use-gl=desktop or Firefox 4

			please star this Chrome issue to get ANGLE support


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.
using Roslyn.Utilities;
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Reflection.Metadata;
using System.Collections.Immutable;
using System.Reflection.PortableExecutable;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

[assembly: Guid("CA89ACD1-A1D5-43DE-890A-5FDF50BC1F93")]

namespace Microsoft.DiaSymReader.PortablePdb
{
    [Guid("E4B18DEF-3B78-46AE-8F50-E67E421BDF70")]
    [ComVisible(true)]
    public sealed class SymBinder : ISymUnmanagedBinder4
    {
        [PreserveSig]
        public unsafe int GetReaderForFile(
            [MarshalAs(UnmanagedType.Interface)]object metadataImport,
            [MarshalAs(UnmanagedType.LPWStr)]string fileName,
            [MarshalAs(UnmanagedType.LPWStr)]string searchPath,
            [MarshalAs(UnmanagedType.Interface)]out ISymUnmanagedReader reader)
        {
            return GetReaderForFile2(
                metadataImport,
                fileName,
                searchPath,
                SymUnmanagedSearchPolicy.AllowReferencePathAccess,
                out reader);
        }

        /// <summary>
        /// Given a metadata interface and a file name, returns the
        /// <see cref="ISymUnmanagedReader"/> interface that will read the debugging symbols associated
        /// with the module.
        /// </summary>
        /// <remarks>
        /// This version of the function can search for the PDB in areas other than
        /// right next to the module.
        /// The search policy can be controlled by combining CorSymSearchPolicyAttributes
        /// e.g AllowReferencePathAccess|AllowSymbolServerAccess will look for the pdb next
        /// to the PE file and on a symbol server, but won't query the registry or use the path
        /// in the PE file.
        /// If a searchPath is provided, those directories will always be searched.
        /// </remarks>
        [PreserveSig]
        public int GetReaderForFile2(
            [MarshalAs(UnmanagedType.Interface)]object metadataImport,
            [MarshalAs(UnmanagedType.LPWStr)]string fileName,
            [MarshalAs(UnmanagedType.LPWStr)]string searchPath,
            SymUnmanagedSearchPolicy searchPolicy,
            [MarshalAs(UnmanagedType.Interface)]out ISymUnmanagedReader reader)
        {
            reader = null;
            try
            {
                var mdImport = metadataImport as IMetadataImport;
                if (mdImport == null || string.IsNullOrEmpty(fileName))
                {
                    return HResult.E_INVALIDARG;
                }

                // See DIA: FLocatePdbDefault, FLocateCvFilePathHelper, FLocatePdbSymsrv, FLocateCvFilePathHelper
                //
                // 1) Try open Combine(<PE directory>, <PDB file name>) (unless RestrictReferencePath)
                // 2) Try open PDB path (unless RestrictOriginalPath)
                // 3) Search Paths - semicolon separated paths
                //    a) searchPath parameter
                //    b) registry (unless RestrictRegistry)
                //       Use search paths from registry Software\Microsoft\VisualStudio\MSPDB, value SymbolSearchPath
                //       with environment variables expanded (ExpandEnvironmentStrings)
                //       i) try USER
                //       ii) try MACHINE
                //    c) environment vars
                //        i) _NT_ALT_SYMBOL_PATH
                //       ii) _NT_SYMBOL_PATH
                //       ii) SystemRoot (unless RestrictSystemRoot)
                //
                //    for each search path:
                //       special paths: SRV*<server>, SYMSRV*SYMSRV.DLL*<server> => symbol server (unless RestrictSymsrv)
                //                      CACHE*<cache> => sym cache (unless RestrictSymsrv)
                //
                //       A) try open <path>\symbols\<PE file extension>\<PDB file name>
                //       B) try open <path>\<PE file extension>\<PDB file name>
                //       C) try open <path>\<PDB file name>
                //
                // Each attempt checks if PDB ID matches.
                //
                // Search policy: all is restricted unless explicitly allowed.
                // After opened store to cache if CACHE* given (only the first cache?)

                CodeViewDebugDirectoryData codeViewData;
                uint stamp;
                if (!TryReadCodeViewData(fileName, out codeViewData, out stamp))
                {
                    return HResult.E_FAIL; // TODO: specific error code (ecToHresult)?
                }

                Guid guid = codeViewData.PdbId;
                int age = codeViewData.Age;
                string pdbFileName = Path.GetFileName(codeViewData.Path);
                var lazyImport = new LazyMetadataImport(mdImport);

                // 1) next to the PE file
                if ((searchPolicy & SymUnmanagedSearchPolicy.AllowReferencePathAccess) != 0)
                {
                    string peDirectory = Path.GetDirectoryName(fileName);
                    string pdbFilePath = Path.Combine(peDirectory, pdbFileName);

                    if (TryCreateReaderForMatchingPdb(pdbFilePath, guid, stamp, age, lazyImport, out reader))
                    {
                        return HResult.S_OK;
                    }
                }

                // 2) PDB path as specified in Debug Directory
                if ((searchPolicy & SymUnmanagedSearchPolicy.AllowOriginalPathAccess) != 0)
                {
                    if (TryCreateReaderForMatchingPdb(codeViewData.Path, guid, stamp, age, lazyImport, out reader))
                    {
                        return HResult.S_OK;
                    }
                }

                // 3) Search Paths
                string peFileExtension = Path.GetExtension(fileName).TrimStart('.');

                foreach (var searchPaths in GetSearchPathsSequence(searchPath, searchPolicy))
                {
                    if (TryFindMatchingPdb(searchPaths, peFileExtension, pdbFileName, guid, stamp, age, lazyImport, searchPolicy, out reader))
                    {
                        return HResult.S_OK;
                    }
                }

                return HResult.E_PDB_NOT_FOUND;
            }
            finally
            {
                InteropUtilities.TransferOwnershipOrRelease(ref metadataImport, reader);
            }
        }

        private static IEnumerable<string> GetSearchPathsSequence(string searchPath, SymUnmanagedSearchPolicy searchPolicy)
        {
            // 3a) parameter
            yield return searchPath;

            // 4b) registry
            if ((searchPolicy & SymUnmanagedSearchPolicy.AllowRegistryAccess) != 0)
            {
                // TODO
            }

            // 5c) environment variables:
            yield return PortableShim.Environment.GetEnvironmentVariable("_NT_ALT_SYMBOL_PATH");
            yield return PortableShim.Environment.GetEnvironmentVariable("_NT_SYMBOL_PATH");
            yield return PortableShim.Environment.GetEnvironmentVariable("SystemRoot");
        }

        private static IEnumerable<string> GetSearchPathSubdirectories(string searchPath, string peFileExtension)
        {
            yield return Path.Combine(searchPath, "symbols", peFileExtension);
            yield return Path.Combine(searchPath, peFileExtension);

            if (peFileExtension.Length > 0)
            {
                yield return Path.Combine(searchPath);
            }
        }

        private static readonly char[] SearchPathSeparators = { ';' };

        private bool TryFindMatchingPdb(
            string searchPaths,
            string peFileExtension, // with no leading .
            string pdbFileName,
            Guid guid,
            uint stamp,
            int age,
            LazyMetadataImport metadataImport,
            SymUnmanagedSearchPolicy searchPolicy,
            out ISymUnmanagedReader reader)
        {
            if (searchPaths == null)
            {
                reader = null;
                return false;
            }

            foreach (var searchPath in searchPaths.Split(SearchPathSeparators, StringSplitOptions.RemoveEmptyEntries))
            {
                // TODO: check symsrv policy
                if (searchPath.StartsWith("SRV*", StringComparison.OrdinalIgnoreCase))
                {
                    // TODO:
                    continue;
                }

                if (searchPath.StartsWith("SYMSRV*", StringComparison.OrdinalIgnoreCase))
                {
                    // TODO:
                    continue;
                }

                if (searchPath.StartsWith("CACHE*", StringComparison.OrdinalIgnoreCase))
                {
                    // TODO:
                    continue;
                }

                foreach (var subdir in GetSearchPathSubdirectories(searchPath, peFileExtension))
                {
                    if (TryCreateReaderForMatchingPdb(Path.Combine(subdir, pdbFileName), guid, stamp, age, metadataImport, out reader))
                    {
                        return true;
                    }
                }
            }

            reader = null;
            return false;
        }

        private bool TryCreateReaderForMatchingPdb(
            string pdbFilePath,
            Guid guid,
            uint stamp,
            int age,
            LazyMetadataImport metadataImport,
            out ISymUnmanagedReader reader)
        {
            try
            {
                if (PortableShim.File.Exists(pdbFilePath))
                {
                    var symReader = SymReader.CreateFromFile(pdbFilePath, metadataImport);
                    reader = symReader;
                    return symReader.PdbReader.MatchesModule(guid, stamp, age);
                }
            }
            catch
            {
                // nop
            }

            reader = null;
            return false;
        }

        private bool TryReadCodeViewData(string peFilePath, out CodeViewDebugDirectoryData codeViewData, out uint stamp)
        {
            try
            {
                var peStream = PortableShim.File.OpenRead(peFilePath);
                using (var peReader = new PEReader(peStream))
                {
                    foreach (var entry in PEUtilities.ReadDebugDirectory(peReader, peStream))
                    {
                        if (entry.EntryType == DebugDirectoryEntryType.CodeView)
                        {
                            codeViewData = PEUtilities.ReadCodeViewDebugDirectoryData(peStream, entry);
                            stamp = entry.Stamp;
                            return true;
                        }
                    }
                }
            }
            catch
            {
            }

            codeViewData = default(CodeViewDebugDirectoryData);
            stamp = 0;
            return false;
        }

        [PreserveSig]
        public int GetReaderFromStream(
            [MarshalAs(UnmanagedType.Interface)]object metadataImport,
            [MarshalAs(UnmanagedType.Interface)]object stream,
            [MarshalAs(UnmanagedType.Interface)]out ISymUnmanagedReader reader)
        {
            reader = null;

            try
            {
                IStream comStream = stream as IStream;
                var mdImport = metadataImport as IMetadataImport;
                if (mdImport == null || comStream == null)
                {
                    return HResult.E_INVALIDARG;
                }

                reader = SymReader.CreateFromStream(comStream, new LazyMetadataImport(mdImport));
                return (reader != null) ? HResult.S_OK : HResult.E_FAIL;
            }
            finally
            {
                InteropUtilities.TransferOwnershipOrRelease(ref metadataImport, reader);
            }
        }

        [PreserveSig]
        public int GetReaderFromCallback(
            [In, MarshalAs(UnmanagedType.Interface)] object metadataImport,
            [MarshalAs(UnmanagedType.LPWStr)]string fileName,
            [MarshalAs(UnmanagedType.LPWStr)]string searchPath,
            SymUnmanagedSearchPolicy searchPolicy,
            [In, MarshalAs(UnmanagedType.Interface)] object callback,
            [MarshalAs(UnmanagedType.Interface)]out ISymUnmanagedReader reader)
        {
            reader = null;
            return HResult.E_NOTIMPL;
        }

        /// <summary>
        /// Creates a new <see cref="ISymUnmanagedReader"/> for the specified PDB file.
        /// </summary>
        /// <param name="metadataImportProvider">
        /// Provider of a metadata importer for the corresponding PE file.
        /// The importer is only constructed if the operation performed on the SymReader requires access
        /// to the metadata.
        /// </param>
        /// <param name="pdbFilePath">PDB file path.</param>
        /// <param name="reader">The new reader instance.</param>
        /// <returns>
        /// E_INVALIDARG
        ///   <paramref name="metadataImportProvider"/> is null, or
        ///   <paramref name="pdbFilePath"/> is null or empty.
        /// Another error code describing failure to open the file.
        /// </returns>
        [PreserveSig]
        public int GetReaderFromPdbFile(
            [MarshalAs(UnmanagedType.Interface)]IMetadataImportProvider metadataImportProvider,
            [MarshalAs(UnmanagedType.LPWStr)]string pdbFilePath,
            [MarshalAs(UnmanagedType.Interface)]out ISymUnmanagedReader reader)
        {
            if (metadataImportProvider == null || string.IsNullOrEmpty(pdbFilePath))
            {
                reader = null;
                return HResult.E_INVALIDARG;
            }

            reader = SymReader.CreateFromFile(pdbFilePath, new LazyMetadataImport(metadataImportProvider));
            return (reader != null) ? HResult.S_OK : HResult.E_FAIL;
        }

        /// <summary>
        /// Creates a new <see cref="ISymUnmanagedReader"/> for the specified PDB file.
        /// </summary>
        /// <param name="metadataImportProvider">
        /// Provider of a metadata importer for the corresponding PE file.
        /// The importer is only constructed if the operation performed on the SymReader requires access
        /// to the metadata.
        /// </param>
        /// <param name="stream">PDB stream.</param>
        /// <param name="reader">The new reader instance.</param>
        /// <returns>
        /// E_INVALIDARG
        ///   <paramref name="metadataImportProvider"/> is null, or
        ///   <paramref name="stream"/> is null.
        /// Another error code describing failure to open the file.
        /// </returns>
        [PreserveSig]
        public int GetReaderFromPdbStream(
            [MarshalAs(UnmanagedType.Interface)]IMetadataImportProvider metadataImportProvider,
            [MarshalAs(UnmanagedType.Interface)]object stream,
            [MarshalAs(UnmanagedType.Interface)]out ISymUnmanagedReader reader)
        {
            IStream comStream = stream as IStream;
            if (metadataImportProvider == null || comStream == null)
            {
                reader = null;
                return HResult.E_INVALIDARG;
            }

            reader = SymReader.CreateFromStream(comStream, new LazyMetadataImport(metadataImportProvider));
            return (reader != null) ? HResult.S_OK : HResult.E_FAIL;
        }
    }
}

// regasm /codebase C:\R0\Binaries\Debug\Microsoft.DiaSymReader.PortablePdb.dll
// tlbexp C:\R0\Binaries\Debug\Microsoft.DiaSymReader.PortablePdb.dll


text:
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.template import loader
from django.views.generic import TemplateView
from django.core.urlresolvers import reverse

from .models import Server, StarredTV, StarredMovie

import os
import re
import logging
import threading
from operator import itemgetter

import kodicontroller

#################################################
# Decorators
#################################################
def GetServerList(func):
  def wrapper(request, *args, **kwargs):
    serverList = Server.objects.all()
    context = {'kodi_servers': serverList}
    return func(request, context, *args, **kwargs)
  return wrapper

def GetServer(func):
  @GetServerList
  def wrapper(request, context, server_id, *args, **kwargs):
    server = Server.objects.get(pk=server_id)
    context['server'] = server
    return func(request, server.conn(), context, *args, **kwargs)
  return wrapper

def GetController(func):
  @GetServer
  def wrapper(request, server, context, *args, **kwargs):
    controller = kodicontroller.KodiController()
    controller.SetServer(*server)
    controller.SetThumbnailCache(os.path.join('static', 'cache'))
    return func(request, controller, context, *args, **kwargs)
  return wrapper

def GetPlaylist(func):
  @GetController
  def wrapper(request, controller, context, *args, **kwargs):
    server_down = True

    try:
      context['playing']    = controller.Player_GetItem()
      context['player']     = controller.Player_GetProperties()
      context['playlist']   = controller.Playlist_GetItems(playlistType='video')
      context['properties'] = controller.Application_GetProperties()
    except Exception as e:
      logging.info(e)
    else:
      server_down = False
      context['special_play'] = False

      try:
        playing_id = context['playing']['id']
      except KeyError:
        pass
      else:
        try:
          playlist_id_list = [item['id'] for item in context['playlist']]
        except KeyError:
          pass
        else:
          if playing_id not in playlist_id_list:
            context['special_play'] = True

    return func(request, controller, context, server_down, *args, **kwargs)
  return wrapper

def ServerDownRedirect(func):
  def wrapper(request, controller, context, server_down, *args, **kwargs):
    if server_down:
      return kodi(request)
    else:
      return func(request, controller, context, *args, **kwargs)
  return wrapper

def ServerDownNoRedirect(func):
  def wrapper(request, controller, context, server_down, *args, **kwargs):
    if server_down:
      return HttpResponse(status=503)
    else:
      return func(request, controller, context, *args, **kwargs)
  return wrapper

#################################################
# Database Functions
#################################################
def AddServer(name, host, port, user, pwd):
  servers = Server.objects.create(name=name, host=host, port=port, user=user, pwd=pwd)
  servers.save()

def RemoveServer(server_id):
  db_entry = Server.objects.get(id=server_id)
  db_entry.delete()

def AddStarredTV(show_id):
  starredtvdb = StarredTV.objects.create(starred_id=show_id)
  starredtvdb.save()

def AddStarredMovie(movie_id):
  starredmoviedb = StarredMovie.objects.create(starred_id=movie_id)
  starredmoviedb.save()

def RemoveStarredTV(show_id):
  db_entry = StarredTV.objects.get(starred_id=show_id)
  db_entry.delete()

def RemoveStarredMovie(movie_id):
  db_entry = StarredMovie.objects.get(starred_id=movie_id)
  db_entry.delete()

def GetStarredTV():
  starred_tvshow_db_list = StarredTV.objects.all()
  starred_tvshow_id_list = [tvshow.get_id() for tvshow in starred_tvshow_db_list]
  return starred_tvshow_id_list

def GetStarredMovie():
  starred_movie_db_list = StarredMovie.objects.all()
  starred_movie_id_list = [movie.get_id() for movie in starred_movie_db_list]
  return starred_movie_id_list

#################################################
# Other Functions
#################################################
def GetMovieList(controller, context, movie_id=None):
  unsorted_movie_list = controller.VideoLibrary_GetMovies()

  starred_movie_id_list = GetStarredMovie()

  starred_movie_list = []
  unstarred_movie_list = []

  for movie in unsorted_movie_list:
    if int(movie['movieid']) in starred_movie_id_list:
      movie['starred'] = True
      starred_movie_list.append(movie)
    else:
      movie['starred'] = False
      unstarred_movie_list.append(movie)

    if movie_id is not None:
      if int(movie['movieid']) == int(movie_id):
        context['activemovie'] = movie

  context['starred_movies'] = sorted(starred_movie_list, key=itemgetter('title'))
  context['movies'] = sorted(unstarred_movie_list, key=itemgetter('title'))

def GetTVShowList(controller, context):
  unsorted_tvshow_list = controller.VideoLibrary_GetTVShows()

  starred_tv_id_list = GetStarredTV()

  starred_tv_list = []
  unstarred_tv_list = []

  for tvshow in unsorted_tvshow_list:
    if int(tvshow['tvshowid']) in starred_tv_id_list:
      tvshow['starred'] = True
      starred_tv_list.append(tvshow)
    else:
      tvshow['starred'] = False
      unstarred_tv_list.append(tvshow)

  context['starred_tvshows'] = sorted(starred_tv_list, key=itemgetter('title'))
  context['tvshows'] = sorted(unstarred_tv_list, key=itemgetter('title'))

def GetAddonList(controller, context, addon_id=None):
  addon_content = ('video', 'audio', 'image', 'executable')
  addon_list = []
  for content in addon_content:
    addons = controller.Addons_GetAddons(addoncontent=content)
    for addon in addons:
      if addon not in addon_list:
        addon_list.append(addon)

  context_addons = []
  for addon in addon_list:
    addon_details = controller.Addons_GetAddonDetails(addon['addonid'])
    context_addons.append(addon_details)

    if addon_id is not None:
      if addon_id == addon['addonid']:
        context['activeaddon'] = addon_details

  context['addons'] = context_addons

def GetSortedEpisodeList(controller, show_id, season_id):
  unsorted_episode_list = controller.VideoLibrary_GetEpisodes(show_id=show_id, season_id=season_id)

  # Set specialsortepisode values for any unset values
  for item in unsorted_episode_list:
    if item['specialsortepisode'] < 0:
      item['specialsortepisode'] = item['episode']

  # Sort by specialsortepsiode then by season (specials go first if they share the same episode number)
  return sorted(unsorted_episode_list, key=itemgetter('specialsortepisode', 'season', 'episode'))

#################################################
# Views
#################################################
def kodi(request):
  return redirect(reverse('config'))

@GetServerList
def config(request, context):
  return render(request, 'kodidj/kodi_config.html', context)

@GetPlaylist
def setserver(request, controller, context, server_down):
  if server_down:
    context = {}
  return render(request, 'kodidj/kodi_control_panel.html', context)

@GetController
def pingserver(request, controller, context):
  status = controller.Status()

  if status is 'Offline':
    return HttpResponse(status=500)
  else:
    return HttpResponse(status=200)

def addserver(request):
  try:
    server_name = request.POST['server_name']
    server_host = request.POST['server_host']
    server_port = request.POST['server_port']
    server_username = request.POST['server_username']
    server_password = request.POST['server_password']
  except KeyError:
    pass
  else:
    AddServer(server_name,server_host,server_port,server_username,server_password)
  return redirect(reverse('config'))

def removeserver(request):
  try:
    server_id = request.POST['server_id']
  except KeyError:
    pass
  else:
    RemoveServer(server_id)
  return redirect(reverse('config'))

@GetPlaylist
@ServerDownRedirect
def server(request, controller, context):
  GetMovieList(controller, context)
  GetTVShowList(controller, context)
  context['recentepisodes'] = controller.VideoLibrary_GetRecentlyAddedEpisodes()
  context['recentmovies'] = controller.VideoLibrary_GetRecentlyAddedMovies()
  return render(request, 'kodidj/kodi_server_index.html', context)

@GetPlaylist
@ServerDownRedirect
def tvindex(request, controller, context):
  GetTVShowList(controller, context)
  return render(request, 'kodidj/kodi_server_tv.html', context)

@GetPlaylist
@ServerDownRedirect
def tvshow(request, controller, context, show_id):
  context['tvshow'] = controller.VideoLibrary_GetTVShowDetails(show_id=show_id)
  context['seasons'] = controller.VideoLibrary_GetSeasons(show_id=show_id)
  return render(request, 'kodidj/kodi_server_tv_show.html', context)

@GetPlaylist
@ServerDownRedirect
def tvseason(request, controller, context, show_id, season_id):
  context['tvshow'] = controller.VideoLibrary_GetTVShowDetails(show_id=show_id)
  context['season'] = season_id
  context['episodes'] = GetSortedEpisodeList(controller, show_id, season_id)
  return render(request, 'kodidj/kodi_server_tv_season.html', context)

@GetPlaylist
@ServerDownRedirect
def tvepisode(request, controller, context, show_id, season_id, episode_id):
  context['tvshow'] = controller.VideoLibrary_GetTVShowDetails(show_id=show_id)
  context['season'] = season_id

  episode_list = GetSortedEpisodeList(controller, show_id, season_id)

  for episode in episode_list:
    if int(episode['episodeid']) == int(episode_id):
      active_episode = episode

  context.update({'activeepisode' : active_episode,
                  'episodes'      : episode_list})

  return render(request, 'kodidj/kodi_server_tv_season.html', context)

@GetPlaylist
@ServerDownRedirect
def movies_index(request, controller, context):
  GetMovieList(controller, context)
  return render(request, 'kodidj/kodi_server_movies.html', context)

@GetPlaylist
@ServerDownRedirect
def movie(request, controller, context, movie_id):
  GetMovieList(controller, context, movie_id)
  return render(request, 'kodidj/kodi_server_movies.html', context)

@GetPlaylist
@ServerDownRedirect
def musicindex(request, controller, context):
  # TODO : Implement this
  return redirect(reverse('config'))

@GetPlaylist
@ServerDownRedirect
def addonsindex(request, controller, context):
  GetAddonList(controller, context)
  return render(request, 'kodidj/kodi_server_addons.html', context)

@GetPlaylist
@ServerDownRedirect
def addon(request, controller, context, addon_id):
  GetAddonList(controller, context, addon_id)
  return render(request, 'kodidj/kodi_server_addons.html', context)

@GetPlaylist
@ServerDownRedirect
def executeaddon(request, controller, context, addon_id):
  controller.Addons_ExecuteAddon(addon_id)
  GetAddonList(controller, context, addon_id)
  return render(request, 'kodidj/kodi_server_addons.html', context)

@GetPlaylist
@ServerDownRedirect
def filesindex(request, controller, context):
  media_list = ['video', 'music', 'pictures', 'files', 'programs']
  for media in media_list:
    context_entry = "{}_files".format(media)
    context[context_entry] = controller.Files_GetSources(media)
  return render(request, 'kodidj/kodi_server_files.html', context)

@GetController
def files(request, controller, context):
  try:
    targetpath = request.GET['targetpath']
  except KeyError:
    return HttpResponse(status=500)
  else:
    try:
      pathhistory = request.GET['pathhistory']
    except KeyError:
      pass
    else:
      context['dir_history'] = pathhistory
    dirlist = controller.Files_GetDirectory(targetpath)
    context['filebrowser_list'] = sorted(dirlist, key=itemgetter('filetype', 'file'))
    return render(request, 'kodidj/kodi_filebrowser_panel.html', context)

@GetController
def filedetails(request, controller, context):
  # TODO : Review file details
  try:
    targetfile = request.GET['targetfile']
  except KeyError:
    return HttpResponse(status=500)
  else:
    controller.EnableLogging()
    context['file_details'] = controller.Files_GetFileDetails(targetfile)
    #controller.Playlist_Clear(playlistType='video')
    #controller.Playlist_Add(playlistType='video', params={'item':{'file':targetfile}})
    #controller.Player_Open(playlistType='video')
    return HttpResponse(status=200)

@GetPlaylist
@ServerDownNoRedirect
def getplaylist(request, controller, context):
  return render(request, 'kodidj/kodi_playlist_panel.html', context)

@GetController
def playfile(request, controller, context):
  try:
    targetfile = request.GET['targetfile']
  except KeyError:
    return HttpResponse(status=500)
  else:
    controller.Playlist_Clear(playlistType='video')
    controller.Playlist_Add(playlistType='video', params={'item':{'file':targetfile}})
    controller.Player_Open(playlistType='video')
  return getplaylist(request, context['server'].id)

@GetController
def addfile(request, controller, context):
  try:
    targetfile = request.GET['targetfile']
  except KeyError:
    return HttpResponse(status=500)
  else:
    controller.Playlist_Add(playlistType='video', params={'item':{'file':targetfile}})
  return getplaylist(request, context['server'].id)

@GetController
def playmovie(request, controller, context, movie_id):
  controller.Playlist_Clear(playlistType='video')
  controller.Playlist_Add(playlistType='video', params={'item':{'movieid':int(movie_id)}})
  movieInfo = controller.VideoLibrary_GetMovieDetails(movie_id=movie_id)
  controller.Player_Open(playlistType='video')
  controller.Player_Seek(position=movieInfo['resume']['percentage'])
  #controller.Player_Open(params={'item':{'movieid':int(movie_id)}, "options" : {"resume" : True}})
  return getplaylist(request, context['server'].id)

@GetController
def addmovie(request, controller, context, movie_id):
  controller.Playlist_Add(playlistType='video', params={'item':{'movieid':int(movie_id)}})
  return getplaylist(request, context['server'].id)

@GetController
def watchedmovie(request, controller, context, movie_id):
  url = request.get_full_path().replace('_watched', '')
  movieInfo = controller.VideoLibrary_GetMovieDetails(movie_id=movie_id)

  if movieInfo['playcount'] > 0:
    playcount = 0
  else:
    playcount = 1

  controller.VideoLibrary_SetMovieDetails(movie_id=movie_id, playcount=playcount)
  return HttpResponse(status=200)

@GetController
def starredmovie(request, controller, context, movie_id):
  url = request.get_full_path().replace('/{}_starred'.format(movie_id), '')

  starred_movie_id_list = GetStarredMovie()

  if int(movie_id) in starred_movie_id_list:
    RemoveStarredMovie(movie_id)
  else:
    AddStarredMovie(movie_id)

  return redirect(url)

@GetController
def removemovie(request, controller, context, movie_id):
  url = request.get_full_path().replace('/{}_remove'.format(movie_id), '')
  controller.VideoLibrary_RemoveMovie(movie_id=movie_id)
  return redirect(url)

@GetController
def playtv(request, controller, context, show_id, season_id, episode_id):
  controller.Playlist_Clear(playlistType='video')
  controller.Playlist_Add(playlistType='video', params={'item':{'episodeid':int(episode_id)}})
  episodeInfo = controller.VideoLibrary_GetEpisodeDetails(episode_id=episode_id)
  controller.Player_Open(playlistType='video')
  controller.Player_Seek(position=episodeInfo['resume']['percentage'])
  #controller.Player_Open(params={'item':{'episodeid':int(episode_id)}, "options" : {"resume" : True}})
  return getplaylist(request, context['server'].id)

@GetController
def addtv(request, controller, context, show_id, season_id, episode_id):
  controller.Playlist_Add(playlistType='video', params={'item':{'episodeid':int(episode_id)}})
  return getplaylist(request, context['server'].id)

@GetController
def watchedtv(request, controller, context, show_id, season_id, episode_id):
  url = request.get_full_path().replace('_watched', '')
  episodeInfo = controller.VideoLibrary_GetEpisodeDetails(episode_id=episode_id)

  if episodeInfo['playcount'] > 0:
    playcount = 0
  else:
    playcount = 1

  controller.VideoLibrary_SetEpisodeDetails(episode_id=episode_id, playcount=playcount)
  return HttpResponse(status=200)

@GetController
def removetvepisode(request, controller, context, show_id, season_id, episode_id):
  url = request.get_full_path().replace('/{}_remove'.format(episode_id), '')
  controller.VideoLibrary_RemoveEpisode(episode_id=episode_id)
  return redirect(url)

@GetController
def removetvshow(request, controller, context, show_id):
  url = request.get_full_path().replace('/{}_remove'.format(show_id), '')
  controller.VideoLibrary_RemoveTVShow(show_id=show_id)
  return redirect(url)

@GetController
def starredtvshow(request, controller, context, show_id):
  url = request.get_full_path().replace('/{}_starred'.format(show_id), '')

  starred_tv_id_list = GetStarredTV()

  if int(show_id) in starred_tv_id_list:
    RemoveStarredTV(show_id)
  else:
    AddStarredTV(show_id)

  return redirect(url)

@GetController
def watchedtvseason(request, controller, context, show_id, season_id):
  url = request.get_full_path().replace('/{}_watched'.format(season_id), '')

  seasons = controller.VideoLibrary_GetSeasons(show_id=show_id)

  for season in seasons:
    if int(season['season']) == int(season_id):
      active_season = season

  if active_season['playcount'] > 0:
    playcount = 0
  else:
    playcount = 1

  episode_list = GetSortedEpisodeList(controller, show_id, season_id)

  for episode in episode_list:
    controller.VideoLibrary_SetEpisodeDetails(episode_id=episode['episodeid'], playcount=playcount)

  return redirect(url)

@GetController
def playpause(request, controller, context):
  # Revisit this, doesn't play if stopped
  controller.Player_PlayPause()
  return HttpResponse(status=200)

@GetController
def stop(request, controller, context):
  controller.Player_Stop()
  return getplaylist(request, context['server'].id)

@GetController
def forward(request, controller, context):
  controller.Player_SetSpeed(speed='increment')
  return HttpResponse(status=200)

@GetController
def backward(request, controller, context):
  controller.Player_SetSpeed(speed='decrement')
  return HttpResponse(status=200)

@GetController
def skip(request, controller, context):
  # goto next item in playlist ?
  controller.Player_Seek(position=100)
  return getplaylist(request, context['server'].id)

@GetController
def restart(request, controller, context):
  # get current position
  # if 0 Player.GoTo previous item in playlist
  controller.Player_Seek(position=0)
  return HttpResponse(status=200)

@GetController
def mute(request, controller, context):
  controller.Application_SetMute()
  return HttpResponse(status=200)

@GetController
def togglesubtitles(request, controller, context):
  properties = controller.Player_GetProperties()
  if properties['subtitleenabled']:
    mode = 'off'
  else:
    mode = 'on'
  controller.Player_SetSubtitle(mode=mode)
  return HttpResponse(status=200)

@GetController
def cyclesubtitles(request, controller, context):
  mode = 'next'
  controller.Player_SetSubtitle(mode=mode)
  return HttpResponse(status=200)

@GetController
def remove(request, controller, context, index):
  controller.Playlist_Remove(playlistType='video', index=index)
  return getplaylist(request, context['server'].id)

@GetController
def playlistplay(request, controller, context, index):
  controller.Player_GoTo(index=index)
  return getplaylist(request, context['server'].id)

@GetController
def clear(request, controller, context):
  controller.Playlist_Clear( playlistType='video')
  return getplaylist(request, context['server'].id)

@GetController
def videoscan(request, controller, context):
  controller.VideoLibrary_Scan(show_dialog=True)
  return HttpResponse(status=200)

@GetController
def quit(request, controller, context):
  controller.System_Shutdown()
  return HttpResponseRedirect(reverse('kodi'))

@GetController
def setvolume(request, controller, context):
  try:
    volume = request.GET['volume']
  except:
    pass
  else:
    controller.Application_SetVolume(volume=volume)
  finally:
    return HttpResponse(status=200)

@GetController
def setprogress(request, controller, context, percentage):
  controller.Player_Seek(position=percentage)
  return HttpResponse(status=200)

@GetController
def getstatus(request, controller, context):
  player_properties = controller.Player_GetProperties()
  application_properties = controller.Application_GetProperties()

  data = {}

  try:
    data['percentage'] = player_properties['percentage']
    data['speed'] = player_properties['speed']
  except KeyError:
    data['percentage'] = 0
    data['speed'] = 0

  data['volume'] = application_properties['volume']
  data['muted'] = application_properties['muted']
  return JsonResponse(data)


text:
/*
 * NaCl Simple/secure ELF loader (NaCl SEL).
 */

#ifndef NATIVE_CLIENT_SRC_TRUSTED_SERVICE_RUNTIME_ARCH_X86_64_TRAMP_64_H__
#define NATIVE_CLIENT_SRC_TRUSTED_SERVICE_RUNTIME_ARCH_X86_64_TRAMP_64_H__
/*
 * text addresses, not word aligned; these are .globl symbols from the
 * assembler source, and there is no type information associated with
 * them.  we could declare these to be (void (*)(void)), i suppose,
 * but it doesn't really matter since we convert their addresses to
 * uintptr_t at every use.
 */
extern char   NaCl_trampoline_code;
extern char   NaCl_trampoline_code_end;
extern char   NaCl_trampoline_call_target;

#endif