text:
#ifndef __SIRIKATA_OH_STORAGE_SQLITE_HPP__
#define __SIRIKATA_OH_STORAGE_SQLITE_HPP__

#include <sirikata/oh/Storage.hpp>
#include <sirikata/sqlite/SQLite.hpp>
#include <sirikata/core/queue/ThreadSafeQueueWithNotification.hpp>

namespace Sirikata {
namespace OH {

class FileStorageEvent;

class SQLiteStorage : public Storage
{
public:
    SQLiteStorage(ObjectHostContext* ctx, const String& dbpath, const Duration& lease_duration);
    ~SQLiteStorage();

    virtual void start();
    virtual void stop();

    virtual void leaseBucket(const Bucket& bucket);
    virtual void releaseBucket(const Bucket& bucket);

    virtual void beginTransaction(const Bucket& bucket);

    virtual void commitTransaction(const Bucket& bucket, const CommitCallback& cb = 0, const String& timestamp="current");
    virtual bool erase(const Bucket& bucket, const Key& key, const CommitCallback& cb = 0, const String& timestamp="current");
    virtual bool write(const Bucket& bucket, const Key& key, const String& value, const CommitCallback& cb = 0, const String& timestamp="current");
    virtual bool read(const Bucket& bucket, const Key& key, const CommitCallback& cb = 0, const String& timestamp="current");
    virtual bool compare(const Bucket& bucket, const Key& key, const String& value, const CommitCallback& cb = 0, const String& timestamp="current");
    virtual bool rangeRead(const Bucket& bucket, const Key& start, const Key& finish, const CommitCallback& cb = 0, const String& timestamp="current");
    virtual bool rangeErase(const Bucket& bucket, const Key& start, const Key& finish, const CommitCallback& cb = 0, const String& timestamp="current");
    virtual bool count(const Bucket& bucket, const Key& start, const Key& finish, const CountCallback& cb = 0, const String& timestamp="current");

private:
    // StorageActions are individual actions to take, i.e. read, write,
    // erase. We queue them up in a list and eventually fire them off in a
    // transaction.
    struct StorageAction {
        enum Type {
            Read,
            ReadRange,
            Compare,
            Write,
            Erase,
            EraseRange,
            Error
        };

        StorageAction();
        StorageAction(const StorageAction& rhs);
        ~StorageAction();

        StorageAction& operator=(const StorageAction& rhs);

        // Executes this action. Assumes the owning SQLiteStorage has setup the transaction.
        Result execute(SQLiteDBPtr db, const Bucket& bucket, ReadSet* rs);

        // Executes this action, retrying the given number of times if there's a
        // temporary failure to lock the database. Assumes the owning
        // SQLiteStorage has setup the transaction.
        Result executeWithRetry(SQLiteDBPtr db, const Bucket& bucket, ReadSet* rs, int32 retries, const Duration& retry_wait);

        // Bucket is implicit, passed into execute
        Type type;
        Key key;
        Key keyEnd; // Only relevant for *Range and Count
        String* value;
    };

    typedef std::vector<StorageAction> Transaction;
    typedef std::tr1::unordered_map<Bucket, Transaction*, Bucket::Hasher> BucketTransactions;

    // We keep a queue of transactions and trigger handlers, which can process
    // more than one at a time, on the storage IOService
    struct TransactionData {
        TransactionData()
         : bucket(), trans(NULL), cb()
        {}
        TransactionData(const Bucket& b, Transaction* t, CommitCallback c)
         : bucket(b), trans(t), cb(c)
        {}

        Bucket bucket;
        Transaction* trans;
        CommitCallback cb;
    };
    typedef ThreadSafeQueueWithNotification<TransactionData> TransactionQueue;

    // Helper that checks and logs errors, then returns bool indicating
    // success/failure
    static bool checkSQLiteError(SQLiteDBPtr db, int rc, const String& msg);

    // Initializes the database. This is separate from the main initialization
    // function because we need to make sure it executes in the right thread so
    // all sqlite requests on the db ptr come from the same thread.
    void initDB();

    // Gets the current transaction or creates one. Also can return whether the
    // transaction was just created, e.g. to tell whether an operation is an
    // implicit transaction.
    Transaction* getTransaction(const Bucket& bucket, bool* is_new = NULL);

    // Indirection to get on mIOService
    void postProcessTransactions();
    // Process transactions. Runs until queue is empty and is triggered anytime
    // the queue goes from empty to non-empty.
    void processTransactions();

    // Tries to execute a commit *assuming it is within a SQL
    // transaction*. Returns whether it was successful, allowing for
    // rollback/retrying.
    Result executeCommit(const Bucket& bucket, Transaction* trans, CommitCallback cb, ReadSet** read_set_out);

    void executeCount(const String value_count, const Key& start, const Key& finish, CountCallback cb);

    // A few helper methods that wrap sql operations.
    bool sqlBeginTransaction();
    bool sqlCommit();
    bool sqlRollback();

    // Helpers for leases:
    // Get the current lease string, which includes our client ID and
    // an expiration time based on the current time
    String getLeaseString();
    // Parse a lease string read from the DB into the client ID
    // (owner) and expiration time.
    void parseLeaseString(const String& ls, String* client_out, Time* expiration_out);

    // Acquire a lease (or update if it's already valid) for the given
    // bucket. This is part of a transaction -- the first part to
    // ensure the transaction is valid
    Result acquireLease(const Bucket& bucket);
    // Renew a lease that we already have. Verifies we still hold the
    // lease, then renews it. This is an entire transaction.
    void renewLease(const Bucket& bucket);
    // Release the lease if we own it.
    void releaseLease(const Bucket& bucket);

    // Process renewals at front of queue that need updating.
    void processRenewals();

    ObjectHostContext* mContext;
    BucketTransactions mTransactions;
    String mDBFilename;
    SQLiteDBPtr mDB;

    // FIXME because we don't have proper multithreaded support in cppoh, we
    // need to allocate our own thread dedicated to IO
    Network::IOService* mIOService;
    Network::IOWork* mWork;
    Thread* mThread;

    // A unique client ID for leases. These should not include '-' as
    // those are used to separate the client ID and timestamp
    const String mSQLClientID;
    const Duration mLeaseDuration;

    TransactionQueue mTransactionQueue;
    // Maximum transactions to combine into a single transaction in the
    // underlying database. TODO(ewencp) this should probably be dynamic, should
    // increase/decrease based on success/failure and avoid latency getting too
    // hight. Right now we just have a reasonable, but small, number.
    uint32 mMaxCoalescedTransactions;

    // Amount of time to sleep between retries. Shouldn't be too big or you can
    // back up all storage, but should be long enough that transient errors such
    // as waiting for other threads to unlock are likely to be resolved.
    const Duration mRetrySleepDuration;
    // Number of times to retry a normal operation (user transaction requests)
    // and lease operations (acquiring/releasing locks). The latter should be
    // more aggressive about retrying, whereas the former can rely on
    // application-level retries when transient errors are detected.
    const int32 mNormalOpRetries;
    const int32 mLeaseOpRetries;

    struct BucketRenewTimeout {
        BucketRenewTimeout(const Bucket& _b, Time _t)
         : bucket(_b), t(_t)
        {}
        const Bucket bucket;
        const Time t;
    };
    std::queue<BucketRenewTimeout> mRenewTimes;
    Network::IOTimerPtr mRenewTimer;
};

}//end namespace OH
}//end namespace Sirikata

#endif //__SIRIKATA_OH_STORAGE_SQLITE_HPP__


text:
@interface OVCModelResponseSerializerTests : XCTestCase

@property (strong, nonatomic) OVCModelResponseSerializer *serializer;

@end

@implementation OVCModelResponseSerializerTests

- (void)setUp {
    [super setUp];

    NSDictionary *modelClassesByPath = @{
        @"test": [OVCTestModel class],
        @"alternative": [OVCAlternativeModel class],
        @"paginated": [OVCAlternativeModel class]
    };

    OVCURLMatcher *matcher = [[OVCURLMatcher alloc] initWithBasePath:nil
                                                  modelClassesByPath:modelClassesByPath];

#if OVERCOAT_SUPPORT_COREDATA
    self.serializer = [OVCModelResponseSerializer serializerWithURLMatcher:matcher
                                                   responseClassURLMatcher:nil
                                                      managedObjectContext:nil
                                                             responseClass:[OVCResponse class]
                                                           errorModelClass:[OVCErrorModel class]];
#else
    self.serializer = [OVCModelResponseSerializer serializerWithURLMatcher:matcher
                                                   responseClassURLMatcher:nil
                                                             responseClass:[OVCResponse class]
                                                           errorModelClass:[OVCErrorModel class]];
#endif
}

- (void)tearDown {
    self.serializer = nil;

    [super tearDown];
}

#if !OVERCOAT_SUPPORT_COREDATA
- (void)testSuccessResponseSerialization {
    NSData *data = [NSJSONSerialization dataWithJSONObject:@{
                        @"name": @"Iron Man",
                        @"realName": @"Anthony Stark"
                    } options:0 error:NULL];
    NSURLResponse *URLResponse = [[NSHTTPURLResponse alloc] initWithURL:[NSURL URLWithString:@"http://example.com/test"]
                                                             statusCode:200
                                                            HTTPVersion:@"1.1"
                                                           headerFields:@{@"Content-Type": @"text/json"}];
    OVCResponse *response = [self.serializer responseObjectForResponse:URLResponse data:data error:NULL];

    XCTAssertTrue([response isKindOfClass:[OVCResponse class]], @"should return a OVCResponse instance");
    XCTAssertTrue([response.result isKindOfClass:[OVCTestModel class]], @"should return a OVCTestModel result");
}

- (void)testErrorResponseSerialization {
    NSData *data = [NSJSONSerialization dataWithJSONObject:@{
                        @"status": @"failed",
                        @"code": @97,
                        @"message": @"Missing signature"
                    } options:0 error:NULL];
    NSURLResponse *URLResponse = [[NSHTTPURLResponse alloc] initWithURL:[NSURL URLWithString:@"http://example.com/test"]
                                                             statusCode:401
                                                            HTTPVersion:@"1.1"
                                                           headerFields:@{@"Content-Type": @"text/json"}];
    OVCResponse *response = [self.serializer responseObjectForResponse:URLResponse data:data error:NULL];

    XCTAssertTrue([response isKindOfClass:[OVCResponse class]], @"should return a OVCResponse instance");
    XCTAssertTrue([response.result isKindOfClass:[OVCErrorModel class]], @"should return a OVCErrorModel result");
}

