text:
package manager

import (
	"fmt"
	"reflect"
	"testing"
	"time"

	"github.com/google/cadvisor/cache/memory"
	"github.com/google/cadvisor/collector"
	"github.com/google/cadvisor/container"
	containertest "github.com/google/cadvisor/container/testing"
	info "github.com/google/cadvisor/info/v1"
	itest "github.com/google/cadvisor/info/v1/test"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

const containerName = "/container"

// Create a containerData instance for a test.
func setupContainerData(t *testing.T, spec info.ContainerSpec) (*containerData, *containertest.MockContainerHandler, *memory.InMemoryCache) {
	mockHandler := containertest.NewMockContainerHandler(containerName)
	mockHandler.On("GetSpec").Return(
		spec,
		nil,
	)
	memoryCache := memory.New(60, nil)
	ret, err := newContainerData(containerName, memoryCache, mockHandler, false, &collector.GenericCollectorManager{}, 60*time.Second, true)
	if err != nil {
		t.Fatal(err)
	}
	return ret, mockHandler, memoryCache
}

// Create a containerData instance for a test and add a default GetSpec mock.
func newTestContainerData(t *testing.T) (*containerData, *containertest.MockContainerHandler, *memory.InMemoryCache) {
	spec := itest.GenerateRandomContainerSpec(4)
	ret, mockHandler, memoryCache := setupContainerData(t, spec)
	return ret, mockHandler, memoryCache
}

func TestUpdateSubcontainers(t *testing.T) {
	subcontainers := []info.ContainerReference{
		{Name: "/container/ee0103"},
		{Name: "/container/abcd"},
		{Name: "/container/something"},
	}
	cd, mockHandler, _ := newTestContainerData(t)
	mockHandler.On("ListContainers", container.ListSelf).Return(
		subcontainers,
		nil,
	)

	err := cd.updateSubcontainers()
	if err != nil {
		t.Fatal(err)
	}

	if len(cd.info.Subcontainers) != len(subcontainers) {
		t.Errorf("Received %v subcontainers, should be %v", len(cd.info.Subcontainers), len(subcontainers))
	}

	for _, sub := range cd.info.Subcontainers {
		found := false
		for _, sub2 := range subcontainers {
			if sub.Name == sub2.Name {
				found = true
			}
		}
		if !found {
			t.Errorf("Received unknown sub container %v", sub)
		}
	}

	mockHandler.AssertExpectations(t)
}

func TestUpdateSubcontainersWithError(t *testing.T) {
	cd, mockHandler, _ := newTestContainerData(t)
	mockHandler.On("ListContainers", container.ListSelf).Return(
		[]info.ContainerReference{},
		fmt.Errorf("some error"),
	)
	mockHandler.On("Exists").Return(true)

	assert.NotNil(t, cd.updateSubcontainers())
	assert.Empty(t, cd.info.Subcontainers, "subcontainers should not be populated on failure")
	mockHandler.AssertExpectations(t)
}

func TestUpdateSubcontainersWithErrorOnDeadContainer(t *testing.T) {
	cd, mockHandler, _ := newTestContainerData(t)
	mockHandler.On("ListContainers", container.ListSelf).Return(
		[]info.ContainerReference{},
		fmt.Errorf("some error"),
	)
	mockHandler.On("Exists").Return(false)

	assert.Nil(t, cd.updateSubcontainers())
	mockHandler.AssertExpectations(t)
}

func checkNumStats(t *testing.T, memoryCache *memory.InMemoryCache, numStats int) {
	var empty time.Time
	stats, err := memoryCache.RecentStats(containerName, empty, empty, -1)
	require.Nil(t, err)
	assert.Len(t, stats, numStats)
}

func TestUpdateStats(t *testing.T) {
	statsList := itest.GenerateRandomStats(1, 4, 1*time.Second)
	stats := statsList[0]

	cd, mockHandler, memoryCache := newTestContainerData(t)
	mockHandler.On("GetStats").Return(
		stats,
		nil,
	)

	err := cd.updateStats()
	if err != nil {
		t.Fatal(err)
	}

	checkNumStats(t, memoryCache, 1)
	mockHandler.AssertExpectations(t)
}

func TestUpdateSpec(t *testing.T) {
	spec := itest.GenerateRandomContainerSpec(4)
	cd, mockHandler, _ := newTestContainerData(t)
	mockHandler.On("GetSpec").Return(
		spec,
		nil,
	)

	err := cd.updateSpec()
	if err != nil {
		t.Fatal(err)
	}

	mockHandler.AssertExpectations(t)
}

func TestGetInfo(t *testing.T) {
	spec := itest.GenerateRandomContainerSpec(4)
	subcontainers := []info.ContainerReference{
		{Name: "/container/ee0103"},
		{Name: "/container/abcd"},
		{Name: "/container/something"},
	}
	cd, mockHandler, _ := setupContainerData(t, spec)
	mockHandler.On("ListContainers", container.ListSelf).Return(
		subcontainers,
		nil,
	)
	mockHandler.Aliases = []string{"a1", "a2"}

	info, err := cd.GetInfo(true)
	if err != nil {
		t.Fatal(err)
	}

	mockHandler.AssertExpectations(t)

	if len(info.Subcontainers) != len(subcontainers) {
		t.Errorf("Received %v subcontainers, should be %v", len(info.Subcontainers), len(subcontainers))
	}

	for _, sub := range info.Subcontainers {
		found := false
		for _, sub2 := range subcontainers {
			if sub.Name == sub2.Name {
				found = true
			}
		}
		if !found {
			t.Errorf("Received unknown sub container %v", sub)
		}
	}

	if !reflect.DeepEqual(spec, info.Spec) {
		t.Errorf("received wrong container spec")
	}

	if info.Name != mockHandler.Name {
		t.Errorf("received wrong container name: received %v; should be %v", info.Name, mockHandler.Name)
	}
}


text:
class Test extends Super{
  public void context() {
    super.method();
  }

  @Override
  public void method() {}
}

class Test1 extends Super {
   @Override
   public void method() {}
}

class U {
  Super t = new Test1();
}

redpajama_set_name: RedPajamaGithub


text:
import {Pipe, PipeTransform} from '@angular/core';

// Tell Angular2 we're creating a Pipe with TypeScript decorators
@Pipe({
  name: 'CollaboratorsPipe'
})
export class CollaboratorsPipe implements PipeTransform {

  // Transform is the new "return function(value, args)" in Angular 1.x
  transform(value, searchText : String) {

    if(value && searchText) {
      return value.filter(collaborator =>  collaborator.isMatch(searchText) );
    } else {
      return value;
    }
  }
}


text:
<?php
namespace Metaregistrar\EPP;
/**
 * The EPP Contact Handle Object
 *
 * This will hold the complete contact info the provider can receive and give you
 *
 *
 *
 */

class eppContactHandle {
    const CONTACT_TYPE_REGISTRANT = 'reg';
    const CONTACT_TYPE_ADMIN = 'admin';
    const CONTACT_TYPE_TECH = 'tech';
    const CONTACT_TYPE_BILLING = 'billing';
    /**
     * Registry handle of contact
     * @var string
     */
    private $contactHandle;
    /**
     * Type of contact: ADMIN, TECH, BILLING
     * @var string
     */
    private $contactType;
    /**
     * Authcode to retrieve contact information
     * @var string
     */
    private $password=null;

    /**
     *
     * @param string $contactHandle
     * @param string $contactType
     * @throws eppException
     */
    public function  __construct($contactHandle, $contactType = null) {
        $this->setContactHandle($contactHandle);
        if ($contactType) {
            $this->setContactType($contactType);
        }
        if (($contactType != null) && ($contactType != self::CONTACT_TYPE_ADMIN) && ($contactType != self::CONTACT_TYPE_REGISTRANT) && ($contactType != self::CONTACT_TYPE_BILLING) && ($contactType != self::CONTACT_TYPE_TECH)) {
            throw new eppException('Invalid contact type: ' . $contactType);
        }
    }

    /**
     * Gets the contact handle
     * @return string
     */
    public function getContactHandle() {
        return $this->contactHandle;
    }

    /**
     * Set the handle of the desired contact
     * @param string $contactHandle
     * @throws eppException
     */
    public function setContactHandle($contactHandle) {
        if (!strlen($contactHandle)) {
            throw new eppException('Contact handle specified is not valid: ' . $contactHandle);
        }
        $this->contactHandle = $contactHandle;
    }

    /**
     * Gets the contact handle
     * @return string
     */
    public function getContactType() {
        return $this->contactType;
    }

    /**
     * Sets the contact type
     * @param string $contactType
     * @return void
     */
    public function setContactType($contactType) {
        $this->contactType = $contactType;
    }

    /**
     * Sets the password
     *
     * **NOTE** This is not used by at the moment, but they do require it to be given
     * @param string $password
     * @return void
     */

    public function setPassword($password) {
        $this->password = htmlspecialchars($password, ENT_COMPAT, "UTF-8");
    }

    /**
     * Gets the password
     * @return string
     */
    public function getPassword() {
        return $this->password;
    }

}


text:
@interface CMDQueryStringReader : NSObject

- (instancetype)initWithString:(NSString *)string;

- (NSDictionary *)dictionaryValue;

@end


text:
extern "C" {
#endif

struct tm* gmtime_r(const time_t* timep, struct tm* result);

struct tm* localtime_r(const time_t* timep, struct tm* result);

const char* strptime(const char* buf, const char* format, struct tm* tm);

time_t timegm(struct tm* tm);

#ifdef __cplusplus
}  // extern "C"
#endif

#endif  // CRASHPAD_COMPAT_WIN_TIME_H_


text:
<?php

class Result {

	private $_successFail = false;
	private $_successData = null;
	private $_errorMessages = array();

	public function addDbError( $pdoStatement ) {

		if ( !empty( $pdoStatement->errorInfo()[2] ) ) {
			$this->addError( $pdoStatement->errorInfo()[2] );
		}
		else {
			$this->addError( 'Internal database error.' );
		}

	}

	public function addError( $errorMsg ) {

		$this->_errorMessages[] = $errorMsg;

	}

	public function addErrors( $errorMessages ) {

		if ( is_array( $errorMessages ) ) {

			array_merge( $errorMessages, $this->_errorMessages );

		}

	}

	public function addSuccessData( $data ) {

		$this->_successData[] = $data;

	}

	public function getErrors() {

		return $this->_errorMessages;

	}

	public function getSuccessData() {

		return $this->_successData;
	}

	public function isSuccess() {

		if ( $this->_successFail || !empty( $this->_successData ) ) {
			return true;
		}
		else {
			return false;
		}

	}

	public function setSuccessFail( $setter ) {

		$this->_successFail = ( bool ) $setter;

	}

} // Result class

?>


text:
/**
 * Created by braveliu on 2017/4/18
 * Function:
 * Desc:
 */
import {StyleSheet} from 'react-native';
import {Colors} from '../../../resource/';

export default StyleSheet.create({
    image_bottom_menu:{
        height:50,
        width:50,
        marginBottom:10,
    },
    view_menu_container:{
        flexDirection:'row',
        justifyContent:'space-around',
        paddingTop:16
    },
    text_menu_title:{
        color:'white',
        fontSize:14
    },
    view_menu_item_container:{
        justifyContent:'center',
        alignItems:'center',
    }

})


text:
title: Blog
layout: post
author: nav.buttar
permalink: /-daily blogs-/
source-id: 1DVz62AJyCSIYFz0E2zB3BmL9y8FelA5bQ3uX6BYUn8I
published: true
---
**Title-Codecademy Diary**                                              ** Date-26/3/17**

**Target-**To Keep a daily blog about my codecademy work.

Day 1 (The lesson)

Today I achieved my target of 35% and I think it went well as I was working on a new topic but I managed to get to grips with it well and after a while I managed to get a lot of work done. However it was hard as I could not understand some of the language as I was looking at a new topic however I could improve this by reading the instruction in detail to help me understand more about the topic and get even more work done.

Day 2

I definitely found things easier coming back to the ocde as I had only just done it a day before and I remembered things better as it was fresh within my memory and I think I also got more work done in 15 minutes than i have before on codecademy when I have not done it the day before so I think that if I continue this pattern I will make more progress on codecademy.

Day 3

I m very happy with this method of 10 minutes a day as I think I am making a lot more progress as the work is always fresh in my mind and it is easier to come back to and work becomes more easier however in only do about 10-15 minutes of work a day so maybe I could do some more however Mr Keen said it was enough and as long as I am making progress that is what matters.

Day 4

Today after doing codecademy I further realized why this method is so effective and Now I know the benefit that i will gain if I continue to do this method I and I really fell by doing this it will really help me. I think I am making great progress and today I did 20 minutes of work as this was a target that would also help me.

Day 5

Now I really believe this method does not have a knock on effect as all the days I have been working on codecademy I think that I remember everything that I have done and I can work quickly and efficiently. I think if I keep this process going then soon I will move on to make a battleship.


text:
import inputs = require('./inputs');
import Q = require('q');
import csm = require('./credstore');
import argm = require('./arguments');
var trace = require('./trace');

export interface ICredentials {
    type: string;
    populated: boolean;
    fromString(creds: string): ICredentials;
    toString(): string;
    promptCredentials(): Q.Promise<ICredentials>;
}

export class PatCredentials implements ICredentials {
    constructor() {
        this.type = 'pat';
    }

    public populated: boolean;
    public type: string;
    public token: string;

    public fromString(creds: string): ICredentials {
        // TODO: validate - it has a specific format
        this.token = creds.split(':')[1];
        this.populated = true;
        return this;
    }

    public toString(): string {
        return this.type + ':' + this.token;
    }

    public promptCredentials(): Q.Promise<ICredentials> {
        trace('PatCredentials.promptCredentials');
        var credInputs = [ argm.PAT ];

        return inputs.Qprompt(credInputs, []).then((result) => {
            this.token = result['token'];
            return this;
        });
    }
}

export class BasicCredentials implements ICredentials {
    constructor() {
        this.type = 'basic';
    }

    public populated: boolean;
    public type: string;
    public username: string;
    public password: string;

    public fromString(creds: string): ICredentials {
        var p = creds.split(':');
        this.username = p[1];
        this.password = p[2];
        this.populated = true;
        return this;
    }

    public toString(): string {
        return this.type + ':' + this.username + ':' + this.password;
    }

    public promptCredentials(): Q.Promise<ICredentials> {
        trace('BasicCredentials.promptCredentials');
        var credInputs = [ argm.USERNAME, argm.PASSWORD ];

        return inputs.Qprompt(credInputs, []).then((result) => {
            this.username = result['username'];
            this.password = result['password'];
            return this;
        });
    }
}

export function getCredentials(url: string, authType: string): Q.Promise<ICredentials> {
    trace('auth.getCredentials');
    var defer = Q.defer<ICredentials>();

    // TODO: support other credential types

    var creds: ICredentials = null;
    return this.getCachedCredentials(url)
    .then((cachedData: string) => {
        var type = cachedData.split(':')[0] || authType;
        switch (type) {
            case 'basic':
                creds = new BasicCredentials();
                break;

            case 'pat':
                creds = new PatCredentials();
                break;

            default:
                throw new Error('Unsupported auth type: ' + type);
        }
        return cachedData ? creds.fromString(cachedData) : creds;
    })
    .then((creds: ICredentials) => {
        return creds.populated ? creds : creds.promptCredentials();
    });

    return <Q.Promise<ICredentials>>defer.promise;
}

export function getCachedCredentials(url: string): Q.Promise<string> {
    trace('auth.getCachedCredentials');
    var defer = Q.defer<string>();

    if (process.env['TFS_BYPASS_CACHE']) {
         trace('Skipping checking cache for credentials');
        defer.resolve('');
    }

    var cs: csm.ICredentialStore = csm.getCredentialStore('tfx');
    cs.getCredential(url, 'allusers')
    .then((cred: string) => {
        trace('Retrieved credentials from cache');
        defer.resolve(cred);
    })
    .fail((err) => {
        trace('No credentials found in cache');
        defer.resolve('');
    });

    return <Q.Promise<string>>defer.promise;
}


text:
require 'pp'

module Omnibus
  module Overrides
    include Logging

    DEFAULT_OVERRIDE_FILE_NAME = 'omnibus.overrides'

    class << self
      # Parses a file of override information into a Hash.
      #
      # Each line of the file must be of the form
      #
      #
      #     <package_name> <version>
      #
      # where the two pieces of data are separated by whitespace.
      #
      # @param file [String] the path to an overrides file
      # @return [Hash, nil]
      def parse_file(file)
        if file
          File.readlines(file).reduce({}) do |acc, line|
            info = line.split

            unless info.count == 2
              raise ArgumentError, "Invalid overrides line: '#{line.chomp}'"
            end

            package, version = info

            if acc[package]
              raise ArgumentError, "Multiple overrides present for '#{package}' in overrides file #{file}!"
            end

            acc[package] = version
            acc
          end
        else
          nil
        end
      end

      # Return the full path to an overrides file, or +nil+ if no such
      # file exists.
      def resolve_override_file
        file = ENV['OMNIBUS_OVERRIDE_FILE'] || DEFAULT_OVERRIDE_FILE_NAME
        path = File.expand_path(file)
        File.exist?(path) ? path : nil
      end

      # Return a hash of override information.  If no such information
      # can be found, the hash will be empty
      #
      # @return [Hash]
      def overrides
        file = resolve_override_file
        overrides = parse_file(file)

        if overrides
          log.info(log_key) do
            out = "Using overrides from #{resolve_override_file}\n"
            out << overrides.pretty_inspect
            out
          end
        end

        overrides || {}
      end
    end
  end
end


text:
namespace adbase {
namespace head {
// {{{ Interface::Interface()

Interface::Interface() {

}

// }}}
// {{{ Interface::~Interface()

Interface::~Interface() {

}

// }}}
// {{{ void Interface::setReadHandler()

void Interface::setReadHandler(const ReadHandler& readHandler) {
	_readHandler = readHandler;
}

// }}}
// {{{ const ReadHandler& Interface::getReadHandler()

const ReadHandler& Interface::getReadHandler() {
	return _readHandler;
}

// }}}
}
}


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/html; charset=utf-8" />
<title>
  Class: Jammit::Controller

    — Jammit

</title>

  <link rel="stylesheet" href="../css/style.css" type="text/css" charset="utf-8" />

  <link rel="stylesheet" href="../css/common.css" type="text/css" charset="utf-8" />

    Index (C) »
    Jammit
     »
    Controller

(no frames)

      Class List

      Method List

      File List

Class: Jammit::Controller

Inherits:

      ActionController::Base

Object

ActionController::Base

Jammit::Controller

        show all

Defined in:

lib/jammit/controller.rb

Overview

The JammitController is added to your Rails application when the Gem is
loaded. It takes responsibility for /assets, and dynamically packages any
missing or uncached asset packages.

Constant Summary

VALID_FORMATS =

[:css, :js]

SUFFIX_STRIPPER =

/-(datauri|mhtml)\Z/

NOT_FOUND_PATH =

"#{Jammit.public_root}/404.html"

      Instance Method Summary
      (collapse)

      - (Object) cache_package

  private

Tells the Jammit::Packager to cache and gzip an asset package.

      - (Object) generate_stylesheets

  private

If we’re generating MHTML/CSS, return a stylesheet with the absolute request URL to the client, and cache a version with the timestamped cache URL swapped in.

      - (Object) package

The “package” action receives all requests for asset packages that haven’t yet been cached.

      - (Object) package_not_found

  private

Render the 404 page, if one exists, for any packages that don’t.

      - (Object) parse_request

  private

Extracts the package name, extension (:css, :js), and variant (:datauri, :mhtml) from the incoming URL.

      - (Object) prefix_url(path)

  private

Generate the complete, timestamped, MHTML url — if we’re rendering a dynamic MHTML package, we’ll need to put one URL in the response, and a different one into the cached package.

Instance Method Details

    - (<tt>Object</tt>) cache_package  (private)

Tells the Jammit::Packager to cache and gzip an asset package. We can’t
just use the built-in “cache_page” because we need to ensure that
the timestamp that ends up in the MHTML is also on the cached file.

41
42
43
44

# File 'lib/jammit/controller.rb', line 41

def cache_package
  dir = File.join(page_cache_directory, Jammit.package_path)
  Jammit.packager.cache(@package, @extension, @contents, dir, @variant, @mtime)
end

    - (<tt>Object</tt>) generate_stylesheets  (private)

If we’re generating MHTML/CSS, return a stylesheet with the absolute
request URL to the client, and cache a version with the timestamped cache
URL swapped in.

57
58
59
60
61
62
63
64
65

# File 'lib/jammit/controller.rb', line 57

def generate_stylesheets
  return @contents = Jammit.packager.pack_stylesheets(@package, @variant) unless @variant == :mhtml
  @mtime      = Time.now
  request_url = prefix_url(request.fullpath)
  cached_url  = prefix_url(Jammit.asset_url(@package, @extension, @variant, @mtime))
  css         = Jammit.packager.pack_stylesheets(@package, @variant, request_url)
  @contents   = css.gsub(request_url, cached_url) if perform_caching
  css
end

    - (<tt>Object</tt>) package

The “package” action receives all requests for asset packages that haven’t
yet been cached. The package will be built, cached, and gzipped.

19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

# File 'lib/jammit/controller.rb', line 19

def package
  parse_request
  template_ext = Jammit.template_extension.to_sym
  case @extension
  when :js
    render :js => (@contents = Jammit.packager.pack_javascripts(@package))
  when template_ext
    render :js => (@contents = Jammit.packager.pack_templates(@package))
  when :css
    render :text => generate_stylesheets, :content_type => 'text/css'
  end
  cache_package if perform_caching && (@extension != template_ext)
rescue Jammit::PackageNotFound
  package_not_found
end

    - (<tt>Object</tt>) package_not_found  (private)

Render the 404 page, if one exists, for any packages that don’t.

82
83
84
85

# File 'lib/jammit/controller.rb', line 82

def package_not_found
  return render(:file => NOT_FOUND_PATH, :status => 404) if File.exists?(NOT_FOUND_PATH)
  render :text => "<h1>404: \"#{@package}\" asset package not found.</h1>", :status => 404
end

    - (<tt>Object</tt>) parse_request  (private)

Extracts the package name, extension (:css, :js), and variant (:datauri,
:mhtml) from the incoming URL.

Raises:

        (<tt>PackageNotFound</tt>)

69
70
71
72
73
74
75
76
77
78
79

# File 'lib/jammit/controller.rb', line 69

def parse_request
  pack       = params[:package]
  @extension = params[:extension].to_sym
  raise PackageNotFound unless (VALID_FORMATS + [Jammit.template_extension.to_sym]).include?(@extension)
  if Jammit.embed_assets
    suffix_match = pack.match(SUFFIX_STRIPPER)
    @variant = Jammit.embed_assets && suffix_match && suffix_match[1].to_sym
    pack.sub!(SUFFIX_STRIPPER, '')
  end
  @package = pack.to_sym
end

    - (<tt>Object</tt>) prefix_url(path)  (private)

Generate the complete, timestamped, MHTML url — if we’re rendering a
dynamic MHTML package, we’ll need to put one URL in the response, and a
different one into the cached package.

49
50
51
52

# File 'lib/jammit/controller.rb', line 49

def prefix_url(path)
  host = request.port == 80 ? request.host : request.host_with_port
  "#{request.protocol}#{host}#{path}"
end

  Generated on Wed Oct 28 12:19:04 2015 by
  yard
  0.8.7.6 (ruby-2.1.3).


text:
<?xml version="1.0" encoding="UTF-8"?>
<Tokens version="1.0">
	<File path="Classes/AWSEC2InstanceStateChange.html">

		<Token>
			<TokenIdentifier>//apple_ref/occ/cl/AWSEC2InstanceStateChange</TokenIdentifier>
			<Abstract type="html">
Describes an instance state change.
</Abstract>
			<DeclaredIn>AWSEC2Model.h</DeclaredIn>

			<NodeRef refid="617"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/AWSEC2InstanceStateChange/setCurrentState:</TokenIdentifier>
			<Abstract type="html">
The current state of the instance.
</Abstract>
			<DeclaredIn>AWSEC2Model.h</DeclaredIn>

			<Declaration>@property (nonatomic, strong) AWSEC2InstanceState *currentState</Declaration>

			<Anchor>//api/name/currentState</Anchor>
            <NodeRef refid="617"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/AWSEC2InstanceStateChange/currentState</TokenIdentifier>
			<Abstract type="html">
The current state of the instance.
</Abstract>
			<DeclaredIn>AWSEC2Model.h</DeclaredIn>

			<Declaration>@property (nonatomic, strong) AWSEC2InstanceState *currentState</Declaration>

			<Anchor>//api/name/currentState</Anchor>
            <NodeRef refid="617"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/AWSEC2InstanceStateChange/currentState</TokenIdentifier>
			<Abstract type="html">
The current state of the instance.
</Abstract>
			<DeclaredIn>AWSEC2Model.h</DeclaredIn>

			<Declaration>@property (nonatomic, strong) AWSEC2InstanceState *currentState</Declaration>

			<Anchor>//api/name/currentState</Anchor>
            <NodeRef refid="617"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/AWSEC2InstanceStateChange/setInstanceId:</TokenIdentifier>
			<Abstract type="html">
The ID of the instance.
</Abstract>
			<DeclaredIn>AWSEC2Model.h</DeclaredIn>

			<Declaration>@property (nonatomic, strong) NSString *instanceId</Declaration>

			<Anchor>//api/name/instanceId</Anchor>
            <NodeRef refid="617"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/AWSEC2InstanceStateChange/instanceId</TokenIdentifier>
			<Abstract type="html">
The ID of the instance.
</Abstract>
			<DeclaredIn>AWSEC2Model.h</DeclaredIn>

			<Declaration>@property (nonatomic, strong) NSString *instanceId</Declaration>

			<Anchor>//api/name/instanceId</Anchor>
            <NodeRef refid="617"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/AWSEC2InstanceStateChange/instanceId</TokenIdentifier>
			<Abstract type="html">
The ID of the instance.
</Abstract>
			<DeclaredIn>AWSEC2Model.h</DeclaredIn>

			<Declaration>@property (nonatomic, strong) NSString *instanceId</Declaration>

			<Anchor>//api/name/instanceId</Anchor>
            <NodeRef refid="617"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/AWSEC2InstanceStateChange/setPreviousState:</TokenIdentifier>
			<Abstract type="html">
The previous state of the instance.
</Abstract>
			<DeclaredIn>AWSEC2Model.h</DeclaredIn>

			<Declaration>@property (nonatomic, strong) AWSEC2InstanceState *previousState</Declaration>

			<Anchor>//api/name/previousState</Anchor>
            <NodeRef refid="617"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/AWSEC2InstanceStateChange/previousState</TokenIdentifier>
			<Abstract type="html">
The previous state of the instance.
</Abstract>
			<DeclaredIn>AWSEC2Model.h</DeclaredIn>

			<Declaration>@property (nonatomic, strong) AWSEC2InstanceState *previousState</Declaration>

			<Anchor>//api/name/previousState</Anchor>
            <NodeRef refid="617"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/AWSEC2InstanceStateChange/previousState</TokenIdentifier>
			<Abstract type="html">
The previous state of the instance.
</Abstract>
			<DeclaredIn>AWSEC2Model.h</DeclaredIn>

			<Declaration>@property (nonatomic, strong) AWSEC2InstanceState *previousState</Declaration>

			<Anchor>//api/name/previousState</Anchor>
            <NodeRef refid="617"/>
		</Token>

	</File>
</Tokens>


text:
import fs from 'fs';
import path from 'path';
import crypto from 'crypto';
import multiparty from 'multiparty';

const MULTIPARTY_REG = /^multipart\/(form-data|related);\s*boundary=(?:"([^"]+)"|([^;]+))$/i;

