text:
#include "inet/physicallayer/pathloss/LogNormalShadowing.h"

namespace inet {

namespace physicallayer {

Define_Module(LogNormalShadowing);

LogNormalShadowing::LogNormalShadowing() :
    sigma(1)
{
}

void LogNormalShadowing::initialize(int stage)
{
    FreeSpacePathLoss::initialize(stage);
    if (stage == INITSTAGE_LOCAL) {
        sigma = par("sigma");
    }
}

void LogNormalShadowing::printToStream(std::ostream& stream) const
{
    stream << "LogNormalShadowing, "
           << "alpha = " << alpha << ", "
           << "systemLoss = " << systemLoss << ", "
           << "sigma = " << sigma;
}

double LogNormalShadowing::computePathLoss(mps propagationSpeed, Hz frequency, m distance) const
{
    m d0 = m(1.0);
    // reference path loss
    double freeSpacePathLoss = computeFreeSpacePathLoss(propagationSpeed / frequency, d0, alpha, systemLoss);
    double PL_d0_db = 10.0 * log10(1 / freeSpacePathLoss);
    // path loss at distance d + normal distribution with sigma standard deviation
    double PL_db = PL_d0_db + 10 * alpha * log10(unit(distance / d0).get()) + normal(0.0, sigma);
    return math::dB2fraction(-PL_db);
}

} // namespace physicallayer

} // namespace inet


text:
layout: docs
section: help
category: reference
tag: Reference
title: Exporting
permalink: /docs/manual/exporting
---
Once you've finished a map design, you can export your map for use in other applications. You can export the entire world or choose a smaller region by setting the bounding box. TileMill can export a variety of formats and each has different advantages.

With a TileMill project open, the export menu at the top-right of the window and presents a number of options.

![TileMill export menu](/assets/tilemill/manual/export.png)

## Interactive, multiscale exports

The __Upload__ and __MBTiles__ options will export pannable, zoomable maps just like the preview you see in TileMill. Any legends and interactive elements will be included. Depending on what you are exporting, this process can take up considerable time and disk space.