#else
- (void)testManagedObjectModelSerialization {
    // Setup the Core Data stack

    NSBundle *bundle = [NSBundle bundleForClass:[self class]];
    NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:@[bundle]];
    OVCManagedStore *store = [OVCManagedStore managedStoreWithModel:model];

    NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [context setPersistentStoreCoordinator:store.persistentStoreCoordinator];

    // Setup the serializer

    OVCURLMatcher *matcher = self.serializer.URLMatcher;
    self.serializer = [OVCModelResponseSerializer serializerWithURLMatcher:matcher
                                                   responseClassURLMatcher:nil
                                                      managedObjectContext:context
                                                             responseClass:[OVCResponse class]
                                                           errorModelClass:[OVCErrorModel class]];

    // Serialize successful response

    NSData *data = [NSJSONSerialization dataWithJSONObject:@{
                        @"offset": @0,
                        @"limit": @100,
                        @"objects": @[
                            @{
                                @"name": @"Iron Man",
                                @"realName": @"Anthony Stark"
                            },
                            @{
                                @"name": @"Batman",
                                @"realName": @"Bruce Wayne"
                            }
                        ]
                    } options:0 error:NULL];

    NSURLResponse *URLResponse = [[NSHTTPURLResponse alloc] initWithURL:[NSURL URLWithString:@"http://example.com/paginated"]
                                                             statusCode:200
                                                            HTTPVersion:@"1.1"
                                                           headerFields:@{@"Content-Type": @"text/json"}];

    OVCResponse *response = [self.serializer responseObjectForResponse:URLResponse data:data error:NULL];

    XCTAssertTrue([response isKindOfClass:[OVCResponse class]], @"should return a OVCResponse instance");

    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"TestModel"];
    NSArray *objects = [context executeFetchRequest:fetchRequest error:NULL];

    XCTAssertEqual(2U, [objects count], @"should return two objects");

    // Serialize error response (should not be persisted)

    id observer = [[NSNotificationCenter defaultCenter] addObserverForName:NSManagedObjectContextObjectsDidChangeNotification
                                                                    object:context
                                                                     queue:nil
                                                                usingBlock:^(NSNotification *note) {
                                                                    XCTFail(@"should ignore error responses");
                                                                }];

    data = [NSJSONSerialization dataWithJSONObject:@{
                @"status": @"failed",
                @"code": @97,
                @"message": @"Missing signature"
            } options:0 error:NULL];
    URLResponse = [[NSHTTPURLResponse alloc] initWithURL:[NSURL URLWithString:@"http://example.com/test"]
                                              statusCode:401
                                             HTTPVersion:@"1.1"
                                            headerFields:@{@"Content-Type": @"text/json"}];
    response = [self.serializer responseObjectForResponse:URLResponse data:data error:NULL];

    [[NSNotificationCenter defaultCenter] removeObserver:observer];
}
#endif

@end

redpajama_set_name: RedPajamaGithub


text:
  {% include social-icons.html %}

{{ site.title }} | {{ site.description }}


text:
import core from 'core-js';

var metadataStoreLookup = new Map(),
    locateMetadataElsewhere;

/**
* Stores metadata and provides helpers for searching and adding to it.
*
* @class MetadataStore
*/
export class MetadataStore {
  constructor(owner){
    this._owner = owner;
    this._first = null;
    this._second = null;
    this._third = null;
    this._rest = null;
  }

  /**
  * Searches metadata and returns the first instance of a particular type.
  *
  * @method first
  * @param {Function} type The metadata type to look for.
  * @param {Boolean} searchPrototype Indicates whether or not to search the inheritance hierarchy for metadata.
  * @return {Object} Returns an instance of the specified metadata type if found; otherwise null.
  */
  first(type, searchPrototype){
    var potential, i, ii, rest;

    if(this._first instanceof type){
      return this._first;
    }

    if(this._second instanceof type){
      return this._second;
    }

    if(this._third instanceof type){
      return this._third;
    }

    rest = this._rest;
    if(rest !== null){
      for(i = 0, ii = rest.length; i < ii; ++i){
        potential = rest[i];
        if(potential instanceof type){
          return potential;
        }
      }
    }

    if(searchPrototype && this._owner !== undefined){
      return Metadata.on(Object.getPrototypeOf(this._owner)).first(type, searchPrototype);
    }

    return null;
  }

  /**
  * Searches metadata and returns true if a particular type of metadata is present.
  *
  * @method has
  * @param {Function} type The metadata type to look for.
  * @param {Boolean} searchPrototype Indicates whether or not to search the inheritance hierarchy for metadata.
  * @return {Object} Returns true if found; false null.
  */
  has(type, searchPrototype){
    return this.first(type, searchPrototype) !== null;
  }

  /**
  * Searches metadata for all instances of a particular type.
  *
  * @method all
  * @param {Function} type The metadata type to look for.
  * @param {Boolean} searchPrototype Indicates whether or not to search the inheritance hierarchy for metadata.
  * @return {Array} Returns an array of the specified metadata type.
  */
  all(type, searchPrototype){
    var potential, i, ii, rest, found = [];

    if(this._first instanceof type){
      found.push(this._first);
    }

    if(this._second instanceof type){
      found.push(this._second);
    }

    if(this._third instanceof type){
      found.push(this._third);
    }

    rest = this._rest;
    if(rest !== null){
      for(i = 0, ii = rest.length; i < ii; ++i){
        potential = rest[i];
        if(potential instanceof type){
          found.push(potential);
        }
      }
    }

    if(searchPrototype && this._owner !== undefined){
      found = found.concat(Metadata.on(Object.getPrototypeOf(this._owner)).all(type, searchPrototype));
    }

    return found;
  }

  /**
  * Searches metadata and returns the first instance of a particular type or creates and adds one if none is found.
  *
  * @method first
  * @param {Function} type The metadata type to look for.
  * @param {Boolean} searchPrototype Indicates whether or not to search the inheritance hierarchy for metadata.
  * @return {Object} Returns an instance of the specified metadata type.
  */
  firstOrAdd(type, searchPrototype){
    var existing = this.first(type, searchPrototype);
    if(existing === null){
      existing = new type();
      this.add(existing);
    }
    return existing;
  }

  /**
  * Adds metadata.
  *
  * @method add
  * @param {Object} instance The metadata instance to add.
  */
  add(instance){
    if(this._first === null){
      this._first = instance;
      return;
    }

    if(this._second === null){
      this._second = instance;
      return;
    }

    if(this._third === null){
      this._third = instance;
      return;
    }

    if(this._rest === null){
      this._rest = [];
    }

    this._rest.push(instance);

    return this;
  }
}

/**
* Provides access to metadata.
*
* @class Metadata
* @static
*/
export var Metadata = {
  none: Object.freeze(new MetadataStore()),
  /**
  * Locates the metadata on the owner.
  *
  * @method on
  * @param {Function} owner The owner of the metadata.
  * @return {MetadataStorage} Returns the stored metadata.
  */
  on(owner){
    var metadata;

    if(!owner){
      return this.none;
    }

    metadata = metadataStoreLookup.get(owner);
    if(metadata !== undefined && metadata._owner === owner){
      return metadata;
    }

    metadata = new MetadataStore(owner);
    metadataStoreLookup.set(owner, metadata);

    if(owner.hasOwnProperty('decorators')){
      var applicator;

      if(typeof owner.decorators === 'function'){
        applicator = owner.decorators();
      }else{
        applicator = owner.decorators;
      }

      if(typeof applicator._decorate === 'function'){
        applicator._decorate(owner);
      }else{
        throw new Error('The return value of your decorator\'s method was not valid.');
      }
    }else if(locateMetadataElsewhere !== undefined){
      locateMetadataElsewhere(owner, metadata);
    }

    return metadata;
  },
  configure: {
    /**
    * Adds a function capable of locating metadata.
    *
    * @method locator
    * @param {Function} locator Configures a function which searches for metadata.
    */
    locator(loc){
      if(locateMetadataElsewhere === undefined){
        locateMetadataElsewhere = loc;
        return;
      }

      var original = locateMetadataElsewhere;
      locateMetadataElsewhere = function(fn, meta){
        original(fn, meta);
        loc(fn, meta);
      };
    }
  }
}


text:
const companyProfileSelector = state => state.companyProfile.companyProfile
const isFetchingSelector = state => state.companyProfile.isFetching

export { companyProfileSelector, isFetchingSelector }


text:
#ifndef COMBINATIONS_H_
#define COMBINATIONS_H_

#include <vector>
#include <forward_list>
#include <algorithm>
#include <memory>
#include "dither_types.h"

namespace dither {

inline void product(
    std::forward_list<dtest_case>& rvvi,           // final result
    dtest_case& rvi,                               // current result
    std::vector<dtest_case>::const_iterator me,    // current input
    std::vector<dtest_case>::const_iterator end);  // final input

inline void product2(
    std::forward_list<std::vector<param>>& rvvi,           // final result
    std::vector<param>& rvi,                               // current result
    std::vector<std::vector<param>>::const_iterator me,    // current input
    std::vector<std::vector<param>>::const_iterator end);  // final input

inline void gcombinations_(const std::vector<int>&, std::vector<int>&,
                           std::forward_list<std::vector<int>>&);

inline void combinations(const int, const std::vector<int>&,
                         std::forward_list<std::vector<int>>&);

inline void product2(
    std::forward_list<std::vector<param>>& rvvi,          // final result
    std::vector<param>& rvi,                              // current result
    std::vector<std::vector<param>>::const_iterator me,   // current input
    std::vector<std::vector<param>>::const_iterator end)  // final input
{
  if (me == end) {
    // terminal condition of the recursion. We no longer have
    // any input vectors to manipulate. Add the current result (rvi)
    // to the total set of results (rvvvi).
    rvvi.push_front(rvi);
    return;
  }

  // need an easy name for my vector-of-ints
  const std::vector<param>& mevi = *me;
  for (std::vector<param>::const_iterator it = mevi.begin(); it != mevi.end();
       it++) {
    // final rvi will look like "a, b, c, ME, d, e, f"
    // At the moment, rvi already has "a, b, c"
    rvi.push_back(*it);                // add ME
    product2(rvvi, rvi, me + 1, end);  // add "d, e, f"
    rvi.pop_back();                    // clean ME off for next round
  }
}

void combinations(const int n, const std::vector<int>& input,
                  std::forward_list<std::vector<int>>& output) {
  std::vector<int> scratch(n);

  if (n <= input.size()) {
    for (int i = 0; i < n; i++) {
      scratch[i] = i;
    }

    gcombinations_(input, scratch, output);
    while (1) {
      int i;
      for (i = n - 1; (i >= 0) && (scratch[i] == (input.size() - n + i)); i--)
        ;

      if (i < 0) {
        break;
      } else {
        scratch[i]++;
        for (++i; i < n; i++) {
          scratch[i] = scratch[i - 1] + 1;
        }
        gcombinations_(input, scratch, output);
      }
    }
  }
}

inline void gcombinations_(const std::vector<int>& input,
                           std::vector<int>& scratch,
                           std::forward_list<std::vector<int>>& output) {
  std::vector<int> result(scratch.size());
  for (std::size_t i = 0; i < result.size(); i++) {
    result[i] = input[scratch[i]];
  }
  output.push_front(result);
}

inline void product(
    std::forward_list<dtest_case>& rvvi,          // final result
    dtest_case& rvi,                              // current result
    std::vector<dtest_case>::const_iterator me,   // current input
    std::vector<dtest_case>::const_iterator end)  // final input
{
  if (me == end) {
    // terminal condition of the recursion. We no longer have
    // any input vectors to manipulate. Add the current result (rvi)
    // to the total set of results (rvvvi).
    rvvi.push_front(rvi);
    return;
  }

  // need an easy name for my vector-of-ints
  const dtest_case& mevi = *me;
  for (dtest_case::const_iterator it = mevi.begin(); it != mevi.end(); it++) {
    // final rvi will look like "a, b, c, ME, d, e, f"
    // At the moment, rvi already has "a, b, c"
    rvi.push_back(*it);               // add ME
    product(rvvi, rvi, me + 1, end);  // add "d, e, f"
    rvi.pop_back();                   // clean ME off for next round
  }
}

inline void product3(std::forward_list<dtest_case>& results,
                     std::vector<dtest_case>::const_iterator begin,
                     std::vector<dtest_case>::const_iterator end) {
  dtest_case ranges;
  for (auto it = begin; it != end; ++it) {
    const dval tmp = (*it).size() - 1;
    ranges.push_back(tmp);
  }

  dtest_case scratch(ranges.size(), 0);

  const std::size_t max = ranges.size() - 1;
  for (std::size_t i = max;;) {
    if (i == max) {
      for (dval val = 0; val <= ranges[i]; val++) {
        results.push_front(scratch);
        scratch[i]++;
      }
      scratch[i] = 0;
      i--;
    } else if (i == 0 && scratch[i] >= ranges[i]) {
      return;
    } else if (scratch[i] < ranges[i]) {
      scratch[i]++;
      i++;
    } else {
      scratch[i] = -1;
      i--;
    }
  }
}

inline std::size_t product4(std::forward_list<param**>& results,
                            param** param_cache,
                            std::vector<std::vector<param>*>& param_matrix) {
  std::vector<int> ranges;
  std::unique_ptr<param* []> scratch_ptr(new param*[param_matrix.size()]);
  auto scratch = scratch_ptr.get();
  for (std::size_t j = 0; j < param_matrix.size(); j++) {
    ranges.push_back(param_matrix[j]->size() - 1);
    scratch[j] = &(*param_matrix[j])[0];
  }
  std::vector<int> indexes(ranges.size(), 0);

  const std::size_t max = ranges.size() - 1;
  const std::size_t length = ranges.size();
  std::size_t j = 0;
  for (std::size_t i = max;;) {
    if (i == max) {
      for (std::size_t val = 0; val <= ranges[i]; val++) {
        scratch[i] = &(*param_matrix[i])[indexes[i]];
        std::copy(scratch, scratch + length, param_cache);
        results.push_front(param_cache);
        param_cache += length;
        indexes[i]++;
        j++;
      }
      indexes[i] = 0;
      i--;
    } else if (i == 0 && indexes[i] >= ranges[i]) {
      return j;
    } else if (indexes[i] < ranges[i]) {
      indexes[i]++;
      scratch[i] = &(*param_matrix[i])[indexes[i]];
      i++;
    } else {
      indexes[i] = -1;
      i--;
    }
  }
}
}