export default class extends THINK.Middleware {

    run(data) {
        if (!this.http.req.readable) {
            return Promise.resolve();
        }
        //file upload by form or FormData
        //can not use http.type method
        if (MULTIPARTY_REG.test(this.http.headers['content-type'])) {
            return this.postFile();
        } else if (this.http.req.headers[THINK.config('post_ajax_filename_header')]) {
            return this.ajaxFile();
        }

        return Promise.resolve(data);
    }

    postFile() {
        //make upload file path
        let uploadDir = THINK.config('post_file_temp_path');
        if (!THINK.isDir(uploadDir)) {
            THINK.mkDir(uploadDir);
        }
        let deferred = THINK.getDefer();

        let form = new multiparty.Form({
            maxFieldsSize: THINK.config('post_max_fields_size'),
            maxFields: THINK.config('post_max_fields'),
            maxFilesSize: THINK.config('post_max_file_size'),
            uploadDir: uploadDir
        });
        //support for file with multiple="multiple"
        let files = this.http._file;
        form.on('file', (name, value) => {
            if (name in files) {
                if (!THINK.isArray(files[name])) {
                    files[name] = [files[name]];
                }
                files[name].push(value);
            } else {
                files[name] = value;
            }
        });
        form.on('field', (name, value) => {
            this.http._post[name] = value;
        });
        //有错误后直接拒绝当前请求
        form.on('error', (err) => deferred.reject(err));
        form.on('close', () => {
            deferred.resolve();
        });
        form.parse(this.http.req);

        return deferred.promise;
    }

