text:
import DataBundleCache from "react-server-data-bundle-cache";

// Only need to do this once.  We're not passing any configuration, so we'll
// get the default, which is unlimited bundles for unlimited time.  The cache
// is blown away by refresh, or non-client-transition navigation.
DataBundleCache.install();

// We'll preload some bundles.  Don't want to preload anything more than once,
// so we'll keep track of paths we've already hit.  The data bundle cache
// actually already does this, but we can make the noops even cheaper by
// checking externally.
const preloaded = {};

export default class DataBundleCacheManager {
	handleRoute(next) {

		// Each page may have its data bundle cached.
		DataBundleCache.optIn();

		// Always make sure the section entrypoints are preloaded.
		DataBundleCacheManager.preload(['/docs', '/source']);

		return next();
	}

	static preload(urls) {

		// Preload the urls one at a time by making a big promise chain out of
		// the array of URLs that's passed in.
		urls.reduce((chain, url) => chain.then(() => {
			if (preloaded[url]) return;
			preloaded[url] = true;
			return DataBundleCache.preload(url); // eslint-disable-line consistent-return
		}), Promise.resolve());
	}

	static addContents(prefix, res) {

		// Preload all of the data bundles for the pages in a site section.
		DataBundleCacheManager
			.preload(res.contents.reduce((pages, section) => pages.concat(
				section.pages.map(page => prefix + page.path)
			), []));

		// Pass the response along.
		return res;
	}
}


text:
package jsettlers.common.action;

import jsettlers.common.material.EPriority;

/**
 * This {@link Action} is used to set the priority of a building. When it is fired, the priority is set for the current selection.
 *
 * @author Andreas Eberle
 */
public class SetBuildingPriorityAction extends Action {

	private final EPriority newPriority;

	/**
	 * Creates a new {@link SetBuildingPriorityAction}.
	 *
	 * @param newPriority
	 *            The new priority.
	 */
	public SetBuildingPriorityAction(EPriority newPriority) {
		super(EActionType.SET_BUILDING_PRIORITY);
		this.newPriority = newPriority;
	}

	/**
	 * @return Returns the new priority that shall be set to the selected building.
	 */
	public EPriority getNewPriority() {
		return newPriority;
	}

}

redpajama_set_name: RedPajamaGithub


text:
const gulp = require('gulp');
const browserSync = require('browser-sync');
const sass = require('gulp-sass');

function swallowError (error) {
    console.log(error.toString());
    this.emit('end');
}

gulp.task('serve', ['sass'], function() {

    browserSync.init({
        server: './'
    });

    gulp.watch('./style/*.scss', ['sass']).on('change', browserSync.reload);
    gulp.watch("./*.html").on('change', browserSync.reload);
})

gulp.task('sass', function() {
    return gulp.src('./style/*.scss')
        .pipe(sass({outputStyle: 'compressed'}))
        .on('error', swallowError)
        .pipe(gulp.dest('./style'))
})

gulp.task('default', ['serve'])


text:
import React, { PureComponent } from 'react';
import { lightWhite, grey900, darkWhite } from 'material-ui/styles/colors';
import typography from 'material-ui/styles/typography';

const FOOTER_ITEM_STYLE = {
  padding: 50,
};

class Footer extends PureComponent<void, {}, void> {
  render() {
    return (

            {`Copyright © Byggreal AS ${new Date().getFullYear()}`}

            {' '}

              {'ove@byggreal.no'}

    );
  }
}

export default Footer;


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

namespace Orleans.Runtime.ConsistentRing
{
    internal class EquallyDevidedRangeRingProvider : IConsistentRingProviderForGrains, IRingRangeListener
    {
        private readonly IConsistentRingProvider ringProvider;
        private readonly List<IAsyncRingRangeListener> grainStatusListeners;
        private readonly TraceLogger logger;
        private readonly int numSubRanges;
        private readonly int mySubRangeIndex;
        private IRingRange myRange;

        internal EquallyDevidedRangeRingProvider(IConsistentRingProvider provider, int mySubRangeIndex, int numSubRanges)
        {
            if (mySubRangeIndex < 0 || mySubRangeIndex >= numSubRanges)
                throw new IndexOutOfRangeException("mySubRangeIndex is out of the range. mySubRangeIndex = " + mySubRangeIndex + " numSubRanges = " + numSubRanges);

            ringProvider = provider;
            this.numSubRanges = numSubRanges;
            this.mySubRangeIndex = mySubRangeIndex;
            grainStatusListeners = new List<IAsyncRingRangeListener>();
            ringProvider.SubscribeToRangeChangeEvents(this);
            logger = TraceLogger.GetLogger(typeof(EquallyDevidedRangeRingProvider).Name);
        }

        public IRingRange GetMyRange()
        {
            return myRange ?? (myRange = CalcMyRange());
        }

        private IRingRange CalcMyRange()
        {
            var equallyDevidedMultiRange = new EquallyDevidedMultiRange(ringProvider.GetMyRange(), numSubRanges);
            return equallyDevidedMultiRange.GetSubRange(mySubRangeIndex);
        }

        public bool SubscribeToRangeChangeEvents(IAsyncRingRangeListener observer)
        {
            lock (grainStatusListeners)
            {
                if (grainStatusListeners.Contains(observer)) return false;

                grainStatusListeners.Add(observer);
                return true;
            }
        }

        public bool UnSubscribeFromRangeChangeEvents(IAsyncRingRangeListener observer)
        {
            lock (grainStatusListeners)
            {
                return grainStatusListeners.Contains(observer) && grainStatusListeners.Remove(observer);
            }
        }

        public void RangeChangeNotification(IRingRange old, IRingRange now, bool increased)
        {
            myRange = CalcMyRange();

            var oldMultiRange = new EquallyDevidedMultiRange(old, numSubRanges);
            IRingRange oldSubRange = oldMultiRange.GetSubRange(mySubRangeIndex);
            var newMultiRange = new EquallyDevidedMultiRange(now, numSubRanges);
            IRingRange newSubRange = newMultiRange.GetSubRange(mySubRangeIndex);

            if (oldSubRange.Equals(newSubRange)) return;

            // For now, always say your range increased and the listeners need to deal with the situation when they get the same range again anyway.
            // In the future, check sub range inclusion. Note that it is NOT correct to just return the passed increased argument.
            // It will be wrong: the multi range may have decreased, while some individual sub range may partialy increase (shift).

            logger.Info("-NotifyLocal GrainRangeSubscribers about old {0} and new {1} increased? {2}.", oldSubRange.ToString(), newSubRange.ToString(), increased);

            List<IAsyncRingRangeListener> copy;
            lock (grainStatusListeners)
            {
                copy = grainStatusListeners.ToList();
            }
            foreach (IAsyncRingRangeListener listener in copy)
            {
                try
                {
                    Task task = listener.RangeChangeNotification(oldSubRange, newSubRange);
                    // We don't want to await it here since it will delay delivering notifications to other listeners.
                    // We only want to log an error if it happends, so use ContinueWith.
                    task.LogException(logger, ErrorCode.CRP_ForGrains_Local_Subscriber_Exception_1,
                                        String.Format("Local IGrainRingRangeListener {0} has thrown an asynchronous exception when was notified about RangeChangeNotification about old {1} new {2}.",
                                        listener.GetType().FullName, oldSubRange, newSubRange))
                        .Ignore();
                }
                catch (Exception exc)
                {
                    logger.Error(ErrorCode.CRP_ForGrains_Local_Subscriber_Exception_2,
                        String.Format("Local IGrainRingRangeListener {0} has thrown an exception when was notified about RangeChangeNotification about old {1} new {2}.",
                        listener.GetType().FullName, oldSubRange, newSubRange), exc);
                }
            }
        }
    }
}


text:
using Content.Server.Botany.Systems;
using Robust.Shared.Prototypes;
using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype;

namespace Content.Server.Botany.Components;
// TODO: This should probably be merged with SliceableFood somehow or made into a more generic Choppable.
// Yeah this is pretty trash. also consolidating this type of behavior will avoid future transform parenting bugs (see #6090).

[RegisterComponent]
[Access(typeof(LogSystem))]
public sealed class LogComponent : Component
{
    [DataField("spawnedPrototype", customTypeSerializer: typeof(PrototypeIdSerializer<EntityPrototype>))]
    public string SpawnedPrototype = "MaterialWoodPlank1";

    [DataField("spawnCount")] public int SpawnCount = 2;
}


text:
Number of registered patients:

2,985


text:
@interface ZCSettingViewController ()

@end

@implementation ZCSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//#pragma mark - UITableViewDataSource方法实现
//#pragma mark 设置UITableView组(缺省为1)
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
//    return 1;
//}
//#pragma mark 设置UITableView第section组行数
//- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//    return 1;
//}
//#pragma mark 设置UITableViewCell
//- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//    static NSString *ID = @"cell";
//    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
//    if (cell == nil) {
//        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ID];
//    }
//    //设置cell数据
//
//    cell.textLabel.text = @"通信地址";
//
//    return cell;
//}
//#pragma mark - UITableViewDelegate方法实现

@end


text:
#ifndef RECTANGULAR_APERTURE_SHAPE_H
#define RECTANGULAR_APERTURE_SHAPE_H

//pyORBIT utils
#include "CppPyWrapper.hh"

#include "Bunch.hh"
#include "BaseApertureShape.hh"

using namespace std;

///////////////////////////////////////////////////////////////////////////
//
// NAME
//
//   RectangularApertureShape
//
// AUTHOR:
//   Andrei Shishlo October 2022
//
///////////////////////////////////////////////////////////////////////////

/**
	RectangularApertureShape is an implementation of BaseApertureShape class.
*/

class RectangularApertureShape: public BaseApertureShape
{
public:

	/** RectangularApertureShape constructor */
	RectangularApertureShape();

	/** RectangularApertureShape decstructor */
	virtual ~RectangularApertureShape();

	/** Return 1 if the particular macro-particle is inside this shape */
	int inside(Bunch* bunch, int count);

	/** Sets the half size in X-direction in [m] */
	void setHalfX(double x_half_size);

	/** Returns the half size in X-direction in [m]  */
	double getHalfX();

	/** Sets the half size in Y-direction in [m] */
	void setHalfY(double y_half_size);

	/** Returns the half size in Y-direction in [m]  */
	double getHalfY();

protected:

	double x_half_size;
	double y_half_size;

};

//end of RECTANGULAR_APERTURE_SHAPE_H ifdef
#endif


text:
package ThirdDotNamedBindings;

public interface MakePayment {
}


text:
/**
 * @license Angular v4.3.6
 * (c) 2010-2017 Google, Inc. https://angular.io/
 * License: MIT
 */
