text:
<!DOCTYPE html>

		<title>three.js webaudio - orientation</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
		<link type="text/css" rel="stylesheet" href="main.css">

	<audio loop id="music" preload="auto" style="display: none">
		<source src="sounds/376737_Skullbeatz___Bad_Cat_Maste.ogg" type="audio/ogg">
		<source src="sounds/376737_Skullbeatz___Bad_Cat_Maste.mp3" type="audio/mpeg">
	</audio>

			<button id="startButton">Click to Play</button>

Audio playback requires user interaction.

		three.js webaudio - orientation

		music by skullbeatz


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>MTB CAT1 Peripheral driver library: Enumerated Types</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen_style.css" rel="stylesheet" type="text/css" />

MTB CAT1 Peripheral driver library

Enumerations

Enumerated Types
SysClk       (System Clock) » Peripherals Clock Dividers

General Description

Enumerations

enum  	en_clk_dst_t
 	The enumerated type that represents a particular peripheral, used when assigning a peripheral to a peripheral clock divider. These values are device-specific. Refer to a device-specific header file, e.g. <PDL_DIR>/devices/include/psoc6_01_config.h for the specific enumerations for each peripheral for that device.

enum  	cy_en_peri_grp_sl_ctl_num_t {

  CY_SYSCLK_PERI_GROUP_SL_CTL = 0U,

  CY_SYSCLK_PERI_GROUP_SL_CTL2 = 1U,

  CY_SYSCLK_PERI_GROUP_SL_CTL3 = 2U

 }
 	Slave control Register Numbers Used with functions Cy_SysClk_ClkHfSetDivider and Cy_SysClk_ClkHfGetDivider.  More...

enum  	cy_en_divider_types_t {

  CY_SYSCLK_DIV_8_BIT = 0U,

  CY_SYSCLK_DIV_16_BIT = 1U,

  CY_SYSCLK_DIV_16_5_BIT = 2U,

  CY_SYSCLK_DIV_24_5_BIT = 3U

 }
 	Programmable clock divider types.  More...

Enumeration Type Documentation

◆ cy_en_peri_grp_sl_ctl_num_t

          enum cy_en_peri_grp_sl_ctl_num_t

Slave control Register Numbers Used with functions Cy_SysClk_ClkHfSetDivider and Cy_SysClk_ClkHfGetDivider.

Enumerator

CY_SYSCLK_PERI_GROUP_SL_CTL
Selects SL_CTL.

CY_SYSCLK_PERI_GROUP_SL_CTL2
Selects SL_CTL2.

CY_SYSCLK_PERI_GROUP_SL_CTL3
Selects SL_CTL3.

◆ cy_en_divider_types_t

          enum cy_en_divider_types_t

Programmable clock divider types.

Enumerator

CY_SYSCLK_DIV_8_BIT
Divider Type is an 8 bit divider.

CY_SYSCLK_DIV_16_BIT
Divider Type is a 16 bit divider.

CY_SYSCLK_DIV_16_5_BIT
Divider Type is a 16.5 bit fractional divider.

CY_SYSCLK_DIV_24_5_BIT
Divider Type is a 24.5 bit fractional divider.

redpajama_set_name: RedPajamaGithub


text:
from django.conf.urls import patterns, include, url

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('spidergraphs.views',
    url(r'^$','index'),
    url(r'^(?P<institution>[a-z_]+)$','institution'),
    url(r'^(?P<institution>[a-z_]+)/(?P<program_id>[\d]+)$','program'),
    url(r'^(?P<institution>[a-z_]+)/(?P<program_id>[\d]+)/(?P<course_id>[\d]+)$','course'),
    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
)
urlpatterns += patterns('',
    # Uncomment the next line to enable the admin:
    url(r'^admin/', include(admin.site.urls)),
)


text:
typedef struct
{
    int d, m, a;
} t_fecha;

int valida_fecha(const t_fecha *);
int cant_dias_mes(int, int);
void nextDateTo(t_fecha *, t_fecha *);
void dateAdd(t_fecha *, int, t_fecha *);

int fechaADiasDelAnio(const t_fecha *);
int fechaADias(const t_fecha *);
void diasAFecha(int, t_fecha *);
void sumarDiasAFecha(const t_fecha *, int, t_fecha *);
void fechaSiguiente(const t_fecha *, t_fecha *);
int diffFechas(const t_fecha *, const t_fecha *);
int getDiaSemana(const t_fecha *);

#endif // FECHA_H_INCLUDED


text:
<?php

namespace Forge;

class DB
{
	/**
	 * Create a new Database_Query of the given type.
	 *
	 *     // Create a new SELECT query
	 *     $query = DB::query(Database::SELECT, 'SELECT * FROM users');
	 *
	 *     // Create a new DELETE query
	 *     $query = DB::query(Database::DELETE, 'DELETE FROM users WHERE id = 5');
	 *
	 * Specifying the type changes the returned result. When using
	 * Database::SELECT, a Database_Query_Result will be returned.
	 * Database::INSERT queries will return the insert id and number of rows.
	 * For all other queries, the number of affected rows is returned.
	 *
	 * @param   integer  $type  type: Database::SELECT, Database::UPDATE, etc
	 * @param   string   $sql   SQL statement
	 * @return  Database_Query
	 */
	public static function query( $type, $sql )
	{
		return new Database_Query( $type, $sql );
	}

	/**
	 * Create a new Database_Query_Builder_Select. Each argument will be
	 * treated as a column. To generate a foo AS bar alias, use an array.
	 *
	 *     // SELECT id, username
	 *     $query = DB::select('id', 'username');
	 *
	 *     // SELECT id AS user_id
	 *     $query = DB::select(array('id', 'user_id'));
	 *
	 * @param   mixed   $columns  column name or array($column, $alias) or object
	 * @return  Database_Query_Builder_Select
	 */
	public static function select( $columns = NULL )
	{
		return new Database_Query_Builder_Select( func_get_args() );
	}

	/**
	 * Create a new Database_Query_Builder_Select from an array of columns.
	 *
	 *     // SELECT id, username
	 *     $query = DB::select_array( array( 'id', 'username' ) );
	 *
	 * @param   array   $columns  columns to select
	 * @return  Database_Query_Builder_Select
	 */
	public static function select_array( array $columns = NULL )
	{
		return new Database_Query_Builder_Select( $columns );
	}

	/**
	 * Create a new Database_Query_Builder_Insert.
	 *
	 *     // INSERT INTO users (id, username)
	 *     $query = DB::insert('users', array('id', 'username'));
	 *
	 * @param   string  $table    table to insert into
	 * @param   array   $columns  list of column names or array($column, $alias) or object
	 * @return  Database_Query_Builder_Insert
	 */
	public static function insert( $table = NULL, array $columns = NULL )
	{
		return new Database_Query_Builder_Insert( $table, $columns );
	}

	/**
	 * Create a new Database_Query_Builder_Update.
	 *
	 *     // UPDATE users
	 *     $query = DB::update('users');
	 *
	 * @param   string  $table  table to update
	 * @return  Database_Query_Builder_Update
	 */
	public static function update( $table = NULL )
	{
		return new Database_Query_Builder_Update( $table );
	}

	/**
	 * Create a new Database_Query_Builder_Delete.
	 *
	 *     // DELETE FROM users
	 *     $query = DB::delete('users');
	 *
	 * @param   string  $table  table to delete from
	 * @return  Database_Query_Builder_Delete
	 */
	public static function delete( $table = NULL )
	{
		return new Database_Query_Builder_Delete( $table );
	}