    ajaxFile() {
        let filename = this.http.header(THINK.config('post_ajax_filename_header'));
        let name = crypto.randomBytes(20).toString('base64').replace(/\+/g, '_').replace(/\//g, '_');

        //make upload file path
        let filepath = THINK.config('post_file_temp_path');
        if (!THINK.isDir(filepath)) {
            THINK.mkDir(filepath);
        }
        filepath += `/${name}${path.extname(filename).slice(0, 5)}`;

        let deferred = THINK.getDefer();
        let stream = fs.createWriteStream(filepath);
        this.http.req.pipe(stream);
        stream.on('error', (err) => deferred.reject(err));
        stream.on('close', () => {
            this.http._file = {
                fieldName: 'file',
                originalFilename: filename,
                path: filepath,
                size: fs.statSync(filepath).size
            };
            deferred.resolve();
        });

        return deferred.promise;
    }

}


text:
title: To cut a long story short
author: alba
layout: post
permalink: /2005/04/07/601/
categories:
  - asides
tags:
  - asides
  - del.icio.us
  - film
  - quicklinks
---
[to cut a long story short][1] – meet the people who make trailers (both good and bad)

 [1]: http://film.guardian.co.uk/features/featurepages/0,4120,1449360,00.html "Guardian Unlimited Film | Features | To cut a long story short"


text:
export {
    OPEN_READONLY,
    OPEN_READWRITE,
    OPEN_CREATE,
    cached,
    RunResult,
    Statement,
    verbose } from 'sqlite3';
import {
    Database as OriginalDatabase
} from 'sqlite3';

export class Database extends OriginalDatabase {
    spatialite(cb: (err: Error) => void): void;
}


text:
/**
(C) Bernhard Zwischenbrugger 2012
GPL, LGPL, MIT Licence, Apache Licence, Copyleft, CC,... choose what you want

This is a simple javascript console.
safari on ios 6, lost the javascript console and if you are on linux or windows
there is no possibility to debug javascript.

If you have a mac use this: https://developer.apple.com/technologies/safari/developer-tools.html
if you have Android 4.x use adb and chrome remote debugger

Update: for iphone you can you
http://debug.phonegap.com/
that's very nice, but the console didn't work for me

This is free software, do with if what you want.
*/
(function() {
        var waterbug=(function (){
                var vararray=[];
                var orientation=0;
                var debugDiv=document.createElement("div");
                debugDiv.style.position="fixed";
                debugDiv.style.right="10px";
                debugDiv.style.bottom="10px";
                debugDiv.style.fontFamily="dejavu sans mono, monospace";
                debugDiv.style.fontSize="11px";
                debugDiv.style.cursor="default";
                debugDiv.style.backgroundColor="mintcream";
                debugDiv.style.minHeight="35%";
                debugDiv.style.maxHeight="45%";
                debugDiv.style.border = "1px solid rgba(0,0,0,0.5)";
                debugDiv.style.boxShadow ='6px 6px 6px -3px rgba(0,0,0,0.7)';

                debugDiv.style.overflow="auto";

                debugDiv.style.letterSpacing="0px";
                debugDiv.style.zIndex="10000";
                debugDiv.style.width="30%";

//              debugDiv.style.display="none";
                var supportsOrientationChange = "onorientationchange" in window,
                orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";

//                window.addEventListener(orientationEvent, function() {
//                        if(window.orientation!=orientation && window.orientation==-90){
//
//				window.scrollTo(1,1);
//                                showValues();
//                        }else{
//                                if(window.orientation!=-90){
//					if(debugDiv.parentNode){
//						document.body.removeChild(debugDiv);
//					}
//                                }
//                        }
//                        horientation=window.orientation;
//                },false);

		//window.onerror=function(msg, url, linenumber){
                window.addEventListener("error", function(error) {
//			alert('Error message: '+error.message+'nURL: '+error.filename+'nLine Number: '+error.lineno)
                        vararray.push({type:"error",message:error});
                        (SITE.properties.options.showConsole) && showValues();

		});

                function showValues(){
			while(debugDiv.firstChild){debugDiv.removeChild(debugDiv.firstChild)};
			document.body.appendChild(debugDiv);
                        debugDiv.style.display="block";
			for(var i=0;i<vararray.length;i++){
				var div=document.createElement("div");
				switch(vararray[i].type){
					case "log":
						for(var j=0;j<vararray[i].message.length;j++){
							var item=formatValue(vararray[i].message[j]);
							item.style.verticalAlign="top";
							item.style.padding="2px";

							div.appendChild(item);
						}
						debugDiv.appendChild(div);
						break;
					case "logError":
						for(var j=0;j<vararray[i].message.length;j++){
							var item=formatValue(vararray[i].message[j]);
							item.style.verticalAlign="top";
							item.style.padding="2px";
							item.style.color="red";

							div.appendChild(item);
						}
						debugDiv.appendChild(div);
						break;
					case "error":
						addSpan(div,vararray[i].message.message,"red");
						addSpan(div," "+vararray[i].message.filename+"  line: "+vararray[i].message.lineno,"gray");
						debugDiv.appendChild(div);
						break;

				}
				div.style.borderBottom="1px solid #eeeeee";
			}
			var evalDiv=document.createElement("div");
			var evalInput=document.createElement("input");
			evalInput.style.border="0px solid red";
			evalInput.style.width="80%";
			evalDiv.style.width="100%";
			evalInput.setAttribute( "autocorrect" , "off");
			evalInput.setAttribute( "autocapitalize" , "none");
			evalInput.style.borderBottom="1px solid #eeeeee";
			evalInput.addEventListener("keyup",function(evt){
				if(evt.keyCode==13){
					try{
						var obj=eval(this.value);
						vararray.push({type:"log",message:[obj]});
					}catch(e){
						vararray.push({type:"error",message:[e]});
					}
					showValues();
				}
			});
			var span=document.createElement("span");
			span.appendChild(document.createTextNode(">"));
			span.style.color="lightblue";
			span.style.fontWeight="bold";
			evalDiv.appendChild(span);
			evalDiv.appendChild(evalInput);
			debugDiv.appendChild(evalDiv);
//			evalDiv.scrollIntoView();  //seams to be buggy
                }
		function formatValue(value){
			switch(typeof(value)){
				case "number":return showNumber(value);
					break;
				case "string":return showString(value);
					break;
				case "object":return showObject(value);
					break;
				default:
					return document.createTextNode(typeof(value));

			}
		}
		function showNumber(value){
			var div=document.createElement("div");
			div.appendChild(document.createTextNode(value));
			div.style.color="blue";
			div.style.display="inline";
			div.style.verticalAlign="top";
			return div;
		}
		function showString(value){
			var div=document.createElement("div");
			div.appendChild(document.createTextNode(value));
			div.style.color="black";
			div.style.display="inline";
			div.style.verticalAlign="top";
			return div;
		}
		function showTheHTML(value){
			var div=document.createElement("div");
			if(value.nodeType===3){  //textnode
				var div=document.createElement("span");
				addSpan(div,value.nodeValue);
				return div;
			}
			var div=document.createElement("div");
			if(value.nodeType===1){  //element
				addSpan(div,"<");
				addSpan(div,value.tagName.toLowerCase(),"purple");
				for(var i=0;i<value.attributes.length;i++){
					addSpan(div," ");
					addSpan(div,value.attributes[i].nodeName,"blue");
					addSpan(div,"='");
					addSpan(div,value.attributes[i].nodeValue,"blue");
					addSpan(div,"'");
				}
				addSpan(div,">");
				for(var i=0;i<value.childNodes.length;i++){
					// div.appendChild(showTheHTML(value.childNodes[i])); //to be continued
				}
				addSpan(div," .... ");
				addSpan(div,"<");
				addSpan(div,value.tagName.toLowerCase(),"purple");
				addSpan(div,">");
			}
                        div.style.color="black";
                        div.style.display="inline";
                        div.style.verticalAlign="top";
                        return div;
		}
		function addSpan(target,text,color){
			var span=document.createElement("span");
			span.appendChild(document.createTextNode(text));
			if(color){
				span.style.color=color;
			}
			target.appendChild(span);
		}

		function showObject(value){
			var div=document.createElement("div");
			if(!value)return div;
			div.style.display="inline";
			if(value && value.nodeType){
				return showTheHTML(value);
			//	return div;
			}
			if(value.length){
				div.appendChild(document.createTextNode("["));
				for(var i=0;i<value.length;i++){
					div.appendChild(formatValue(value[i]));
					if(i<value.length -1){
					div.appendChild(document.createTextNode(","));
					}

				}
				div.style.verticalAlign="top";
				div.appendChild(document.createTextNode("]"));
			}else{
				var objDiv=document.createElement("div");
				var arrow=document.createElement("span");
				arrow.appendChild(document.createTextNode("▶  Object"));
				arrow.style.color="gray";
				objDiv.appendChild(arrow);
				objDiv.style.display="inline";
				arrow.style.fontSize="20px";
				objDiv.theObject=value;
				objDiv.expanded=false;
				objDiv.addEventListener("click",function(evt){
					if(this.expanded){
						this.firstChild.textContent="▶  Object";
						while(this.childNodes.length >1){
							this.removeChild(this.lastChild);
						}
						this.expanded=false;
					}else{
						var x=expandObject(this.theObject);
						this.appendChild(x);
						this.firstChild.textContent="▼  Object";
						this.expanded=true;
					}
					evt.stopPropagation();
				},false);
				div.appendChild(objDiv);
				div.style.display="inline-block";
			}
			return div;
		}
		function expandObject(value){
			var div=document.createElement("div");
			for(var i in value){
				var nameValueDiv=document.createElement("div");
				var nameSpan=document.createElement("span");
				nameSpan.appendChild(document.createTextNode(i+":"));
				nameSpan.style.color="purple";
				nameValueDiv.appendChild(nameSpan);
				if(i!="opener"){  //error prevent
					nameValueDiv.appendChild(formatValue(value[i]));
				}
				nameValueDiv.style.verticalAlign="top";
				nameSpan.style.verticalAlign="top";
//				nameValueDiv.style.display="inline-block";
				div.appendChild(nameValueDiv);
			}
//			div.style.border="1px solid black";
			div.style.marginLeft="14px";
			return div;
		}
                function push(type, obj){
			//if(debugDiv.parentNode)return; //console is open, don't record events
                        vararray.push({type:type,message:obj});
                }
                return {
                        log:function(name, value ){
                                push("log", arguments);
                        },
                        logError:function(name, value ){
                                push("logError", arguments);
                        },
			show:function(){
				showValues();
			}

                }
        })();
        if ( typeof define === "function" && define.amd ) {
            define(function () { return waterbug; } );
        }
        else {
            window.waterbug = waterbug;
        }
})();


text:
<?php

namespace Components\Tools\Admin\Controllers;

use Components\Tools\Models\Middleware;
use Components\Tools\Helpers\Utils;
use Hubzero\Component\AdminController;
use Hubzero\Config\Registry;
use Filesystem;
use Request;
use Config;
use Notify;
use Route;
use Lang;
use App;

include_once dirname(dirname(__DIR__)) . DS . 'models' . DS . 'middleware.php';

/**
 * Administrative tools controller for zones
 */
class Zones extends AdminController
{
	/**
	 * Determines task being called and attempts to execute it
	 *
	 * @return	void
	 */
	public function execute()
	{
		if (!$this->config->get('zones'))
		{
			App::redirect(Route::url('index.php?option=' . $this->_option, false));
			return;
		}

		$this->registerTask('add', 'edit');
		$this->registerTask('apply', 'save');

		parent::execute();
	}