#endif


text:
import 'should';

import * as BT from '../lib/index';
import {BaseError} from '../lib/errors';
import {CommandParams} from '../lib/commands';

class TestError extends BaseError {
}

describe('BackTalker Libraries', () => {
    var scope: BT.Scope, evaluator: BT.Evaluator;

    beforeEach(() => {
        evaluator = new BT.Evaluator();
        scope = evaluator.scope;
    });

    it("can add a reference to a scope", () => {
        var lib = BT.Library.create()
            .ref("bar", 3)
            .done();

        lib.addToScope(scope);
        scope.get("bar").should.eql(3);
    });

    it("can add a function to calculate a reference in addToScope", () => {
        var lib = BT.Library.create()
            .ref("bar", () => 3)
            .done();

        lib.addToScope(scope);
        scope.get("bar").should.eql(3);
    });

    it("can add a reference via addToScope", () => {
        var lib = BT.Library.create()
            .done();

        lib.addToScope(scope, {}, {
            bar: 3
        });
        scope.get("bar").should.eql(3);
    });

    it("can add a command to a scope", () => {
        var lib = BT.Library.create()
            .command("foo", ["foo <bar|baz>:barbaz"])
                .help('Returns either 1 or 2')
                .impl((args: CommandParams, self: BT.Evaluator) => {
                    return args.getNumber("barbaz") + 1;
                })
            .done()
        ;

        lib.addToScope(scope);
        scope.findCommand("foo bar").should.be.ok;
        evaluator.evalString("foo bar").should.eql(1);
    });

    it("can add hanging commands to a scope", () => {
        BT.Library.create()
            .command("bar", ["bar:"])
                .help("runs the body with the variable $bar")
                .callsBody(BT.Library.ONCE)
                .impl(() => "wow")
                .includes()
                    .command("foo", ["foo"])
                    .help("returns 'bar'")
                    .impl(() => "bar")
                .done()
            .done()
            .addToScope(scope)
        ;

        scope.findCommand("bar :").should.be.ok;
    });

    it("can set command implementations during addToScope", () => {
        BT.Library.create()
            .command("bar", ["bar"])
                .impl(() => "wow")
            .command("baz", ["baz"])
            .command("boop", ["boop"])
            .done()
            .addToScope(scope, {
                bar: () => "bar",
                baz: () => "baz"
            });

        evaluator.evalString("bar").should.eql("bar");
        evaluator.evalString("baz").should.eql("baz");
        (scope.findCommand("boop") === null).should.be.ok;
    });

    it("adds metadata to the scope", () => {
        let help = "runs the body with the variable $bar";
        BT.Library.create()
            .command("bar", ["bar :"])
                .help(help)
                .impl(() => "wow")
            .done()
            .addToScope(scope);
        scope.findCommand("bar :").meta.help.should.be.exactly(help);
    });
});