	/**
	 * Create a new Database_Expression which is not escaped. An expression
	 * is the only way to use SQL functions within query builders.
	 *
	 *     $expression = DB::expr('COUNT(users.id)');
	 *     $query = DB::update('users')->set(array('login_count' => DB::expr('login_count + 1')))->where('id', '=', $id);
	 *     $users = ORM::factory('user')->where(DB::expr("BINARY `hash`"), '=', $hash)->find();
	 *
	 * @param   string  $string  expression
	 * @param   array   parameters
	 * @return  Database_Expression
	 */
	public static function expr( $string, $parameters = array() )
	{
		return new Database_Expression( $string, $parameters );
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.cyrilleguipie.rolldice"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-sdk tools:node="replace" />
    <uses-feature android:name="android.hardware.type.watch" />
    <uses-permission android:name="android.permission.VIBRATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/icon"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.DeviceDefault" >

        <meta-data android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <activity
            android:name=".RollWearActivity"
            android:label="@string/app_name" >
        </activity>
        <activity
            android:name=".MenuActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name=".AboutActivity">
        </activity>
        <service android:name=".DeviceDataListenerService">
            <intent-filter>
                <action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
            </intent-filter>
        </service>
    </application>

</manifest>


text:
import json
import functools
import os
import sys

import pytest
from flask import Flask

# Set up the path to import from `server`.
root = os.path.join(os.path.dirname(__file__))
package = os.path.join(root, '..')
sys.path.insert(0, os.path.abspath(package))

from server.app import create_app
from server.api import create_searcher

class TestResponseClass(Flask.response_class):

    @property
    def json(self):
        return json.loads(self.data)

Flask.response_class = TestResponseClass

def humanize_werkzeug_client(client_method):
    """Wraps a `werkzeug` client method (the client provided by `Flask`) to make
    it easier to use in tests.

    """
    @functools.wraps(client_method)
    def wrapper(url, **kwargs):
        # Always set the content type to `application/json`.
        kwargs.setdefault('headers', {}).update({
            'content-type': 'application/json'
        })

        # If data is present then make sure it is json encoded.
        if 'data' in kwargs:
            data = kwargs['data']
            if isinstance(data, dict):
                kwargs['data'] = json.dumps(data)

        kwargs['buffered'] = True

        return client_method(url, **kwargs)

    return wrapper

@pytest.fixture(scope='session', autouse=True)
def app(request):
    app = create_app({
        'TESTING': True,
        'INDEX_NAME': ''
    })

    # Establish an application context before running the tests.
    ctx = app.app_context()
    ctx.push()

    def teardown():
        ctx.pop()

    request.addfinalizer(teardown)
    return app

@pytest.fixture(scope='function')
def client(app, request):
    return app.test_client()

@pytest.fixture(scope='function')
def get(client):
    return humanize_werkzeug_client(client.get)


text:
package com.plattebasintimelapse.phocalstream.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.plattebasintimelapse.phocalstream.R;
import com.plattebasintimelapse.phocalstream.managers.AuthenticationManager;

/**
 * A login screen that offers login via email/password.
 */
public class LoginActivity extends FragmentActivity {

    private CallbackManager callbackManager;
    private ProgressBar progressBar;
    private AuthenticationManager authenticationManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FacebookSdk.sdkInitialize(getApplicationContext());

        setContentView(R.layout.activity_login);
        progressBar = (ProgressBar) findViewById(R.id.login_progress);

        authenticationManager = new AuthenticationManager(LoginActivity.this);

        AccessToken accessToken = AccessToken.getCurrentAccessToken();
        if (accessToken != null) {
            authenticationManager.login(progressBar, accessToken.getToken());
        }

        callbackManager = CallbackManager.Factory.create();
        LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
        loginButton.setReadPermissions("public_profile", "email", "user_friends");
        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                authenticationManager.login(progressBar, loginResult.getAccessToken().getToken());
            }

            @Override
            public void onCancel() {
                Toast.makeText(getApplicationContext(), "Facebook login cancelled.", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(FacebookException exception) {
                Toast.makeText(getApplicationContext(), "Facebook Error: " + exception.toString(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void cameraSites(View view) {
        startActivity(new Intent(LoginActivity.this, CameraSitesActivity.class));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }
}


text:
class ApplicationController < ActionController::Base
  before_action :authenticate_user!
  protect_from_forgery with: :exception

  def after_sign_out_path_for(resource)
    root_path
  end

  def after_sign_in_path_for(resource)
    user_channels_url
  end
end


text:
using System;
using System.ComponentModel;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Linq;
using STEP;

namespace IFC
{
    /// <summary>
    /// http://www.buildingsmart-tech.org/ifc/IFC4/final/html/link/ifcsimplepropertytemplatetypeenum.htm
    /// </summary>
    public enum IfcSimplePropertyTemplateTypeEnum {P_SINGLEVALUE,P_ENUMERATEDVALUE,P_BOUNDEDVALUE,P_LISTVALUE,P_TABLEVALUE,P_REFERENCEVALUE,Q_LENGTH,Q_AREA,Q_VOLUME,Q_COUNT,Q_WEIGHT,Q_TIME}
}


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

<TITLE>
Uses of Class org.apache.fop.fonts.truetype.FontFileReader (Apache FOP 2.1 API)
</TITLE>

<META NAME="date" CONTENT="2016-01-07">

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

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

fop 2.1

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.apache.fop.fonts.truetype.FontFileReader

Packages that use FontFileReader

org.apache.fop.complexscripts.fonts

org.apache.fop.fonts.cff

org.apache.fop.fonts.truetype
Classes for TrueType fonts.

org.apache.fop.render.pcl.fonts

org.apache.fop.render.pcl.fonts.truetype

Uses of FontFileReader in org.apache.fop.complexscripts.fonts

Constructors in org.apache.fop.complexscripts.fonts with parameters of type FontFileReader

OTFAdvancedTypographicTableReader(OpenFont otf,
                                  FontFileReader in)

          Construct an OTFAdvancedTypographicTableReader instance.

Uses of FontFileReader in org.apache.fop.fonts.cff

Constructors in org.apache.fop.fonts.cff with parameters of type FontFileReader

CFFDataReader(FontFileReader fontFile)

          Constructor for the CFF data reader which accepts a FontFileReader object
 which points to the original font file as an argument.

Uses of FontFileReader in org.apache.fop.fonts.truetype

Fields in org.apache.fop.fonts.truetype declared as FontFileReader

protected  FontFileReader
OpenFont.fontFile

          The FontFileReader used to read this TrueType font.

Methods in org.apache.fop.fonts.truetype with parameters of type FontFileReader

protected  boolean
TTFSubSetFile.createCvt(FontFileReader in)

          Copy the cvt table as is from original font to subset font

protected  boolean
TTFSubSetFile.createFpgm(FontFileReader in)

          Copy the fpgm table as is from original font to subset font

protected  void
TTFSubSetFile.createHead(FontFileReader in)

          Copy the head table as is from original font to subset font
 and set indexToLocaFormat to long and set
 checkSumAdjustment to 0, store offset to checkSumAdjustment
 in checkSumAdjustmentOffset

protected  void
TTFSubSetFile.createHhea(FontFileReader in,
           int size)

          Copy the hhea table as is from original font to subset font
 and fill in size of hmtx table

protected  void
TTFSubSetFile.createHmtx(FontFileReader in,
           java.util.Map<java.lang.Integer,java.lang.Integer> glyphs)

          Create the hmtx table by copying metrics from original
 font to subset font.

protected  void
TTFSubSetFile.createMaxp(FontFileReader in,
           int size)

          Copy the maxp table as is from original font to subset font
 and set num glyphs to size

protected  boolean
TTFSubSetFile.createName(FontFileReader in)

          Copy the name table as is from the original.

protected  boolean
TTFSubSetFile.createOS2(FontFileReader in)

          Copy the OS/2 table as is from the original.

protected  void
TTFSubSetFile.createPost(FontFileReader in)

protected  boolean
TTFSubSetFile.createPrep(FontFileReader in)

          Copy the prep table as is from original font to subset font

static byte[]
OTFFile.getCFFData(FontFileReader fontFile)

          Reads the CFFData from a given font file

 java.util.List<java.lang.String>
OpenFont.getTTCnames(FontFileReader in)

          Return TTC font names

protected  void
OpenFont.handleCharacterSpacing(FontFileReader in)

protected  void
OTFFile.initializeFont(FontFileReader in)

protected abstract  void
OpenFont.initializeFont(FontFileReader in)

protected  void
TTFFile.initializeFont(FontFileReader in)

 java.lang.String
OFDirTabEntry.read(FontFileReader in)

          Read Dir Tab.

 void
OpenFont.readFont(FontFileReader in,
         java.lang.String header)

          Reads the font using a FontFileReader.

 void
OpenFont.readFont(FontFileReader in,
         java.lang.String header,
         MultiByteFont mbfont)

          Reads a font.

 boolean
OpenFont.readFont(FontFileReader in,
         java.lang.String header,
         java.lang.String name)

          Read the font data.

 void
TTFSubSetFile.readFont(FontFileReader in,
         java.lang.String name,
         java.lang.String header,
         java.util.Map<java.lang.Integer,java.lang.Integer> glyphs)

          Reads a font and creates a subset of the font.

 void
OTFSubSetFile.readFont(FontFileReader in,
         java.lang.String embeddedName,
         java.lang.String header,
         MultiByteFont mbFont)

static java.lang.String
OFFontLoader.readHeader(FontFileReader fontFile)

protected  void
TTFSubSetFile.scanGlyphs(FontFileReader in,
           java.util.Map<java.lang.Integer,java.lang.Integer> subsetGlyphs)

 boolean
OpenFont.seekTab(FontFileReader in,
        OFTableName tableName,
        long offset)

          Position inputstream to position indicated
 in the dirtab offset + offset

Constructors in org.apache.fop.fonts.truetype with parameters of type FontFileReader

GlyfTable(FontFileReader in,
          OFMtxEntry[] metrics,
          OFDirTabEntry dirTableEntry,
          java.util.Map<java.lang.Integer,java.lang.Integer> glyphs)

Uses of FontFileReader in org.apache.fop.render.pcl.fonts

Fields in org.apache.fop.render.pcl.fonts declared as FontFileReader

protected  FontFileReader
PCLCharacterWriter.fontReader

Methods in org.apache.fop.render.pcl.fonts that return FontFileReader

abstract  FontFileReader
PCLFontReader.getFontFileReader()

 FontFileReader
PCLSoftFont.getReader()

Methods in org.apache.fop.render.pcl.fonts with parameters of type FontFileReader

 void
PCLSoftFont.setReader(FontFileReader reader)

Uses of FontFileReader in org.apache.fop.render.pcl.fonts.truetype

Fields in org.apache.fop.render.pcl.fonts.truetype declared as FontFileReader

protected  FontFileReader
PCLTTFFontReader.reader

protected  FontFileReader
PCLTTFTable.reader

Methods in org.apache.fop.render.pcl.fonts.truetype that return FontFileReader

 FontFileReader
PCLTTFFontReader.getFontFileReader()

Methods in org.apache.fop.render.pcl.fonts.truetype with parameters of type FontFileReader

static PCLTTFTableFactory
PCLTTFTableFactory.getInstance(FontFileReader reader)

protected  void
PCLTTFTable.skipByte(FontFileReader reader,
         int skips)

protected  void
PCLTTFTable.skipLong(FontFileReader reader,
         int skips)

protected  void
PCLTTFTable.skipShort(FontFileReader reader,
          int skips)

Constructors in org.apache.fop.render.pcl.fonts.truetype with parameters of type FontFileReader

PCLTTFOS2FontTable(FontFileReader in)

PCLTTFPCLTFontTable(FontFileReader in)

PCLTTFPOSTFontTable(FontFileReader in)

PCLTTFTable(FontFileReader reader)

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

fop 2.1

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright 1999-2016 The Apache Software Foundation. All Rights Reserved.


text:
// Handler
//
// Douglas Thrift
//
// Handler.cs

using System;
using System.Collections.Generic;

public interface Handler
{
    IEnumerable<string> Options
    {
        get;
    }
    IEnumerable<string> Usages
    {
        get;
    }
    IEnumerable<Setting> Settings
    {
        get;
    }
    Setting Setting
    {
        get;
    }

    MatchOption DoMatch(string arg);
    bool Find();
    void Execute(Uri uri, string user, string password);
}


text: A server that serves up nodes for a gossip protocol, built for BYU CS 462


text:
<?php

namespace Cart\Tests;

use Cart\Cart;
use Cart\Item;
use Cart\Tests\Resources\Session;

class CartTest extends \PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
        parent::setUp();
    }

    /** @test */
    public function createCart()
    {
        $cart = new Cart();

        // Is a Cart
        $this->assertInstanceOf('Cart\Cart', $cart);

        // Check Properties
        foreach (['id', 'items', 'session', 'currency'] as $property) {
            $this->assertObjectHasAttribute($property, $cart);
        }

        // Check methods
        foreach (['has', 'items', 'add', 'update', 'session'] as $method) {
            $this->assertTrue(
                method_exists($cart, $method),
                'Cart does not have method "' . $method . '"'
            );
        }

        // Check constants
        foreach (['DEFAULT_ID_KEY'] as $constant) {
            $cart = new \ReflectionClass(Cart::class);
            $this->assertArrayHasKey($constant, $cart->getConstants());
        }
    }

    /** @test */
    public function createCartWithCustomId()
    {
        $id = uniqid();
        $cart = new Cart($id);

        $this->assertEquals($cart->id(), $id);
    }

    /** @test */
    public function changeCartId()
    {
        $cart = new Cart();
        $id = uniqid();

        $this->assertNotEquals($cart->id(), $id);

        $cart->id($id);

        $this->assertEquals($cart->id(), $id);
    }

    /** @test */
    public function setCardCurrency()
    {
        $cart = new Cart();

        $cart->currency('EUR');

        $this->assertEquals(get_class($cart->currency()), 'Money\Currency');
    }

    /** @test */
    public function getStoredCard()
    {
        $id = uniqid();
        $currency = 'EUR';
        $cart = new Cart($id);

        $cart->currency($currency);

        unset($cart);

        $cart2 = new Cart($id);

        $this->assertEquals(get_class($cart2->currency()), 'Money\Currency');
        $this->assertEquals($cart2->currency(), $currency);
    }

    /** @test */
    public function changeSessionSystem()
    {
        $cart = new Cart();

        // The default session class is set
        $this->assertInstanceOf('Cart\Session', $cart->session());

        $cart->session(new Session());

        $this->assertInstanceOf('\Cart\Tests\Resources\Session', $cart->session());
    }

    /** @test */
    public function cartPropertiesReturnsAnArray()
    {
        $cart = new Cart();

        $this->assertTrue(
            is_array($cart->properties()),
            'Cart properties does not return an array'
        );
    }

    /** @test */
    public function addItem()
    {
        $cart = new Cart();
        $id = uniqid();
        $item = new Item($id);

        $this->assertEquals(count($cart->items()), 0);

        $cart->add($item);

        $this->assertEquals(count($cart->items()), 1);

        /** @noinspection PhpUndefinedMethodInspection */
        $this->assertEquals($cart->items()[0]->id(), $id);
    }

    /** @test */
    public function addMultipleItems()
    {
        $cart = new Cart();
        $id0 = uniqid();
        $id1 = uniqid();
        $id2 = uniqid();
        $items = [
            new Item($id0),
            new Item($id1),
            new Item($id2),
        ];

        $this->assertEquals(count($cart->items()), 0);

        $cart->add($items);

        $cartItems = $cart->items();

        $this->assertEquals(count($cartItems), 3);
        /** @noinspection PhpUndefinedMethodInspection */
        $this->assertEquals($cartItems[0]->id(), $id0);
        /** @noinspection PhpUndefinedMethodInspection */
        $this->assertEquals($cartItems[1]->id(), $id1);
        /** @noinspection PhpUndefinedMethodInspection */
        $this->assertEquals($cartItems[2]->id(), $id2);
    }

    /** @test */
    public function addItemsWithFluent()
    {
        $cart = new Cart();
        $id0 = uniqid();
        $id1 = uniqid();
        $id2 = uniqid();

        $cart->add(new Item($id0))->add(new Item($id1))->add(new Item($id2));

        $this->assertEquals(count($cart->items()), 3);
    }

    /** @test */
    public function updateCartItem()
    {
        $cart = new Cart();
        $id = uniqid();
        $item = new Item($id);
        $quantity = rand(1, 100);

        $cart->add($item);
        $item->quantity($quantity);
        $cart->update($item);

        $this->assertEquals(count($cart->items()), 1);
        /** @noinspection PhpUndefinedMethodInspection */
        $this->assertTrue($cart->item($id)->quantity() === $quantity);
    }

    /** @test */
    public function updateCartItemWithAnotherItemObject()
    {
        $cart = new Cart();
        $id = uniqid();
        $quantity = rand(1, 10);

        $cart->add(new Item($id))->update(new Item([
            'id' => $id,
            'quantity' => $quantity
        ]));

        /** @noinspection PhpUndefinedMethodInspection */
        $this->assertEquals($cart->items()[0]->quantity(), $quantity);
    }

    /** @test */
    public function whenAddingAnItemTwiceItGetsUpdated()
    {
        $cart = new Cart();
        $item = new Item(uniqid());

        $this->assertEquals(count($cart->items()), 0);

        $cart->add($item);

        $this->assertEquals(count($cart->items()), 1);

        /** @noinspection PhpUndefinedFieldInspection */
        $item->foo = 'bar';
        $cart->add($item);

        $this->assertEquals(count($cart->items()), 1);
        $this->assertObjectHasAttribute('foo', $cart->items()[0]);
    }

    /** @test */
    public function getCartItem()
    {
        $cart = new Cart();
        $id = uniqid();
        $item = new Item($id);

        $cart->add($item);
        $retrievedItem = $cart->item($id);

        $this->assertEquals($item, $retrievedItem);
    }

    /**
     * @test
     * @expectedException \Exception
     */
    public function addCartItemsWithoutIdShouldFail()
    {
        $cart = new Cart();
        $item = new Item();

        $cart->add($item);
    }

    /** @test */
    public function addItemsWithIdsAddedFluently()
    {
        $cart = new Cart();
        $item = new Item();

        $item->id(uniqid());

        $cart->add([
            new Item(uniqid()),
            $item,
        ]);
    }
}


text:
var cbpAnimatedHeader = (function() {

	var docElem = document.documentElement,
		header = document.querySelector( '.navbar-fixed-top' ),
		didScroll = false,
		changeHeaderOn = 120;

	function init() {
		window.addEventListener( 'scroll', function( event ) {
			if( !didScroll ) {
				didScroll = true;
				// setTimeout( scrollPage, 250 );

				setTimeout( scrollPage, 250 );
			}
		}, false );
	}

	function scrollPage() {
		var sy = scrollY();
		if ( sy >= changeHeaderOn ) {
			classie.add( header, 'navbar-shrink' );
		}
		else {
			classie.remove( header, 'navbar-shrink' );
		}
		didScroll = false;
	}

	function scrollY() {
		return window.pageYOffset || docElem.scrollTop;
	}

	init();

})();


text:
using System.Linq;

namespace Lumia.Imaging.Extras.Effects.DepthOfField.Internal
{

	public class GroupChangeTracker : IChangeTracker
	{
		private IChangeTracker[] m_changeTrackers;

		public GroupChangeTracker(params IChangeTracker[] changeTrackers)
		{
			m_changeTrackers = changeTrackers;
		}

		public bool IsDirty
		{
			get
			{
				return m_changeTrackers.Any(tracker => tracker.IsDirty);
			}
		}

		public void Reset()
		{
			foreach (var changeTracker in m_changeTrackers)
			{
				changeTracker.Reset();
			}
		}
	}

}


text:
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('blog', '0001_initial'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='entry',
            options={'get_latest_by': 'pub_date', 'ordering': ['-id', '-pub_date'], 'verbose_name': 'Entrada', 'verbose_name_plural': 'Entradas'},
        ),
    ]


text:
/* line 3, /Users/yamadanaoki/Documents/workspace/dev.cm/middleman/source/assets/stylesheets/appendix/css_length.scss */
img {
  padding: 0;
  margin: auto;
  display: block; }

/* line 8, /Users/yamadanaoki/Documents/workspace/dev.cm/middleman/source/assets/stylesheets/appendix/css_length.scss */
img {
  width: 10vw; }


text:
#include <aws/opensearch/model/DomainInformationContainer.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace OpenSearchService
{
namespace Model
{

DomainInformationContainer::DomainInformationContainer() :
    m_aWSDomainInformationHasBeenSet(false)
{
}

DomainInformationContainer::DomainInformationContainer(JsonView jsonValue) :
    m_aWSDomainInformationHasBeenSet(false)
{
  *this = jsonValue;
}

DomainInformationContainer& DomainInformationContainer::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("AWSDomainInformation"))
  {
    m_aWSDomainInformation = jsonValue.GetObject("AWSDomainInformation");

    m_aWSDomainInformationHasBeenSet = true;
  }

  return *this;
}

JsonValue DomainInformationContainer::Jsonize() const
{
  JsonValue payload;

  if(m_aWSDomainInformationHasBeenSet)
  {
   payload.WithObject("AWSDomainInformation", m_aWSDomainInformation.Jsonize());

  }

  return payload;
}

} // namespace Model
} // namespace OpenSearchService
} // namespace Aws