	/**
	 * Display a list of hosts
	 *
	 * @return  void
	 */
	public function displayTask()
	{
		// Get filters
		$this->view->filters = array(
			'zone' => urldecode(Request::getState(
				$this->_option . '.' . $this->_controller . '.zone',
				'zone',
				''
			)),
			'master' => urldecode(Request::getState(
				$this->_option . '.' . $this->_controller . '.master',
				'master',
				''
			)),
			// Sorting
			'sort' => Request::getState(
				$this->_option . '.' . $this->_controller . '.sort',
				'filter_order',
				'zone'
			),
			'sort_Dir' => Request::getState(
				$this->_option . '.' . $this->_controller . '.sortdir',
				'filter_order_Dir',
				'ASC'
			),
			// Get paging variables
			'limit' => Request::getState(
				$this->_option . '.' . $this->_controller . '.limit',
				'limit',
				Config::get('list_limit'),
				'int'
			),
			'start' => Request::getState(
				$this->_option . '.' . $this->_controller . '.limitstart',
				'limitstart',
				0,
				'int'
			)
		);

		// In case limit has been changed, adjust limitstart accordingly
		$this->view->filters['start'] = ($this->view->filters['limit'] != 0 ? (floor($this->view->filters['start'] / $this->view->filters['limit']) * $this->view->filters['limit']) : 0);

		// Get the middleware
		$model = new Middleware();

		$this->view->total = $model->zones('count', $this->view->filters);

		$this->view->rows  = $model->zones('list', $this->view->filters);

		// Set any errors
		foreach ($this->getErrors() as $error)
		{
			$this->view->setError($error);
		}

		// Display results
		$this->view->display();
	}

	/**
	 * Edit a record
	 *
	 * @param   mixed  $row
	 * @return  void
	 */
	public function editTask($row=null)
	{
		Request::setVar('hidemainmenu', 1);

		// Get the middleware database
		$mwdb = Utils::getMWDBO();

		$mw = new Middleware($mwdb);

		if (!is_object($row))
		{
			// Incoming
			$id = Request::getInt('id', 0);

			$row = new Middleware\Zone($id);
		}

		$this->view->row = $row;

		if (!$this->view->row->exists())
		{
			$this->view->row->set('state', 'down');
		}

		$this->view->row->params = new Registry($this->view->row->get('params'));

		// Set any errors
		foreach ($this->getErrors() as $error)
		{
			$this->view->setError($error);
		}

		// Display results
		$this->view
			->setLayout('edit')
			->display();
	}

	/**
	 * Save changes to a record
	 *
	 * @return  void
	 */
	public function saveTask()
	{
		// Check for request forgeries
		Request::checkToken();

		// Incoming
		$fields = Request::getArray('fields', array(), 'post');
		$params = Request::getArray('zoneparams', array(), 'post');
		$row    = new Middleware\Zone($fields['id']);

		$fields['params'] = json_encode($params);

		$row = new Middleware\Zone($fields['id']);
		if (!$row->bind($fields))
		{
			Notify::error($row->getError());
			return $this->editTask($row);
		}

		// Store new content
		if (!$row->store(true))
		{
			Notify::error($row->getError());
			return $this->editTask($row);
		}

		/*$vl = new \Components\Tools\Tables\ZoneLocations($mwdb);
		$vl->deleteByZone($row->id);

		$locations = Request::getArray('locations', array(), 'post');
		foreach ($locations as $location)
		{
			$vl = new \Components\Tools\Tables\ZoneLocations($mwdb);
			$vl->zone_id = $row->id;
			$vl->location = $location;
			if (!$vl->check())
			{
				Notify::error($vl->getError());
				return $this->editTask($row);
			}
			if (!$vl->store())
			{
				Notify::error($vl->getError());
				return $this->editTask($row);
			}
		}*/
		Notify::success(Lang::txt('COM_TOOLS_ITEM_SAVED'));

		if ($this->getTask() == 'apply')
		{
			return $this->editTask($row);
		}

		App::redirect(
			Route::url('index.php?option=' . $this->_option . '&controller=' . $this->_controller, false)
		);
	}

	/**
	 * Toggle a zone's state
	 *
	 * @return     void
	 */
	public function stateTask()
	{
		// Check for request forgeries
		Request::checkToken('get');

		// Incoming
		$id = Request::getInt('id', 0);
		$state = strtolower(Request::getWord('state', 'up'));

		if ($state != 'up' && $state != 'down')
		{
			App::redirect(
				Route::url('index.php?option=' . $this->_option . '&controller=' . $this->_controller, false)
			);
			return;
		}

		// Get the middleware database
		$mwdb = Utils::getMWDBO();

		$row = new \Components\Tools\Tables\Zones($mwdb);
		if ($row->load($id))
		{
			$row->state = $state;
			if (!$row->store())
			{
				Notify::error(Lang::txt('COM_TOOLS_ERROR_STATE_UPDATE_FAILED'));
			}
		}

		App::redirect(
			Route::url('index.php?option=' . $this->_option . '&controller=' . $this->_controller, false)
		);
	}

	/**
	 * Delete one or more records
	 *
	 * @return     void
	 */
	public function removeTask()
	{
		// Check for request forgeries
		Request::checkToken();

		// Incoming
		$ids = Request::getArray('id', array());

		$mwdb = Utils::getMWDBO();

		if (count($ids) > 0)
		{
			$row = new \Components\Tools\Tables\Zones($mwdb);

			// Loop through each ID
			foreach ($ids as $id)
			{
				if (!$row->delete(intval($id)))
				{
					throw new \Exception($row->getError(), 500);
				}
			}
		}

		App::redirect(
			Route::url('index.php?option=' . $this->_option . '&controller=' . $this->_controller, false),
			Lang::txt('COM_TOOLS_ITEM_DELETED'),
			'message'
		);
	}