(function (global, factory) {
	typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/compiler/testing'), require('@angular/core'), require('@angular/platform-browser-dynamic/testing'), require('@angular/platform-browser/animations'), require('@angular/platform-server')) :
	typeof define === 'function' && define.amd ? define(['exports', '@angular/compiler/testing', '@angular/core', '@angular/platform-browser-dynamic/testing', '@angular/platform-browser/animations', '@angular/platform-server'], factory) :
	(factory((global.ng = global.ng || {}, global.ng.platformServer = global.ng.platformServer || {}, global.ng.platformServer.testing = global.ng.platformServer.testing || {}),global.ng.compiler.testing,global.ng.core,global.ng.platformBrowserDynamic.testing,global._angular_platformBrowser_animations,global.ng.platformServer));
}(this, (function (exports,_angular_compiler_testing,_angular_core,_angular_platformBrowserDynamic_testing,_angular_platformBrowser_animations,_angular_platformServer) { 'use strict';

/**
 * @license Angular v4.3.6
 * (c) 2010-2017 Google, Inc. https://angular.io/
 * License: MIT
 */
/**
 * @license
 * Copyright Google Inc. All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://angular.io/license
 */
/**
 * Platform for testing
 *
 * @experimental API related to bootstrapping are still under review.
 */
var platformServerTesting = _angular_core.createPlatformFactory(_angular_compiler_testing.platformCoreDynamicTesting, 'serverTesting', _angular_platformServer.ɵINTERNAL_SERVER_PLATFORM_PROVIDERS);
/**
 * NgModule for testing.
 *
 * @experimental API related to bootstrapping are still under review.
 */
var ServerTestingModule = (function () {
    function ServerTestingModule() {
    }
    return ServerTestingModule;
}());
ServerTestingModule.decorators = [
    { type: _angular_core.NgModule, args: [{
                exports: [_angular_platformBrowserDynamic_testing.BrowserDynamicTestingModule],
                imports: [_angular_platformBrowser_animations.NoopAnimationsModule],
                providers: _angular_platformServer.ɵSERVER_RENDER_PROVIDERS
            },] },
];
/** @nocollapse */
ServerTestingModule.ctorParameters = function () { return []; };

exports.platformServerTesting = platformServerTesting;
exports.ServerTestingModule = ServerTestingModule;

Object.defineProperty(exports, '__esModule', { value: true });

})));
//# sourceMappingURL=platform-server-testing.umd.js.map


text:
package bristol.zepp.com.bridge;

/**
 * Created by xubinggui on 2/16/16.
 */
public abstract class MagicWeaponImpl {

    public abstract void wieldImp();

    public abstract void swingImp();

    public abstract void unwieldImp();

}


text:
package org.elasticsearch.xpack.watcher.transport.action;

import org.elasticsearch.client.Client;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.ContextParser;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.test.AbstractSerializingTestCase;
import org.elasticsearch.xpack.core.watcher.support.xcontent.WatcherParams;
import org.elasticsearch.xpack.core.watcher.support.xcontent.WatcherXContentParser;
import org.elasticsearch.xpack.core.watcher.support.xcontent.XContentSource;
import org.elasticsearch.xpack.core.watcher.transport.actions.QueryWatchesAction;
import org.elasticsearch.xpack.core.watcher.watch.Watch;
import org.elasticsearch.xpack.core.watcher.watch.WatchStatus;
import org.elasticsearch.xpack.watcher.actions.email.EmailActionTests;
import org.elasticsearch.xpack.watcher.common.http.HttpClient;
import org.elasticsearch.xpack.watcher.support.search.WatcherSearchTemplateService;
import org.elasticsearch.xpack.watcher.test.WatcherTestUtils;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.List;

import static org.elasticsearch.common.xcontent.ConstructingObjectParser.constructorArg;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.Mockito.mock;

public class QueryWatchesResponseTests extends AbstractSerializingTestCase<QueryWatchesAction.Response> {

    private static final ConstructingObjectParser<QueryWatchesAction.Response.Item, Void> TEST_ITEM_PARSER = new ConstructingObjectParser<>(
        "query_watches_response_item",
        false,
        (args, c) -> new QueryWatchesAction.Response.Item((String) args[0], (XContentSource) args[1],
            (WatchStatus) args[2], (long) args[3], (long) args[4])
    );

    static {
        TEST_ITEM_PARSER.declareString(constructorArg(), new ParseField("_id"));
        TEST_ITEM_PARSER.declareObject(
            constructorArg(),
            (p, c) -> new XContentSource(XContentBuilder.builder(p.contentType().xContent()).copyCurrentStructure(p)),
            new ParseField("watch")
        );
        TEST_ITEM_PARSER.declareObject(
            constructorArg(),
            (p, c) -> WatchStatus.parse("_not_used", new WatcherXContentParser(p, ZonedDateTime.now(ZoneOffset.UTC), null, false)),
            new ParseField("status")
        );
        TEST_ITEM_PARSER.declareLong(constructorArg(), new ParseField("_seq_no"));
        TEST_ITEM_PARSER.declareLong(constructorArg(), new ParseField("_primary_term"));
    }

    @SuppressWarnings("unchecked")
    private static final ConstructingObjectParser<QueryWatchesAction.Response, Void> TEST_PARSER = new ConstructingObjectParser<>(
        "query_watches_response",
        false,
        (args, c) -> new QueryWatchesAction.Response((long) args[0], (List<QueryWatchesAction.Response.Item>) args[1])
    );

    static {
        TEST_PARSER.declareLong(constructorArg(), new ParseField("count"));
        TEST_PARSER.declareObjectArray(constructorArg(), (ContextParser<Void, Object>) TEST_ITEM_PARSER::parse, new ParseField("watches"));
    }

    @Override
    protected QueryWatchesAction.Response doParseInstance(XContentParser parser) throws IOException {
        return TEST_PARSER.parse(parser, null);
    }

    @Override
    protected Writeable.Reader<QueryWatchesAction.Response> instanceReader() {
        return QueryWatchesAction.Response::new;
    }