text:
namespace SimpleHttpServer
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net.Sockets;
    using System.Text;
    using System.Text.RegularExpressions;
    using Enums;
    using Models;
    using Utilities;

    public class HttpProcessor
    {
        private IList<Route> routes;
        private HttpRequest request;
        private HttpResponse response;

        public HttpProcessor(IEnumerable<Route> routes)
        {
            this.routes = new List<Route>(routes);
        }

        public void HandleClient(TcpClient tcpClient)
        {
            using (var stream = tcpClient.GetStream())
            {
                this.request = GetRequest(stream);
                this.response = RouteRequest();

                StreamUtils.WriteResponse(stream, this.response);
            }
        }

        private HttpResponse RouteRequest()
        {
            var routes = this.routes
                .Where(x => Regex.Match(this.request.Url, x.UrlRegex).Success)
                .ToList();

            var test = this.routes.FirstOrDefault().UrlRegex;

            if (!routes.Any())
            {
                return HttpResponseBuilder.NotFound();
            }

            var route = routes.FirstOrDefault(x => x.Method == this.request.Method);

            if (route == null)
            {
                return new HttpResponse()
                {
                    StatusCode = ResponseStatusCode.MethodNotAllowed
                };
            }

            try
            {
                return route.Callable(this.request);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                return HttpResponseBuilder.InternalServerError();
            }

        }

        private HttpRequest GetRequest(NetworkStream inputStream)
        {
            //Read Request Line
            var requestLine = StreamUtils.ReadLine(inputStream);
            var tokens = requestLine.Split(' ');
            while (tokens.Length != 3)
            {
                requestLine = StreamUtils.ReadLine(inputStream);
                tokens = requestLine.Split(' ');
            }

            var method = (RequestMethod)Enum.Parse(typeof(RequestMethod), tokens[0].ToUpper());
            var url = tokens[1];
            var protocolVersion = tokens[2];

            //Read Headers
            var header = new Header(HeaderType.HttpRequest);

            string line;
            while ((line = StreamUtils.ReadLine(inputStream)) != null)
            {
                if (line.Equals(""))
                {
                    break;
                }

                int separator = line.IndexOf(':');
                if (separator == -1)
                {
                    throw new Exception("Invalid http header line: " + line);
                }

                string name = line.Substring(0, separator);
                int pos = separator + 1;
                while ((pos < line.Length) && (line[pos] == ' '))
                {
                    pos++;
                }

                string value = line.Substring(pos, line.Length - pos);
                if (name == "Cookie")
                {
                    string[] cookieSaves = value.Split(';');
                    foreach (var cookieSave in cookieSaves)
                    {
                        string[] cookiePair = cookieSave.Split('=').Select(x => x.Trim()).ToArray();
                        var cookie = new Cookie(cookiePair[0], cookiePair[1]);
                        header.Cookies.Add(cookie);
                    }
                }
                else if (name == "Content-Length")
                {
                    header.ContentLength = value;
                }
                else
                {
                    header.OtherParameters.Add(name, value);
                }
            }

            string content = null;
            if (header.ContentLength != null)
            {
                int totalBytes = Convert.ToInt32(header.ContentLength);
                int bytesLeft = totalBytes;
                var bytes = new byte[totalBytes];

                while (bytesLeft > 0)
                {
                    var buffer = new byte[bytesLeft > 1024 ? 1024 : bytesLeft];
                    int n = inputStream.Read(buffer, 0, buffer.Length);
                    buffer.CopyTo(bytes, totalBytes - bytesLeft);

                    bytesLeft -= n;
                }

                content = Encoding.ASCII.GetString(bytes);
            }

            var request = new HttpRequest()
            {
                Method = method,
                Url = url,
                Header = header,
                Content = content
            };

            Console.WriteLine("-REQUEST-----------------------------");
            Console.WriteLine(request);
            Console.WriteLine("------------------------------");

            return request;
        }
    }
}