	/**
	 * Method to set the default property for a zone
	 *
	 * @return     void
	 */
	public function defaultTask()
	{
		// Get item to default from request
		$id = Request::getArray('id', [], '', 'array');

		if (empty($id))
		{
			App::abort(404, Lang::txt('COM_TOOLS_ERROR_MISSING_ID'));
		}

		// Get the middleware database
		$mwdb = Utils::getMWDBO();
		$row  = new \Components\Tools\Tables\Zones($mwdb);

		if ($row->load($id[0]))
		{
			// Get rid of the current default
			$default = new \Components\Tools\Tables\Zones($mwdb);
			$default->load(['is_default' => 1]);
			$default->is_default = 0;
			if (!$default->store())
			{
				App::abort(500, Lang::txt('COM_TOOLS_ERROR_DEFAULT_UPDATE_FAILED'));
			}

			// Set a new default
			$row->is_default = 1;
			if (!$row->store())
			{
				App::abort(500, Lang::txt('COM_TOOLS_ERROR_DEFAULT_UPDATE_FAILED'));
			}
		}

		App::redirect(Route::url('index.php?option=' . $this->_option . '&controller=' . $this->_controller, false));
	}

	/**
	 * Upload a file to the wiki via AJAX
	 *
	 * @return  string
	 */
	public function ajaxUploadTask()
	{
		// Check for request forgeries
		Request::checkToken(['get', 'post']);

		// Ensure we have an ID to work with
		$id = Request::getInt('id', 0);
		if (!$id)
		{
			echo json_encode(array('error' => Lang::txt('COM_TOOLS_ERROR_MISSING_ID')));
			return;
		}

		$zone = Middleware\Zone::getInstance($id);

		// Build the path
		$path = $zone->logo('path');

		if (!$path)
		{
			echo json_encode(array('error' => $this->getError()));
			return;
		}

		// allowed extensions for uplaod
		$allowedExtensions = array('png','jpeg','jpg','gif');

		// max upload size
		$sizeLimit = $this->config->get('maxAllowed', 40000000);

		// get the file
		if (isset($_GET['qqfile']))
		{
			$stream = true;
			$file = $_GET['qqfile'];
			$size = (int) $_SERVER["CONTENT_LENGTH"];
		}
		elseif (isset($_FILES['qqfile']))
		{
			$stream = false;
			$file = $_FILES['qqfile']['name'];
			$size = (int) $_FILES['qqfile']['size'];
		}
		else
		{
			echo json_encode(array('error' => Lang::txt('COM_TOOLS_ERROR_NO_FILE')));
			return;
		}

		if (!is_dir($path))
		{
			if (!Filesystem::makeDirectory($path))
			{
				echo json_encode(array('error' => Lang::txt('COM_TOOLS_ERROR_UNABLE_TO_CREATE_UPLOAD_PATH')));
				return;
			}
		}

		if (!is_writable($path))
		{
			echo json_encode(array('error' => Lang::txt('COM_TOOLS_ERROR_DIRECTORY_NOT_WRITABLE')));
			return;
		}

		// check to make sure we have a file and its not too big
		if ($size == 0)
		{
			echo json_encode(array('error' => Lang::txt('COM_TOOLS_ERROR_EMPTY_FILE')));
			return;
		}
		if ($size > $sizeLimit)
		{
			$max = preg_replace('/<abbr \w+=\\"\w+\\">(\w{1,3})<\\/abbr>/', '$1', \Hubzero\Utility\Number::formatBytes($sizeLimit));
			echo json_encode(array('error' => Lang::txt('COM_TOOLS_ERROR_FILE_TOO_LARGE', $max)));
			return;
		}

		// don't overwrite previous files that were uploaded
		$pathinfo = pathinfo($file);
		$filename = $pathinfo['filename'];

		// Make the filename safe
		$filename = urldecode($filename);
		$filename = Filesystem::clean($filename);
		$filename = str_replace(' ', '_', $filename);

		$ext = $pathinfo['extension'];
		if (!in_array(strtolower($ext), $allowedExtensions))
		{
			echo json_encode(array('error' => Lang::txt('COM_TOOLS_ERROR_INVALID_FILE_TYPE')));
			return;
		}

		$file = $path . DS . $filename . '.' . $ext;

		if ($stream)
		{
			//read the php input stream to upload file
			$input = fopen("php://input", "r");
			$temp = tmpfile();
			$realSize = stream_copy_to_stream($input, $temp);
			fclose($input);

			//move from temp location to target location which is user folder
			$target = fopen($file, "w");
			fseek($temp, 0, SEEK_SET);
			stream_copy_to_stream($temp, $target);
			fclose($target);
		}
		else
		{
			move_uploaded_file($_FILES['qqfile']['tmp_name'], $file);
		}

		// Do we have an old file we're replacing?
		if ($curfile = $zone->get('picture'))
		{
			// Remove old image
			if (file_exists($path . DS . $curfile))
			{
				if (!Filesystem::delete($path . DS . $curfile))
				{
					echo json_encode(array('error' => Lang::txt('COM_TOOLS_ERROR_UNABLE_TO_DELETE_FILE')));
					return;
				}
			}
		}

		$zone->set('picture', $filename . '.' . $ext);
		if (!$zone->store())
		{
			echo json_encode(array('error' => $zone->getError()));
			return;
		}

		$this_size = filesize($file);
		list($width, $height, $type, $attr) = getimagesize($file);

		//echo result
		echo json_encode(array(
			'success'   => true,
			'file'      => $filename . '.' . $ext,
			'directory' => str_replace(PATH_APP, '', $path),
			'id'        => $id,
			'size'      => \Hubzero\Utility\Number::formatBytes($this_size),
			'width'     => $width,
			'height'    => $height
		));
	}

	/**
	 * Upload a file
	 *
	 * @return  void
	 */
	public function uploadTask()
	{
		if (Request::getInt('no_html', 0))
		{
			return $this->ajaxUploadTask();
		}

		// Check for request forgeries
		Request::checkToken();

		// Incoming
		$id = Request::getInt('id', 0);
		if (!$id)
		{
			$this->setError(Lang::txt('COM_COURSES_NO_ID'));
			$this->pictureTask('', $id);
			return;
		}

		$zone = Middleware\Zone::getInstance($id);

		// Build the path
		$path = $zone->logo('path');

		if (!$path)
		{
			$this->pictureTask('', $id);
			return;
		}

		// Incoming file
		$file = Request::getArray('upload', '', 'files');
		if (!$file['name'])
		{
			$this->setError(Lang::txt('COM_TOOLS_ERROR_NO_FILE'));
			$this->pictureTask('', $id);
			return;
		}
		$curfile = Request::getString('curfile', '');

		if (!is_dir($path))
		{
			if (!Filesystem::makeDirectory($path))
			{
				$this->setError(Lang::txt('COM_TOOLS_ERROR_UNABLE_TO_CREATE_UPLOAD_PATH'));
				$this->pictureTask('', $id);
				return;
			}
		}

		// Make the filename safe
		$file['name'] = Filesystem::clean($file['name']);
		$file['name'] = str_replace(' ', '_', $file['name']);

		// Perform the upload
		if (!Filesystem::upload($file['tmp_name'], $path . DS . $file['name']))
		{
			$this->setError(Lang::txt('COM_TOOLS_ERROR_UPLOADING'));
			$file = $curfile;
		}
		else
		{
			// Do we have an old file we're replacing?
			if ($curfile = $zone->get('picture'))
			{
				// Remove old image
				if (file_exists($path . DS . $curfile))
				{
					if (!Filesystem::delete($path . DS . $curfile))
					{
						$this->setError(Lang::txt('COM_TOOLS_ERROR_UNABLE_TO_DELETE_FILE'));
						$this->pictureTask($file['name'], $id);
						return;
					}
				}
			}

			$zone->set('picture', $file['name']);
			if (!$zone->store())
			{
				$this->setError($zone->getError());
			}

			$file = $file['name'];
		}

		// Push through to the image view
		$this->pictureTask($file, $id);
	}

	/**
	 * Upload a file to the wiki via AJAX
	 *
	 * @return  string
	 */
	public function ajaxRemoveTask()
	{
		// Check for request forgeries
		Request::checkToken(['get', 'post']);

		// Ensure we have an ID to work with
		$id = Request::getInt('id', 0);
		if (!$id)
		{
			echo json_encode(array('error' => Lang::txt('COM_TOOLS_ERROR_MISSING_ID')));
			return;
		}

		$zone = Middleware\Zone::getInstance($id);

		// Build the path
		$path = $zone->logo('path');
		if (!$path)
		{
			echo json_encode(array('error' => $this->getError()));
			return;
		}

		$file = $zone->get('picture');

		if (!file_exists($path . DS . $file) or !$file)
		{
			$this->setError(Lang::txt('COM_TOOLS_ERROR_FILE_NOT_FOUND'));
		}
		else
		{
			// Attempt to delete the file
			if (!Filesystem::delete($path . DS . $file))
			{
				echo json_encode(array('error' => Lang::txt('COM_TOOLS_ERROR_UNABLE_TO_DELETE_FILE')));
				return;
			}
		}

		// Instantiate a model, change some info and save
		$zone->set('picture', '');
		if (!$zone->store())
		{
			echo json_encode(array('error' => $zone->getError()));
			return;
		}

		//echo result
		echo json_encode(array(
			'success'   => true,
			'file'      => '',
			'directory' => str_replace(PATH_APP, '', $path),
			'id'        => $id,
			'size'      => 0,
			'width'     => 0,
			'height'    => 0
		));
	}

	/**
	 * Delete a file
	 *
	 * @return  void
	 */
	public function removefileTask()
	{
		if (Request::getInt('no_html', 0))
		{
			return $this->ajaxRemoveTask();
		}

		// Check for request forgeries
		Request::checkToken('get');

		// Incoming member ID
		$id = Request::getInt('id', 0);
		if (!$id)
		{
			$this->setError(Lang::txt('COM_TOOLS_ERROR_MISSING_ID'));
			$this->pictureTask('', $id);
			return;
		}

		$zone = Middleware\Zone::getInstance($id);

		// Build the file path
		$path = $zone->logo('path');
		$file = $zone->get('picture');

		if (!file_exists($path . DS . $file) or !$file)
		{
			$this->setError(Lang::txt('COM_TOOLS_ERROR_FILE_NOT_FOUND'));
		}
		else
		{
			// Attempt to delete the file
			if (!Filesystem::delete($path . DS . $file))
			{
				$this->setError(Lang::txt('COM_TOOLS_ERROR_UNABLE_TO_DELETE_FILE'));
				$this->pictureTask($file, $id);
				return;
			}

			$zone->set('picture', '');
			if (!$zone->store())
			{
				$this->setError($zone->getError());
			}

			$file = '';
		}

		$this->pictureTask($file, $id);
	}