The MBTiles option creates a package of [tiles](http://mapbox.com/developers/guide/) that can be used in a variety of ways. You can upload them to a MapBox account, host them yourself with [TileStream](https://github.com/mapbox/tilestream) or transfer them to [MapBox for iPad](http://mapbox.com/ipad/) for offline access. Technical details about MBTiles files can be found in the [MapBox developers documentation](http://mapbox.com/developers/mbtiles/).

If you have a [MapBox account](http://mapbox.com/plans/) you can connect it with your TileMill installation and use the Upload export to streamline the process of creating an MBTiles file and uploading it to MapBox.

## Static image exports

The __PNG__, __PDF__, and __SVG__ export options allow you to export specific views of your map. If your project includes legends or interactive elements they will not be included for these types of exports.

Use PNG to export a static image of your map. This format is useful if you want to add a snapshot to a word processor.

PDF and SVG provide vector-based exports of your map, which are useful if you're designing maps for printed material or need to make further edits to the design or layout. Both PDF and SVG output should contain very similar content but SVG is often supported by drawing programs natively (does not require conversion upon import).

## Mapnik XML export

TileMill's __Mapnik XML__ export option is aimed at advanced users who are familiar with [Mapnik](http://mapnik.org/), the software that TileMill uses under the hood to handles rendering your maps.

TileMill uses [CartoCSS](https://github.com/mapbox/carto) to translate your CSS styles and layer definitions into the XML format that Mapnik can read each time you save your project. Most users will not need to directly use this underlying Mapnik XML, but it is easy to leverage if you want to move your raw map styles out of TileMill to set up for rendering directly with Mapnik, or other tools that work with Mapnik like [TileStache](http://tilestache.org/) and [Invar](https://github.com/onyxfish/invar/).

__Note:__ If you export a Mapnik XML file into a TileMill project directory, this XML style will __override__ all of the layers and stylesheets for that project. Any changes you make to the project in TileMill will not be visible until the XML file is moved.

## Exports from the command line

TileMill can be invoked from a terminal shell. This is useful for running exports on headless servers or scripting batch exports. To do this you'll need to find and execute TileMill's `index.js` file, the specifics of which will depend on your platform.

### Mac OS X

    cd /Applications/TileMill.app/Contents/Resources/
    ./index.js export --help

### Ubuntu

    node /usr/share/tilemill/index.js export --help

For other Linux distribution or for custom-compiled TileMill installation, you'll can to navigate to the directory where TileMill is installed and execute `./index.js export --help` from there.

### Windows

    cd "C:\Program Files (x86)\TileMill-v0.10.0\tilemill"
    .\node.exe .\index.js export --help

### Export examples

To export an mbtiles file into `~/Documents/MapBox/export` (the same folder the TileMill user interface will use)
from the `geography-class` project for a restricted set of zoom levels do:

    ./index.js export geography-class ~/Documents/MapBox/export/geography-class.mbtiles --minzoom=0 --maxzoom=5

To export a single png image from the `geography-class`	project for a bounding box representing the USA do:

    ./index.js export geography-class ~/Documents/MapBox/export/geography-class.png --format=png --width=600 --height=400 --bbox="-131.4844,20.3034,-62.5781,51.3992"

### How to make the export less verbose

By default Millstone outputs a lot of debugging information, but this can be disabled on the fly by doing:

    export NODE_ENV=production

Do this in the shell in which you run the export command.

You can also pass `--verbose=off` to reduce the amount of output from TileMill's export script.

### Command line export options

Usage:

    index.js export [options] <project> <export_file>

Options:

--format=[format]                 	Export format (png|jpeg|tiff|pdf|svg|mbtiles|upload|sync). (Default: undefined)

--bbox=[xmin,ymin,xmax,ymax]      	Comma separated coordinates of bounding box to export. (Default: undefined)

--minzoom=[zoom]                  	MBTiles: minimum zoom level to export. (Default: undefined)

--maxzoom=[zoom]                  	MBTiles: maximum zoom level to export. (Default: undefined)

--width=[width]                   	Image: image width in pixels. (Default: 400)

--height=[height]                 	Image: image height in pixels. (Default: 400)

--url=[url]                       	URL to PUT updates to. (Default: undefined)

--log                             	Write crash logs to destination directory. (Default: undefined)

--quiet                           	Suppresses progress output. (Default: undefined)

--scheme=[scanline|pyramid|file]  	Enumeration scheme that defines the order in which tiles will be rendered. (Default: "scanline")

--job=[file]                      	Store state in this file. If it exists, that job will be resumed. (Default: false)

--list=[file]                     	Provide a list file for filescheme render. (Default: false)

--metatile=[num]                  	Metatile size. (Default: undefined)

--scale=[num]                     	Scale factor (Default: undefined)

--concurrency=[num]               	Number of exports that can be run concurrently. (Default: 4)

--files=[path]                    	Path to files directory. (Default: "/home/aj/Documents/MapBox")

--syncURL=[URL]                   	MapBox sync URL. (Default: "https://api.mapbox.com")

--syncAccount=[account]           	MapBox account name. (Default: "")

--syncAccessToken=[token]         	MapBox access token. (Default: "")

--verbose=on|off                  	verbose logging (Default: "on")

--config=[path]                   	Path to JSON configuration file.

redpajama_set_name: RedPajamaGithub


text:
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* PHP_Beautifier_Common and PHP_Beautifier_Interface
*
* PHP version 5
*
* LICENSE: This source file is subject to version 3.0 of the PHP license
* that is available through the world-wide-web at the following URI:
* http://www.php.net/license/3_0.txt.  If you did not receive a copy of
* the PHP License and are unable to obtain it through the web, please
* send a note to license@php.net so we can mail you a copy immediately.
* @category   PHP
* @package PHP_Beautifier
* @author Claudio Bustos <cdx@users.sourceforge.com>
* @copyright  2004-2006 Claudio Bustos
* @link     http://pear.php.net/package/PHP_Beautifier
* @link     http://beautifyphp.sourceforge.net
* @license    http://www.php.net/license/3_0.txt  PHP License 3.0
* @version    CVS: $Id:$
*/
/**
* Wraps commons method por PHP_Beautifier
*
* Common methods for PHP_Beautifier, almost file management.
* All the methods are static
*
* @category   PHP
* @package PHP_Beautifier
* @author Claudio Bustos <cdx@users.sourceforge.com>
* @copyright  2004-2006 Claudio Bustos
* @link     http://pear.php.net/package/PHP_Beautifier
* @link     http://beautifyphp.sourceforge.net
* @license    http://www.php.net/license/3_0.txt  PHP License 3.0
* @version    Release: 0.1.14
*/
class PHP_Beautifier_Common {
    /**
    * Normalize reference to directories
    * @param  string path to directory
    * @return string normalized path to directory
    */
    public static function normalizeDir($sDir)
    {
        $sDir = str_replace(DIRECTORY_SEPARATOR, '/', $sDir);
        if (substr($sDir, -1) != '/') {
            $sDir.= '/';
        }
        return $sDir;
    }
    /**
    * Search, inside a dir, for a file pattern, using regular expresion
    * Example:
    *
    * PHP_Beautifier_Common::getFilesByPattern('.','*.php',true);
    * Search recursively for all the files with php extensions
    * in the current dir
    * @param    string  path to a dir
    * @param    string  file pattern
    * @param    bool    recursive?
    * @return   array   path to files
    */
    public static function getFilesByPattern($sDir, $sFilePattern, $bRecursive = false)
    {
        if (substr($sDir, -1) == '/') {
            $sDir = substr($sDir, 0, -1);
        }
        $dh = @opendir($sDir);
        if (!$dh) {
            throw (new Exception("Cannot open directory '$sDir'"));
        }
        $matches = array();
        while ($entry = @readdir($dh)) {
            if ($entry == '.' or $entry == '..') {
                continue;
            } elseif (is_dir($sDir.'/'.$entry) and $bRecursive) {
                $matches = array_merge($matches, PHP_Beautifier_Common::getFilesByPattern($sDir.'/'.$entry, $sFilePattern, $bRecursive));
            } elseif (preg_match("/".$sFilePattern."$/", $entry)) {
                $matches[] = $sDir."/".$entry;
            }
        }
        if (!$matches) {
            PHP_Beautifier_Common::getLog()->log("$sDir/$sFilePattern pattern don't match any file", PEAR_LOG_DEBUG);
        }
        return $matches;
    }
    /**
    * Create a dir for a file path
    * @param    string  file path
    * @return   bool
    * @throws   Exception
    */
    public static function createDir($sFile)
    {
        $sDir = dirname($sFile);
        if (file_exists($sDir)) {
            return true;
        } else {
            $aPaths = explode('/', $sDir);
            $sCurrentPath = '';
            foreach($aPaths as $sPartialPath) {
                $sCurrentPath.= $sPartialPath.'/';
                if (file_exists($sCurrentPath)) {
                    continue;
                } else {
                    if (!@mkdir($sCurrentPath)) {
                        throw (new Exception("Can't create directory '$sCurrentPath'"));
                    }
                }
            }
        }
        return true;
    }
    /**
    * Return an array with the paths to save for an array of files
    * @param    array  Array of files (input)
    * @param    string Init path
    * @return   array  Array of files (output)
    */
    public static function getSavePath($aFiles, $sPath = './')
    {
        $sPath = PHP_Beautifier_Common::normalizeDir($sPath);
        // get the lowest denominator..
        $sPrevious = '';
        $iCut = 0;
        foreach($aFiles as $i=>$sFile) {
            $sFile = preg_replace("/^.*?#/", '', $sFile);
            $aFiles[$i] = $sFile;
            if (!$sPrevious) {
                $sPrevious = dirname($sFile);
                continue;
            }
            $aPreviousParts=explode("/",$sPrevious);
            $aCurrentParts=explode("/",dirname($sFile));
            for($x=0;$x<count($aPreviousParts);$x++) {
                if($aPreviousParts[$x]!=$aCurrentParts[$x]) {
                    $sPrevious=implode("/",array_slice($aPreviousParts,0,$x));
                }
            }
        }
        $iCut = strlen($sPrevious);
        $aPathsOut = array();
        foreach($aFiles as $sFile) {
            $sFileOut = preg_replace("/^(\w:\/|\.\/|\/)/", "", substr($sFile, $iCut));
            $aPathsOut[] = $sPath.$sFileOut;
        }
        return $aPathsOut;
    }
    /**
    * Search, inside a dir, for a file pattern using glob(* and ?)
    * @param    string  path
    * @param    bool    recursive
    * @return   array   path to files
    */
    public static function getFilesByGlob($sPath, $bRecursive = false)
    {
        if (!$bRecursive) {
            return glob($sPath);
        } else {
            $sDir = (dirname($sPath)) ? realpath(dirname($sPath)) : realpath('./');
            $sDir = PHP_Beautifier_Common::normalizeDir($sDir);
			$sDir = substr($sDir, 0, -1); // strip last slash
            $sGlob = basename($sPath);
            $dh = @opendir($sDir);
            if (!$dh) {
                throw (new Exception("Cannot open directory '$sPath'"));
            }
            $aMatches = glob($sDir.'/'.$sGlob);
            while ($entry = @readdir($dh)) {
                if ($entry == '.' or $entry == '..') {
                    continue;
                } elseif (is_dir($sDir.'/'.$entry)) {
                    $aMatches = array_merge($aMatches, PHP_Beautifier_Common::getFilesByGlob($sDir.'/'.$entry.'/'.$sGlob, true));
                }
            }
            return $aMatches;
        }
    }
    /**
    * Get a {@link Log_composite} object for PHP_Beautifier
    * Always return the same object (Singleton pattern)
    * @return Log_composite
    */
    public static function getLog()
    {
        return Log::singleton('composite', 'PHP_Beautifier');
    }
    /**
    * Transform whitespaces into its representation
    * So, tabs becomes \t, newline \n and feed \r
    * Useful for log
    * @param string
    * @return string
    */
    public static function wsToString($sText)
    {
        // ArrayNested->off();
        return str_replace(array("\r", "\n", "\t"), array('\r', '\n', '\t'), $sText);
        // ArrayNested->on();

    }
}
// Interfaces

/**
* Interface for PHP_Beautifier and subclasses.
* Created to made a 'legal' Decorator implementation
*
* @category   PHP
* @package PHP_Beautifier
* @author Claudio Bustos <cdx@users.sourceforge.com>
* @copyright  2004-2006 Claudio Bustos
* @link     http://pear.php.net/package/PHP_Beautifier
* @link     http://beautifyphp.sourceforge.net
* @license    http://www.php.net/license/3_0.txt  PHP License 3.0
* @version    Release: 0.1.14
*/
interface PHP_Beautifier_Interface {
    /**
    * Process the file(s) or string
    */
    public function process();
    /**
    * Show on screen the output
    */
    public function show();
    /**
    * Get the output on a string
    * @return string
    */
    public function get();
    /**
    * Save the output to a file
    * @param string path to file
    */
    public function save($sFile = null);
}
?>


text:
import { defaultsDeep } from 'lodash';
import { PanelPluginMeta, PluginMeta, PluginType, PanelPlugin, PanelProps } from '@savantly/sprout-api';
import { ComponentType } from 'enzyme';

export const getMockPlugins = (amount: number): PluginMeta[] => {
  const plugins = [];

  for (let i = 0; i <= amount; i++) {
    plugins.push({
      defaultNavUrl: 'some/url',
      enabled: false,
      hasUpdate: false,
      id: `${i}`,
      info: {
        author: {
          name: 'Grafana Labs',
          url: 'url/to/GrafanaLabs',
        },
        description: 'pretty decent plugin',
        links: ['one link'],
        logos: { small: 'small/logo', large: 'large/logo' },
        screenshots: [{ path: `screenshot/${i}` }],
        updated: '2018-09-26',
        version: '1',
      },
      latestVersion: `1.${i}`,
      name: `pretty cool plugin-${i}`,
      pinned: false,
      state: '',
      type: '',
      module: {},
    });
  }

  return plugins as any;
};

export function getPanelPlugin(
  options: Partial<PanelPluginMeta>,
  reactPanel?: ComponentType<PanelProps>,
  angularPanel?: any
): PanelPlugin {
  const plugin = new PanelPlugin(reactPanel!);
  plugin.meta = {
    id: options.id!,
    type: PluginType.panel,
    name: options.id!,
    sort: options.sort || 1,
    info: {
      author: {
        name: options.id + 'name',
      },
      description: '',
      links: [],
      logos: {
        large: '',
        small: '',
      },
      screenshots: [],
      updated: '',
      version: '',
    },
    hideFromList: options.hideFromList === true,
    module: '',
    baseUrl: '',
  };
  return plugin;
}

export function getMockPlugin(overrides?: Partial<PluginMeta>): PluginMeta {
  const defaults: PluginMeta = {
    defaultNavUrl: 'some/url',
    enabled: false,
    hasUpdate: false,
    id: '1',
    info: {
      author: {
        name: 'Grafana Labs',
        url: 'url/to/GrafanaLabs',
      },
      description: 'pretty decent plugin',
      links: [{ name: 'project', url: 'one link' }],
      logos: { small: 'small/logo', large: 'large/logo' },
      screenshots: [{ path: `screenshot`, name: 'test' }],
      updated: '2018-09-26',
      version: '1',
    },
    latestVersion: '1',
    name: 'pretty cool plugin 1',
    baseUrl: 'path/to/plugin',
    pinned: false,
    type: PluginType.panel,
    module: 'path/to/module',
  };

  return defaultsDeep(overrides || {}, defaults) as PluginMeta;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ftp.Utilities
{
    public sealed class MainExecutor
    {

        public void Run()
        {

        }
    }
}


text:
..
      Copyright 2015 OpenStack Foundation
      All Rights Reserved.

      Licensed under the Apache License, Version 2.0 (the "License"); you may
      not use this file except in compliance with the License. You may obtain
      a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
      WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
      License for the specific language governing permissions and limitations
      under the License.

==================
Basic architecture
==================

OpenStack Glance has a client-server architecture that provides a REST API
to the user through which requests to the server can be performed.

A Glance Domain Controller manages the internal server operations
that is divided into layers. Specific tasks are implemented
by each layer.

All the file (Image data) operations are performed using
glance_store library, which is responsible for interaction with external
storage back ends and (or) local filesystem(s). The glance_store library
provides a uniform interface to access the backend stores.

Glance uses a central database (Glance DB) that is shared amongst all
the components in the system and is sql-based by default. Other types
of database backends are somewhat supported and used by operators
but are not extensively tested upstream.

.. figure:: ./images/architecture.png
   :figwidth: 100%
   :align: center
   :alt: OpenStack Glance Architecture Diagram.
         Consists of 5 main blocks: "Client" "Glance" "Keystone"
         "Glance Store" and "Supported Storages".
         Glance block exposes a REST API.  The REST API makes use of the
         AuthZ Middleware and a Glance Domain Controller, which contains
         Auth, Notifier, Policy, Quota, Location and DB.  The Glance Domain
         Controller makes use of the Glance Store (which is external to the
         Glance block), and (still within the Glance block) it makes use of
         the Database Abstraction Layer, and (optionally) the Registry Layer.
         The Registry Layer makes use of the Database Abstraction Layer. The
         Database abstraction layer exclusively makes use of the Glance
         Database.
         The Client block makes use of the Rest API (which exists in the
         Glance block) and the Keystone block.
         The Glance Store block contains AuthN which makes use of the
         Keystone block, and it also contains Glance Store Drivers, which
         exclusively makes use of each of the storage systems in the
         Supported Storages block.  Within the Supported Storages block,
         there exist the following storage systems, none of which make use
         of anything else: Filesystem, Swift, Ceph, "ellipses", Sheepdog.
         A complete list is given by the currently  available drivers in
         glance_store/_drivers.

.. centered:: Image 1. OpenStack Glance Architecture

Following components are present in the Glance architecture:

* **A client** - any application that makes use of a Glance server.

* **REST API** - Glance functionalities are exposed via REST.

* **Database Abstraction Layer (DAL)** - an application programming interface
    (API) that unifies the communication between Glance and databases.

* **Glance Domain Controller** - middleware that implements the main
    Glance functionalities such as authorization, notifications, policies,
    database connections.

* **Glance Store** - used to organize interactions between Glance and various
    data stores.

* **Registry Layer** - optional layer that is used to organise secure
    communication between the domain and the DAL by using a separate service.


text:
FROM ubuntu

# Set the file maintainer
MAINTAINER Dongyi Yang <dongyi.yang@vmturbo.com>

ADD ./_output/conntracker /bin/conntracker

ENTRYPOINT ["/bin/conntracker"]


text:
namespace blimp {
namespace client {

static jlong Init(
    JNIEnv* env,
    const base::android::JavaParamRef<jobject>& jobj,
    const base::android::JavaParamRef<jobject>& blimp_client_session) {
  BlimpClientSession* client_session =
      BlimpClientSessionAndroid::FromJavaObject(env, blimp_client_session);

  return reinterpret_cast<intptr_t>(
      new TabControlFeatureAndroid(env,
                                   jobj,
                                   client_session->GetTabControlFeature()));
}

// static
bool TabControlFeatureAndroid::RegisterJni(JNIEnv* env) {
  return RegisterNativesImpl(env);
}

TabControlFeatureAndroid::TabControlFeatureAndroid(
    JNIEnv* env,
    const base::android::JavaParamRef<jobject>& jobj,
    TabControlFeature* tab_control_feature)
    : tab_control_feature_(tab_control_feature) {
  java_obj_.Reset(env, jobj);
}

TabControlFeatureAndroid::~TabControlFeatureAndroid() {}

void TabControlFeatureAndroid::Destroy(
    JNIEnv* env,
    const base::android::JavaParamRef<jobject>& jobj) {
  delete this;
}

void TabControlFeatureAndroid::OnContentAreaSizeChanged(
    JNIEnv* env,
    const base::android::JavaParamRef<jobject>& jobj,
    jint width,
    jint height,
    jfloat dp_to_px) {
  tab_control_feature_->SetSizeAndScale(gfx::Size(width, height), dp_to_px);
}

}  // namespace client
}  // namespace blimp


text:
<?php
/**
 * Created by PhpStorm.
 * User: phemmy
 * Date: 24/12/15
 * Time: 1:12 PM
 */

class Prog_model extends CI_Model {

    public function __construct()
    {
        // Call the CI_Model constructor
        parent::__construct();
    }

    public function get_last_ten_entries()
    {
        $query = $this->db->get('programme_listing', 10);
        return $query->result();
    }

    public function insert_prog()
    {
        $this->db->insert('programme_listing', $this);
    }

    public function update_entry()
    {
        $this->db->update('programme_listing', $this, array('id' => $_POST['id']));
    }

}

?>


text:
int main()                                    // Main function
{
 print("War Eagle\n");
 print("Roar Lions");
}


text:
package stripe_test

import (
	"log"

	stripe "github.com/stripe/stripe-go"
	"github.com/stripe/stripe-go/charge"
	"github.com/stripe/stripe-go/customer"
	"github.com/stripe/stripe-go/invoice"
	"github.com/stripe/stripe-go/plan"
)

func ExampleCharge_new() {
	stripe.Key = "sk_key"

	params := &stripe.ChargeParams{
		Amount:   stripe.Int64(1000),
		Currency: stripe.String(string(stripe.CurrencyUSD)),
	}
	params.SetSource("tok_visa")
	params.AddMetadata("key", "value")

	ch, err := charge.New(params)

	if err != nil {
		log.Fatal(err)
	}

	log.Printf("%v\n", ch.ID)
}

func ExampleCharge_get() {
	stripe.Key = "sk_key"

	params := &stripe.ChargeParams{}
	params.AddExpand("customer")
	params.AddExpand("application")
	params.AddExpand("balance_transaction")

	ch, err := charge.Get("ch_example_id", params)

	if err != nil {
		log.Fatal(err)
	}

	if ch.Application != nil {
		log.Fatal(err)
	}

	log.Printf("%v\n", ch.ID)
}

func ExampleInvoice_update() {
	stripe.Key = "sk_key"

	params := &stripe.InvoiceParams{
		Description: stripe.String("updated description"),
	}

	inv, err := invoice.Update("sub_example_id", params)

	if err != nil {
		log.Fatal(err)
	}

	log.Printf("%v\n", inv.Description)
}

func ExampleCustomer_delete() {
	stripe.Key = "sk_key"

	customerDel, err := customer.Del("cus_example_id", nil)

	if err != nil {
		log.Fatal(err)
	}

	if !customerDel.Deleted {
		log.Fatal("Customer doesn't appear deleted while it should be")
	}
}

func ExamplePlan_list() {
	stripe.Key = "sk_key"

	params := &stripe.PlanListParams{}
	params.Filters.AddFilter("limit", "", "3")
	params.Single = true

	it := plan.List(params)
	for it.Next() {
		log.Printf("%v ", it.Plan().Nickname)
	}
	if err := it.Err(); err != nil {
		log.Fatal(err)
	}
}


text:
package io.akkawarsjawa.core

import akka.actor._
import java.util.UUID
import com.codahale.metrics.{MetricRegistry, Meter}
import akka.event.Logging
import java.nio.charset.Charset
import akka.contrib.pattern.ReliableProxy

object LogReceiverActor {
   case class SendMessage(to: String, message: String)
   case class JsonLogMessage(appName: String, json: Map[String, String])
   case class LineLogMessage(appName: String, line: String)
   case class FileLogMessage(appName: String, bytes: Array[Byte])
}

class LogReceiverActor(aggregator: ActorRef) extends Actor with ActorLogging {

   import LogReceiverActor._
   import scala.concurrent.duration._
   val processor = context.actorOf(
      Props(classOf[LogProcessor]), "logProcessor")

   override def preStart() = {
      log.debug("Starting LogReceiverActor")
   }

   def receive: Receive = {
      case message @ JsonLogMessage(appName, jsonMap) =>
         log.debug(s"Received json for app: $appName")
         aggregator ! message
      case lineMessage @ LineLogMessage(appName, line) =>
         log.debug(s"Received single line for app: $appName")
         processor ! lineMessage
      case FileLogMessage(appName, bytes) =>
         log.debug(s"Received file for app: $appName")
         val content = new String(bytes, Charset.forName("UTF-8"))
         val lines = content.split("\n")
         for(line <- lines) {
            aggregator ! JsonLogMessage(appName,
               Map("message" -> line))
         }
   }
}


text:
import argparse
import os
import subprocess

def main():
    p = argparse.ArgumentParser()
    p.add_argument('cmake_path', help='The cmake binary to use')
    p.add_argument('swift_src_dir', help='The swift source directory')
    p.add_argument('clang', help='The path to the clang binary to use')
    p.add_argument('swift_root_dir',
                   help='A path to a swift root produced by installing '
                        'Swift and Foundation together. We infer swiftc '
                        'from here')
    p.add_argument('destdir', help='The directory to perform the actual '
                                   'build in')
    p.add_argument('--clean', action='store_true',
                   help='Delete destdir before performing a build.')
    args = p.parse_args()

    if args.clean:
        print("Asked to clean... Cleaning!")
        subprocess.check_output(['/bin/rm', '-rfv', args.destdir])
    subprocess.check_call(['/bin/mkdir', '-p', args.destdir])
    os.chdir(args.destdir)
    configureInvocation = [
        args.cmake_path, '-GNinja',
        '-DSWIFT_EXEC={}/bin/swiftc'.format(args.swift_root_dir),
        '-DCLANG_EXEC={}'.format(args.clang),
        '-DSWIFT_LIBRARY_PATH={}/lib/swift'.format(args.swift_root_dir),
        '{}/benchmark'.format(args.swift_src_dir)
    ]
    print('COMMAND: {}'.format(' '.join(configureInvocation)))
    subprocess.check_call(configureInvocation)

    buildInvocation = [
        args.cmake_path, '--build', args.destdir, '--',
        'swift-benchmark-linux-x86_64'
    ]
    print('COMMAND: {}'.format(' '.join(buildInvocation)))
    subprocess.check_call(buildInvocation)

if __name__ == "__main__":
    main()


text:
<ion-view title="{{fungame}}" class="fungame-page">
    <ion-content has-header="true" padding="true">
       this fungame is {{fungame}}
	</ion-content>
</ion-view>


text:
<?php

require(__DIR__ . '/vendor/autoload.php');

Httpful\Bootstrap::init();
RESTful\Bootstrap::init();
Balanced\Bootstrap::init();

Balanced\Settings::$api_key = "ak-test-2eKlj1ZDfAcZSARMf3NMhBHywDej0avSY";

$bank_account = Balanced\BankAccount::get("/bank_accounts/BA45anEaEr8g0lOhzhcE9VAN");
$bank_account->credits->create(array(
    "amount" => 5000,
));

?>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

	<title>Services</title>
	<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=iso-8859-1" />
	<meta http-equiv="imagetoolbar" content="no" />
	<link rel="stylesheet" type="text/css" href="/style.css" />
	<link rel="shortcut icon" href="/favicon.ico" />

<?php include("../../header.php"); ?>

On-Site Consulting Services: $125/hour

One (1) hour minimum during business hours.

Three (3) hour minimum outside business hours.

Off-Site Consulting Services: $75/hour

Twenty (20) minute minimum.

May be billed on a "fair time" basis.  Fair time is billed as an
		estimate of focused time spent on your project.

Emergency Service: $175/hour + expenses

Billing commences upon emergency declaration and includes travel both
		to and from your location.

Expenses incurred to interrupt present activity may be billed.
		For example, if your representative is out for dinner, you may be
		billed the cost of the dinner.

Projects: Contact Us

Contract pricing is available for large projects and custom software
		development.  Contact us for more information.

	<?php include("../../contact/contact.php"); ?>

<?php include("../../menu.php"); ?>

<?php include("../../footer.php"); ?>


text:
An application for importing analytics into Influx from a 128T router or conductor.

## Building

Simply clone the repository and run `make` in the base directory.

## Running

First, download the application by going to [the releases page](https://github.com/128technology/influx-importer/releases/) and choosing the correct bundle based on your operating system and architecture.

Running `./influx-importer --help` will display a series of help.

Create the configuration file that influx-importer will use

```bash
./influx-importer init --out influx-importer.conf
```

You will be prompted to input information about the 128T instance you plan to run against. This information will also be used to populate the available metrics within the configuration file.

Open influx-importer.conf and fill in the sections for "influx", and "metrics".

The "influx" section contains settings for access to your Influx database. These should be self expanitory. *Note: Make sure you create the Influx database before you run this application!*

Finally, the "metrics" section comes pre-populated with all the metrics that Devils Purse has.
Simply find the metrics you are interested in and uncomment them.
Remember, the more metrics you uncomment the longer it takes to poll and the more stress you place on the 128T.

```bash
$ ./influx-importer extract --config ./influx-importer.conf

Successfully exported bandwidth(router=corp,node=t128_corp_primary).
Successfully exported session_count(router=corp,node=t128_corp_primary).
Successfully exported session_arrival_rate(router=corp,node=t128_corp_primary).
Successfully exported session_departure_rate(router=corp,node=t128_corp_primary).
Successfully exported total_data(router=corp,node=t128_corp_primary).
Successfully exported rx_data(router=corp,node=t128_corp_primary).
Successfully exported tx_data(router=corp,node=t128_corp_primary).
Successfully exported bandwidth(router=corp,device_interface=10).
Successfully exported session_count(router=corp,device_interface=10).
Successfully exported session_arrival_rate(router=corp,device_interface=10).
Successfully exported session_departure_rate(router=corp,device_interface=10).
Successfully exported total_data(router=corp,device_interface=10).
...
```

## Production Tips

The following are tips for running in a production environment.

### Run with Cron

The influx-importer application is not a long running process in that it will query then exit. Because of this, it's important
to consider setting execution of the application up using `cron`.

### Use a Log Rotator

The influx-importer application is verbose. When running, it's important to save the log output as it'll be crucial to debugging
any issue between the 128T application and the Influx database. However, saving it to a file without a log rotation mechanism is not recommended.
A productive solution is to output logs to `/var/log/influx-importer` and setup `/etc/logrotate.conf` to rotate the logs within that directory.

### Influx Authentication Requirements

The influx-importer requires read/write access to the influx database. Without read access you will find that the application does not
smartly ask the 128T for the delta of a metric since the last query. Instead, the influx-importer will always ask for `config query-time` worth of data.
This `read` requirement is because the influx-importer queries Influx for the last time a metric was retrieved and asks the 128T for data up to that point
in time.


text:
import { createSelector } from 'reselect';

/**
 * Direct selector to the myBooksPage state domain
 */
const selectMyBooksPageDomain = () => (state) => state.get('myBooksPage');

/**
 * Other specific selectors
 */
const makeSelectFetching = () => createSelector(
  selectMyBooksPageDomain(),
  (MyBooksState) => MyBooksState.get('fetching')
);

const makeSelectError = () => createSelector(
  selectMyBooksPageDomain(),
  (MyBooksState) => MyBooksState.get('error')
);

const makeSelectBooks = () => createSelector(
  selectMyBooksPageDomain(),
  (MyBooksState) => MyBooksState.get('books')
);

const makeSelectNumPages = () => createSelector(
  selectMyBooksPageDomain(),
  (MyBooksState) => MyBooksState.get('numPages')
);

const makeSelectActivePage = () => createSelector(
  selectMyBooksPageDomain(),
  (MyBooksState) => MyBooksState.get('activePage')
);
/**
 * Default selector used by MyBooksPage
 */

const makeSelectMyBooksPage = () => createSelector(
  selectMyBooksPageDomain(),
  (substate) => substate.toJS()
);

export default makeSelectMyBooksPage;
export {
  selectMyBooksPageDomain,
  makeSelectFetching,
  makeSelectError,
  makeSelectBooks,
  makeSelectNumPages,
  makeSelectActivePage,
};


text: #include "DiligentCore/Graphics/GraphicsAccessories/interface/SRBMemoryAllocator.hpp"


text:
<?php

class ExplorerController extends BaseController {

    private $bitcoinClient;

    public function __construct(Blocktrail $client) {
        $this->bitcoinClient = $client;
    }

    public function showHome()
    {
        try {
            //get the latest few blocks
            $blocks = $this->bitcoinClient->allBlocks($page = 1, $limit = 5, $sortDir = 'desc');

            //create the view, passing the data
            $data = array('blocks' => $blocks);
            return View::make('explorer.home', $data);

        } catch(Exception $e) {
            $data = array(
                "title"    => "",
                "subtitle" => "An Error Ocurred",
                "message" => $e->getMessage(),
            );
            return View::make('error.general', $data);
        }
    }

    public function showAddress($address)
    {
        try {
            //get the address data
            $addressInfo = $this->bitcoinClient->address($address);
            //get the address transactions
            $page = Input::get('page', 1);
            $transactions = $this->bitcoinClient->addressTransactions($address, $page, $limit=20, $sortDir='desc');

            //create an instance of the Paginator for easy pagination of the results
            $transactions = Paginator::make($transactions['data'], $transactions['total'], $transactions['per_page']);

            $data = array('summary' => $addressInfo, 'transactions' => $transactions);
            return View::make('explorer.address', $data);

        } catch(Exception $e) {
            $data = array(
                "title"    => "Bitcoin Address",
                "subtitle" => "Could Not Get Address Data",
                "message" => $e->getMessage(),
            );
            return View::make('error.general', $data);
        }
    }

    public function showTransaction($txhash)
    {
        try {
            //get the transaction data
            $data = $this->bitcoinClient->transaction($txhash);

            return View::make('explorer.transaction', $data);

        } catch(Exception $e) {
            $data = array(
                "title"    => "Bitcoin Transaction",
                "subtitle" => "Could Not Get Transaction Data",
                "message" => $e->getMessage(),
            );
            return View::make('error.general', $data);
        }
    }

    public function showBlock($block)
    {
        try {
            //get the block data
            $blockInfo = $this->bitcoinClient->block($block);
            //get the block transactions
            $page = Input::get('page', 1);
            $transactions = $this->bitcoinClient->blockTransactions($block, $page, $limit=20, $sortDir='desc');

            //create an instance of the Paginator for easy pagination of the results
            $transactions = Paginator::make($transactions['data'], $transactions['total'], $transactions['per_page']);

            $data = array('block' => $blockInfo, 'transactions' => $transactions);
            return View::make('explorer.block', $data);

        } catch(Exception $e) {
            $data = array(
                "title"    => "Bitcoin Block",
                "subtitle" => "Could Not Get Block Data",
                "message" => $e->getMessage(),
            );
            return View::make('error.general', $data);
        }
    }

    public function search()
    {
        if(Input::get('query')) {
            //detect what is being searched for
            $query = Input::get('query');

            $addressRegex = "/^[123][a-km-zA-HJ-NP-Z0-9]{25,34}$/i";
            $blockHashRegex = "/^[0-9a-f]{64}$/i";
            $txHashRegex = "/^[0-9a-f]{64}$/i";
            $blockHeightRegex = "/^[0-9]+$/i";

            if(preg_match($addressRegex, $query)) {
                //go to address
                return Redirect::route('address', $query);
            } else if( (preg_match($blockHashRegex, $query) && strpos($query, "00000000") === 0) || preg_match($blockHeightRegex, $query)) {
                //go to block
                return Redirect::route('block', $query);
            } else if(preg_match($txHashRegex, $query)) {
                //go to transaction
                return Redirect::route('transaction', $query);
            } else {
                //no matching pattern
                $data = array(
                    "title"    => "",
                    "subtitle" => 'No search results for "'.$query.'"',
                    "message" => "please check your input, it doesn't appear to be an address, block hash or block height",
                );
                return View::make('error.search', $data);
            }
        }

        //no search input
        $data = array(
            "title"    => "",
            "subtitle" => "No search results ",
            "message" => "please enter an address hash, block hash or height",
        );
        return View::make('error.search', $data);
    }

}


text:
{% extends "base.html" %}
{% from 'products/includes/topic_macros.html' import topic_sidebar %}
{% set crumbs = [(url('products.product', slug=product.slug), pgettext('DB: products.Product.title', product.title))] %}
{% if subtopic %}
  {% set crumbs = crumbs + [(url('products.documents', product_slug=product.slug, topic_slug=topic.slug), pgettext('DB: products.Topic.title', topic.title)), (None, pgettext('DB: products.Topic.title', subtopic.title))] %}
  {% set canonical_url = canonicalize(model_url=subtopic.get_absolute_url()) %}
{% else %}
  {% set crumbs = crumbs + [(None, pgettext('DB: products.Topic.title', topic.title))] %}
  {% set canonical_url = canonicalize(model_url=topic.get_absolute_url()) %}
{% endif %}
{% set styles = ('products',) %}
{% set search_params = {'product': product.slug} %}

{% block title %}{{ pgettext('DB: products.Topic.title', topic.title) }} | {{ _('{product} Help')|f(product=pgettext('DB: products.Product.title', product.title)) }}{% endblock %}

{% block content %}

    {{ search_box(settings, id='support-search-documents', params=search_params) }}

      {% set prod_url = url('products.product', slug=product.slug) %}

      {{ pgettext('DB: products.Product.title', product.title) }}

    {{ topic_sidebar(topics[:10], subtopics, product, topic, subtopic) }}

  {% if product.slug == 'firefox' %}
    {# show-fx-download.js will remove the 'hidden' class below if the visitor is *NOT* using Firefox #}

              {{ _('Download Firefox') }}

{{ _('Systems and Languages') }}

{{ _("What's New") }}

{{ _('Privacy') }}

  {% endif %}

        {% if subtopic %}

        {% endif %}
        {{ pgettext('DB: products.Topic.title', topic.title) }}
        {% if subtopic %}

        {% endif %}

      {% if subtopic %}

          {{ pgettext('DB: products.Topic.title', subtopic.title) }}

      {% endif %}

      {# Show the description if it is different than the title. Otherwise, don't bother. #}
      {% if (subtopic and subtopic.title != subtopic.description) or (not subtopic and topic.title != topic.description) %}

          {% if subtopic %}
             {{ pgettext('DB: products.Topic.description', subtopic.description) }}
          {% else %}
            {{ pgettext('DB: products.Topic.description', topic.description) }}
          {% endif %}

      {% endif %}

        {% if not subtopic and subtopics %}
          {# only show subtopics on the parent topic page #}
          {% for subtopic in subtopics %}

              {{ pgettext('DB: products.Topic.title', subtopic.title) }}
              {% if subtopic.title != subtopic.description %}
                {{ pgettext('DB: products.Topic.description', subtopic.description) }}
              {% endif %}

          {% endfor %}
        {% endif %}
        {% for document in documents %}

            {{ document['document_title'] }}
            {{ document['document_summary'] }}

        {% endfor %}

      {% if fallback_documents %}

{{ _('In English') }}

        {% for document in fallback_documents %}
          {% if loop.first %}
{% endif %}

            {{ document['document_title'] }}

          {% if loop.last %}
{% endif %}
        {% endfor %}
      {% endif %}

      {{ _('Volunteer for Mozilla Support') }}

{% endblock %}

{% block for_contributors %}{% endblock %}


text:
require 'active_support'
require 'active_support/all'
require 'terminal-table'
require 'fileutils'
require 'yaml'
require 'erubis'
require 'hashie'
Hashie::Mash # for some reason, there are load issue later if i don't do this

require 'octokit'

require 'hubtime/version'
require 'hubtime/hub_config'
require 'hubtime/cacher'
require 'hubtime/commit'
require 'hubtime/github'
require 'hubtime/activity'
require 'hubtime/repo'


text:
layout: post
title: "How to host ASP.NET 5 Application in Azure Web Apps"
subtitle: "How to host ASP.NET 5 Application in Azure Web Apps"
date: 2015-04-18 19:46
author: "Anuraj"
comments: true
categories: [.Net, ASP.Net, ASP.Net MVC, Windows Azure]
tags: [.Net, ASP.Net, ASP.NET 5, ASP.Net MVC, ASP.Net vNext, Azure Websites, C#, IIS, IIS Express, Windows Azure]
header-img: "img/post-bg-01.jpg"
---
This post is about hosting ASP.NET 5 Application in Azure WebApps / Websites. If you are using Visual Studio, you can use the publish wizard. But if you are using k or dnx runtimes this option is not available. ASP.NET [wiki](https://github.com/aspnet/home/wiki) in GitHub contains a [page](https://github.com/aspnet/Home/wiki/FTP-deploy-an-AspNet-vNext-application-to-Microsoft-Azure-websites) about FTP deploy but it is not working :( Later I found another [ page](https://github.com/aspnet/Home/wiki/Deploy-an-AspNet-vNext-application-to-Microsoft-Azure-websites), which discuss about this. But I had to spent some time to make the deployment work successfully.

Here is the steps you need to follow to deploy ASP.NET app to Azure Web App.

1.  Include IIS in the project.json file - Even if you are using WebListener, you have to include the reference of IIS in your project.json file. This is important without this deployment will not work. So your project.json will look like this.

{% highlight Javascript %}
{
    "webroot": "wwwroot",
    "dependencies": {
        "Microsoft.AspNet.Diagnostics": "1.0.0-beta3",
        "Microsoft.AspNet.Hosting": "1.0.0-beta3",
        "Microsoft.AspNet.Mvc": "6.0.0-beta3",
        "Microsoft.AspNet.Server.WebListener": "1.0.0-beta3",
        "Microsoft.AspNet.StaticFiles": "1.0.0-beta3",
        "Microsoft.AspNet.Server.IIS": "1.0.0-beta3"
    },
    "commands": {
        "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5001"
    },
    "frameworks": {
        "aspnet50": { }
    }
}
{% endhighlight %}

2.  Bundle the application using KPM build command - I am using k runtime, I tried with dnx runtime, but I faced few issues, so switched back to k runtime. Here is the command, which will bundle the source and will make it ready for deployment. Make sure, you are bundling with the proper runtime. I am using shared mode in azure, and hence my target platform is x86. So I am bundling with x86 version of the runtime.

{% highlight text %}
kpm bundle --out C:\WebApp --runtime kre-clr-win-x86.1.0.0-beta3
{% endhighlight %}

You can find the installed runtimes and the name from the "C:\Users\[username]\.k\runtimes" folder. I am using beta3 runtime. Once you execute this command, you will find a folder structure like this in the C:\WebApp folder.

![Bundle output - Folder structure]({{ site.url }}/assets/images/2015/04/folderstructure.png)

Make sure you have a bin folder inside wwwroot folder, and which contains file - AspNet.Loader.dll. And here is the web.config file, inside wwwroot folder.
{% highlight XML %}
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="kpm-package-path" value="..\approot\packages" />
    <add key="bootstrapper-version" value="1.0.0-beta3" />
    <add key="runtime-path" value="..\approot\packages" />
    <add key="kre-version" value="1.0.0-beta3" />
    <add key="kre-clr" value="clr" />
    <add key="kre-app-base" value="..\approot\src\MVCApp" />
  </appSettings>
</configuration>
{% endhighlight %}

All the runtime, dependencies and packages are created inside approot folder. If you are deploying it in IIS, you need to point the website to the wwwroot folder.

3.  Publish files using FTP - Connect to the website FTP folder using any FTP client. Copy the contents in the C:\WebApp(output folder of kpm build) to site folder of the website. With this copy operation, You are overwriting the original site/wwwroot folder with the one in output folder and adding a new folder site/approot. Once upload finished, Remote site folder structure will look like this.

![Remote site folder structure]({{ site.url }}/assets/images/2015/04/remotesite.png)

**Hosting ASP.NET 5 apps in IIS and IIS Express.**

As I mentioned earlier, you can host this app in IIS, by pointing the physical path to the wwwroot folder.

![ASP.NET 5 - Hosting in IIS]({{ site.url }}/assets/images/2015/04/hostinginiis.png)

And you can do the same with IIS express as well.

{% highlight text %}
iisexpress /path:C:\WebApp\wwwroot /port:5001
{% endhighlight %}

Happy Programming :)


text:
	width
	height
	border
	border-top
	background
	border-radius


text:
import React from 'react';
import mui from 'material-ui';
// import injectTapEventPlugin from 'react-tap-event-plugin';
import Playbar from './Playbar/Playbar';

const MusicNoteIcon = require('material-ui/lib/svg-icons/image/music-note');
const List = mui.List;
const ListItem = mui.ListItem;
const ListDivider = mui.Divider;

class Playlist extends React . Component {
  constructor( props ) {
    super( props );
    this.state = {
      date: {},
      playing: 0,
      listLength: 0,
      current: {},
      mutex: true,
    };
  }

  static propTypes = {
    list: React.PropTypes.array.isRequired,
  }

  static childContextTypes = {
    callback: React.PropTypes.func,
    onError: React.PropTypes.func,
    onEnd: React.PropTypes.func,
    onPlay: React.PropTypes.func,
    mutex: React.PropTypes.bool,
  }

  getChildContext() {
    return {
      callback: this.onChangeSong.bind(this),
      onError: this.onError.bind(this),
      onEnd: this.onEnd.bind(this),
      onPlay: this.onPlay.bind(this),
      mutex: this.state.mutex,
    };
  }

  onChangeSong( index ) {
    let i = index;
    if (this.state.mutex) {
      // console.log('Waiting on youtube');
      return;
    }
    // console.log('new index', index, 'length', this.state.listLength);
    if (index < 0) {
      i = this.props.list.length - 1;
    }

    if ( index > this.props.list.length - 1) {
      i = 0;
    }

    this.setState( {
      mutex: true,
      playing: i,
    } );
  }

  onError() {
    // If error play the next song
    // if the error occurs on the last song,
    // return to the first song
    let index = this.state.playing;
    if (index === (this.state.listLength - 1 )) {
      index = -1;
    }
    this.setState({mutex: false});
    this.onChangeSong(++index);
  }

  onEnd() {
    // console.log('song ended', this);
    this.onError();
  }

  onPlay() {
    // console.log('Mutex off');
    this.setState({mutex: false});
    return;
    // if (!("Notification" in window)) {
    //   alert("This browser does not support desktop notification");
    // }

    // // Let's check whether notification permissions have already been granted
    // else if (Notification.permission === "granted") {
    //   console.log(this.state)
    //   // If it's okay let's create a notification
    //   // var options = {
    //   //   body: theBody,
    //   //   icon: theIcon
    //   // }
    //   var notification = new Notification(this.state.current);
    // }

    // // Otherwise, we need to ask the user for permission
    // else if (Notification.permission !== 'denied') {
    //   Notification.requestPermission(function (permission) {
    //     // If the user accepts, let's create a notification
    //     if (permission === 'granted') {
    //       var notification = new Notification('Hi there!');
    //     }
    //   });
    // }

    // At last, if the user has denied notifications, and you
    // want to be respectful there is no need to bother them any more.
  }

  render() {
    const playlist = this.props.list.map( (song, index) => {
      let
        component = (

            <ListItem primaryText={song.title} key={index} onClick={ this.onChangeSong.bind( this, index ) } />

        );
      if ( index === this.state.playing ) {
        component = (

            <ListItem leftIcon={<MusicNoteIcon/>} primaryText={song.title} key={index} onClick={ this.onChangeSong.bind( this, index ) } />

        );
      }
      return (component);
    });

    // console.log('current playing', this.state);
    if ( this.props.list.length === 0 ) {
      return (

      );
    }
    return (

      < List>
        {playlist}
        < /List>
        < ListDivider />

          <Playbar metadata={this.props.list[this.state.playing] } index={this.state.playing} parentCallback={this.onChangeSong.bind(this)} />

    );
  }

}

// export default Playlist;


text:
class DocumentHelper

  @@runtime_cache = {}
  @@remote_ip = nil
  @@base_url = nil

  class << self

    def init (ip, url)
      @@remote_ip = ip
      @@base_url = url
    end

    # define max file size
    def file_size_max
      if Rails.configuration.fileSizeMax == nil
        5 * 1024 * 1024
      else
        Rails.configuration.fileSizeMax  # or get it from the config
      end
    end

    # all the supported file extensions
    def file_exts
      [].concat(viewed_exts).concat(edited_exts).concat(convert_exts).concat(fill_forms_exts)
    end

    def fill_forms_exts
      if Rails.configuration.fillDocs.empty?
        []
      else
        Rails.configuration.fillDocs.split("|")
      end
    end

    # file extensions that can be viewed
    def viewed_exts
      if Rails.configuration.viewedDocs.empty?
        []
      else
        Rails.configuration.viewedDocs.split("|")
      end
    end

    # file extensions that can be edited
    def edited_exts
      if Rails.configuration.editedDocs.empty?
        []
      else
        Rails.configuration.editedDocs.split("|")
      end
    end

    # file extensions that can be converted
    def convert_exts
      if Rails.configuration.convertDocs.empty?
        []
      else
        Rails.configuration.convertDocs.split("|")
      end
    end

    # get current user host address
    def cur_user_host_address(user_address)
      (user_address == nil ? @@remote_ip : user_address).gsub(/[^0-9\-.a-zA-Z_=]/, '_');
    end

    # get the storage path of the given file
    def storage_path(file_name, user_address)
      directory = File.absolute_path?(Rails.configuration.storagePath) ? Rails.configuration.storagePath
                    : Rails.root.join('public', Rails.configuration.storagePath, cur_user_host_address(user_address))  # get the path to the directory for the host address

      # create a new directory if it doesn't exist
      unless File.directory?(directory)
        FileUtils.mkdir_p(directory)
      end

      # put the given file to this directory
      File.join(directory, File.basename(file_name))
    end

    # get the path to the forcesaved file version
    def forcesave_path(file_name, user_address, create)
      directory = File.absolute_path?(Rails.configuration.storagePath) ? Rails.configuration.storagePath
                    : Rails.root.join('public', Rails.configuration.storagePath, cur_user_host_address(user_address))

      # the directory with host address doesn't exist
      unless File.directory?(directory)
        return ""
      end

      directory = File.join(directory,"#{File.basename(file_name)}-hist")  # get the path to the history of the given file
      unless File.directory?(directory)
        if create
          FileUtils.mkdir_p(directory)  # create history directory if it doesn't exist
        else
          return ""  # the history directory doesn't exist and we are not supposed to create it
        end
      end

      directory = File.join(directory, File.basename(file_name))  # get the path to the given file
      unless File.file?(directory)
        if !create
          return ""
        end
      end

      return directory.to_s
    end

    # get the path to the file history
    def history_dir(storage_path)
      directory = "#{storage_path}-hist"

      # create history directory if it doesn't exist
      unless File.directory?(directory)
        FileUtils.mkdir_p(directory)
      end

      return directory
    end

    # get the path to the specified file version
    def version_dir(hist_dir, ver)
      return File.join(hist_dir, ver.to_s)
    end

    # get the last file version
    def get_file_version(hist_dir)
      if !Dir.exist?(hist_dir)
        return 1
      end

      ver = 1
      Dir.foreach(hist_dir) {|e|  # run through all the file versions
        next if e.eql?(".")
        next if e.eql?("..")
        if File.directory?(File.join(hist_dir, e))
          ver += 1  # and count them
        end
      }

      return ver
    end

    # get the correct file name if such a name already exists
    def get_correct_name(file_name, user_address)
      ext = File.extname(file_name)  # get file extension
      base_name = File.basename(file_name, ext)  # get file name without extension
      name = base_name + ext.downcase  # get full file name
      index = 1

      while File.exist?(storage_path(name, user_address))  # if the file with such a name already exists in this directory
          name = base_name + ' (' + index.to_s + ')' + ext.downcase  # add an index after its base name
          index = index + 1
      end

      name
    end

    # get all the stored files from the folder
    def get_stored_files(user_address)
      directory = File.absolute_path?(Rails.configuration.storagePath) ? Rails.configuration.storagePath
                    : Rails.root.join('public', Rails.configuration.storagePath, cur_user_host_address(user_address))

      arr = [];

      if Dir.exist?(directory)
        Dir.foreach(directory) {|e|  # run through all the elements from the folder
          next if e.eql?(".")
          next if e.eql?("..")
          next if File.directory?(File.join(directory, e))  # if the element is a directory, skip it

          arr.push(e)  # push the file to the array
        }
      end

      return arr
    end

    # create file meta information
    def create_meta(file_name, uid, uname, user_address)
      hist_dir = history_dir(storage_path(file_name, user_address))  # get the path to the file history

      # write user name, user uid and the creation time to the json object
      json = {
        :created => Time.now.to_formatted_s(:db),
        :uid => uid,
        :uname => uname
      }

      # write file meta information to the createdInfo.json file
      File.open(File.join(hist_dir, "createdInfo.json"), 'wb') do |file|
        file.write(json.to_json)
      end
    end

    # create demo document
    def create_demo(file_ext, sample, user)
      demo_name = (sample == 'true' ? 'sample.' : 'new.') + file_ext
      file_name = get_correct_name(demo_name, nil)  # get the correct file name if such a name already exists

      src = Rails.root.join('public', 'assets', sample == 'true' ? 'sample' : 'new', demo_name)  # save sample document of a necessary extension to the storage directory
      dest = storage_path file_name, nil

      FileUtils.cp src, dest

      # save file meta data to the file

      create_meta(file_name, user.id, user.name, nil)

      file_name
    end

    # get file url
    def get_file_uri(file_name, for_document_server)
      uri = get_server_url(for_document_server) + '/' + Rails.configuration.storagePath + '/' + cur_user_host_address(nil) + '/' + ERB::Util.url_encode(file_name)

      return uri
    end

    # get history path url
    def get_historypath_uri(file_name,version,file,is_serverUrl=true)
      # for redirection to my link
      user_host = is_serverUrl ? '&userAddress=' + cur_user_host_address(nil) : ""
      uri = get_server_url(is_serverUrl) + '/downloadhistory/?fileName=' + ERB::Util.url_encode(file_name) + '&ver='+ version.to_s + '&file='+ ERB::Util.url_encode(file) + user_host
      return uri
    end

    # get server url
    def get_server_url(for_document_server)
      if for_document_server && !Rails.configuration.urlExample.empty?
        return Rails.configuration.urlExample
      else
        return @@base_url
      end
    end

    # get callback url
    def get_callback(file_name)

      get_server_url(true) + '/track?fileName=' + ERB::Util.url_encode(file_name)  + '&userAddress=' + cur_user_host_address(nil)

    end

    # get url to the created file
    def get_create_url(document_type)

      get_server_url(false) + '/sample?fileExt=' + get_internal_extension(document_type).delete('.')

    end

    # get url to download a file
    def get_download_url(file_name, is_serverUrl=true)

      user_host = is_serverUrl ? '&userAddress=' + cur_user_host_address(nil) : ""
      get_server_url(is_serverUrl) + '/download?fileName=' + ERB::Util.url_encode(file_name)  + user_host

    end

    # get internal file extension by its type
    def get_internal_extension(file_type)

      case file_type
        when 'word'  # .docx for word type
          ext = '.docx'
        when 'cell'  # .xlsx for cell type
          ext = '.xlsx'
        when 'slide'  # .pptx for slide type
          ext = '.pptx'
        else
          ext = '.docx'  # the default value is .docx
      end

      ext
    end

    # get image url for templates
    def get_template_image_url(file_type)
      path = get_server_url(true) + "/assets/"
      case file_type
        when 'word'  # for word type
          full_path = path + 'file_docx.svg'
        when 'cell'  # .xlsx for cell type
          full_path = path + 'file_xlsx.svg'
        when 'slide'  # .pptx for slide type
          full_path = path + 'file_pptx.svg'
        else
          full_path = path + 'file_docx.svg'  # the default value is .docx
      end

      full_path
    end

    # get files information
    def get_files_info(file_id)
      result = [];

      for fileName in get_stored_files(nil)  # run through all the stored files from the folder
        directory = storage_path(fileName, nil)
        uri = cur_user_host_address(nil) + '/' + fileName

        # write file parameters to the info object
        info = {
          "version" => get_file_version(history_dir(directory)),
          "id" => ServiceConverter.generate_revision_id("#{uri}.#{File.mtime(directory).to_s}"),
          "contentLength" => "#{(File.size(directory)/ 1024.0).round(2)} KB",
          "pureContentLength" => File.size(directory),
          "title" => fileName,
          "updated" => File.mtime(directory)
        }

        if file_id == nil  # if file id is undefined
          result.push(info)  # push info object to the response array
        else  # if file id is defined
          if file_id.eql?(info["id"])  # and it is equal to the document key value
            result.push(info)  # response object will be equal to the info object
            return result
          end
        end
      end

      if file_id != nil
        return "\"File not found\""
      else
        return result
      end
    end
    # enable ignore certificate
    def verify_ssl(file_uri, http)
      if file_uri.start_with?('https') && Rails.configuration.verify_peer_off.eql?('true')
        http.use_ssl = true
        http.verify_mode = OpenSSL::SSL::VERIFY_NONE  # set the flags for the server certificate verification at the beginning of SSL session
      end
    end
  end

end


text:
package me.curlpipesh.pipe.util.helpers;

import me.curlpipesh.pipe.event.ChatSend;
import me.curlpipesh.pipe.injectors.GuiChatInjector;
import pw.aria.event.EventManager;

import java.util.Arrays;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

/**
 * Used in {@link GuiChatInjector} for
 * redirecting the chat messages to our custom "handler," so that we can push
 * {@link ChatSend} events without too much pain.
 *
 * @author c
 * @since 5/27/15
 */
@SuppressWarnings("unused")
public class ChatHelper {
    /**
     * The {@link Logger} implementation for this class. Uses a custom
     * {@link Handler} to log messages to the in-game chat.
     */
    private static final Logger logger = Logger.getLogger("Pipe");

    /**
     * Handles the "redirection" of chat messages. Method is "unused" because
     * the code that uses it is generated at runtime.
     *
     * @param message The message to tinker with.
     */
    public static void handle(String message) {
        if(!EventManager.push(new ChatSend(message)).isCancelled()) {
            Helper._sendChatMessage(message);
        }
    }

    /**
     * Logs a set of "INFO" messages to the chat
     *
     * @param messages The messages to log
     */
    public static void log(String... messages) {
        Arrays.stream(messages).forEach(logger::info);
    }

    /**
     * Logs a set of "DEBUG" messages to the chat
     *
     * @param messages The messages to log
     */
    public static void debug(String... messages) {
        Arrays.stream(messages).forEach(m -> logger.info("§0[§4Debug§0]§r " + m));
    }

    /**
     * Logs a set of "WARNING" messages to the chat
     *
     * @param messages The messages to log
     */
    public static void warn(String... messages) {
        Arrays.stream(messages).forEach(logger::warning);
    }

    static {
        logger.addHandler(new Handler() {
            @Override
            public void publish(LogRecord logRecord) {
                String levelColor =
                        logRecord.getLevel().equals(Level.SEVERE) ? "§4" :
                                logRecord.getLevel().equals(Level.WARNING) ? "§c" :
                                        logRecord.getLevel().equals(Level.INFO) ? "§e" : "§b";

                Helper.addChatMessage(String.format("§7[§aPipe§7]§r §7[%s%s§7]§r %s", levelColor, logRecord.getLevel(),
                        logRecord.getMessage()));
            }

            @Override
            public void flush() {
            }

            @Override
            public void close() throws SecurityException {
            }
        });
        logger.setUseParentHandlers(false);
    }
}


text:
package cfvbaibai.cardfantasy.engine.skill;

import cfvbaibai.cardfantasy.data.Skill;
import cfvbaibai.cardfantasy.engine.CardInfo;
import cfvbaibai.cardfantasy.engine.SkillEffect;
import cfvbaibai.cardfantasy.engine.SkillEffectType;
import cfvbaibai.cardfantasy.engine.SkillUseInfo;
import cfvbaibai.cardfantasy.engine.SkillResolver;

public class Revenge extends PreAttackCardSkill {
    public static void apply(SkillResolver resolver, SkillUseInfo skillUseInfo, CardInfo attacker) {
        int myDeadCount = attacker.getOwner().getGrave().size();
        if (myDeadCount == 0) {
            return;
        }
        Skill skill = skillUseInfo.getSkill();
        int adjAT = skill.getImpact() * myDeadCount;
        resolver.getStage().getUI().useSkill(attacker, skill, true);
        resolver.getStage().getUI().adjustAT(attacker, attacker, adjAT, skill);
        attacker.addEffect(new SkillEffect(SkillEffectType.ATTACK_CHANGE, skillUseInfo, adjAT, false));
    }
}


text:
namespace DEM::Game
{

class CMoveInteraction : public CInteraction
{
public:

	CMoveInteraction(std::string_view CursorImage = {});

	virtual bool      IsTargetValid(const CGameSession& Session, U32 Index, const CInteractionContext& Context) const override;
	virtual ESoftBool NeedMoreTargets(const CInteractionContext& Context) const override;
	virtual bool      Execute(CGameSession& Session, CInteractionContext& Context, bool Enqueue, bool PushChild) const override;
};

}


text:
#ifndef NCSJPC_H
#define NCSJPC_H

#ifndef NCSJPCMAINHEADER_H
#include "NCSJPCMainHeader.h"
#endif // NCSJPCMAINHEADER_H
#ifndef NCSJPCTILEPARTHEADER_H
#include "NCSJPCTilePartHeader.h"
#endif // NCSJPCTILEPARTHEADER_H

#include <map>

	/**
	 * CNCSJPC class - the JPC codestream class.
	 *
	 * @author       Simon Cope
	 * @version      $Revision: 1.24 $ $Author: russell $ $Date: 2005/03/04 05:02:48 $
	 */
class NCSJPC_EXPORT_ALL CNCSJPC: public CNCSJPCMainHeader {
public:
	typedef enum {
			/** Profile 0 */
		BASELINE_0		= 0,
			/** Profile 1 */
		BASELINE_1		= 1,
			/** Profile 2 - unrestricted */
		BASELINE_2		= 2,
			/** NITF NPJE profile */
		NITF_BIIF_NPJE	= 3,
			/** NITF EPJE Profile */
		NITF_BIIF_EPJE	= 4
	} Profile;

		/** Pointer to IO Stream instance for this codestream */
	CNCSJPCIOStream *m_pStream;

	/** A vector of the first Tile Part for each tile */
	std::vector<CNCSJPCTilePartHeader *> m_Tiles;

	/** Current Tile-Part being decoded */
	CNCSJPCTilePartHeader	*m_pCurrentTilePart;
		/** Next tilepart index */
	UINT32	m_nNextZtp;

		/** performing low-memory compression */
	bool m_bLowMemCompression;
		/** Reconstruction parameter */
	IEEE4 m_fReconstructionParameter;

		/** Default constructor, initialises members */
	CNCSJPC();
		/** Virtual destructor */
	virtual ~CNCSJPC();

		/**
		 * Parse the JPC codestream.
		 * @param		Stream		IOStream to use to parse file.
		 * @return      CNCSError	NCS_SUCCESS, or Error code on failure.
		 */
	virtual CNCSError Parse(CNCSJPCIOStream &Stream);
		/**
		 * UnParse the JPC codestream.
		 * @param		Stream		IOStream to use to parse file.
		 * @return      CNCSError	NCS_SUCCESS, or Error code on failure.
		 */
	virtual CNCSError UnParse(CNCSJPCIOStream &Stream);

		/**
		 * Get the Tile from the index and part index
		 * @param		INT32		Tile Index, >= 0, -1 == current tile main tile header
		 * @param		INT32		Tile Part Index, >= 0
		 * @return		CNCSJPCTilePartHeader*		Pointer to tile part
		 */
	CNCSJPCTilePartHeader *GetTile(INT32 iIndex = -1, INT32 iPart = 0);
		/**
		 * Get length of a packet in the file.
		 * @param		nPacket		Absolute Packet number to determine length for
		 * @return      UINT32		Packet length or 0 on failure.
		 */
	UINT32 GetPacketLength(UINT32 nPacket);
		/**
		 * Read a packet from the file.
		 * @param		nPacket		Absolute Packet number to determine length for
		 * @param		pLength		Returned length of packet (header+data)
		 * @return      void *		NCSMalloc()'d pointer to read packet (header+data).
		 */
	void *GetPacket(UINT32 nPacket, UINT32 *pLength);
		/**
		 * Get packet header for the specified absolute packet index.
		 * @param		nPacket		Absolute Packet number
		 * @return      class CNCSJPCPacket*		Packet header
		 */
	class CNCSJPCPacket *GetPacketHeader(UINT32 nPacket);
		/**
		 * Fnid the RCPL for the specified packet index
		 * @param		nPacket		Absolute Packet number
		 * @param		nTile		Tile index
		 * @param		nResolution Resolution number
		 * @param		nComponent	Component index
		 * @param		nPrecinctX	Precinct X index
		 * @param		nPrecinctY  Precinct Y index
		 * @param		nLayer		Quality Layer
		 * @return      bool 		true, or false on failure
		 */
	bool FindPacketRCPL(UINT32 nPacket, UINT16 &nTile, UINT8 &nResolution, UINT16 &nComponent, UINT32 &nPrecinctX, UINT32 &nPrecinctY, UINT16 &nLayer);
private:
};

#endif // !NCSJPC_H


text:
package org.apache.james.protocols.netty;

import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.timeout.IdleState;
import org.jboss.netty.handler.timeout.IdleStateHandler;
import org.jboss.netty.util.Timer;

/**
 * {@link IdleStateHandler} implementation which disconnect the {@link Channel} after a configured
 * idle timeout. Be aware that this handle is not thread safe so it can't be shared across pipelines
 *
 */
public class TimeoutHandler extends IdleStateHandler{

    public TimeoutHandler(Timer timer, int readerIdleTimeSeconds) {
        super(timer, readerIdleTimeSeconds, 0, 0);
    }

    @Override
    protected void channelIdle(ChannelHandlerContext ctx, IdleState state, long lastActivityTimeMillis) throws Exception {
        if (state.equals(IdleState.READER_IDLE)) {
            ctx.getChannel().close();
        }
    }

}


text:
#pragma comment(lib, "libeng.lib")
#pragma comment(lib, "libmx.lib")
#pragma comment(lib, "libmat.lib")
#pragma comment(lib, "libmex.lib")

#include <iostream>
#include <vector>
#include "common.h"

using namespace std;

namespace Matlab{
#include <engine.h>
}

namespace pc{

static Matlab::Engine* g_Ep;
extern AlgParam algparam;

void OpenMatlab(){
	if (!(g_Ep = Matlab::engOpen(nullptr))){
		std::cout << "engOpen failed" << std::endl;
		return;
	}
	Matlab::engSetVisible(g_Ep, algparam.showprocess);
	Matlab::engEvalString(g_Ep, "cd F:\\MATLAB\\calibration");
	Matlab::engEvalString(g_Ep, "addpath(\'D:\\Program Files\\MATLAB\\R2016a\\toolbox\\calib')");
	Matlab::engEvalString(g_Ep, "clear");
	Matlab::engEvalString(g_Ep, "load('Calib_Results_stereo.mat')");
}

void CloseMatlab(){
	Matlab::engClose(g_Ep);
}

vector<cv::Point3d> stereoTriangulation(vector<pair<Ipoint, Ipoint>>& matches){
	OpenMatlab();
	Matlab::mxArray* leftPoint = Matlab::mxCreateDoubleMatrix(2, matches.size(), Matlab::mxREAL);
	Matlab::mxArray* rightPoint = Matlab::mxCreateDoubleMatrix(2, matches.size(), Matlab::mxREAL);
	for (int i = 0; i < matches.size(); ++i){
		Matlab::mxGetPr(leftPoint)[2 * i] = matches[i].first.x;
		Matlab::mxGetPr(leftPoint)[2 * i + 1] = matches[i].first.y;
		Matlab::mxGetPr(rightPoint)[2 * i] = matches[i].second.x;
		Matlab::mxGetPr(rightPoint)[2 * i + 1] = matches[i].second.y;
	}
	Matlab::engPutVariable(g_Ep, "xL", leftPoint);
	Matlab::engPutVariable(g_Ep, "xR", rightPoint);
	Matlab::engEvalString(g_Ep, "[XL, XR] = stereo_triangulation(xL, xR, om, T, fc_left, cc_left, kc_left, alpha_c_left, fc_right, cc_right, kc_right, alpha_c_right); ");
	Matlab::mxArray* xL = Matlab::engGetVariable(g_Ep, "XL");
	Matlab::mxArray* xR = Matlab::engGetVariable(g_Ep, "XR");

	vector<cv::Point3d> pointsL(matches.size()), pointsR(matches.size());
	for (int i = 0; i < matches.size(); ++i){
		pointsL[i].x = Matlab::mxGetPr(xL)[3 * i + 0];
		pointsL[i].y = Matlab::mxGetPr(xL)[3 * i + 1];
		pointsL[i].z = Matlab::mxGetPr(xL)[3 * i + 2];
		pointsR[i].x = Matlab::mxGetPr(xR)[3 * i + 0];
		pointsR[i].y = Matlab::mxGetPr(xR)[3 * i + 1];
		pointsR[i].z = Matlab::mxGetPr(xR)[3 * i + 2];
	}

	Matlab::mxDestroyArray(leftPoint);
	Matlab::mxDestroyArray(rightPoint);
	CloseMatlab();
	return pointsL;
}

}


text:
package org.apache.camel.component.vertx.websocket;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.camel.AsyncCallback;
import org.apache.camel.CamelExecutionException;
import org.apache.camel.Exchange;

/**
 * Handles the result of one or more asynchronous WebSocket write operations
 */
class VertxWebsocketResultHandler {
    private final Exchange exchange;
    private final AsyncCallback callback;
    private final Set<String> connectionKeys;
    private final Map<String, Throwable> errors = new HashMap<>();
    private final Object lock = new Object();

    VertxWebsocketResultHandler(Exchange exchange, AsyncCallback callback, Set<String> connectionKeys) {
        this.exchange = exchange;
        this.callback = callback;
        this.connectionKeys = new HashSet<>(connectionKeys);
    }

    void onResult(String connectionKey) {
        synchronized (lock) {
            connectionKeys.remove(connectionKey);
            if (connectionKeys.isEmpty()) {
                onComplete();
            }
        }
    }

    void onError(String connectionKey, Throwable cause) {
        synchronized (lock) {
            errors.put(connectionKey, cause);
        }
    }

    private void onComplete() {
        if (!errors.isEmpty()) {
            if (errors.size() == 1) {
                final Map.Entry<String, Throwable> entry = errors.entrySet().iterator().next();
                final String msg = "Sending message to WebSocket peer for connection key " + entry.getKey() + " failed";
                exchange.setException(new CamelExecutionException(msg, exchange, entry.getValue()));
            } else {
                final StringBuilder msg = new StringBuilder("Sending message to multiple WebSocket peers failed:");
                for (Map.Entry<String, Throwable> entry : errors.entrySet()) {
                    msg.append("\n  connection key: ")
                            .append(entry.getKey())
                            .append(", cause: ")
                            .append(entry.getValue().getMessage());
                }
                exchange.setException(new CamelExecutionException(msg.toString(), exchange));
            }
        }
        callback.done(false);
    }
}


text:
.tundra .dijitToolbar {
	padding: 3px 0 1px 3px;
	border-bottom: 1px solid #ccc;
	background:#eaeaea url("images/titleBar.png") repeat-x top left;
}

.tundra .dijitToolbar .dijitButtonNode {
	background: none;
	margin: 0px !important;
	padding: 0px !important;
	border: none;
	font-size: 12px;
}

.tundra .dijitToolbar .dijitButton,
.tundra .dijitToolbar .dijitToggleButton,
.tundra .dijitToolbar .dijitDropDownButton {
	background: none;
	margin: 1px;
	padding: 0px;
	border: 1px solid transparent;
}

.tundra .dijitToolbar .dijitButtonChecked,
.tundra .dijitToolbar .dijitToggleButtonChecked {
	background-color:#d4dff2;
	border:1px solid #316ac5;
	margin: 1px !important;
	padding: 0px !important;
}

.tundra .dijitToolbar .dijitButtonCheckedHover,
.tundra .dijitToolbar .dijitToggleButtonCheckedHover
 {
	background-color:#abc1e5;
	border:1px solid #316ac5;
	margin: 1px !important;
	padding: 0px !important;
}

.tundra .dijitToolbar .dijitButtonHover,
.tundra .dijitToolbar .dijitToggleButtonHover,
.tundra .dijitToolbar .dijitDropDownButtonHover {
	/* TODO: change this from Hover to Selected so that button is still highlighted while drop down is being used */
	border: 1px solid #316ac5;
	background-color:#abc1e5;
}

.tundra .dijitToolbar label {
	padding: 3px 3px 0 6px;
}

.dj_ie .tundra .dijitToolbar .dijitComboButton .dijitButtonContentsFocused,
.dj_ie .tundra .dijitToolbar .dijitComboButton .dijitDownArrowButtonFocused,
.dj_ff2 .tundra.dijitToolbar .dijitComboButton .dijitButtonContentsFocused,
.dj_ff2 .tundra .dijitToolbar .dijitComboButton .dijitDownArrowButtonFocused {
	border: 1px black dotted !important;
}

/* IE6 specific rules */
.dj_ie6 .tundra .dijitToolbar .dijitButton,
.dj_ie6 .tundra .dijitToolbar .dijitToggleButton,
.dj_ie6 .tundra .dijitToolbar .dijitDropDownButton {
	/* workaround no transparent border support in IE6 */
	margin: 2px;
	padding: 0px 2px;
	border: 0px;
}

.dj_ie6 .tundra .dijitToolbar .dijitButtonChecked,
.dj_ie6 .tundra .dijitToolbar .dijitToggleButtonChecked,
.dj_ie6 .tundra .dijitToolbar .dijitDropDownButtonChecked {
	background-color:#c1d2ee;
	border:1px solid #316ac5;
	margin: 1px !important;
	padding: 0px 2px !important;
}

.dj_ie6 .tundra .dijitToolbar .dijitButtonCheckedHover,
.dj_ie6 .tundra .dijitToolbar .dijitToggleButtonCheckedHover,
.dj_ie6 .tundra .dijitToolbar .dijitDropDownButtonCheckedHover {
	background-color:#c1d2ee;
	border:1px solid #316ac5;
	margin: 1px !important;
	padding: 0px 2px !important;
}

.dj_ie6 .tundra .dijitToolbar .dijitButtonHover,
.dj_ie6 .tundra .dijitToolbar .dijitToggleButtonHover,
.dj_ie6 .tundra .dijitToolbar .dijitDropDownButtonHover  {
	background-color:#c1d2ee;
	border:1px solid #316ac5;
	margin: 1px !important;
	padding: 0px 2px !important;
}


text:
import Ember from 'ember';
import layout from '../templates/components/sockjs-chat';

export default Ember.Component.extend({

	sockjs: Ember.inject.service('sockjs'),
	   layout,
	   message:'',

	   init() {
		   this._super(...arguments);
		   this.get('sockjs').setupSockjs(this.attrs.url);
		   this.get('sockjs').on('messageReceived',this,function(message){
			   this.set('message',message);
			   this._actionHandler('receiveAction',message);
		   });
	   },
	   _actionHandler(actionName, ...args) {

		   if(this.attrs && Ember.typeOf(this.attrs[actionName]) === 'function'){
			   this.attrs[actionName](...args);
		   } else {
			   this.sendAction(actionName,...args);
		   }
	   },

	   actions: {
		   enter: function(info,username) {
			   this._actionHandler('sendAction',info,username);

		   }
	   }

});


text:
myportfolio
===========

A new version of my porfolio in HTML5


text:
module Atmosphere
  class DefaultPdp
    def initialize(current_user)
      @current_user = current_user
    end

    def can_start_in_production?(at)
      true
    end

    def can_start_in_development?(at)
      true
    end

    def can_manage?(obj)
      obj.user_id == current_user.id
    end

    def filter(ats, filter = nil)
      ats.where(visibility_for_filter(filter.to_s))
    end

    private

    attr_reader :current_user

    def visibility_for_filter(filter)
      case filter
      when 'production'  then { visible_to: [:all, :owner] }
      when 'manage'      then { user_id: current_user.id }
      else {}
      end
    end
  end
end


text:
class RHIBuffer;
namespace EReflectionProbeMode
{
	enum Type
	{
		ERealTime,
		EOneSidePreframe,
		Baked,
		Limit
	};
}
class ReflectionProbe
{
public:
	ReflectionProbe(glm::vec3 Pos = glm::vec3(0,0,0));
	~ReflectionProbe();
	FrameBuffer* CapturedTexture = nullptr;
	FrameBuffer* ConvolutionBuffer = nullptr;
	IntPoint GetDimentions()const;
	EReflectionProbeMode::Type ProbeMode = EReflectionProbeMode::Baked;
	bool NeedsCapture() const;
	void SetCaptured();
	bool GetNeedsDownSample() const;
	void SetNeedsDownSample(bool val);
	void BindViews(RHICommandList * List, int index, int slot);
	void UpdateReflectionParams(glm::vec3 lightPos);
	glm::vec3 GetPosition() const;
	void SetPosition(glm::vec3 val);
private:
	glm::vec3 Position = glm::vec3(0, 0, 0);

	IntPoint Dimentions = IntPoint(1024, 1024);
	int ConvolutionRes = 128;
	bool IsCaptured = false;
	bool NeedsDownSample = false;
	MVBuffer CubeMapViews[6];
	float zNear = 0.1f;
	float ZFar = 1000.0f;
	RHIBuffer* RelfectionProbeProjections = nullptr;
};


text:
#include "api/rtp_sender_interface.h"

namespace webrtc {

void RtpSenderInterface::SetFrameEncryptor(
    rtc::scoped_refptr<FrameEncryptorInterface> frame_encryptor) {}

rtc::scoped_refptr<FrameEncryptorInterface>
RtpSenderInterface::GetFrameEncryptor() const {
  return nullptr;
}

std::vector<RtpEncodingParameters> RtpSenderInterface::init_send_encodings()
    const {
  return {};
}

rtc::scoped_refptr<DtlsTransportInterface> RtpSenderInterface::dtls_transport()
    const {
  return nullptr;
}

void RtpSenderInterface::SetEncoderToPacketizerFrameTransformer(
    rtc::scoped_refptr<FrameTransformerInterface> frame_transformer) {}

}  // namespace webrtc


text:
import mock
from oslo_utils import uuidutils

from neutron.agent.l2.extensions import qos
from neutron.api.rpc.callbacks.consumer import registry
from neutron.api.rpc.callbacks import events
from neutron.api.rpc.callbacks import resources
from neutron.api.rpc.handlers import resources_rpc
from neutron import context
from neutron.plugins.ml2.drivers.openvswitch.agent.common import constants
from neutron.tests import base

TEST_POLICY = object()

class QosExtensionBaseTestCase(base.BaseTestCase):

    def setUp(self):
        super(QosExtensionBaseTestCase, self).setUp()
        self.qos_ext = qos.QosAgentExtension()
        self.context = context.get_admin_context()
        self.connection = mock.Mock()

        # Don't rely on used driver
        mock.patch(
            'neutron.manager.NeutronManager.load_class_for_provider',
            return_value=lambda: mock.Mock(spec=qos.QosAgentDriver)
        ).start()

class QosExtensionRpcTestCase(QosExtensionBaseTestCase):

    def setUp(self):
        super(QosExtensionRpcTestCase, self).setUp()
        self.qos_ext.initialize(
            self.connection, constants.EXTENSION_DRIVER_TYPE)

        self.pull_mock = mock.patch.object(
            self.qos_ext.resource_rpc, 'pull',
            return_value=TEST_POLICY).start()

    def _create_test_port_dict(self):
        return {'port_id': uuidutils.generate_uuid(),
                'qos_policy_id': uuidutils.generate_uuid()}

    def test_handle_port_with_no_policy(self):
        port = self._create_test_port_dict()
        del port['qos_policy_id']
        self.qos_ext._process_reset_port = mock.Mock()
        self.qos_ext.handle_port(self.context, port)
        self.qos_ext._process_reset_port.assert_called_with(port)

    def test_handle_unknown_port(self):
        port = self._create_test_port_dict()
        qos_policy_id = port['qos_policy_id']
        port_id = port['port_id']
        self.qos_ext.handle_port(self.context, port)
        # we make sure the underlaying qos driver is called with the
        # right parameters
        self.qos_ext.qos_driver.create.assert_called_once_with(
            port, TEST_POLICY)
        self.assertEqual(port,
            self.qos_ext.qos_policy_ports[qos_policy_id][port_id])
        self.assertTrue(port_id in self.qos_ext.known_ports)

    def test_handle_known_port(self):
        port_obj1 = self._create_test_port_dict()
        port_obj2 = dict(port_obj1)
        self.qos_ext.handle_port(self.context, port_obj1)
        self.qos_ext.qos_driver.reset_mock()
        self.qos_ext.handle_port(self.context, port_obj2)
        self.assertFalse(self.qos_ext.qos_driver.create.called)

    def test_handle_known_port_change_policy_id(self):
        port = self._create_test_port_dict()
        self.qos_ext.handle_port(self.context, port)
        self.qos_ext.resource_rpc.pull.reset_mock()
        port['qos_policy_id'] = uuidutils.generate_uuid()
        self.qos_ext.handle_port(self.context, port)
        self.pull_mock.assert_called_once_with(
             self.context, resources.QOS_POLICY,
             port['qos_policy_id'])
        #TODO(QoS): handle qos_driver.update call check when
        #           we do that

    def test_delete_known_port(self):
        port = self._create_test_port_dict()
        port_id = port['port_id']
        self.qos_ext.handle_port(self.context, port)
        self.qos_ext.qos_driver.reset_mock()
        self.qos_ext.delete_port(self.context, port)
        self.qos_ext.qos_driver.delete.assert_called_with(port, None)
        self.assertNotIn(port_id, self.qos_ext.known_ports)

    def test_delete_unknown_port(self):
        port = self._create_test_port_dict()
        port_id = port['port_id']
        self.qos_ext.delete_port(self.context, port)
        self.assertFalse(self.qos_ext.qos_driver.delete.called)
        self.assertNotIn(port_id, self.qos_ext.known_ports)

    def test__handle_notification_ignores_all_event_types_except_updated(self):
        with mock.patch.object(
            self.qos_ext, '_process_update_policy') as update_mock:

            for event_type in set(events.VALID) - {events.UPDATED}:
                self.qos_ext._handle_notification(object(), event_type)
                self.assertFalse(update_mock.called)

    def test__handle_notification_passes_update_events(self):
        with mock.patch.object(
            self.qos_ext, '_process_update_policy') as update_mock:

            policy = mock.Mock()
            self.qos_ext._handle_notification(policy, events.UPDATED)
            update_mock.assert_called_with(policy)

    def test__process_update_policy(self):
        port1 = self._create_test_port_dict()
        port2 = self._create_test_port_dict()
        self.qos_ext.qos_policy_ports = {
            port1['qos_policy_id']: {port1['port_id']: port1},
            port2['qos_policy_id']: {port2['port_id']: port2},
        }
        policy = mock.Mock()
        policy.id = port1['qos_policy_id']
        self.qos_ext._process_update_policy(policy)
        self.qos_ext.qos_driver.update.assert_called_with(port1, policy)

        self.qos_ext.qos_driver.update.reset_mock()
        policy.id = port2['qos_policy_id']
        self.qos_ext._process_update_policy(policy)
        self.qos_ext.qos_driver.update.assert_called_with(port2, policy)

    def test__process_reset_port(self):
        port1 = self._create_test_port_dict()
        port2 = self._create_test_port_dict()
        port1_id = port1['port_id']
        port2_id = port2['port_id']
        self.qos_ext.qos_policy_ports = {
            port1['qos_policy_id']: {port1_id: port1},
            port2['qos_policy_id']: {port2_id: port2},
        }
        self.qos_ext.known_ports = {port1_id, port2_id}

        self.qos_ext._process_reset_port(port1)
        self.qos_ext.qos_driver.delete.assert_called_with(port1, None)
        self.assertNotIn(port1_id, self.qos_ext.known_ports)
        self.assertIn(port2_id, self.qos_ext.known_ports)

        self.qos_ext.qos_driver.delete.reset_mock()
        self.qos_ext._process_reset_port(port2)
        self.qos_ext.qos_driver.delete.assert_called_with(port2, None)
        self.assertNotIn(port2_id, self.qos_ext.known_ports)

class QosExtensionInitializeTestCase(QosExtensionBaseTestCase):

    @mock.patch.object(registry, 'subscribe')
    @mock.patch.object(resources_rpc, 'ResourcesPushRpcCallback')
    def test_initialize_subscribed_to_rpc(self, rpc_mock, subscribe_mock):
        self.qos_ext.initialize(
            self.connection, constants.EXTENSION_DRIVER_TYPE)
        self.connection.create_consumer.assert_has_calls(
            [mock.call(
                 resources_rpc.resource_type_versioned_topic(resource_type),
                 [rpc_mock()],
                 fanout=True)
             for resource_type in self.qos_ext.SUPPORTED_RESOURCES]
        )
        subscribe_mock.assert_called_with(mock.ANY, resources.QOS_POLICY)


text:
module Random where
import System.Random
import Cards

-- erzeugt einen Zufallsgenerator aus einem Int
makeGenerator :: Int -> StdGen
makeGenerator x = mkStdGen x

-- Erzeuge eine Zufallszahl zwischen 0 und x, sowie einen neuen Zufallsgenerator
-- Es muss ein RandomGenerator gen sowie die Obergrenze x uebergeben werden
randomizer :: StdGen -> Int -> (Int, StdGen)
randomizer gen x = randomR (0,x) gen

--Gibt eine Zufallszahl zwischen l und r zuruck
randomBetrag :: StdGen -> Int -> Int -> Int
randomBetrag gen l r = fst $ randomR (l,r) gen

-- Gibt die n.te Karte des übergebenden Kartenstapels (beliebiger Groesse) zurueck
getCard :: [Card] -> Int -> Card
getCard stapel n = stapel !! n

-- Entfernt ein Element aus einer Liste und gibt die Liste ohne das Element zurueck
removeElem :: Int -> [a] -> [a]
removeElem n xs =
  let (ys,zs) = splitAt n xs
  in ys ++ (tail zs)

-- Mische das Deck und gibt das gemischte Deck zurueck
-- Nimmt eine zufaellige Karte aus dem zu mischendem Stapel und tut sie in einen neuen Stapel
-- solange bis der alte/zu mischende Stapel leer ist
shuffle :: [Card] -> StdGen -> [Card] -> [Card]
shuffle [] gen newDeck = newDeck
shuffle oldDeck gen newDeck = shuffle (removeElem (randomX oldDeck gen) oldDeck) (newGenX oldDeck gen)
  ((getCard oldDeck (randomX oldDeck gen)) : newDeck)
  where randomX :: [Card] -> StdGen -> Int -- Gibt einen random Int zurueck
        randomX oldDeck gen = fst $ randomizer gen $ (length oldDeck) -1
        newGenX :: [Card] -> StdGen -> StdGen -- gibt einen neuen Zufallsgenerator zurueck
        newGenX oldDeck gen = snd $ randomizer gen $ (length oldDeck) -1


text:
	MySQL connections.

	<?php
	if( isset($_POST['submit']) ) {
		try {
		  $mysql_host     = $_POST['host'];//MySQL Host.
          $mysql_username = $_POST['username'];//MySQL Username
          $mysql_password = (!$_POST['password'])? '' : $_POST['password'];//MySQL Password
          $mysql_database = $_POST['database'];//MySQL Database
          $mysql_prefix   = $_POST['prefix'];//MySQL Prefix.

          $request  = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
          $site_url = explode('/install/', $request);
          $site_url = $site_url[0];

          if(!$mysql_host or !$mysql_username or !$mysql_password or !$mysql_database or !$mysql_prefix){//Check if all values are there.
              throw new Exception('All fields are required!');//If not, error.
          }elseif(!$conn = @mysqli_connect($mysql_host, $mysql_username, $mysql_password)){//Checks if MySQL connection could be established.
              throw new Exception('MySQL Server connection could not be established.');//If not, error.
          }elseif(!@mysqli_select_db($conn, $mysql_database)){//Checks for connection to database.
              throw new Exception('MySQL Database connection could not be established.');//If not, error.
          }else{

              $time = time();

              /*
               * Placing correct values into configuration file.
               */
              $config = file_get_contents('../config.php');
              $config = str_replace('%mysql_host%', $mysql_host, $config);
              $config = str_replace('%mysql_username%', $mysql_username, $config);
              $config = str_replace('%mysql_password%', $mysql_password, $config);
              $config = str_replace('%mysql_database%', $mysql_database, $config);
              $config = str_replace('%mysql_prefix%', $mysql_prefix, $config);
              $config = str_replace('%blog_url%', $site_url, $config);
              //file_put_contents('../applications/config.php', $config);

              //Write contents into the config.php file in the applications directory.
              $fh = fopen('../../applications/config.php', 'w');
              fwrite($fh, $config);
              fclose($fh);

              $MYSQL = new mysqli($mysql_host, $mysql_username, $mysql_password, $mysql_database);
              $MYSQL->query("CREATE TABLE IF NOT EXISTS `" . $mysql_prefix . "blog` (`id` int(11) NOT NULL AUTO_INCREMENT,`blog_name` varchar(255) NOT NULL,`blog_theme` varchar(255) NOT NULL,`blog_language` varchar(255) NOT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
");
              $MYSQL->query("CREATE TABLE IF NOT EXISTS `" . $mysql_prefix . "blog_api` (`id` int(11) NOT NULL AUTO_INCREMENT,`user_name` varchar(255) NOT NULL,`user_email` varchar(255) NOT NULL,`public_key` varchar(255) NOT NULL,`private_key` varchar(255) NOT NULL,`is_admin` int(11) NOT NULL DEFAULT '0',`permissions` text NOT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
");
              $MYSQL->query("CREATE TABLE IF NOT EXISTS `" . $mysql_prefix . "blog_posts` (`id` int(11) NOT NULL AUTO_INCREMENT,`post_id` varchar(255) NOT NULL,`post_url` varchar(255) NOT NULL,`post_title` varchar(255) NOT NULL,`post_slug` varchar(255) NOT NULL,`post_content` text NOT NULL,`post_tags` varchar(255) NOT NULL,`time_posted` int(11) NOT NULL,`posted_by` int(11) NOT NULL,`post_type` int(11) NOT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
");
              $MYSQL->query("INSERT INTO `" . $mysql_prefix . "blog_posts` (`id`, `post_id`, `post_url`, `post_title`, `post_slug`, `post_content`, `post_tags`, `time_posted`, `posted_by`, `post_type`) VALUES (1, 'firstpost123', '', 'First post!', 'first_post', 'This is the post created during installation. You can delete or edit this via the API.', 'first,post', " . $time . ", 1, 1);
");

              echo '
Success! Continue.
';
          }

      } catch (Exception $e) {
          echo '
'.$e->getMessage().'
';
      }
    }
  ?>
  <form action="javascript:ajaxForm('pages/mysql.php')" class="ajaxForm" method="POST">
    <input type="text" name="host" class="form-control input-lg" placeholder="MySQL Host" />
    <input type="text" name="username" class="form-control input-lg" placeholder="MySQL Username" />
    <input type="password" name="password" class="form-control input-lg" placeholder="MySQL Password" />
    <input type="text" name="database" class="form-control input-lg" placeholder="MySQL Database" />
    <input type="text" name="prefix" class="form-control input-lg" placeholder="MySQL Prefix" value="r_" />

    <input type="hidden" name="submit" value="" />
    <input type="submit" name="submit" class="btn btn-primary btn-lg btn-block" value="Test Connection and Continue" />
  </form>