text:
<?php
namespace Beehive\Msa\Protocol;

use Beehive\Kernel\ArrayObject;

/**
 * 协议包封装
 *
 * @author Ewenlaz
 */
class Packet extends ArrayObject
{
    const FLAG_RESPONSE = 1;
    const FLAG_EVENT = 2;
    public function pack()
    {
        return beehive_packet_pack($this->storage);
    }

    public function unpack($stream)
    {
        return $this->storage = beehive_packet_unpack($stream);
    }
}


text:
package org.apache.cassandra.service.pager;

import org.apache.cassandra.config.CFMetaData;
import org.apache.cassandra.db.*;
import org.apache.cassandra.db.filter.*;
import org.apache.cassandra.db.partitions.*;
import org.apache.cassandra.exceptions.RequestExecutionException;
import org.apache.cassandra.exceptions.RequestValidationException;
import org.apache.cassandra.service.ClientState;

/**
 * Static utility methods for paging.
 */
public class QueryPagers
{
    private QueryPagers() {};

    /**
     * Convenience method that count (live) cells/rows for a given slice of a row, but page underneath.
     */
//<<<<<<< HEAD
//    //只在org.apache.cassandra.thrift.CassandraServer.get_count调用
//    public static int countPaged(String keyspace,
//                                 String columnFamily,
//                                 ByteBuffer key,
//                                 SliceQueryFilter filter,
//=======
    public static int countPaged(CFMetaData metadata,
                                 DecoratedKey key,
                                 ColumnFilter columnFilter,
                                 ClusteringIndexFilter filter,
                                 DataLimits limits,
                                 ConsistencyLevel consistencyLevel,
                                 ClientState state,
                                 final int pageSize,
                                 int nowInSec,
                                 boolean isForThrift) throws RequestValidationException, RequestExecutionException
    {
        SinglePartitionReadCommand command = SinglePartitionReadCommand.create(isForThrift, metadata, nowInSec, columnFilter, RowFilter.NONE, limits, key, filter);
        final SinglePartitionPager pager = new SinglePartitionPager(command, null);

        int count = 0;
        while (!pager.isExhausted())
        {
            try (CountingPartitionIterator iter = new CountingPartitionIterator(pager.fetchPage(pageSize, consistencyLevel, state), limits, nowInSec))
            {
                PartitionIterators.consume(iter);
                count += iter.counter().counted();
            }
        }
        return count;
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Threading.Tasks;
using RabbitMQ.Client;
using RawRabbit.IntegrationTests.TestMessages;
using RawRabbit.Pipe;
using RawRabbit.Pipe.Middleware;
using Xunit;

namespace RawRabbit.IntegrationTests.Features
{
	public class GracefulShutdownTest : IntegrationTestBase
	{
		[Fact]
		public async Task Should_Cancel_Subscription_When_Shutdown_Is_Called()
		{
			var singleton = RawRabbitFactory.CreateTestClient();
			var instanceFactory = RawRabbitFactory.CreateTestInstanceFactory();
			var client = instanceFactory.Create();
			var processMs =50;
			var firstMsg = (new BasicMessage { Prop = "I'll get processed" });
			var secondMsg = (new BasicMessage { Prop = "I'll get stuck in the queue" });

			var firstTsc = new TaskCompletionSource<BasicMessage>();
			await client.SubscribeAsync<BasicMessage>(async message =>
			{
				firstTsc.TrySetResult(message);
				await Task.Delay(processMs);
			}, ctx => ctx
				.UseSubscribeConfiguration(cfg => cfg
					.FromDeclaredQueue(q => q
						.WithAutoDelete(false)
				)
			));

			await client.PublishAsync(firstMsg);
			await firstTsc.Task;
			var shutdownTask = instanceFactory.ShutdownAsync(TimeSpan.FromMilliseconds(processMs));
			await Task.Delay(TimeSpan.FromMilliseconds(10));
			await singleton.PublishAsync(secondMsg);
			await shutdownTask;

			var secondReceived = await singleton.GetAsync<BasicMessage>(get => get.WithAutoAck());
			await singleton.DeleteQueueAsync<BasicMessage>();
			await singleton.DeleteExchangeAsync<BasicMessage>();
			singleton.Dispose();

			Assert.Equal(firstMsg.Prop, firstTsc.Task.Result.Prop);
			Assert.Equal(secondMsg.Prop, secondReceived.Content.Prop);
		}
	}
}


text:
System.register([], function (exports, module) {
	'use strict';
	return {
		execute: function () {

			const x = exports('a', 1);

			const y = exports('b', 2);

			const z = exports('c', 3);

		}
	};
});


text:
var Promise = require('bluebird')
var seconds = require('juration').parse
var zlib = require('zlib')
var globber = require('glob-to-regexp')
var assign = require('deep-assign')
var copy = require('deep-copy')
var Resurrector = require('../lib/resurrect')

var DEFAULT_MONGO_URL = 'mongodb://127.0.0.1:27017/kev'
var DEFAULT_COLLECTION = 'kev'

var ID_KEY = "key"
var TAGS_KEY = "tags"
var DATA_FIELD_KEY = "value"
var TTL_KEY = "expiresAt"

var connections = {}
var dbs = []
var clients = []
var expired = (r) => r && r[TTL_KEY] && r[TTL_KEY] < new Date(Date.now())

var KevMongo = module.exports = function KevMongo (options) {
  if (!(this instanceof KevMongo)) return new KevMongo(options)

  var mongodb = require('mongodb')
  var MongoClient = mongodb.MongoClient
  Promise.promisifyAll(mongodb.Collection.prototype)
  Promise.promisifyAll(mongodb.Db.prototype)
  Promise.promisifyAll(mongodb.Cursor.prototype)
  Promise.promisifyAll(MongoClient)

  options = options || {}
  this.collection = options.collection || DEFAULT_COLLECTION
  if (options.ttl) options.ttl = seconds(String(options.ttl))

  if (options.db) {
    this.db = Promise.resolve()
      .then(() => options.db)
      .then((db) => {
        if (!db.createCollectionAsync) return Promise.promisifyAll(db)
        else return db
      })
  } else {
    var url = options.url || DEFAULT_MONGO_URL
    if (!connections[url]) {
      connections[url] = MongoClient.connectAsync(url, options.options || {})
    }
    this.db = connections[url]
    this.url = url
  }

  this.options = options
  var restore = options.restoreTypes || {}
  if (restore.pack && restore.unpack) {
    this.options.restore = restore
  } else if (restore.resurrect) {
    var resurrect = new Resurrector(restore.resurrect)
    this.options.restore = { pack: resurrect.stringify.bind(resurrect), unpack: resurrect.resurrect.bind(resurrect) }
  } else {
    this.options.restore = { pack: (v) => v, unpack: (v) => v }
  }

  this.storage = this.db.then((db) => {
    this.db = db
    return db.createCollectionAsync(this.collection)
      .catch((err) => {
        if (~err.message.indexOf('collection already exists')) return db.collectionAsync(this.collection)
        else throw err
      })
      .then((collection) => {
        if (!~dbs.indexOf(db)) {
          clients[dbs.length] = []
          dbs.push(db)
        }
        clients[dbs.indexOf(db)].push(collection)
        return collection
      })
  }).then((collection) => {
    if (!collection.createIndexAsync) collection = Promise.promisifyAll(collection)
    collection.createIndex({ [ID_KEY]: 1 }, { background: true })
    collection.createIndex({ [TAGS_KEY]: 1 })
    collection.createIndex({ [TTL_KEY]: 1 }, { background: true, expireAfterSeconds: 0 })
    return collection
  })
}

KevMongo.prototype.get = function get (keys, options, done) {
  var compress = merge_opt(options.compress, this.options.compress)
  var restore = merge_opt(options.restore, this.options.restore)
  this.storage.then((db) => db.findAsync({ [ID_KEY]: { $in: keys } }))
    .then((r) => Promise.fromCallback(r.toArray.bind(r)))
    .filter((v) => !expired(v))
    .reduce((out, v) => { out[v[ID_KEY]] = unpack(compress, restore)(v[DATA_FIELD_KEY]); return out }, {})
    .props()
    .tap((out) => { keys.forEach((k) => { out[k] = out[k] || null }) })
    .then((out) => done && done(null, out))
    .catch((err) => done && done(err))
}

KevMongo.prototype.put = function put (keys, options, done) {
  var compress = merge_opt(options.compress, this.options.compress)
  var restore = merge_opt(options.restore, this.options.restore)
  var ttl = options.ttl || options.ttl === 0 ? seconds(String(options.ttl)) : this.options.ttl
  this.storage.then((db) => {
    for (key in keys) {
      keys[key] = put(key, keys[key])
    }

    function put (key, value) {
      var query = { [ID_KEY]: key }
      var update = { [ID_KEY]: key }
      if (ttl) update[TTL_KEY] = new Date(Date.now() + ttl * 1000)
      return pack(compress, restore)(value)
        .then((v) => update[DATA_FIELD_KEY] = v)
        .then(() => db.findOneAndReplaceAsync(query, update, { upsert: true }))
        .then((r) => (r && r.value && !expired(r.value)) ? r.value[DATA_FIELD_KEY] : null)
        .then(unpack(compress, restore))
    }

    return Promise.props(keys)
      .then((v) => done && done(null, v))
      .catch((e) => done && done(e))
  })
}

KevMongo.prototype.del = function del (keys, done) {
  this.storage.then((db) => {
    return Promise.resolve(keys)
      .reduce((out, key) => {
        out[key] = db.findOneAndDeleteAsync({ [ID_KEY]: key })
          .then((r) => (r && r.value) ? r.value[DATA_FIELD_KEY] : null)
          .then(unpack(this.options.compress, this.options.restore))
        return out
      }, {})
      .props()
      .then((v) => done && done(null, v))
      .catch((e) => done && done(e))
  })
}

KevMongo.prototype.drop = function drop (pattern, done) {
  var re = globber(pattern)
  this.storage
    .then((db) => db.deleteManyAsync({ [ID_KEY]: { $regex: re } }))
    .then((r) => done && done(null, r.deletedCount))
    .catch((e) => done && done(e))
}

KevMongo.prototype.tag = function tag (key, tags, done) {
  var update = { $addToSet: { [TAGS_KEY]: { $each: tags } } }
  this.storage.then((db) => db.findOneAndUpdateAsync({ [ID_KEY]: key }, update))
    .then((r) => done && done())
    .catch((e) => done && done(e))
}

KevMongo.prototype.tags = function tags (keys, done) {
  this.storage.then((db) => db.findAsync({ [ID_KEY]: { $in: keys } }, { [TAGS_KEY]: 1, [ID_KEY]: 1, [TTL_KEY]: 1 }))
    .then((r) => Promise.fromCallback(r.toArray.bind(r)))
    .filter((v) => !expired(v))
    .reduce((out, v) => { out[v[ID_KEY]] = v[TAGS_KEY]; return out }, {})
    .then((out) => done && done(null, out))
    .catch((err) => done && done(err))
}

KevMongo.prototype.dropTag = function dropTag (tags, done) {
  this.storage
    .then((db) => db.deleteManyAsync({ [TAGS_KEY]: { $elemMatch: { $in: tags } } }))
    .then((r) => done && done(null, r.deletedCount))
    .catch((e) => done && done(e))
}

KevMongo.prototype.close = function (done) {
  this.storage.then((collection) => {
    var db = this.db
    var db_clients = clients[dbs.indexOf(db)]
    db_clients.splice(db_clients.indexOf(collection), 1)
    if (db_clients.length === 0) {
      var index = dbs.indexOf(db)
      dbs.splice(index, 1)
      clients.splice(index, 1)
      this.url && delete connections[this.url]
      db.close(done)
    } else {
      done && done()
    }
  })
}

function pack (compress, restore) {
  return Promise.promisify((value, done) => {
    if (!value) return setImmediate(() => done(null, null))

    var data = restore.pack(value)
    if (!compress) return setImmediate(() => done(null, data))

    var fn = compress.type === 'gzip' ? 'gzip' : 'deflate'
    var encoding = compress.encoding || 'base64'
    zlib[fn](JSON.stringify(data), compress, (err, buf) => {
      if (err) done(err)
      else done(null, buf.toString(encoding))
    })
  })
}

function unpack (compress, restore) {
  return Promise.promisify((value, done) => {
    if (!value) return setImmediate(() => done(null, null))
    if (!compress) return setImmediate(() => done(null, restore.unpack(value)))
    if (compress.raw) return setImmediate(() => done(null, value))
    var fn = compress.type === 'gzip' ? 'gunzip' : 'inflate'
    var encoding = compress.encoding || 'base64'
    zlib[fn](new Buffer(value, encoding), compress, (err, val) => {
      if (err) done(err)
      else done(null, restore.unpack(JSON.parse(val.toString())))
    })
  })
}

function merge_opt (target, source) {
  if (target === false) return false
  if (!target) return source
  if (!source || source === true) return target
  return assign({}, copy(target), copy(source))
}


text:
/********************************************************************
*
*	25. Mobile Service Provider
*
*       A mobile phone service provider has three different
*       subscription packages for its customers:
*
*       Package A: For $39.99 per month 450 minutes are provided.
*                  Additional minutes are $0.45 per minute.
*       Package B: For $59.99 per month 900 minutes are provided.
*                  Additional minutes are $0.40 per minute.
*       Package C: For $69.99 per month unlimited minutes provided.
*
*       Write a program that calculates a customer's monthly bill.
*       It should ask which package the customer has purchased and how
*       many minutes were used. It should then display the total amount
*       due.
*
*       Input Validation: Be sure the user only selects package A, B, or
*       C.
*
* 	Jesus Hilario Hernandez
* 	February 26, 2018
*
********************************************************************/
#include <iostream>
using namespace std;
int main()
{
    // Variables
    char menu_choice;

    // Display menu
    cout << "\nPackage A: For $39.99 per month 450 minutes are provided." << endl;
    cout << "           Additional minutes are $0.45 per minute." << endl;
    cout << "Package B: For $59.99 per month 900 minutes are provided." << endl;
    cout << "           Additional minutes are $0.40 per minute." << endl;
    cout << "Package C: For $69.99 per month unlimited minutes provided.\n" << endl;

    // Ask for package customer purchased
    cout << "Choose package: ";
    cin >> menu_choice;
    cout << endl;

    // Validate menu_choice
    switch (menu_choice)
    {
        // Variables
        int mins_used;
        float total_charges;

        case 'a':
        case 'A':
        case 'B':
        case 'b':
        case 'c':
        case 'C':
            // Ask how many minutes used
            cout << "How many minutes used? ";
            cin >> mins_used;
            cout << endl;

            // Validate mins_used
            if (mins_used < 0)
            {
                cout << "We're sorry. Minutes must be greater than 0.\n";
                cout << "Rerun the program and try again." << endl;
            }
            else
            {
                // Display total amount due
                cout << "Total monthly charges: ";

                // Calculates customer's monthly bill (choice A)
                if (menu_choice == 'a' || menu_choice == 'A')
                    total_charges = mins_used > 450 ? 39.99 + ((mins_used - 450) * .45) : 39.99;

                // Calculates customer's monthly bill (choice B)
                else if (menu_choice == 'b' || menu_choice == 'B')
                    total_charges = mins_used > 900 ? 59.99 + ((mins_used - 900) * .40) : 59.99;

                // Calculates customer's monthly bill (choice C)
                else if (menu_choice == 'c' || menu_choice == 'C')
                    total_charges = 69.99;

                // Display total charges
                cout << total_charges << endl;
            }
            break;

        default:
            // Display error.
            cout << "We're sorry. Menu choice must be A, B, or C.\n";
            cout << "Rerun the program and try again." << endl;
    }

    cout << endl;

    // Terminate program
    return 0;
}


text:
extern crate xvmtest;

use xvmtest::dbgprint;

#[no_mangle]
pub extern "C" fn test_main() {
    dbgprintln!("This is a dummy test payload");
}


text:
<?php

/**
 * Description of MinifiedCssTest
 *
 * @author Bryan
 */
class MinifiedJsTest extends AssetCompilerTest
{
    public function setUp()
    {
        parent::setUp();
        $this->AssetCompiler->config()->minify(true);
    }

    public function test_get_single_minified_js_file()
    {
        $actual = $this->AssetCompiler->getScript('test1.js');
        $fileTime = filemtime(__DIR__ . '/testresources/js/test1.js');
        $expected = '<script src="/js/compiled/test1.min.js?v=' . $fileTime . '" ></script>';
        $this->assertEquals($expected, $actual);
    }

    public function test_get_single_minified_js_file_contents()
    {
        $fileName = 'test1.js';
        $minifiedName = 'test1.min.js';
        $minifiedPath = $this->rootPath . 'js/' . $this->AssetCompiler->config()->compiledFolder() . '/' . $minifiedName;
        $this->AssetCompiler->getScript($fileName);

        $this->assertFileExists($minifiedPath);

        $actual = file_get_contents($minifiedPath);
        $expected = 'var message="Hello World"';

        $this->assertEquals($expected, $actual);
    }

    public function test_get_single_minified_js_file_contents_not_minified_in_debug_mode()
    {
        $this->AssetCompiler->config()->debug(true);

        $actual = $this->AssetCompiler->getScript('test1.js');
        $fileTime = filemtime(__DIR__ . '/testresources/js/test1.js');
        $expected = '<script src="/js/test1.js?v=' . $fileTime . '" ></script>';
        $this->assertEquals($expected, $actual);
    }

    public function test_get_multi_minified_js_file()
    {
        $compiledName = 'compiledJs.js';
        $filePath = __DIR__ . '/testresources/js/test1.js';
        touch($filePath);
        $fileTime = filemtime($filePath);

        $actual = $this->AssetCompiler->getScriptsMulti(['test1.js', 'test2.js'], $compiledName);
        $expected = '<script src="/js/' . $this->AssetCompiler->config()->compiledFolder() . '/' . $compiledName . '?v=' . $fileTime . '" ></script>';

        $this->assertFileExists($this->rootPath . 'js/' . $this->AssetCompiler->config()->compiledFolder() . '/' . $compiledName);
        $this->assertEquals($expected, $actual);
    }

    public function test_get_multi_minified_js_file_contents()
    {
        $compiledName = 'compiledJs.js';
        $filePath = $this->rootPath . 'js/' . $this->AssetCompiler->config()->compiledFolder() . '/' . $compiledName;
        $this->AssetCompiler->getScriptsMulti(['test1.js', 'test2.js'], $compiledName);

        $this->assertFileExists($filePath);

        $actual = file_get_contents($filePath);
        $expected = 'var message="Hello World";function doSomething(){return 2+2}';

        $this->assertEquals($expected, $actual);
    }

    public function test_get_multi_minified_js_file_contents_not_minified_in_debug_mode()
    {
        $compiledName = 'compiledJs.js';
        $files = ['test1.js', 'test2.js'];
        $this->AssetCompiler->config()->debug(true);
        $actual = $this->AssetCompiler->getScriptsMulti($files, $compiledName);

        $expected = '';
        foreach ($files as $file) {
            $fileTime = filemtime(__DIR__ . '/testresources/js/' . $file);
            $expected .= '<script src="/js/' . $file . '?v=' . $fileTime . '" ></script>' . "\n";
        }

        $this->assertEquals($expected, $actual);
    }
}


text:
<?php
	// check if user is authorized with Tumblr
	function check_tumblr_oauth_access($db) {
		if($oauth = $db->get_row("SELECT oauth_username,oauth_token,oauth_secret FROM users_oauth WHERE uo_usr_id = ".$db->escape($_SESSION['usr']['id'])." AND oauth_provider = 'tumblr'")) {
			$tumblroauth = new TumblrOAuth(TUMBLR_OAUTH_KEY, TUMBLR_OAUTH_SECRET, $oauth->oauth_token, $oauth->oauth_secret);
			$user = $tumblroauth->get('http://api.tumblr.com/v2/user/info');
			if($user->response->user->name == $oauth->oauth_username){
				return true;
			} else {
				return false;
			}
		}
	}


text:
require 'rubygems'
require 'ruby-debug'
require 'active_support'
require 'active_record'
require 'action_controller'
require 'action_view'
require 'shoulda'

require File.join(File.dirname(__FILE__), 'shoulda_macros', 'generator_macros')
require File.join(File.dirname(__FILE__), 'stolen_from_railties')

unless defined?(RAILS_DEFAULT_LOGGER)
  @test_log = File.join(RAILS_ROOT, 'test.log')
  RAILS_DEFAULT_LOGGER = Logger.new(@test_log)
end

Rails::Generator::Base.prepend_sources Rails::Generator::PathSource.new(:mongo_mapper_generators, File.join(File.dirname(__FILE__), "..", "rails_generators"))

class GeneratorTestCase
  def run_generator(name, params=[])
    silence_generator do
      build_generator(name, params).command(:create).invoke!
    end
  end
end


text: export { Row, Col } from './components';


text:
package com.communote.plugins.core.registries;

import org.apache.felix.ipojo.annotations.Bind;
import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Instantiate;
import org.apache.felix.ipojo.annotations.Unbind;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.communote.server.web.WebServiceLocator;
import com.communote.server.web.fe.widgets.extension.WidgetExtension;
import com.communote.server.web.fe.widgets.extension.WidgetExtensionManagement;
import com.communote.server.web.fe.widgets.extension.WidgetExtensionManagementRepository;

/**
 * Registry to automatically add widget extensions.
 *
 * @author Communote GmbH - http://www.communote.com/
 */
@Component
@Instantiate
public class WidgetExtensionRegistry {
    private static final Logger LOGGER = LoggerFactory.getLogger(WidgetExtensionRegistry.class);
    private WidgetExtensionManagementRepository extensionRepository;

    /**
     * @return the lazily initialized repository
     */
    private WidgetExtensionManagementRepository getExtensionRepository() {
        if (extensionRepository == null) {
            extensionRepository = WebServiceLocator.instance()
                    .getWidgetExtensionManagementRepository();
        }
        return extensionRepository;
    }

    /**
     * Add a widget extension to a registered management. The management to use is defined by the
     * extension.
     *
     * @param <E>
     *            the type of the widget extension
     * @param <M>
     *            the type of the management that handles the widget extension type
     * @param extension
     *            the extension to add
     */
    @Bind(id = "registerWidgetExtension", optional = true, aggregate = true)
    public <E extends WidgetExtension<E, M>, M extends WidgetExtensionManagement<E, M>> void registerExtension(
            E extension) {
        if (!getExtensionRepository().addExtension(extension)) {
            LOGGER.info("Adding widget extension {} failed", extension.getClass().getName());
        } else {
            LOGGER.debug("Added widget extension {}", extension.getClass().getName());
        }
    }

    /**
     * Remove a previously registered extension from its management.
     *
     * @param <E>
     *            the type of the widget extension
     * @param <M>
     *            the type of the management that handles the widget extension type
     * @param extension
     *            the extension to remove
     */
    @Unbind(id = "registerWidgetExtension", optional = true, aggregate = true)
    public <E extends WidgetExtension<E, M>, M extends WidgetExtensionManagement<E, M>> void removeExtension(
            E extension) {
        getExtensionRepository().removeExtension(extension);
        LOGGER.debug("Removed widget extension {}", extension.getClass().getName());
    }
}