text:
**Note:** Not recommended if full support for IE8 and lower is required. [Details](https://github.com/babel/minify/pull/45#discussion_r70181249)

## Example

**In**

```javascript
Boolean(x);
Number(x);
String(x);
Array(3);
Array(3,1);
Object({foo: 'bar'});
```

**Out**

```javascript
!!x;
+x;
x + "";
[,,,];
[3, 1];
{foo: 'bar'};
```

## Installation

```sh
npm install babel-plugin-minify-type-constructors --save-dev
```

## Usage

### Via `.babelrc` (Recommended)

**.babelrc**

```json
{
  "plugins": ["minify-type-constructors"]
}
```

### Via CLI

```sh
babel --plugins minify-type-constructors script.js
```

### Via Node API

```javascript
require("@babel/core").transform("code", {
  plugins: ["minify-type-constructors"]
});
```

## Options

+ `array` - prevent plugin from minifying arrays
+ `boolean` - prevent plugin from minifying booleans
+ `number` — prevent plugin from minifying numbers
+ `object` — prevent plugin from minifying objects
+ `string` — prevent plugin from minifying strings


text:
import piquant.log as log
import piquant.piquant_options as po
import piquant.piquant_commands as pc
import pytest
import schema
import tempfile
import sys

def _get_logger():
    return log.get_logger(sys.stderr, "critical")

def _get_test_option_value(
        default_value=None, option_validator=int,
        value_namer=lambda x: x, file_namer=None):

    return po._OptionValue(default_value, option_validator,
                           value_namer, file_namer)

def _get_test_option(
        name="name", title="The Name",
        description="description for the option",
        is_numeric=False, option_value=_get_test_option_value()):

    option = po._PiquantOption(
        name, description, title=title, option_value=option_value,
        is_numeric=is_numeric)

    po._PiquantOption.OPTIONS.remove(option)
    return option

def _get_test_qr_option(
        name="name", title="The Name",
        description="description for the option",
        is_numeric=False, option_value=_get_test_option_value()):

    option = po._QuantRunOption(
        name, description, title=title, option_value=option_value,
        is_numeric=is_numeric)

    po._PiquantOption.OPTIONS.remove(option)
    po._QuantRunOption.OPTIONS.remove(option)
    return option

def _get_ignore_options():
    return [
        po.READ_DEPTH,
        po.PAIRED_END,
        po.ERRORS,
        po.BIAS,
        po.STRANDED,
        po.NOISE_DEPTH_PERCENT,
        po.TRANSCRIPT_GTF,
        po.NOISE_TRANSCRIPT_GTF,
        po.GENOME_FASTA_DIR,
        po.NUM_MOLECULES,
        po.NUM_NOISE_MOLECULES,
        po.NUM_THREADS
    ]

def test_piquant_option_name_is_correct():
    name = "piquant_option_name"
    opt = _get_test_option(name=name)
    assert opt.name == name

def test_piquant_option_description_is_correct():
    description = "This is an option"
    opt = _get_test_option(description=description)
    assert opt.description == description

def test_piquant_option_default_value_is_correct():
    default_value = "DEF"
    opt = _get_test_option(
        option_value=_get_test_option_value(default_value=default_value))
    assert opt.default_value() == default_value

def test_piquant_option_option_validator_is_correct():
    option_validator = lambda x: x
    opt = _get_test_option(
        option_value=_get_test_option_value(option_validator=option_validator))
    assert opt.option_value.validator == option_validator

def test_piquant_option_has_value_is_correct():
    opt = _get_test_option(option_value=None)
    assert not opt.has_value()
    opt = _get_test_option(option_value=_get_test_option_value())
    assert opt.has_value()

def test_piquant_option_title_is_correct():
    title = "A Title"
    opt = _get_test_option(title=title)
    assert opt.title == title

def test_piquant_option_is_numeric_is_correct():
    is_numeric = True
    opt = _get_test_option(is_numeric=is_numeric)
    assert opt.is_numeric == is_numeric

def test_piquant_option_value_namer_is_correct():
    value_namer = lambda x: x + "bp"
    opt = _get_test_option(
        option_value=_get_test_option_value(value_namer=value_namer))
    assert opt.option_value.value_namer == value_namer

def test_piquant_option_file_namer_is_correct():
    file_namer = lambda x: x + "bp"
    opt = _get_test_option(
        option_value=_get_test_option_value(file_namer=file_namer))
    assert opt.option_value.file_namer == file_namer

def test_get_usage_string_returns_correct_string_when_option_has_value():
    opt = _get_test_option(name="the_opt")
    assert opt.get_usage_string() == "--the-opt=<the-opt>"

def test_get_usage_string_returns_correct_string_when_option_does_not_have_value():
    opt = _get_test_option(name="the_opt", option_value=None)
    assert opt.get_usage_string() == "--the-opt"

def test_get_option_name_returns_correct_value_when_dashes_included():
    opt = _get_test_option(name="the_opt")
    assert opt.get_option_name() == "--the-opt"

def test_get_option_name_returns_correct_value_when_dashes_not_included():
    opt = _get_test_option(name="the_opt")
    assert opt.get_option_name(include_dashes=False) == "the-opt"

def test_get_option_description_includes_usage_string():
    opt = _get_test_option()
    assert opt.get_option_description().find(opt.get_usage_string()) > -1

def test_get_option_description_includes_description():
    opt = _get_test_option()
    assert opt.get_option_description().find(opt.description) > -1

def test_get_option_description_includes_default_value_specification_when_default_specified():
    default_value = "DEF"
    opt = _get_test_option(
        option_value=_get_test_option_value(default_value=default_value))
    assert opt.get_option_description().find("default:") > -1
    assert opt.get_option_description().find(default_value) > -1

def test_get_option_description_does_not_include_default_value_when_default_value_not_specified():
    opt = _get_test_option()
    assert opt.get_option_description().find("default") == -1

def test_get_value_name_returns_correct_value_when_no_value_namer_supplied():
    value = 30
    opt = _get_test_option()
    assert opt.get_value_name(value) == value

def test_get_value_name_returns_correct_value_when_value_namer_supplied():
    value = 30
    opt = _get_test_option(
        option_value=_get_test_option_value(
            value_namer=lambda x: "VAL{v}".format(v=x)))
    assert opt.get_value_name(value) == "VAL" + str(value)

def test_get_file_name_part_returns_correct_value_when_no_value_or_file_namer_supplied():
    value = 30
    opt = _get_test_option()
    assert opt.get_file_name_part(value) == value

def test_get_file_name_part_returns_correct_value_when_no_file_namer_supplied():
    value = 30
    opt = _get_test_option(
        option_value=_get_test_option_value(
            value_namer=lambda x: "VAL{v}".format(v=x)))
    assert opt.get_file_name_part(value) == "VAL" + str(value)

def test_get_file_name_part_returns_correct_value_when_file_namer_supplied():
    value = 30
    opt = _get_test_option(
        option_value=_get_test_option_value(
            file_namer=lambda x: "{v}bp".format(v=x)))
    assert opt.get_file_name_part(value) == str(value) + "bp"

def test_default_values_dont_overwrite_file_values_for_piquant_options():
    file_value = 10
    default_value = file_value + 1
    opt = _get_test_option(
        option_value=_get_test_option_value(default_value=default_value))

    option_values = {}
    opt.validate_value(
        {opt.get_option_name(): str(default_value)},
        {opt.get_option_name(): str(file_value)},
        option_values, {})

    assert option_values[opt.name] == file_value

def test_default_values_dont_overwrite_file_values_for_quant_run_options():
    file_value = 10
    default_value = file_value + 1
    opt = _get_test_qr_option(
        option_value=_get_test_option_value(default_value=default_value))

    qr_option_values = {}
    opt.validate_value(
        {opt.get_option_name(): str(default_value)},
        {opt.get_option_name(): str(file_value)},
        {}, qr_option_values)

    assert qr_option_values[opt.name] == file_value

def test_get_multi_quant_run_options_returns_mqr_option_instances():
    opts = po.get_multiple_quant_run_options()
    assert all([isinstance(o, po._MultiQuantRunOption) for o in opts])

def test_get_numerical_mqr_options_returns_numeric_options():
    opts = po.get_numerical_mqr_options()
    assert all([o.is_numeric for o in opts])

def test_validate_option_values_returns_correct_number_of_options():
    options = {
        po.PLOT_FORMAT: "svg",
        po.QUANT_METHOD: "Cufflinks",
        po.READ_LENGTH: "10,20",
    }

    opt_vals, qr_opt_vals = po._validate_option_values(
        _get_logger(), {o.get_option_name(): v for o, v in options.items()},
        {}, options.keys())
    assert len(opt_vals) == 1
    assert len(qr_opt_vals) == 2

def test_validate_option_values_returns_correct_number_of_transformed_values():
    num_values = 5
    options = {
        po.READ_LENGTH.get_option_name():
        ",".join([str(i) for i in range(1, num_values + 1)])
    }

    opt_vals, qr_opt_vals = po._validate_option_values(
        _get_logger(), options, {}, [po.READ_LENGTH])

    assert len(qr_opt_vals[po.READ_LENGTH.name]) == num_values

def test_validate_option_values_returns_correct_transformed_values():
    len1 = 10
    len2 = 20
    options = {
        po.READ_LENGTH.get_option_name(): str(len1) + "," + str(len2)
    }

    opt_vals, qr_opt_vals = po._validate_option_values(
        _get_logger(), options, {}, [po.READ_LENGTH])

    for val in [len1, len2]:
        assert val in qr_opt_vals[po.READ_LENGTH.name]

def test_validate_option_values_raises_exception_for_invalid_option_values():
    options = {
        po.READ_LENGTH.get_option_name(): "abc"
    }

    with pytest.raises(schema.SchemaError):
        po._validate_option_values(
            _get_logger(), options, {}, [po.READ_LENGTH])

def test_validate_option_values_raises_exception_if_quant_run_option_values_not_supplied():
    options = {
        po.READ_LENGTH.get_option_name(): "10,20",
    }

    with pytest.raises(schema.SchemaError):
        po._validate_option_values(
            _get_logger(), options, {}, [po.READ_LENGTH, po.READ_DEPTH])

def test_read_file_options_reads_options_from_file():
    quant_method = "Cufflinks"
    read_length = "10,20"
    with tempfile.NamedTemporaryFile(mode='w+') as tmp_file:
        tmp_file.write(po.QUANT_METHOD.get_option_name() +
                       " " + quant_method + "\n")
        tmp_file.write(po.READ_LENGTH.get_option_name() +
                       " " + read_length + "\n")
        tmp_file.flush()

        options = po._read_file_options(tmp_file.name)

        assert options[po.QUANT_METHOD.get_option_name()] == quant_method
        assert options[po.READ_LENGTH.get_option_name()] == read_length

def test_validate_option_values_overrides_file_parameters_with_cl_options():
    len1 = 10
    len2 = 20
    len3 = 30

    file_options = {
        po.READ_LENGTH.get_option_name(): str(len1) + "," + str(len2)
    }

    cl_options = {
        po.READ_LENGTH.get_option_name(): str(len3)
    }

    opts, qr_opts = po._validate_option_values(
        _get_logger(), cl_options, file_options, [po.READ_LENGTH])

    assert len1 not in qr_opts[po.READ_LENGTH.name]
    assert len2 not in qr_opts[po.READ_LENGTH.name]
    assert len3 in qr_opts[po.READ_LENGTH.name]

def test_get_run_name_returns_correct_name():
    qr_options = {
        po.READ_LENGTH.name: 50,
        po.READ_DEPTH.name: 30,
        po.PAIRED_END.name: True,
        po.BIAS.name: False,
    }

    assert po.get_run_name(qr_options) == "30x_50b_pe_no_bias"

def test_get_value_names_returns_correct_translated_values():
    mqr_options = {
        po.READ_LENGTH: 50,
        po.READ_DEPTH: 10,
        po.STRANDED: False,
        po.PAIRED_END: True,
        po.ERRORS: False,
        po.BIAS: True,
        po.NOISE_DEPTH_PERCENT: 5,
        po.QUANT_METHOD: "Cufflinks",
    }

    assert po.get_value_names(mqr_options) == \
        ["Cufflinks", "10x", "50b", "paired-end", "no errors",
         "unstranded", "with bias", "noise-5x"]

def test_execute_for_mqr_option_sets_executes_for_correct_number_of_option_sets():
    len1 = 3
    len2 = 5
    len3 = 7
    qr_options = {
        po.READ_LENGTH.name: [1] * len1,
        po.READ_DEPTH.name: [2] * len2,
        po.ERRORS.name: [True] * len3
    }

    execute_counter = []

    def count_incrementer(logger, options, **qr_options):
        del logger
        del options
        del qr_options
        execute_counter.append(1)

    command = pc._PiquantCommand("dummy", "dummy", [])
    command.executables = [count_incrementer]
    po.execute_for_mqr_option_sets(
        command, None, None, qr_options)

    assert len(execute_counter) == len1 * len2 * len3

def test_execute_for_mqr_option_sets_executes_all_callables():
    qr_options = {
        po.READ_LENGTH.name: [50]
    }

    execute_record = []

    def callable1(logger, options, **qr_options):
        del logger
        del options
        del qr_options
        execute_record.append(1)

    def callable2(logger, options, **qr_options):
        del logger
        del options
        del qr_options
        execute_record.append(2)

    command = pc._PiquantCommand("dummy", "dummy", [])
    command.executables = [callable1, callable2]

    po.execute_for_mqr_option_sets(
        command, None, None, qr_options)

    assert 1 in execute_record
    assert 2 in execute_record
    assert len(execute_record) == 2

def test_execute_for_mqr_option_sets_executes_for_correct_sets_of_piquant_options():
    piquant_options1 = [75, 100]
    piquant_options2 = [30, 50]
    qr_options = {
        po.READ_LENGTH.name: piquant_options1,
        po.READ_DEPTH.name: piquant_options2
    }

    execute_record = []

    def callable1(logger, options, **qr_option):
        del logger
        del options
        execute_record.append([v for v in qr_option.values()])

    command = pc._PiquantCommand("dummy", "dummy", [])
    command.executables = [callable1]
    po.execute_for_mqr_option_sets(
        command, None, None, qr_options)

    execute_record = \
        [set(piquant_options) for piquant_options in execute_record]
    assert set([piquant_options1[0], piquant_options2[0]]) in execute_record
    assert set([piquant_options1[0], piquant_options2[1]]) in execute_record
    assert set([piquant_options1[1], piquant_options2[0]]) in execute_record
    assert set([piquant_options1[1], piquant_options2[1]]) in execute_record


text:
namespace POS.Infra.Data.Migrations
{
    using System.CodeDom.Compiler;
    using System.Data.Entity.Migrations;
    using System.Data.Entity.Migrations.Infrastructure;
    using System.Resources;

    [GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")]
    public sealed partial class PaymentMethodCategoryandProductTables : IMigrationMetadata
    {
        private readonly ResourceManager Resources = new ResourceManager(typeof(PaymentMethodCategoryandProductTables));

        string IMigrationMetadata.Id
        {
            get { return "201707150353192_Payment Method, Category and Product Tables"; }
        }

        string IMigrationMetadata.Source
        {
            get { return null; }
        }

        string IMigrationMetadata.Target
        {
            get { return Resources.GetString("Target"); }
        }
    }
}


text:
#import "RTCSessionDescription+JSON.h"

static NSString const *kRTCSessionDescriptionTypeKey = @"type";
static NSString const *kRTCSessionDescriptionSdpKey = @"sdp";

@implementation RTCSessionDescription (JSON)

+ (RTCSessionDescription *)descriptionFromJSONDictionary:
    (NSDictionary *)dictionary {
  NSString *type = dictionary[kRTCSessionDescriptionTypeKey];
  NSString *sdp = dictionary[kRTCSessionDescriptionSdpKey];
  return [[RTCSessionDescription alloc] initWithType:type sdp:sdp];
}

- (NSData *)JSONData {
  NSDictionary *json = @{
    kRTCSessionDescriptionTypeKey : self.type,
    kRTCSessionDescriptionSdpKey : self.description
  };
  return [NSJSONSerialization dataWithJSONObject:json options:0 error:nil];
}

@end


text:
{% extends "wagtailadmin/base.html" %}
{% load wagtailadmin_tags i18n %}
{% block titletag %}
    {% if count == 1 %}
      {% blocktrans with snippet_type_name=model_opts.verbose_name %}Delete {{ snippet_type_name }}{% endblocktrans %} - {{ instances|first }}
    {% else %}
      {{ count }} {{ model_opts.verbose_name_plural|capfirst }}
    {% endif %}
{% endblock %}
{% block content %}
    {% trans "Delete " as delete_str %}
    {% if count == 1 %}
        {% include "wagtailadmin/shared/header.html" with title=delete_str subtitle=instances|first icon="snippet" %}
    {% else %}
        {% include "wagtailadmin/shared/header.html" with title=delete_str subtitle=model_opts.verbose_name_plural|capfirst icon="snippet" %}
    {% endif %}

        {% if count == 1 %}
            {% usage_count_enabled as uc_enabled %}
            {% if uc_enabled %}

                    {% blocktrans count usage_count=instances.0.get_usage.count %}Used {{ usage_count }} time{% plural %}Used {{ usage_count }} times{% endblocktrans %}

            {% endif %}

{% blocktrans with snippet_type_name=model_opts.verbose_name %}Are you sure you want to delete this {{ snippet_type_name }}?{% endblocktrans %}

        {% else %}

{% blocktrans with snippet_type_name=model_opts.verbose_name_plural %}Are you sure you want to delete {{ count }} {{ snippet_type_name }}?{% endblocktrans %}

                {% for instance in instances %}

{{ instance }}

                {% endfor %}

        {% endif %}
        <form action="{{ submit_url }}" method="POST">
            {% csrf_token %}
            <input type="submit" value="{% trans 'Yes, delete' %}" class="button serious" />
            {% trans "No, don't delete" %}
        </form>

{% endblock %}


text:
<?php
App::uses('ContentsController', 'ContentManager.Controller');

/**
 * ContentsController Test Case
 *
 */
class ContentsControllerTest extends ControllerTestCase {

/**
 * Fixtures
 *
 * @var array
 */
	public $fixtures = array(
		'plugin.content_manager.content'
	);

}


text:
using namespace std;
using namespace Drake;

int main(int argc, char* argv[]) {
  shared_ptr<lcm::LCM> lcm = make_shared<lcm::LCM>();
  if (!lcm->good()) return 1;

  auto p = std::make_shared<Pendulum>();
  auto c = std::make_shared<PendulumEnergyShapingController>(*p);

  if (true) {  // run as LCM node
    runLCM(c, lcm, 0, 10, NullVector<double>());
  } else {  // run a stand-alone simulation
    SimulationOptions options;
    options.realtime_factor = 1.0;

    Eigen::Vector2d x0;
    x0 << 0.1, 0.2;

    auto v = std::make_shared<BotVisualizer<PendulumState> >(
        lcm, getDrakePath() + "/examples/Pendulum/Pendulum.urdf",
        DrakeJoint::FIXED);
    auto sys = cascade(feedback(p, c), v);
    simulate(*sys, 0, 10, x0, options);
  }
}


text:
require 'spec_helper'

describe String do
  let!(:raw_dn) { '/DC=org/DC=ruby-lang/CN=Ruby certificate rbcert' }
  let(:dn) {
    DN.new({
      dn_string: raw_dn,
    })
  }
  let(:dn_to_s) { 'CN=RUBY CERTIFICATE RBCERT,DC=RUBY-LANG,DC=ORG' }

  after :all do
    #expect(@log_output.readline).to eq("DEBUG String: DNC raw_dn:\n")
  end

  describe ".to_dn" do
    it "should return a DN instance if the string can be parsed" do
      expect(raw_dn.to_dn.class.to_s).to eq('DN')
      expect(raw_dn.to_dn.to_yaml).to eq(dn.to_yaml)
    end

    it "should return nil otherwise" do
      expect("".to_dn).to eql(nil)
      expect("nope".to_dn).to eql(nil)
    end
  end

  describe ".to_dn!" do
    it "should return a DN instance if the string can be parsed" do
      expect(raw_dn.to_dn!.class.to_s).to eq('DN')
      expect(raw_dn.to_dn!.to_yaml).to eq(dn.to_yaml)
    end

    it "should raise a DnStringUnparsableError otherwise" do
      expect{ "".to_dn! }.to raise_error(DnStringUnparsableError)
      expect{ "nope".to_dn! }.to raise_error(DnStringUnparsableError)
    end
  end
end


text:
var recordButton = document.getElementById('recordToggle');
var constraints = { audio: true };

var shouldRecord = false;
var mediaRecorder = null;
var recordedMimeType = null;

if (navigator.mediaDevices && MediaRecorder) {
  if (MediaRecorder.isTypeSupported('audio/webm;codecs=opus')) {
    recordedMimeType = 'audio/webm;codecs=opus';
  } else if (MediaRecorder.isTypeSupported('audio/ogg;codecs=opus')) {
    recordedMimeType = 'audio/ogg;codecs=opus';
  }
}

if (recordedMimeType === null) {
  recordButton.style.visibility = 'hidden';
} else {
  recordButton.addEventListener('click', function() {
    shouldRecord = !shouldRecord;
    if (shouldRecord) {
      navigator.mediaDevices.getUserMedia(constraints).then(handleSuccess);
      recordButton.classList.add('purple');
    } else if (mediaRecorder) {
      mediaRecorder.stop();
      recordButton.classList.remove('purple');
    }
  });
}

function handleSuccess(stream) {
  var chunks = [];
  mediaRecorder = new MediaRecorder(stream, {mimeType: recordedMimeType});

  mediaRecorder.addEventListener('stop', function() {
    Api.sendBlobRequest(new Blob(chunks, { 'type' : recordedMimeType }));

    for (var track of stream.getTracks()) {
      track.stop();
    }
  });

  mediaRecorder.addEventListener('dataavailable', function(e) {
    if (e.data.size > 0) {
      chunks.push(e.data);
    }
  });

  mediaRecorder.start();
}


text:
require 'spec_helper'

module FlightScrapper

	describe EasyjetRequestBuilder do
		describe '#build_url' do

			it 'builds the RoundTrip URL' do
				criteria = FactoryGirl.build(:search_criteria, :round_trip_one_adult)
				EasyjetRequestBuilder.build_url(criteria).should eql 'http://www.easyjet.com/links.mvc?dep=BCN&dest=LTN&dd=18/01/2014&rd=04/04/2014&apax=1&pid=www.easyjet.com&cpax=0&ipax=0&lang=EN&isOneWay=off&searchFrom=SearchPod|/en/'
			end

			it 'builds the OneWay URL' do
				criteria = FactoryGirl.build(:search_criteria, :one_way_one_adult)
				EasyjetRequestBuilder.build_url(criteria).should eql 'http://www.easyjet.com/links.mvc?dep=BCN&dest=LTN&dd=18/01/2014&apax=1&pid=www.easyjet.com&cpax=0&ipax=0&lang=EN&isOneWay=on&searchFrom=SearchPod|/en/'
			end

		end
	end

end


text:
from mod_pywebsocket import msgutil

def web_socket_do_extra_handshake(request):
    # Exact number of headers that will fit in 256KB. Above 256KB an
    # ERR_RESPONSE_HEADERS_TOO_BIG error is triggered instead.

    name = 'Set-Cookie'
    common_length = len(name + ': ' + '\r\n')

    i = 0
    total_length = 0
    while True:
        value = 'ws-%d=1' % i

        total_length += common_length + len(value)
        # Subtract 1KB to make sure we have space for the other headers.
        if total_length >= 256 * 1024 - 1024:
            break

        request.extra_headers.append((name, value))
        i += 1

def web_socket_transfer_data(request):
    pass


text:
Chef::Log.info("******Git - Checkout BPM Application.******")

git "/home/ec2-user/app" do
  repository "git://github.com/joedanz/flask-bpm.git"
  revision "master"
  user "ec2-user"
  group "ec2-user"
  action :sync
end


text:
'use strict';

// MODULES //

var tape = require( 'tape' );
var proxyquire = require( 'proxyquire' );
var IS_BROWSER = require( '@stdlib/assert/is-browser' );
var smskinv = require( './../lib' );

// VARIABLES //

var opts = {
	'skip': IS_BROWSER
};

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.strictEqual( typeof smskinv, 'function', 'main export is a function' );
	t.end();
});

