text:
var app = angular.module('myApp', [
  "ui.router",
  "myApp.main",
  "myApp.top100visual",
  "myApp.search",
  "firebase",
  "d3",
  "myApp.directives",
  "myApp.trackUser",
  "myApp.trackPost",
  "myApp.home"
  ]);

app.config(function($stateProvider, $urlRouterProvider) {

  $stateProvider
    .state('main', {
      url: '/main',
      templateUrl: 'main/main.html',
      controller: 'mainController'
    })
    .state('main.subviews', {
      views: {
        'search': {
          templateUrl: 'search/search.html',
          controller: 'searchCtrl'
        },
        'top100visual': {
          controller: 'top100visualController',
          templateUrl: 'top100visual/top100visual.html'
        },
        'trackUser': {
          templateUrl: 'trackUser/trackUser.html',
          controller: 'trackUserController'
        },
        'home': {
          templateUrl: 'home/home.html',
          controller: 'homeController'
        },
        'trackPost': {
          templateUrl: 'trackPost/trackPost.html',
          controller: 'trackPostController'
        }
      }
    });
  $urlRouterProvider.otherwise("/main");
});


text:
/* This file was generated by SableCC (http://www.sablecc.org/). */

package org.acre.lang.node;

import java.util.*;

public class TypedLinkedList extends LinkedList
{
    Cast cast;

    public TypedLinkedList()
    {
        super();

        cast = NoCast.instance;
    }

    public TypedLinkedList(Collection c)
    {
        super();
        cast = NoCast.instance;
        this.addAll(c);
    }

    public TypedLinkedList(Cast cast)
    {
        super();

        this.cast = cast;
    }

    public TypedLinkedList(Collection c, Cast cast)
    {
        super();
        this.cast = cast;
        this.addAll(c);
    }

    public Cast getCast()
    {
        return cast;
    }

    public void add(int index, Object element)
    {
        super.add(index, cast.cast(element));
    }

    public boolean add(Object o)
    {
        return super.add(cast.cast(o));
    }

    public boolean addAll(Collection c)
    {
        for(Iterator i = c.iterator(); i.hasNext(); )
        {
            super.add(cast.cast(i.next()));
        }
        return true;
    }

    public boolean addAll(int index, Collection c)
    {
        int pos = index;
        for(Iterator i = c.iterator(); i.hasNext(); )
        {
            super.add(pos++, cast.cast(i.next()));
        }
        return true;
    }

    public void addFirst(Object o)
    {
        super.addFirst(cast.cast(o));
    }

    public void addLast(Object o)
    {
        super.addLast(cast.cast(o));
    }

    public ListIterator listIterator(int index)
    {
        return new TypedLinkedListIterator(super.listIterator(index));
    }

    private class TypedLinkedListIterator implements ListIterator
    {
        ListIterator iterator;

        TypedLinkedListIterator(ListIterator iterator)
        {
            this.iterator = iterator;
        }

        public boolean hasNext()
        {
            return iterator.hasNext();
        }

        public Object next()
        {
            return iterator.next();
        }

        public boolean hasPrevious()
        {
            return iterator.hasPrevious();
        }

        public Object previous()
        {
            return iterator.previous();
        }

        public int nextIndex()
        {
            return iterator.nextIndex();
        }

        public int previousIndex()
        {
            return iterator.previousIndex();
        }

        public void remove()
        {
            iterator.remove();
        }

        public void set(Object o)
        {
            iterator.set(cast.cast(o));
        }

