text:
'use strict';

const _ = require('lodash');
const chai = require('chai');
const expect = chai.expect;
chai.use(require('chai-spies'));
chai.use(require('chai-string'));
chai.use(require('chai-xml'));

const Formatter = require('../src/formatter');
const inputMock = require('./mocks/input');
const outputMock = require('./mocks/output');

describe('formatter', function() {
    describe('#formatError', function() {
        it('should return a valid xml', function() {
            _.forEach(inputMock, function(input) {
                _.forEach(input.errors, function(error) {
                    const formatter = new Formatter();
                    const actualXml = formatter.formatError(error);
                    expect(actualXml).xml.to.be.valid();
                });
            });
        });

        it('should return the xml corresponding to the error', function() {
            _.forEach(inputMock, function(input, name) {
                _.forEach(input.errors, function(error, i) {
                    const formatter = new Formatter();
                    const actualXml = formatter.formatError(error);
                    expect(actualXml).to.be.equal(outputMock[name].errors[i]);
                });
            });
        });
    });

    describe('#formatFile', function() {
        it('should return a valid xml', function() {
            _.forEach(outputMock, function(mock) {
                const formatter = new Formatter();
                const errors = _.map(mock.errors, function(error) {
                    return {
                        path: mock.fullFilename,
                        xml: error
                    };
                });
                const actualXml = formatter.formatFile(mock.fullFilename, errors);
                expect(actualXml).xml.to.be.valid();
            });
        });

        it('should return an empty string when there is no error', function() {
            const formatter = new Formatter();
            expect(formatter.formatFile(outputMock.clean.fullFilename, outputMock.clean.errors))
                .to.equal('');
        });

        it('should return a file element with as many children as failure', function() {
            _.forEach(outputMock, function(mock) {
                const formatter = new Formatter();
                const errors = _.map(mock.errors, function(error) {
                    return {
                        path: mock.fullFilename,
                        xml: error
                    };
                });
                const actualXml = formatter.formatFile(mock.fullFilename, errors);
                expect(actualXml).to.have.entriesCount('<violation', errors.length);
            });
        });
    });

    describe('#formatStream', function() {
        const errors = _.flatten(_.map(outputMock, function(mock) {
            return _.map(mock.errors, function(error) {
                return {
                    path: mock.relativeFilename,
                    xml: error
                };
            });
        }));

        it('should return a valid xml', function() {
            const formatter = new Formatter();
            const actualXml = formatter.formatStream(errors);
            expect(actualXml).xml.to.be.valid();
        });

        it('should call #formatFile for each file with error', function() {
            const formatter = new Formatter();
            const spy = chai.spy.on(formatter, 'formatFile');
            formatter.formatStream(errors);
            expect(spy).to.have.been.called.exactly(2);
        });

        it('should return a pmd element with as many children as file with error', function() {
            const formatter = new Formatter();
            const actualXml = formatter.formatStream(errors);
            expect(actualXml).to.have.entriesCount('<pmd', 1);
            expect(actualXml).to.have.entriesCount('<file', 2);
        });
    });
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace KinderChat.Core.Entities
{
    public class AuthTokens
    {
        [JsonProperty("AccessToken")]
        public string AccessToken { get; set; }

        [JsonProperty("Username")]
        public string UserDeviceId { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

declare(strict_types=1);

namespace Tests\Core\Application\Configuration\NotificationPolicy\UseCase;

use Core\Application\Configuration\NotificationPolicy\UseCase\FindNotificationPolicyResponse;
use Core\Domain\Configuration\Notification\Model\NotifiedContact;
use Core\Domain\Configuration\Notification\Model\NotifiedContactGroup;
use Core\Domain\Configuration\Notification\Model\HostNotification;
use Core\Domain\Configuration\Notification\Model\ServiceNotification;
use Core\Domain\Configuration\TimePeriod\Model\TimePeriod;

beforeEach(function () {
    $hostNotification = new HostNotification(new Timeperiod(1, '24x7', '24/24 7/7'));
    $hostNotification->addEvent(HostNotification::EVENT_HOST_DOWN);

    $serviceNotification = new ServiceNotification(new Timeperiod(1, '24x7', '24/24 7/7'));
    $serviceNotification->addEvent(ServiceNotification::EVENT_SERVICE_CRITICAL);

    $this->contact = new NotifiedContact(
        2,
        'user2',
        'user 2',
        'user2@localhost',
        $hostNotification,
        $serviceNotification,
    );

    $this->contactGroup = new NotifiedContactGroup(3, 'cg3', 'cg 3');
});

it('converts given host notification models to array', function () {
    $response = new FindNotificationPolicyResponse(
        [$this->contact],
        [$this->contactGroup],
        true,
    );

    expect($response->notifiedContacts)->toBe([
        [
            'id' => $this->contact->getId(),
            'name' => $this->contact->getName(),
            'alias' => $this->contact->getAlias(),
            'email' => $this->contact->getEmail(),
            'notifications' => [
                'host' => [
                    'events' => ['DOWN'],
                    'time_period' => [
                        'id' => 1,
                        'name' => '24x7',
                        'alias' => '24/24 7/7',
                    ],
                ],
                'service' => [
                    'events' => ['CRITICAL'],
                    'time_period' => [
                        'id' => 1,
                        'name' => '24x7',
                        'alias' => '24/24 7/7',
                    ],
                ],
            ],
        ],
    ]);

    expect($response->notifiedContactGroups)->toBe([
        [
            'id' => $this->contactGroup->getId(),
            'name' => $this->contactGroup->getName(),
            'alias' => $this->contactGroup->getAlias(),
        ],
    ]);

    expect($response->isNotificationEnabled)->toBe(true);
});

it('converts given service notification models to array', function () {
    $response = new FindNotificationPolicyResponse(
        [$this->contact],
        [$this->contactGroup],
        true,
    );

    expect($response->notifiedContacts)->toBe([
        [
            'id' => $this->contact->getId(),
            'name' => $this->contact->getName(),
            'alias' => $this->contact->getAlias(),
            'email' => $this->contact->getEmail(),
            'notifications' => [
                'host' => [
                    'events' => ['DOWN'],
                    'time_period' => [
                        'id' => 1,
                        'name' => '24x7',
                        'alias' => '24/24 7/7',
                    ],
                ],
                'service' => [
                    'events' => ['CRITICAL'],
                    'time_period' => [
                        'id' => 1,
                        'name' => '24x7',
                        'alias' => '24/24 7/7',
                    ],
                ],
            ],
        ],
    ]);

    expect($response->notifiedContactGroups)->toBe([
        [
            'id' => $this->contactGroup->getId(),
            'name' => $this->contactGroup->getName(),
            'alias' => $this->contactGroup->getAlias(),
        ],
    ]);

    expect($response->isNotificationEnabled)->toBe(true);
});


text:
/*
 * floor_function.hpp
 *
 *  Created on: Dec 8, 2015
 *      Author: bdezonia
 */

#ifndef SRC_FLOOR_FUNCTION_HPP_
#define SRC_FLOOR_FUNCTION_HPP_

#include "point_function.hpp"

class FloorFunction : public PointFunction {
public:
	FloorFunction(const std::shared_ptr<PointFunction>& other);

	~FloorFunction();

    double evaluate(const size_t dim, const double* point) const;

    bool acceptsDimensionality(const size_t d) const;

private:
    std::shared_ptr<PointFunction> f;
};

#endif /* SRC_FLOOR_FUNCTION_HPP_ */


text:
<?php

  namespace osCommerce\OM\Core\Site\Admin\Application\Languages\SQL\PostgreSQL;

  use osCommerce\OM\Core\Registry;

/**
 * @since v3.0.3
 */

  class Get {
    public static function execute($data) {
      $OSCOM_PDO = Registry::get('PDO');

      $sql_query = 'select l.*, (select count(*) from :table_languages_definitions ld where ld.languages_id = l.languages_id) as total_definitions from :table_languages l where';

      if ( is_numeric($data['id']) ) {
        $sql_query .= ' l.languages_id = :languages_id';
      } else {
        $sql_query .= ' l.code = :code';
      }

      $sql_query .= ' limit 1';

      $Qlanguage = $OSCOM_PDO->prepare($sql_query);

      if ( is_numeric($data['id']) ) {
        $Qlanguage->bindInt(':languages_id', $data['id']);
      } else {
        $Qlanguage->bindValue(':code', $data['id']);
      }

      $Qlanguage->execute();

      return $Qlanguage->fetch();
    }
  }
?>


text:
from setuptools import setup

setup(
    name='cb-event-duplicator',
    version='1.2.0',
    packages=['cbopensource', 'cbopensource.tools', 'cbopensource.tools.eventduplicator'],
    url='https://github.com/carbonblack/cb-event-duplicator',
    license='MIT',
    author='Bit9 + Carbon Black Developer Network',
    author_email='dev-support@bit9.com',
    description='Extract events from one Carbon Black server and send them to another server ' +
                '- useful for demo/testing purposes',
    install_requires=[
        'requests==2.7.0',
        'paramiko<2.0',
        'psycopg2==2.6.1'
    ],
    entry_points={
        'console_scripts': ['cb-event-duplicator=cbopensource.tools.eventduplicator.data_migration:main']
    },
    classifiers=[
        'Development Status :: 4 - Beta',

        # Indicate who your project is intended for
        'Intended Audience :: Developers',

        # Pick your license as you wish (should match "license" above)
        'License :: OSI Approved :: MIT License',

        # Specify the Python versions you support here. In particular, ensure
        # that you indicate whether you support Python 2, Python 3 or both.
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.5',
    ],
    keywords='carbonblack',

)


text:
package burlap.oomdp.stateserialization;

import burlap.oomdp.core.states.State;

/**
 * A factory interface for generating {@link burlap.oomdp.stateserialization.SerializableState} instances from an input
 * {@link burlap.oomdp.core.states.State} by using the {@link #serialize(burlap.oomdp.core.states.State)} method. This
 * interface requires a {@link #getGeneratedClass()} method that reports the specific {@link burlap.oomdp.stateserialization.SerializableState}
 * implementation that is returned so that complex classes that have {@link burlap.oomdp.core.states.State} instances
 * to be turned into a {@link burlap.oomdp.stateserialization.SerializableState} can map them to the appropriate class type.
 * @author James MacGlashan.
 */
public interface SerializableStateFactory {

	/**
	 * Takes a {@link burlap.oomdp.core.states.State} and turns it into a {@link burlap.oomdp.stateserialization.SerializableState}.
	 * @param s the input {@link burlap.oomdp.core.states.State} to convert.
	 * @return a {@link burlap.oomdp.stateserialization.SerializableState}
	 */
	SerializableState serialize(State s);

	/**
	 * Returns the {@link burlap.oomdp.stateserialization.SerializableState} implementation that is generated by this factory.
	 * @return the {@link java.lang.Class} of the {@link burlap.oomdp.stateserialization.SerializableState} implementation that is generated by this factory.
	 */
	Class<?> getGeneratedClass();
}


text:
typedef unsigned char uint8_t;
typedef uint8_t u_int8_t;
typedef unsigned short uint16_t;
typedef uint16_t u_int16_t;
typedef unsigned uint32_t;
typedef uint32_t u_int32_t;
typedef unsigned long long uint64_t;
typedef uint64_t u_int64_t;
#define snprintf _snprintf
#define __attribute__(unused)
#elif defined(__sun)
typedef uint8_t u_int8_t;
typedef uint16_t u_int16_t;
typedef uint32_t u_int32_t;
typedef uint64_t u_int64_t;
#else
#include <stdint.h>
#endif

#define explicit_bzero(s,n) memset(s, 0, n)
#define DEF_WEAK(f)

int bcrypt_hashpass(const char *key, const char *salt, char *encrypted, size_t encryptedlen);
int encode_base64(char *, const u_int8_t *, size_t);
int timingsafe_bcmp(const void *b1, const void *b2, size_t n);
int bcrypt_pbkdf(const char *pass, size_t passlen, const uint8_t *salt, size_t saltlen, uint8_t *key, size_t keylen, unsigned int rounds);

#endif


text:
#ifndef SRC_BGP_ROUTING_POLICY_ROUTING_POLICY_H_
#define SRC_BGP_ROUTING_POLICY_ROUTING_POLICY_H_

#include <boost/scoped_ptr.hpp>
#include <boost/intrusive_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include <tbb/atomic.h>
#include <tbb/mutex.h>
#include <sandesh/sandesh_trace.h>

#include <list>
#include <map>
#include <string>
#include <utility>
#include <vector>

#include "base/lifetime.h"
#include "base/util.h"
#include "bgp/bgp_common.h"
#include "db/db_table.h"

class BgpAttr;
class BgpPath;
class BgpRoute;
class BgpServer;
class BgpTable;
class RoutingPolicyMgr;
class BgpRoutingPolicyConfig;
class RoutingInstance;
class RoutingPolicyMatch;
class RoutingPolicyAction;
class RoutingPolicyTermConfig;
class TaskTrigger;

// Routing Policy Manager
// This class implements the routing policy for control node.
// It maintains the list of routing policies configured on the system
// It provides API to lookup the routing policy by name.
//
// A mutex is used to serialize access from multiple bgp::ConfigHelper tasks.
//
// It provides two APIs to apply routing policy on the routes belonging to given
// routing instance.
// 1. ApplyRoutingPolicy
//    Apply routing policy on the routing instance passed as input.
//    To achieve this Routing policy manager walks all the routing tables of
//    the routing instance. On each route encountered during the walk, policy
//    is evaluated using EvaluateRoutingPolicy. EvaluateRoutingPolicy visits
//    all the BgpPath and apply all routing policies of that routing instance
//    on that BgpPath.
//
// 2. ExecuteRoutingPolicy
//     This function is called on the given route + path from two code path.
//     First one is from InsertPath. i.e. when new path is being added to a
//     route.
//     Second path is from DBTable walk context while applying the routing
//     policy on routing instance.  This function calls the operator() of the
//     policy in input to match and apply the action on successful match.
//
//
// RoutingPolicyManager takes a delete reference of BgpServer.
//
// RoutingPolicy
//
// This represents one Routing Policy in operational data.
// Each routing policy has multiple policy terms (represented using PolicyTerm
// class) represented as ordered list using std::list.
//
// Routing Policy object takes lifetime reference of RoutingPolicyMgr.
//
// Reference to RoutingPolicy object is done using intrusive pointer which
// keeps track of ref_count.
// The DeleteActor of the RoutingPolicy uses this ref_count to allow/disallow
// delete of the RoutingPolicy object. On last dereference of the RoutingPolicy
// object, RetryDelete on the DeleteActor is triggered.
//
// RoutingPolicy is removed from the name-map in RoutingPolicyMgr  only in
// Destroy method of DeleteActor. It is possible that config might have revived
// the RoutingPolicy object with same name(with same or different config).
// In such case, RoutingPolicyMgr recreate the routing policy based on the
// new config object.
//
// RoutingPolicy object provided operator() to apply the policy on a
// BgpRoute+BgpPath. In this operator overload function, route is processed
// against each policy term till a terminal rule is encountered.
// A terminal rule is a term where action on successful match is to Reject or
// Accept the route. Return value gives the hint of result of policy apply.
// Result is represented as a pair with first element representing whether the
// match was for terminal rule and second element indicating whether there
// was a policy match.
//
// RoutingPolicy object is updated on config update function in UpdateConfig
// method. This method walks newly configured policy term list and existing
// policy term list and compares the PolicyTerm to see whether
//    a. Policy term matches (Done using operator==() function on PolicyTerm).
//       If no match is found, new PolicyTerm as per new config is created and
//       inserted in to ordered list of PolicyTerm.
//    b. New policy Term is inserted
//    c. Existing policy term is deleted
// At the end of the update, generation number of the policy term is updated to
// indicate config change to Routing Policy. Routing Instances referring to
// this policy is not triggered from this path. It is expected that
// BgpConfigListener infra would put the RoutingInstance to the change_list when
// the routing policy it is referring undergoes a change.
//
// Routing Instance
// Routing instance maintains ordered list of routing policies that it refers.
// This is represented as std::list of pair<RoutingPolicyPtr, gen-id of policy>.
// Please note RoutingPolicyPtr is an intrusive pointer to RoutingPolicy object.
//
// While processing the routing policies on each routes belonging to this
// instance, each of routing policies are applied till terminal rule is hit.
// BgpRoute is update with all policy actions from the matching policy term.
// Policy action is stored in BgpPath (in flag ond/or in BgpAttr)
//
// Update of the routing instance checks whether the routing policy list on the
// instance has changed. This process checks for following
//   a. If a routing policy order is update
//   b. If new routing policy(ies) are added to the routing policy list
//   c. If existing routing policy(ies) are removed from the routing policy list
//   d. If the routing policies that it is referring has undergone config change
//      This is done by checking the generation number of routing policy that
//      is applied on the routing instance.
// In case the routing policy is updated on the routing instance
// (if either of (a) to (d) above is true), all the BgpTables belonging to the
// routing instance is walked to reapply the routing policy.
//
// BgpRoute/BgpPath
// BgpPath maintains original BgpAttribute that it received in a new field
// called as original_attr_. The path attribute attr_ represents the
// BgpAttribute after applying the policy.
// New flag is introduced to indicate if the path is rejected by routing policy.
//
// PolicyTerm
// Policy Term has two ordered lists
//      1. Match conditions
//      2. Actions
//
// PolicyTerm class provides accessor method to get list of matches and actions.
// It also provides compare function (operator==()) to check whether two policy
// terms matches/same. It would return true if each policy term has same match
// set(ordered list) and same action list(ordered).
//
// Policy action is represented as ordered list of action to be taken on
// successful match. The top of the action list indicates what should be done
// with route on successful match. e.g. Accept/Reject/NextTerm.
// Subsequent entry in this list are the update action to be taken on policy
// match.
//
// Match Condition
// RoutingPolicyMatch is the abstract base class to implement a match condition.
// This abstract class provides Match() function to compare the route + Path
// attribute with match condition. The derived class provides implementation
// to compare the route + attribute with match condition. Another method of this
// class is comparator function operator==(). This method compares whether two
// match conditions are same. This is done by comparing the typeid() (RTTI) and
// calling IsEqual pure virtual method if type ids are same.
//
// All match conditions inherit this RoutingPolicyMatch and provide
// implementation of pure virtual methods.
// In the current release, match is supported on Community and prefix.
//
// MatchCommunity implements match for community value
// MatchPrefix provides templetized implementation for matching prefix.
// Currently PrefixMatchInet and PrefixMatchInet6 implementation is supported
// to match inet and inet6 routes.
//
// Policy Action
// RoutingPolicyAction is the abstract base class for implementing the policy
// action.
// Action is represented as
//      RoutingPolicyNexTermAction,
//      RoutingPolicyRejectAction,
//      RoutingPolicyAcceptAction or
//      RoutingPolicyUpdateAction
// This represents NextTerm, Reject, accept and route update action respectively
// RoutingPolicyRejectAction & RoutingPolicyAcceptAction as Terminal actions.
// RoutingPolicyNexTermAction and RoutingPolicyAcceptAction may/may not have
// RoutingPolicyUpdateAction associated with it.
// RoutingPolicyUpdateAction represents the modification done to path attribute
// on successful match.
// RoutingPolicyAction provides comparator function to check whether two actions
// are same. This is done by comparing the typeid() of the object and invoking
// IsEqual when typeid() is same.
// RoutingPolicyUpdateAction which inherits the RoutingPolicyAction provides the
// pure virtual method operator() to apply update action on BgpAttr.
// Currently support for updating the local-pref and community list is supported
// for update action.
// UpdateCommunity supports add/remove/set list of
// community to incoming BgpAttr.
//
class PolicyTerm {
public:
    typedef std::vector<RoutingPolicyAction *> ActionList;
    typedef std::vector<RoutingPolicyMatch *> MatchList;
    PolicyTerm();
    ~PolicyTerm();
    bool terminal() const;
    bool ApplyTerm(const BgpRoute *route,
                   const BgpPath *path, BgpAttr *attr) const;
    void set_actions(const ActionList &actions) {
        actions_ = actions;
    }
    void set_matches(const MatchList &matches) {
        matches_ = matches;
    }
    const MatchList &matches() const {
        return matches_;
    }
    const ActionList &actions() const {
        return actions_;
    }
    bool operator==(const PolicyTerm &term) const;

private:
    MatchList matches_;
    ActionList actions_;
};

class RoutingPolicy {
public:
    typedef boost::shared_ptr<PolicyTerm>  PolicyTermPtr;
    typedef std::list<PolicyTermPtr> RoutingPolicyTermList;
    typedef std::pair<bool, bool> PolicyResult;
    RoutingPolicy(std::string name, BgpServer *server,
                    RoutingPolicyMgr *mgr,
                    const BgpRoutingPolicyConfig *config);
    virtual ~RoutingPolicy();
    void ProcessConfig();
    void UpdateConfig(const BgpRoutingPolicyConfig *config);
    void ClearConfig();
    void Shutdown();

    bool MayDelete() const;
    void RetryDelete();
    void ManagedDelete();
    LifetimeActor *deleter();
    const LifetimeActor *deleter() const;
    bool deleted() const;

    const std::string &name() const { return name_; }
    const BgpRoutingPolicyConfig *config() const { return config_; }
    const RoutingPolicyMgr *manager() const { return mgr_; }

    BgpServer *server() { return server_; }
    const BgpServer *server() const { return server_; }

    RoutingPolicyTermList *terms() { return &terms_; }
    const RoutingPolicyTermList &terms() const { return terms_; }
    void add_term(PolicyTermPtr term) {
        terms_.push_back(term);
    }

    PolicyResult operator()(const BgpRoute *route,
                            const BgpPath *path, BgpAttr *attr) const;
    uint32_t generation() const { return generation_; }
    uint32_t refcount() const { return refcount_; }

private:
    friend class RoutingPolicyMgr;
    class DeleteActor;
    friend void intrusive_ptr_add_ref(RoutingPolicy *policy);
    friend void intrusive_ptr_release(RoutingPolicy *policy);

    PolicyTermPtr BuildTerm(const RoutingPolicyTermConfig &term);
    std::string name_;
    BgpServer *server_;
    RoutingPolicyMgr *mgr_;
    const BgpRoutingPolicyConfig *config_;
    boost::scoped_ptr<DeleteActor> deleter_;
    LifetimeRef<RoutingPolicy> manager_delete_ref_;

    // Updated when routing policy undergoes a change
    tbb::atomic<uint32_t> refcount_;
    uint32_t generation_;
    RoutingPolicyTermList terms_;
};

inline void intrusive_ptr_add_ref(RoutingPolicy *policy) {
    policy->refcount_.fetch_and_increment();
    return;
}

inline void intrusive_ptr_release(RoutingPolicy *policy) {
    int prev = policy->refcount_.fetch_and_decrement();
    if (prev == 1) {
        if (policy->MayDelete())
            policy->RetryDelete();
    }
}

class RoutingPolicyMgr {
public:
    typedef std::map<std::string, RoutingPolicy*> RoutingPolicyList;
    typedef RoutingPolicyList::iterator name_iterator;
    typedef RoutingPolicyList::const_iterator const_name_iterator;
    typedef std::map<BgpTable *,
            DBTable::DBTableWalkRef> RoutingPolicyWalkRequests;

    explicit RoutingPolicyMgr(BgpServer *server);
    virtual ~RoutingPolicyMgr();
    SandeshTraceBufferPtr trace_buffer() const { return trace_buf_; }

    name_iterator name_begin() { return routing_policies_.begin(); }
    name_iterator name_end() { return routing_policies_.end(); }
    name_iterator name_lower_bound(const std::string &name) {
        return routing_policies_.lower_bound(name);
    }
    const_name_iterator name_cbegin() { return routing_policies_.begin(); }
    const_name_iterator name_cend() { return routing_policies_.end(); }
    const_name_iterator name_clower_bound(const std::string &name) {
        return routing_policies_.lower_bound(name);
    }

    RoutingPolicy *GetRoutingPolicy(const std::string &name) {
        name_iterator it;
        if ((it = routing_policies_.find(name)) != routing_policies_.end()) {
            return it->second;
        }
        return NULL;
    }
    const RoutingPolicy *GetRoutingPolicy(const std::string &name) const {
        const_name_iterator it;
        if ((it = routing_policies_.find(name)) != routing_policies_.end()) {
            return it->second;
        }
        return NULL;
    }

    virtual RoutingPolicy *CreateRoutingPolicy(
                             const BgpRoutingPolicyConfig *config);
    void UpdateRoutingPolicy(const BgpRoutingPolicyConfig *config);
    virtual void DeleteRoutingPolicy(const std::string &name);

    bool deleted();
    void ManagedDelete();

    void DestroyRoutingPolicy(RoutingPolicy *policy);

    size_t count() const { return routing_policies_.size(); }
    BgpServer *server() { return server_; }
    const BgpServer *server() const { return server_; }
    LifetimeActor *deleter();

    RoutingPolicy::PolicyResult ExecuteRoutingPolicy(
        const RoutingPolicy *policy, const BgpRoute *route,
        const BgpPath *path, BgpAttr *attr) const;

    // Update the routing policy list on attach point
    bool UpdateRoutingPolicyList(const RoutingPolicyConfigList &cfg_list,
                                       RoutingPolicyAttachList *oper_list);

    // RoutingInstance is updated with new set of policies. This function
    // applies that policy on each route of this routing instance
    void ApplyRoutingPolicy(RoutingInstance *instance);

    void RequestWalk(BgpTable *table);
    void WalkDone(DBTableBase *dbtable);
    bool EvaluateRoutingPolicy(DBTablePartBase *root, DBEntryBase *entry);

private:
    class DeleteActor;

    BgpServer *server_;
    tbb::mutex mutex_;
    RoutingPolicyList routing_policies_;
    boost::scoped_ptr<DeleteActor> deleter_;
    LifetimeRef<RoutingPolicyMgr> server_delete_ref_;
    RoutingPolicyWalkRequests routing_policy_sync_;
    SandeshTraceBufferPtr trace_buf_;
};

#endif  // SRC_BGP_ROUTING_POLICY_ROUTING_POLICY_H_


text:
<?php

namespace Autodns\Tool;

class XmlToArrayConverter
{
    /**
     * @param string $xmlString
     * @return array
     */
    public function convert($xmlString)
    {
        $xml = simplexml_load_string($xmlString);
        $json = json_encode($xml);
        return json_decode($json, true);
    }
}


text:
package org.cagrid.gaards.dorian.policy;

import java.io.IOException;

import javax.xml.namespace.QName;

import org.apache.axis.Constants;
import org.apache.axis.encoding.SerializationContext;
import org.apache.axis.encoding.Serializer;
import org.apache.axis.wsdl.fromJava.Types;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Element;
import org.xml.sax.Attributes;

public class HostAgreementSerializer implements Serializer {

    protected static Log LOG = LogFactory.getLog(HostAgreementSerializer.class.getName());

    public void serialize(QName name, Attributes attributes, Object value, SerializationContext context)
        throws IOException {

        try {
            // context.setPretty(false);
            context.setWriteXMLType(null);
            context.writeString(PolicyUtils.hostAgreementToString((HostAgreement) value));
            context.setWriteXMLType(null);
            // context.writeDOMElement(SAMLUtils.samlAssertionToDOM((SAMLAssertion
            // ) value));
        } catch (Exception e) {
            LOG.error("Error writing HostAgreement to DOM.", e);
        }
    }

    public String getMechanismType() {
        return Constants.AXIS_SAX;
    }

    /**
     * Return XML schema for the specified type, suitable for insertion into the
     * <types> element of a WSDL document, or underneath an
     * <element> or <attribute> declaration.
     *
     * @param javaType
     *            the Java Class we're writing out schema for
     * @param types
     *            the Java2WSDL Types object which holds the context for the
     *            WSDL being generated.
     * @return a type element containing a schema simpleType/complexType
     * @see org.apache.axis.wsdl.fromJava.Types
     */
    public Element writeSchema(Class javaType, Types types) throws Exception {
        return null;
    }
}


text:
class CombinationIndex
  attr_reader :element_lists

  def initialize(element_lists)
    @element_lists = element_lists
  end

  def [](index_or_range)
    if index_or_range.class == Range
      index_or_range.to_a.map { |index| _single_combination(index) }
    else
      _single_combination(index_or_range)
    end
  end

  def sample(quantity=1)
    return _sample_one if quantity == 1
    result = []
    quantity.times { result << _sample_one }
    result
  end

  def size
    _element_list_sizes.reduce(:*)
  end

  def _sample_one
    self[rand(size)]
  end
  # converts a single index to several indexes
  # ie converts from base ten (index) to a mixed base value
  # with each place (element array) being a new base (size of the element array)
  def _multi_array_indexes(i)
    element_list_sizes_tmp = _element_list_sizes
    array_indexes = []

    while element_list_size = element_list_sizes_tmp.pop
      i, remainder = i.divmod(element_list_size)
      array_indexes.unshift remainder
    end

    array_indexes
  end

  def _element_list_sizes
    element_lists.map(&:size)
  end

  def _single_combination(i)
    combination = ""
    element_list_indexes = _multi_array_indexes(i)

    element_lists.each do |element_list|
      element_list_index = element_list_indexes.shift
      combination += element_list[element_list_index]
    end

    combination
  end
end


text:
<?php

namespace App\G6K\Manager\Json\JsonSQL;

use App\G6K\Manager\Json\JsonSQL;

/**
 *  The class JsonSQLStatement represents a prepared statement and,
 *  after the statement is executed, an associated result set.
 */
abstract class Statement  {

	/**
	 * @var \App\G6K\Manager\Json\JsonSQL $jsonsql the JsonSQL instance
	 *
	 * @access  protected
	 *
	 */
	protected $jsonsql = null;

	/**
	 * @var object $request The prepared statement
	 *
	 * @access  protected
	 *
	 */
	protected $request = null;

	/**
	 * @var array $result The result set
	 *
	 * @access  protected
	 *
	 */
	protected $result = null;

	/**
	 * @var int $rowCount The number of rows affected by the last SQL statement
	 *
	 * @access  protected
	 *
	 */
	protected $rowCount = null;

	/**
	 * @var array      $params The list of parameters to be bound
	 *
	 * @access  protected
	 *
	 */
	protected $params = array();

	/**
	 * @var \App\G6K\Manager\Json\JsonSQL\Engine $engine The JsonSQL engine
	 *
	 * @access  protected
	 *
	 */
	protected $engine = null;

	/**
	 * Class Constructor
	 *
	 * @access protected
	 * @param JsonSQL $jsonsql The JsonSQL instance
	 * @param \stdClass $request The prepared statement
	 */
	protected function __construct(JsonSQL $jsonsql, \stdClass &$request) {
		$this->jsonsql = $jsonsql;
		$this->engine = $jsonsql->getEngine();
		$this->request = $request;
		$this->result = array();
		$this->rowCount = 0;
	}

	/**
	 * Statement factory
	 *
	 * @access public
	 * @static
	 * @param JsonSQL $jsonsql The JsonSQL instance
	 * @param \stdClass &$request The prepared statement
	 */
	public function create(JsonSQL $jsonsql, \stdClass &$request) {
		switch($request->statement) {
			case 'select':
			case 'compound select':
			case 'insert':
			case 'update':
			case 'delete':
			case 'truncate':
				return new DMLStatement($jsonsql, $request);
			case 'create table':
			case 'alter table':
			case 'drop table':
				return new DDLStatement($jsonsql, $request);
			default:
				throw new JsonSQLException("Unexpected statement : " . $request->statement);

		}
	}

	/**
	 * Binds a value to a corresponding named or question mark placeholder
	 * in the SQL statement that was used to prepare the statement.
	 *
	 * @access public
	 * @param mixed $parameter The parameter identifier
	 * @param  mixed $value The value to bind to the parameter
	 * @param int $type The data type for the parameter using the PDO::PARAM_* constants.
	 * @return bool true on success or false on failure.
	 */
	public function bindValue($parameter, $value, $type=\PDO::PARAM_STR) {
		$this->checkValue($value);
		$value = $this->engine->quote($value, $type);
		if (in_array($this->request->statement, array('select', 'delete'))) {
			if (is_int($parameter)) {
				$this->request->where = preg_replace_callback("/\?/",
					function($found) use ($parameter, $value) {
						$parameter--;
						if ($parameter==0) return preg_replace("/\?/", $value, reset($found));
						return reset($found);
					}, $this->request->where, $parameter);
				return true;
			} elseif (preg_match("/^\:/", $parameter)) {
				$this->request->where = preg_replace('/\\'.$parameter.'/', $value, $this->request->where);
				return true;
			}
		} elseif ($this->request->statement == 'insert') {
			if (is_int($parameter)) {
				foreach($this->request->values as $v => $val) {
					if ($val == '?')  {
						$parameter--;
						if ($parameter == 0) {
							$this->request->values[$v] = $value;
							return true;
						}
					}
				}
			} elseif (preg_match("/^\:/", $parameter)) {
				foreach($this->request->values as $v => $val) {
					if ($val == $parameter)  {
						$this->request->values[$v] = $value;
						return true;
					}
				}
			}
		}
		return false;
	}

	/**
	 * Binds a PHP variable to a corresponding named or question mark placeholder
	 * in the SQL statement that was used to prepare the statement.
	 * the variable is bound as a reference and will only be evaluated
	 * at the time that execute() is called.
	 *
	 * @access public
	 * @param mixed $parameter The parameter identifier
	 * @param  mixed &$variable The variable to bind to the parameter
	 * @param int $type The data type for the parameter using the PDO::PARAM_* constants.
	 * @return bool true on success or false on failure.
	 */
	public function bindParam($parameter, &$variable, $type=\PDO::PARAM_STR) {
		$this->params[] = array($parameter, &$variable, $type);
		return true;
	}

	/**
	 * Executes a prepared statement.
	 *
	 * @access public
	 * @param array $parameters An array of values with as many elements as there are bound parameters
	 * in the SQL statement being executed. All values are treated as PDO::PARAM_STR.
	 * @return bool true on success or false on failure.
	 */
	public function execute($parameters = array()) {
		foreach($parameters as $parameter => $value) {
			if (!$this->bindValue($parameter, $value)) {
				return false;
			}
		}
		foreach($this->params as $param) {
			if (!$this->bindValue($param[0], $param[1], $param[2])) {
				return false;
			}
		}
		if ($this->request->statement == 'compound select') {
			return $this->executeCompoundSelect();
		} elseif ($this->request->statement == 'select') {
			return $this->executeSelect();
		} elseif ($this->request->statement == 'insert') {
			return $this->executeInsert();
		} elseif ($this->request->statement == 'update') {
			return $this->executeUpdate();
		} elseif ($this->request->statement == 'delete') {
			return $this->executeDelete();
		} elseif ($this->request->statement == 'create table') {
			return $this->executeCreateTable();
		} elseif ($this->request->statement == 'alter table') {
			return $this->executeAlterTable();
		} elseif ($this->request->statement == 'truncate') {
			return $this->executeTruncate();
		} elseif ($this->request->statement == 'drop table') {
			return $this->executeDropTable();
		}
		$this->params = array();
		return false;
	}

	/**
	 * Returns the number of rows affected by the last SQL statement
	 *
	 * @access public
	 * @return int The number of rows.
	 */
	public function rowCount() {
		return $this->rowCount;
	}

	/**
	 * Returns the number of columns in the result set
	 *
	 * @access public
	 * @return int The number of columns in the result set.
	 * If there is no result set, returns 0.
	 */
	public function columnCount() {
		return $this->rowCount > 0 ? count($this->result[0]) : 0;
	}

	/**
	 * Checks if a value corresponds to its type and if it is safety in case of string
	 *
	 * @access protected
	 * @param string $value The value
	 * @param int $type The expected type
	 * @return void
	 * @throws JsonSQLException
	 */
	protected function checkValue($value, $type=\PDO::PARAM_STR) {
		if ($type == \PDO::PARAM_INT) {
			if (!is_int($value)) {
				throw new JsonSQLException("syntax error : int value expected");
			}
		} elseif ($type == \PDO::PARAM_BOOL) {
			if (!is_bool($value)) {
				throw new JsonSQLException("syntax error : bool value expected");
			}
		} else {
			$dmlparser = new DMLParser($this->jsonsql, "");
			$dmlparser->checkSafety($value);
		}
	}

	/**
	 * Executes a prepared select statement with set opertations.
	 *
	 * @access protected
	 * @return bool Always true.
	 */
	abstract protected function executeCompoundSelect();

	/**
	 * Executes a prepared select statement.
	 *
	 * @access protected
	 * @return bool Always true.
	 */
	abstract protected function executeSelect();

	/**
	 * Executes a prepared insert statement.
	 *
	 * @access protected
	 * @return bool Always true.
	 */
	abstract protected function executeInsert();

	/**
	 * Executes a prepared update statement.
	 *
	 * @access protected
	 * @return bool Always true.
	 */
	abstract protected function executeUpdate();

	/**
	 * Executes a prepared delete statement.
	 *
	 * @access protected
	 * @return bool Always true.
	 */
	abstract protected function executeDelete();

	/**
	 * Executes a prepared 'create table' statement.
	 *
	 * @access protected
	 * @return bool TRUE.
	 */
	abstract protected function executeCreateTable();

	/**
	 * Executes a prepared 'alter table' statement.
	 *
	 * @access protected
	 * @return bool TRUE.
	 */
	abstract protected function executeAlterTable();

	/**
	 * Executes a prepared 'truncate' statement.
	 *
	 * @access protected
	 * @return bool Always true.
	 */
	abstract protected function executeTruncate();

	/**
	 * Executes a prepared 'drop table' statement.
	 *
	 * @access protected
	 * @return bool TRUE.
	 */
	abstract protected function executeDropTable();

}

?>


text:
/*******************************************************************************
file: interbrack.js
project: Bracket Advisor
date: February 2014
authors: P. Bustamante

*******************************************************************************/

$(document).ready(function(){ // begin document.ready block

	//document.write("hello javascript");

	$('#holding').load('js/interbrack.js', function() {
			console.log("it worked");
	});

/*
  $.ajax({
        url: "interbrack.php",
        type: "post",
        //data: values,
        success: function(data){
        	console.log(data);
        },
        error:function(){
            alert("failure");
            //$("#result").html('There is an error submitting');
        }
    });
*/

	$('#gobtn').on('click', function() {
				$('#holding').load('incl/leaderboard.php?t1='+curteam1+'&t2='+curteam2+'&t1name='+team1name+'&t2name='+team2name, function() {
					$('#holding').hide();
			    });
	});

}); // end document.ready block


text:
==================
BlueprintMigration
==================

.. autoclass:: canvasapi.blueprint.BlueprintMigration
	:members:

=====================
BlueprintSubscription
=====================

.. autoclass:: canvasapi.blueprint.BlueprintSubscription
	:members:

=================
BlueprintTemplate
=================

.. autoclass:: canvasapi.blueprint.BlueprintTemplate
    :members:

============
ChangeRecord
============

.. autoclass:: canvasapi.blueprint.ChangeRecord
    :members:


text:
@interface SSStatusSymbolView()
@property (nonatomic,strong) CAShapeLayer *statusLayer;

@end

@implementation SSStatusSymbolView

- (instancetype)initWithTapedHandler:(viewTapedHandler)tapedHandler tapedActionHandler:(viewTapedActionHandler)tapedActionHandler
{
    self = [super initWithTapedHandler:tapedHandler tapedActionHandler:tapedActionHandler];
    if (!self) return nil;

    _symbolViewSize = CGSizeMake(25, 25);
    _strokeColor = [UIColor redColor];
    _strokeLineWidth = 3.0f;

    [self setBackgroundColor:[UIColor clearColor]];
    [self.layer addSublayer:self.statusLayer];

    return self;
}

- (void)setStrokeColor:(UIColor *)strokeColor
{
    _strokeColor = strokeColor;
    _statusLayer.strokeColor = strokeColor.CGColor;
}

- (void)setStrokeLineWidth:(CGFloat)strokeLineWidth
{
    _strokeLineWidth = strokeLineWidth;
    _statusLayer.lineWidth = strokeLineWidth;
}

- (void)setSymbolViewSize:(CGSize)symbolViewSize
{
    _symbolViewSize = symbolViewSize;
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];

    CGFloat x = (CGRectGetWidth(self.frame) - _symbolViewSize.width) / 2;
    CGFloat y = (CGRectGetHeight(self.frame) - _symbolViewSize.height) / 2;

    _statusLayer.frame = CGRectMake(x, y, _symbolViewSize.width, _symbolViewSize.height);
    _statusLayer.path = [self statusSymbolViewPath];
}

- (CGPathRef)statusSymbolViewPath
{
    CGFloat centerx = _symbolViewSize.width / 2;
    CGFloat centery = _symbolViewSize.height / 2;
    CGFloat r = _symbolViewSize.width / 2;

    UIBezierPath *bezierPath = [UIBezierPath bezierPath];
    [bezierPath moveToPoint:CGPointMake(centerx, 0)];
    [bezierPath addArcWithCenter:CGPointMake(centerx, centery) radius:r startAngle:- M_PI_2 endAngle:M_PI * 2 - M_PI_2 clockwise:YES];

    switch (_type)
    {
        case SSStatusViewTypeSymbolSuccess:
        {
            CGSize symbolSize = CGSizeMake(SSSTATUS_SYMBOL_XFACTOR(26), SSSTATUS_SYMBOL_YFACTOR(30));
            CGFloat x = (_symbolViewSize.width - symbolSize.width) / 2;
            CGFloat y = (_symbolViewSize.height - symbolSize.height) / 2;

            [bezierPath moveToPoint:CGPointMake(x, y + SSSTATUS_SYMBOL_YFACTOR(16))];
            [bezierPath addLineToPoint:CGPointMake(x + SSSTATUS_SYMBOL_XFACTOR(10), y + SSSTATUS_SYMBOL_YFACTOR(26))];
            [bezierPath addLineToPoint:CGPointMake(x + SSSTATUS_SYMBOL_XFACTOR(27), y + SSSTATUS_SYMBOL_YFACTOR(9))];
        }
            break;
        case SSStatusViewTypeSymbolError:
        {
            CGSize symbolSize = CGSizeMake(SSSTATUS_SYMBOL_XFACTOR(23), SSSTATUS_SYMBOL_XFACTOR(23));
            CGFloat x = (_symbolViewSize.width - symbolSize.width) / 2;
            CGFloat y = (_symbolViewSize.height - symbolSize.height) / 2;

            [bezierPath moveToPoint:CGPointMake(x, y)];
            [bezierPath addLineToPoint:CGPointMake(x + symbolSize.width, y + symbolSize.height)];
            [bezierPath moveToPoint:CGPointMake(x + symbolSize.width, y)];
            [bezierPath addLineToPoint:CGPointMake(x, y + symbolSize.height)];
        }
            break;
        case SSStatusViewTypeSymbolAlert:
        {
            CGSize symbolSize = CGSizeMake(SSSTATUS_SYMBOL_XFACTOR(35), SSSTATUS_SYMBOL_YFACTOR(35));
            CGFloat x = (_symbolViewSize.width - symbolSize.width) / 2;
            CGFloat y = (_symbolViewSize.height - symbolSize.height) / 2;

            CGFloat internalR = _statusLayer.lineWidth / 4;
            CGFloat acenterx = x + symbolSize.width / 2;

            [bezierPath moveToPoint:CGPointMake(acenterx, y + SSSTATUS_SYMBOL_YFACTOR(8))];
            [bezierPath addArcWithCenter:CGPointMake(acenterx, y + SSSTATUS_SYMBOL_YFACTOR(8)) radius:internalR startAngle:- M_PI_2 endAngle:M_PI * 2 - M_PI_2 clockwise:YES];
            [bezierPath moveToPoint:CGPointMake(acenterx, y + SSSTATUS_SYMBOL_YFACTOR(14) + internalR * 2)];
            [bezierPath addLineToPoint:CGPointMake(acenterx, y + SSSTATUS_SYMBOL_YFACTOR(30) + internalR * 2)];
        }
            break;
        default:
            break;
    }

    return bezierPath.CGPath;
}

- (void)statusSymbolViewReadyToAnimation
{
    [_statusLayer addAnimation:[self statusViewAddAnimation] forKey:@"statusAnimation"];
}

- (CAShapeLayer *)statusLayer
{
    if (!_statusLayer)
    {
        _statusLayer = [CAShapeLayer layer];
        _statusLayer.lineWidth = _strokeLineWidth;
        _statusLayer.fillColor = [UIColor clearColor].CGColor;
        _statusLayer.strokeColor = _strokeColor.CGColor;
    }
    return _statusLayer;
}

- (CABasicAnimation *)statusViewAddAnimation
{
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    animation.fromValue = [NSNumber numberWithFloat:0];
    animation.toValue = [NSNumber numberWithFloat:1.0f];
    animation.duration = 1.0f;
    animation.repeatCount = 1.0f;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    return animation;
}

@end


text:
<!DOCTYPE html>

    <title>Floater Module Example</title>

        I Float

header

Home

Blog

About

Contact

          I'm some left nav that likes to be floated

hey, I'm content

footer


text:
class CreateSidebars < ActiveRecord::Migration
  def self.up
    create_table :sidebars do |t|
      t.integer :pagina_id
      t.integer :caja_id
      t.integer :orden

      t.timestamps
    end
  end

  def self.down
    drop_table :sidebars
  end
end


text:
Framework Design Guidelines advise against implementing `ICloneable` or even using it in public APIs mostly because this interface
does not specify whether the copy is deep or shallow. Instead, they suggest to define a `Clone` method on types that need a cloning
mecanism and to ensure the documentation clearly states whether it is a deep or shallow copy.

As a **user**, I am only concerned by the fact that changing properties of copy are not reflected on the original, unless they are meant to.

For instance, let say we have a `Person` with `Name` and `Addresses`. Changing the name of its _clone_ should not change its name, yet the
_clone_ can move to another address. On the other hand, if we fix a typo in the address, the typo should be fixed for the person and its _clone_.

As an **implementer**, it is my responsability to decide whether the copy is deep or shallow.

As an **inheritor**, I should be guided on what type of copy I should implement.

Not only the suggestion does not help with any of these but it prevent us to rely on the `ICloneable` contract for some generic operations. It does,
however, fix an issue they did not mention: `Clone` returns an object, so the return value should be cast before being used.

At first, I thought of defining a new interface
```csharp
public interface ICloneable<out T> : ICloneable
{
    new T Clone();
}
```

but it does not cope well with inheritance, as it can only return the type on which the interface is implement. Unlike C++, the return type of
virtual function in C# is not covariant.

So, instead, I'd rather call an extension method to the rescue
```csharp
public static T Clone<T>(this T obj)
    where T : ICloneable
{
    return (T)obj.Clone();
}
```

This extension works best when `ICloneable` is explicitly implemented. If not, you have to specify `Clone<T>()` to disambiguate
the method call.

Not being able to make the method virtual is not really a problem as we can kill two birds with on stone by delegating the implementation
to a virtual method having an extra parameter that will be indicating to **inheritors** whether the copy should be deep or shallow.
```csharp
    protected virtual object Clone(Cloning.Deep strategy)
    {
        return MemberwiseClone();
    }

    object ICloneable.Clone()
    {
        return Clone(Cloning.SuggestDeep);
    }
```

The strategy can implemeted with type markers, so the intent is clearly state in the signature of the method.

```csharp
public static class Cloning
{
    #region Markers

    /// <summary>
    /// Marker to indicate the cloning should be deep.
    /// </summary>
    public struct Deep { }

    /// <summary>
    /// Suggest the cloning should be deep.
    /// </summary>
    public static readonly Deep SuggestDeep;

    /// <summary>
    /// Marker to indicate the cloning should be shallow.
    /// </summary>
    public struct Shallow { }

    /// <summary>
    /// Suggest the cloning should be shallow.
    /// </summary>
    public static readonly Shallow SuggestShallow;

    #endregion

    ...
}
```


text:
<?php
namespace test\Util\aaa;

class Def{

}


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

namespace LinFx.Extensions.DynamicProxy;

/// <summary>
/// Castle's dynamic proxy class feature will have performance issues for some components, such as the controller of Asp net core MVC.
/// For related discussions, see: https://github.com/castleproject/Core/issues/486 https://github.com/abpframework/abp/issues/3180
/// The Abp framework may enable interceptors for certain components (UOW, Auditing, Authorization, etc.), which requires dynamic proxy classes, but will cause application performance to decline.
/// We need to use other methods for the controller to implement interception, such as middleware or MVC / Page filters.
/// So we provide some ignored types to avoid enabling dynamic proxy classes.
/// By default it is empty. When you use middleware or filters for these components in your application, you can add these types to the list.
/// </summary>
public static class DynamicProxyIgnoreTypes
{
    private static HashSet<Type> IgnoredTypes { get; } = new HashSet<Type>();

    public static void Add<T>()
    {
        lock (IgnoredTypes)
        {
            IgnoredTypes.AddIfNotContains(typeof(T));
        }
    }

    public static bool Contains(Type type, bool includeDerivedTypes = true)
    {
        lock (IgnoredTypes)
        {
            return includeDerivedTypes
                ? IgnoredTypes.Any(t => t.IsAssignableFrom(type))
                : IgnoredTypes.Contains(type);
        }
    }
}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\module\handbook\models\DisciplineGroups */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'id_discipline')->textInput() ?>

    <?= $form->field($model, 'id_group')->textInput() ?>

        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
{% extends 'base.html' %}
{% load twittercard %}
{% block twittercard %}{% twittercard_summary title="Foo" description="Bar" image="http://foo.tld/image.png" %}{% endblock %}


text:
module Dedalus
  module Elements
    class Void < Dedalus::Atom
      attr_accessor :width, :height
      def render(*); end

      def self.description
        'an empty space'
      end

      def self.example_data
        { width: 300, height: 300 }
      end
    end
  end
end


text:
'use strict';

import { expect } from 'chai';
import SiteMapper from '../src/index.js';

const map = [
    { label: 'Section A', url: '/section-a' },
    {
        label: 'Section B', url: '/section-b',
        children: [
            { label: 'Page A', url: '/section-b/page-a' },
            { label: 'Page B', url: '/section-b/page-b' },
            { label: 'Page C', url: '/section-b/page-c' },
        ],
    },
    {
        label: 'Section C', url: '/section-c',
        children: [
            { label: 'Page D', url: '/page-d' },
            { label: 'Page E', url: '/page-e' },
            { label: 'Page F', url: '/page-f' },
        ],
    },
];

const sitemap = new SiteMapper(map);

describe('constructor', () => {
    it('should store the map', () => {
        expect(sitemap.map).to.deep.equal(map);
    });

    it('should make the map immutable', () => {
        const addItem = () => {
            sitemap.map.push({ url: '/test', label: 'Test' });
        };

        expect(addItem).to.throw;
    });
});

describe('getPath', () => {
    it('should return array to provided url', () => {
        expect(sitemap.getPath('/section-a')).to.deep.equal(['/section-a']);
        expect(sitemap.getPath('/section-b/page-a')).to.deep.equal(['/section-b', '/section-b/page-a']);
        expect(sitemap.getPath('/page-d')).to.deep.equal(['/section-c', '/page-d']);
    });

    it('should return undefined on no match', () => {
        expect(sitemap.getPath('/foobar')).to.be.undefined;
    });
});

describe('getObj', () => {
    it('should return the full page object', () => {
        expect(sitemap.getObj('/section-a')).to.deep.equal({ label: 'Section A', url: '/section-a' });
        expect(sitemap.getObj('/section-b')).to.deep.equal({
            label: 'Section B', url: '/section-b',
            children: [
                { label: 'Page A', url: '/section-b/page-a' },
                { label: 'Page B', url: '/section-b/page-b' },
                { label: 'Page C', url: '/section-b/page-c' },
            ],
        });
        expect(sitemap.getObj('/page-d')).to.deep.equal({ label: 'Page D', url: '/page-d' });
    });

    it('should return undefined on no match', () => {
        expect(sitemap.getObj('/foobar')).to.be.undefined;
    });
});

describe('getLink', () => {
    it('should return the page object without children', () => {
        expect(sitemap.getLink('/section-a')).to.deep.equal({ label: 'Section A', url: '/section-a', active: false });
        expect(sitemap.getLink('/section-b')).to.deep.equal({ label: 'Section B', url: '/section-b', active: false });
        expect(sitemap.getLink('/page-d')).to.deep.equal({ label: 'Page D', url: '/page-d', active: false });
    });

    it('should mark link as active', () => {
        expect(sitemap.getLink('/section-a', true)).to.deep.equal({ label: 'Section A', url: '/section-a', active: true });
    });

    it('should return undefined on no match', () => {
        expect(sitemap.getLink('/foobar')).to.be.undefined;
    });
});

describe('getSubnav', () => {
    it('should return undefined if url has no children', () => {
        expect(sitemap.getSubnav('/section-a')).to.be.undefined;
    });

    it('should return an array of child links', () => {
        expect(sitemap.getSubnav('/section-b')).to.deep.equal([
            { label: 'Page A', url: '/section-b/page-a', active: false },
            { label: 'Page B', url: '/section-b/page-b', active: false },
            { label: 'Page C', url: '/section-b/page-c', active: false },
        ]);
    });

    it('should mark the active link if provided', () => {
        expect(sitemap.getSubnav('/section-c', '/page-e')).to.deep.equal([
            { label: 'Page D', url: '/page-d', active: false },
            { label: 'Page E', url: '/page-e', active: true },
            { label: 'Page F', url: '/page-f', active: false },
        ]);
    });

    it('should return undefined on no match', () => {
        expect(sitemap.getSubnav('/foobar')).to.be.undefined;
    });
});

describe('getBreadcrumb', () => {
    it('should return a path of link objects', () => {
        expect(sitemap.getBreadcrumbNav('/section-a', false)).to.deep.equal([
            { label: 'Section A', url: '/section-a', active: false },
        ]);

        expect(sitemap.getBreadcrumbNav('/section-b/page-a', false)).to.deep.equal([
            { label: 'Section B', url: '/section-b', active: false },
            { label: 'Page A', url: '/section-b/page-a', active: false },
        ]);

        expect(sitemap.getBreadcrumbNav('/page-d', false)).to.deep.equal([
            { label: 'Section C', url: '/section-c', active: false },
            { label: 'Page D', url: '/page-d', active: false },
        ]);
    });

    it('should mark the last link as active by default', () => {
        expect(sitemap.getBreadcrumbNav('/section-a')).to.deep.equal([
            { label: 'Section A', url: '/section-a', active: true },
        ]);

        expect(sitemap.getBreadcrumbNav('/section-b/page-a')).to.deep.equal([
            { label: 'Section B', url: '/section-b', active: false },
            { label: 'Page A', url: '/section-b/page-a', active: true },
        ]);

        expect(sitemap.getBreadcrumbNav('/page-d')).to.deep.equal([
            { label: 'Section C', url: '/section-c', active: false },
            { label: 'Page D', url: '/page-d', active: true },
        ]);
    });

    it('should return undefined on no match', () => {
        expect(sitemap.getBreadcrumbNav('/foobar')).to.be.undefined;
    });
});


text:
object TraisAbstractClass {

  abstract class AbsIterator {
    //da definire, templetizzato
    type T
    def hasNext: Boolean
    def next(): T
  }

  class StringIterator(s: String) extends AbsIterator {
    //definisco la classe T, devo definirla perche' questa classe non e' astratta
    type T = Char

    //nuovo campo
    private var i = 0

    //definisco quello che manca
    def hasNext = i < s.length
    def next() = {
      val ch = s charAt i
      i += 1
      ch
    }
  }

  //tratto che estende una classe astratta, aggiunge un metodo, non definisce hasNext, next e T
  trait RichIterator extends AbsIterator {
    def foreach(f: T => Unit): Unit = while (hasNext) f(next())
  }

  // estende CLASSE con MIXIN, MIXIN, MIXIN etc
  // oppure
  // estende TRAIT con MIXIN, MIXIN etc
  class Iter extends StringIterator("prova 12345 test test") with RichIterator
  // StringIterator e' una classe concreta, RichIterator e' un traid, da definire T, hasNext e next, che sono definiti da StringIterator, quindi Iter e' concreta e compila correttamente

  // ------------------------------------------------------------------------------
  // Non ho nessun obbligo a usare traits o derivare traits con metodi in parte definiti o completamente definiti
  // Quindi una classe puo' derivare da due traits che derivano a loro volta da una classe, avendo quindi una multi ereditarieta'
  //
  // PROBLEMA DEL DIAMANTE:
  // Scala resolves method names using a right-first depth-first search of extended 'traits',
  // Quindi non ci saranno errori di doppia dichiarazione di un metodo, ma verra' sempre preso il "primo" a destra in alto

  class concreta {
    def f() = println("funzione da classe concreta, assunta da un tratto")
  }
  trait trattoconcreto extends concreta {
    def f2() = println("funzione da tratto concreto")
  }
  class concreta2 extends trattoconcreto

  def main(args: Array[String]) {
    val iter = new Iter
    iter.foreach(println(_))
    (new concreta2).f
    (new concreta2).f2
  }
}


text:
GrassOverflow.com

# Members
Alex Wen (thatnewwen)
Andrey Slonski (aslonski)
Ryan Dempsey (rmdemp)
Tomasz Sok (tomsapps)
Dominick Lombardo (lombardo-chcg)

# MVP User Stories
* user can post questions
* user can post answer to questions
* user can comment on questions and answers
* the author can choose "the sharpest blade," aka the best answer
* users can upvote and downvote on questions, answers and comments
* users can only view all content when not logged in
* when logged in users can post questions, answers, comments and vote

## Users
```
has many questions
has many answers
has many comments
has many votes
```

## Questions
```
belongs to author
has many answers (class user)
has many comments (poly)
has many votes (poly)
```

## Answers
```
belongs to question
belongs to author (class user)
has many comments (poly)
has many votes (poly)
```

## Comments
```
belongs to author (class user)
belongs to question (poly)
belongs to answer (poly)
has many votes
```

## Votes
```
belongs to voter (class user)
belongs to question (poly)
belongs to answer (poly)
belongs to comment (poly)
```


text:
package com.thetonyk.UHC.Commands;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;

import com.thetonyk.UHC.Main;
import com.thetonyk.UHC.Inventories.GameInventory;
import com.thetonyk.UHC.Utils.GameUtils;
import com.thetonyk.UHC.Utils.GameUtils.Status;

public class HostCommand implements CommandExecutor {

	public static Map<UUID, GameInventory> inventories = new HashMap<UUID, GameInventory>();
	private static Map<UUID, BukkitTask> check = new HashMap<UUID, BukkitTask>();

	public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {

		if (!sender.hasPermission("uhc.list")) {

			sender.sendMessage(Main.NO_PERMS);
			return true;

		}

		Player player = Bukkit.getPlayer(sender.getName());

		if (args.length > 0 && args[0].equalsIgnoreCase("reset")) {

			if (HostCommand.check.containsKey(player.getUniqueId())) {

				HostCommand.check.get(player.getUniqueId()).cancel();
				HostCommand.check.clear();
				GameUtils.resetGame();
				return true;

			}

			BukkitTask timer = new BukkitRunnable() {

				public void run() {

					if (!HostCommand.check.containsKey(player.getUniqueId())) return;

					HostCommand.check.remove(player.getUniqueId());

					cancel();

				}

			}.runTaskLater(Main.uhc, 600);

			HostCommand.check.put(player.getUniqueId(), timer);
			sender.sendMessage(Main.PREFIX + "Are you sure? It will reset all the game and players will loose everything.");
			sender.sendMessage(Main.PREFIX + "Type §6/" + label + " reset §7another time to confirm.");
			return true;

		}

		if (GameUtils.getStatus() != Status.NONE) {

			sender.sendMessage(Main.PREFIX + "You can't schedule a game when another game is running");
			return true;

		}

		if (!HostCommand.inventories.containsKey(player.getUniqueId())) HostCommand.inventories.put(player.getUniqueId(), new GameInventory());

		player.openInventory(HostCommand.inventories.get(player.getUniqueId()).getInventory());
		return true;

	}

}


text:
package tubame.knowhow.plugin.ui.editor.multi.listener;

import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tubame.knowhow.biz.util.resource.MessagePropertiesUtil;

import tubame.knowhow.plugin.ui.editor.multi.documentation.EditorTreeViewerOperator;

/**
 * Classes for the Up / Down items TreeViewer.

 * Processing of Up / Down is delegated to TreeViewerOperator.

 */
public class UpDownListener implements SelectionListener {
    /** Logger */
    private static final Logger LOGGER = LoggerFactory
            .getLogger(UpDownListener.class);
    /** true:UP false:down */
    private boolean upOrdown;
    /** TreeViewer */
    private EditorTreeViewerOperator treeViewer;

    /**
     * Constructor.

     *
     * @param upOrdown
     *            true:UP false:down
     * @param treeViewer
     *            TreeViewer
     */
    public UpDownListener(boolean upOrdown, EditorTreeViewerOperator treeViewer) {
        this.treeViewer = treeViewer;
        this.upOrdown = upOrdown;
        UpDownListener.LOGGER.debug("[upOrdown]" + upOrdown + "[treeViewer]"
                + treeViewer);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void widgetSelected(SelectionEvent e) {
        UpDownListener.LOGGER.info(MessagePropertiesUtil
                .getMessage(MessagePropertiesUtil.LOG_MOVE_ITEM));
        if (this.upOrdown) {
            this.treeViewer.upItem();
        } else {
            this.treeViewer.downItem();
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void widgetDefaultSelected(SelectionEvent e) {
        // no operation
    }
}


text:
"""Show the content of DeepCpG data files.

Shows the content of ``dcpg_data.py`` output files for a selected region, for
example the methylation state of the target CpG site, neighboring CpG sites, or
the DNA sequence.

Examples
--------
Show the output methylation state of CpG sites on on chromosome 19 between
position 3028955 and 3079682:

.. code:: bash

    dcpg_data_show.py
        ./data/*.h5
        --chromo 1
        --start 3028955
        --end 3079682
        --outputs

Show output methylation states and the state as well as the distance of
10 neighboring CpG sites of cell BS27_1_SER:

.. code:: bash

    dcpg_data_show.py
        ./data/*.h5
        --chromo 1
        --start 3028955
        --end 3079682
        --outputs cpg/BS27_1_SER
        --cpg BS27_1_SER
        --cpg_wlen 10
        --cpg_dist

Show output methylation states and DNA sequence windows of length 11 and
store the results in HDF5 file ``selected.h5``:

.. code:: bash

    dcpg_data_show.py
        ./data/*.h5
        --chromo 1
        --start 3028955
        --end 3079682
        --outputs
        --dna_wlen 11
        --out_hdf selected.h5
"""

from __future__ import print_function
from __future__ import division

from collections import OrderedDict
import os
import sys

import argparse
import h5py as h5
import logging
import numpy.random
import pandas as pd

from deepcpg.data import hdf

def delta_columns(delta, zero=True):
    columns = ['%s' % column for column in list(range(-delta, 0))]
    if zero:
        columns.append('0')
    columns += ['+%s' % column for column in list(range(1, delta + 1))]
    return columns

class App(object):

    def run(self, args):
        name = os.path.basename(args[0])
        parser = self.create_parser(name)
        opts = parser.parse_args(args[1:])
        return self.main(name, opts)

    def create_parser(self, name):
        p = argparse.ArgumentParser(
            prog=name,
            formatter_class=argparse.ArgumentDefaultsHelpFormatter,
            description='Shows selected data from DeepCpG data files')
        p.add_argument(
            'data_files',
            nargs='+',
            help='Data files')
        p.add_argument(
            '-o', '--out_hdf',
            help='Write selected data to HDF5 file')
        p.add_argument(
            '--outputs',
            nargs='*',
            help='Name of outputs that are shown')
        p.add_argument(
            '--dna_wlen',
            type=int,
            help='Length of DNA sequence window that is shown')
        p.add_argument(
            '--cpg',
            nargs='*',
            help='Name of replicates that are shown')
        p.add_argument(
            '--cpg_wlen',
            type=int,
            default=10,
            help='CpG window length')
        p.add_argument(
            '--cpg_dist',
            action='store_true',
            help='Also show distance to neighboring CpG sites')
        p.add_argument(
            '--chromo',
            help='Chromosome')
        p.add_argument(
            '--start',
            type=int,
            help='Start position')
        p.add_argument(
            '--end',
            type=int,
            help='End position')
        p.add_argument(
            '--verbose',
            help='More detailed log messages',
            action='store_true')
        p.add_argument(
            '--log_file',
            help='Write log messages to file')
        return p

    def main(self, name, opts):
        logging.basicConfig(filename=opts.log_file,
                            format='%(levelname)s (%(asctime)s): %(message)s')
        log = logging.getLogger(name)
        if opts.verbose:
            log.setLevel(logging.DEBUG)
        else:
            log.setLevel(logging.INFO)
        log.debug(opts)

        if opts.dna_wlen and opts.dna_wlen % 2 == 0:
            raise ValueError('DNA window length must be odd!')

        if opts.cpg_wlen and opts.cpg_wlen % 2 == 1:
            raise ValueError('CpG window length must be even!')

        data = []
        for filename in opts.data_files:
            data_file = h5.File(filename, 'r')
            data_chunk = OrderedDict()
            loc = pd.DataFrame({'chromo': data_file['chromo'].value,
                                'pos': data_file['pos'].value},
                               columns=['chromo', 'pos'])
            data_chunk['loc'] = loc

            if opts.outputs is not None:
                group = data_file['outputs']
                output_names = opts.outputs
                if not len(output_names):
                    output_names = hdf.ls(filename, 'outputs', recursive=True)
                outputs = []
                for output_name in output_names:
                    output = pd.Series(group[output_name].value,
                                       name=output_name)
                    outputs.append(output)
                outputs = pd.concat(outputs, axis=1)
                data_chunk['outputs'] = outputs

            if opts.dna_wlen:
                group = data_file['/inputs/dna']
                wlen = group.shape[1]
                delta = opts.dna_wlen // 2
                ctr = wlen // 2
                idx = slice(ctr - delta, ctr + delta + 1)
                dna = group[:, idx]
                dna = pd.DataFrame(dna, columns=delta_columns(delta))
                data_chunk['dna'] = dna

            if opts.cpg is not None:
                kinds = ['state']
                if opts.cpg_dist:
                    kinds.append('dist')

                group = data_file['/inputs/cpg']
                names = opts.cpg
                if not len(names):
                    names = list(group.keys())
                for name in names:
                    for kind in kinds:
                        path = '%s/%s' % (name, kind)
                        cpg = group[path].value
                        if opts.cpg_wlen:
                            ctr = cpg.shape[1] // 2
                            delta = opts.cpg_wlen // 2
                            cpg = cpg[:, (ctr - delta):(ctr + delta)]
                        columns = delta_columns(delta, zero=False)
                        cpg = pd.DataFrame(cpg, columns=columns)
                        data_chunk[path] = cpg

            data_chunk = pd.concat(data_chunk.values(),
                                   axis=1,
                                   keys=data_chunk.keys())
            if opts.chromo:
                idx = data_chunk['loc']['chromo'] == opts.chromo.encode()
                data_chunk = data_chunk.loc[idx]
            if opts.start:
                idx = data_chunk['loc']['pos'] >= opts.start
                data_chunk = data_chunk.loc[idx]
            if opts.end:
                idx = data_chunk['loc']['pos'] <= opts.end
                data_chunk = data_chunk.loc[idx]
            data.append(data_chunk)

        data = pd.concat(data)
        data[('loc', 'chromo')] = [x.decode() for x in data['loc']['chromo']]
        if opts.out_hdf:
            data.to_hdf(opts.out_hdf, '/data')
        else:
            print(data.to_string())

        return 0

if __name__ == '__main__':
    app = App()
    app.run(sys.argv)


text:
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var mp=require('./src/minPanel');

module.exports = mp;
window.mp=mp;

},{"./src/minPanel":12}],2:[function(require,module,exports){
function css(elem, value) {
    if (arguments.length < 2) {
        var result = this.getComputedStyle(elem, '');
        return result;
    } else {
        if (elem && typeof(value) == 'string') {
            var css = elem + ":" + value;
            return this.style.cssText += css + ';'
        }
    }
}

module.exports={css:css}

},{}],3:[function(require,module,exports){
var Event = {
    on: function (name, lister) {
        if (!name) {
            return;
        }
        if (!this._events_) {
            this._events_ = {};
        }
        var events = this._events_;
        if (!events[name]) {
            events[name] = [];
        }
        events[name].push(lister);

    },
    emit: function (name) {
        var events = this._events_;
        if (!name || !events || !events[name]) {
            return;
        }
        var queue = events[name];
        var length = queue.length;
        var args = Array.prototype.slice.call(arguments, 1);
        for (var i = 0; i < length; i++) {
            queue[i].apply(this, args);
        }

    }

};

module.exports = Event;

},{}],4:[function(require,module,exports){
module.exports = function (source, add) {
    for (var o in add) {
        if (add.hasOwnProperty(o)) {
            source[o] = add[o];
        }
    }
    return source;
};

},{}],5:[function(require,module,exports){
var diff = require('./lib/diff');

var createElement = require('./lib/createElement');

var render = require('./lib/render');

var KVD = {
    diff: diff,
    render: render,
    createElement:createElement
}

window.KVD = KVD;

module.exports = KVD;

},{"./lib/createElement":6,"./lib/diff":7,"./lib/render":8}],6:[function(require,module,exports){
var REGX_ClassId = /\.|#/;
var REGX_SplitClasId = /(\.|#)\w+/g;
var REGX_GetProperties = /\(.+\)/;
var REGX_SplitProperties = /\w+="[\w:,]+"/g;

function createElement(option, children) {
    var tag = option.tag
    var vnode = {};
    var tagName, classId;
    tagName = tagName = tag.split(" ")[0].split(REGX_ClassId)[0];

    vnode['tagName'] = tagName;
    vnode['text']=tag.split(" ")[1]||'';

    classId = tag.match(REGX_SplitClasId);

    var properties = {};
    for (key in option) {
        if (key != 'tag') {
            properties[key] = option[key];
        }
    }
    //var properties = tag.match(REGX_GetProperties)[0].match(REGX_SplitProperties);
    vnode['propertyList'] = properties;
    var part, type, classList;

    if (classId!=null) {
        classId.forEach(function(v, idx) {
            part = v;
            type = part.charAt(0);
            if (type === '.') {
                classList = classList || [];
                classList.push(part.substring(1));
            } else if (type === '#') {
                vnode['id'] = part.substring(1);
            }
        });

        vnode['classList'] = classList;
    }

    vnode.children=children
    return vnode;
}

module.exports = createElement;

},{}],7:[function(require,module,exports){
function diff(a, b) {

    var diff;

    for (key in b) {
        if (!(key in a)) {
            diff = diff || {};
            diff[key] = b[key];
     	}
    }

    return diff;
}

module.exports = diff;

},{}],8:[function(require,module,exports){
var vnode=require('./createElement');

function renderNode(vnode){
	var el=document.createElement(vnode.tagName);
	for (key in vnode.propertyList){
		var part=vnode.propertyList[key];
		if(typeof part=="string")el.setAttribute(key,part);
		else if(typeof part =="object"){
			var partStr=JSON.stringify(part);
			partStr=partStr.substring(1,partStr.length-1).replace(/"/g,"").replace(/,(?=[\w-])/g,";");			       el.setAttribute(key,partStr);
		}
	}
	if(vnode.text)el.innerText=vnode.text;
	return el;

}

function render(vnode,container) {

    var node = renderNode(vnode);

    var children =vnode.children;
    if (children && children.length > 0) {
        for (var i = 0; i < children.length; i++) {
            var child = children[i]
            node.appendChild(render(child));
        }
    }
    return node;

}

function fix(str){
	return str.match(/[\w:,]+/)[0];
}

module.exports = render;

},{"./createElement":6}],9:[function(require,module,exports){
var ELEMENTS = {
	MP_ATTRIBUTE :{
            tag: 'div MP',
            style: {
                "border-radius": "5px",
                "padding": "5px",
                "background-color": "rgba(0, 0, 0, 0.2)",
                "right": "5%",
                "width": "25px",
		"top": "5%",
                "color": "#fff"
            },
	    text:'MP'
        },
	PANNEL_ATTRIBUTE :{
            tag: 'div',
            style: {
                "border-radius": "5px",
                "padding": "5px",
                "background-color": "rgba(0, 0, 0, 0.2)",
                "width": "80%",
                "height": "80%",
                "position": "fixed",
                "top": "5%",
                "color": "#fff"
            }
	},
	PANNEL_TEXTAREA_ATTRIBUTE:{
	   tag: 'textarea',
	   style:{
	   	"width": "100%",
  		"box-sizing": "border-box",
		"height": "80%",
		"resize": "none",
		"font-size": "1em",
		"color": "#fff",
  		"background-color": "rgba(0, 0, 0, 0.8)"
	   }
	},
	PANNEL_BTN_BLOCK_ATTRIBUTE:{
	   tag:'div',
	   style:{
	   	"display":"-webkit-box",
		"height":"5%"
	   }
	},
	PANNEL_BTN_ATTRIBUTE:{
	   tag:'button',
	   style:{
	   	"display": "block",
		"-webkit-box-flex": "1",
		"height": "100%"
	   }
	},
	PANNEL_INPUT_ATTRIBUTE:{
	   tag:'input',
	   style:{
	   	"display": "block",
		"-webkit-box-flex": "3",
		"height": "100%",
		"border":"0"
	   }
	}

}

module.exports=ELEMENTS;

},{}],10:[function(require,module,exports){
var event = require('../lib/event');

var dom = require('../lib/dom-handle');

function bindEvent(mp) {

    //open or close the pannel
    mp.min.addEventListener('click', function(e) {
        getComputedStyle(mp.node).display == 'block' ? dom.css.call(mp.node, 'display', 'none') : dom.css.call(mp.node, 'display', 'block');
    });

    function customBtnCheck(btnType) {
        return /btn\d/.test(btnType);
    }

    for (key in mp.el.btn) {
        (function(btnType) {
            if(customBtnCheck(btnType))dom.css.call(mp.el.btn[btnType], 'color', '#ccc');
            mp.el.btn[btnType].addEventListener('click', function(e) {
		    if(customBtnCheck(btnType))event.emit(btnType);
		    else if(btnType=='btn_back')history.go(-1);
		    else if(btnType=='btn_forward')history.go(1);
		    else if(btnType=='btn_refresh')location.reload();
            }, false)

        })(key)
    }
}

module.exports = bindEvent;

},{"../lib/dom-handle":2,"../lib/event":3}],11:[function(require,module,exports){
var ELEMENTS = require('./attributesConfig');

var KVD = require('kvd');

var Extend = require('../lib/extend');

function createDom(mp) {
     mp.el={};
    var min_vnode=KVD.createElement(ELEMENTS.MP_ATTRIBUTE);
    var pannel_vnode=KVD.createElement(ELEMENTS.PANNEL_ATTRIBUTE,[
		  KVD.createElement(ELEMENTS.PANNEL_TEXTAREA_ATTRIBUTE),
		  KVD.createElement(ELEMENTS.PANNEL_BTN_BLOCK_ATTRIBUTE,[
			  	KVD.createElement(Extend(ELEMENTS.PANNEL_BTN_ATTRIBUTE,{tag: 'button BTN1'})),
			  	KVD.createElement(Extend(ELEMENTS.PANNEL_BTN_ATTRIBUTE,{tag: 'button BTN2'})),
			  	KVD.createElement(Extend(ELEMENTS.PANNEL_BTN_ATTRIBUTE,{tag: 'button BTN3'}))					  ]),
		  KVD.createElement(ELEMENTS.PANNEL_BTN_BLOCK_ATTRIBUTE,[
			  	KVD.createElement(Extend(ELEMENTS.PANNEL_BTN_ATTRIBUTE,{tag: 'button BTN4'})),
			  	KVD.createElement(Extend(ELEMENTS.PANNEL_BTN_ATTRIBUTE,{tag: 'button BTN5'})),
			  	KVD.createElement(Extend(ELEMENTS.PANNEL_BTN_ATTRIBUTE,{tag: 'button BTN6'}))
			  ]),
		  KVD.createElement(ELEMENTS.PANNEL_BTN_BLOCK_ATTRIBUTE,[
			  	KVD.createElement(Extend(ELEMENTS.PANNEL_BTN_ATTRIBUTE,{tag: 'button 返回'})),
				KVD.createElement(Extend(ELEMENTS.PANNEL_BTN_ATTRIBUTE,{tag: 'button 前进'})),
				KVD.createElement(Extend(ELEMENTS.PANNEL_BTN_ATTRIBUTE,{tag: 'button 刷新'}))

			  ]),
		  KVD.createElement(ELEMENTS.PANNEL_BTN_BLOCK_ATTRIBUTE,[
			  	KVD.createElement(Extend(ELEMENTS.PANNEL_INPUT_ATTRIBUTE,{tag: 'input'})),
				KVD.createElement(Extend(ELEMENTS.PANNEL_BTN_ATTRIBUTE,{tag: 'button 跳转'}))
			  ]),

		  KVD.createElement(ELEMENTS.PANNEL_BTN_BLOCK_ATTRIBUTE)
	]);
    var body = document.getElementsByTagName('body')[0];

    //node tree
    mp.min=KVD.render(min_vnode);
    mp.node=KVD.render(pannel_vnode);

    //render
    body.appendChild(mp.min);
    body.appendChild(mp.node);

    //fast way
    mp.el.btn={
    	btn1:mp.node.children[1].children[0],
	btn2:mp.node.children[1].children[1],
	btn3:mp.node.children[1].children[2],
	btn4:mp.node.children[2].children[0],
	btn5:mp.node.children[2].children[1],
	btn6:mp.node.children[2].children[2],
	btn_back:mp.node.children[3].children[0],
	btn_forward:mp.node.children[3].children[1],
	btn_refresh:mp.node.children[3].children[2]
    }

    mp.el.textarea=mp.node.children[0];
    mp.el.href={
	    input:mp.node.children[4].children[0],
	    btn:mp.node.children[4].children[1]

    }
    return mp;
}

module.exports = createDom;

},{"../lib/extend":4,"./attributesConfig":9,"kvd":5}],12:[function(require,module,exports){
Extend = require('../lib/extend');
createDom = require('./createDom');
bindEvent = require('./bindEvent');
Event = require('../lib/event');

dom=require('../lib/dom-handle');

function mp() {
    var self = this;
    this.txtlog = "";
    createDom(this);
    bindEvent(this);
    this.el.href.input.value=location.href;
}

mp.prototype.value = function(key, value) {
    var text = 'watch:';
    text += key;
    text += '=';
    text += JSON.stringify(value);
    text += '\n';
    this.txtlog+= text;
    this.el.textarea.textContent = this.txtlog;
}

mp.prototype.log = function(text) {
    this.txtlog += text;
    this.el.textarea.textContent = this.txtlog;
}

mp.prototype.on =function(type,fn){
	dom.css.call( this.el.btn[type],'color','#000');
	Event.on(type,fn);
}

module.exports = mp;

},{"../lib/dom-handle":2,"../lib/event":3,"../lib/extend":4,"./bindEvent":10,"./createDom":11}]},{},[1]);


text:
(function (mod) {
    if (typeof exports === 'object' && typeof module === 'object') { // CommonJS
        module.exports = mod();
    } else if (typeof define === 'function' && define.amd) { // AMD
        return define([], mod);
    } else { // Plain browser env
        this.PIE = mod();
    }
})(function () {
    "use strict";

    var exports = {};
    var modes = {};

    modes.html = function (data) {
        var content = document.getElementById(data.id);
        content.innerHTML = data.content;
        return content;
    };

    modes.insert = function (data) {
        var content = document.getElementById(data.id);
        content.insertAdjacentHTML(data.pos, data.content);
        return content;
    };

    modes.render = function (data) {
        return PIPE.modes.html(JSON.parse(data));
    };

    exports.on = function (data) {
        return modes[(data.mode || 'html')].call(null, JSON.parse(decodeURIComponent(data)));
    };

    exports.hasClass = function (elem, name) {
        var pattern = new RegExp('(?:^' + name + '$)|(?: ' + name + ' )|(?: ' + name + '$)|(?: ' + name + ' )');
        return pattern.test(elem.className);
    };

    function addClass(elem, name) {
        if (!exports.hasClass(elem, name)) {
            return elem.className + ' ' + name;
        }
        return elem.className;
    }

    exports.addClass = function (elem, names) {
        if (typeof names === 'string') {
            elem.className = addClass(elem, names);
            return;
        }
        if (names instanceof Array) {
            names.forEach(function (name) {
                elem.className += addClass(elem, name);
            });
        }
    };

    exports.removeClass = function (elem, names) {
        var className = elem.className;
        if (typeof names === 'string') {
            if (exports.hasClass(elem, names)) {
                elem.className = className.replace(names, '').replace(/\s+/g, ' ');
            }
            return;
        }
        if (names instanceof Array) {
            names.forEach(function (name) {
                if (exports.hasClass(elem, name)) {
                    className = className.replace(name, '');
                }
            });
            elem.className = className.replace(/\s+/g, ' ');
        }
    };

    exports.style = function (elem) {
        return elem.currentStyle || document.defaultView.getComputedStyle(elem, null);
    };

    exports.process = function (f, time) {
        var id = null;
        return function () {
            clearTimeout(id);
            id = setTimeout(function () {
                f();
                id = null;
            }, time);
        };
    };

    function ajax(http, method, url, data, f) {
        http.onreadystatechange = function () {
            if (http.readyState === 4) {
                if (http.status >= 200 && http.status < 300 || http.status === 304) {
                    if (typeof f === 'function') {
                        f.call(null, http.responseText);
                    }
                }
            }
        };
        http.open(method, url, true);
        http.send(data);
    };

    exports.ajax = ajax;

    exports.get = function (http, url, f) {
        ajax(http, 'get', url, null, f);
    };

    exports.post = function (http, url, data, f) {
        ajax(http, 'post', url, data, f);
    };

    return exports;
});


text:
<?php

class Google_Service_ServiceManagement_SystemParameters extends Google_Collection
{
  protected $collection_key = 'rules';
  protected $rulesType = 'Google_Service_ServiceManagement_SystemParameterRule';
  protected $rulesDataType = 'array';

  public function setRules($rules)
  {
    $this->rules = $rules;
  }
  public function getRules()
  {
    return $this->rules;
  }
}


text:
<!DOCTYPE html>
<svg width="200" height="200">
  <rect x="100" y="50" width="20" height="100" fill="red"/>
  <foreignObject x="100" y="50" width="20" height="100"
      style="overflow: hidden; writing-mode: vertical-rl">

Should not show this

  </foreignObject>
</svg>


text:
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using Estacionamento.Models.Mapping;

namespace Estacionamento.Models
{
    public partial class EstacionamentoContext : DbContext
    {
        static EstacionamentoContext()
        {
            Database.SetInitializer<EstacionamentoContext>(null);
        }

        public EstacionamentoContext()
            : base("Name=EstacionamentoContext")
        {
        }

        public DbSet<Fluxo> Fluxoes { get; set; }
        public DbSet<Horario> Horarios { get; set; }
        public DbSet<ModelosCarro> ModelosCarroes { get; set; }
        public DbSet<Usuario> Usuarios { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new FluxoMap());
            modelBuilder.Configurations.Add(new HorarioMap());
            modelBuilder.Configurations.Add(new ModelosCarroMap());
            modelBuilder.Configurations.Add(new UsuarioMap());
        }
    }
}


text:
package it.dtk.kafka

import scala.concurrent.{ Future, Promise }
import java.util.Properties

import it.dtk.feed.Model._
import org.apache.kafka.clients.producer.{ RecordMetadata, ProducerRecord, KafkaProducer }
import org.apache.kafka.clients.producer.ProducerConfig._
import org.json4s.NoTypeHints
import org.json4s._
import org.json4s.jackson.Serialization
import org.json4s.jackson.Serialization.write
import it.dtk.concurrent.JavaFutureConversions._

/**
 * Created by fabiofumarola on 09/08/15.
 */
class FeedProducerKafka(val topic: String,
                        val clientId: String,
                        brokersList: String,
                        batchSize: Int = 1,
                        retries: Int = 3,
                        ack: Int = -1) {
  implicit val formats = org.json4s.DefaultFormats ++ org.json4s.ext.JodaTimeSerializers.all

  private val props = new Properties()
  props.put(BOOTSTRAP_SERVERS_CONFIG, brokersList)
  props.put(CLIENT_ID_CONFIG, clientId)
  props.put(BATCH_SIZE_CONFIG, batchSize.toString) //send each message
  props.put(RETRIES_CONFIG, retries.toString)
  props.put(ACKS_CONFIG, ack.toString)
  props.put(COMPRESSION_TYPE_CONFIG, "none") //Valid values are "none", "gzip" and "snappy".
  props.put(KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.ByteArraySerializer")
  props.put(VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.ByteArraySerializer")

  private val producer = new KafkaProducer[Array[Byte], Array[Byte]](props)

  def sendAsync(feed: Feed): Future[RecordMetadata] = {
    val message = new ProducerRecord[Array[Byte], Array[Byte]](topic, feed.uri.getBytes(), write(feed).getBytes)
    producer.send(message)
  }

  def sendAsync(procFeed: ProcessedFeed): Future[RecordMetadata] = {
    val message = new ProducerRecord[Array[Byte], Array[Byte]](topic, procFeed.uri.getBytes(), write(procFeed).getBytes)
    producer.send(message)
  }

  def sendAsync(pageData: PageData): Future[RecordMetadata] = {
    val message = new ProducerRecord[Array[Byte], Array[Byte]](topic, pageData.url.getBytes(), write(pageData).getBytes)
    producer.send(message)
  }

  def sendSync(feed: Feed): RecordMetadata = {
    val message = new ProducerRecord[Array[Byte], Array[Byte]](topic, feed.uri.getBytes(), write(feed).getBytes)
    producer.send(message).get()
  }

  def sendSync(procFeed: ProcessedFeed): RecordMetadata = {
    val msg = new ProducerRecord[Array[Byte], Array[Byte]](topic, procFeed.uri.getBytes(), write(procFeed).getBytes)
    producer.send(msg).get()
  }

  def sendSync(pageData: PageData): RecordMetadata = {
    val msg = new ProducerRecord[Array[Byte], Array[Byte]](topic, pageData.url.getBytes(), write(pageData).getBytes)
    producer.send(msg).get
  }

  def close() = producer.close()
}


text:
import PropTypes from 'prop-types'
import React, {Component} from 'react'
import {Transition} from 'react-transition-group'
import {Portal} from 'react-portal'

import propTypes from '../../prop-types'
import cn from '../../lib/class-names'

// This has to be synced with the transition timeouts in the styles
const TRANSITION_TIMEOUT = 0.3 * 1000

class ModalPortal extends Component {
  static propTypes = {
    ...propTypes.component,
    in: PropTypes.bool, // To stay compatible with TransitionGroup
    isOpen: PropTypes.bool,
    onClose: PropTypes.func,
    children: PropTypes.node,
    lightbox: PropTypes.bool,
    fullscreenMobile: PropTypes.bool
  }

  componentDidMount() {
    if (this.props.isOpen) {
      global.document.body.style.overflow = 'hidden'
    }

    global.addEventListener('keydown', this.onKeyDown, false)
  }

  componentDidUpdate(prevProps) {
    if (this.props.isOpen && !prevProps.isOpen) {
      global.document.body.style.overflow = 'hidden'
    } else if (this.props.isOpen && !prevProps.isOpen) {
      global.document.body.style.overflow = ''
    }
  }

  componentWillUnmount() {
    global.document.body.style.overflow = ''

    global.removeEventListener('keydown', this.onKeyDown, false)
  }

  onKeyDown = event => {
    if (this.isOpen() && this.props.onClose && event.keyCode === 27) {
      this.props.onClose()
    }
  }

  isOpen = () => this.props.isOpen || this.props.in

  render() {
    const {classNames, onClose, children, lightbox = false, fullscreenMobile = false} = this.props

    return (
      <Transition
        in={this.isOpen()}
        appear
        timeout={TRANSITION_TIMEOUT}
        mountOnEnter
        unmountOnExit
        onEnter={node => node && node.scrollTop} // Force first paint before going into entering state!
      >
        {state => (
          <Portal>

{children}

          </Portal>
        )}
      </Transition>
    )
  }
}

export default ModalPortal


text:
{% extends 'wall.html' %}
{% block script %}
    {{ super() }}
    <script>
        $(function() {
            $.aip.wall.init({
                makePageUrl: function(page) { return '/plused/page/' + page; },
                makePageData: function(page) { return { user_id: '{{ current_user.id }}' }; }
            });
        });
    </script>
{% endblock %}