tape( 'attached to the main export is a method providing an ndarray interface', function test( t ) {
	t.strictEqual( typeof smskinv.ndarray, 'function', 'method is a function' );
	t.end();
});

tape( 'if a native implementation is available, the main export is the native implementation', opts, function test( t ) {
	var smskinv = proxyquire( './../lib', {
		'@stdlib/utils/try-require': tryRequire
	});

	t.strictEqual( smskinv, mock, 'returns native implementation' );
	t.end();

	function tryRequire() {
		return mock;
	}

	function mock() {
		// Mock...
	}
});

tape( 'if a native implementation is not available, the main export is a JavaScript implementation', opts, function test( t ) {
	var smskinv;
	var m;

	m = require( './../lib/smskinv.js' );

	smskinv = proxyquire( './../lib', {
		'@stdlib/utils/try-require': tryRequire
	});

	t.strictEqual( smskinv, m, 'returns JavaScript implementation' );
	t.end();

	function tryRequire() {
		return new Error( 'Cannot find module' );
	}
});


text:
#pragma once
#include <aws/glue/Glue_EXPORTS.h>
#include <aws/glue/GlueRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <utility>

namespace Aws
{
namespace Glue
{
namespace Model
{

  /**
   */
  class AWS_GLUE_API BatchStopJobRunRequest : public GlueRequest
  {
  public:
    BatchStopJobRunRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "BatchStopJobRun"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The name of the job definition for which to stop job runs.

     */
    inline const Aws::String& GetJobName() const{ return m_jobName; }

    /**
     *
The name of the job definition for which to stop job runs.

     */
    inline void SetJobName(const Aws::String& value) { m_jobNameHasBeenSet = true; m_jobName = value; }

    /**
     *
The name of the job definition for which to stop job runs.

     */
    inline void SetJobName(Aws::String&& value) { m_jobNameHasBeenSet = true; m_jobName = std::move(value); }

    /**
     *
The name of the job definition for which to stop job runs.

     */
    inline void SetJobName(const char* value) { m_jobNameHasBeenSet = true; m_jobName.assign(value); }

    /**
     *
The name of the job definition for which to stop job runs.

     */
    inline BatchStopJobRunRequest& WithJobName(const Aws::String& value) { SetJobName(value); return *this;}

    /**
     *
The name of the job definition for which to stop job runs.

     */
    inline BatchStopJobRunRequest& WithJobName(Aws::String&& value) { SetJobName(std::move(value)); return *this;}

    /**
     *
The name of the job definition for which to stop job runs.

     */
    inline BatchStopJobRunRequest& WithJobName(const char* value) { SetJobName(value); return *this;}

    /**
     *
A list of the JobRunIds that should be stopped for that job definition.

     */
    inline const Aws::Vector<Aws::String>& GetJobRunIds() const{ return m_jobRunIds; }

    /**
     *
A list of the JobRunIds that should be stopped for that job definition.

     */
    inline void SetJobRunIds(const Aws::Vector<Aws::String>& value) { m_jobRunIdsHasBeenSet = true; m_jobRunIds = value; }

    /**
     *
A list of the JobRunIds that should be stopped for that job definition.

     */
    inline void SetJobRunIds(Aws::Vector<Aws::String>&& value) { m_jobRunIdsHasBeenSet = true; m_jobRunIds = std::move(value); }

    /**
     *
A list of the JobRunIds that should be stopped for that job definition.

     */
    inline BatchStopJobRunRequest& WithJobRunIds(const Aws::Vector<Aws::String>& value) { SetJobRunIds(value); return *this;}

    /**
     *
A list of the JobRunIds that should be stopped for that job definition.

     */
    inline BatchStopJobRunRequest& WithJobRunIds(Aws::Vector<Aws::String>&& value) { SetJobRunIds(std::move(value)); return *this;}

    /**
     *
A list of the JobRunIds that should be stopped for that job definition.

     */
    inline BatchStopJobRunRequest& AddJobRunIds(const Aws::String& value) { m_jobRunIdsHasBeenSet = true; m_jobRunIds.push_back(value); return *this; }

    /**
     *
A list of the JobRunIds that should be stopped for that job definition.

     */
    inline BatchStopJobRunRequest& AddJobRunIds(Aws::String&& value) { m_jobRunIdsHasBeenSet = true; m_jobRunIds.push_back(std::move(value)); return *this; }

    /**
     *
A list of the JobRunIds that should be stopped for that job definition.

     */
    inline BatchStopJobRunRequest& AddJobRunIds(const char* value) { m_jobRunIdsHasBeenSet = true; m_jobRunIds.push_back(value); return *this; }

  private:

    Aws::String m_jobName;
    bool m_jobNameHasBeenSet;

    Aws::Vector<Aws::String> m_jobRunIds;
    bool m_jobRunIdsHasBeenSet;
  };

} // namespace Model
} // namespace Glue
} // namespace Aws


text:
<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\User;
use app\models\AccessRights;
use app\models\Template;
use app\models\NewTemplateForm;
use app\models\EditTemplateForm;
use app\models\Log;