    @Override
    protected QueryWatchesAction.Response createTestInstance() {
        int numWatches = randomIntBetween(0, 10);
        List<QueryWatchesAction.Response.Item> items = new ArrayList<>(numWatches);
        for (int i = 0; i < numWatches; i++) {
            Watch watch = createWatch("_id + " + i);
            try (XContentBuilder builder = jsonBuilder()) {
                watch.toXContent(builder, WatcherParams.builder()
                    .hideSecrets(true)
                    .includeStatus(false)
                    .build());
                items.add(new QueryWatchesAction.Response.Item(randomAlphaOfLength(4),
                    new XContentSource(builder), watch.status(), 1, 0));
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }
        return new QueryWatchesAction.Response(numWatches + randomIntBetween(0, 100), items);
    }

    private Watch createWatch(String watchId)  {
        return WatcherTestUtils.createTestWatch(watchId,
            mock(Client.class),
            mock(HttpClient.class),
            new EmailActionTests.NoopEmailService(),
            mock(WatcherSearchTemplateService.class),
            logger);
    }

    @Override
    protected void assertEqualInstances(QueryWatchesAction.Response expectedInstance, QueryWatchesAction.Response newInstance) {
        assertThat(expectedInstance.getWatchTotalCount(), equalTo(newInstance.getWatchTotalCount()));
        assertThat(expectedInstance.getWatches().size(), equalTo(newInstance.getWatches().size()));
        for (int i = 0; i < expectedInstance.getWatches().size(); i++) {
            QueryWatchesAction.Response.Item expected = expectedInstance.getWatches().get(i);
            QueryWatchesAction.Response.Item actual = newInstance.getWatches().get(i);
            assertThat(expected.getId(), equalTo(actual.getId()));
            assertThat(expected.getSource(), equalTo(actual.getSource()));
            assertThat(expected.getSeqNo(), equalTo(actual.getSeqNo()));
            assertThat(expected.getPrimaryTerm(), equalTo(actual.getPrimaryTerm()));
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
  PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="copyright" content="(C) Copyright 2005"/>
<meta name="DC.rights.owner" content="(C) Copyright 2005"/>
<meta name="DC.Type" content="reference"/>
<meta name="DC.Title" content="C++ Native Functions: com.ibm.streamsx.network.geohash"/>
<meta name="DC.Format" content="XHTML"/>
<meta name="DC.Identifier" content="spldoc_functions"/>
<link rel="stylesheet" type="text/css" href="../../html/commonltr.css"/>
<link rel="stylesheet" type="text/css" href="../../html/spldoc.css"/>
<title>C++ Native Functions: com.ibm.streamsx.network.geohash</title>

C++ Native Functions: <tt class="ph tt">com.ibm.streamsx.network.geohash</tt>

IBMStreams com.ibm.streamsx.network Toolkit > com.ibm.streamsx.network 3.4.3 > com.ibm.streamsx.network.geohash > C++ Native Functions

This page documents native functions that can be invoked from SPL, including the SPL interfaces that can be used to invoke each of the native functions.

Functions

<tt class="ph tt">      public list<float64> geohashDecode(rstring geohash)      </tt>

The geohashDecode() function decodes a geohash as the latitude and longitude of its center point and bounding box. The 'geohash' argument is a string value of 1 to 12 characters composed of the characters '0123456789bcdefghjkmnpqrstuvwxyz'.

The function returns a list of six float64 values if the 'geohash' value is valid:

 0: the latitude of the center point

 1: the longitude of the center point

 2: the latitude of the top edge (that is, the northern edge) of the bounding box

 3: the longitude of the right edge (that is, the eastern edge) of the bounding box

 4: the latitude of the bottom edge (that is, the southern edge) of the bounding box

 5: the longitude of the left edge (that is, the western edge) of the bounding box

The function returns an empty list if the 'geohash' value is not valid.

<tt class="ph tt">      public rstring geohashEncode(float64 latitude, float64 longitude, int32 precision)      </tt>

The geohashEncode() function encodes a latitude/longitude pair as a geohash of a specified precision. The argument values are limited to these ranges:

 'latitude' is a float64 value limited to the range -90 to +90, representing degrees of latitude

 'longitude' is a float64 value limited to the range -180 to +180, representing degrees of longitude

 'precision' is an int32 value limited to the range 1 to 12, specifying the length of the 'geohash'

The function returns a string of length 'precision' containing the encoded 'geohash' if all of the parameters are within range. The 'geohash' string is composed of the characters '0123456789bcdefghjkmnpqrstuvwxyz'.

The function returns an empty string if any of the parameters are out of range.


text:
package org.apache.accumulo.server.util.time;

/**
 * Provide time from System time and hints from another time source.
 *
 * Provides a convenient static replacement for System.currentTimeMillis()
 */
public class RelativeTime extends BaseRelativeTime {

  private RelativeTime() {
    super(new SystemTime());
  }

  private static BaseRelativeTime instance = new RelativeTime();

  public static BaseRelativeTime getInstance() {
    return instance;
  }

  public static void setInstance(BaseRelativeTime newInstance) {
    instance = newInstance;
  }

  public static long currentTimeMillis() {
    return getInstance().currentTime();
  }

}


text:
namespace net {

class BalsaFrame;
class FlipAcceptor;
class MemoryCache;

class SpdySM : public spdy::SpdyFramerVisitorInterface,
               public SMInterface {
 public:
  SpdySM(SMConnection* connection,
         SMInterface* sm_http_interface,
         EpollServer* epoll_server,
         MemoryCache* memory_cache,
         FlipAcceptor* acceptor);
  virtual ~SpdySM();

  virtual void InitSMInterface(SMInterface* sm_http_interface,
                               int32 server_idx) {}

  virtual void InitSMConnection(SMConnectionPoolInterface* connection_pool,
                                SMInterface* sm_interface,
                                EpollServer* epoll_server,
                                int fd,
                                std::string server_ip,
                                std::string server_port,
                                std::string remote_ip,
                                bool use_ssl);

  static bool disable_data_compression() { return disable_data_compression_; }
  static void set_disable_data_compression(bool value) {
    disable_data_compression_ = value;
  }

 private:
  virtual void set_is_request() {}
  virtual void OnError(spdy::SpdyFramer* framer) {}
  SMInterface* NewConnectionInterface();
  SMInterface* FindOrMakeNewSMConnectionInterface(std::string server_ip,
                                                  std::string server_port);
  int SpdyHandleNewStream(const spdy::SpdyControlFrame* frame,
                          std::string &http_data,
                          bool *is_https_scheme);

  // SpdyFramerVisitor interface.
  virtual void OnControl(const spdy::SpdyControlFrame* frame);
  virtual void OnStreamFrameData(spdy::SpdyStreamId stream_id,
                                 const char* data, size_t len);

 public:
  virtual size_t ProcessReadInput(const char* data, size_t len);
  virtual size_t ProcessWriteInput(const char* data, size_t len);
  virtual bool MessageFullyRead() const;
  virtual void SetStreamID(uint32 stream_id) {}
  virtual bool Error() const;
  virtual const char* ErrorAsString() const;
  virtual void Reset() {}
  virtual void ResetForNewInterface(int32 server_idx);
  virtual void ResetForNewConnection();
  // SMInterface's Cleanup is currently only called by SMConnection after a
  // protocol message as been fully read. Spdy's SMInterface does not need
  // to do any cleanup at this time.
  // TODO (klindsay) This method is probably not being used properly and
  // some logic review and method renaming is probably in order.
  virtual void Cleanup() {}
  // Send a settings frame
  virtual int PostAcceptHook();
  virtual void NewStream(uint32 stream_id,
                         uint32 priority,
                         const std::string& filename);
  void AddToOutputOrder(const MemCacheIter& mci);
  virtual void SendEOF(uint32 stream_id);
  virtual void SendErrorNotFound(uint32 stream_id);
  void SendOKResponse(uint32 stream_id, std::string* output);
  virtual size_t SendSynStream(uint32 stream_id, const BalsaHeaders& headers);
  virtual size_t SendSynReply(uint32 stream_id, const BalsaHeaders& headers);
  virtual void SendDataFrame(uint32 stream_id, const char* data, int64 len,
                             uint32 flags, bool compress);
  spdy::SpdyFramer* spdy_framer() { return spdy_framer_; }

  static std::string forward_ip_header() { return forward_ip_header_; }
  static void set_forward_ip_header(std::string value) {
    forward_ip_header_ = value;
  }

 private:
  void SendEOFImpl(uint32 stream_id);
  void SendErrorNotFoundImpl(uint32 stream_id);
  void SendOKResponseImpl(uint32 stream_id, std::string* output);
  void KillStream(uint32 stream_id);
  void CopyHeaders(spdy::SpdyHeaderBlock& dest, const BalsaHeaders& headers);
  size_t SendSynStreamImpl(uint32 stream_id, const BalsaHeaders& headers);
  size_t SendSynReplyImpl(uint32 stream_id, const BalsaHeaders& headers);
  void SendDataFrameImpl(uint32 stream_id, const char* data, int64 len,
                         spdy::SpdyDataFlags flags, bool compress);
  void EnqueueDataFrame(DataFrame* df);
  virtual void GetOutput();
 private:
  uint64 seq_num_;
  spdy::SpdyFramer* spdy_framer_;
  bool valid_spdy_session_;  // True if we have seen valid data on this session.
                             // Use this to fail fast when junk is sent to our
                             // port.

  SMConnection* connection_;
  OutputList* client_output_list_;
  OutputOrdering client_output_ordering_;
  uint32 next_outgoing_stream_id_;
  EpollServer* epoll_server_;
  FlipAcceptor* acceptor_;
  MemoryCache* memory_cache_;
  std::vector<SMInterface*> server_interface_list;
  std::vector<int32> unused_server_interface_list;
  typedef std::map<uint32, SMInterface*> StreamToSmif;
  StreamToSmif stream_to_smif_;
  bool close_on_error_;

  static bool disable_data_compression_;
  static std::string forward_ip_header_;
};

}  // namespace net

#endif  // NET_TOOLS_FLIP_SERVER_SPDY_INTERFACE_


text:
package org.apache.commons.collections;

/**
 * The BufferOverflowException is used when the buffer's capacity has been
 * exceeded.
 *
 * @since Commons Collections 2.1
 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $
 *
 * @author Avalon
 * @author Berin Loritsch
 * @author Jeff Turner
 * @author Paul Jack
 * @author Stephen Colebourne
 */
public class BufferOverflowException extends RuntimeException {

    /** The root cause throwable */
    private final Throwable throwable;

    /**
     * Constructs a new BufferOverflowException.
     */
    public BufferOverflowException() {
        super();
        throwable = null;
    }

    /**
     * Construct a new BufferOverflowException.
     *
     * @param message  the detail message for this exception
     */
    public BufferOverflowException(String message) {
        this(message, null);
    }

    /**
     * Construct a new BufferOverflowException.
     *
     * @param message  the detail message for this exception
     * @param exception  the root cause of the exception
     */
    public BufferOverflowException(String message, Throwable exception) {
        super(message);
        throwable = exception;
    }

    /**
     * Gets the root cause of the exception.
     *
     * @return the root cause
     */
    public final Throwable getCause() {
        return throwable;
    }

}


text:
build:
	node_modules/.bin/coffee -co dist/ src/

uglify:
	node_modules/.bin/uglifyjs dist/ionic.resetfield.js > dist/ionic.resetfield.min.js

clean:
	rm -rf dist

.PHONY: all clean

all: clean build uglify


text:
import requests
import sys
import traceback
import json
import re
import time
from datetime import datetime
import calendar
from optparse import make_option

import pyprind

from django.conf import settings
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand, CommandError
from django.core.urlresolvers import reverse

from moocng.users.models import User
from moocng.courses.models import Course, CourseStudent, KnowledgeQuantum
from moocng.peerreview.models import PeerReviewAssignment
from moocng.peerreview.utils import get_peer_review_review_score
from moocng.x_api.utils import learnerAccessAPage, learnerEnrollsInMooc, learnerSubmitsAResource
from moocng import mongodb

class Command(BaseCommand):
	option_list = BaseCommand.option_list + (
		make_option('-b', '--datebefore',
					action='store',
					dest='datebefore',
					default='',
					help='Max date to export. Format "DD/MM/YYYY hh:mm"'),
		make_option('-a', '--dateafter',
					action='store',
					dest='dateafter',
					default='',
					help='Min date to export. Format "DD/MM/YYYY hh:mm"'),
		make_option('-e', '--enrollments',
					action='store_true',
					dest='enrollments',
					default='',
					help='Export only enrollments'),

		make_option('-c', '--accesses',
					action='store_true',
					dest='accesses',
					default='',
					help='Export only accesses'),
		make_option('-f', '--forum',
					action='store_true',
					dest='forum',
					default='',
					help='Export forum entries'),
		make_option('-t', '--tasks',
					action='store_true',
					dest='tasks',
					default='',
					help='Export tasks submission entries'),
		make_option('-p', '--peerassessments',
					action='store_true',
					dest='peerassessments',
					default='',
					help='Export peer assesments submission entries'),
		make_option('-r', '--peerreviews',
					action='store_true',
					dest='peerreviews',
					default='',
					help='Export peer reviews submission entries'),
		make_option('-i', '--badges',
					action='store_true',
					dest='badges',
					default='',
					help='Export badges (insignia) attribution entries'),
		make_option('--debug',
					action='store_true',
					dest='debug',
					default='',
					help='Show debug messages')
	)

	def error(self, message):
		self.stderr.write("%s\n" % message.encode("ascii", "replace"))

	def message(self, message):
		self.stdout.write("%s\n" % message.encode("ascii", "replace"))

	def handle(self, *args, **options):
		if options['datebefore']:
			max_timestamp = calendar.timegm(time.strptime(options['datebefore'], '%d/%m/%Y %H:%M'))
		else:
			max_timestamp = calendar.timegm(time.gmtime())

		if options['dateafter']:
			min_timestamp = calendar.timegm(time.strptime(options['dateafter'], '%d/%m/%Y %H:%M'))
		else:
			min_timestamp = 0

		if options['enrollments']:
			# Get enrollments
			enrollments = CourseStudent.objects.exclude(timestamp__lte=min_timestamp).filter(timestamp__lte=max_timestamp)
			self.message("%d enrollments between %d and %d" % (enrollments.count(), min_timestamp, max_timestamp))

			#Send each enrollment entry as xAPI statement
			bar = pyprind.ProgBar(enrollments.count())
			for enrollment in enrollments:
				try:
					geolocation = {
						'lat': enrollment.pos_lat,
						'lon': enrollment.pos_lon
					}
					timestamp = time.gmtime(enrollment.timestamp)
					learnerEnrollsInMooc(enrollment.student, enrollment.course, geolocation, timestamp)
				except:
					self.error('ERROR sending an statement for user %s in enrollment with timestamp %s' % (enrollment.student, time.strftime("%d/%m/%Y %H:%M:%S", timestamp)))
					if options['debug']:
						exc_type, exc_value, exc_traceback = sys.exc_info()
						self.error('Exception %s: %s' % (exc_type, exc_value))
						traceback.print_tb(exc_traceback, limit=5, file=sys.stdout)
					continue

				bar.update()

			self.message('\nEnrollments succesfully exported')

		if options['accesses']:
			# Get history
			history_col = mongodb.get_db().get_collection('history')
			histories = history_col.find({'$and': [
        									{'timestamp': {'$lte': max_timestamp * 1000} },
        									{'timestamp': {'$gte': min_timestamp * 1000} }
        								]})
			self.message("%d histories until %d" % (histories.count(), max_timestamp))

			# Send each history entry as xAPI Statement
			bar = pyprind.ProgBar(histories.count())
			for history in histories:
				course = None
				try:
					user_id = str(int(history['user_id']))
					user = User.objects.get(pk=user_id)
					if 'course_id' in history:
						course_id = str(int(history['course_id']))
						course = Course.objects.get(pk=course_id)

					page = {}
					page['url'] = history['url']
					if course:
						page['name'] = course.name
						page['description'] = course.name
					else:
						page['name'] = ''
						page['description'] = ''

					geolocation = {
						'lat': history['lat'],
						'lon': history['lon']
					}
					timestamp = time.gmtime(history['timestamp']/1000)
					learnerAccessAPage(user, page, course, geolocation, timestamp)
				except:
					self.error('ERROR sending a statement for user %s in history with timestamp %s' % (history['user_id'], time.strftime("%d/%m/%Y %H:%M:%S", timestamp)))
					if options['debug']:
						exc_type, exc_value, exc_traceback = sys.exc_info()
						self.error('Exception %s: %s' % (exc_type, exc_value))
						traceback.print_tb(exc_traceback, limit=5, file=sys.stdout)
					continue

				bar.update()

			self.message('\nHistory succesfully exported')

		if options['forum']:
			# Get forum entries
			if options['datebefore']:
				max_date = time.strftime('%Y-%m-%dT%H:%M',time.strptime(options['datebefore'], '%d/%m/%Y %H:%M'))
			else:
				max_date = time.strftime('%Y-%m-%dT%H:%M',time.gmtime())

			if options['dateafter']:
				min_date = time.strftime('%Y-%m-%dT%H:%M',time.strptime(options['dateafter'], '%d/%m/%Y %H:%M'))
			else:
				min_date = '1970-01-01T00:00'
			forum_col = mongodb.get_db().get_collection('forum_post')
			forum_posts = forum_col.find({'$and': [
        									{'date': {'$lte': max_date} },
        									{'date': {'$gte': min_date} }
        								]})
			self.message("%d forum posts between %s and %s" % (forum_posts.count(), min_date, max_date))

			# Send each post entry as xAPI Statement
			bar = pyprind.ProgBar(forum_posts.count())
			for post in forum_posts:
				course = None
				try:
					user_id = str(int(post['id_user']))
					user = User.objects.get(pk=user_id)
					if 'category_slug' in post:
						course_slug = str(post['category_slug'])
						course = Course.objects.get(slug=course_slug)

					page = {}
					post_url = "https://%s%s" % (settings.API_URI, reverse('course_forum_post', kwargs={'course_slug': course_slug, 'post_id': post['_id']})),
					page['url'] = post_url[0]

					if 'is_child' in post:
						is_child = bool(post['is_child'])
					else:
						is_child = False

					if is_child:
						page['type'] = 'threadreply'
						page['description'] = "This is a forum message"
					else:
						page['type'] = 'threadpost'
						page['description'] = "This is a thread-opening forum message"

					if 'title' in post:
						page['name'] = post['title']
					else:
						page['name'] = "Unnamed post"

					geolocation = {
						'lat': 0.0,
						'lon': 0.0
					}
					timestamp = time.strptime(post['date'], '%Y-%m-%dT%H:%M:%S.%f')
					learnerSubmitsAResource(user, page, course, geolocation, timestamp)
				except:
					self.error('\nERROR sending a statement for user %s in post with timestamp %s' % (post['id_user'], post['date']))
					if options['debug']:
						exc_type, exc_value, exc_traceback = sys.exc_info()
						self.error('Exception %s: %s' % (exc_type, exc_value))
						traceback.print_tb(exc_traceback, limit=5, file=sys.stdout)
					continue

				bar.update()

			self.message('\nForum succesfully exported')

		if options['tasks']:
			# Get tasks entries
			if options['datebefore']:
				max_date = datetime.fromtimestamp(time.mktime(time.strptime(options['datebefore'], '%d/%m/%Y %H:%M')))
			else:
				max_date = datetime.fromtimestamp(time.mktime(time.gmtime()))

			if options['dateafter']:
				min_date = datetime.fromtimestamp(time.mktime(time.strptime(options['dateafter'], '%d/%m/%Y %H:%M')))
			else:
				min_date = datetime.fromtimestamp(time.mktime(time.strptime('1970-01-01T00:00', '%d/%m/%Y %H:%M')))

			tasks_col = mongodb.get_db().get_collection('answers')
			tasks_entries = tasks_col.find({'$and': [
        									{'date': {'$lte': max_date} },
        									{'date': {'$gte': min_date} }
        								]})
			self.message("%d task submission entries between %s and %s" % (tasks_entries.count(), options['dateafter'], options['datebefore']))

			# Send each task entry as xAPI Statement
			bar = pyprind.ProgBar(tasks_entries.count())
			for task in tasks_entries:
				course = None
				try:
					user_id = str(int(task['user_id']))
					user = User.objects.get(pk=user_id)
					if 'course_id' in task:
						course_id = int(task['course_id'])
						course = Course.objects.get(pk=course_id)

					page = {}
					task_url = "https://%s%s#unit%s/kq%s/q" % (settings.API_URI, reverse('course_classroom', kwargs={'course_slug': course.slug}),task['unit_id'],task['kq_id']),
					page['url'] = task_url[0]

					page['type'] = 'task'

					kq = KnowledgeQuantum.objects.get(pk=task['kq_id'])
					page['name'] = kq.title
					page['description'] = 'Task for course %s' % (course.name)

					geolocation = {
						'lat': 0.0,
						'lon': 0.0
					}

					timestamp = task['date'].timetuple()
					learnerSubmitsAResource(user, page, course, geolocation, timestamp)
				except:
					self.error('\nERROR sending a statement for user %s in task with timestamp %s' % (task['user_id'], task['date']))
					if options['debug']:
						exc_type, exc_value, exc_traceback = sys.exc_info()
						self.error('Exception %s: %s' % (exc_type, exc_value))
						traceback.print_tb(exc_traceback, limit=5, file=sys.stdout)
					continue

				bar.update()

			self.message('\nTask submission entries succesfully exported')

		if options['peerassessments']:
			# Get peerassessments entries
			if options['datebefore']:
				max_date = datetime.fromtimestamp(time.mktime(time.strptime(options['datebefore'], '%d/%m/%Y %H:%M')))
			else:
				max_date = datetime.fromtimestamp(time.mktime(time.gmtime()))

			if options['dateafter']:
				min_date = datetime.fromtimestamp(time.mktime(time.strptime(options['dateafter'], '%d/%m/%Y %H:%M')))
			else:
				min_date = datetime.fromtimestamp(time.mktime(time.strptime('1970-01-01T00:00', '%d/%m/%Y %H:%M')))

			prs_col = mongodb.get_db().get_collection('peer_review_submissions')
			prs_entries = prs_col.find({'$and': [
        									{'created': {'$lte': max_date} },
        									{'created': {'$gte': min_date} }
        								]})
			self.message("%d peer review submission entries between %s and %s" % (prs_entries.count(), options['dateafter'], options['datebefore']))

			# Send each peer review submission entry as xAPI Statement
			bar = pyprind.ProgBar(prs_entries.count())
			for pr in prs_entries:
				course = None
				try:
					user_id = str(int(pr['author']))
					user = User.objects.get(pk=user_id)
					if 'course' in pr:
						course_id = int(pr['course'])
						course = Course.objects.get(pk=course_id)

					page = {}
					pr_url = "https://%s%s#unit%s/kq%s/p" % (settings.API_URI, reverse('course_classroom', kwargs={'course_slug': course.slug}),pr['unit'],pr['kq']),
					page['url'] = pr_url[0]

					page['type'] = 'assessment'

					kq = KnowledgeQuantum.objects.get(pk=pr['kq'])
					page['name'] = kq.title
					page['description'] = 'Peer assesment for course %s' % (course.name)

					geolocation = {
						'lat': 0.0,
						'lon': 0.0
					}

					timestamp = pr['created'].timetuple()
					learnerSubmitsAResource(user, page, course, geolocation, timestamp)
				except:
					self.error('\nERROR sending a statement for user %s in peer review submission with timestamp %s' % (pr['author'], pr['created']))
					if options['debug']:
						exc_type, exc_value, exc_traceback = sys.exc_info()
						self.error('Exception %s: %s' % (exc_type, exc_value))
						traceback.print_tb(exc_traceback, limit=5, file=sys.stdout)
					continue

				bar.update()

			self.message('\nPeer assessment submission entries succesfully exported')

		if options['peerreviews']:
			# Get peerassessments entries
			if options['datebefore']:
				max_date = datetime.fromtimestamp(time.mktime(time.strptime(options['datebefore'], '%d/%m/%Y %H:%M')))
			else:
				max_date = datetime.fromtimestamp(time.mktime(time.gmtime()))

			if options['dateafter']:
				min_date = datetime.fromtimestamp(time.mktime(time.strptime(options['dateafter'], '%d/%m/%Y %H:%M')))
			else:
				min_date = datetime.fromtimestamp(time.mktime(time.strptime('1970-01-01T00:00', '%d/%m/%Y %H:%M')))

			prr_col = mongodb.get_db().get_collection('peer_review_reviews')
			prr_entries = prr_col.find({'$and': [
        									{'created': {'$lte': max_date} },
        									{'created': {'$gte': min_date} }
        								]})
			self.message("%d peer review submission entries between %s and %s" % (prr_entries.count(), options['dateafter'], options['datebefore']))

			# Send each peer review submission entry as xAPI Statement
			bar = pyprind.ProgBar(prr_entries.count())
			for pr in prr_entries:
				course = None
				try:
					user_id = str(int(pr['reviewer']))
					user = User.objects.get(pk=user_id)
					if 'course' in pr:
						course_id = int(pr['course'])
						course = Course.objects.get(pk=course_id)
					kq = KnowledgeQuantum.objects.get(pk=pr['kq'])
					assignment = PeerReviewAssignment.objects.get(kq__id=pr['kq'])
					page = {}
					pr_url = "https://%s%s" % (settings.API_URI, reverse('course_review_review', kwargs={'course_slug': course.slug, 'assignment_id': assignment.id})),
					page['url'] = pr_url[0]

					page['type'] = 'peerfeedback'

					page['name'] = kq.title
					page['description'] = 'Peer assesment for course %s' % (course.name)

					geolocation = {
						'lat': 0.0,
						'lon': 0.0
					}

					score = get_peer_review_review_score(pr) *2 / 10
					result = {
                        'score': score,
                        'comment': pr['comment']
                    }

					timestamp = pr['created'].timetuple()
					learnerSubmitsAResource(user, page, course, geolocation, timestamp, result=result)
				except:
					self.error('\nERROR sending a statement for user %s in peer review submission with timestamp %s' % (pr['author'], pr['created']))
					if options['debug']:
						exc_type, exc_value, exc_traceback = sys.exc_info()
						self.error('Exception %s: %s' % (exc_type, exc_value))
						traceback.print_tb(exc_traceback, limit=5, file=sys.stdout)
					continue

				bar.update()

			self.message('\nPeer review submission entries succesfully exported')


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of manufacturer
 *
 * @author Wilson McCoubrey <wilson@mccoubreys.co.uk>
 */
class manufacturer extends My_Controller{
    function __construct() {
        parent::__construct();
        $this->load->model('Model_Manufacturer');
    }

    function index(){
        $id = $this->uri->segment(2);
        $manufacturer = $this->Model_Manufacturer->getManufacturer($id);
        $data['manufacturer'] = $manufacturer;
        parent::loadPage('manufacturer', $manufacturer->row()->name, $data);
    }
}


text:
package slib.platform.android.ui.helper;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

import slib.platform.android.Logger;

public class WebViewFileChooser implements FileChooserListener {

	private WebView webView;
	private int requestCode;
	private FileChooser fileChooser;
	private ValueCallback<Uri[]> callback;
	private ValueCallback<Uri> callbackOld;

	private boolean flagUseDefaultFileChooserParams;

	public WebViewFileChooser(WebView webView, int requestCode) {
		this.webView = webView;
		this.requestCode = requestCode;
		this.fileChooser = new FileChooser((Activity)(webView.getContext()), requestCode, this);
	}

	@TargetApi(Build.VERSION_CODES.LOLLIPOP)
	public void chooseFile(ValueCallback<Uri[]> callback, WebChromeClient.FileChooserParams fileChooserParams) {
		if (flagUseDefaultFileChooserParams) {
			this.callback = callback;
			this.callbackOld = null;
			((Activity)(webView.getContext())).startActivityForResult(fileChooserParams.createIntent(), requestCode);
		} else {
			String[] acceptTypes = fileChooserParams.getAcceptTypes();
			String acceptTypeTotal = "";
			for (int i = 0; i < acceptTypes.length; i++) {
				String acceptType = acceptTypes[i];
				if (acceptType != null && acceptType.length() > 0) {
					if (acceptTypeTotal.length() > 0) {
						acceptTypeTotal += ";";
					}
					acceptTypeTotal += acceptType;
				}
			}
			if (acceptTypeTotal.length() == 0) {
				acceptTypeTotal = "*";
			}
			chooseFile(acceptTypeTotal, fileChooserParams.isCaptureEnabled() ? "capture" : "filesystem", null, callback);
		}
	}

	public void chooseFile(ValueCallback<Uri> callback) {
		chooseFile(callback, "");
	}

	public void chooseFile(ValueCallback<Uri> callback, String acceptType) {
		chooseFile(callback, acceptType, "filesystem");
	}

	public void chooseFile(ValueCallback<Uri> callback, String acceptType, String mediaSource) {
		chooseFile(acceptType, mediaSource, callback, null);
	}

	public void chooseFile(String acceptType, String mediaSource, ValueCallback<Uri> callbackOld, ValueCallback<Uri[]> callback) {
		this.callbackOld = callbackOld;
		this.callback = callback;

		try {
			boolean flagFileSystem = false;
			if (mediaSource == null || mediaSource.length() == 0) {
				flagFileSystem = true;
				mediaSource = "filesystem";
			} else if (mediaSource.equals("filesystem")) {
				flagFileSystem = true;
			}
			if (flagFileSystem) {
				int indexCapture = acceptType.indexOf("capture=");
				if (indexCapture >= 0) {
					indexCapture += 8;
					int lastCapture = acceptType.indexOf(';', indexCapture);
					if (lastCapture < 0) {
						mediaSource = acceptType.substring(indexCapture);
					} else {
						mediaSource = acceptType.substring(indexCapture, lastCapture);
					}
					if (!(mediaSource.equals("filesystem"))) {
						flagFileSystem = false;
					}
				}
			}
			if (acceptType.startsWith("image/")) {
				if (!flagFileSystem && (mediaSource.equals("camera") || mediaSource.equals("capture"))) {
					fileChooser.captureImage();
				} else {
					fileChooser.chooseImage();
				}
			} else if (acceptType.startsWith("video/")) {
				if (!flagFileSystem && (mediaSource.equals("camcorder") || mediaSource.equals("capture"))) {
					fileChooser.captureVideo();
				} else {
					fileChooser.chooseVideo();
				}
			} else if (acceptType.startsWith("audio/")) {
				if (!flagFileSystem && (mediaSource.equals("microphone") || mediaSource.equals("capture"))) {
					fileChooser.captureAudio();
				} else {
					fileChooser.chooseAudio();
				}
			} else {
				fileChooser.chooseFile();
			}
		} catch (Exception e) {
			Logger.exception(e);
			if (callback != null) {
				callback.onReceiveValue(null);
			}
			if (callbackOld != null) {
				callbackOld.onReceiveValue(null);
			}
		}

	}

	@Override
	public void onChooseFile(Uri uri, Object content) {
		if (callback != null) {
			if (uri != null) {
				callback.onReceiveValue(new Uri[]{uri});
			} else {
				callback.onReceiveValue(null);
			}
		}
		if (callbackOld != null) {
			callbackOld.onReceiveValue(uri);
		}
	}

	public void processActivityResult(int resultCode, Intent intent) {
		if (flagUseDefaultFileChooserParams && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
			if (callback != null) {
				callback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
			}
		} else {
			fileChooser.processActivityResult(resultCode, intent);
		}
	}

}


text:
abstract class Person(name: String){ override def toString = name }
class Man(name: String) extends Person(name)
class Woman(name: String) extends Person(name)
class Child(name: String) extends Person(name)


text:
<!DOCTYPE html>

<title>Quiz Game – Регистрация</title>
	<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" />
	<link rel="stylesheet" href="css/styles.css" />
	<link rel="stylesheet" href="css/form.css" />

		<form th:action="@{/addUser}" method="post" class="form-signin">

Регистрация

Пользователь с таким именем уже зарегистрирован.

			Имя пользователя
			<input type="text" id="username" name="username" class="form-control" placeholder="Имя пользователя" required="required" autofocus="autofocus" />
			Пароль
        	<input type="password" id="password" name="password" class="form-control" placeholder="Пароль" required="required" />
        	<button class="btn btn-lg btn-primary btn-block" type="submit">Регистрация</button>
        	Войти в игру
		</form>


text:
import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

// this is just a service for getting the contents of files that are in the publshed
// branch of the site repository

@Injectable()
export class FileContentService {
  private baseUrl = '/'; // all request urls should be relative to the site's root url

  constructor(private http: Http) { }

  // copied from tour of heroes tutorial
  private simpleErrorHandler(error: any): Promise<any> {
    console.error('An error occurred', error); // for demo purposes only
    return Promise.reject(error.message || error);
  }

  // copied from server communication example
  private handleError(error: Response | any): Observable<any> {
    // In a real world app, you might use a remote logging infrastructure
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = /* body.error || */ JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }
}


text:
default[:phpunit][:install_method] = "pear"
default[:phpunit][:version] = "latest"


text:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { ChannelTableComponent } from './channel-table.component';

describe('ChannelTableComponent', () => {
  let component: ChannelTableComponent;
  let fixture: ComponentFixture<ChannelTableComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ ChannelTableComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ChannelTableComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});


text:
extern "C" {
#include "hiredis/async.h"
#include "hiredis/hiredis.h"
}

// TODO(pcm): Integrate into the C++ tree.
#include "ray/common/ray_config.h"

namespace {

/// A helper function to call the callback and delete it from the callback
/// manager if necessary.
void ProcessCallback(int64_t callback_index,
                     std::shared_ptr<ray::gcs::CallbackReply> callback_reply) {
  RAY_CHECK(callback_index >= 0) << "The callback index must be greater than 0, "
                                 << "but it actually is " << callback_index;
  auto callback_item = ray::gcs::RedisCallbackManager::instance().get(callback_index);
  if (!callback_item->is_subscription_) {
    // Record the redis latency for non-subscription redis operations.
    auto end_time = absl::GetCurrentTimeNanos() / 1000;
    ray::stats::RedisLatency().Record(end_time - callback_item->start_time_);
  }

  // Dispatch the callback.
  callback_item->Dispatch(callback_reply);

  if (!callback_item->is_subscription_) {
    // Delete the callback if it's not a subscription callback.
    ray::gcs::RedisCallbackManager::instance().remove(callback_index);
  }
}

}  // namespace

namespace ray {

namespace gcs {

CallbackReply::CallbackReply(redisReply *redis_reply) : reply_type_(redis_reply->type) {
  RAY_CHECK(nullptr != redis_reply);

  switch (reply_type_) {
  case REDIS_REPLY_NIL: {
    break;
  }
  case REDIS_REPLY_ERROR: {
    RAY_CHECK(false) << "Got an error in redis reply: " << redis_reply->str;
    break;
  }
  case REDIS_REPLY_INTEGER: {
    int_reply_ = static_cast<int64_t>(redis_reply->integer);
    break;
  }
  case REDIS_REPLY_STATUS: {
    const std::string status_str(redis_reply->str, redis_reply->len);
    if (status_str == "OK") {
      status_reply_ = Status::OK();
    } else {
      status_reply_ = Status::RedisError(status_str);
    }
    break;
  }
  case REDIS_REPLY_STRING: {
    string_reply_ = std::string(redis_reply->str, redis_reply->len);
    break;
  }
  case REDIS_REPLY_ARRAY: {
    // Array replies are only used for pub-sub messages. Parse the published message.
    redisReply *message_type = redis_reply->element[0];
    if (strcmp(message_type->str, "subscribe") == 0) {
      // If the message is for the initial subscription call, return the empty
      // string as a response to signify that subscription was successful.
    } else if (strcmp(message_type->str, "message") == 0) {
      // If the message is from a PUBLISH, make sure the data is nonempty.
      redisReply *message = redis_reply->element[redis_reply->elements - 1];
      // data is a notification message.
      string_reply_ = std::string(message->str, message->len);
      RAY_CHECK(!string_reply_.empty()) << "Empty message received on subscribe channel.";
    } else {
      RAY_LOG(FATAL) << "This is not a pubsub reply: data=" << message_type->str;
    }
    break;
  }
  default: {
    RAY_LOG(WARNING) << "Encountered unexpected redis reply type: " << reply_type_;
  }
  }
}

bool CallbackReply::IsNil() const { return REDIS_REPLY_NIL == reply_type_; }

int64_t CallbackReply::ReadAsInteger() const {
  RAY_CHECK(reply_type_ == REDIS_REPLY_INTEGER) << "Unexpected type: " << reply_type_;
  return int_reply_;
}

Status CallbackReply::ReadAsStatus() const {
  RAY_CHECK(reply_type_ == REDIS_REPLY_STATUS) << "Unexpected type: " << reply_type_;
  return status_reply_;
}

std::string CallbackReply::ReadAsString() const {
  RAY_CHECK(reply_type_ == REDIS_REPLY_STRING) << "Unexpected type: " << reply_type_;
  return string_reply_;
}

std::string CallbackReply::ReadAsPubsubData() const {
  RAY_CHECK(reply_type_ == REDIS_REPLY_ARRAY) << "Unexpected type: " << reply_type_;
  return string_reply_;
}

// This is a global redis callback which will be registered for every
// asynchronous redis call. It dispatches the appropriate callback
// that was registered with the RedisCallbackManager.
void GlobalRedisCallback(void *c, void *r, void *privdata) {
  if (r == nullptr) {
    return;
  }
  int64_t callback_index = reinterpret_cast<int64_t>(privdata);
  redisReply *reply = reinterpret_cast<redisReply *>(r);
  ProcessCallback(callback_index, std::make_shared<CallbackReply>(reply));
}

int64_t RedisCallbackManager::add(const RedisCallback &function, bool is_subscription,
                                  boost::asio::io_service &io_service) {
  auto start_time = absl::GetCurrentTimeNanos() / 1000;

  std::lock_guard<std::mutex> lock(mutex_);
  callback_items_.emplace(
      num_callbacks_,
      std::make_shared<CallbackItem>(function, is_subscription, start_time, io_service));
  return num_callbacks_++;
}

std::shared_ptr<RedisCallbackManager::CallbackItem> RedisCallbackManager::get(
    int64_t callback_index) {
  std::lock_guard<std::mutex> lock(mutex_);
  RAY_CHECK(callback_items_.find(callback_index) != callback_items_.end());
  return callback_items_[callback_index];
}

void RedisCallbackManager::remove(int64_t callback_index) {
  std::lock_guard<std::mutex> lock(mutex_);
  callback_items_.erase(callback_index);
}

#define REDIS_CHECK_ERROR(CONTEXT, REPLY)                     \
  if (REPLY == nullptr || REPLY->type == REDIS_REPLY_ERROR) { \
    return Status::RedisError(CONTEXT->errstr);               \
  }

RedisContext::~RedisContext() {
  if (context_) {
    redisFree(context_);
  }
}

Status AuthenticateRedis(redisContext *context, const std::string &password) {
  if (password == "") {
    return Status::OK();
  }
  redisReply *reply =
      reinterpret_cast<redisReply *>(redisCommand(context, "AUTH %s", password.c_str()));
  REDIS_CHECK_ERROR(context, reply);
  freeReplyObject(reply);
  return Status::OK();
}

Status AuthenticateRedis(redisAsyncContext *context, const std::string &password) {
  if (password == "") {
    return Status::OK();
  }
  int status = redisAsyncCommand(context, NULL, NULL, "AUTH %s", password.c_str());
  if (status == REDIS_ERR) {
    return Status::RedisError(std::string(context->errstr));
  }
  return Status::OK();
}

void RedisAsyncContextDisconnectCallback(const redisAsyncContext *context, int status) {
  RAY_LOG(DEBUG) << "Redis async context disconnected. Status: " << status;
  // Reset raw 'redisAsyncContext' to nullptr because hiredis will release this context.
  reinterpret_cast<RedisAsyncContext *>(context->data)->ResetRawRedisAsyncContext();
}

void SetDisconnectCallback(RedisAsyncContext *redis_async_context) {
  redisAsyncContext *raw_redis_async_context =
      redis_async_context->GetRawRedisAsyncContext();
  raw_redis_async_context->data = redis_async_context;
  redisAsyncSetDisconnectCallback(raw_redis_async_context,
                                  RedisAsyncContextDisconnectCallback);
}

template <typename RedisContext, typename RedisConnectFunction>
Status ConnectWithRetries(const std::string &address, int port,
                          const RedisConnectFunction &connect_function,
                          RedisContext **context) {
  int connection_attempts = 0;
  *context = connect_function(address.c_str(), port);
  while (*context == nullptr || (*context)->err) {
    if (connection_attempts >= RayConfig::instance().redis_db_connect_retries()) {
      if (*context == nullptr) {
        RAY_LOG(FATAL) << "Could not allocate redis context.";
      }
      if ((*context)->err) {
        RAY_LOG(FATAL) << "Could not establish connection to redis " << address << ":"
                       << port << " (context.err = " << (*context)->err << ")";
      }
      break;
    }
    RAY_LOG(WARNING) << "Failed to connect to Redis, retrying.";
    // Sleep for a little.
    usleep(RayConfig::instance().redis_db_connect_wait_milliseconds() * 1000);
    *context = connect_function(address.c_str(), port);
    connection_attempts += 1;
  }
  return Status::OK();
}

Status RedisContext::Connect(const std::string &address, int port, bool sharding,
                             const std::string &password = "") {
  RAY_CHECK(!context_);
  RAY_CHECK(!redis_async_context_);
  RAY_CHECK(!async_redis_subscribe_context_);

  RAY_CHECK_OK(ConnectWithRetries(address, port, redisConnect, &context_));
  RAY_CHECK_OK(AuthenticateRedis(context_, password));

  redisReply *reply = reinterpret_cast<redisReply *>(
      redisCommand(context_, "CONFIG SET notify-keyspace-events Kl"));
  REDIS_CHECK_ERROR(context_, reply);
  freeReplyObject(reply);

  // Connect to async context
  redisAsyncContext *async_context = nullptr;
  RAY_CHECK_OK(ConnectWithRetries(address, port, redisAsyncConnect, &async_context));
  RAY_CHECK_OK(AuthenticateRedis(async_context, password));
  redis_async_context_.reset(new RedisAsyncContext(async_context));
  SetDisconnectCallback(redis_async_context_.get());

  // Connect to subscribe context
  redisAsyncContext *subscribe_context = nullptr;
  RAY_CHECK_OK(ConnectWithRetries(address, port, redisAsyncConnect, &subscribe_context));
  RAY_CHECK_OK(AuthenticateRedis(subscribe_context, password));
  async_redis_subscribe_context_.reset(new RedisAsyncContext(subscribe_context));
  SetDisconnectCallback(async_redis_subscribe_context_.get());

  return Status::OK();
}

Status RedisContext::RunArgvAsync(const std::vector<std::string> &args) {
  RAY_CHECK(redis_async_context_);
  // Build the arguments.
  std::vector<const char *> argv;
  std::vector<size_t> argc;
  for (size_t i = 0; i < args.size(); ++i) {
    argv.push_back(args[i].data());
    argc.push_back(args[i].size());
  }
  // Run the Redis command.
  Status status = redis_async_context_->RedisAsyncCommandArgv(
      nullptr, nullptr, args.size(), argv.data(), argc.data());
  return status;
}

Status RedisContext::SubscribeAsync(const ClientID &client_id,
                                    const TablePubsub pubsub_channel,
                                    const RedisCallback &redisCallback,
                                    int64_t *out_callback_index) {
  RAY_CHECK(pubsub_channel != TablePubsub::NO_PUBLISH)
      << "Client requested subscribe on a table that does not support pubsub";
  RAY_CHECK(async_redis_subscribe_context_);

  int64_t callback_index =
      RedisCallbackManager::instance().add(redisCallback, true, io_service_);
  RAY_CHECK(out_callback_index != nullptr);
  *out_callback_index = callback_index;
  Status status = Status::OK();
  if (client_id.IsNil()) {
    // Subscribe to all messages.
    std::string redis_command = "SUBSCRIBE %d";
    status = async_redis_subscribe_context_->RedisAsyncCommand(
        reinterpret_cast<redisCallbackFn *>(&GlobalRedisCallback),
        reinterpret_cast<void *>(callback_index), redis_command.c_str(), pubsub_channel);
  } else {
    // Subscribe only to messages sent to this client.
    std::string redis_command = "SUBSCRIBE %d:%b";
    status = async_redis_subscribe_context_->RedisAsyncCommand(
        reinterpret_cast<redisCallbackFn *>(&GlobalRedisCallback),
        reinterpret_cast<void *>(callback_index), redis_command.c_str(), pubsub_channel,
        client_id.Data(), client_id.Size());
  }

  return status;
}

}  // namespace gcs

}  // namespace ray


text:
package org.wso2.siddhi.core.query.window;

import junit.framework.Assert;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import org.wso2.siddhi.core.ExecutionPlanRuntime;
import org.wso2.siddhi.core.SiddhiManager;
import org.wso2.siddhi.core.event.Event;
import org.wso2.siddhi.core.query.output.callback.QueryCallback;
import org.wso2.siddhi.core.stream.input.InputHandler;
import org.wso2.siddhi.core.util.EventPrinter;

public class UniqueWindowTestCase {
    private static final Logger log = Logger.getLogger(UniqueWindowTestCase.class);
    private int count;
    private long value;
    private boolean eventArrived;

    @Before
    public void init() {
        count = 0;
        value = 0;
        eventArrived = false;
    }

    @Test
    public void uniqueWindowTest1() throws InterruptedException {
        log.info("uniqueWindow test1");

        SiddhiManager siddhiManager = new SiddhiManager();

        String cseEventStream = "" +
                "define stream LoginEvents (timeStamp long, ip string);";
        String query = "" +
                "@info(name = 'query1') " +
                "from LoginEvents#window.unique(ip) " +
                "select count(ip) as ipCount, ip " +
                "insert into uniqueIps ;";

        ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(cseEventStream + query);

        executionPlanRuntime.addCallback("query1", new QueryCallback() {
            @Override
            public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
                EventPrinter.print(timeStamp, inEvents, removeEvents);
                if (inEvents != null) {
                    value = (Long) inEvents[inEvents.length - 1].getData(0);
                }
                eventArrived = true;
            }

        });

        InputHandler inputHandler = executionPlanRuntime.getInputHandler("LoginEvents");
        executionPlanRuntime.start();

        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.4"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"});
        inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.5"});

        Thread.sleep(1000);

        Assert.assertEquals("Event arrived", true, eventArrived);
        Assert.assertEquals("Event max value", 3, value);

        executionPlanRuntime.shutdown();
    }

    @Test
    public void uniqueWindowTest2() throws InterruptedException {
        log.info("uniqueWindow test2");

        SiddhiManager siddhiManager = new SiddhiManager();

        String cseEventStream = "" +
                "define stream LoginEvents (id String , timeStamp long, ip string);";
        String query = "" +
                "@info(name = 'query1') " +
                "from LoginEvents#window.unique(ip) " +
                "select id, count(ip) as ipCount, ip " +
                "insert into uniqueIps ;";

        ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(cseEventStream + query);

        executionPlanRuntime.addCallback("query1", new QueryCallback() {
            @Override
            public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
                EventPrinter.print(timeStamp, inEvents, removeEvents);
                if (inEvents != null) {
                    value = (Long) inEvents[inEvents.length - 1].getData(1);
                }
                eventArrived = true;
            }

        });

        InputHandler inputHandler = executionPlanRuntime.getInputHandler("LoginEvents");
        executionPlanRuntime.start();

        inputHandler.send(new Object[]{"A1", System.currentTimeMillis(), "192.10.1.3"});
        inputHandler.send(new Object[]{"A2", System.currentTimeMillis(), "192.10.1.3"});
        inputHandler.send(new Object[]{"A3", System.currentTimeMillis(), "192.10.1.4"});
        inputHandler.send(new Object[]{"A4", System.currentTimeMillis(), "192.10.1.3"});
        inputHandler.send(new Object[]{"A5", System.currentTimeMillis(), "192.10.1.5"});

        Thread.sleep(1000);

        Assert.assertEquals("Event arrived", true, eventArrived);
        Assert.assertEquals("Event max value", 3, value);

        executionPlanRuntime.shutdown();
    }

}