	/**
	 * Display a file and its info
	 *
	 * @param   string   $file  File name
	 * @param   integer  $id    User ID
	 * @return  void
	 */
	public function pictureTask($file='', $id=0)
	{
		// Incoming
		$id = $id ?: Request::getInt('id', 0);

		$this->view->zone = Middleware\Zone::getInstance($id);

		// Set any errors
		foreach ($this->getErrors() as $error)
		{
			$this->view->setError($error);
		}

		// Output the HTML
		$this->view
			->set('config', $this->config)
			->setLayout('picture')
			->display();
	}
}


text:
package com.github.slackey.codecs.types

case class Profile(
  bot_id: Option[String],
  first_name: Option[String],
  last_name: Option[String],
  real_name: Option[String],
  real_name_normalized: Option[String],
  email: Option[String],
  skype: Option[String],
  phone: Option[String],
  image_24: String,
  image_32: String,
  image_48: String,
  image_72: String,
  image_192: String
)


text:
package mgmt

import (
	"github.com/golang/protobuf/proto"
	"github.com/hyperledger/fabric-protos-go/msp"
	"github.com/hyperledger/fabric/bccsp"
	"github.com/pkg/errors"
)

const (
	// Admins is the label for the local MSP admins
	Admins = "Admins"

	// Members is the label for the local MSP members
	Members = "Members"
)

type MSPPrincipalGetter interface {
	// Get returns an MSP principal for the given role
	Get(role string) (*msp.MSPPrincipal, error)
}

func NewLocalMSPPrincipalGetter(cryptoProvider bccsp.BCCSP) MSPPrincipalGetter {
	return &localMSPPrincipalGetter{
		cryptoProvider: cryptoProvider,
	}
}

type localMSPPrincipalGetter struct {
	cryptoProvider bccsp.BCCSP
}

func (m *localMSPPrincipalGetter) Get(role string) (*msp.MSPPrincipal, error) {
	mspid, err := GetLocalMSP(m.cryptoProvider).GetIdentifier()
	if err != nil {
		return nil, errors.WithMessage(err, "could not extract local msp identifier")
	}

	switch role {
	case Admins:
		principalBytes, err := proto.Marshal(&msp.MSPRole{Role: msp.MSPRole_ADMIN, MspIdentifier: mspid})
		if err != nil {
			return nil, errors.Wrap(err, "marshalling failed")
		}

		return &msp.MSPPrincipal{
			PrincipalClassification: msp.MSPPrincipal_ROLE,
			Principal:               principalBytes,
		}, nil
	case Members:
		principalBytes, err := proto.Marshal(&msp.MSPRole{Role: msp.MSPRole_MEMBER, MspIdentifier: mspid})
		if err != nil {
			return nil, errors.Wrap(err, "marshalling failed")
		}

		return &msp.MSPPrincipal{
			PrincipalClassification: msp.MSPPrincipal_ROLE,
			Principal:               principalBytes,
		}, nil
	default:
		return nil, errors.Errorf("MSP Principal role [%s] not recognized", role)
	}
}


text:
#pragma once

#include <chrono>
#include <condition_variable>
#include <future>
#include <map>
#include <thread>

#include <boost/noncopyable.hpp>
#include <folly/dynamic.h>
#include <wangle/client/persistence/LRUInMemoryCache.h>
#include <wangle/client/persistence/PersistentCache.h>
#include <wangle/client/persistence/PersistentCacheCommon.h>

namespace wangle {

/**
 * The underlying persistence layer interface.  Implementations may
 * write to file, db, /dev/null, etc.
 */
template<typename K, typename V>
class CachePersistence {
 public:
  CachePersistence() : persistedVersion_(0) {}

  virtual ~CachePersistence() = default;

  /**
   * Persist a folly::dynamic array of key value pairs at the
   * specified version.  Returns true if persistence succeeded.
   */
  bool persistVersionedData(
      const folly::dynamic& kvPairs, const CacheDataVersion& version) {
    auto result = persist(kvPairs);
    if (result) {
      persistedVersion_ = version;
    }
    return result;
  }

  /**
   * Get the last version of the data that was successfully persisted.
   */
  CacheDataVersion getLastPersistedVersion() const {
    return persistedVersion_;
  }

  /**
   * Force set a persisted version.  This is primarily for when a persistence
   * layer acts as the initial source of data for some version tracking cache.
   */
  void setPersistedVersion(CacheDataVersion version) noexcept {
    persistedVersion_ = version;
  }

  /**
   * Persist a folly::dynamic array of key value pairs.
   * Returns true on success.
   */
  virtual bool persist(const folly::dynamic& kvPairs) noexcept = 0;

  /**
   * Returns a list of key value pairs that are present in this
   * persistence store.
   */
  virtual folly::Optional<folly::dynamic> load() noexcept = 0;

 private:
  CacheDataVersion persistedVersion_;
};

/**
 * A PersistentCache implementation that used a CachePersistence for
 * storage. In memory structure fronts the persistence and the cache
 * operations happen on it. Loading from and syncing to persistence are
 * hidden from clients. Sync to persistence happens asynchronously on
 * a separate thread at a configurable interval. Syncs to persistence
 * on destruction as well.
 *
 * The in memory structure is an EvictingCacheMap which causes this class
 * to evict entries in an LRU fashion.
 *
 * NOTE NOTE NOTE: Although this class aims to be a cache for arbitrary,
 * it relies heavily on folly::toJson, folly::dynamic and convertTo for
 * serialization and deserialization. So It may not suit your need until
 * true support arbitrary types is written.
 */
template<typename K, typename V, typename MutexT = std::mutex>
class LRUPersistentCache : public PersistentCache<K, V>,
                            private boost::noncopyable {
  static_assert(std::is_convertible<K, folly::dynamic>::value &&
                std::is_convertible<V, folly::dynamic>::value,
                "Key and Value types must be convertible to dynamic");

 public:
  /**
   * LRUPersistentCache constructor
   * @param cacheCapacity max number of elements to hold in the cache.
   * @param syncInterval how often to sync to the persistence (in ms).
   * @param nSyncRetries how many times to retry to sync on failure.
   *
   * Loads the cache and starts of the syncer thread that periodically
   * syncs the cache to persistence.
   *
   * If persistence is specified, the cache is initially loaded with the
   * contents from it. If load fails, then cache starts empty.
   *
   * On write failures, the sync will happen again up to nSyncRetries times.
   * Once failed nSyncRetries amount of time, then it will give up and not
   * attempt to sync again until another update occurs.
   *
   * On reaching capacity limit, LRU items are evicted.
   */
  explicit LRUPersistentCache(
    const std::size_t cacheCapacity,
    const std::chrono::milliseconds& syncInterval =
    std::chrono::milliseconds(5000),
    const int nSyncRetries = 3,
    std::unique_ptr<CachePersistence<K, V>> persistence = nullptr
  );

  /**
   * LRUPersistentCache Destructor
   *
   * Signals the syncer thread to stop, waits for any pending syncs to
   * be done.
   */
  ~LRUPersistentCache() override;

  /**
   * Check if there are updates that need to be synced to persistence
   */
  bool hasPendingUpdates();

  /**
   * PersistentCache operations
   */
  folly::Optional<V> get(const K& key) override {
    return cache_.get(key);
  }

  void put(const K& key, const V& val) override {
    cache_.put(key, val);
  }

  bool remove(const K& key) override {
    return cache_.remove(key);
  }

  void clear() override {
    cache_.clear();
  }

  size_t size() override {
    return cache_.size();
  }

  /**
   * Set a new persistence layer on this cache.  This call blocks while the
   * new persistence layer is loaded into the cache.  The load is also
   * done under a lock so multiple calls to this will not stomp on each
   * other.
   */
  void setPersistence(std::unique_ptr<CachePersistence<K, V>> persistence);

 private:
  /**
   * Helper to set persistence that will load the persistence data
   * into memory and optionally sync versions
   */
  void setPersistenceHelper(
    std::unique_ptr<CachePersistence<K, V>> persistence,
    bool syncVersion) noexcept;

  /**
   * Load the contents of the persistence passed to constructor in to the
   * in-memory cache. Failure to read will result in no changes to the
   * in-memory data.  That is, if in-memory entries exist, and loading
   * fails, the in-memory data remains and will sync down to the underlying
   * persistence layer on the next sync.
   *
   * Failure to read inclues IO errors and deserialization errors.
   *
   * @returns the in memory cache's new version
   */
  CacheDataVersion load(CachePersistence<K, V>& persistence) noexcept;

  /**
   * The syncer thread's function. Syncs to the persistence, if necessary,
   * after every syncInterval_ seconds.
   */
  void sync();
  static void* syncThreadMain(void* arg);

  /**
   * Helper to sync routine above that actualy does the serialization
   * and writes to persistence.
   *
   * @returns boolean, true on successful serialization and write to
   *                    persistence, false otherwise
   */
  bool syncNow(CachePersistence<K, V>& persistence);

  /**
   * Helper to get the persistence layer under lock since it will be called
   * by syncer thread and setters call from any thread.
   */
  std::shared_ptr<CachePersistence<K, V>> getPersistence();

 private:

  // Our threadsafe in memory cache
  LRUInMemoryCache<K, V, MutexT> cache_;

  // used to signal syncer thread
  bool stopSyncer_;
  // mutex used to synchronize syncer_ on destruction, tied to stopSyncerCV_
  std::mutex stopSyncerMutex_;
  // condvar used to wakeup syncer on exit
  std::condition_variable stopSyncerCV_;

  // sync interval in milliseconds
  const std::chrono::milliseconds syncInterval_;
  // limit on no. of sync attempts
  const int nSyncRetries_;

  // persistence layer
  // we use a shared pointer since the syncer thread might be operating on
  // it when the client decides to set a new one
  std::shared_ptr<CachePersistence<K, V>> persistence_;
  // for locking access to persistence set/get
  MutexT persistenceLock_;

  // thread for periodic sync
  std::thread syncer_;
};

}

#include <wangle/client/persistence/LRUPersistentCache-inl.h>


text:
Encryption
==========

Rhubarb provides a framework for implementing two types of encryption: two way encryption and one way
or 'hashing'.

Both types of encryption follow the provider pattern: you can set a default hash provider and a default encryption
provider for your application. Systems that require encryption and decryption will use these default providers.

Because making choices about encryption are so critical there are provider engaged by default. You must configure
the provider you want for your encryption before encryption can be used.

Rhubarb includes the following encryption methods as standard:

### Encryption

* Aes256

### Hashing

* Sha512

## Hashing

### Setting the default hash provider

The default hash provider should be set in your application's main module and simply involves calling the static
function `HashProvider::setProviderClassName()`:

~~~ php
HashProvider::setProviderClassName(Sha512HashProvider::class);
~~~

### Creating a hash

While you can instantiate HashProvider classes and use them directly we *strongly recommend* using the default
provider by using:

~~~ php
$hashProvider = HashProvider::getProvider();
~~~

This way if the provider for a project is changed all code using the hash provider starts using the new one
immediately.

To create a hash simply call the `createHash` function:

~~~ php
$hashProvider = HashProvider::getProvider();
$hash = $hashProvider->createHash("stringtobehashed", $salt);
~~~

The second parameter is optional and supplies a salt to the hashing algorithm (if required). If omitted a
random salt will be generated for you.

### Checking hash values

To check if a value matches that of the hash simply call the `compareHash` function:

~~~ php
$hashProvider = HashProvider::getProvider();
$matched = $hashProvider->compareHash($valueToTest, $storedHash);
~~~

This extracts the salt from the stored hash and hashes the comparison value ($valueToTest) and then compares
the two hashes.

`compareHash()` returns true if the hash matches the tested value and false if it does not.

## Encryption

### Setting the default encryption provider

The default encryption provider should also be set by your application's main module and likewise
simply involves calling a static function `EncryptionProvider::setProviderClassName()`:

~~~ php
EncryptionProvider::setProviderClassName("MyAes256EncryptionProvider");
~~~

### Encrypting a value.

In a similar way to hash providers we recommend using the provider pattern to get the encryption provider.

Encrypting is then simply a case of calling the `encrypt` method with the data to be encrypted:

~~~ php
$cipher = EncryptionProvider::getProvider();
$crypt = $cipher->encrypt( "stringtobeencrypted" );
~~~

The `Encrypt` method can take a second parameter which will might be used by the encryption provider to
generate a unique key for the encryption process. This allows you to have a unique key per record rather than
one key for the whole application.

### Decrypting a value.

Decryption is straightforward - simply call `decrypt`

~~~ php
$cipher = EncryptionProvider::getProvider();
$plainText = $cipher->decrypt( "verysecretencryptedstring" );
~~~

If you supplied an additional argument to the `encrypt` method you will need to pass the same arguments here too.

### Creating an encryption provider

Most encryption providers are abstract as two way encryption requires a key. Storage and supply of the key
is a potential weak point that must be carefully thought about in your application. Usually you must extend an
encryption provider and override the `getEncryptionKey()` method:

``` php
class MyAes256EncryptionProvider extends Aes256EncryptionProvider
{
    protected function getEncryptionKey($keySalt = "")
    {
        if (!$keySalt){
            $keySalt = uniqid();
        }

        return sha1($keySalt.microtime());
    }
}
```


text:
class ExportService
  include Singleton