class TemplateController extends Controller
{

    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout'],
                'rules' => [
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    /**
     * Logs out the current user.
     *
     * @return mixed
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }

    public function actionNew()
    {
        $rights = AccessRights::getAccessRightsForMenu(Yii::$app->user->id);
        Yii::$app->view->params['accessRightsArray'] = $rights;

        if (!empty(array_intersect([1,4], $rights))) {
            $model = new NewTemplateForm();
            if ($model->load(Yii::$app->request->post()) && $model->validate()){
                $template = new Template();
                $template->template_name = $model->name;
                $template->source_code = $model->sourceCode;
                $template->save();

                Log::writeLog(Yii::$app->user->id, 9, $model->name);
            }
            return $this->render('new', array('model' => $model));
        }

        return $this->render('error', array('name'=>'Nepovolený prístup', 'message'=>'Do tejto časti nemáte prístup!'));
    }

    public function actionAll()
    {
        $rights = AccessRights::getAccessRightsForMenu(Yii::$app->user->id);
        Yii::$app->view->params['accessRightsArray'] = $rights;

        if (!empty(array_intersect([1,4], $rights))) {
            $templates = Template::find()->all();
            return $this->render('all', array('templates' => $templates));
        }

        return $this->render('error', array('name'=>'Nepovolený prístup', 'message'=>'Do tejto časti nemáte prístup!'));
    }

    public function actionShow($id)
    {
        $rights = AccessRights::getAccessRightsForMenu(Yii::$app->user->id);
        Yii::$app->view->params['accessRightsArray'] = $rights;

        if (!empty(array_intersect([1,4], $rights))) {
            $template = Template::findOne(['id' => $id]);

            if ($template === null){
                return $this->render('error', array('name'=>'Šablóna neexistuje', 'message'=>'Šablóna so zadaným ID neexistuje.'));
            }

            $model = new EditTemplateForm();
            $model->sourceCode = $template->source_code;
            if ($model->load(Yii::$app->request->post()) && $model->validate()){
                $template = Template::findById($id);
                $template->source_code = $model->sourceCode;
                $template->update();

                Log::writeLog(Yii::$app->user->id, 10, $template->template_name);
            }
            return $this->render('show', array('model' => $model, 'template' => $template));
        }

        return $this->render('error', array('name'=>'Nepovolený prístup', 'message'=>'Do tejto časti nemáte prístup!'));
    }
}


text:
#region license
// Copyright 2014 JetBrains s.r.o.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion

using JetBrains.Application.Settings;
using JetBrains.DataFlow;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.JavaScript.CodeStyle;

namespace JetBrains.ReSharper.Plugins.AngularJS.Psi.AngularJs.CodeStyle
{
    [Language(typeof(AngularJsLanguage))]
    public class AngularJsCodeFormatter : JavaScriptCodeFormatterBase
    {
        public AngularJsCodeFormatter(Lifetime lifetime, PsiLanguageType language, ISettingsStore settingsStore,
                                      ISettingsOptimization settingsOptimization,
                                      JavaScriptFormattingInfoProviderBase formattingProvider,
                                      JavaScriptIndentingInfoProviderBase indentingProvider,
                                      IViewable<IJavaScriptCodeFormatterExtension> extensions)
            : base(lifetime, language, settingsStore, settingsOptimization,
                   formattingProvider, indentingProvider, extensions)
        {
        }
    }
}


text:
package spacequota

import (
	"github.com/codegangsta/cli"
	"github.com/nttlabs/cli/cf/api/space_quotas"
	"github.com/nttlabs/cli/cf/command_metadata"
	"github.com/nttlabs/cli/cf/configuration/core_config"
	"github.com/nttlabs/cli/cf/flag_helpers"
	"github.com/nttlabs/cli/cf/formatters"
	. "github.com/nttlabs/cli/cf/i18n"
	"github.com/nttlabs/cli/cf/requirements"
	"github.com/nttlabs/cli/cf/terminal"
)

type UpdateSpaceQuota struct {
	ui             terminal.UI
	config         core_config.Reader
	spaceQuotaRepo space_quotas.SpaceQuotaRepository
}

func NewUpdateSpaceQuota(ui terminal.UI, config core_config.Reader, spaceQuotaRepo space_quotas.SpaceQuotaRepository) (cmd *UpdateSpaceQuota) {
	return &UpdateSpaceQuota{
		ui:             ui,
		config:         config,
		spaceQuotaRepo: spaceQuotaRepo,
	}
}

func (cmd *UpdateSpaceQuota) Metadata() command_metadata.CommandMetadata {
	return command_metadata.CommandMetadata{
		Name:        "update-space-quota",
		Description: T("update an existing space quota"),
		Usage:       T("CF_NAME update-space-quota SPACE-QUOTA-NAME [-i MAX-INSTANCE-MEMORY] [-m MEMORY] [-n NEW_NAME] [-r ROUTES] [-s SERVICES] [--allow-paid-service-plans | --disallow-paid-service-plans]"),
		Flags: []cli.Flag{
			flag_helpers.NewStringFlag("i", T("Maximum amount of memory an application instance can have (e.g. 1024M, 1G, 10G). -1 represents an unlimited amount.")),
			flag_helpers.NewStringFlag("m", T("Total amount of memory a space can have (e.g. 1024M, 1G, 10G)")),
			flag_helpers.NewStringFlag("n", T("New name")),
			flag_helpers.NewIntFlag("r", T("Total number of routes")),
			flag_helpers.NewIntFlag("s", T("Total number of service instances")),
			cli.BoolFlag{Name: "allow-paid-service-plans", Usage: T("Can provision instances of paid service plans")},
			cli.BoolFlag{Name: "disallow-paid-service-plans", Usage: T("Can not provision instances of paid service plans")},
		},
	}
}

func (cmd *UpdateSpaceQuota) GetRequirements(requirementsFactory requirements.Factory, c *cli.Context) (reqs []requirements.Requirement, err error) {
	if len(c.Args()) != 1 {
		cmd.ui.FailWithUsage(c)
	}

	reqs = []requirements.Requirement{
		requirementsFactory.NewLoginRequirement(),
		requirementsFactory.NewTargetedOrgRequirement(),
	}
	return
}

func (cmd *UpdateSpaceQuota) Run(c *cli.Context) {
	name := c.Args()[0]

	spaceQuota, apiErr := cmd.spaceQuotaRepo.FindByName(name)
	if apiErr != nil {
		cmd.ui.Failed(apiErr.Error())
		return
	}

	allowPaidServices := c.Bool("allow-paid-service-plans")
	disallowPaidServices := c.Bool("disallow-paid-service-plans")
	if allowPaidServices && disallowPaidServices {
		cmd.ui.Failed(T("Please choose either allow or disallow. Both flags are not permitted to be passed in the same command."))
	}

	if allowPaidServices {
		spaceQuota.NonBasicServicesAllowed = true
	}

	if disallowPaidServices {
		spaceQuota.NonBasicServicesAllowed = false
	}

	if c.String("i") != "" {
		var memory int64
		var formatError error

		memFlag := c.String("i")

		if memFlag == "-1" {
			memory = -1
		} else {
			memory, formatError = formatters.ToMegabytes(memFlag)
			if formatError != nil {
				cmd.ui.FailWithUsage(c)
			}
		}

		spaceQuota.InstanceMemoryLimit = memory
	}

	if c.String("m") != "" {
		memory, formatError := formatters.ToMegabytes(c.String("m"))

		if formatError != nil {
			cmd.ui.FailWithUsage(c)
		}

		spaceQuota.MemoryLimit = memory
	}

	if c.String("n") != "" {
		spaceQuota.Name = c.String("n")
	}

	if c.IsSet("s") {
		spaceQuota.ServicesLimit = c.Int("s")
	}

	if c.IsSet("r") {
		spaceQuota.RoutesLimit = c.Int("r")
	}

	cmd.ui.Say(T("Updating space quota {{.Quota}} as {{.Username}}...",
		map[string]interface{}{
			"Quota":    terminal.EntityNameColor(name),
			"Username": terminal.EntityNameColor(cmd.config.Username()),
		}))

	apiErr = cmd.spaceQuotaRepo.Update(spaceQuota)
	if apiErr != nil {
		cmd.ui.Failed(apiErr.Error())
		return
	}

	cmd.ui.Ok()
}


text:
package org.yaml.snakeyaml.types;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @see http://yaml.org/type/null.html
 */
public class NullTagTest extends AbstractTest {

    public void testNull() throws IOException {
        assertNull("Got: '" + load("---\n") + "'", load("---\n"));
        assertNull(load("---\n..."));
        assertNull(load("---\n...\n"));
        assertNull(load("\n"));
        assertNull(load(""));
        assertNull(load(" "));
        assertNull(load("~"));
        assertNull(load("---\n~"));
        assertNull(load("null"));
        assertNull(load("Null"));
        assertNull(load("NULL"));
        assertNull(getMapValue("empty:\n", "empty"));
        assertNull(getMapValue("canonical: ~", "canonical"));
        assertNull(getMapValue("english: null", "english"));
        assertNull(getMapValue("english: Null", "english"));
        assertNull(getMapValue("english: NULL", "english"));
        assertEquals("null key", getMapValue("~: null key\n", null));
    }

    @SuppressWarnings("unchecked")
    public void testSequenceNull() throws IOException {
        String input = "---\n# This sequence has five\n# entries, two have values.\nsparse:\n  - ~\n  - 2nd entry\n  -\n  - 4th entry\n  - Null\n";
        List<String> parsed = (List<String>) getMapValue(input, "sparse");
        assertEquals(5, parsed.size());
        assertNull(parsed.get(0));
        assertEquals("2nd entry", parsed.get(1));
        assertNull("Got: '" + parsed.get(2) + "'", parsed.get(2));
        assertEquals("4th entry", parsed.get(3));
        assertNull(parsed.get(4));
    }

    public void testNullInMap() throws IOException {
        String input = "key1: null\n~: value1";
        Map<String, Object> parsed = getMap(input);
        assertEquals(2, parsed.size());
        assertTrue(parsed.containsKey(null));
        Object value1 = parsed.get(null);
        assertEquals("value1", value1);
        //
        assertNull(parsed.get("key1"));
        //
        assertFalse(getMap("key2: value2").containsKey(null));
    }

    public void testBoolShorthand() throws IOException {
        assertNull(getMapValue("nothing: !!null null", "nothing"));
    }

    public void testBoolTag() throws IOException {
        assertNull(getMapValue("nothing: !<tag:yaml.org,2002:null> null", "nothing"));
    }

    public void testBoolOut() throws IOException {
        String output = dump(null);
        assertEquals("null\n", output);
    }

}


text:
package sun.jvm.hotspot.oops;

import java.io.*;
import java.util.*;
import sun.jvm.hotspot.debugger.*;
import sun.jvm.hotspot.runtime.*;
import sun.jvm.hotspot.types.*;

public class CompiledICHolderKlass extends Klass {
  static {
    VM.registerVMInitializedObserver(new Observer() {
        public void update(Observable o, Object data) {
          initialize(VM.getVM().getTypeDataBase());
        }
      });
  }

  private static synchronized void initialize(TypeDataBase db) throws WrongTypeException {
    Type type  = db.lookupType("compiledICHolderKlass");
    headerSize = type.getSize() + Oop.getHeaderSize();
  }

  CompiledICHolderKlass(OopHandle handle, ObjectHeap heap) {
    super(handle, heap);
  }

  private static long headerSize;

  public long getObjectSize() { return alignObjectSize(headerSize); }

  public void printValueOn(PrintStream tty) {
    tty.print("CompilerICHolderKlass");
  }
}


text:
@protocol FFTDownloadDelegate
- (void)downloadSucceeded:(NSData *)downloadData;
- (void)downloadFailedWithError:(NSError *)downloadError;

@optional
- (void)foundUrls:(NSArray *)urls;
@end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Sporidesmium granulosum Durieu & Mont.

### Remarks
null


text:
HidMirror = require('./HidMirror.js');

var mirror = new HidMirror ();

mirror.start();

mirror.on("hidm_up", function (data){
    console.log("-> mir:ror up");
});
mirror.on("hidm_down", function (data){
    console.log("-> mir:ror down");
});
mirror.on("hidm_in", function (data){
    console.log("-> mir:ror RFID IN --> ID =>> "); console.log(data);
});
mirror.on("hidm_out", function (data){
    console.log("-> mir:ror RFID OUT --> ID =>> "); console.log(data);
});
mirror.on("hidm_started", function (data){
    console.log("-> mir:ror READY ");
});
mirror.on("hidm_stopped", function (data){
    console.log("-> mir:ror STOPPED ");
});


text:
module.exports = {
  plugins: [
    require('babel-plugin-transform-runtime')
  ]
}


text:
@class SBJSON;

@interface MaxDepth : SenTestCase {
    SBJSON *json;
}

@end


text:
module.exports = {
	'basic': {
		message: 'supports basic usage'
	},
	'basic:preserve': {
		message: 'supports { preserve: false } usage',
		options: {
			preserve: false
		}
	},
	'basic:import': {
		message: 'supports { importFrom: { customProperties: { ... } } } usage',
		options: {
			importFrom: {
				customProperties: {
					'--color': 'rgb(255, 0, 0)',
					'--color-2': 'yellow',
					'--ref-color': 'var(--color)',
					'--margin': '0 10px 20px 30px',
					'--z-index': 10
				}
			}
		}
	},
	'basic:import-fn': {
		message: 'supports { importFrom() } usage',
		options: {
			importFrom() {
				return {
					customProperties: {
						'--color': 'rgb(255, 0, 0)',
						'--color-2': 'yellow',
						'--ref-color': 'var(--color)',
						'--margin': '0 10px 20px 30px',
						'--z-index': 10
					}
				};
			}
		},
		expect: 'basic.import.expect.css',
		result: 'basic.import.result.css'
	},
	'basic:import-fn-promise': {
		message: 'supports { async importFrom() } usage',
		options: {
			importFrom() {
				return new Promise(resolve => {
					resolve({
						customProperties: {
							'--color': 'rgb(255, 0, 0)',
							'--color-2': 'yellow',
							'--ref-color': 'var(--color)',
							'--z-index': 10
						}
					})
				});
			}
		},
		expect: 'basic.import.expect.css',
		result: 'basic.import.result.css'
	},
	'basic:import-json': {
		message: 'supports { importFrom: "test/import-properties.json" } usage',
		options: {
			importFrom: 'test/import-properties.json'
		},
		expect: 'basic.import.expect.css',
		result: 'basic.import.result.css'
	},
	'basic:import-js': {
		message: 'supports { importFrom: "test/import-properties{-2}?.js" } usage',
		options: {
			importFrom: [
				'test/import-properties.js',
				'test/import-properties-2.js'
			]
		},
		expect: 'basic.import.expect.css',
		result: 'basic.import.result.css'
	},
	'basic:import-css': {
		message: 'supports { importFrom: "test/import-properties{-2}?.css" } usage',
		options: {
			importFrom: [
				'test/import-properties.css',
				'test/import-properties-2.css'
			]
		},
		expect: 'basic.import.expect.css',
		result: 'basic.import.result.css'
	},
	'basic:import-css-js': {
		message: 'supports { importFrom: "test/import-properties{-2}?.{css|js}" } usage',
		options: {
			importFrom: [
				'test/import-properties.js',
				'test/import-properties-2.css'
			]
		},
		expect: 'basic.import.expect.css',
		result: 'basic.import.result.css'
	},
	'basic:import-css-pcss': {
		message: 'supports { importFrom: "test/import-properties.{p}?css" } usage',
		options: {
			importFrom: [
				'test/import-properties.pcss',
				'test/import-properties-2.css'
			]
		},
		expect: 'basic.import.expect.css',
		result: 'basic.import.result.css'
	},
	'basic:import-css-from': {
		message: 'supports { importFrom: { from: "test/import-properties.css" } } usage',
		options: {
			importFrom: [
				{ from: 'test/import-properties.css' },
				{ from: 'test/import-properties-2.css' }
			]
		},
		expect: 'basic.import.expect.css',
		result: 'basic.import.result.css'
	},
	'basic:import-css-from-type': {
		message: 'supports { importFrom: [ { from: "test/import-properties.css", type: "css" } ] } usage',
		options: {
			importFrom: [
				{ from: 'test/import-properties.css', type: 'css' },
				{ from: 'test/import-properties-2.css', type: 'css' }
			]
		},
		expect: 'basic.import.expect.css',
		result: 'basic.import.result.css'
	},
	'basic:import-override': {
		message: 'importFrom with { preserve: false } should override root properties',
		options: {
			preserve: false,
			importFrom: {
				customProperties: {
					'--color': 'rgb(0, 0, 0)',
					'--color-2': 'yellow',
					'--ref-color': 'var(--color)',
					'--margin': '0 10px 20px 30px',
					'--shadow-color': 'rgb(0,0,0)',
					'--z-index': 10
				}
			}
		},
		expect: 'basic.import-override.expect.css',
		result: 'basic.import-override.result.css'
	},
	'basic:export': {
		message: 'supports { exportTo: { customProperties: { ... } } } usage',
		options: {
			exportTo: (global.__exportPropertiesObject = global.__exportPropertiesObject || {
				customProperties: null
			})
		},
		expect: 'basic.expect.css',
		result: 'basic.result.css',
		after() {
			if (__exportPropertiesObject.customProperties['--color'] !== 'rgb(255, 0, 0)') {
				throw new Error('The exportTo function failed');
			}
		}
	},
	'basic:export-fn': {
		message: 'supports { exportTo() } usage',
		options: {
			exportTo(customProperties) {
				if (customProperties['--color'] !== 'rgb(255, 0, 0)') {
					throw new Error('The exportTo function failed');
				}
			}
		},
		expect: 'basic.expect.css',
		result: 'basic.result.css'
	},
	'basic:export-fn-promise': {
		message: 'supports { async exportTo() } usage',
		options: {
			exportTo(customProperties) {
				return new Promise((resolve, reject) => {
					if (customProperties['--color'] !== 'rgb(255, 0, 0)') {
						reject('The exportTo function failed');
					} else {
						resolve();
					}
				});
			}
		},
		expect: 'basic.expect.css',
		result: 'basic.result.css'
	},
	'basic:export-scss': {
		message: 'supports { exportTo: "test/export-properties.scss" } usage',
		options: {
			exportTo: 'test/export-properties.scss'
		},
		expect: 'basic.expect.css',
		result: 'basic.result.css',
		before() {
			global.__exportPropertiesString = require('fs').readFileSync('test/export-properties.scss', 'utf8');
		},
		after() {
			if (global.__exportPropertiesString !== require('fs').readFileSync('test/export-properties.scss', 'utf8')) {
				throw new Error('The original file did not match the freshly exported copy');
			}
		}
	},
	'basic:export-json': {
		message: 'supports { exportTo: "test/export-properties.json" } usage',
		options: {
			exportTo: 'test/export-properties.json'
		},
		expect: 'basic.expect.css',
		result: 'basic.result.css',
		before() {
			global.__exportPropertiesString = require('fs').readFileSync('test/export-properties.json', 'utf8');
		},
		after() {
			if (global.__exportPropertiesString !== require('fs').readFileSync('test/export-properties.json', 'utf8')) {
				throw new Error('The original file did not match the freshly exported copy');
			}
		}
	},
	'basic:export-js': {
		message: 'supports { exportTo: "test/export-properties.js" } usage',
		options: {
			exportTo: 'test/export-properties.js'
		},
		expect: 'basic.expect.css',
		result: 'basic.result.css',
		before() {
			global.__exportPropertiesString = require('fs').readFileSync('test/export-properties.js', 'utf8');
		},
		after() {
			if (global.__exportPropertiesString !== require('fs').readFileSync('test/export-properties.js', 'utf8')) {
				throw new Error('The original file did not match the freshly exported copy');
			}
		}
	},
	'basic:export-mjs': {
		message: 'supports { exportTo: "test/export-properties.mjs" } usage',
		options: {
			exportTo: 'test/export-properties.mjs'
		},
		expect: 'basic.expect.css',
		result: 'basic.result.css',
		before() {
			global.__exportPropertiesString = require('fs').readFileSync('test/export-properties.mjs', 'utf8');
		},
		after() {
			if (global.__exportPropertiesString !== require('fs').readFileSync('test/export-properties.mjs', 'utf8')) {
				throw new Error('The original file did not match the freshly exported copy');
			}
		}
	},
	'basic:export-css': {
		message: 'supports { exportTo: "test/export-properties.css" } usage',
		options: {
			exportTo: 'test/export-properties.css'
		},
		expect: 'basic.expect.css',
		result: 'basic.result.css',
		before() {
			global.__exportPropertiesString = require('fs').readFileSync('test/export-properties.css', 'utf8');
		},
		after() {
			if (global.__exportPropertiesString !== require('fs').readFileSync('test/export-properties.css', 'utf8')) {
				throw new Error('The original file did not match the freshly exported copy');
			}
		}
	},
	'basic:export-css-to': {
		message: 'supports { exportTo: { to: "test/export-properties.css" } } usage',
		options: {
			exportTo: { to: 'test/export-properties.css' }
		},
		expect: 'basic.expect.css',
		result: 'basic.result.css',
		before() {
			global.__exportPropertiesString = require('fs').readFileSync('test/export-properties.css', 'utf8');
		},
		after() {
			if (global.__exportPropertiesString !== require('fs').readFileSync('test/export-properties.css', 'utf8')) {
				throw new Error('The original file did not match the freshly exported copy');
			}
		}
	},
	'basic:export-css-to-type': {
		message: 'supports { exportTo: { to: "test/export-properties.css", type: "css" } } usage',
		options: {
			exportTo: { to: 'test/export-properties.css', type: 'css' }
		},
		expect: 'basic.expect.css',
		result: 'basic.result.css',
		before() {
			global.__exportPropertiesString = require('fs').readFileSync('test/export-properties.css', 'utf8');
		},
		after() {
			if (global.__exportPropertiesString !== require('fs').readFileSync('test/export-properties.css', 'utf8')) {
				throw new Error('The original file did not match the freshly exported copy');
			}
		}
	},
	'basic:import-is-empty': {
		message: 'supports { importFrom: {} } usage',
		options: {
			importFrom: {}
		}
	}
};


text:
..  Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

..    http://www.apache.org/licenses/LICENSE-2.0

..  Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.

Writing Logs
============

Writing Logs Locally
--------------------

Users can specify a logs folder in ``airflow.cfg`` using the
``base_log_folder`` setting. By default, it is in the ``AIRFLOW_HOME``
directory.

In addition, users can supply a remote location for storing logs and log
backups in cloud storage.

In the Airflow Web UI, local logs take precedence over remote logs. If local logs
can not be found or accessed, the remote logs will be displayed. Note that logs
are only sent to remote storage once a task completes (including failure). In other
words, remote logs for running tasks are unavailable. Logs are stored in the log
folder as ``{dag_id}/{task_id}/{execution_date}/{try_number}.log``.

.. _write-logs-amazon:

Writing Logs to Amazon S3
-------------------------

Before you begin
''''''''''''''''

Remote logging uses an existing Airflow connection to read/write logs. If you
don't have a connection properly setup, this will fail.

Enabling remote logging
'''''''''''''''''''''''

To enable this feature, ``airflow.cfg`` must be configured as in this
example:

.. code-block:: bash

    [core]
    # Airflow can store logs remotely in AWS S3. Users must supply a remote
    # location URL (starting with either 's3://...') and an Airflow connection
    # id that provides access to the storage location.
    remote_base_log_folder = s3://my-bucket/path/to/logs
    remote_log_conn_id = MyS3Conn
    # Use server-side encryption for logs stored in S3
    encrypt_s3_logs = False

In the above example, Airflow will try to use ``S3Hook('MyS3Conn')``.

.. _write-logs-azure:

Writing Logs to Azure Blob Storage
----------------------------------

Airflow can be configured to read and write task logs in Azure Blob Storage.
Follow the steps below to enable Azure Blob Storage logging.

#. Airflow's logging system requires a custom .py file to be located in the ``PYTHONPATH``, so that it's importable from Airflow. Start by creating a directory to store the config file. ``$AIRFLOW_HOME/config`` is recommended.
#. Create empty files called ``$AIRFLOW_HOME/config/log_config.py`` and ``$AIRFLOW_HOME/config/__init__.py``.
#. Copy the contents of ``airflow/config_templates/airflow_local_settings.py`` into the ``log_config.py`` file that was just created in the step above.
#. Customize the following portions of the template:

    .. code-block:: bash

        # wasb buckets should start with "wasb" just to help Airflow select correct handler
        REMOTE_BASE_LOG_FOLDER = 'wasb-<whatever you want here>'

        # Rename DEFAULT_LOGGING_CONFIG to LOGGING CONFIG
        LOGGING_CONFIG = ...

#. Make sure a Azure Blob Storage (Wasb) connection hook has been defined in Airflow. The hook should have read and write access to the Azure Blob Storage bucket defined above in ``REMOTE_BASE_LOG_FOLDER``.

#. Update ``$AIRFLOW_HOME/airflow.cfg`` to contain:

    .. code-block:: bash

        remote_logging = True
        logging_config_class = log_config.LOGGING_CONFIG
        remote_log_conn_id = <name of the Azure Blob Storage connection>

#. Restart the Airflow webserver and scheduler, and trigger (or wait for) a new task execution.
#. Verify that logs are showing up for newly executed tasks in the bucket you've defined.

.. _write-logs-gcp:

Writing Logs to Google Cloud Storage
------------------------------------

Follow the steps below to enable Google Cloud Storage logging.

To enable this feature, ``airflow.cfg`` must be configured as in this
example:

.. code-block:: bash

    [core]
    # Airflow can store logs remotely in AWS S3, Google Cloud Storage or Elastic Search.
    # Users must supply an Airflow connection id that provides access to the storage
    # location. If remote_logging is set to true, see UPDATING.md for additional
    # configuration requirements.
    remote_logging = True
    remote_base_log_folder = gs://my-bucket/path/to/logs
    remote_log_conn_id = MyGCSConn

#. Install the ``gcp_api`` package first, like so: ``pip install apache-airflow[gcp_api]``.
#. Make sure a Google Cloud Platform connection hook has been defined in Airflow. The hook should have read and write access to the Google Cloud Storage bucket defined above in ``remote_base_log_folder``.
#. Restart the Airflow webserver and scheduler, and trigger (or wait for) a new task execution.
#. Verify that logs are showing up for newly executed tasks in the bucket you've defined.
#. Verify that the Google Cloud Storage viewer is working in the UI. Pull up a newly executed task, and verify that you see something like:

    .. code-block:: bash

        *** Reading remote log from gs://<bucket where logs should be persisted>/example_bash_operator/run_this_last/2017-10-03T00:00:00/16.log.
        [2017-10-03 21:57:50,056] {cli.py:377} INFO - Running on host chrisr-00532
        [2017-10-03 21:57:50,093] {base_task_runner.py:115} INFO - Running: ['bash', '-c', u'airflow run example_bash_operator run_this_last 2017-10-03T00:00:00 --job_id 47 --raw -sd DAGS_FOLDER/example_dags/example_bash_operator.py']
        [2017-10-03 21:57:51,264] {base_task_runner.py:98} INFO - Subtask: [2017-10-03 21:57:51,263] {__init__.py:45} INFO - Using executor SequentialExecutor
        [2017-10-03 21:57:51,306] {base_task_runner.py:98} INFO - Subtask: [2017-10-03 21:57:51,306] {models.py:186} INFO - Filling up the DagBag from /airflow/dags/example_dags/example_bash_operator.py

Note the top line that says it's reading from the remote log file.


text:
require 'rails_helper'

RSpec.describe FlexibleProjectsController, type: :controller do
  before{ allow(controller).to receive(:current_user).and_return(current_user) }
  before{ CatarseSettings[:base_url] = 'http://catarse.me' }
  before{ CatarseSettings[:email_projects] = 'foo@bar.com' }
  render_views
  subject{ response }
  let(:project){ create(:project, state: 'draft', online_days: nil) }
  let!(:flexible_project) { create(:flexible_project, project: project, state: 'draft') }
  let(:current_user){ nil }

  describe "GET push_to_online" do
    let(:current_user) { project.user }

    before do
      current_user.update_attributes({
        address_city: 'foo',
        address_state: 'MG',
        address_street: 'bar',
        address_number: '123',
        address_neighbourhood: 'MMs',
        address_zip_code: '000000',
        phone_number: '33344455333'
      })
      create(:reward, project: project)
      create(:bank_account, user: current_user)
      get :push_to_online, id: flexible_project.id, locale: :pt
      flexible_project.reload
    end

    it { expect(flexible_project.open_for_contributions?).to eq(true) }
    it { expect(flexible_project.expires_at).to_not be_present }
  end

  describe "GET finish" do
    let(:current_user) { project.user }

    before do
      flexible_project.push_to_online
      get :finish, id: flexible_project.id, locale: :pt
      flexible_project.reload
    end

    it { expect(project.open_for_contributions?).to eq(true) }
    it { expect(project.expires_at).to be_nil }
  end

end


text:
var webpack = require('webpack');
var path = require('path');
var _ = require('underscore');

var getDir = function() {
  var args = Array.prototype.slice.call(arguments);
  return path.resolve.apply(path, [__dirname].concat(args));
};

var isProd = "production" === process.env["NODE_ENV"];

var cfg = {
  // webpack options
  context: getDir('./src'),

  entry: {
    index: ["./script/index_jsx.js"]
  },

  output: {
    path: getDir('./build'),
    filename: "[name].e.js",
    chunkFilename: '[id].c.js',
    publicPath: '/pomodoro/'
  },

  module: {
    loaders: [
      { test: /\.css$/, loader: "style!css"},
      { test: /\.(jpeg|png|jpg)$/, loader: "url?limit=1024" },
      { test: /_jsx\.js/, loader: "jsx" },
      {
        test: /\.scss$/,
        loader: "style!css!sass?outputStyle=expanded&" +
          "includePaths[]=" + getDir('node_modules', 'foundation-sites', 'scss')
      },
      { test: /\.(mp3|swf)$/, loader: "file?name=./f/[hash].[ext]" }
    ],

    postLoaders: [
      {
        test: /\.js$/, // include .js files
        exclude: /node_modules/, // exclude any and all files in the node_modules folder
        loader: "jshint-loader"
      }
    ]
  },

  jshint: _.defaults(
    {
      browser: true
    },
    require(path.join(__dirname, "jshintrc.js"))),

  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(true)
  ],

  resolve: {
    root: [
      getDir("src"),
      getDir('node_modules', 'foundation-sites', 'js', 'foundation')
    ],
    alias: {
      "modernizr": getDir("./node_modules/foundation-sites/js/vendor/modernizr.js"),
      "rhaboo": getDir("./node_modules/rhaboo/src/rocks/arr.js"),
      "react": getDir("./node_modules/react/addons.js"),
      "jquery": getDir("./node_modules/jquery/dist/jquery.js")
    },
    extensions: ["", ".js", ".scss"]
  },

  progress: false, // Don't show progress
  // Defaults to true

  failOnError: true // don't report error to grunt if webpack find errors

};

if (!isProd) {
  cfg.watch = true;
  cfg.keepalive = true;
  cfg.devtool = 'eval';
  cfg.jshint.devel = true;

} else {
  var plugins = [
    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': "\"" + process.env["NODE_ENV"] + "\""
      }
    }),

    new webpack.optimize.UglifyJsPlugin({
      mangle: true,
      compress: {
        warnings: false
      },
      output: {
        comments:false,
        space_colon: false
      }
    })
  ];

  cfg.plugins = cfg.plugins.concat(plugins);
}