text:
def exception(logger,extraLog=None):
    """
    A decorator that wraps the passed in function and logs
    exceptions should one occur
    @param logger: The logging object
    """
    print logger
    def decorator(func):
        print "call decorator"
        def wrapper(*args, **kwargs):
            print "call exception decor"
            print args
            print kwargs
            try:
                print "-----: normal"
                return func(*args, **kwargs)
            except:
                # log the exception
                err = "There was an exception in  "
                err += func.__name__
                #logger.exception(err)
                print "-----: except"
                logger.exception(err,extra=extraLog)
            # re-raise the exception
            raise
        return wrapper
    return decorator


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

<title>osInformationFactory</title>
<meta name="date" content="2020-02-23">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

bichromate.core

Class osInformationFactory

java.lang.Object

bichromate.core.osInformationFactory

public class osInformationFactory
extends java.lang.Object

This class Demonstrates osInformationFactory() - Main class to navigate all OS access. This allows Bichromate to run on Linux, Mac, Windows

Version:

1.0

Author:

davidwramer

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

java.lang.String
buildWorkingDirectoryPath(java.lang.String directory)

This function Demonstrates buildWorkingDirectoryPath().

java.lang.String
fileSeperator()

This function Demonstrates fileSeperator().

java.lang.String
getArchitecture()

This function Demonstrates isWin32BitOS().

java.lang.String
getCountry()

This function Demonstrates getCountry().

java.lang.String
getCurrentDateAndTimeWithSystemTimeZone()

This method Demonstrates getCurrentDateAndTimeWithSystemTimeZone().

java.lang.String
getCurrentDateAndUTCTime()

This method Demonstrates getCurrentDateAndUTCTime().

java.lang.String
getHostName()

This function Demonstrates getHostName().

java.lang.String
getHostNameAndIP()

This function Demonstrates getHostNameAndIP().

java.lang.String
getIPAddress()

This function Demonstrates getIPAddress().

java.lang.String
getLanguage()

This function Demonstrates getLanguage().

java.lang.String
getOSName()

This function Demonstrates getOSName().

systemInformation
getSystemInformation()

This function Demonstrates getSystemInformation().

boolean
isRunningWin64()

This function Demonstrates isRunningWin64().

java.lang.String
pathSeperator()

This function Demonstrates pathSeperator().

java.lang.String
setFilePath(java.lang.String path)

This function Demonstrates setFilePath().

java.lang.String
workingDirectory()

This function Demonstrates workingDirectory().

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Method Detail

getSystemInformation

public systemInformation getSystemInformation()

This function Demonstrates getSystemInformation().
 Used to get system information

Returns:

systemInformation

getLanguage

public java.lang.String getLanguage()

This function Demonstrates getLanguage().
 Returns the language setting from Locale

Returns:

String country

getCountry

public java.lang.String getCountry()

This function Demonstrates getCountry().
 Returns the country setting from Locale

Returns:

String country

getHostNameAndIP

public java.lang.String getHostNameAndIP()

This function Demonstrates getHostNameAndIP().
 Used to return hostname and IP

Returns:

String HostName and IP

pathSeperator

public java.lang.String pathSeperator()

This function Demonstrates pathSeperator().

This function returns the path separator for the given OS: System.getProperty("path.separator")

Returns:

pathSeperator of the path separator for the current OS

fileSeperator

public java.lang.String fileSeperator()

This function Demonstrates fileSeperator().
 This function returns the file seperator for the given OS: System.getProperty("file.separator")

Returns:

fileSeperator of the file seperator for the current OS

getArchitecture

public java.lang.String getArchitecture()

This function Demonstrates isWin32BitOS().
 This function returns true if the windows environment is 64 bit

Returns:

true if win OS is 64 bit

isRunningWin64

public boolean isRunningWin64()

This function Demonstrates isRunningWin64().
 This function returns true if the windows environment is 64 bit

Returns:

true if win OS is amd64

getHostName

public java.lang.String getHostName()

This function Demonstrates getHostName().
 This function returns the hostName

Returns:

hostname  of the computer

getIPAddress

public java.lang.String getIPAddress()

This function Demonstrates getIPAddress().
 This function returns the hostName

Returns:

ip  of the computer

getOSName

public java.lang.String getOSName()

This function Demonstrates getOSName().
 This function returns the path seperator for the given OS

Returns:

osName of the path seperator for the current OS

getCurrentDateAndTimeWithSystemTimeZone

public java.lang.String getCurrentDateAndTimeWithSystemTimeZone()

This method Demonstrates getCurrentDateAndTimeWithSystemTimeZone().
 This function returns the current date in the following format yyyy-MM-dd-HH-mm-ss properties file

Returns:

String  date  yyyy-MM-dd-HH-mm-ss with the current system Time Zone.

getCurrentDateAndUTCTime

public java.lang.String getCurrentDateAndUTCTime()

This method Demonstrates getCurrentDateAndUTCTime().
 This function returns the current date in the following format yyyy-MM-dd-HH-mm-ss

Returns:

String  date  yyyy-MM-dd-HH-mm-ss set to UTC Time.

workingDirectory

public java.lang.String workingDirectory()