  def start_new_export(user, format)
    Export::CreateExportJob.new(user, format)
  end

  def delete_expired_exports
    Export::MaintainExportsJob.new
  end
end


text:
<?php

class Tampilkan_siswa extends CI_Model{

            function tampilkan_data(){

                        return $this->db->get('el_siswa');

            }

}


text:
from random import randint

from rdflib.namespace import RDF
from rdflib.term import BNode, URIRef

__all__ = ["Container", "Bag", "Seq", "Alt", "NoElementException"]

class Container(object):
    """A class for constructing RDF containers, as per https://www.w3.org/TR/rdf11-mt/#rdf-containers

    Basic usage, creating a ``Bag`` and adding to it::

        >>> from rdflib import Graph, BNode, Literal, Bag
        >>> g = Graph()
        >>> b = Bag(g, BNode(), [Literal("One"), Literal("Two"), Literal("Three")])
        >>> print(g.serialize(format="turtle"))
        @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
        <BLANKLINE>
        [] a rdf:Bag ;
            rdf:_1 "One" ;
            rdf:_2 "Two" ;
            rdf:_3 "Three" .
        <BLANKLINE>
        <BLANKLINE>

        >>> # print out an item using an index reference
        >>> print(b[2])
        Two

        >>> # add a new item
        >>> b.append(Literal("Hello")) # doctest: +ELLIPSIS
        <rdflib.container.Bag object at ...>
        >>> print(g.serialize(format="turtle"))
        @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
        <BLANKLINE>
        [] a rdf:Bag ;
            rdf:_1 "One" ;
            rdf:_2 "Two" ;
            rdf:_3 "Three" ;
            rdf:_4 "Hello" .
        <BLANKLINE>
        <BLANKLINE>

    """

    def __init__(self, graph, uri, seq=[], rtype="Bag"):
        """Creates a Container

        :param graph: a Graph instance
        :param uri: URI or Blank Node of the Container
        :param seq: the elements of the Container
        :param rtype: the type of Container, one of "Bag", "Seq" or "Alt"
        """

        self.graph = graph
        self.uri = uri or BNode()
        self._len = 0
        self._rtype = rtype  # rdf:Bag or rdf:Seq or rdf:Alt

        self.append_multiple(seq)

        # adding triple corresponding to container type
        self.graph.add((self.uri, RDF.type, RDF[self._rtype]))

    def n3(self):

        items = []
        for i in range(len(self)):

            v = self[i + 1]
            items.append(v)

        return "( %s )" % " ".join([a.n3() for a in items])

    def _get_container(self):
        """Returns the URI of the container"""

        return self.uri

    def __len__(self):
        """Number of items in container"""

        return self._len

    def type_of_conatiner(self):
        return self._rtype

    def index(self, item):
        """Returns the 1-based numerical index of the item in the container"""

        pred = self.graph.predicates(self.uri, item)
        if not pred:
            raise ValueError("%s is not in %s" % (item, "container"))
        li_index = URIRef(str(RDF) + "_")

        i = None
        for p in pred:
            i = int(p.replace(li_index, ""))
        return i

    def __getitem__(self, key):
        """Returns item of the container at index key"""

        c = self._get_container()

        assert isinstance(key, int)
        elem_uri = str(RDF) + "_" + str(key)
        if key <= 0 or key > len(self):
            raise KeyError(key)
        v = self.graph.value(c, URIRef(elem_uri))
        if v:
            return v
        else:
            raise KeyError(key)

    def __setitem__(self, key, value):
        """Sets the item at index key or predicate rdf:_key of the container to value"""

        assert isinstance(key, int)

        c = self._get_container()
        elem_uri = str(RDF) + "_" + str(key)
        if key <= 0 or key > len(self):
            raise KeyError(key)

        self.graph.set((c, URIRef(elem_uri), value))

    def __delitem__(self, key):
        """Removing the item with index key or predicate rdf:_key"""

        assert isinstance(key, int)
        if key <= 0 or key > len(self):
            raise KeyError(key)

        graph = self.graph
        container = self.uri
        elem_uri = str(RDF) + "_" + str(key)
        graph.remove((container, URIRef(elem_uri), None))
        for j in range(key + 1, len(self) + 1):
            elem_uri = str(RDF) + "_" + str(j)
            v = graph.value(container, URIRef(elem_uri))
            graph.remove((container, URIRef(elem_uri), v))
            elem_uri = str(RDF) + "_" + str(j - 1)
            graph.add((container, URIRef(elem_uri), v))

        self._len -= 1

    def items(self):
        """Returns a list of all items in the container"""

        l_ = []
        container = self.uri
        i = 1
        while True:
            elem_uri = str(RDF) + "_" + str(i)

            if (container, URIRef(elem_uri), None) in self.graph:
                i += 1
                l_.append(self.graph.value(container, URIRef(elem_uri)))
            else:
                break
        return l_

    def end(self):  #

        # find end index (1-based) of container

        container = self.uri
        i = 1
        while True:
            elem_uri = str(RDF) + "_" + str(i)

            if (container, URIRef(elem_uri), None) in self.graph:
                i += 1
            else:
                return i - 1

    def append(self, item):
        """Adding item to the end of the container"""

        end = self.end()
        elem_uri = str(RDF) + "_" + str(end + 1)
        container = self.uri
        self.graph.add((container, URIRef(elem_uri), item))
        self._len += 1

        return self

    def append_multiple(self, other):
        """Adding multiple elements to the container to the end which are in python list other"""

        end = self.end()  # it should return the last index

        container = self.uri
        for item in other:

            end += 1
            self._len += 1
            elem_uri = str(RDF) + "_" + str(end)
            self.graph.add((container, URIRef(elem_uri), item))

        return self

    def clear(self):
        """Removing all elements from the container"""

        container = self.uri
        graph = self.graph
        i = 1
        while True:
            elem_uri = str(RDF) + "_" + str(i)
            if (container, URIRef(elem_uri), None) in self.graph:
                graph.remove((container, URIRef(elem_uri), None))
                i += 1
            else:
                break
        self._len = 0
        return self

class Bag(Container):
    """Unordered container (no preference order of elements)"""

    def __init__(self, graph, uri, seq=[]):
        Container.__init__(self, graph, uri, seq, "Bag")

class Alt(Container):
    def __init__(self, graph, uri, seq=[]):
        Container.__init__(self, graph, uri, seq, "Alt")

    def anyone(self):
        if len(self) == 0:
            raise NoElementException()
        else:
            p = randint(1, len(self))
            item = self.__getitem__(p)
            return item

class Seq(Container):
    def __init__(self, graph, uri, seq=[]):
        Container.__init__(self, graph, uri, seq, "Seq")

    def add_at_position(self, pos, item):
        assert isinstance(pos, int)
        if pos <= 0 or pos > len(self) + 1:
            raise ValueError("Invalid Position for inserting element in rdf:Seq")

        if pos == len(self) + 1:
            self.append(item)
        else:
            for j in range(len(self), pos - 1, -1):
                container = self._get_container()
                elem_uri = str(RDF) + "_" + str(j)
                v = self.graph.value(container, URIRef(elem_uri))
                self.graph.remove((container, URIRef(elem_uri), v))
                elem_uri = str(RDF) + "_" + str(j + 1)
                self.graph.add((container, URIRef(elem_uri), v))
            elem_uri_pos = str(RDF) + "_" + str(pos)
            self.graph.add((container, URIRef(elem_uri_pos), item))
            self._len += 1
        return self

class NoElementException(Exception):
    def __init__(self, message="rdf:Alt Container is empty"):
        self.message = message

    def __str__(self):
        return self.message


text:
package com.pupu.chat;

public class Protocol {
	public static final String JSON_TYPE = "type";
	public static final String JSON_MSG = "msg";

	public static final String NEW = "new";
	public static final String JOIN = "join";
	public static final String LEAVE = "leave";
	public static final String YOU_MSG = "you_msg";
	public static final String STRANGER_MSG = "stranger_msg";
	public static final String START_TYPING = "start_typing";
	public static final String STOP_TYPING = "stop_typing";
	public static final String TOTAL_USER_COUNT = "total_user_count";
}


text:
@implementation FLCheckMarkTableViewCell

@synthesize checked = _checked;
@synthesize checkMarkGroup = _group;
@synthesize checkedValue = _checkedValue;

- (void) dealloc
{
	FLRelease(_group);
	FLRelease(_checkedValue);
//	  FLRelease(_checkMark);
	FLRelease(_subLabel);
	FLSuperDealloc();
}

- (void) initSubLabel
{
	_subLabel = [[FLLabel alloc] initWithFrame:CGRectZero];
	_subLabel.font	 = [UIFont systemFontOfSize:[UIFont smallSystemFontSize]];
	_subLabel.textColor = [UIColor grayColor];
	_subLabel.backgroundColor = [UIColor clearColor];
	[self addSubview:_subLabel];
}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
	if((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]))
	{
		self.accessoryType = UITableViewCellAccessoryNone;
		self.selectionStyle = UITableViewCellSelectionStyleBlue;
		[self initSubLabel];
	}

	return self;
}

- (void) calculateCellHeightInTable:(UITableView *)tableView
{
	self.cellHeight = 50.0f; // DeviceIsPad() ? 50.0 : 36.0f; // TODO: set with theme.
}