module.exports = cfg;


text:
using LanguageExt;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reactive.Linq;
using static LanguageExt.Prelude;

namespace Echo
{
    public static partial class Process
    {
        /// <summary>
        /// Spawns a new process with N worker processes, each message is sent to one worker
        /// process in a round robin fashion.
        /// </summary>
        /// <typeparam name="T">Message type</typeparam>
        /// <param name="Name">Delegator process name</param>
        /// <param name="Count">Number of worker processes</param>
        /// <param name="Inbox">Worker message handler</param>
        /// <param name="Flags">Process flags</param>
        /// <param name="Strategy">Failure supervision strategy</param>
        /// <param name="MaxMailboxSize">Maximum inbox size</param>
        /// <returns>Process ID of the delegator process</returns>
        [EditorBrowsable(EditorBrowsableState.Never)]
        [Obsolete("spawnRoundRobin is obsolete, use Router.roundRobin instead")]
        public static ProcessId spawnRoundRobin<T>(
            ProcessName Name,
            int Count,
            Action<T> Inbox,
            ProcessFlags Flags = ProcessFlags.Default,
            State<StrategyContext, Unit> Strategy = null,
            int MaxMailboxSize = ProcessSetting.DefaultMailboxSize
            ) =>
            Router.roundRobin(Name, Count, Inbox, Flags, Strategy, MaxMailboxSize);