This function Demonstrates workingDirectory().
 This function returns the working directory

Returns:

workingDirectory of the working directory

buildWorkingDirectoryPath

public java.lang.String buildWorkingDirectoryPath(java.lang.String directory)

This function Demonstrates buildWorkingDirectoryPath().
 inserts the correct /\ to build the correct path to the working directory

Parameters:

directory - - used to set file path

Returns:

workingDirectory of the working directory

setFilePath

public java.lang.String setFilePath(java.lang.String path)

This function Demonstrates setFilePath().
 This function takes a path and changes the \ or / based on specific OS
 There is no need to change properties file path names when running on different OS.

Parameters:

path - path to be checked

Returns:

newPath of the correct path for the current OS

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
using System.ComponentModel.DataAnnotations;

namespace KDCLLC.Identity.Services.ViewModels.Account
{
    public class ExternalLoginConfirmationViewModel
    {
        [Required]
        [Display(Name = "Email")]
        public string Email { get; set; }

        public string UserName { get; set; }

    }
}


text:
"""
    sanic_dispatcher
    ~~~~

    :copyright: (c) 2017 by Ashley Sommer (based on DispatcherMiddleware in the Werkzeug Project).
    :license: MIT, see LICENSE for more details.
"""
from collections import defaultdict
from inspect import isawaitable
from io import BytesIO
from warnings import warn
try:
    from setuptools.extern import packaging
except ImportError:
    from pkg_resources.extern import packaging

from sanic import Sanic, __version__ as sanic_version
from sanic.exceptions import URLBuildError
from sanic.response import HTTPResponse, BaseHTTPResponse
from sanic.server import HttpProtocol
from sanic.websocket import WebSocketProtocol

SANIC_VERSION = packaging.version.parse(sanic_version)
SANIC_0_7_0 = packaging.version.parse('0.7.0')
if SANIC_VERSION < SANIC_0_7_0:
    raise RuntimeError("Please use Sanic v0.7.0 or greater with this extension.")
SANIC_19_03_0 = packaging.version.parse('19.3.0')
SANIC_18_12_0 = packaging.version.parse('18.12.0')
SANIC_21_03_0 = packaging.version.parse('21.03.0')
IS_19_03 = SANIC_VERSION >= SANIC_19_03_0
IS_18_12 = SANIC_VERSION >= SANIC_18_12_0
IS_21_03 = SANIC_VERSION >= SANIC_21_03_0
if IS_19_03:
    from sanic.request import RequestParameters
    from sanic.log import error_logger
else:
    import logging
    error_logger = logging.getLogger("sanic.error")
if IS_21_03:
    from sanic.compat import CancelledErrors

class WsgiApplication(object):
    __slots__ = ['app', 'apply_middleware']

    def __init__(self, app, apply_middleware=False):
        self.app = app
        self.apply_middleware = apply_middleware

class SanicApplication(object):
    __slots__ = ['app', 'server_settings', 'apply_middleware']

    def __init__(self, app, apply_middleware=False):
        self.app = app
        self.server_settings = {}
        self.apply_middleware = apply_middleware

class SanicCompatURL(object):
    """
    This class exists because the sanic native URL type is private (a non-exposed C module)
    and all of its components are read-only. We need to modify the URL path in the dispatcher
    so we build a feature-compatible writable class of our own to use instead.
    """
    __slots__ = ('schema', 'host', 'port', 'path', 'query', 'fragment', 'userinfo')

    def __init__(self, schema, host, port, path, query, fragment, userinfo):
        self.schema = schema
        self.host = host
        self.port = port
        self.path = path
        self.query = query
        self.fragment = fragment
        self.userinfo = userinfo

class SanicComatRequest(object):
    __slots__ = ("orig_req", "parent_app")
    def __init__(self, orig_req, parent_app):
        self.orig_req = orig_req
        self.parent_app = parent_app

    def __getattr__(self, item):
        if item in SanicComatRequest.__slots__:
            return object.__getattribute__(self, item)
        return getattr(self.orig_req, item)

    def __setattr__(self, key, val):
        if key in SanicComatRequest.__slots__:
            return object.__setattr__(self, key, val)
        return setattr(self.orig_req, key, val)

    async def respond(self, response=None, *args, status=200, headers=None, content_type=None):
        # From Sanic 21.03
        # This logic of determining which response to use is subject to change
        if response is None:
            response = (self.stream and self.stream.response) or HTTPResponse(
                status=status,
                headers=headers,
                content_type=content_type,
            )
        # Connect the response
        if isinstance(response, BaseHTTPResponse) and self.stream:
            response = self.stream.respond(response)
        # Run child's response middleware
        try:
            response = await self.app._run_response_middleware(
                self, response, request_name=self.name
            )
        except CancelledErrors:
            raise
        except Exception:
            error_logger.exception(
                "Exception occurred in one of response middleware handlers"
            )
        parent_app = self.parent_app
        if parent_app.response_middleware:
            self.orig_req.app = parent_app
            for _middleware in parent_app.response_middleware:
                _response = _middleware(self, response)
                if isawaitable(_response):
                    _response = await _response
                if _response:
                    response = _response
                    if isinstance(response, BaseHTTPResponse):
                        response = self.stream.respond(response)
        return response