        public void add(Object o)
        {
            iterator.add(cast.cast(o));
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace RenanBr\WsseMiddleware\Test;

use Interop\Http\ServerMiddleware\DelegateInterface;
use RenanBr\WsseMiddleware;
use Zend\Diactoros\ServerRequest;

class InvalidPasswordTest extends TestCase
{
    public function testUnauthorizedResponseCausedByInvalidPassword()
    {
        // Middleware
        $middleware = new WsseMiddleware(['bob' => 'right']);

        // Request
        $header = $this->generateWsseHeader('bob', 'wrong', date('c'));
        $request = (new ServerRequest())->withHeader('X-WSSE', $header);

        // Delegate
        $delegate = $this->createMock(DelegateInterface::class);
        $delegate
            ->expects($this->never())
            ->method('process')
        ;

        $response = $middleware->process($request, $delegate);

        $this->assertSame(401, $response->getStatusCode());
    }
}


text:
declare module 'lodash/debounce' {
  interface Debounce {
    (): void;
    timerId: any;
    cancel(): void;
  }

  export default function debounce(func: Function, wait: number, options?: any): Debounce;
}

declare module 'lodash/clamp' {
  export default function clamp(n: number, low: number, high: number): number;
}


text:
    <ion-header-bar>
      <button class="button button-clear button-positive" ng-click="compose_modal.hide()">Cancel</button>

New Thread

Edit Thread

      <button class="button button-clear button-positive" ng-click="publish_post()">Publish</button>
    </ion-header-bar>
    <ion-content>

          Title
          <input type="text" placeholder="" ng-model="new_post.title">

          Content
          <textarea rows="5" ng-model="new_post.content"></textarea>

           This is an event

             <input type="checkbox" ng-model="new_post.is_event">

          Event date
          <input type="date" placeholder="" ng-model="new_post.event_time">

    </ion-content>


text:
use strict;

# This script is used to test streaming error cases in pig.
# Usage: PigStreaming.pl <start|middle|end>
# the parameter tells the application when to exit with error

if ($#ARGV < 0)
{
	print STDERR "Usage PigStreaming.pl <start|middle|end>\n";
	exit (-1);
}

my $pos = $ARGV[0];

if ($pos eq "start")
{
	print STDERR "Failed in the beginning of the processing\n";
	exit(1);
}

print STDERR "PigStreamingBad.pl: starting processing\n";

my $cnt = 0;
while (<STDIN>)
{
	print "$_";
	$cnt++;
	print STDERR "PigStreaming.pl: processing $_\n";
	if (($cnt > 100) && ($pos eq "middle"))
	{
		print STDERR "Failed in the middle of processing\n";
		exit(2);
	}
}

print STDERR "Failed at the end of processing\n";
exit(3);


text:
package com.communote.server.core.external;

import java.util.Collection;

import com.communote.server.model.user.User;
import com.communote.server.model.user.group.ExternalUserGroup;

/**
 * Tracker for incremental repository changes.
 *
 * @author Communote GmbH - http://www.communote.com/
 */
public interface IncrementalRepositoryChangeTracker {
    /**
     * Method to return the next groups from the repository.
     *
     * @return List of groups or null if no groups left.
     */
    Collection<ExternalUserGroup> getNextGroups();

    /**
     * Method to return the next users from the repository.
     *
     * @return List of users or null if no users left.
     */
    Collection<User> getNextUsers();

    /**
     * If this method returns true, the UserGroupSynchronizer has to visit the members of a group
     * explicitly. This could be useful, if getNextUser doesn't return users, which group membership
     * has changed.
     *
     * @return True, if the synchronizer needs to visit the members of groups explicitly. Default is
     *         false.
     */
    boolean needsToAcceptMembersOfGroups();

    /**
     * Method to be called before the synchronization starts.
     */
    void start();

    /**
     * Method to be called after the synchronization ran.
     *
     * @param success
     *            True, if the sync was successful.
     */
    void stop(boolean success);

}


text:
import {Component, OnInit} from "@angular/core";
import {Router, ActivatedRoute, Params} from "@angular/router";
import {Idea} from "../../models/idea.model.app";
import {User} from "../../models/user.model.app";
import {IdeaService} from "../../services/idea.service";

@Component({
    selector: "idea-details",
    templateUrl: "./idea-details.component.html",
    styles: [ require("./idea-details.component.css").toString() ]
})
export class IdeaDetailsComponent implements OnInit {

    private idea: Idea = new Idea();
    private author: User = new User();

    constructor(
        private route: ActivatedRoute,
        private router: Router,
        private ideaService: IdeaService) {

        // loading animation before image is loaded
        this.idea.pic =
            "https://res.cloudinary.com/lighthauz-harbor/image/upload/v1482734274/hourglass.gif";

    }

    ngOnInit(): void {
        this.route.params.forEach((params: Params) => {
            let id = params["id"];
            this.ideaService.getSingleIdea(id)
                .subscribe((json: any) => {
                    if (json.fail) {
                        alert(json.fail);
                        this.router.navigate(["/ideas"]);
                    } else {
                        let extraLink = json.idea.extraLink;
                        if (extraLink != "" &&
                            !extraLink.includes("http://") && !extraLink.includes("https://")) {
                            extraLink = "http://" + extraLink;
                        }

                        let {title, pic, description, background, problem, solution} = json.idea;
                        let {valueProposition, customerSegments, customerRelationships,
                            channels, keyActivities, keyResources, keyPartners,
                            costStructure, revenueStreams} = json.idea;
                        let {strengths, weaknesses, opportunities, threats} = json.idea;

                        this.idea = new Idea(id,
                            {
                                visibility: json.visibility,
                                title, pic, description, background,
                                problem, solution, extraLink
                            },
                            {
                                valueProposition, customerSegments, customerRelationships,
                                channels, keyActivities, keyResources, keyPartners,
                                costStructure, revenueStreams
                            },
                            {
                                strengths, weaknesses, opportunities, threats
                            },
                            json.category,
                            new Date(json.timestamp));

                        this.author = new User(
                            json.author.id,
                            json.author.email,
                            "user",
                            json.author.name,
                            json.author.bio);
                    }
                });
        });
    }

}


text:
import logging
import time

from pants.engine.scheduler import Scheduler
from pants.pantsd.service.pants_service import PantsService

class StoreGCService(PantsService):
    """Store Garbage Collection Service.

    This service both ensures that in-use files continue to be present in the engine's Store, and
    performs occasional garbage collection to bound the size of the engine's Store.
    """

    def __init__(
        self,
        scheduler: Scheduler,
        period_secs=10,
        lease_extension_interval_secs=(30 * 60),
        gc_interval_secs=(4 * 60 * 60),
    ):
        super().__init__()
        self._scheduler_session = scheduler.new_session(
            zipkin_trace_v2=False, build_id="store_gc_service_session"
        )
        self._logger = logging.getLogger(__name__)

        self._period_secs = period_secs
        self._lease_extension_interval_secs = lease_extension_interval_secs
        self._gc_interval_secs = gc_interval_secs

        self._set_next_gc()
        self._set_next_lease_extension()

    def _set_next_gc(self):
        self._next_gc = time.time() + self._gc_interval_secs

    def _set_next_lease_extension(self):
        self._next_lease_extension = time.time() + self._lease_extension_interval_secs

    def _maybe_extend_lease(self):
        if time.time() < self._next_lease_extension:
            return
        self._logger.debug("Extending leases")
        self._scheduler_session.lease_files_in_graph()
        self._logger.debug("Done extending leases")
        self._set_next_lease_extension()

    def _maybe_garbage_collect(self):
        if time.time() < self._next_gc:
            return
        self._logger.debug("Garbage collecting store")
        self._scheduler_session.garbage_collect_store()
        self._logger.debug("Done garbage collecting store")
        self._set_next_gc()

    def run(self):
        """Main service entrypoint.

        Called via Thread.start() via PantsDaemon.run().
        """
        while not self._state.is_terminating:
            self._maybe_garbage_collect()
            self._maybe_extend_lease()
            # Waiting with a timeout in maybe_pause has the effect of waiting until:
            # 1) we are paused and then resumed
            # 2) we are terminated (which will break the loop)
            # 3) the timeout is reached, which will cause us to wake up and check gc/leases
            self._state.maybe_pause(timeout=self._period_secs)


text:
package com.mongodb.graph.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

import com.mongodb.*;
import com.mongodb.graph.Direction;
import com.mongodb.graph.EdgeFilter;
import com.mongodb.graph.GraphEngine;
import com.mongodb.graph.PathListener;
import com.mongodb.graph.Relationship;

public class EdgeIndexGraphEngine implements GraphEngine
{
	private static final int DEFAULT_BATCH_SIZE = 100;
	private static final int DEFAULT_RESULT_LIMIT = 1000;
	private static final String DEFAULT_EDGE_COLLECTION = "graph_edges";
	private static final String SOURCE_KEY = "_s";
	private static final String DEST_KEY = "_d";
	private static final String ID_KEY = "_id";

	private DB _db = null;
	private DBCollection _edgeColl = null;

	public EdgeIndexGraphEngine(DB db){

		_db = db;
		_edgeColl = _db.getCollection(DEFAULT_EDGE_COLLECTION);

        this._edgeColl.ensureIndex(
                new BasicDBObject(SOURCE_KEY, 1).append(DEST_KEY, 1));
        this._edgeColl.ensureIndex(
                new BasicDBObject(DEST_KEY, 1).append(SOURCE_KEY, 1));
	}

	@Override
	public DBObject addEdge(DBObject sourceVertexId, DBObject targetVertexId, DBObject edgeData) {

		BasicDBObject newEdge = new BasicDBObject();
		newEdge.putAll(edgeData);
		newEdge.append(SOURCE_KEY, sourceVertexId);
		newEdge.append(DEST_KEY, targetVertexId);
		this._edgeColl.insert(newEdge);

		return newEdge;
	}

	@Override
	public List<DBObject> getEdges(DBObject vertexId){

		return this.getEdges(vertexId, null);
	}

	@Override
	public List<DBObject> getEdges(DBObject vertexId, EdgeFilter filter){

		// Setup the query components based on filter
		Direction direction = getAllowedDirection(filter, Direction.BOTH);
		BasicDBObject projection = buildProjection(filter);
		BasicDBObject edgeQuery = buildEdgeQuery(vertexId, filter, direction);

		// In this call, we just need the edges as documents
		List<DBObject> resultList = new ArrayList<DBObject>();

		DBCursor outCursor = null;
		try{
			// run query and exhaust cursor
			outCursor = _edgeColl.find(edgeQuery, projection);
			outCursor.batchSize(DEFAULT_BATCH_SIZE);
			outCursor.limit(DEFAULT_RESULT_LIMIT);

			// exhaust cursor
			while(outCursor.hasNext())
				resultList.add(outCursor.next());
		}
		finally{
			if(outCursor != null)
				outCursor.close();
		}

		return resultList;
	}

	@Override
	public List<Relationship> getNeighbors(DBObject vertexId){
		return getNeighbors(vertexId, null);
	}

	@Override
	public List<Relationship> getNeighbors(DBObject vertexId, EdgeFilter filter){

		// Find all edges by default
		Direction direction = getAllowedDirection(filter, Direction.BOTH);
		BasicDBObject projection = buildProjection(filter);
		BasicDBObject edgeQuery = buildEdgeQuery(vertexId, filter, direction);

		// In this call, we need to construct relationships
		List<Relationship> resultList = new ArrayList<Relationship>();

		DBCursor outCursor = null;
		try{
			// run query and exhaust cursor
			outCursor = _edgeColl.find(edgeQuery, projection);
			outCursor.batchSize(DEFAULT_BATCH_SIZE);
			outCursor.limit(DEFAULT_RESULT_LIMIT);

			// exhaust cursor
			while(outCursor.hasNext())
				resultList.add(relationshipFromEdge(outCursor.next(), vertexId));
		}
		finally{
			if(outCursor != null)
				outCursor.close();
		}

		return resultList;
	}

	@Override
	public Collection<List<Relationship>> findPaths(
			DBObject fromVertexId, DBObject targetVertexId,
			EdgeFilter filter, int degreeLimit, PathListener listener){

		List<List<Relationship>> resultList = new LinkedList<List<Relationship>>();
		List<Relationship> currentPath = new ArrayList<Relationship>(degreeLimit);

		// Add the id for the start into the current path
		processLevel(fromVertexId, fromVertexId, targetVertexId, filter,
				degreeLimit, currentPath, resultList, listener);
		if(listener != null) listener.complete();
		return resultList;
	}

	private void processLevel(
			DBObject startVertex, DBObject levelVertexId, DBObject targetVertexId,
			EdgeFilter filter, int degrees, List<Relationship> currentPath,
			List<List<Relationship>> resultList, PathListener listener){

		if(degrees > 0 && levelVertexId != null && targetVertexId != null){

			// Find all edges by default
			Direction direction = getAllowedDirection(filter, Direction.OUT);
			BasicDBObject projection = buildProjection(filter);
			BasicDBObject edgeQuery = buildEdgeQuery(levelVertexId, filter, direction);

			DBCursor outCursor = null;
			try{
				// run query and exhaust cursor
				outCursor = _edgeColl.find(edgeQuery, projection);
				outCursor.batchSize(DEFAULT_BATCH_SIZE);
				outCursor.limit(DEFAULT_RESULT_LIMIT);

				// exhaust cursor
				while(outCursor.hasNext()){
					Relationship current = relationshipFromEdge(
							outCursor.next(), levelVertexId);

					if(pathHasVertex(startVertex, currentPath,
							current.getRelatedId()) == false){

						// push the current hop to the path
						currentPath.add(current);

						if(idMatch(targetVertexId, current.getRelatedId())){
							// This is a result add it !
							ArrayList<Relationship> resultPath = new ArrayList<Relationship>(currentPath);
							resultList.add(resultPath);
							if(listener != null) listener.handlePath(resultPath);
						}
						else{
							// This is a path to investigate
							processLevel(startVertex, current.getRelatedId(), targetVertexId, filter,
									degrees - 1, currentPath, resultList, listener);
						}

						// pop the current hop off
						currentPath.remove(currentPath.size() - 1);
					}
				}
			}
			finally{
				if(outCursor != null)
					outCursor.close();
			}
		}
	}

	private boolean pathHasVertex(DBObject startVertex,
			List<Relationship> currentPath, DBObject relatedId) {
		for(Relationship step : currentPath){
			if(step.getRelatedId().equals(relatedId))
				return true;
		}

		return startVertex.equals(relatedId);
	}

	private Relationship relationshipFromEdge(DBObject edge, DBObject relativeTo) {
		DBObject relatedId = (DBObject) edge.get(SOURCE_KEY);
		Direction edgeDirection = Direction.IN;

		// if source == relativeTo, then this is an outgoing
		if(relatedId.equals(relativeTo)){
			relatedId = (DBObject) edge.get(DEST_KEY);
			edgeDirection = Direction.OUT;
		}

		return new Relationship(relatedId, edge, edgeDirection);
	}

	private BasicDBObject buildEdgeQuery(DBObject vertexId,
			EdgeFilter filter, Direction direction) {

		// Initialize query with terms for direction
		BasicDBObject edgeQuery = new BasicDBObject();

		// Based on the allowed direction, add a clause to
		// specify the source/destination we expect
		if(direction == Direction.BOTH ){
			List<BasicDBObject> orList = new ArrayList<BasicDBObject>(2);
			orList.add(new BasicDBObject(SOURCE_KEY, vertexId));
			orList.add(new BasicDBObject(DEST_KEY, vertexId));
			edgeQuery.append("$or", orList);
		}
		else if(direction == Direction.OUT){
			edgeQuery.append(SOURCE_KEY, vertexId);
		}
		else {// direction == Direction.IN
			edgeQuery.append(DEST_KEY, vertexId);
		}

		if(filter != null && filter.getQuery() != null){
			// need explicit $and to avoid $or clashes in user query
			List<DBObject> andList = new ArrayList<DBObject>(2);
			andList.add(edgeQuery);
			andList.add(filter.getQuery());
	    	edgeQuery = new BasicDBObject("$and", andList);
		}

		return edgeQuery;
	}

	private BasicDBObject buildProjection(EdgeFilter filter) {

		BasicDBObject projection = new BasicDBObject(ID_KEY, false);
		if(filter != null){
			if(filter.getIncludeEdgeIds() == true)
				projection.remove(ID_KEY);

			if(filter.hasProjection()){
				projection.append(SOURCE_KEY, true).append(DEST_KEY, true);
				projection.putAll(filter.getProjection());
			}
		}

		return projection;
	}

	private Direction getAllowedDirection(
			EdgeFilter filter, Direction defaultDirection) {
		return (filter == null || filter.getAllowedDirection() == null) ?
				defaultDirection : filter.getAllowedDirection();
	}

	private boolean idMatch(DBObject original, DBObject subject) {
		return original.equals(subject);
	}
}


text:
import test from 'ava';
import Header from './Header.js';
import React from 'react';
import { shallow } from 'enzyme';

test("should construct a header with a title", t => {
  const wrapper = shallow(<Header title={"A new modal"} />);
  t.is(wrapper.find('h3').text(), "A new modal");
  //not dismissable by default
  t.is(wrapper.find('button').length, 0);
})

test("should construct a header with a title", t => {
  const wrapper = shallow(<Header title={"A newer modal"} dismissable={true}/>);
  t.is(wrapper.find('h3').text(), "A newer modal");
  //not dismissable by default
  t.is(wrapper.find('button').length, 1);
})


text:
const {assert} = chai;

import * as Common from '../../../../../front_end/core/common/common.js';

const CompositeProgress = Common.Progress.CompositeProgress;
const ProgressProxy = Common.Progress.ProgressProxy;

class MockProgressIndicator implements Common.Progress.Progress {
  private isCanceledInternal = false;
  private totalWork = 0;
  private workCompleted = 0;
  private title!: string|undefined;

  get getTitle(): string|undefined {
    return this.title;
  }

  get getWorkCompleted(): number {
    return this.workCompleted;
  }

  get getTotalWork(): number {
    return this.totalWork;
  }

  isCanceled() {
    return this.isCanceledInternal;
  }

  done() {
    return 'progress indicator: done';
  }

  setTotalWork(totalWork: number) {
    this.totalWork = totalWork;
  }

  setWorked(worked: number, title: string) {
    this.workCompleted = worked;
    if (typeof title !== 'undefined') {
      this.title = title;
    }
  }

  setTitle(title: string) {
    this.title = title;
  }

  incrementWorked(worked: number) {
    this.totalWork += worked;
  }

  // Test methods.
  cancel() {
    this.isCanceledInternal = true;
  }
}

describe('Composite Progress Bar', () => {
  it('works correctly with a single subprogress', () => {
    const indicator = new MockProgressIndicator();
    const composite = new CompositeProgress(indicator);
    const subProgress = composite.createSubProgress();

    assert.strictEqual(indicator.getTitle, undefined);
    assert.strictEqual(indicator.getWorkCompleted, 0);
    assert.strictEqual(indicator.getTotalWork, 1);

    subProgress.setTitle('cuckooing');
    subProgress.setWorked(10);
    assert.strictEqual(indicator.getTitle, 'cuckooing');
    assert.strictEqual(indicator.getWorkCompleted, 0);
    assert.strictEqual(indicator.getTotalWork, 1);

    subProgress.setTotalWork(100);
    assert.strictEqual(indicator.getTitle, 'cuckooing');
    assert.strictEqual(indicator.getWorkCompleted, 0.1);
    assert.strictEqual(indicator.getTotalWork, 1);

    subProgress.setWorked(20, 'meowing');
    assert.strictEqual(indicator.getTitle, 'meowing');
    assert.strictEqual(indicator.getWorkCompleted, 0.2);
    assert.strictEqual(indicator.getTotalWork, 1);

    subProgress.done();
    assert.strictEqual(indicator.getTitle, 'meowing');
    assert.strictEqual(indicator.getWorkCompleted, 1);
    assert.strictEqual(indicator.getTotalWork, 1);
  });

  it('works correctly with multiple subprogresses', () => {
    const indicator = new MockProgressIndicator();
    const composite = new CompositeProgress(indicator);
    // Creates a sub progress with the default weight of 1
    const subProgress1 = composite.createSubProgress();
    // Creates a sub progress with the weight of 3
    const subProgress2 = composite.createSubProgress(3);

    assert.strictEqual(indicator.getTitle, undefined);
    assert.strictEqual(indicator.getWorkCompleted, 0);
    assert.strictEqual(indicator.getTotalWork, 1);

    subProgress1.setTitle('cuckooing');
    subProgress1.setTotalWork(100);
    subProgress1.setWorked(20);
    assert.strictEqual(indicator.getTitle, 'cuckooing');
    assert.strictEqual(indicator.getWorkCompleted, 0.05);
    assert.strictEqual(indicator.getTotalWork, 1);

    subProgress2.setWorked(10);
    assert.strictEqual(indicator.getTitle, 'cuckooing');
    assert.strictEqual(indicator.getWorkCompleted, 0.05);
    assert.strictEqual(indicator.getTotalWork, 1);

    subProgress2.setTotalWork(10);
    subProgress2.setWorked(3, 'barking');
    assert.strictEqual(indicator.getTitle, 'barking');
    assert.strictEqual(indicator.getWorkCompleted, 0.275);
    assert.strictEqual(indicator.getTotalWork, 1);

    subProgress1.setWorked(50, 'meowing');
    subProgress2.setWorked(5);
    assert.strictEqual(indicator.getTitle, 'meowing');
    assert.strictEqual(indicator.getWorkCompleted, 0.5);
    assert.strictEqual(indicator.getTotalWork, 1);

    subProgress2.done();
    assert.strictEqual(indicator.getTitle, 'meowing');
    assert.strictEqual(indicator.getWorkCompleted, 0.875);
    assert.strictEqual(indicator.getTotalWork, 1);

    subProgress1.done();
    assert.strictEqual(indicator.getTitle, 'meowing');
    assert.strictEqual(indicator.getWorkCompleted, 1);
    assert.strictEqual(indicator.getTotalWork, 1);
  });

  it('returns the correct cancellation status', () => {
    const indicator = new MockProgressIndicator();
    const composite = new CompositeProgress(indicator);
    const subProgress = composite.createSubProgress();

    assert.isFalse(subProgress.isCanceled(), 'progress should not be canceled');
    indicator.cancel();
    assert.isTrue(subProgress.isCanceled(), 'progress should be canceled');
  });

  it('works correctly with nested subprogresses', () => {
    const indicator = new MockProgressIndicator();
    const composite0 = new CompositeProgress(indicator);
    const subProgress01 = composite0.createSubProgress();
    const composite1 = new CompositeProgress(subProgress01);
    const subProgress11 = composite1.createSubProgress(10);  // Weight should have no effect

    assert.strictEqual(indicator.getTitle, undefined);
    assert.strictEqual(indicator.getWorkCompleted, 0);
    assert.strictEqual(indicator.getTotalWork, 1);

    subProgress11.setWorked(10);
    assert.strictEqual(indicator.getTitle, undefined);
    assert.strictEqual(indicator.getWorkCompleted, 0);
    assert.strictEqual(indicator.getTotalWork, 1);

    subProgress11.setTotalWork(100);
    assert.strictEqual(indicator.getTitle, undefined);
    assert.strictEqual(indicator.getWorkCompleted, 0.1);
    assert.strictEqual(indicator.getTotalWork, 1);

    subProgress11.setWorked(50, 'meowing');
    assert.strictEqual(indicator.getTitle, 'meowing');
    assert.strictEqual(indicator.getWorkCompleted, 0.5);
    assert.strictEqual(indicator.getTotalWork, 1);

    assert.isFalse(subProgress11.isCanceled(), 'progress should not be canceled');
    indicator.cancel();
    assert.isTrue(subProgress11.isCanceled(), 'progress should be canceled');

    subProgress11.done();
    assert.strictEqual(indicator.getTitle, 'meowing');
    assert.strictEqual(indicator.getWorkCompleted, 1);
    assert.strictEqual(indicator.getTotalWork, 1);
  });

  it('can set sub progress to be worked', () => {
    const indicator = new MockProgressIndicator();
    const composite = new CompositeProgress(indicator);
    const subProgress = composite.createSubProgress();

    assert.strictEqual(indicator.getTitle, undefined);
    assert.strictEqual(indicator.getWorkCompleted, 0);
    assert.strictEqual(indicator.getTotalWork, 1);
    assert.strictEqual(subProgress.getWorked(), 0);

    subProgress.incrementWorked();

    assert.strictEqual(indicator.getTitle, undefined);
    assert.strictEqual(indicator.getWorkCompleted, 0);
    assert.strictEqual(indicator.getTotalWork, 1);
    assert.strictEqual(subProgress.getWorked(), 1);
  });

  it('returns the correct cancellation status for a progress proxy with no delegate', () => {
    const progressProxy = new ProgressProxy();
    assert.isFalse(progressProxy.isCanceled());
  });

  it('returns the correct cancellation status for a progress proxy with delegate', () => {
    const indicator = new MockProgressIndicator();
    const composite = new CompositeProgress(indicator);
    const subProgress = composite.createSubProgress();
    const progressProxy = new ProgressProxy(subProgress);

    assert.isFalse(progressProxy.isCanceled(), 'progress should not be canceled');
    indicator.cancel();
    assert.isTrue(progressProxy.isCanceled(), 'progress should be canceled');
  });

  it('returns the correct title for a progress proxy with no delegate', () => {
    const indicator = new MockProgressIndicator();
    const progressProxy = new ProgressProxy();

    progressProxy.setTitle('test proxy');
    assert.isUndefined(indicator.getTitle);
  });

  it('returns the correct title for a progress proxy with delegate', () => {
    const indicator = new MockProgressIndicator();
    const composite = new CompositeProgress(indicator);
    const subProgress = composite.createSubProgress();
    const progressProxy = new ProgressProxy(subProgress);

    progressProxy.setTitle('test proxy');
    assert.strictEqual(indicator.getTitle, 'test proxy');
  });

  it('marks a progress proxy as done', () => {
    const indicator = new MockProgressIndicator();
    const composite = new CompositeProgress(indicator);
    const subProgress = composite.createSubProgress();
    const progressProxy = new ProgressProxy(subProgress);

    progressProxy.setTotalWork(1);
    progressProxy.done();
    assert.strictEqual(subProgress.getWorked(), 1);
  });

  it('able to set worked with title for a progress proxy', () => {
    const indicator = new MockProgressIndicator();
    const composite = new CompositeProgress(indicator);
    const subProgress = composite.createSubProgress();
    const progressProxy = new ProgressProxy(subProgress);

    progressProxy.setWorked(1, 'test proxy');
    assert.strictEqual(subProgress.getWorked(), 1);
    assert.strictEqual(indicator.getTitle, 'test proxy');
  });

  it('able to set worked without title for a progress proxy', () => {
    const indicator = new MockProgressIndicator();
    const composite = new CompositeProgress(indicator);
    const subProgress = composite.createSubProgress();
    const progressProxy = new ProgressProxy(subProgress);

    progressProxy.incrementWorked(1);
    assert.strictEqual(subProgress.getWorked(), 1);
  });
});


text:
import HmacSHA256 from 'crypto-js/hmac-sha256';
import Base64 from 'crypto-js/enc-base64';
import Utf8 from 'crypto-js/enc-utf8';

// @dynamic
export class AnsynJwt {
	public base64;
	public utf8;
	public hmacSha256;

	constructor() {
		this.base64 = Base64;
		this.utf8 = Utf8;
		this.hmacSha256 = HmacSHA256;
	}

	static get roles() {
		return {
			ADMIN: 'ADMIN',
			USER: 'USER',
			GUEST: 'GUEST'
		};
	};

	createJWT(header, payload) {
		const now = Date.now();
		let exp = now;
		switch (payload.role) {
			case AnsynJwt.roles.ADMIN:
				exp += this.year();
				break;
			case AnsynJwt.roles.USER:
				exp += this.month();
				break;
			case AnsynJwt.roles.GUEST:
				exp += this.week();
				break;
		}
		payload.exp = exp;
		const token = this.encode(header) + '.' + this.encode(payload);
		return token + '.' + this.encodeSigneture(token, now.toString());
	}

	day() {
		return 60 * 60 * 24;
	}

	month() {
		return this.day() * 30;
	}

	year() {
		return this.month() * 12;
	}

	week() {
		return this.day() * 7;
	}

	encode(source) {
		return this.base64.stringify(this.utf8.parse(JSON.stringify(source)));
	}

	decode(token) {
		// CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(JSON.stringify(source)));
		return JSON.parse(this.utf8.stringify(this.base64.parse(token)));
	}

	encodeSigneture(token, salt) {
		return this.base64.stringify(this.hmacSha256(token, salt));
	}

	check(jwt) {
		let jwtValues = jwt.split('.');
		if (jwtValues.length !== 3) {
			return false;
		}
		const [header, data, signeture] = [...jwtValues];
		const payload = this.decode(data);
		let key = payload.exp;
		switch (payload.role) {
			case AnsynJwt.roles.ADMIN:
				key -= this.year();
				break;
			case AnsynJwt.roles.USER:
				key -= this.month();
				break;
			case AnsynJwt.roles.GUEST:
				key -= this.week();
				break;
		}
		return signeture === this.encodeSigneture(header + '.' + data, key.toString());
	}

	getPayload(jwt) {
		const [header, data, signeture] = [...jwt.split('.')];
		return this.decode(data);
	}

}


text:
module Together
  module Slug
    extend ActiveSupport::Concern
    included do
      # Callbacks
      before_validation :generate_slug, on: :create, uniqueness: true

      # Call slug instead of ID
      def to_param
        slug
      end

      # String Generator
      def generate_slug(size = 8)
        charset = [("a".."z"), ("A".."Z"), (0..9)].map(&:to_a).flatten
        string = (0...size).map { charset[rand(charset.size)] }.join
        self.slug = string
      end
    end
  end
end


text:
/*
 * XSEC
 *
 * XKMSKeyBindingAbstractTypeImpl := Implementation of base for KeyBinding elements
 *
 * $Id$
 *
 */

#include <xsec/dsig/DSIGKeyInfoList.hpp>
#include <xsec/framework/XSECDefs.hpp>
#include <xsec/framework/XSECError.hpp>
#include <xsec/framework/XSECEnv.hpp>

XERCES_CPP_NAMESPACE_USE

#ifdef XSEC_XKMS_ENABLED

#include "../../utils/XSECDOMUtils.hpp"

#include "XKMSKeyBindingAbstractTypeImpl.hpp"
#include "XKMSUseKeyWithImpl.hpp"

#include <xsec/xkms/XKMSConstants.hpp>

#include <xercesc/dom/DOM.hpp>
#include <xercesc/util/XMLUniDefs.hpp>

// --------------------------------------------------------------------------------
//           Constructor/Destructor
// --------------------------------------------------------------------------------

XKMSKeyBindingAbstractTypeImpl::XKMSKeyBindingAbstractTypeImpl(
		const XSECEnv * env) :
mp_keyBindingAbstractTypeElement(NULL),
mp_env(env),
mp_idAttr(NULL),
mp_keyUsageSignatureElement(NULL),
mp_keyUsageEncryptionElement(NULL),
mp_keyUsageExchangeElement(NULL),
mp_keyInfoElement(NULL) {

	XSECnew(mp_keyInfoList, DSIGKeyInfoList(mp_env));

}

XKMSKeyBindingAbstractTypeImpl::XKMSKeyBindingAbstractTypeImpl(
		const XSECEnv * env,
		XERCES_CPP_NAMESPACE_QUALIFIER DOMElement * node) :
mp_keyBindingAbstractTypeElement(node),
mp_env(env),
mp_idAttr(NULL),
mp_keyUsageSignatureElement(NULL),
mp_keyUsageEncryptionElement(NULL),
mp_keyUsageExchangeElement(NULL),
mp_keyInfoElement(NULL) {

	XSECnew(mp_keyInfoList, DSIGKeyInfoList(mp_env));

}

XKMSKeyBindingAbstractTypeImpl::~XKMSKeyBindingAbstractTypeImpl() {

	if (mp_keyInfoList != NULL)
		delete mp_keyInfoList;

	UseKeyWithVectorType::iterator i;
	for (i = m_useKeyWithList.begin(); i != m_useKeyWithList.end(); ++i)
		delete (*i);

}

// --------------------------------------------------------------------------------
//           Load from DOM
// --------------------------------------------------------------------------------

void XKMSKeyBindingAbstractTypeImpl::load(void) {

	if (mp_keyBindingAbstractTypeElement == NULL) {
		throw XSECException(XSECException::ExpectedXKMSChildNotFound,
			"XKMSKeyBindingAbstractTypeImpl::load - called on empty DOM");
	}

	// Id
	mp_idAttr =
		mp_keyBindingAbstractTypeElement->getAttributeNodeNS(NULL, XKMSConstants::s_tagId);

	DOMElement * tmpElt = findFirstElementChild(mp_keyBindingAbstractTypeElement);

	if (tmpElt != NULL && strEquals(getDSIGLocalName(tmpElt), XKMSConstants::s_tagKeyInfo)) {

		if (mp_keyInfoList != NULL)
			delete mp_keyInfoList;

		XSECnew(mp_keyInfoList, DSIGKeyInfoList(mp_env));

		mp_keyInfoList->loadListFromXML(tmpElt);
		mp_keyInfoElement = tmpElt;

		tmpElt = findNextElementChild(tmpElt);

	}

	while (tmpElt != NULL && strEquals(getXKMSLocalName(tmpElt), XKMSConstants::s_tagKeyUsage)) {

		DOMNode * txt = findFirstChildOfType(tmpElt, DOMNode::TEXT_NODE);

		if (txt == NULL) {
			throw XSECException(XSECException::ExpectedXKMSChildNotFound,
				"XKMSKeyBindingAbstractTypeImpl::load - Require text node beneath <KeyUsage>");
		}

		const XMLCh * usageStr = txt->getNodeValue();
		int index = XMLString::indexOf(usageStr, chPound);
		if (index == -1 || XMLString::compareNString(usageStr, XKMSConstants::s_unicodeStrURIXKMS, index)) {
			throw XSECException(XSECException::XKMSError,
				"XKMSResultType::load - KeyUsage not in XKMS Name Space");
		}

		usageStr = &usageStr[index+1];

		if (strEquals(usageStr, XKMSConstants::s_tagEncryption)) {
			mp_keyUsageEncryptionElement = tmpElt;
		} else 	if (strEquals(usageStr, XKMSConstants::s_tagExchange)) {
			mp_keyUsageExchangeElement = tmpElt;
		} else if (strEquals(usageStr, XKMSConstants::s_tagSignature)) {
			mp_keyUsageSignatureElement = tmpElt;
		} else {
			throw XSECException(XSECException::ExpectedXKMSChildNotFound,
				"XKMSKeyBindingAbstractTypeImpl::load - require Encryption, Exchange or Signature text node beneath <KeyUsage>");
		}

		tmpElt = findNextElementChild(tmpElt);
	}

	while (tmpElt != NULL && strEquals(getXKMSLocalName(tmpElt), XKMSConstants::s_tagUseKeyWith)) {

		XKMSUseKeyWithImpl *ukw;
		XSECnew(ukw, XKMSUseKeyWithImpl(mp_env, tmpElt));

		m_useKeyWithList.push_back(ukw);
		ukw->load();

		tmpElt = findNextElementChild(tmpElt);
	}
}

// --------------------------------------------------------------------------------
//           Create Blank
// --------------------------------------------------------------------------------

DOMElement * XKMSKeyBindingAbstractTypeImpl::createBlankKeyBindingAbstractType(const XMLCh * tag) {

	// Get some setup values
	safeBuffer str;
	DOMDocument *doc = mp_env->getParentDocument();
	const XMLCh * prefix = mp_env->getXKMSNSPrefix();

	makeQName(str, prefix, tag);

	mp_keyBindingAbstractTypeElement = doc->createElementNS(XKMSConstants::s_unicodeStrURIXKMS,
												str.rawXMLChBuffer());

	mp_env->doPrettyPrint(mp_keyBindingAbstractTypeElement);

	return mp_keyBindingAbstractTypeElement;

}

// --------------------------------------------------------------------------------
//           Getter methods
// --------------------------------------------------------------------------------

DOMElement * XKMSKeyBindingAbstractTypeImpl::getElement(void) const {

	return mp_keyBindingAbstractTypeElement;

}

const XMLCh * XKMSKeyBindingAbstractTypeImpl::getId(void) const {

	return (mp_idAttr != NULL ? mp_idAttr->getNodeValue() : NULL);

}

DSIGKeyInfoList * XKMSKeyBindingAbstractTypeImpl::getKeyInfoList(void) const {

	return mp_keyInfoList;

}

bool XKMSKeyBindingAbstractTypeImpl::getEncryptionKeyUsage(void) const {

	return (mp_keyUsageEncryptionElement != NULL ||
		(mp_keyUsageExchangeElement == NULL && mp_keyUsageSignatureElement == NULL));

}

bool XKMSKeyBindingAbstractTypeImpl::getSignatureKeyUsage(void) const {

	return (mp_keyUsageSignatureElement != NULL ||
		(mp_keyUsageExchangeElement == NULL && mp_keyUsageEncryptionElement == NULL));

}

bool XKMSKeyBindingAbstractTypeImpl::getExchangeKeyUsage(void) const {

	return (mp_keyUsageExchangeElement != NULL ||
		(mp_keyUsageEncryptionElement == NULL && mp_keyUsageSignatureElement == NULL));

}

// --------------------------------------------------------------------------------
//			KeyInfo elements
// --------------------------------------------------------------------------------

DSIGKeyInfoList * XKMSKeyBindingAbstractTypeImpl::getKeyInfoList() {

	return mp_keyInfoList;

}

void XKMSKeyBindingAbstractTypeImpl::clearKeyInfo(void) {

	if (mp_keyInfoElement == NULL)
		return;

	if (mp_keyBindingAbstractTypeElement->removeChild(mp_keyInfoElement) != mp_keyInfoElement) {

		throw XSECException(XSECException::ExpectedDSIGChildNotFound,
			"Attempted to remove KeyInfo node but it is no longer a child of <KeyBindingAbstractType>");

	}

	mp_keyInfoElement->release();		// No longer required

	mp_keyInfoElement = NULL;

	// Clear out the list
	mp_keyInfoList->empty();

}

void XKMSKeyBindingAbstractTypeImpl::createKeyInfoElement(void) {

	if (mp_keyInfoElement != NULL)
		return;

	safeBuffer str;

	const XMLCh * prefixNS = mp_env->getDSIGNSPrefix();
	makeQName(str, prefixNS, "KeyInfo");

	mp_keyInfoElement = mp_keyInfoList->createKeyInfo();

	// Needs to be first element
	DOMNode * insertBefore = mp_keyBindingAbstractTypeElement->getFirstChild();

	if (insertBefore != NULL) {

		if (mp_env->getPrettyPrintFlag() == true)
			mp_keyBindingAbstractTypeElement->insertBefore(mp_env->getParentDocument()->createTextNode(DSIGConstants::s_unicodeStrNL), insertBefore);
		mp_keyBindingAbstractTypeElement->insertBefore(mp_keyInfoElement, insertBefore);

	}

	else {

		mp_keyBindingAbstractTypeElement->appendChild(mp_keyInfoElement);
		mp_env->doPrettyPrint(mp_keyBindingAbstractTypeElement);

	}

	// Need to add the DS namespace

	if (prefixNS[0] == '\0') {
		str.sbTranscodeIn("xmlns");
	}
	else {
		str.sbTranscodeIn("xmlns:");
		str.sbXMLChCat(prefixNS);
	}

	mp_keyInfoElement->setAttributeNS(DSIGConstants::s_unicodeStrURIXMLNS,
							str.rawXMLChBuffer(),
							DSIGConstants::s_unicodeStrURIDSIG);

}

DSIGKeyInfoName * XKMSKeyBindingAbstractTypeImpl::appendKeyName(const XMLCh * name, bool isDName) {

	createKeyInfoElement();
	return mp_keyInfoList->appendKeyName(name, isDName);

}

DSIGKeyInfoValue * XKMSKeyBindingAbstractTypeImpl::appendDSAKeyValue(const XMLCh * P,
						   const XMLCh * Q,
						   const XMLCh * G,
						   const XMLCh * Y) {

	createKeyInfoElement();
	return mp_keyInfoList->appendDSAKeyValue(P, Q, G, Y);

}

DSIGKeyInfoValue * XKMSKeyBindingAbstractTypeImpl::appendRSAKeyValue(const XMLCh * modulus,
						   const XMLCh * exponent) {

	createKeyInfoElement();
	return mp_keyInfoList->appendRSAKeyValue(modulus, exponent);

}

DSIGKeyInfoX509 * XKMSKeyBindingAbstractTypeImpl::appendX509Data(void) {

	createKeyInfoElement();
	return mp_keyInfoList->appendX509Data();

}

DSIGKeyInfoPGPData * XKMSKeyBindingAbstractTypeImpl::appendPGPData(const XMLCh * id, const XMLCh * packet) {

	createKeyInfoElement();
	return mp_keyInfoList->appendPGPData(id, packet);

}

DSIGKeyInfoSPKIData * XKMSKeyBindingAbstractTypeImpl::appendSPKIData(const XMLCh * sexp) {

	createKeyInfoElement();
	return mp_keyInfoList->appendSPKIData(sexp);

}

DSIGKeyInfoMgmtData * XKMSKeyBindingAbstractTypeImpl::appendMgmtData(const XMLCh * data) {

	createKeyInfoElement();
	return mp_keyInfoList->appendMgmtData(data);

}

// --------------------------------------------------------------------------------
//           Setter methods
// --------------------------------------------------------------------------------

void XKMSKeyBindingAbstractTypeImpl::setId(const XMLCh * id) {

	// Setup the id
	XMLCh * myId;

	if (id == NULL)
		myId = generateId();

	mp_keyBindingAbstractTypeElement->setAttributeNS(NULL, XKMSConstants::s_tagId, id ? id : myId);
	if (id == NULL)
	    XSEC_RELEASE_XMLCH(myId);
	mp_keyBindingAbstractTypeElement->setIdAttributeNS(NULL, XKMSConstants::s_tagId, true);
	mp_idAttr =
		mp_keyBindingAbstractTypeElement->getAttributeNodeNS(NULL, XKMSConstants::s_tagId);

}

DOMElement * XKMSKeyBindingAbstractTypeImpl::setKeyUsage(const XMLCh * usage) {

	/* Create the element and string*/
	safeBuffer str;
	DOMDocument *doc = mp_env->getParentDocument();
	const XMLCh * prefix = mp_env->getXKMSNSPrefix();

	makeQName(str, prefix, XKMSConstants::s_tagKeyUsage);

	/* Create the element */
	DOMElement * e = doc->createElementNS(XKMSConstants::s_unicodeStrURIXKMS,
		str.rawXMLChBuffer());

	str.sbXMLChIn(XKMSConstants::s_unicodeStrURIXKMS);
	str.sbXMLChCat(usage);
	e->appendChild(doc->createTextNode(str.rawXMLChBuffer()));

	/* Now find where it goes */

	DOMElement * t = findFirstElementChild(mp_keyBindingAbstractTypeElement);
	while (t != NULL) {
		if (!strEquals(getDSIGLocalName(t), XKMSConstants::s_tagKeyInfo) &&
			!strEquals(getXKMSLocalName(t), XKMSConstants::s_tagKeyUsage))
			break;

		t = findNextElementChild(t);
	}

	// Append the element
	if (t == NULL) {
		mp_keyBindingAbstractTypeElement->appendChild(e);
		mp_env->doPrettyPrint(mp_keyBindingAbstractTypeElement);
	}
	else {
		mp_keyBindingAbstractTypeElement->insertBefore(e, t);
		if (mp_env->getPrettyPrintFlag()) {
			mp_keyBindingAbstractTypeElement->insertBefore(
				mp_env->getParentDocument()->createTextNode(DSIGConstants::s_unicodeStrNL),
				t);
		}
	}

	return e;

}

void XKMSKeyBindingAbstractTypeImpl::setEncryptionKeyUsage(void) {

	if (mp_keyUsageEncryptionElement != NULL)
		return;

	mp_keyUsageEncryptionElement = setKeyUsage(XKMSConstants::s_tagEncryption);

}
void XKMSKeyBindingAbstractTypeImpl::setSignatureKeyUsage(void) {

	if (mp_keyUsageSignatureElement != NULL)
		return;

	mp_keyUsageSignatureElement = setKeyUsage(XKMSConstants::s_tagSignature);

}
void XKMSKeyBindingAbstractTypeImpl::setExchangeKeyUsage(void) {

	if (mp_keyUsageExchangeElement != NULL)
		return;

	mp_keyUsageExchangeElement = setKeyUsage(XKMSConstants::s_tagExchange);

}

// --------------------------------------------------------------------------------
//           UseKeyWith handling
// --------------------------------------------------------------------------------

int XKMSKeyBindingAbstractTypeImpl::getUseKeyWithSize(void) const {

	return (int) m_useKeyWithList.size();

}

XKMSUseKeyWith * XKMSKeyBindingAbstractTypeImpl::getUseKeyWithItem(int item) const {

	if (item < 0 || item >= (int) m_useKeyWithList.size()) {
		throw XSECException(XSECException::XKMSError,
			"XKMSKeyBindingAbstractType::getUseKeyWithItem - item out of range");
	}

	return m_useKeyWithList[item];

}

XKMSUseKeyWith * XKMSKeyBindingAbstractTypeImpl::appendUseKeyWithItem(
			const XMLCh * application,
			const XMLCh * identifier) {

	XKMSUseKeyWithImpl * u;

	XSECnew(u, XKMSUseKeyWithImpl(mp_env));

	m_useKeyWithList.push_back(u);

	DOMElement * e = u->createBlankUseKeyWith(application, identifier);

	// Find where to append the element
	DOMElement * t = findFirstElementChild(mp_keyBindingAbstractTypeElement);
	while (t != NULL) {
		if (!strEquals(getDSIGLocalName(t), XKMSConstants::s_tagKeyInfo) &&
			!strEquals(getXKMSLocalName(t), XKMSConstants::s_tagKeyUsage) &&
			!strEquals(getXKMSLocalName(t), XKMSConstants::s_tagUseKeyWith))
			break;

		t = findNextElementChild(t);
	}

	// Append the element
	if (t == NULL) {
		mp_keyBindingAbstractTypeElement->appendChild(e);
		mp_env->doPrettyPrint(mp_keyBindingAbstractTypeElement);
	}
	else {
		mp_keyBindingAbstractTypeElement->insertBefore(e, t);
		if (mp_env->getPrettyPrintFlag()) {
			mp_keyBindingAbstractTypeElement->insertBefore(
				mp_env->getParentDocument()->createTextNode(DSIGConstants::s_unicodeStrNL),
				t);
		}
	}

	return u;

}

#endif /* XSEC_XKMS_ENABLED */


text:
json
(filter in module ng
)

Improve this doc
Description

Allows you to convert a JavaScript object into JSON string.

This filter is mostly useful for debugging. When using the double curly {{value}} notation
the binding is automatically converted to JSON.

Usage

In HTML Template Binding

{{ json_expression | json }}

In JavaScript

$filter('json')(object)

Parameters

object – {*} –

Any JavaScript object (including arrays and primitive types) to filter.

Returns

{string}
–

JSON string.

Example

Source

Demo


text: Ruby and Rails bootcamp materials and assignments.


text:
package com.hackaton.lviv.rest;

import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.hackaton.lviv.service.AggregatorService;

@Path("/aggregator")
@Component
public class LoggerAggregatorApi {

	@Autowired
	private AggregatorService aggregatorService;

	@GET
	@Path("/errors")
	@Produces(MediaType.APPLICATION_JSON)
	public Response getErrors() {
		return Response.status(200)
				.build();
	}

	@GET
	@Path("/logs")
	@Produces(MediaType.APPLICATION_JSON)
	public Response getLogFiles() {
		List<String> files = aggregatorService.getLogFilesList();
		return Response.ok().entity(files).build();
	}

	/**
	 * ��� ����� ���� ������ ���� � ������ �� ����� notifyUsers
	 */
	public void getContent() {

	}

	/**
	 * ������ �����. ���� �� ���� ��� ����� � ������� � ����(���������)
	 * �� ����� ������. (�� � ���� �������� �� ������ ���� ���� ��� �� ���)
	 *
	 * @param s
	 */
	public void processLogs(String s) {
		//aggregatorService.processLogs(s);
		//getAllRulesForFile
		//do regex
		//if match get user of regex and notify
	}

}


text:
<?php

namespace Eklerni\DatabaseBundle\Repository;

use Doctrine\ORM\EntityRepository;

class ActiviteRepository extends EntityRepository implements CASRepositoryInterface
{

    /**
     * @return mixed
     */
    public function findAll()
    {
        return $this->_em->createQueryBuilder()
            ->select("a")
            ->from("EklerniDatabaseBundle:Activite", "a")
            ->innerJoin("a.matiere", 'm')
            ->orderBy('m.name, a.name');
    }

    /**
     * @param $idProf integer
     * @return mixed
     */
    public function findByProf($idProf)
    {
        return $this->_em->createQueryBuilder()
            ->select("a")
            ->from("EklerniDatabaseBundle:Activite", "a")
            ->innerJoin("a.matiere", "m")
            ->innerJoin("m.classes", "c")
            ->innerJoin("c.enseignants", "e")
            ->where("e.id = :id")
            ->setParameter("id", $idProf)
            ->orderBy('m.name, a.name');
    }

    public function findByMatiere($idMatiere)
    {
        return $this->_em->createQueryBuilder()
            ->select("a")
            ->from("EklerniDatabaseBundle:Activite", "a")
            ->innerJoin("a.matiere", "m")
            ->where("m.id = :id")
            ->setParameter("id", $idMatiere);
    }
}


text:
from distutils.core import setup
setup(
    name = 'url_extract',
    packages = ['url_extract'],
    version = '0.16',
    description = 'extracts tld, domain, subdomains and query from URLs. It also validates the URLs.',
    author = 'Yoan Arnaudov',
    author_email = 'jonidev@gmail.com',
    url = 'https://github.com/nacholibre/url_extract',
    download_url = 'https://github.com/nacholibre/url_extract/tarball/0.16',
    keywords = ['domain', 'tld', 'extract'],
    classifiers = [],
)


text:
require 'rubygems'

active_record_version = ENV["ACTIVE_RECORD_VERSION"] || [">= 2.2.2"]
active_record_version = [active_record_version] unless active_record_version.is_a?(Array)
gem 'activerecord', *active_record_version

require 'active_record'
puts "Testing Against ActiveRecord #{ActiveRecord::VERSION::STRING}" if defined?(ActiveRecord::VERSION)

require File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib', 'seamless_database_pool'))
require File.expand_path(File.join(File.dirname(__FILE__), 'test_model'))

$LOAD_PATH << File.expand_path("../test_adapter", __FILE__)


text:
package se.ranzdo.bukkit.methodcommand.handlers;

import org.bukkit.command.CommandSender;

import se.ranzdo.bukkit.methodcommand.CommandArgument;
import se.ranzdo.bukkit.methodcommand.TransformError;

public class DoubleArgumentHandler extends NumberArgumentHandler<Double> {
	public DoubleArgumentHandler() {
		setMessage("parse_error", "The parameter [%p] is not a number");
	}

	@Override
	public Double transform(CommandSender sender, CommandArgument argument, String value) throws TransformError {
		try {
			return Double.parseDouble(value);
		}
		catch(NumberFormatException e) {
			throw new TransformError(argument.getMessage("parse_error"));
		}
	}
}


text:
"""An anagram is a type of word play, the result of rearranging the letters
of a word or phrase to produce a new word or phrase, using all the original
letters exactly once; e.g., orchestra = carthorse, A decimal point = I'm
a dot in place. Write a Python program that, when started 1) randomly
picks a word w from given list of words, 2) randomly permutes w (thus
creating an anagram of w), 3) presents the anagram to the user, and 4)
enters an interactive loop in which the user is invited to guess the
original word. It may be a good idea to work with (say) colour words
only. The interaction with the program may look like so:

>>> import anagram
Colour word anagram: onwbr
Guess the colour word!
black
Guess the colour word!
brown
Correct!"""

def anagram(word_list, subject):
	pass

#test
anagram(['brown','yellow', 'green', 'red', 'blue'], 'colour')
anagram(['Haiti','USA', 'France', 'Spain', 'China'], 'country')


text:
package org.apache.webbeans.test.interceptors.ejb;

import java.util.ArrayList;
import java.util.Collection;

import org.junit.Assert;

import org.apache.webbeans.test.AbstractUnitTest;
import org.apache.webbeans.test.interceptors.beans.ApplicationScopedBean;
import org.apache.webbeans.test.interceptors.beans.DependentScopedBean;
import org.apache.webbeans.test.interceptors.beans.RequestScopedBean;
import org.junit.Test;

public class EjbInterceptorTest extends AbstractUnitTest
{

    @Test
    public void testEjbInterceptor()
    {
        Collection<String> beanXmls = new ArrayList<String>();
        Collection<Class<?>> beanClasses = new ArrayList<Class<?>>();
        beanClasses.add(RequestScopedBean.class);
        beanClasses.add(ManagedBeanWithEjbInterceptor.class);
        beanClasses.add(ApplicationScopedBean.class);
        beanClasses.add(DependentScopedBean.class);
        beanClasses.add(EjbInterceptor.class);

        startContainer(beanClasses, beanXmls);

        ManagedBeanWithEjbInterceptor reference = getInstance(ManagedBeanWithEjbInterceptor.class);
        Assert.assertNotNull(reference);

        EjbInterceptor.CALLED = false;
        reference.sayHello();
        Assert.assertTrue(EjbInterceptor.CALLED);

        shutDownContainer();
    }

    @Test
    public void testEjbMethodInterceptor()
    {
        Collection<String> beanXmls = new ArrayList<String>();
        Collection<Class<?>> beanClasses = new ArrayList<Class<?>>();
        beanClasses.add(RequestScopedBean.class);
        beanClasses.add(ManagedBeanWithMethodEjbInterceptor.class);
        beanClasses.add(ApplicationScopedBean.class);
        beanClasses.add(DependentScopedBean.class);
        beanClasses.add(EjbInterceptor.class);

        startContainer(beanClasses, beanXmls);

        ManagedBeanWithMethodEjbInterceptor reference = getInstance(ManagedBeanWithMethodEjbInterceptor.class);
        Assert.assertNotNull(reference);

        EjbInterceptor.CALLED = false;
        reference.sayHello();
        Assert.assertTrue(EjbInterceptor.CALLED);

        EjbInterceptor.CALLED = false;
        reference.uninterceptedAction();
        Assert.assertFalse(EjbInterceptor.CALLED);

        shutDownContainer();
    }

    @Test
    public void testDynamicEjbInterceptor()
    {
        Collection<String> beanXmls = new ArrayList<String>();
        Collection<Class<?>> beanClasses = new ArrayList<Class<?>>();
        beanClasses.add(ManagedBeanWithoutInterceptor.class);
        beanClasses.add(EjbInterceptor.class);
        addExtension(new EjbInterceptorExtension());

        startContainer(beanClasses, beanXmls);

        ManagedBeanWithoutInterceptor reference = getInstance(ManagedBeanWithoutInterceptor.class);
        Assert.assertNotNull(reference);

        EjbInterceptor.CALLED = false;
        reference.sayHello();
        Assert.assertTrue(EjbInterceptor.CALLED);

        shutDownContainer();
    }
}


text:
import { IterableX } from '../../iterable/iterablex';
import { repeatValue as _repeatValue } from '../../iterable/repeatvalue';

/** @nocollapse */
IterableX.repeatValue = _repeatValue;

export declare namespace iterable {
  let repeatStatic: typeof _repeatValue;
}

declare module '../../iterable/iterablex' {
  // eslint-disable-next-line no-shadow
  namespace IterableX {
    export let repeatValue: typeof _repeatValue;
  }
}


text:
package com.manolovn.sample.exporter;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Simple image exporter
 */
public class ImageExporter {

    private static final String ALBUM_NAME = "Trianglify";

    public ImageExporter() {
    }

    public void exportFromView(final Context context, final View view) throws IOException {
        File folder = FileUtils.getOrCreateFolder(ALBUM_NAME);

        Bitmap bitmap = view.getDrawingCache(true);

        File file = null;
        int number = 1;
        boolean creating = true;
        while (creating) {
            String imageName = String.format("%05d", number);
            file = new File(folder + "/" + imageName + ".png");

            if (file.exists()) {
                number++;
            } else {
                creating = false;
            }
        }

        FileOutputStream fos = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);

        fos.flush();
        fos.close();

        file.createNewFile();
        FileUtils.scanForFile(context, file.getPath());
    }
}


text:
{{+bindTo:partials.standard_nacl_api}}

logging.h File Reference

{{- dummy div to appease doxygen -}}

Include dependency graph for logging.h:

<map name="logging_8h" id="logging_8h">
</map>

Defines

#define 	PP_DCHECK(a)   assert(a)

#define 	PP_NOTREACHED()   assert(false)

Detailed Description

This file defines two macro asserts.

Define Documentation

#define PP_DCHECK
(

a	)
   assert(a)

This macro asserts that 'a' evaluates to true.

In debug mode, this macro will crash the program if the assertion evaluates to false. It (typically) has no effect in release mode.

#define PP_NOTREACHED
(
	)
   assert(false)

This macro asserts false in debug builds.

It's used in code paths that you don't expect to execute.

Example:

 if (!pointer) {
 // Pointer wasn't valid! This shouldn't happen.
 PP_NOTREACHED();
 return;
 }
 // Do stuff to the pointer, since you know it's valid.
 pointer->DoSomething();

{{/partials.standard_nacl_api}}


text:
<dom-module id="blogdown-render">
  <template>
  </template>
  <script>
    class BlogdownRender {
      beforeRegister() {
        this.is = 'blogdown-render';

        this.actions = {
          cacheFile: function(hash, file) {
            return (dispatch) => {
              const payload = {};
              payload[hash] = file;
              dispatch({
                type: CACHE_FILE,
                payload
              });
            };
          }
        };

        this.properties = {
          route: {
            type: Object,
            statePath: 'route'
          },
          meta: {
            type: Object,
            statePath: 'meta'
          },
          baseUrl: {
            type: String,
            statePath: 'meta.baseUrl'
          },
          settings: {
            type: Object,
            statePath: 'settings'
          },
          urlKnown: {
            type: Boolean,
            value: false
          },
          renderer: {
            type: Object,
            value: {}
          },
          url: {
            type: String,
            value: {}
          },
          body: {
            type: String,
            value: ''
          },
          page: {
            type: Object
          },
          post: {
            type: Object
          }
        };
      }

      get behaviors() {
        return [
          ReduxActionsBehavior,
          ReduxStateBehavior
        ];
      }

      ready() {
        this.page ? this.set('content', this.page) : this.set('content', this.post);
        const cachedFiles = this.meta.cachedFiles;
        const hash = murmurHash3.x86.hash128(this.content.slug + JSON.stringify(this.content.taxonomy));
        if (this.settings.cacheBusting !== 'always' && _.includes(_.keys(cachedFiles), hash)) {
          const cachedFile = cachedFiles[hash];
          const renderer = document.createElement(app._renderers[cachedFile.renderer]);
          renderer.content = cachedFile.content;
          renderer.url = cachedFile.url;
          renderer.body = cachedFile.body;
          Polymer.dom(this.root).appendChild(renderer);
          return Promise.resolve();
        }
        return this.getUrl(this.content).then((url) => {
          const renderer = document.createElement(app._renderers[this.renderer]);
          renderer.content = this.content;
          renderer.url = this.url;
          renderer.body = this.body;
          if (this.settings.cacheBusting !== 'always') {
            this.dispatch('cacheFile', hash, {
              content: this.content,
              url: this.url,
              body: this.body,
              renderer: this.renderer
            });
          }
          Polymer.dom(this.root).appendChild(renderer);
        });
      }

      getUrl(content) {
        let firstRenderer = null;
        const renderers = _.remove(_.keys(app._renderers), (renderer) => {
          if (this.content.format !== renderer) return true;
          firstRenderer = renderer;
          return false;
        });
        if (firstRenderer) renderers.unshift(firstRenderer);
        const promises = [];
        if (this.page) {
          _.each(renderers, (renderer) => {
            const url = `${app.getContentUrl()}/pages/${this.page.slug}.${renderer}`;
            promises.push(this.loadFile.bind(this, url, renderer));
          });
          if (this.page.slug !== _.snakeCase(this.page.title).replace(/_/g, '-')) {
            _.each(renderers, (renderer) => {
              const url = `${app.getContentUrl()}/pages/${_.snakeCase(this.page.title).replace(/_/g, '-')}`
                        + `.${renderer}`;
              promises.push(this.loadFile.bind(this, url, renderer));
            });
          }
        } else {
          _.each(renderers, (renderer) => {
            const url = `${app.getContentUrl()}/${this.route.slugs.parent}/`
                      + `${this.post.slug}.${renderer}`;
            promises.push(this.loadFile.bind(this, url, renderer));
          });
          if (this.post.slug !== _.snakeCase(this.post.title).replace(/_/g, '-')) {
            _.each(renderers, (renderer) => {
              const url = `${app.getContentUrl()}/${this.route.slugs.parent}/`
                        + `${_.snakeCase(this.post.title).replace(/_/g, '-')}.${renderer}`;
              promises.push(this.loadFile.bind(this, url, renderer));
            });
          }
          if (this.post.date && this.post.slug !== this.post.date.format('X')) {
            _.each(renderers, (renderer) => {
              const url = `${app.getContentUrl()}/${this.route.slugs.parent}/`
                        + `${this.post.date.format('X')}.${renderer}`;
              promises.push(this.loadFile.bind(this, url, renderer));
            });
          }
        }
        let promiseChain = Promise.resolve();
        _.each(promises, (promise) => {
          promiseChain = promiseChain.then(promise);
        });
        return promiseChain.then(() => {
          return this.url;
        });
      }

      loadFile(url, renderer) {
        url = `${url}?${app.getTimestamp()}`;
        if (this.urlKnown) return Promise.resolve();
        return fetch(url).then((res) => {
          if (res.status === 404) return null;
          return res.text();
        }).then((body) => {
          if (body) {
            this.set('body', body);
            this.set('url', url);
            this.set('renderer', renderer);
            this.set('urlKnown', true);
          }
        });
      }
    }
    Polymer(BlogdownRender);
  </script>
</dom-module>


text:
package org.kie.workbench.common.stunner.client.widgets.canvas;

import com.ait.lienzo.client.core.shape.Layer;
import com.ait.lienzo.client.core.shape.MultiPath;
import com.ait.lienzo.client.core.shape.wires.WiresLayer;
import com.ait.lienzo.client.core.shape.wires.WiresShape;
import com.ait.lienzo.client.core.types.Point2D;
import com.ait.lienzo.client.widget.panel.Bounds;
import com.ait.lienzo.client.widget.panel.impl.BoundsProviderFactory;
import com.ait.lienzo.test.LienzoMockitoTestRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import static org.junit.Assert.assertEquals;

@RunWith(LienzoMockitoTestRunner.class)
public class StunnerBoundsProviderFactoryTest {

    private Layer layer;
    private WiresLayer wiresLayer;
    private WiresShape shape1;
    private WiresShape shape2;

    @Before
    public void init() {
        layer = new Layer();
        wiresLayer = new WiresLayer(layer);
        shape1 = new WiresShape(new MultiPath().circle(50))
                .setLocation(new Point2D(100, 33));
        shape2 = new WiresShape(new MultiPath().circle(230))
                .setLocation(new Point2D(15, 120));
        wiresLayer.add(shape1);
        wiresLayer.add(shape2);
    }

    @Test
    public void testNewProvider() {
        BoundsProviderFactory.WiresBoundsProvider provider = StunnerBoundsProviderFactory.newProvider();
        Bounds bounds = provider.build(provider.getAll(wiresLayer));
        assertEquals(0d, bounds.getX(), 0d);
        assertEquals(0d, bounds.getY(), 0d);
        assertEquals(1260d, bounds.getWidth(), 0d);
        assertEquals(580d + StunnerBoundsProviderFactory.PADDING, bounds.getHeight(), 0d);
    }

    @Test
    public void testComputeSizesPreservingRatio() {
        final int width = 330;
        final int height = 110;
        final int computeWidth = StunnerBoundsProviderFactory.computeWidth(height);
        final int computeHeight = StunnerBoundsProviderFactory.computeHeight(width);
        assertEquals(220, computeWidth);
        assertEquals(165, computeHeight);
    }
}


text:
from rest_framework import serializers
from workflow.apps.team.models import Person, Team
from workflow.apps.workflow.models import Comment, Item, Workflow, Project, ItemCategory

class PersonSerializer(serializers.ModelSerializer):
    username = serializers.CharField(source='user.username', read_only=True)

    class Meta:
        model = Person

class TeamSerializer(serializers.ModelSerializer):
    class Meta:
        model = Team

class CommentSerializer(serializers.ModelSerializer):
    username = serializers.CharField(source='person.user.username', read_only=True)

    class Meta:
        model = Comment

class WorkflowSerializer(serializers.ModelSerializer):
    success_percent = serializers.FloatField(source='get_success_percent')

    class Meta:
        model = Workflow

class ProjectSerializer(serializers.ModelSerializer):
    class Meta:
        model = Project

class ItemCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = ItemCategory

class ItemSerializer(serializers.ModelSerializer):
    category = ItemCategorySerializer()

    class Meta:
        model = Item


text:
import Rect from './elements/Rect';
import Circle from './elements/Circle';
import Ellipse from './elements/Ellipse';
import Polygon from './elements/Polygon';
import Polyline from './elements/Polyline';
import Line from './elements/Line';
import Svg from './elements/Svg';
import Path from './elements/Path';
import G from './elements/G';
import Text from './elements/Text';
import Use from './elements/Use';
import Image from './elements/Image';
import Symbol  from './elements/Symbol';
import Defs from './elements/Defs';
import LinearGradient from './elements/LinearGradient';
import RadialGradient from './elements/RadialGradient';
import Stop from './elements/Stop';
import ClipPath from './elements/ClipPath';

export {
    Svg,
    Circle,
    Ellipse,
    G,
    Text,
    Path,
    Polygon,
    Polyline,
    Line,
    Rect,
    Use,
    Image,
    Symbol,
    Defs,
    LinearGradient,
    RadialGradient,
    Stop,
    ClipPath
};

export default Svg;


text:
package client

import (
	"errors"
	"math"
	"strings"
	"testing"
	"time"

	"github.com/m3db/m3cluster/placement"
	"github.com/m3db/m3cluster/shard"
	"github.com/m3db/m3metrics/aggregation"
	"github.com/m3db/m3metrics/metadata"
	"github.com/m3db/m3metrics/metric"
	"github.com/m3db/m3metrics/metric/aggregated"
	"github.com/m3db/m3metrics/metric/unaggregated"
	"github.com/m3db/m3metrics/pipeline"
	"github.com/m3db/m3metrics/pipeline/applied"
	"github.com/m3db/m3metrics/policy"
	"github.com/m3db/m3x/clock"
	"github.com/m3db/m3x/instrument"
	xtime "github.com/m3db/m3x/time"

	"github.com/golang/mock/gomock"
	"github.com/stretchr/testify/require"
)

var (
	testNowNanos     = time.Now().UnixNano()
	testCutoverNanos = testNowNanos - int64(time.Minute)
	testCutoffNanos  = testNowNanos + int64(time.Hour)
	testCounter      = unaggregated.MetricUnion{
		Type:       metric.CounterType,
		ID:         []byte("foo"),
		CounterVal: 1234,
	}
	testBatchTimer = unaggregated.MetricUnion{
		Type:          metric.TimerType,
		ID:            []byte("foo"),
		BatchTimerVal: []float64{222.22, 345.67, 901.23345},
	}
	testGauge = unaggregated.MetricUnion{
		Type:     metric.GaugeType,
		ID:       []byte("foo"),
		GaugeVal: 123.456,
	}
	testTimed = aggregated.Metric{
		Type:      metric.CounterType,
		ID:        []byte("testForwarded"),
		TimeNanos: 1234,
		Value:     178,
	}
	testForwarded = aggregated.ForwardedMetric{
		Type:      metric.CounterType,
		ID:        []byte("testForwarded"),
		TimeNanos: 1234,
		Values:    []float64{34567, 256, 178},
	}
	testStagedMetadatas = metadata.StagedMetadatas{
		{
			CutoverNanos: 100,
			Tombstoned:   false,
			Metadata: metadata.Metadata{
				Pipelines: []metadata.PipelineMetadata{
					{
						AggregationID: aggregation.DefaultID,
						StoragePolicies: []policy.StoragePolicy{
							policy.NewStoragePolicy(20*time.Second, xtime.Second, 6*time.Hour),
							policy.NewStoragePolicy(time.Minute, xtime.Minute, 2*24*time.Hour),
							policy.NewStoragePolicy(10*time.Minute, xtime.Minute, 25*24*time.Hour),
						},
					},
				},
			},
		},
		{
			CutoverNanos: 200,
			Tombstoned:   true,
			Metadata: metadata.Metadata{
				Pipelines: []metadata.PipelineMetadata{
					{
						AggregationID: aggregation.DefaultID,
						StoragePolicies: []policy.StoragePolicy{
							policy.NewStoragePolicy(time.Second, xtime.Second, time.Hour),
						},
					},
				},
			},
		},
	}
	testTimedMetadata = metadata.TimedMetadata{
		AggregationID: aggregation.DefaultID,
		StoragePolicy: policy.NewStoragePolicy(time.Minute, xtime.Minute, 12*time.Hour),
	}
	testForwardMetadata = metadata.ForwardMetadata{
		AggregationID: aggregation.DefaultID,
		StoragePolicy: policy.NewStoragePolicy(time.Minute, xtime.Minute, 12*time.Hour),
		Pipeline: applied.NewPipeline([]applied.OpUnion{
			{
				Type: pipeline.RollupOpType,
				Rollup: applied.RollupOp{
					ID:            []byte("foo"),
					AggregationID: aggregation.MustCompressTypes(aggregation.Count),
				},
			},
		}),
		SourceID:          1234,
		NumForwardedTimes: 3,
	}
	testPlacementInstances = []placement.Instance{
		placement.NewInstance().
			SetID("instance1").
			SetEndpoint("instance1_endpoint").
			SetShards(shard.NewShards([]shard.Shard{
				shard.NewShard(0).
					SetState(shard.Initializing).
					SetCutoverNanos(testCutoverNanos).
					SetCutoffNanos(testCutoffNanos),
				shard.NewShard(1).
					SetState(shard.Initializing).
					SetCutoverNanos(testCutoverNanos).
					SetCutoffNanos(testCutoffNanos),
			})),
		placement.NewInstance().
			SetID("instance2").
			SetEndpoint("instance2_endpoint").
			SetShards(shard.NewShards([]shard.Shard{
				shard.NewShard(2).
					SetState(shard.Initializing).
					SetCutoverNanos(testCutoverNanos).
					SetCutoffNanos(testCutoffNanos),
				shard.NewShard(3).
					SetState(shard.Initializing).
					SetCutoverNanos(testCutoverNanos).
					SetCutoffNanos(testCutoffNanos),
			})),
		placement.NewInstance().
			SetID("instance3").
			SetEndpoint("instance3_endpoint").
			SetShards(shard.NewShards([]shard.Shard{
				shard.NewShard(0).
					SetState(shard.Initializing).
					SetCutoverNanos(testCutoverNanos).
					SetCutoffNanos(testCutoffNanos),
				shard.NewShard(1).
					SetState(shard.Initializing).
					SetCutoverNanos(testCutoverNanos).
					SetCutoffNanos(testCutoffNanos),
			})),
		placement.NewInstance().
			SetID("instance4").
			SetEndpoint("instance4_endpoint").
			SetShards(shard.NewShards([]shard.Shard{
				shard.NewShard(2).
					SetState(shard.Initializing).
					SetCutoverNanos(testCutoverNanos).
					SetCutoffNanos(testCutoffNanos),
				shard.NewShard(3).
					SetState(shard.Initializing).
					SetCutoverNanos(testCutoverNanos).
					SetCutoffNanos(testCutoffNanos),
			})),
	}
	testPlacement = placement.NewPlacement().
			SetVersion(1).
			SetCutoverNanos(12345).
			SetShards([]uint32{0, 1, 2, 3}).
			SetInstances(testPlacementInstances)
)

func TestClientInitUninitializedOrClosed(t *testing.T) {
	c := NewClient(testOptions()).(*client)

	c.state = clientInitialized
	require.Equal(t, errClientIsInitializedOrClosed, c.Init())

	c.state = clientClosed
	require.Equal(t, errClientIsInitializedOrClosed, c.Init())
}

func TestClientInitWatcherWatchError(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	errTestWatcherWatch := errors.New("error watching")
	watcher := placement.NewMockStagedPlacementWatcher(ctrl)
	watcher.EXPECT().Watch().Return(errTestWatcherWatch)
	c := NewClient(testOptions()).(*client)
	c.placementWatcher = watcher
	require.Equal(t, errTestWatcherWatch, c.Init())
}

func TestClientInitSuccess(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	watcher := placement.NewMockStagedPlacementWatcher(ctrl)
	watcher.EXPECT().Watch().Return(nil)
	c := NewClient(testOptions()).(*client)
	c.placementWatcher = watcher
	require.NoError(t, c.Init())
	require.Equal(t, clientInitialized, c.state)
}

func TestClientWriteUntimedMetricClosed(t *testing.T) {
	c := NewClient(testOptions()).(*client)
	c.state = clientUninitialized
	for _, input := range []unaggregated.MetricUnion{testCounter, testBatchTimer, testGauge} {
		var err error
		switch input.Type {
		case metric.CounterType:
			err = c.WriteUntimedCounter(input.Counter(), testStagedMetadatas)
		case metric.TimerType:
			err = c.WriteUntimedBatchTimer(input.BatchTimer(), testStagedMetadatas)
		case metric.GaugeType:
			err = c.WriteUntimedGauge(input.Gauge(), testStagedMetadatas)
		}
		require.Equal(t, errClientIsUninitializedOrClosed, err)
	}
}

func TestClientWriteUntimedMetricActiveStagedPlacementError(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	errActiveStagedPlacementError := errors.New("error active staged placement")
	watcher := placement.NewMockStagedPlacementWatcher(ctrl)
	watcher.EXPECT().ActiveStagedPlacement().Return(nil, nil, errActiveStagedPlacementError).MinTimes(1)
	c := NewClient(testOptions()).(*client)
	c.state = clientInitialized
	c.placementWatcher = watcher

	for _, input := range []unaggregated.MetricUnion{testCounter, testBatchTimer, testGauge} {
		var err error
		switch input.Type {
		case metric.CounterType:
			err = c.WriteUntimedCounter(input.Counter(), testStagedMetadatas)
		case metric.TimerType:
			err = c.WriteUntimedBatchTimer(input.BatchTimer(), testStagedMetadatas)
		case metric.GaugeType:
			err = c.WriteUntimedGauge(input.Gauge(), testStagedMetadatas)
		}
		require.Equal(t, errActiveStagedPlacementError, err)
	}
}

func TestClientWriteUntimedMetricActivePlacementError(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	errActivePlacementError := errors.New("error active placement")
	stagedPlacement := placement.NewMockActiveStagedPlacement(ctrl)
	stagedPlacement.EXPECT().ActivePlacement().Return(nil, nil, errActivePlacementError).MinTimes(1)
	watcher := placement.NewMockStagedPlacementWatcher(ctrl)
	watcher.EXPECT().ActiveStagedPlacement().Return(stagedPlacement, func() {}, nil).MinTimes(1)
	c := NewClient(testOptions()).(*client)
	c.state = clientInitialized
	c.placementWatcher = watcher

	for _, input := range []unaggregated.MetricUnion{testCounter, testBatchTimer, testGauge} {
		var err error
		switch input.Type {
		case metric.CounterType:
			err = c.WriteUntimedCounter(input.Counter(), testStagedMetadatas)
		case metric.TimerType:
			err = c.WriteUntimedBatchTimer(input.BatchTimer(), testStagedMetadatas)
		case metric.GaugeType:
			err = c.WriteUntimedGauge(input.Gauge(), testStagedMetadatas)
		}
		require.Equal(t, errActivePlacementError, err)
	}
}

func TestClientWriteUntimedMetricSuccess(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	var (
		instancesRes []placement.Instance
		shardRes     uint32
		payloadRes   payloadUnion
	)
	writerMgr := NewMockinstanceWriterManager(ctrl)
	writerMgr.EXPECT().
		Write(gomock.Any(), gomock.Any(), gomock.Any()).
		DoAndReturn(func(
			instance placement.Instance,
			shardID uint32,
			payload payloadUnion,
		) error {
			instancesRes = append(instancesRes, instance)
			shardRes = shardID
			payloadRes = payload
			return nil
		}).
		MinTimes(1)
	stagedPlacement := placement.NewMockActiveStagedPlacement(ctrl)
	stagedPlacement.EXPECT().ActivePlacement().Return(testPlacement, func() {}, nil).MinTimes(1)
	watcher := placement.NewMockStagedPlacementWatcher(ctrl)
	watcher.EXPECT().ActiveStagedPlacement().Return(stagedPlacement, func() {}, nil).MinTimes(1)
	c := NewClient(testOptions()).(*client)
	c.state = clientInitialized
	c.nowFn = func() time.Time { return time.Unix(0, testNowNanos) }
	c.writerMgr = writerMgr
	c.placementWatcher = watcher

	expectedInstances := []placement.Instance{
		testPlacementInstances[0],
		testPlacementInstances[2],
	}
	for _, input := range []unaggregated.MetricUnion{testCounter, testBatchTimer, testGauge} {
		// Reset states in each iteration.
		instancesRes = instancesRes[:0]
		shardRes = 0
		payloadRes = payloadUnion{}

		var err error
		switch input.Type {
		case metric.CounterType:
			err = c.WriteUntimedCounter(input.Counter(), testStagedMetadatas)
		case metric.TimerType:
			err = c.WriteUntimedBatchTimer(input.BatchTimer(), testStagedMetadatas)
		case metric.GaugeType:
			err = c.WriteUntimedGauge(input.Gauge(), testStagedMetadatas)
		}

		require.NoError(t, err)
		require.Equal(t, expectedInstances, instancesRes)
		require.Equal(t, uint32(1), shardRes)
		require.Equal(t, untimedType, payloadRes.payloadType)
		require.Equal(t, input, payloadRes.untimed.metric)
		require.Equal(t, testStagedMetadatas, payloadRes.untimed.metadatas)
	}
}

func TestClientWriteUntimedMetricPartialError(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	var (
		instancesRes     []placement.Instance
		shardRes         uint32
		payloadRes       payloadUnion
		errInstanceWrite = errors.New("instance write error")
	)
	writerMgr := NewMockinstanceWriterManager(ctrl)
	writerMgr.EXPECT().
		Write(gomock.Any(), gomock.Any(), gomock.Any()).
		DoAndReturn(func(
			instance placement.Instance,
			shardID uint32,
			payload payloadUnion,
		) error {
			if instance.ID() == testPlacementInstances[0].ID() {
				return errInstanceWrite
			}
			instancesRes = append(instancesRes, instance)
			shardRes = shardID
			payloadRes = payload
			return nil
		}).
		MinTimes(1)
	stagedPlacement := placement.NewMockActiveStagedPlacement(ctrl)
	stagedPlacement.EXPECT().ActivePlacement().Return(testPlacement, func() {}, nil).MinTimes(1)
	watcher := placement.NewMockStagedPlacementWatcher(ctrl)
	watcher.EXPECT().ActiveStagedPlacement().Return(stagedPlacement, func() {}, nil).MinTimes(1)
	c := NewClient(testOptions()).(*client)
	c.state = clientInitialized
	c.nowFn = func() time.Time { return time.Unix(0, testNowNanos) }
	c.writerMgr = writerMgr
	c.placementWatcher = watcher

	expectedInstances := []placement.Instance{
		testPlacementInstances[2],
	}
	err := c.WriteUntimedCounter(testCounter.Counter(), testStagedMetadatas)
	require.Error(t, err)
	require.True(t, strings.Contains(err.Error(), errInstanceWrite.Error()))
	require.Equal(t, expectedInstances, instancesRes)
	require.Equal(t, uint32(1), shardRes)
	require.Equal(t, untimedType, payloadRes.payloadType)
	require.Equal(t, testCounter, payloadRes.untimed.metric)
	require.Equal(t, testStagedMetadatas, payloadRes.untimed.metadatas)
}

func TestClientWriteUntimedMetricBeforeShardCutover(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	var instancesRes []placement.Instance
	stagedPlacement := placement.NewMockActiveStagedPlacement(ctrl)
	stagedPlacement.EXPECT().ActivePlacement().Return(testPlacement, func() {}, nil).MinTimes(1)
	watcher := placement.NewMockStagedPlacementWatcher(ctrl)
	watcher.EXPECT().ActiveStagedPlacement().Return(stagedPlacement, func() {}, nil).MinTimes(1)
	c := NewClient(testOptions()).(*client)
	c.shardCutoverWarmupDuration = time.Second
	c.state = clientInitialized
	c.nowFn = func() time.Time { return time.Unix(0, testCutoverNanos-1).Add(-time.Second) }
	c.writerMgr = nil
	c.placementWatcher = watcher

	err := c.WriteUntimedCounter(testCounter.Counter(), testStagedMetadatas)
	require.NoError(t, err)
	require.Nil(t, instancesRes)
}

func TestClientWriteUntimedMetricAfterShardCutoff(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	var instancesRes []placement.Instance
	stagedPlacement := placement.NewMockActiveStagedPlacement(ctrl)
	stagedPlacement.EXPECT().ActivePlacement().Return(testPlacement, func() {}, nil).MinTimes(1)
	watcher := placement.NewMockStagedPlacementWatcher(ctrl)
	watcher.EXPECT().ActiveStagedPlacement().Return(stagedPlacement, func() {}, nil).MinTimes(1)
	c := NewClient(testOptions()).(*client)
	c.shardCutoffLingerDuration = time.Second
	c.state = clientInitialized
	c.nowFn = func() time.Time { return time.Unix(0, testCutoffNanos+1).Add(time.Second) }
	c.writerMgr = nil
	c.placementWatcher = watcher

	err := c.WriteUntimedCounter(testCounter.Counter(), testStagedMetadatas)
	require.NoError(t, err)
	require.Nil(t, instancesRes)
}

func TestClientWriteTimedMetricSuccess(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	var (
		instancesRes []placement.Instance
		shardRes     uint32
		payloadRes   payloadUnion
	)
	writerMgr := NewMockinstanceWriterManager(ctrl)
	writerMgr.EXPECT().
		Write(gomock.Any(), gomock.Any(), gomock.Any()).
		DoAndReturn(func(
			instance placement.Instance,
			shardID uint32,
			payload payloadUnion,
		) error {
			instancesRes = append(instancesRes, instance)
			shardRes = shardID
			payloadRes = payload
			return nil
		}).
		MinTimes(1)
	stagedPlacement := placement.NewMockActiveStagedPlacement(ctrl)
	stagedPlacement.EXPECT().ActivePlacement().Return(testPlacement, func() {}, nil).MinTimes(1)
	watcher := placement.NewMockStagedPlacementWatcher(ctrl)
	watcher.EXPECT().ActiveStagedPlacement().Return(stagedPlacement, func() {}, nil).MinTimes(1)
	c := NewClient(testOptions()).(*client)
	c.state = clientInitialized
	c.nowFn = func() time.Time { return time.Unix(0, testNowNanos) }
	c.writerMgr = writerMgr
	c.placementWatcher = watcher

	expectedInstances := []placement.Instance{
		testPlacementInstances[0],
		testPlacementInstances[2],
	}
	testMetric := testTimed
	testMetric.TimeNanos = testNowNanos
	err := c.WriteTimed(testMetric, testTimedMetadata)
	require.NoError(t, err)
	require.Equal(t, expectedInstances, instancesRes)
	require.Equal(t, uint32(1), shardRes)
	require.Equal(t, timedType, payloadRes.payloadType)
	require.Equal(t, testMetric, payloadRes.timed.metric)
	require.Equal(t, testTimedMetadata, payloadRes.timed.metadata)
}

func TestClientWriteTimedMetricPartialError(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	var (
		instancesRes     []placement.Instance
		shardRes         uint32
		payloadRes       payloadUnion
		errInstanceWrite = errors.New("instance write error")
	)
	writerMgr := NewMockinstanceWriterManager(ctrl)
	writerMgr.EXPECT().
		Write(gomock.Any(), gomock.Any(), gomock.Any()).
		DoAndReturn(func(
			instance placement.Instance,
			shardID uint32,
			payload payloadUnion,
		) error {
			if instance.ID() == testPlacementInstances[0].ID() {
				return errInstanceWrite
			}
			instancesRes = append(instancesRes, instance)
			shardRes = shardID
			payloadRes = payload
			return nil
		}).
		MinTimes(1)
	stagedPlacement := placement.NewMockActiveStagedPlacement(ctrl)
	stagedPlacement.EXPECT().ActivePlacement().Return(testPlacement, func() {}, nil).MinTimes(1)
	watcher := placement.NewMockStagedPlacementWatcher(ctrl)
	watcher.EXPECT().ActiveStagedPlacement().Return(stagedPlacement, func() {}, nil).MinTimes(1)
	c := NewClient(testOptions()).(*client)
	c.state = clientInitialized
	c.nowFn = func() time.Time { return time.Unix(0, testNowNanos) }
	c.writerMgr = writerMgr
	c.placementWatcher = watcher

	expectedInstances := []placement.Instance{
		testPlacementInstances[2],
	}
	testMetric := testTimed
	testMetric.TimeNanos = testNowNanos
	err := c.WriteTimed(testMetric, testTimedMetadata)
	require.Error(t, err)
	require.True(t, strings.Contains(err.Error(), errInstanceWrite.Error()))
	require.Equal(t, expectedInstances, instancesRes)
	require.Equal(t, uint32(1), shardRes)
	require.Equal(t, timedType, payloadRes.payloadType)
	require.Equal(t, testMetric, payloadRes.timed.metric)
	require.Equal(t, testTimedMetadata, payloadRes.timed.metadata)
}

func TestClientWriteForwardedMetricSuccess(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	var (
		instancesRes []placement.Instance
		shardRes     uint32
		payloadRes   payloadUnion
	)
	writerMgr := NewMockinstanceWriterManager(ctrl)
	writerMgr.EXPECT().
		Write(gomock.Any(), gomock.Any(), gomock.Any()).
		DoAndReturn(func(
			instance placement.Instance,
			shardID uint32,
			payload payloadUnion,
		) error {
			instancesRes = append(instancesRes, instance)
			shardRes = shardID
			payloadRes = payload
			return nil
		}).
		MinTimes(1)
	stagedPlacement := placement.NewMockActiveStagedPlacement(ctrl)
	stagedPlacement.EXPECT().ActivePlacement().Return(testPlacement, func() {}, nil).MinTimes(1)
	watcher := placement.NewMockStagedPlacementWatcher(ctrl)
	watcher.EXPECT().ActiveStagedPlacement().Return(stagedPlacement, func() {}, nil).MinTimes(1)
	c := NewClient(testOptions()).(*client)
	c.state = clientInitialized
	c.nowFn = func() time.Time { return time.Unix(0, testNowNanos) }
	c.writerMgr = writerMgr
	c.placementWatcher = watcher

	expectedInstances := []placement.Instance{
		testPlacementInstances[0],
		testPlacementInstances[2],
	}
	testMetric := testForwarded
	testMetric.TimeNanos = testNowNanos
	err := c.WriteForwarded(testMetric, testForwardMetadata)
	require.NoError(t, err)
	require.Equal(t, expectedInstances, instancesRes)
	require.Equal(t, uint32(1), shardRes)
	require.Equal(t, forwardedType, payloadRes.payloadType)
	require.Equal(t, testMetric, payloadRes.forwarded.metric)
	require.Equal(t, testForwardMetadata, payloadRes.forwarded.metadata)
}

func TestClientWriteForwardedMetricPartialError(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	var (
		instancesRes     []placement.Instance
		shardRes         uint32
		payloadRes       payloadUnion
		errInstanceWrite = errors.New("instance write error")
	)
	writerMgr := NewMockinstanceWriterManager(ctrl)
	writerMgr.EXPECT().
		Write(gomock.Any(), gomock.Any(), gomock.Any()).
		DoAndReturn(func(
			instance placement.Instance,
			shardID uint32,
			payload payloadUnion,
		) error {
			if instance.ID() == testPlacementInstances[0].ID() {
				return errInstanceWrite
			}
			instancesRes = append(instancesRes, instance)
			shardRes = shardID
			payloadRes = payload
			return nil
		}).
		MinTimes(1)
	stagedPlacement := placement.NewMockActiveStagedPlacement(ctrl)
	stagedPlacement.EXPECT().ActivePlacement().Return(testPlacement, func() {}, nil).MinTimes(1)
	watcher := placement.NewMockStagedPlacementWatcher(ctrl)
	watcher.EXPECT().ActiveStagedPlacement().Return(stagedPlacement, func() {}, nil).MinTimes(1)
	c := NewClient(testOptions()).(*client)
	c.state = clientInitialized
	c.nowFn = func() time.Time { return time.Unix(0, testNowNanos) }
	c.writerMgr = writerMgr
	c.placementWatcher = watcher

	expectedInstances := []placement.Instance{
		testPlacementInstances[2],
	}
	testMetric := testForwarded
	testMetric.TimeNanos = testNowNanos
	err := c.WriteForwarded(testMetric, testForwardMetadata)
	require.Error(t, err)
	require.True(t, strings.Contains(err.Error(), errInstanceWrite.Error()))
	require.Equal(t, expectedInstances, instancesRes)
	require.Equal(t, uint32(1), shardRes)
	require.Equal(t, forwardedType, payloadRes.payloadType)
	require.Equal(t, testMetric, payloadRes.forwarded.metric)
	require.Equal(t, testForwardMetadata, payloadRes.forwarded.metadata)
}

func TestClientFlushClosed(t *testing.T) {
	c := NewClient(testOptions()).(*client)
	c.state = clientClosed
	require.Equal(t, errClientIsUninitializedOrClosed, c.Flush())
}

func TestClientFlushError(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	errTestFlush := errors.New("test flush error")
	writerMgr := NewMockinstanceWriterManager(ctrl)
	writerMgr.EXPECT().Flush().Return(errTestFlush).MinTimes(1)
	opts := testOptions()
	c := NewClient(opts).(*client)
	c.state = clientInitialized
	c.writerMgr = writerMgr
	require.Equal(t, errTestFlush, c.Flush())
}

func TestClientFlushSuccess(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	writerMgr := NewMockinstanceWriterManager(ctrl)
	writerMgr.EXPECT().Flush().Return(nil).MinTimes(1)
	opts := testOptions()
	c := NewClient(opts).(*client)
	c.state = clientInitialized
	c.writerMgr = writerMgr
	require.NoError(t, c.Flush())
}

func TestClientCloseUninitializedOrClosed(t *testing.T) {
	c := NewClient(testOptions()).(*client)

	c.state = clientUninitialized
	require.Equal(t, errClientIsUninitializedOrClosed, c.Close())

	c.state = clientClosed
	require.Equal(t, errClientIsUninitializedOrClosed, c.Close())
}

func TestClientCloseSuccess(t *testing.T) {
	c := NewClient(testOptions()).(*client)
	c.state = clientInitialized
	require.NoError(t, c.Close())
}

func TestClientWriteTimeRangeFor(t *testing.T) {
	c := NewClient(testOptions()).(*client)
	testShard := shard.NewShard(0).SetState(shard.Initializing)
	for _, input := range []struct {
		cutoverNanos     int64
		cutoffNanos      int64
		expectedEarliest int64
		expectedLatest   int64
	}{
		{
			cutoverNanos:     0,
			cutoffNanos:      int64(math.MaxInt64),
			expectedEarliest: 0,
			expectedLatest:   int64(math.MaxInt64),
		},
		{
			cutoverNanos:     testNowNanos,
			cutoffNanos:      int64(math.MaxInt64),
			expectedEarliest: testNowNanos - int64(time.Minute),
			expectedLatest:   int64(math.MaxInt64),
		},
		{
			cutoverNanos:     0,
			cutoffNanos:      testNowNanos,
			expectedEarliest: 0,
			expectedLatest:   testNowNanos + int64(10*time.Minute),
		},
	} {
		testShard = testShard.SetCutoverNanos(input.cutoverNanos).SetCutoffNanos(input.cutoffNanos)
		earliest, latest := c.writeTimeRangeFor(testShard)
		require.Equal(t, input.expectedEarliest, earliest)
		require.Equal(t, input.expectedLatest, latest)
	}
}

func testOptions() Options {
	return NewOptions().
		SetClockOptions(clock.NewOptions()).
		SetConnectionOptions(testConnectionOptions()).
		SetInstrumentOptions(instrument.NewOptions()).
		SetShardFn(func([]byte, int) uint32 { return 1 }).
		SetInstanceQueueSize(10).
		SetMaxTimerBatchSize(140).
		SetShardCutoverWarmupDuration(time.Minute).
		SetShardCutoffLingerDuration(10 * time.Minute)
}


text:
package com.air.twitterclient.activity;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

import com.air.twitterclient.R;
import com.air.twitterclient.rest.TwitterClient;
import com.codepath.oauth.OAuthLoginActionBarActivity;

public class LoginActivity extends OAuthLoginActionBarActivity<TwitterClient> {
    private TextView mTitle;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
        Typeface fontJamesFajardo = Typeface.createFromAsset(this.getAssets(), "fonts/JamesFajardo.ttf");

        Toolbar toolbar = (Toolbar) findViewById(R.id.tolBrLogin);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        mTitle = (TextView) toolbar.findViewById(R.id.toolbar_login_title);

        toolbar.setLogo(R.drawable.ic_tweets);
        mTitle.setTypeface(fontJamesFajardo);
	}

	// Inflate the menu; this adds items to the action bar if it is present.
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.login, menu);
		return true;
	}