text:
package org.librairy.modeler.lda.dao;

import lombok.Data;
import org.librairy.boot.storage.generator.URIGenerator;

import java.io.Serializable;
import java.util.List;

/**
 * @author Badenes Olmedo, Carlos <cbadenes@fi.upm.es>
 */
@Data
public class ShapeRow implements Serializable{

    private String uri;
    private Long id;
    private List<Double> vector;
    private String date;
    private String type;
}


text:
Meteor.startup(function() {
	Tracker.autorun(function() {
		if (RocketChat.settings.get('Message_AllowSnippeting')) {
			RocketChat.TabBar.addButton({
				groups: ['channel', 'group', 'direct'],
				id: 'snippeted-messages',
				i18nTitle: 'snippet-message',
				icon: 'code',
				template: 'snippetedMessages',
				order: 20
			});
		} else {
			RocketChat.TabBar.removeButton('snippeted-messages');
		}
	});
});


text:
package org.apache.harmony.vts.test.vm.jvmti;

/**
 * @author Valentin Al. Sitnick
 * @version $Revision: 1.1 $
 *
 */
public class GetObjectMonitorUsage0104 {
    public static Object obj_ = new Object();
    public static Object obj = new Object();
    static int thread_counter = 0;

    static public void main(String args[]) {

        TestThread_GOMU_0104 t1 = new TestThread_GOMU_0104("agent 1");
        TestThread_GOMU_0104 t2 = new TestThread_GOMU_0104("agent 2");
        TestThread_GOMU_0104 t3 = new TestThread_GOMU_0104("agent 3");

        t1.start();
        t2.start();
        t3.start();

        return;
    }
}