class SanicDispatcherMiddleware(object):
    """
    A multi-application dispatcher, and also acts as a sanic-to-wsgiApp adapter.
    Based on the DispatcherMiddleware class in werkzeug.
    """

    __slots__ = ['parent_app', 'parent_handle_request', 'mounts', 'hosts']

    use_wsgi_threads = True

    def __init__(self, parent_app, parent_handle_request, mounts=None, hosts=None):
        self.parent_app = parent_app
        self.parent_handle_request = parent_handle_request
        self.mounts = mounts or {}
        self.hosts = frozenset(hosts) if hosts else frozenset()

    @staticmethod
    def _call_wsgi(script_name, path_info, request, wsgi_app, response_callback):
        http_response = None
        body_bytes = bytearray()

        def _start_response(status, headers, *args, **kwargs):
            """The start_response callback as required by the wsgi spec. This sets up a response including the
            status code and the headers, but doesn't write a body."""
            nonlocal http_response
            nonlocal body_bytes
            if isinstance(status, int):
                code = status
            elif isinstance(status, str):
                code = int(status.split(" ")[0])
            else:
                raise RuntimeError("status cannot be turned into a code.")
            sanic_headers = dict(headers)
            response_constructor_args = {'status': code,  'headers': sanic_headers}
            if 'content_type' in kwargs:
                response_constructor_args['content_type'] = kwargs['content_type']
            elif 'Content-Type' in sanic_headers:
                response_constructor_args['content_type'] = str(sanic_headers['Content-Type']).split(";")[0].strip()
            http_response = HTTPResponse(**response_constructor_args)

            def _write_body(body_data):
                """This doesn't seem to be used, but it is part of the wsgi spec, so need to have it."""
                nonlocal body_bytes
                nonlocal http_response
                if isinstance(body_data, bytes):
                    pass
                else:
                    try:
                        # Try to encode it regularly
                        body_data = body_data.encode()
                    except AttributeError:
                        # Convert it to a str if you can't
                        body_data = str(body_data).encode()
                body_bytes.extend(body_data)
            return _write_body

        environ = {}
        original_script_name = environ.get('SCRIPT_NAME', '')
        environ['SCRIPT_NAME'] = original_script_name + script_name
        environ['PATH_INFO'] = path_info
        if request._parsed_url and request._parsed_url.host is not None:
            host = request._parsed_url.host.decode('utf-8')
        elif 'host' in request.headers:
            host = request.headers['host']
        else:
            host = 'localhost:80'
        if 'content-type' in request.headers:
            content_type = request.headers['content-type']
        else:
            content_type = 'text/plain'
        environ['CONTENT_TYPE'] = content_type
        if 'content-length' in request.headers:
            content_length = request.headers['content-length']
            environ['CONTENT_LENGTH'] = content_length

        split_host = host.split(':', 1)
        host_has_port = len(split_host) > 1
        server_name = split_host[0]
        if request._parsed_url and request._parsed_url.port is not None:
            server_port = request._parsed_url.port.decode('ascii')
        elif host_has_port:
            server_port = split_host[1]
        else:
            server_port = '80'  # TODO: Find a better way of determining the port number when not provided
        if (not host_has_port) and (server_port != '80'):
            host = ":".join((host, server_port))
        environ['SERVER_PORT'] = server_port
        environ['SERVER_NAME'] = server_name
        environ['SERVER_PROTOCOL'] = 'HTTP/1.1' if request.version == "1.1" else 'HTTP/1.0'
        environ['HTTP_HOST'] = host
        environ['QUERY_STRING'] = request.query_string or ''
        environ['REQUEST_METHOD'] = request.method
        environ['wsgi.url_scheme'] = 'http'  # todo: detect http vs https
        environ['wsgi.input'] = BytesIO(request.body) if request.body is not None and len(request.body) > 0\
            else BytesIO(b'')
        try:
            wsgi_return = wsgi_app(environ, _start_response)
        except Exception as e:
            error_logger.exception(e)
            raise e
        if http_response is None:
            http_response = HTTPResponse("WSGI call error.", 500)
        else:
            for body_part in wsgi_return:
                if body_part is not None:
                    if isinstance(body_part, bytes):
                        pass
                    else:
                        try:
                            # Try to encode it regularly
                            body_part = body_part.encode()
                        except AttributeError:
                            # Convert it to a str if you can't
                            body_part = str(body_part).encode()
                    body_bytes.extend(body_part)
            http_response.body = bytes(body_bytes)
        if response_callback:
            return response_callback(http_response)
        return http_response

    if IS_21_03:
        async def call_wsgi_app(self, script_name, path_info, request, wsgi_app):

            if self.use_wsgi_threads:
                return await self.parent_app.loop.run_in_executor(None, self._call_wsgi, script_name, path_info, request, wsgi_app, False)
            else:
                return self._call_wsgi(script_name, path_info, request, wsgi_app, False)
    else:
        async def call_wsgi_app(self, script_name, path_info, request, wsgi_app, response_callback):
            if self.use_wsgi_threads:
                return await self.parent_app.loop.run_in_executor(
                    None, self._call_wsgi, script_name, path_info, request,
                    wsgi_app, response_callback)
            else:
                return self._call_wsgi(script_name, path_info, request, wsgi_app, response_callback)
    @staticmethod
    def get_request_scheme(request):
        try:
            if request.headers.get('upgrade') == 'websocket':
                scheme = b'ws'
            elif request.transport.get_extra_info('sslcontext'):
                scheme = b'https'
            else:
                scheme = b'http'
        except (AttributeError, KeyError):
            scheme = b'http'
        return scheme

    def _get_application_by_route(self, request, use_host=False):
        host = request.headers.get('Host', '')
        scheme = self.get_request_scheme(request)
        path = request._parsed_url.path
        port = request._parsed_url.port
        query_string = request._parsed_url.query
        fragment = request._parsed_url.fragment
        userinfo = request._parsed_url.userinfo
        script = path
        if ':' in host and port is None:
            (host, port) = host.split(':', 1)[0:2]
            port = port.encode('ascii')
        host_bytes = host.encode('utf-8')

        if use_host:
            script = b'%s%s' % (host_bytes, script)
        path_info = b''
        while b'/' in script:
            script_str = script.decode('utf-8')
            try:
                application = self.mounts[script_str]
                break
            except KeyError:
                pass
            script, last_item = script.rsplit(b'/', 1)
            path_info = b'/%s%s' % (last_item, path_info)
        else:
            script_str = script.decode('utf-8')
            application = self.mounts.get(script_str, None)
        if application is not None:
            request._parsed_url = SanicCompatURL(scheme, host_bytes, port,
                                                 path_info, query_string, fragment, userinfo)
            if IS_19_03:
                # To trigger re-parse args
                request.parsed_args = defaultdict(RequestParameters)
            else:
                request.parsed_args = None  # To trigger re-parse args
            path = request.path
        return application, script_str, path

    if IS_21_03:
        async def __call__(self, request):
            # Assume at this point that we have no app. So we cannot know if we are on Websocket or not.
            if self.hosts and len(self.hosts) > 0:
                application, script, path = self._get_application_by_route(request, use_host=True)
                if application is None:
                    application, script, path = self._get_application_by_route(request, use_host=False)
            else:
                application, script, path = self._get_application_by_route(request)
            if application is None:  # no child matches, call the parent
                return await self.parent_handle_request(request)
            return await self._call_2103(request, application, script, path)
    else:
        async def __call__(self, request, write_callback, stream_callback):
            # Assume at this point that we have no app. So we cannot know if we are on Websocket or not.
            if self.hosts and len(self.hosts) > 0:
                application, script, path = self._get_application_by_route(request, use_host=True)
                if application is None:
                    application, script, path = self._get_application_by_route(request, use_host=False)
            else:
                application, script, path = self._get_application_by_route(request)
            if application is None:  # no child matches, call the parent
                return await self.parent_handle_request(request, write_callback, stream_callback)
            return await self._call_old(request, application, script, path, write_callback, stream_callback)

    async def _call_old(self, request, application, script, path, write_callback, stream_callback):
        real_write_callback = write_callback
        real_stream_callback = stream_callback
        response = False
        streaming_response = False
        def _write_callback(child_response):
            nonlocal response
            response = child_response

        def _stream_callback(child_stream):
            nonlocal streaming_response
            streaming_response = child_stream

        replaced_write_callback = _write_callback
        replaced_stream_callback = _stream_callback
        parent_app = self.parent_app
        if application.apply_middleware and parent_app.request_middleware:
            request.app = parent_app
            for middleware in parent_app.request_middleware:
                response = middleware(request)
                if isawaitable(response):
                    response = await response
                if response:
                    break
        child_app = application.app
        if not response and not streaming_response:
            if isinstance(application, WsgiApplication):  # child is wsgi_app
                await self.call_wsgi_app(script, path, request,
                                         child_app, replaced_write_callback)
            else:  # must be a sanic application
                request.app = child_app
                await child_app.handle_request(request, replaced_write_callback, replaced_stream_callback)

        if application.apply_middleware and parent_app.response_middleware:
            request.app = parent_app
            for _middleware in parent_app.response_middleware:
                _response = _middleware(request, response)
                if isawaitable(_response):
                    _response = await _response
                if _response:
                    response = _response
                    break

        while isawaitable(response):
            response = await response
        if streaming_response:
            return real_stream_callback(streaming_response)
        return real_write_callback(response)

    async def _call_2103(self, request, application, script, path):

        our_response = False
        streaming_response = False

        if request.stream.request_body:  # type: ignore
            # Non-streaming handler: preload body
            await request.receive_body()

        parent_app = self.parent_app
        if application.apply_middleware and parent_app.request_middleware:
            request.app = parent_app
            for middleware in parent_app.request_middleware:
                our_response = middleware(request)
                if isawaitable(our_response):
                    our_response = await our_response
                if our_response:
                    break
        child_app = application.app
        if application.apply_middleware:
            request = SanicComatRequest(request, parent_app)
        if not our_response and not streaming_response:
            if isinstance(application, WsgiApplication):  # child is wsgi_app
                our_response = await self.call_wsgi_app(script, path, request, child_app)
            else:  # must be a sanic application
                request.app = child_app
                return await child_app.handle_request(request)
        if our_response is not None:
            try:
                our_response = await request.respond(our_response)
            except BaseException:
                # Skip response middleware
                if request.stream:
                    request.stream.respond(our_response)
                await our_response.send(end_stream=True)
                raise
        else:
            if request.stream:
                our_response = request.stream.response
        if isinstance(our_response, BaseHTTPResponse):
            await our_response.send(end_stream=True)
        return our_response