	// OAuth authenticated successfully, launch primary authenticated activity
	// i.e Display application "homepage"
	@Override
	public void onLoginSuccess() {
        //Toast.makeText(this, "screen", Toast.LENGTH_SHORT).show();
		Intent i = new Intent(this, TimeLineActivity.class);
		startActivity(i);
	}

	// OAuth authentication flow failed, handle the error
	// i.e Display an error dialog or toast
	@Override
	public void onLoginFailure(Exception e) {
		e.printStackTrace();
	}

	// Click handler method for the button used to start OAuth flow
	// Uses the client to initiate OAuth authorization
	// This should be tied to a button used to login
	public void loginToRest(View view) {
		getClient().connect();
	}

}


text:
<?php

namespace Home\Controllers;

class NewsController extends ControllerBase
{
	public function index($name = "")
	{
		echo "Home\Controllers\NewsController->indexAction " . $name;
	}

	public function test()
	{
		echo "NewsController->testAction";
	}

	public function read()
	{
		echo "NewsController->readAction";
	}

	public function readOne($id = "")
	{
		echo "NewsController->readOneAction " . $id;
	}

	public function create()
	{
		echo "NewsController->createAction";
	}

	public function update($id = "")
	{
		echo "NewsController->updateAction " . $id;
	}

	public function delete($id = "")
	{
		echo "NewsController->deleteAction " . $id;
	}
}