        /// <summary>
        /// Spawns a new process with N worker processes, each message is sent to one worker
        /// process in a round robin fashion.
        /// </summary>
        /// <typeparam name="S">State type</typeparam>
        /// <typeparam name="T">Message type</typeparam>
        /// <param name="Name">Delegator process name</param>
        /// <param name="Count">Number of worker processes</param>
        /// <param name="Inbox">Worker message handler</param>
        /// <param name="Flags">Process flags</param>
        /// <param name="Strategy">Failure supervision strategy</param>
        /// <param name="MaxMailboxSize">Maximum inbox size</param>
        /// <returns>Process ID of the delegator process</returns>
        [EditorBrowsable(EditorBrowsableState.Never)]
        [Obsolete("spawnRoundRobin is obsolete, use Router.roundRobin instead")]
        public static ProcessId spawnRoundRobin<S, T>(
            ProcessName Name,
            int Count,
            Func<S> Setup,
            Func<S, T, S> Inbox,
            ProcessFlags Flags = ProcessFlags.Default,
            State<StrategyContext, Unit> Strategy = null,
            int MaxMailboxSize = ProcessSetting.DefaultMailboxSize
            ) =>
            Router.roundRobin(Name, Count, Setup, Inbox, Flags, Strategy, MaxMailboxSize);
    }
}


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms").   Any redistribution of this code must retain the above
/// copyright and this notice and otherwise comply with the Use Terms.
/**
 * @path ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-5-15.js
 * @description Array.prototype.forEach - Date Object can be used as thisArg
 */

function testcase() {

        var result = false;
        var objDate = new Date();

        function callbackfn(val, idx, obj) {
            result = (this === objDate);
        }

        [11].forEach(callbackfn, objDate);
        return result;
    }
runTestCase(testcase);