class SanicDispatcherMiddlewareController(object):
    __slots__ = ['parent_app', 'parent_handle_request', 'parent_url_for', 'applications', 'url_prefix',
                 'filter_host', 'hosts', 'started']

    def __init__(self, app, url_prefix=None, host=None):
        """
        :param Sanic app:
        :param url_prefix:
        """
        self.parent_app = app
        self.applications = {}
        self.url_prefix = None if url_prefix is None else str(url_prefix).rstrip('/')
        self.hosts = set()
        if host:
            self.filter_host = host
            self.hosts.add(host)
        else:
            self.filter_host = None
        self.started = False
        self.parent_app.register_listener(self._before_server_start_listener, 'before_server_start')
        self.parent_app.register_listener(self._after_server_start_listener, 'after_server_start')
        self.parent_app.register_listener(self._before_server_stop_listener, 'before_server_stop')
        self.parent_app.register_listener(self._after_server_stop_listener, 'after_server_stop')
        # Woo, monkey-patch!
        self.parent_handle_request = app.handle_request
        self.parent_url_for = app.url_for
        if IS_21_03:
            self.parent_app.handle_request = self.handle_request_2103
        else:
            self.parent_app.handle_request = self.handle_request
        self.parent_app.url_for = self.patched_url_for

    async def _before_server_start_listener(self, app, loop):
        if self.started is True:
            raise RuntimeError("Cannot start a sanic parent application more than once.")
        has_ws = False
        for route, child_app in self.applications.items():
            if isinstance(child_app, SanicApplication):
                s_app = child_app.app
                is_ws = getattr(s_app, 'websocket_enabled', False)
                protocol = WebSocketProtocol if is_ws else HttpProtocol
                server_settings = s_app._helper(host=None, port=None, loop=loop,
                                                protocol=protocol, run_async=False)
                child_app.server_settings = server_settings
                await s_app.trigger_events(
                    server_settings.get("before_start", []),
                    server_settings.get("loop"),
                )
                has_ws = has_ws or is_ws
        if not getattr(app, 'websocket_enabled', False) and has_ws:
            raise RuntimeError(
                "Found child apps with Websockets enabled, but parent app is not Websockets enabled.\n"
                "Add parent_app.enable_websocket() before starting the app.")

    async def _after_server_start_listener(self, app, loop):
        is_asgi = getattr(app, 'asgi', False)
        if is_asgi:
            error_logger.warning("Sanic-Dispatcher has not been tested on ASGI apps. It may not work correctly.")

        self.started = True

        for route, child_app in self.applications.items():
            if isinstance(child_app, SanicApplication):
                server_settings = child_app.server_settings
                await child_app.app.trigger_events(
                    server_settings.get("after_start", []),
                    server_settings.get("loop"),
                )

    async def _before_server_stop_listener(self, app, loop):
        for route, child_app in self.applications.items():
            if isinstance(child_app, SanicApplication):
                server_settings = child_app.server_settings
                await child_app.app.trigger_events(
                    server_settings.get("before_stop", []),
                    server_settings.get("loop"),
                )

    async def _after_server_stop_listener(self, app, loop):
        for route, child_app in self.applications.items():
            if isinstance(child_app, SanicApplication):
                server_settings = child_app.server_settings
                await child_app.app.trigger_events(
                    server_settings.get("after_stop", []),
                    server_settings.get("loop"),
                )

    def _determine_uri(self, url_prefix, host=None):
        uri = ''
        if self.url_prefix is not None:
            uri = self.url_prefix
        if host is not None:
            uri = str(host) + uri
            self.hosts.add(host)
        elif self.filter_host is not None:
            uri = str(self.filter_host) + uri
        uri += url_prefix
        return uri

    def register_app(self, app, url_prefix, host=None, apply_middleware=False):
        if isinstance(app, Sanic):
            self.register_sanic_application(app, url_prefix, host=host,
                                            apply_middleware=apply_middleware)
        else:
            self.register_wsgi_application(app, url_prefix, host=host,
                                           apply_middleware=apply_middleware)

    def register_sanic_application(self, application, url_prefix, host=None, apply_middleware=False):
        """
        :param Sanic application:
        :param url_prefix:
        :param host:
        :param apply_middleware:
        :return:
        """
        if self.started is True:
            raise warn("Registering an application when the server is already started may work,"
                       "but is not supported.")
        assert isinstance(application, Sanic),\
            "Pass only instances of Sanic to register_sanic_application."
        if str(url_prefix).endswith('/'):
            url_prefix = url_prefix[:-1]
        if host is not None and isinstance(host, (list, set)):
            for _host in host:
                self.register_sanic_application(application, url_prefix, host=_host,
                                                apply_middleware=apply_middleware)
            return

        registered_service_url = self._determine_uri(url_prefix, host)
        self.applications[registered_service_url] = SanicApplication(application, apply_middleware)
        self._update_request_handler()

    def register_wsgi_application(self, application, url_prefix, host=None, apply_middleware=False):
        """
        :param application:
        :param url_prefix:
        :param apply_middleware:
        :return:
        """
        if self.started is True:
            raise RuntimeError("Cannot register an application when the server is already started.")
        if str(url_prefix).endswith('/'):
            url_prefix = url_prefix[:-1]
        if host is not None and isinstance(host, (list, set)):
            for _host in host:
                self.register_wsgi_application(application, url_prefix, host=_host,
                                               apply_middleware=apply_middleware)
            return

        registered_service_url = self._determine_uri(url_prefix, host)
        self.applications[registered_service_url] = WsgiApplication(application, apply_middleware)
        self._update_request_handler()

    def unregister_application(self, application, all_matches=False):
        if isinstance(application, (SanicApplication, WsgiApplication)):
            application = application.app
        urls_to_unregister = []
        for url, reg_application in self.applications.items():
            if reg_application.app == application:
                urls_to_unregister.append(url)
                if not all_matches:
                    break
        for url in urls_to_unregister:
            del self.applications[url]
        self._update_request_handler()

    def unregister_prefix(self, url_prefix, host=None):
        if str(url_prefix).endswith('/'):
            url_prefix = url_prefix[:-1]
        if host is not None and isinstance(host, (list, set)):
            for _host in host:
                self.unregister_prefix(url_prefix, host=_host)
            return
        registered_service_url = self._determine_uri(url_prefix, host)
        try:
            del self.applications[registered_service_url]
        except KeyError:
            pass
        self._update_request_handler()

    def _update_request_handler(self):
        """
        Rebuilds the SanicDispatcherMiddleware every time a new application is registered
        :return:
        """
        dispatcher = SanicDispatcherMiddleware(self.parent_app, self.parent_handle_request, self.applications,
                                               self.hosts)
        self.parent_app.handle_request = dispatcher

    async def handle_request(self, request, write_callback, stream_callback):
        """
        This is only called as a backup handler if _update_request_handler was not yet called.
        :param request:
        :param write_callback:
        :param stream_callback:
        :return:
        """
        dispatcher = SanicDispatcherMiddleware(self.parent_app, self.parent_handle_request, self.applications,
                                               self.hosts)
        self.parent_app.handle_request = dispatcher  # save it for next time
        retval = dispatcher(request, write_callback, stream_callback)
        if isawaitable(retval):
            retval = await retval
        return retval

    async def handle_request_2103(self, request):
        """
        This is only called as a backup handler if _update_request_handler was not yet called.
        :param request:
        :return:
        """
        dispatcher = SanicDispatcherMiddleware(self.parent_app, self.parent_handle_request, self.applications,
                                               self.hosts)
        self.parent_app.handle_request = dispatcher  # save it for next time
        _ = await dispatcher(request)
        # This 2103 handler doesn't return anything

    def _dispatcher_url_for(self, view_name, **kwargs):
        """
        Checks all of the registered applications in the dispatcher for `url_for()`
        :param str view_name:
        :param kwargs:
        :return:
        """
        for url_prefix, reg_application in self.applications.items():
            app = reg_application.app
            try:
                _url_for = getattr(app, 'url_for', None)
                if _url_for is None:
                    continue
                try:
                    _url = _url_for(view_name, **kwargs)
                except URLBuildError:
                    continue
                if _url is not None:
                    return ''.join((url_prefix, str(_url)))
            except (AssertionError, KeyError):
                continue
        return None

    def patched_url_for(self, view_name, **kwargs):
        """
        When `url_for()` is called on the parent app, this gets called instead.
        :param str view_name:
        :param kwargs:
        :return:
        """
        try:
            url = self.parent_url_for(view_name, **kwargs)
        except URLBuildError:
            url = None
        if url is None:
            try:
                url = self._dispatcher_url_for(view_name, **kwargs)
            except URLBuildError:
                url = None
        if url is None:
            raise URLBuildError("Url Not found in the Parent App, nor the Dispatcher routes")

        return url

    def url_for(self, view_name, **kwargs):
        """
        When `url_for()` is called on the dispatcher app, this gets called instead.
        :param str view_name:
        :param kwargs:
        :return:
        """
        try:
            url = self._dispatcher_url_for(view_name, **kwargs)
        except URLBuildError:
            url = None
        if url is None:
            try:
                url = self.parent_url_for(view_name, **kwargs)
            except URLBuildError:
                url = None
        if url is None:
            raise URLBuildError("Url Not found in the Dispatcher routes, nor the Parent App")
        return url


text:
package org.apache.asterix.lang.common.statement;

import org.apache.asterix.common.exceptions.AsterixException;
import org.apache.asterix.lang.common.base.Statement;
import org.apache.asterix.lang.common.struct.Identifier;
import org.apache.asterix.lang.common.visitor.base.ILangVisitor;

public class RefreshExternalDatasetStatement implements Statement {

    private Identifier dataverseName;
    private Identifier datasetName;

    public Identifier getDatasetName() {
        return datasetName;
    }

    public void setDatasetName(Identifier datasetName) {
        this.datasetName = datasetName;
    }

    public Identifier getDataverseName() {
        return dataverseName;
    }

    public void setDataverseName(Identifier dataverseName) {
        this.dataverseName = dataverseName;
    }

    @Override
    public <R, T> R accept(ILangVisitor<R, T> visitor, T arg) throws AsterixException {
        return null;
    }

    @Override
    public Kind getKind() {
        return Kind.EXTERNAL_DATASET_REFRESH;
    }

}


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Helper
</TITLE>

<META NAME="date" CONTENT="2012-10-10">

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

      概述
      软件包
    类
      使用
      树
      已过时
      索引
      帮助

 上一个类
 下一个类

  框架
 无框架

  所有类

  摘要: 嵌套 | 字段 | 构造方法 | 方法

详细信息: 字段 | 构造方法 | 方法

com.aliyun.android.util

类 Helper

java.lang.Object
  com.aliyun.android.util.Helper

public class Helper
extends java.lang.Object

工具类

作者:

Michael

构造方法摘要

Helper()

方法摘要

static java.lang.String
formatPath(java.lang.String path)

          格式化文件夹路径 * @param path /** * @return

static java.util.Date
getDateFromString(java.lang.String dateString)

          将String格式的日期按默认格式转换为Date对象* @param dateString /** * @return /** * @throws
 ParseException

static java.util.Date
getDateFromString(java.lang.String format,
                  java.lang.String dateString)

          将String格式的日起按给定格式* @param format 转换为Date对象 /** * @param dateString /** * @return
 /** * @throws ParseException

static java.lang.String
getGMTDate()

          获取当前GMT时间

static java.lang.String
getGMTDate(java.util.Date date)

          获取GMT时间

static java.util.Date
getGMTDateFromString(java.lang.String dateStr)

          解析日期字符串得到对象

static java.lang.String
getHmacSha1Signature(java.lang.String value,
                     java.lang.String key)

          获取Hmac sha1的签名

static java.lang.String
inputStream2String(java.io.InputStream inputStream)

          将inputStream的内容转为String

static boolean
isEmptyString(java.lang.String str)

          判断是否为空字符串

从类 java.lang.Object 继承的方法

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

构造方法详细信息

Helper

public Helper()

方法详细信息

getGMTDate

public static java.lang.String getGMTDate()

获取当前GMT时间

返回:
GMT时间的字符串表示

getGMTDate

public static java.lang.String getGMTDate(java.util.Date date)

获取GMT时间

getGMTDateFromString

public static java.util.Date getGMTDateFromString(java.lang.String dateStr)
                                           throws java.text.ParseException

解析日期字符串得到对象

参数:
dateStr - 表示日期的字符串

返回:
日期对象

抛出:

java.text.ParseException

getHmacSha1Signature

public static java.lang.String getHmacSha1Signature(java.lang.String value,
                                                    java.lang.String key)
                                             throws java.security.NoSuchAlgorithmException,
                                                    java.security.InvalidKeyException

获取Hmac sha1的签名

返回:
base64 encode后的签名字符串

抛出:

java.security.NoSuchAlgorithmException

java.security.InvalidKeyException

isEmptyString

public static boolean isEmptyString(java.lang.String str)

判断是否为空字符串

inputStream2String

public static java.lang.String inputStream2String(java.io.InputStream inputStream)
                                           throws java.lang.Exception

将inputStream的内容转为String

抛出:

java.lang.Exception

getDateFromString

public static java.util.Date getDateFromString(java.lang.String dateString)
                                        throws java.text.ParseException

将String格式的日期按默认格式转换为Date对象* @param dateString /** * @return /** * @throws
 ParseException

抛出:

java.text.ParseException

getDateFromString

public static java.util.Date getDateFromString(java.lang.String format,
                                               java.lang.String dateString)
                                        throws java.text.ParseException

将String格式的日起按给定格式* @param format 转换为Date对象 /** * @param dateString /** * @return
 /** * @throws ParseException

抛出:

java.text.ParseException

formatPath

public static java.lang.String formatPath(java.lang.String path)

格式化文件夹路径 * @param path /** * @return

      概述
      软件包
    类
      使用
      树
      已过时
      索引
      帮助

 上一个类
 下一个类

  框架
 无框架

  所有类

  摘要: 嵌套 | 字段 | 构造方法 | 方法

详细信息: 字段 | 构造方法 | 方法


text:
package behavior.state;

/**
 * Created by zhuyanan on 17/8/15.
 */