class TestThread_GOMU_0104 extends Thread {
    static boolean test = false;

    TestThread_GOMU_0104(String name) {
        super(name);
    }

    public void run() {
        synchronized(GetObjectMonitorUsage0104.obj_) {
            GetObjectMonitorUsage0104.thread_counter++;
        }

        synchronized(GetObjectMonitorUsage0104.obj) {

            if (!test) {
                test = true;
                while ( GetObjectMonitorUsage0104.thread_counter < 3 ) {
                    try {
                        Thread.sleep(500);
                    } catch (Throwable tex) { }
                }
                special_method( GetObjectMonitorUsage0104.obj );
            }
        }
    }

    static public void special_method(Object obj) {
        Object _OBJ = obj;
        /*
         * Transfer control to native part.
         */
        try {
            throw new InterruptedException();
        } catch (Throwable tex) { }
        return;
    }
}


text:
@import url("/Portals/_default/Skins/AgapeBlue/start/jquery-ui-1.8.16.custom.css");
/*########## PortalCSS ################*/
/*Use this section to set the styles for the portal to match your skin */
.p {
	margin:0px;
	padding:0px;
	font-size: inherit;
	font-family: inherit;
	font-weight: inherit;
	text-align: inherit;
	color: inherit;
	line-height: inherit;
	vertical-align: top;
	font-family:verdana;
}