+ (id) checkMarkedTableCell:(NSString*) labelOrNil checked:(BOOL) checked checkedValue:(id) checkedValue
{
	FLCheckMarkTableViewCell* cell = FLAutorelease([[[self class] alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"FLCheckMarkedTableCell"]);
	if(FLStringIsNotEmpty(labelOrNil))
	{
		cell.textLabelText = labelOrNil;
	}
	cell.checkedValue = checkedValue;
	cell.checked = checked;
	return cell;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {

	[super setSelected:selected animated:animated];

	if(selected && self.canEditData)
	{
		self.checked = YES;
	}
}

#define SUBLABEL_INDENT 40

- (void) _showCheckMark:(BOOL) checked
{
	if(checked)
	{
		self.label.selected = YES;
		self.accessoryType = UITableViewCellAccessoryCheckmark;

	}
	else
	{
		self.label.selected = NO;
		self.accessoryType = UITableViewCellAccessoryNone;
	}
}

- (void) updateCellState
{
	if(self.dataSource)
	{
		self.checked = [self.dataSourceObject isEqual:_checkedValue];
	}
}

- (void) layoutSubviews
{
	[super layoutSubviews];

	[self _showCheckMark:self.checked];

	if(_subLabel.text.length > 0)
	{
		CGRect subLabelFrame = self.layoutRect;
		subLabelFrame.origin.x += SUBLABEL_INDENT;
		subLabelFrame.size.width -= SUBLABEL_INDENT;
		subLabelFrame.size.height = 18;
		subLabelFrame.origin.y = self.frame.size.height - subLabelFrame.size.height;

		_subLabel.frameOptimizedForSize = subLabelFrame;

		CGRect textFrame = self.label.frame;
		textFrame.origin.y -= 4;
		self.label.frameOptimizedForSize = textFrame;
	}
}

- (BOOL) checked
{
	return _checked;
}

- (void) setChecked:(BOOL) checked
{
	_checked = checked;
	if(_checked)
	{
		if(self.dataSource)
		{
			self.dataSourceObject = self.checkedValue;
		}
		if(_group)
        {
            [_group checkMarkWasSelected:self];
        }
	}
	[self setNeedsLayout];
}

- (NSString*) subText
{
	return _subLabel.text;
}

- (void) setSubText:(NSString*) subText
{
	_subLabel.text = subText;
}

@end

@implementation FLCircleView

@synthesize borderWidth = _borderWidth;
@synthesize borderColor = _color;

- (void) drawRect:(CGRect)rect
{
	CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);

	[self.borderColor setStroke];

    CGContextSetLineWidth(context, self.borderWidth);
    CGContextStrokeEllipseInRect(context, CGRectInset(self.bounds, self.borderWidth, self.borderWidth));

    CGContextRestoreGState(context);
}

- (void) dealloc
{
	FLRelease(_color);
	FLSuperDealloc();
}
@end

@implementation FLOnOffCheckMarkTableViewCell

@synthesize checked = _checked;

- (void) calculateCellHeightInTable:(UITableView *)tableView
{
	self.cellHeight = 50.0f; // DeviceIsPad() ? 50.0 : 36.0f; // TODO: set with theme.
}

+ (id) onOffCheckMarkTableViewCell:(NSString*) labelOrNil
{
	FLOnOffCheckMarkTableViewCell* cell = FLAutorelease([[[self class] alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"FLCheckMarkedTableCell"]);
	if(FLStringIsNotEmpty(labelOrNil))
	{
		cell.textLabelText = labelOrNil;
	}
	return cell;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {

	[super setSelected:selected animated:animated];

	if(selected && self.canEditData)
	{
		self.checked = !self.checked;
	}
}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
	if((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]))
	{
        self.accessoryType = UITableViewCellAccessoryNone;
		self.selectionStyle = UITableViewCellSelectionStyleBlue;

        _check = [[UIImageView alloc] initWithImage:[UIImage whiteImageNamed:@"check.png"]];
        _check.hidden = YES;
        [_check resizeToImageSize];
        [self addSubview:_check];

        _circle = [[FLCircleView alloc] initWithFrame:CGRectMake(0,0,34,30)];
        _circle.backgroundColor = [UIColor clearColor];
        _circle.borderColor = [UIColor grayColor];
        _circle.borderWidth = 2.0f;
        [self addSubview:_circle];
    }

	return self;
}

- (void) dealloc
{
    FLRelease(_check);
    FLSuperDealloc();
}

#define kTextLeft 60.0f
#define kLeftBuffer 0.0f

- (void)layoutSubviews
{
    [super layoutSubviews];

    CGRect layoutRect = self.layoutRect;
	_circle.frameOptimizedForSize = FLRectCenterRectInRectVertically(layoutRect, FLRectSetLeft(_circle.frame, layoutRect.origin.x + kLeftBuffer));
    _check.frame = FLRectCenterRectInRect(_circle.frame, _check.frame);

    self.label.frameOptimizedForSize = FLRectCenterRectInRectVertically(layoutRect, FLRectSetLeft(self.label.frame, kTextLeft));
}

- (void) setChecked:(BOOL) checked
{
    _checked = checked;
    if(self.dataSource)
    {
        self.dataSourceObject = [NSNumber numberWithBool:_checked];
    }
    _check.hidden = !self.isChecked;

   	[self setNeedsLayout];
}

- (void) updateCellState
{
    if(self.dataSource)
	{
		self.checked = [self.dataSourceObject isEqual:[NSNumber numberWithBool:YES]];
	}
}

@end


text:
$.register_module({
    name: 'og.common.gadgets.manager',
    dependencies: [],
    obj: function () {
        var manager, collector, gadgets = [], interval = 5 * 60 * 1000, layout,
            resize = function () {
                return manager.clean().forEach(function (gadget) {gadget.resize.call(gadget.context);});
            };
        setTimeout((collector = function () {return manager.clean(), setTimeout(collector, interval);}), interval);
        $(function () {if (!(layout = !!og.views.common.layout)) $(window).on('resize', manager.resize);});
        return manager = {
            clean: function () {
                return gadgets = gadgets.filter(function (gadget) {
                    // if context has been cleared (e.g. removed iframe, a compile-and-go error will be thrown)
                    try {return gadget.alive.call(gadget.context);} catch (error) {return og.dev.warn(error), false;}
                });
            },
            gadgets: function () {return gadgets;},
            register: function (gadget) {manager.clean().push(gadget);},
            resize: (function (timeout) {
                return function () {timeout = clearTimeout(timeout) || setTimeout(resize, layout ? 0 : 200);};
            })(null)
        };
    }
});


text:
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 * vim: sw=2 ts=8 et :
 */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef mozilla_WidgetUtils_h
#define mozilla_WidgetUtils_h

#include "mozilla/EventForwards.h"
#include "mozilla/gfx/Matrix.h"
#include "nsCOMPtr.h"
#include "nsIDOMWindow.h"
#include "nsIWidget.h"
#include "nsPIDOMWindow.h"
#include "nsRect.h"

namespace mozilla {

// NB: these must match up with pseudo-enum in nsIScreen.idl.
enum ScreenRotation {
  ROTATION_0 = 0,
  ROTATION_90,
  ROTATION_180,
  ROTATION_270,

  ROTATION_COUNT
};

gfx::Matrix ComputeTransformForRotation(const nsIntRect& aBounds,
                                        ScreenRotation aRotation);

gfx::Matrix ComputeTransformForUnRotation(const nsIntRect& aBounds,
                                          ScreenRotation aRotation);

nsIntRect RotateRect(nsIntRect aRect,
                     const nsIntRect& aBounds,
                     ScreenRotation aRotation);

namespace widget {

class WidgetUtils
{
public:
  /**
   * Shutdown() is called when "xpcom-will-shutdown" is notified.  This is
   * useful when you need to observe the notification in XP level code under
   * widget.
   */
  static void Shutdown();

  /**
   * Starting at the docshell item for the passed in DOM window this looks up
   * the docshell tree until it finds a docshell item that has a widget.
   */
  static already_AddRefed<nsIWidget> DOMWindowToWidget(nsIDOMWindow *aDOMWindow);

  /**
   * Compute our keyCode value (NS_VK_*) from an ASCII character.
   */
  static uint32_t ComputeKeyCodeFromChar(uint32_t aCharCode);

  /**
   * Get unshifted charCode and shifted charCode for aKeyCode if the keyboad
   * layout is a Latin keyboard layout.
   *
   * @param aKeyCode            Our keyCode (NS_VK_*).
   * @param aIsCapsLock         TRUE if CapsLock is Locked.  Otherwise, FALSE.
   *                            This is used only when aKeyCode is NS_VK_[0-9].
   * @param aUnshiftedCharCode  CharCode for aKeyCode without Shift key.
   *                            This may be zero if aKeyCode key doesn't input
   *                            a Latin character.
   *                            Note that must not be nullptr.
   * @param aShiftedCharCode    CharCode for aKeyCOde with Shift key.
   *                            This is always 0 when aKeyCode isn't
   *                            NS_VK_[A-Z].
   *                            Note that must not be nullptr.
   */
  static void GetLatinCharCodeForKeyCode(uint32_t aKeyCode,
                                         bool aIsCapsLock,
                                         uint32_t* aUnshiftedCharCode,
                                         uint32_t* aShiftedCharCode);

  /**
  * Does device have touch support
  */
  static uint32_t IsTouchDeviceSupportPresent();
};

} // namespace widget
} // namespace mozilla

#endif // mozilla_WidgetUtils_h


text:
function solve() {

}


text:
describe("module:ng.directive:ngClassOdd", function() {
  beforeEach(function() {
    browser.get("./examples/example-example18/index-jquery.html");
  });

  it('should check ng-class-odd and ng-class-even', function() {
    expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
      toMatch(/odd/);
    expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
      toMatch(/even/);
  });
});


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

namespace System.UnitTesting
{
    public static class EnumerableAssert
    {
        public static void AreEqual<T>(IEnumerable<T> actual, params T[] expected)
        {
            AreEqual<T>((IEnumerable<T>)expected, (IEnumerable<T>)actual);
        }

        private static void AreEqual<T>(IEnumerable expected, IList<T> actual)
        {
            foreach (object value in expected)
            {
                bool removed = actual.Remove((T)value);

                Assert.True(removed);
            }

            Assert.Equal(0, actual.Count);
        }

        public static void AreEqual<T>(IEnumerable<T> expected, IEnumerable<T> actual)
        {
            // First, test the IEnumerable implementation
            Assert.Equal(expected.Count(), actual.Count());
            AreEqual((IEnumerable)expected, actual.ToList());

            // Second, test the IEnumerable<T> implementation
            Assert.Equal(expected.Count(), actual.Count());

            List<T> actualList = actual.ToList();

            foreach (T value in expected)
            {
                bool removed = actualList.Remove(value);

                Assert.True(removed);
            }

            Assert.Equal(0, actualList.Count);
        }

        public static void AreEqual<TKey, TValue>(IDictionary<TKey, TValue> expected, IDictionary<TKey, TValue> actual)
        {
            Assert.Equal(expected.Count, actual.Count);

            foreach (KeyValuePair<TKey, TValue> kvp in expected)
            {
                TValue firstValue = kvp.Value;
                TValue secondValue = default(TValue);
                if (!actual.TryGetValue(kvp.Key, out secondValue))
                {
                    throw new NotImplementedException();
                }

                if ((firstValue is IDictionary<TKey, TValue>) && (secondValue is IDictionary<TKey, TValue>))
                {
                    AreEqual((IDictionary<TKey, TValue>)firstValue, (IDictionary<TKey, TValue>)secondValue);
                    continue;
                }

                Assert.Equal(kvp.Value, secondValue);
            }
        }
    }
}


text:
<script src="{{ "/assets/js/plugins.min.js" | prepend: site.baseurl }}"></script>
<script src="{{ "/assets/js/functions.js" | prepend: site.baseurl }}"></script>


text:
import { Component, ViewChild } from '@angular/core';
import { NavController, Slides, IonicPage } from 'ionic-angular';

@IonicPage()
@Component({
  selector: 'page-slide-color-changing',
  templateUrl: 'slide-color-changing.html'
})
export class SlideColorChangingPage {
  @ViewChild('slider') slider: Slides;

  slides = [
    {
      title: 'Dream\'s Adventure',
      imageUrl: 'assets/img/lists/wishlist-1.jpg',
      songs: 2,
      private: false
    },
    {
      title: 'For the Weekend',
      imageUrl: 'assets/img/lists/wishlist-2.jpg',
      songs: 4,
      private: false
    },
    {
      title: 'Family Time',
      imageUrl: 'assets/img/lists/wishlist-3.jpg',
      songs: 5,
      private: true
    },
    {
      title: 'My Trip',
      imageUrl: 'assets/img/lists/wishlist-4.jpg',
      songs: 12,
      private: true
    }
  ];

  color: any;
  colors = ['#e43737', '#e0e437', '#37e446', '#375be4', '#972cb1'];

  onSlideChanged() {
    const currentIndex = this.slider.getActiveIndex();
    this.color = this.colors[currentIndex];
    console.log('Slide changed! Current index is', currentIndex);
  }

  constructor(public navCtrl: NavController) {
    this.color = this.colors[0];
  }
}