text:
using System.Collections.Generic;
using System.Runtime.Serialization;
using DvachBrowser3.Links;

namespace DvachBrowser3.Posts
{
    /// <summary>
    /// Коллекция постов.
    /// </summary>
    [DataContract(Namespace = CoreConstants.DvachBrowserNamespace)]
    public class PostTreeContainer
    {
        /// <summary>
        /// Ссылка.
        /// </summary>
        [DataMember]
        public BoardLinkBase Link { get; set; }

        /// <summary>
        /// Посты.
        /// </summary>
        [DataMember]
        public List<PostTree> Posts { get; set; }
    }
}


text:
from .my_test_case import MyTestCase
from flask import request
from flask_restful import Api, Resource
import flask_restful_extend as restful_extend
from datetime import datetime
import time
from decimal import Decimal

class JSONEncoderTestCase(MyTestCase):
    def setUp(self):
        self.setup_app()

        testcase = self
        testcase.json_data = None

        class Routes(Resource):
            def get(self):
                return testcase.json_data

        self.api = Api(self.app)
        self.api.add_resource(Routes, '/')

        restful_extend.enhance_json_encode(self.api)

    def verify(self, data, expect_text_result):
        self.json_data = data
        rv = self.client.get('/')
        self.assertEqual(rv.content_type, 'application/json')
        self.assertEqual(expect_text_result, rv.data.decode("utf-8"))

    def test_basic(self):
        def gen():
            l = [1, 2, 3]
            for i in l:
                yield i

        now = datetime.now()

        samples = [
            (105.132, '105.132'),
            ('abc', '"abc"'),
            (u'你好', u'"你好"'),
            (True, 'true'),
            (None, 'null'),

            ([1, 'a', 10.5], '[1, "a", 10.5]'),

            (now, str(time.mktime(now.timetuple()))),
            (Decimal(10.5), '10.5'),
            (gen(), '[1, 2, 3]'),
        ]

        for data, result in samples:
            self.verify(data, result)

    def test_custom_encoder(self):
        class CustomDataType(object):
            def __init__(self, a, b):
                self.a = a
                self.b = b

        self.api.json_encoder.register(lambda obj: obj.a + obj.b, CustomDataType)
        self.verify(CustomDataType(Decimal(10.5), 1), '11.5')

class JSONPTestCase(MyTestCase):

    callback_arg_name = 'jsonp_callback'
    js_callback = 'doIt'
    return_data = 'custom_result'

    def setUp(self):
        self.setup_app()

        testcase = self

        class Routes(Resource):
            def get(self):
                return testcase.return_data

        self.api = Api(self.app)
        self.api.add_resource(Routes, '/')

    def verify(self):
        rv = self.client.get('/?{}={}'.format(self.callback_arg_name, self.js_callback))
        self.assertEqual(rv.content_type, 'application/json')
        self.assertEqual(rv.data.decode("utf-8"), '{}("{}")'.format(self.js_callback, self.return_data))

        rv = self.client.get('/')
        self.assertEqual(rv.content_type, 'application/json')
        self.assertEqual(rv.data.decode("utf-8"), '"{}"'.format(self.return_data))

    def test_str_source(self):
        restful_extend.support_jsonp(self.api, self.callback_arg_name)
        self.verify()

    def test_fn_source(self):
        restful_extend.support_jsonp(self.api, lambda: request.args.get(self.callback_arg_name, False))
        self.verify()