div {

	font-family:verdana;
	/*font-size:12px;*/
	margin:0px;
	padding: 0px;

}

h1, .AgapeH1{color: #026890;font-size:  36pt; font-family:  Verdana, Geneva, sans-serif; font-weight: bold ;border-bottom: solid 2px #026890;}
h2, .AgapeH2{color: #026890;font-size: 24pt; font-family:  Verdana, Geneva, sans-serif; font-weight: bold ;border-bottom: solid 2px #026890;}
h3, .AgapeH3{color: #026890;font-size: 18pt; font-family:  Verdana, Geneva, sans-serif; font-weight: bold ;}
h4, .AgapeH4{color: #026890;font-size: 12pt; font-family:  Verdana, Geneva, sans-serif; font-weight: bold ;}
h5, .AgapeH5{color: #026890;font-size: 10pt; font-family:  Verdana, Geneva, sans-serif; font-weight: bold ;}

.AgapeError
{
    color: Red;
    font-style: italic;
}
.Agape_Story_subtitle {
font-family: verdana;
font-size: 9pt;
font-weight: lighter;
font-style: italic;
color:
gray;
}
.Agape_Story_picturebox {
margin: 0px 15px 15px 0px;
float: left;
display: inline;
width: 300px;
}

a:link,a:visited,a:active,a .AgapeLink  {color:#3E81B5; text-decoration:none; font-weight:normal; }
a:hover{color:#026890; text-decoration: underline;  }

.DataGrid_Container {margin-top:15px;}

.dnnGridItem
{
    text-align: left;
}

.ui-widget-header.dnnGridHeader, .ui-widget-header.dnnGridFooter, .ui-widget-header.dnnGridHeader th{font-weight:bold; background-image: none; color: White;

                                                  }
.DataGrid_Header td, .NormalBold td{font-weight:bold; color: White;}

.acGridHeader{opacity: .5; border: 0;}

.plainButton {background:#aaa;background:-moz-linear-gradient(top, #F3F3F3 0%, #CFCFCF 100%);
			background:-webkit-gradient(linear, left top, left bottom, color-stop(0%,#F3F3F3), color-stop(100%,#CFCFCF));
			filter:progid:DXImageTransform.Microsoft.gradient( startColorstr='#F3F3F3', endColorstr='#CFCFCF',GradientType=0 );
			;padding:8px 20px;border:1px #999 solid;border-radius:3px;-moz-border-radius:3px;line-height:16px;height:16px;font-weight:bold;font-size:11px;min-width:65px;cursor:default; text-align: center;}


text:
<?php

namespace Zoop\Contracts;

use Zoop\Lib\APIResource;

interface ZoopInvoices{

    /**
     * API Resource.
     *
     * @param $APIResource $APIResource
    */
    public function __construct(APIResource $APIResource);

    /**
     * Create a new Invoice
     *
     * @param $post array
    */
    public function create($post);

        /**
     * Update a created Invoice
     *
     * @param $invoiceID string
     * @param $post array
     */
    public function update($invoiceID, $post);

    /**
     * Delete a Invoice by id
     *
     * @param $invoiceID string
    */
    public function delete($invoiceID);

    /**
     * Approve a Invoice by id
     *
     * @param $invoiceID string
    */
    public function approve($invoiceID);

    /**
     * Void a Invoice by id
     *
     * @param $invoiceID string
    */
    public function void($invoiceID);

    /**
     * Retrieve the details of a Invoice by id
     *
     * @param $invoiceID string
     */
    public function get($invoiceID);

    /**
     * Returns a JSON object with a list of Invoices.
     */
    public function getAll();

    /**
     * Returns a JSON object with a list of Invoices of seller.
     */
    public function getAllBySeller($customerID);
}


text:
import sys

from difflib import SequenceMatcher

from pygments import lex
from pygments.lexers.c_cpp import CLexer
from pygments.styles import get_style_by_name

class CodeDiff:
  opcode_style = {
    'insert': {'bgcolor': 'eaffea'}, 'replace': {'bgcolor': 'fff68f'},
    'delete': {'bgcolor': 'ffaaaa'}, 'equal': {'bgcolor': None},
  }

  def __init__(self, from_str, to_str):
    self.from_str = from_str
    self.to_str = to_str

    # difflib stuff.
    self.sm = SequenceMatcher(None, from_str, to_str)

  def get_desc(self, for_from_str):
    descs = []
    pdesc = self.get_pygmentation_desc(for_from_str)
    ddesc = self.get_difflib_desc(for_from_str)
    while pdesc or ddesc:
      # The diff may be larger than the program itself.
      if not pdesc:
        desc = ddesc.pop(0)

        # Update the starting position of the diff fragment to the last
        # character descriptor in descriptor list.
        desc[1] = descs[-1][2]
        descs.append(desc)
        break

      # We have an opcode from dstart to dend.
      dstyle, dstart, dend = ddesc[0]

      # We have an token dstart to dend.
      pstyle, pstart, pend = pdesc[0]

      # TODO: update() overwrites values for common keys, is this correct?
      style = pstyle + dstyle

      # If the token fits within the opcode region, merge the two styles.
      if dstart <= pstart and pend <= dend:
        descs.append([style, pstart, pend])

        # Next token & remove the diff opcode if necessary.
        pdesc.pop(0)
        if (pend == dend): ddesc.pop(0)

      # If the token doesn't fit within the opcode region, seperate it into two.
      elif dstart <= pstart and pend >= dend:
        descs.append([style, pstart, dend])

        # Second part of the token stays in the array.
        pdesc[0] = [style, dend, pend]
        ddesc.pop(0)
      else:
        # TODO: missing some cases?
        assert False

    # Both arrays should be empty when the above loop finishes.
    assert (not pdesc) and (not ddesc)
    return descs

  def get_pygmentation_desc(self, for_from_str):
    desc = []
    s = self.from_str if for_from_str else self.to_str
    token_start = token_end = 0
    for token_type, token in lex(s, CLexer()):
      token_start = token_end
      token_end += len(token)
      token_class = 'token-' + '-'.join(token_type).lower()
      desc.append([[token_class], token_start, token_end])
    return desc

  def get_difflib_desc(self, for_from_str):
    desc = []
    for s in self.sm.get_opcodes():
      opcode, from_start, from_end, to_start, to_end = s
      if for_from_str:
        desc.append([['opcode-' + opcode], from_start, from_end])
      else:
        desc.append([['opcode-' + opcode], to_start, to_end])
    return desc

  def to_html(self, for_from_str):
    # TODO: don't hardcode output formatting.
    html = ""
    descs = self.get_desc(for_from_str)
    for style, start, end in descs:
      span = ''
      fragment = (self.from_str if for_from_str else self.to_str)[start:end]
      fragment = fragment.replace('\n', '
')
      fragment = fragment.replace(' ', ' ')
      span += fragment + ''
      html += span
    return html

  @staticmethod
  def from_files(from_file, to_file):
    with open(from_file) as f:
      from_str = f.read()
    with open(to_file) as f:
      to_str = f.read()
    return CodeDiff(from_str, to_str)


text:
package uk.co.o2.android.roboexample.opengl.models;

import org.jetbrains.annotations.NotNull;

/**
 * Created by hostova1 on 08/09/2014.
 */
public class PointLight {

    private float[] mLightAmbient = new float[]{1.0f, 1.0f, 1.0f};
    private float[] mLightDiffuse = new float[]{1.0f, 1.0f, 1.0f};
    private float[] mLightSpecular = new float[]{1.0f, 1.0f, 1.0f};
    private float mSpecularShininess = 5;

    private Vector3 mPosition = new Vector3(0.0f, 0.0f, 0.0f);

    public float[] getAmbientColor() {
        return mLightAmbient;
    }

    public void setAmbientColor(@NotNull float[] ambientColor) {
        this.mLightAmbient = ambientColor;
    }

    public float[] getDiffuseColor() {
        return mLightDiffuse;
    }

    public void setDiffuseColor(@NotNull float[] diffuseColor) {
        this.mLightDiffuse = diffuseColor;
    }

    public float[] getSpecularColor() {
        return mLightSpecular;
    }

    public void setSpecularColor(@NotNull float[] specularColor) {
        this.mLightSpecular = specularColor;
    }

    public void setSpecularShininess(float specularShininess) {
        this.mSpecularShininess = specularShininess;
    }

    public float getSpecularShininess() {
        return mSpecularShininess;
    }

    public Vector3 getPosition() {
        return mPosition;
    }

    public void setPosition(@NotNull Vector3 position) {
        this.mPosition = position;
    }

    public void setPosition(float x, float y, float z) {
        this.mPosition.x = x;
        this.mPosition.y = y;
        this.mPosition.z = z;
    }
}


text:
const notify = require("gulp-notify");

module.exports = function (errorObject) {
  notify.onError(errorObject.toString()).apply(this, arguments);
  // Keep gulp from hanging on this task
  if (typeof this.emit === "function") {
    this.emit("end");
  }
};


text:
package org.zmlx.hg4idea.test;

import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.history.VcsFileRevision;
import com.intellij.openapi.vcs.history.VcsHistorySession;
import com.intellij.vcsUtil.VcsUtil;
import org.testng.annotations.Test;
import org.zmlx.hg4idea.HgVcs;

import java.io.File;
import java.util.Collection;
import java.util.List;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;

/**
 * HgHistoryTest tests retrieving file history and specific revisions.
 */
public class HgHistoryTest extends HgSingleUserTest {

  /**
   * 1. Make two versions of a file (create, add, commit, modify, commit).
   * 2. Get the revisions history.
   * 3. Verify versions' contents and the current version.
   */
  @Test
  public void testCurrentAndPreviousRevisions() throws Exception {
    int versions = 0;
    fillFile(myProjectDir, new String[]{ AFILE }, FILE_CONTENT);
    addAll();
    commitAll("initial content");
    versions++;
    fillFile(myProjectDir, new String[] { AFILE} , FILE_CONTENT_2);
    commitAll("updated content");
    versions++;

    final VcsHistorySession session = getHistorySession(AFILE);
    final List<VcsFileRevision> revisions = session.getRevisionList();
    for (VcsFileRevision rev : revisions) {
      rev.loadContent();
    }

    assertEquals(revisions.size(), versions);
    assertTrue(session.isCurrentRevision(revisions.get(0).getRevisionNumber()));
    assertEquals(revisions.get(0).getContent(), FILE_CONTENT_2.getBytes());
    assertEquals(revisions.get(1).getContent(), FILE_CONTENT.getBytes());
  }

  /**
   * 1. Make initial version of a file (create, add, commit).
   * 2. Rename file (rename, commit).
   * 3. Update file (modify, commit).
   * 4. Get the file history.
   * 5. Verify revision contents and the current revision.
   */
  @Test
  public void renameShouldPreserveFileHistory() throws Exception {
    int versions = 0;

    fillFile(myProjectDir, new String[]{ AFILE }, FILE_CONTENT);
    addAll();
    commitAll("initial content");
    versions++;

    runHgOnProjectRepo("rename", AFILE, BFILE);
    commitAll("file renamed");
    versions++;

    fillFile(myProjectDir, new String[]{ BFILE }, FILE_CONTENT_2);
    commitAll("updated content");
    versions++;

    final VcsHistorySession session = getHistorySession(BFILE);
    final List<VcsFileRevision> revisions = session.getRevisionList();
    loadAllRevisions(revisions);

    assertEquals(revisions.size(), versions);
    assertTrue(session.isCurrentRevision(revisions.get(0).getRevisionNumber()));
    assertEquals(revisions.get(0).getContent(), FILE_CONTENT_2.getBytes());
    assertEquals(revisions.get(2).getContent(), FILE_CONTENT.getBytes());
  }

  private void loadAllRevisions(Collection<VcsFileRevision> revisions) throws Exception {
    for (VcsFileRevision rev : revisions) {
      rev.loadContent();
    }
  }

  private VcsHistorySession getHistorySession(String relativePath) throws VcsException {
    return HgVcs.getInstance(myProject).getVcsHistoryProvider().createSessionFor(VcsUtil.getFilePath(new File(myProjectDir, relativePath), false));
  }

}


text:
echo running commmon provisioner
cp /vagrant/resources/motd /etc/motd
set -e
set -x

# Turn on selinux to be more like production
sed -i 's/SELINUX=permissive/SELINUX=enforcing/' /etc/selinux/config
setenforce 1

# Add host entry for sandbox.bigfix.com
echo 127.0.0.1 sandbox.bigfix.com >> /etc/hosts

# Apply updates, required for latest docker
#yum -y update

# Run docker install script
# see https://docs.docker.com/docker/installation/centos/
curl -sSL https://get.docker.com/ | sh

# change the docker config to allocate 20G to containers
# see https://docs.docker.com/articles/systemd/ for info on configuration
mkdir -p /etc/systemd/system/docker.service.d
echo '[Service]' > /etc/systemd/system/docker.service.d/docker.conf
echo 'ExecStart=' >> /etc/systemd/system/docker.service.d/docker.conf
echo "ExecStart=/usr/bin/docker -d -s=devicemapper --storage-opt dm.basesize=20G -H fd:// " \
    >>  /etc/systemd/system/docker.service.d/docker.conf
systemctl daemon-reload

# Start docker and set to start on boot
systemctl start docker
systemctl enable docker

# install docker compose
curl -L \
  https://github.com/docker/compose/releases/download/1.4.2/docker-compose-`uname -s`-`uname -m` \
  > /usr/local/bin/docker-compose
chmod +x /usr/local/bin/docker-compose


text:
KunstmaanAdminNodeBundle by Kunstmaan
=================================

About
-----
The KunstmaanAdminNodeBundle for Symfony 2 is part of the bundles we use to build custom and flexible applications at Kunstmaan.
You have to install this bundle in order to work with nodes and pagetypes.

View screenshots and more on our [github page](http://kunstmaan.github.com/KunstmaanAdminNodeBundle).

[![Build Status](https://secure.travis-ci.org/Kunstmaan/KunstmaanAdminNodeBundle.png?branch=master)](http://travis-ci.org/Kunstmaan/KunstmaanAdminNodeBundle)

Installation requirements
-------------------------
You should be able to get Symfony 2 up and running before you can install the KunstmaanAdminNodeBundle.

Installation instructions
-------------------------
Assuming you have installed composer.phar or composer binary:

``` bash
$ composer require kunstmaan/adminnode-bundle
```

Add the KunstmaanAdminNodeBundle to your AppKernel.php file:

```
new Kunstmaan\AdminNodeBundle\KunstmaanAdminNodeBundle(),
```

Contact
-------
Kunstmaan (support@kunstmaan.be)

Download
--------
You can also clone the project with Git by running:

```
$ git clone git://github.com/Kunstmaan/KunstmaanAdminNodeBundle
```


text:
package de.codesourcery.jinvaders.sound;

import java.io.IOException;
import java.net.URL;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.LineUnavailableException;

import de.codesourcery.jinvaders.Main;

public enum SoundEffect
{
	PLAYER_SHOOTING("/player_laser.wav",Volume.LOUD , 3),
	ONE_LIFE_LOST("/one_life_lost.wav",Volume.LOUD , 2),
	INVADER_SHOOTING("/invader_laser.wav",Volume.QUIET , 3),
	GAME_OVER("/gameover.wav",Volume.NOT_SO_LOUD, 1),
	WAVE_COMPLETED("/wave_completed.wav",Volume.LOUD, 1),
	INVADER_DESTROYED("/invader_destroyed.wav",Volume.LOUD, 3);

	private final Clip[] clips;

	private final int concurrency; // maximum number of instances of this sound that may be playing at the same time
	private int currentClipIdx;

	private SoundEffect(String soundFileName,Volume volume,int concurrency)
	{
		this.concurrency = concurrency;
		this.clips = new Clip[ concurrency ];
		try
		{
			final URL url = Main.class.getResource(soundFileName);
			if ( url == null ) {
				throw new RuntimeException("Failed to locate sound on classpath: '"+soundFileName+"'");
			}
			for ( int i = 0 ; i < concurrency ; i++ )
			{
				clips[i] = createClip( AudioSystem.getAudioInputStream(url) , volume );
			}
		}
		catch (final Exception e) {
			throw new RuntimeException(e);
		}
	}

	private Clip createClip(AudioInputStream stream,Volume volume) throws LineUnavailableException, IOException
	{
		final Clip clip = AudioSystem.getClip();
		clip.open( stream );

		final FloatControl masterGain = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);

		final float range = masterGain.getMaximum() - masterGain.getMinimum();
		final float value = masterGain.getMinimum() + range*volume.gainPercentage;
		masterGain.setValue( value );
		return clip;
	}

	public void play()
	{
		currentClipIdx = (currentClipIdx+1) % concurrency;
		final Clip clip = clips[ currentClipIdx ];
		if ( ! clip.isActive() ) {
			clip.setFramePosition(0);
			clip.start();
		}
	}
}


text:
<?php if ( ! defined( 'ABSPATH' ) ) exit;

final class NF_Admin_Menus_AllForms extends NF_Abstracts_Submenu
{
    public $parent_slug = 'ninja-forms';

    public $page_title = 'All Forms';

    public $menu_slug = 'admin.php?page=ninja-forms';

    public $priority = 1;

    public function __construct()
    {
        parent::__construct();
    }

    public function get_page_title()
    {
        return __( 'All Forms', 'ninja-forms' );
    }

    public function get_capability()
    {
        return apply_filters( 'ninja_forms_admin_all_forms_capabilities', $this->capability );
    }

    public function display()
    {
        // This section intentionally left blank.
    }

} // End Class NF_Admin_Settings


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>A Note on System Failure</title>
    <link rel="stylesheet" href="gettingStarted.css" type="text/css" />
    <meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
    <link rel="start" href="index.html" title="Getting Started with Berkeley DB Transaction Processing" />
    <link rel="up" href="introduction.html" title="Chapter 1. Introduction" />
    <link rel="prev" href="introduction.html" title="Chapter 1. Introduction" />
    <link rel="next" href="apireq.html" title="Application Requirements" />

Library Version 11.2.5.3

          A Note on System Failure

          Prev
          Chapter 1. Introduction
           Next

A Note on System Failure

            From time to time this manual mentions that transactions
            protect your data against 'system or application failure.' This
            is true up to a certain extent. However, not all failures are
            created equal and no data protection mechanism can protect you
            against every conceivable way a computing system can find to
            die.

            Generally, when this book talks about protection against
            failures, it means that transactions offer protection against
            the likeliest culprits for system and application crashes. So
            long as your data modifications have been committed to disk,
            those modifications should persist even if your application or
            OS subsequently fails.  And, even if the application or OS
            fails in the middle of a transaction commit (or abort), the
            data on disk should be either in a consistent state, or there
            should be enough data available to bring your databases into a
            consistent state (via a recovery procedure, for example). You
            may, however, lose whatever data you were committing at the
            time of the failure, but your databases will be otherwise
            unaffected.

Note

                    Be aware that many disks have a disk write cache and on
                    some systems it is enabled by default.  This means that
                    a transaction can have committed, and to your
                    application the data may appear to reside on disk, but
                    the data may in fact reside only in the write cache at
                    that time. This means that if the disk write cache is
                    enabled and there is no battery backup for it, data can
                    be lost after an OS crash even when maximum durability
                    mode is in use.  For maximum durability, disable the
                    disk write cache or use a disk write cache with a
                    battery backup.

            Of course, if your disk fails, then the transactional benefits described in this book
            are only as good as the backups you have taken.

                By spreading your data and log files across separate disks,
                you can minimize the risk of data loss due to a disk
                failure, but even in this case it is possible to conjure a
                scenario where even this protection is insufficient (a fire
                in the machine room, for example) and you must go to your
                backups for protection.

            Finally, by following the programming examples shown in this book, you can write your code so as to protect
            your data in the event that your code crashes. However, no programming API can protect you against logic
            failures in your own code; transactions cannot protect you from simply writing the wrong thing to your
            databases.

          Prev

            Up

           Next

          Chapter 1. Introduction

            Home

           Application Requirements


text:
<?php

namespace Sylius\Bundle\ResourceBundle\Controller;

use Hateoas\Configuration\Route;
use Hateoas\Representation\Factory\PagerfantaFactory;
use Pagerfanta\Pagerfanta;
use Sylius\Component\Resource\Repository\RepositoryInterface;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
final class ResourcesCollectionProvider implements ResourcesCollectionProviderInterface
{
    /**
     * @var ResourcesResolverInterface
     */
    private $resourcesResolver;

    /**
     * @var PagerfantaFactory
     */
    private $pagerfantaRepresentationFactory;

    /**
     * @param ResourcesResolverInterface $resourcesResolver
     * @param PagerfantaFactory $pagerfantaRepresentationFactory
     */
    public function __construct(ResourcesResolverInterface $resourcesResolver, PagerfantaFactory $pagerfantaRepresentationFactory)
    {
        $this->resourcesResolver = $resourcesResolver;
        $this->pagerfantaRepresentationFactory = $pagerfantaRepresentationFactory;
    }

    /**
     * {@inheritdoc}
     */
    public function get(RequestConfiguration $requestConfiguration, RepositoryInterface $repository)
    {
        $resources = $this->resourcesResolver->getResources($requestConfiguration, $repository);

        if ($resources instanceof Pagerfanta) {
            $request = $requestConfiguration->getRequest();
            $resources->setMaxPerPage($requestConfiguration->getPaginationMaxPerPage());
            $resources->setCurrentPage($request->query->get('page', 1));

            if (!$requestConfiguration->isHtmlRequest()) {
                $route = new Route($request->attributes->get('_route'), array_merge($request->attributes->get('_route_params'), $request->query->all()));

                return $this->pagerfantaRepresentationFactory->createRepresentation($resources, $route);
            }
        }

        return $resources;
    }
}


text:
<?php
/**
 * Base module for integration of Pomm projects with ZF2 applications
 *
 * @license MIT
 * @link    http://www.pomm-project.org/
 * @author  Martin Supiot <msupiot@jack.fr>
 */

namespace PommModule\Service;

use RuntimeException;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

/**
 * Return the Pomm options
 */
abstract class AbstractServiceFactory implements FactoryInterface
{
    /**
     * @var \Zend\Stdlib\AbstractOptions
     */
    protected $options;

    /**
     * @param ServiceLocatorInterface $sl
     * @param string $key
     * @param null|string $name
     * @return \Zend\Stdlib\AbstractOptions
     * @throws \RuntimeException
     */
    public function getPommOptions(ServiceLocatorInterface $sl)
    {
        $options = $sl->get('Config');
        $options = $options['pomm'];

        if (null === $options) {
            throw new RuntimeException('Options could not be found in "pomm".');
        }

        $pommOptionsClass = $this->getOptionsClass();

        return new $pommOptionsClass($options);
    }

    /**
     * @abstract
     * @return string
     */
    abstract public function getOptionsClass();
}


text:
<?php

declare(strict_types=1);

namespace Doctrine\ODM\MongoDB\Tests\Functional\Ticket;

use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Doctrine\ODM\MongoDB\Tests\BaseTest;
use function get_class;

class MODM117Test extends BaseTest
{
    public function testIssue()
    {
        $user             = new MODM117User();
        $user->first_name = 'jon';
        $user->last_name  = 'wage';
        $this->dm->persist($user);
        $this->dm->flush();

        $check = $this->dm->getDocumentCollection(get_class($user))->findOne();
        $this->assertEquals('jon', $check['first_name']);
        $this->assertEquals('wage', $check['last_name']);
    }
}

/** @ODM\Document */
class MODM117User
{
    /** @ODM\Id */
    public $id;

    /** @ODM\Field(type="string") */
    public $first_name;

    /** @ODM\Field(type="string", name="last_name") */
    protected $_last_name;

    public function __get($name)
    {
        return $this->{'_' . $name};
    }

    public function __set($name, $value)
    {
        $this->{'_' . $name} = $value;
    }
}


text:
var NAVTREE =
[
  [ "ConcurrentPriorityTaskRunner", "index.html", [
    [ "Packages", null, [
      [ "Packages", "namespaces.html", "namespaces" ],
      [ "Package Functions", "namespacemembers.html", [
        [ "All", "namespacemembers.html", null ],
        [ "Enumerations", "namespacemembers_enum.html", null ],
        [ "Enumerator", "namespacemembers_eval.html", null ]
      ] ]
    ] ],
    [ "Classes", null, [
      [ "Class List", "annotated.html", "annotated" ],
      [ "Class Index", "classes.html", null ],
      [ "Class Members", "functions.html", [
        [ "All", "functions.html", null ],
        [ "Functions", "functions_func.html", null ],
        [ "Properties", "functions_prop.html", null ],
        [ "Events", "functions_evnt.html", null ]
      ] ]
    ] ],
    [ "Files", null, [
      [ "File List", "files.html", "files" ]
    ] ]
  ] ]
];

var NAVTREEINDEX =
[
"_assembly_info_8cs.html"
];

var SYNCONMSG = 'click to disable panel synchronisation';
var SYNCOFFMSG = 'click to enable panel synchronisation';