public interface State {

    void handle(String param);
}


text:
'use strict';

/*
    if access to Twitter API, have a pagemod
    if no access to Twitter API, no need for a pagemod

*/

import pagemodModule = require("sdk/page-mod");
import selfModule =  require("sdk/self");

import getAccessToken = require('./getAccessToken');
import getTimelineOverATimePeriod = require('./getTimelineOverATimePeriod');
import TwitterAPIViaServer = require('./TwitterAPIViaServer');
import guessAddonUserTwitterName = require('./guessAddonUserTwitterName');
import getAddonUserInfoAndFriends = require('./getAddonUserInfoAndFriends');

//import stemByLang = require('../data/metrics-integration/stem');

const PageMod = pagemodModule.PageMod;
const data = selfModule.data;

const ONE_DAY = 24*60*60*1000;
const DISPLAY_DAY_COUNT = 40;

let twitterAPI : TwitterAPI_I;

/*let addonUsername : string;
let addonUserAndFriendsP : Promise<{
    user: TwitterAPIUser
    friendIds: TwitterUserId[]
}>;*/

let languages: {code: string, name: string}[];

// create the pageMod inconditionally
// if the browser was offline initially, an access token couldn't be acquired
// the pageMod will verify if there is an access token at each attach event (and retry)
const twitterProfilePageMod = new PageMod({
    include: /^https?:\/\/twitter\.com\/([^\/]+)\/?$/,

    contentScriptFile: [
        data.url("ext/react.js"),

        data.url("metrics-integration/twitter-assistant-content.js")
    ],
    contentScriptWhen: "start", // mostly so the 'attach' event happens as soon as possible

    contentStyleFile: [
        data.url("metrics-integration/main.css"),
        data.url("metrics-integration/additional.css")
    ]
});

twitterProfilePageMod.on('attach', function onAttach(worker){
    // TODO:
    // Do nothing on 404 pages as well as search results

    const matches = worker.url.match(/^https?:\/\/twitter\.com\/([^\/\?]+)[\/\?]?/);

    if(!Array.isArray(matches) || matches.length < 2)
        return;
    const visitedUser : string = matches[1];

    twitterAPI.lookupUsersByScreenNames([visitedUser]).then( users => {
        worker.port.emit('visited-user-details', users[0]);
    });

    getAddonUserInfoAndFriends(twitterAPI).then( result => {
        worker.port.emit('addon-user-and-friends', result);
    });

    worker.port.emit('display-days-count', DISPLAY_DAY_COUNT);

    const getTimelineWithProgress = getTimelineOverATimePeriod(twitterAPI.getUserTimeline);
    const timelineComplete = getTimelineWithProgress({
        username: visitedUser,
        timestampFrom: (new Date()).getTime() - ONE_DAY*40
    }, sendTimelineToContent);

    (<any> timelineComplete).catch( (err: Error) => {
        console.error('error while getting the user timeline', visitedUser, err);
    });

    /*if(languages){
        worker.port.emit('languages', languages);
    }
    else{
        twitterAPI.getLanguages()
            .then(l => {
                languages = l;
                worker.port.emit('languages', languages);
            })
            .catch(err => console.error('Twitter languages error', err));
    }*/

    function sendTimelineToContent(partialTimeline: TwitterAPITweet[]){
        worker.port.emit('twitter-user-data', partialTimeline);
    }

    worker.port.on('ask-users', (userIds: TwitterUserId[]) => {
        twitterAPI.lookupUsersByIds(userIds).then(users => {
            worker.port.emit('answer-users', users)
        });
    });

});

function getReady(oauthToken: string, serverOrigin: string) : Promise<any>{
    twitterAPI = TwitterAPIViaServer(oauthToken, serverOrigin);
    return Promise.resolve(); // so TS shut up
}

export = getReady;


text:
'use strict';

this.LiveBlocks = {};
(function(host) {

  // Collect all classes and functions on inner
  var inner = {};
  (function(host) {


text:
using System;
using System.Collections.Generic;

namespace GfaSteps.Settings
{
	[Serializable]
	public sealed class ArcGISSettings
	{
		public string AdminUser { get; set; }

		public string AdminUserPassword { get; set; }

		public string ServerUrl { get; set; }

		public bool UploadSD { get; set; }

		public bool RefreshSOE { get; set; }

		public List<string> SOEPaths { get; set; }

		public List<string> SDPaths { get; set; }
	}
}


text:
package freebsd

import (
	"os/exec"
	"strings"

	"github.com/mackerelio/mackerel-agent/logging"
)

// KernelGenerator Generates specs about the kernel.
// Keys below are expected.
// - name:    the operating system name ("Linux")
// - release: the operating system release ("2.6.32-5-686")
// - version: the operating system version ("#1 SMP Sun Sep 23 09:49:36 UTC 2012")
// - machine: the machine hardware name ("i686")
// - os:      the operating system name ("GNU/Linux")
type KernelGenerator struct {
}

// Key XXX
func (g *KernelGenerator) Key() string {
	return "kernel"
}

var kernelLogger = logging.GetLogger("spec.kernel")

// Generate XXX
func (g *KernelGenerator) Generate() (interface{}, error) {
	unameArgs := map[string][]string{
		"release": []string{"-r"},
		"version": []string{"-v"},
		"machine": []string{"-m"},
		"os":      []string{"-s"},
	}

	results := make(map[string]string, len(unameArgs)+1)

	for field, args := range unameArgs {
		out, err := exec.Command("/usr/bin/uname", args...).Output()
		if err != nil {
			kernelLogger.Errorf("Failed to run uname %s (skip this field): %s", args, err)
			continue
		}

		results[field] = strings.TrimSpace(string(out))
	}

	results["name"] = results["os"]

	return results, nil
}


text:
package com.emc.ecs.metadata.dao;

import java.util.Date;

import com.emc.ecs.management.entity.NamespaceBillingInfo;
import com.emc.ecs.management.entity.ObjectBuckets;

public interface BillingDAO {

	public  final static String XPACK_SECURITY_USER = "xpack.security.user";

	public enum ManagementDataType {
		billing_namespace,
		billing_bucket,
		object_bucket
	};

	/**
	 * Init indexes
	 * @param collectionTime - collection time
	 */
	public void initIndexes(Date collectionTime);

	/**
	 * Inserts billing namespace info into datastore
	 * @param billingData - billing data
	 * @param collectionTime - collection time
	 */
	public void insert(NamespaceBillingInfo billingData, Date collectionTime);

	/**
	 * Inserts bucket info into datastore
	 * @param bucketResponse - bucket response
	 * @param collectionTime - collection time
	 */
	public void insert(ObjectBuckets bucketResponse, Date collectionTime);

	/**
	 * Purge date collected before a certain date
	 * @param type - management data type
	 * @param collectionTime - collection time
	 * @return Long
	 */
	public Long purgeOldData( ManagementDataType type, Date collectionTime);
}


text:
package ch.iserver.ace.net;

import ch.iserver.ace.CaretUpdateMessage;
import ch.iserver.ace.algorithm.Request;
import ch.iserver.ace.algorithm.Timestamp;

/**
 * A SessionConnection is a network layer interface abstracting the concept of
 * a connection to the session represented by this object. SessionConnections
 * are only used by participants and not by the owner of the session (a
 * different mechanism is used for published sessions).
 */
public interface SessionConnection {

	/**
	 * Gets the participant id of the local user.
	 *
	 * @return the participant id of the local user
	 */
	int getParticipantId();

	/**
	 * Leave the session. After calling this method, the session becomes
	 * stale, i.e. it should not be used anymore.
	 */
	void leave();

	/**
	 * Sends the given request to the session.
	 *
	 * @param request the request to be sent
	 */
	void sendRequest(Request request);

	/**
	 * Sends the given caret update to the session.
	 *
	 * @param message the CaretUpdateMessage to be sent
	 */
	void sendCaretUpdateMessage(CaretUpdateMessage message);

	/**
	 * Sends an acknowledge message to the other site.
	 *
	 * @param siteId the local site id
	 * @param timestamp the local timestamp
	 */
	void sendAcknowledge(int siteId, Timestamp timestamp);

}