text:
""" Decorator ``try_jit`` accelerates computation via Numba, when available
"""
from functools import wraps
import logging
import os

logger = logging.getLogger('yatsm')

has_numba = True
try:
    import numba as nb
except ImportError:
    has_numba = False
else:
    # Check if disabled via environment
    if os.environ.get('NUMBA_DISABLE_JIT') == '1':
        has_numba = False
    # Check for an adequate version number
    try:
        nb_ver = nb.__version__.split('.')
        if int(nb_ver[0]) == 0 and int(nb_ver[1]) < 22:
            has_numba = False
            logger.warning('You have numba installed, but the version is too '
                           'old to be used (%s)' % nb.__version__)
    except:
        logger.warning('Could not parse numba version. Disabling numba.jit')
        has_numba = False

def _doublewrap(f):
    """ Allows decorators to be called with/without args/kwargs

    Allows:

    .. code-block:: python

        @decorator
        @decorator()
        @decorator(args, kwargs=values)

    Modification of answer from user "bj0" on StackOverflow:
    http://stackoverflow.com/a/14412901
    """
    @wraps(f)
    def new_dec(*args, **kwargs):
        if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):
            # called as @decorator
            return f(args[0])
        elif len(args) == 1 and callable(args[0]):
            # called as decorator(f, **kwargs)
            return f(args[0], **kwargs)
        elif len(args) == 0 and len(kwargs) == 0:
            # called as @decorator()
            return f
        else:
            # called as @decorator(*args, **kwargs)
            return lambda realf: f(realf, *args, **kwargs)

    return new_dec

@_doublewrap
def try_jit(f, *args, **kwargs):
    """ Apply numba.jit to function ``f`` if Numba is available

    Accepts arguments to Numba jit function (signature, nopython, etc.).

    Examples:

    .. code-block:: python

        @try_jit
        @try_jit()
        @try_jit(nopython=True)
        @try_jit("float32[:](float32[:], float32[:])", nopython=True)

    """
    if has_numba:
        @wraps(f)
        def wrap(*args, **kwargs):
            return nb.jit(*args, **kwargs)
        return wrap(f, *args, **kwargs)
    else:
        return f


text:
import {expect} from 'chai';
import DMA from '../../src/memory/DMA';

describe('memory/DMA', () => {
  let dma, reads, writes;

  const cpuMemory = {
    read: () => reads++,
    write: () => writes++,
  };

  beforeEach(() => {
    reads = 0;
    writes = 0;
    dma = new DMA;
    dma.connect({cpuMemory});
    dma.reset();
  });

  it('does not block CPU by default', () => {
    expect(dma.isBlockingCPU()).to.be.false;
  });

  it('blocks CPU after address write', () => {
    dma.writeAddress(0);
    expect(dma.isBlockingCPU()).to.be.true;
  });

  it('transfers 256B of data during 512 cycles', () => {
    let cycles = 0;
    dma.writeAddress(0);
    while (dma.isBlockingCPU()) {
      dma.tick();
      cycles++;
    }
    expect(cycles).to.equal(512);
    expect(reads).to.equal(256);
    expect(writes).to.equal(256);
  });
});

redpajama_set_name: RedPajamaGithub


text:
package oauthid

import (
	"testing"

	. "github.com/smartystreets/goconvey/convey"
)

func TestWhitelist(t *testing.T) {
	Convey("Works", t, func() {
		wl := NewWhitelist("primary-client-id", []string{
			"additional-client-id-1",
			"additional-client-id-2",
		})
		call := wl.IsAllowedOAuthClientID

		So(call("abc@appspot.gserviceaccount.com", "anonymous"), ShouldBeTrue)
		So(call("dude@example.com", ""), ShouldBeFalse)
		So(call("dude@example.com", GoogleAPIExplorerClientID), ShouldBeTrue)
		So(call("dude@example.com", "primary-client-id"), ShouldBeTrue)
		So(call("dude@example.com", "additional-client-id-2"), ShouldBeTrue)
		So(call("dude@example.com", "unknown-client-id"), ShouldBeFalse)
	})
}


text:
package com.tom.core.item;

import java.util.List;

import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;

import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

public class Holotape extends Item {
	@Override
	@SuppressWarnings({"rawtypes", "unchecked"})
	@SideOnly(Side.CLIENT)
	public void addInformation(ItemStack is, World player, List list, ITooltipFlag isAdvanced) {
		if (is.getTagCompound() != null && is.getTagCompound().hasKey("name")) {
			String name = is.getTagCompound().getString("name");
			list.add(name);
		}
	}
}


text:
/* global alert, confirm */
import i18n from 'i18n';

export default {
  ACTIONS: {
    CREATE_FOLDER: 'create-folder',
    EDIT_FILE: 'edit',
  },
  MOVE_SUCCESS_DURATION: 3000,
  CSS_TRANSITION_TIME: 300,
  SMALL_THUMBNAIL_HEIGHT: 60,
  SMALL_THUMBNAIL_WIDTH: 60,
  THUMBNAIL_HEIGHT: 150,
  THUMBNAIL_WIDTH: 200,
  BULK_ACTIONS: [
    {
      value: 'delete',
      label: i18n._t('AssetAdmin.BULK_ACTIONS_DELETE', 'Delete'),
      className: 'font-icon-trash',
      destructive: true,
      callback: null, // defined in <Gallery> for now
      canApply: (items) => (
        items.every(item => item && item.canDelete)
      ),
    },
    {
      value: 'edit',
      label: i18n._t('AssetAdmin.BULK_ACTIONS_EDIT', 'Edit'),
      className: 'font-icon-edit',
      destructive: false,
      // Only allow editing if a single item (file or folder) is selected
      canApply: (items) => items.length === 1,
      callback: null, // defined in <Gallery> for now
    },
    {
      value: 'move',
      label: i18n._t('AssetAdmin.BULK_ACTIONS_MOVE', 'Move'),
      className: 'font-icon-folder-move',
      canApply: (items) => items.every(item => item && item.canEdit),
      destructive: false,
      callback: null,
    },
    {
      value: 'publish',
      label: i18n._t('AssetAdmin.BULK_ACTIONS_PUBLISH', 'Publish'),
      className: 'font-icon-rocket',
      destructive: false,
      callback: null, // defined in <Gallery> for now
      canApply: (items) => (
        items.some(item => item && item.modified) &&
        items.every(item => item.canEdit && item.type !== 'folder')
      ),
      confirm: null,
    },
    {
      value: 'unpublish',
      label: i18n._t('AssetAdmin.BULK_ACTIONS_UNPUBLISH', 'Unpublish'),
      className: 'font-icon-cancel-circled',
      destructive: false,
      callback: null, // defined in <Gallery> for now
      canApply: (items) => (
        items.some(item => item.published) &&
        items.every(item => item.canEdit && item.type !== 'folder')
      ),
      confirm: null,
    },
    {
      value: 'insert',
      label: i18n._t('AssetAdmin.BULK_ACTIONS_INSERT', 'Insert'),
      className: 'font-icon-plus-circled btn-primary',
      destructive: false,
      callback: null, // defined in <Gallery> for now
      canApply: (items) => items.length,
      confirm: null,
    },
  ],
  BULK_ACTIONS_PLACEHOLDER: i18n._t('AssetAdmin.BULK_ACTIONS_PLACEHOLDER'),
  SPACE_KEY_CODE: 32,
  RETURN_KEY_CODE: 13,
  DEFAULT_PREVIEW: 'framework/client/dist/images/app_icons/generic_92.png',
  MODAL_MOVE: 'MODAL_MOVE',
};


text:
class CGPModel
{
private:
    static CfgFile *config;

    // for the nodes
    int number_of_nodes;
    CGPModelNode *node_elements;

    // for the outputs
    ProbabilisticModelElement *output_elements;
	int *genotype;
	double probability;
public:
    static void set_config( CfgFile& cfg );

    CGPModel();
    ~CGPModel();
	void delete_genotype();
	int length();
	void print( ostream& fout );

    int* get_genotype( RandomNumberGenerator& rng );
	void guided_mutation( int *elite_gene, int *new_gene, RandomNumberGenerator& rng );
	double get_probability( int *gene );
	void normalize( int *gene );
    void pipe_mutate( RandomNumberGenerator& rng );
    void pipe_increment( int *gene );
	void pipe_adapt( int *gene, int fitnessBest, int fitnessElite );
	void pbil_mutate( RandomNumberGenerator& rng );
    void pbil_increment( int *gene );
	void pbil_adapt( int *gene );

	void* traverse_model( void *param, int directive );
};

#endif


text:
import EditorEvents = require("editor/EditorEvents");
import EditorUI = require("ui/EditorUI");
import ModalWindow = require("../ModalWindow");
import ProgressModal = require("../ProgressModal");

class ProPlatformWindow extends ModalWindow {

    constructor() {

        super(false);

        this.init("Platform License Required", "AtomicEditor/editor/ui/platformsinfo.tb.txt");

        var editField = <Atomic.UIEditField> this.getWidget("info");

        var text = "\nAtomic Game Engine Pro is required to deploy apps to this platform.\n\n<color #D4FB79>Installed platforms:</color>\n\n";

        var licenseSystem = ToolCore.licenseSystem;

        var installedText = "    <widget TBSkinImage: skin: 'LogoMac-Small'> <widget TBSkinImage: skin: 'LogoWindows-Small'> <widget TBSkinImage: skin: 'LogoHTML5-Small'> ";
        var availableText = "   ";

        if (licenseSystem.licenseAndroid)
            installedText += "<widget TBSkinImage: skin: 'LogoAndroid-Small'> ";
        else
            availableText += "<widget TBSkinImage: skin: 'LogoAndroid-Small'> ";

            if (licenseSystem.licenseIOS)
                installedText += "<widget TBSkinImage: skin: 'LogoIOS-Small'> ";
            else
                availableText += "<widget TBSkinImage: skin: 'LogoIOS-Small'> ";

        text += installedText + "\n\n\n";

        if (!licenseSystem.licenseIOS || !licenseSystem.licenseAndroid || !licenseSystem.licenseModule3D) {
          text += "<color #76D6FF>Available platforms:</color>\n\n";
          text += availableText + "\n\n\n";
      }

      editField.text = text;

      this.resizeToFitContent();
      this.center();

      editField.reformat();

    }

    handleWidgetEvent(ev: Atomic.UIWidgetEvent) {

        if (ev.type == Atomic.UI_EVENT_TYPE_CLICK) {

            var id = ev.target.id;

            if (id == "purchase") {

                Atomic.fileSystem.systemOpen("https://store.atomicgameengine.com/site");

            } else if (id == "ok") {

                this.hide();

                return true;
            }

            return false;

        }
    }

}

export = ProPlatformWindow;


text:
function Portal(scene, primaryCamera, portalPosition, prePortalCam, postPortalCam, composer, renderer, doorScenePosition) {
    this.scene = scene;
    this.primaryCamera = primaryCamera;
    this.prePortalCam = prePortalCam;
    this.portalPosition = portalPosition;
    this.doorScenePosition = doorScenePosition;
    var self = this;

    //this.portalRotation = new THREE.Vector3(Math.random()*Math.PI*2, Math.random()*Math.PI*2, Math.random()*Math.PI*2);
    this.portalRotation = new THREE.Vector3(0, 0, 0);

    var portalScene = new THREE.Scene();
    this.portal = new THREE.Mesh(new THREE.PlaneGeometry(Portal.DOOR_WIDTH, Portal.DOOR_HEIGHT, 1, 1), new THREE.MeshBasicMaterial({ color: 0x000000 }));
    this.portal.position = portalPosition.clone();
    this.portal.position.y = Portal.DOOR_HEIGHT/2;
    this.portal.rotation.set(this.portalRotation.x, this.portalRotation.y, this.portalRotation.z);
    portalScene.add(this.portal);

    var clonedPortal = new THREE.Mesh(
        new THREE.CubeGeometry(Portal.DOOR_WIDTH, Portal.DOOR_HEIGHT, 1),
        new THREE.MeshBasicMaterial({ color: 0xFFFFFF }),
        0
    );
    clonedPortal.position = this.portal.position.clone();
    clonedPortal.rotation.set(this.portalRotation.x, this.portalRotation.y, this.portalRotation.z);
    //scene.add(clonedPortal);
    this.clonedPortal = clonedPortal;

    var backPortal = new THREE.Mesh(
        new THREE.CubeGeometry(Portal.DOOR_WIDTH, Portal.DOOR_HEIGHT, Portal.DOOR_BREADTH),
        new THREE.MeshBasicMaterial({ color: 0xFFFFFF }),
        0
    );
    backPortal.position = this.portal.position.clone();
    backPortal.position.z -= Portal.DOOR_BREADTH/2 + 1/2;
    backPortal.rotation.set(this.portalRotation.x, this.portalRotation.y, this.portalRotation.z);
    //scene.add(backPortal);
    this.backPortal = backPortal;

    this.clearMask = new THREE.ClearMaskPass();
    //clearMask.clear = true;
    //var tmpCam = new THREE.PerspectiveCamera(FIELD_OF_VIEW, window.innerWidth / window.innerHeight, 0.1, 1);
    //var tmpMesh = new THREE.Mesh(new THREE.PlaneGeometry(9999999, 9999999, 1, 1), new THREE.MeshBasicMaterial({ color: 0xFF00FF }));
    //var tmpScene = new THREE.Scene();
    //tmpMesh.z += 10;
    //tmpScene.add(tmpMesh);
    //tmpCam.lookAt(tmpMesh);
    //var clearMask = new THREE.MaskPass(tmpScene, tmpCam);
    //clearMask.inverse = true;
    //
    this.renderMask = new THREE.MaskPass(portalScene, prePortalCam);
    this.renderMask.clear = true;
    var renderModel = new THREE.RenderPass(scene, postPortalCam);

    this.composerScene = new THREE.EffectComposer(renderer, new THREE.WebGLRenderTarget(window.innerWidth, window.innerHeight, { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat, stencilBuffer: true } ) );
    this.composerScene.addPass(renderModel);

    this.renderScene = new THREE.TexturePass(this.composerScene.renderTarget2);

    composer.addPass(this.renderMask);
    composer.addPass(this.renderScene);
    composer.addPass(this.clearMask);
}

Portal.DOOR_WIDTH = 1;
Portal.DOOR_HEIGHT = 2;
Portal.DOOR_BREADTH = 0.1;

Portal.prototype = {

    destroy: function() {
        this.renderScene.enabled = false;
        this.scene.remove(this.clonedPortal);
        this.scene.remove(this.backPortal);
    },

    contains: function(vector) {
        var vector = this.prePortalCam.position.clone();

        var vFOV = FIELD_OF_VIEW * Math.PI / 180;        // convert vertical fov to radians
        var height = 2 * Math.tan( vFOV / 2 ) * vector.distanceTo(this.portalPosition); // visible height

        var aspect = window.innerWidth / window.innerHeight;
        var width = height * aspect;                  // visible width

        return false;
        return (width <= DOOR_WIDTH && height <= DOOR_HEIGHT);
    },

    collide: function() {
        console.log('warp');
        var warpPos = new THREE.Vector3(this.doorScenePosition.x, this.doorScenePosition.y, this.doorScenePosition.z);
        warpPos.y += primaryCamera_HEIGHT/2;
        this.primaryCamera.position = warpPos;
        //this.primaryCamera.hasTeleported = !this.primaryCamera.hasTeleported;
    },

    render: function() {
        this.renderScene.enabled = true;

        this.composerScene.render(0.1);

        //detect if portal is visible
        //thanks http://stackoverflow.com/questions/17624021/determine-if-a-mesh-is-visible-on-the-viewport-according-to-current-camera
        var frustum = new THREE.Frustum();
        var cameraViewProjectionMatrix = new THREE.Matrix4();

        // every time the camera or objects change position (or every frame)

        this.prePortalCam.updateMatrixWorld(); // make sure the camera matrix is updated
        this.prePortalCam.matrixWorldInverse.getInverse( this.prePortalCam.matrixWorld );
        cameraViewProjectionMatrix.multiplyMatrices( this.prePortalCam.projectionMatrix, this.prePortalCam.matrixWorldInverse );
        frustum.setFromMatrix( cameraViewProjectionMatrix );

        // frustum is now ready to check all the objects you need

        //if (this.primaryCamera.hasTeleported || !frustum.intersectsObject( this.portal )) {
        if (!frustum.intersectsObject( this.portal )) {
            this.renderScene.enabled = false;
        }
    }

}


text:
import gulp from "gulp";
import sourcemaps from "gulp-sourcemaps";
import connect from "gulp-connect";
import gutil from "gulp-util";
import buffer from "vinyl-buffer";
import source from "vinyl-source-stream";
import chalk from "chalk";
import browserify from "browserify";
import watchify from "watchify";
import babelify from "babelify";
import notifier from "node-notifier";
import config from "../config";

const BASE_DIR = __dirname.substring(0, __dirname.indexOf("gulp/tasks"));

function handleError(error) {
  notifier.notify({
    "title": "Build Error",
    "message": error.message
  });
  if (error.filename) {
    gutil.log(chalk.red(error.name) + " in " +
      chalk.white(error.filename.replace(BASE_DIR, "")) +
      ": " + "Line " + chalk.magenta(error.loc.line) + " & " +
      "Column " + chalk.magenta(error.loc.column) +
      " Message: " + chalk.yellow(error.message));
  } else {
    gutil.log(chalk.red(error.name) + ": " + chalk.yellow(error.message));
  }
}

var bundler = watchify(browserify(config.browserify.settings)
  .transform(babelify));

bundler.on("update", (files) => {
  files.forEach(f => {
    gutil.log(new Date()
      .toString() + ": Recompiling " + f.replace(BASE_DIR, ""));
  });
  bundle();
});

if (config.browserify.debug) {
  bundler.on("log", gutil.log);
}

function bundle() {
  return bundler
    .bundle()
    .on("error", handleError)
    .pipe(source(config.browserify.outFile))
    .pipe(buffer())
    .pipe(sourcemaps.init({
      loadMaps: true
    }))
    .pipe(sourcemaps.write("."))
    .pipe(gulp.dest(config.browserify.dest))
    .pipe(connect.reload());
}

gulp.task("browserify", bundle);


text: })(window, undefined);


text:
from __future__ import absolute_import, division, print_function

from cryptography import utils
from cryptography.exceptions import (
    InvalidSignature, UnsupportedAlgorithm, _Reasons
)
from cryptography.hazmat.backends.openssl.utils import _truncate_digest
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import (
    AsymmetricSignatureContext, AsymmetricVerificationContext, ec
)

def _truncate_digest_for_ecdsa(ec_key_cdata, digest, backend):
    """
    This function truncates digests that are longer than a given elliptic
    curve key's length so they can be signed. Since elliptic curve keys are
    much shorter than RSA keys many digests (e.g. SHA-512) may require
    truncation.
    """

    _lib = backend._lib
    _ffi = backend._ffi

    group = _lib.EC_KEY_get0_group(ec_key_cdata)

    with backend._tmp_bn_ctx() as bn_ctx:
        order = _lib.BN_CTX_get(bn_ctx)
        backend.openssl_assert(order != _ffi.NULL)

        res = _lib.EC_GROUP_get_order(group, order, bn_ctx)
        backend.openssl_assert(res == 1)

        order_bits = _lib.BN_num_bits(order)

    return _truncate_digest(digest, order_bits)

def _ec_key_curve_sn(backend, ec_key):
    group = backend._lib.EC_KEY_get0_group(ec_key)
    backend.openssl_assert(group != backend._ffi.NULL)

    nid = backend._lib.EC_GROUP_get_curve_name(group)
    # The following check is to find EC keys with unnamed curves and raise
    # an error for now.
    if nid == backend._lib.NID_undef:
        raise NotImplementedError(
            "ECDSA certificates with unnamed curves are unsupported "
            "at this time"
        )

    curve_name = backend._lib.OBJ_nid2sn(nid)
    backend.openssl_assert(curve_name != backend._ffi.NULL)

    sn = backend._ffi.string(curve_name).decode('ascii')
    return sn

def _mark_asn1_named_ec_curve(backend, ec_cdata):
    """
    Set the named curve flag on the EC_KEY. This causes OpenSSL to
    serialize EC keys along with their curve OID which makes
    deserialization easier.
    """

    backend._lib.EC_KEY_set_asn1_flag(
        ec_cdata, backend._lib.OPENSSL_EC_NAMED_CURVE
    )

def _sn_to_elliptic_curve(backend, sn):
    try:
        return ec._CURVE_TYPES[sn]()
    except KeyError:
        raise UnsupportedAlgorithm(
            "{0} is not a supported elliptic curve".format(sn),
            _Reasons.UNSUPPORTED_ELLIPTIC_CURVE
        )

@utils.register_interface(AsymmetricSignatureContext)
class _ECDSASignatureContext(object):
    def __init__(self, backend, private_key, algorithm):
        self._backend = backend
        self._private_key = private_key
        self._digest = hashes.Hash(algorithm, backend)

    def update(self, data):
        self._digest.update(data)

    def finalize(self):
        ec_key = self._private_key._ec_key

        digest = self._digest.finalize()

        digest = _truncate_digest_for_ecdsa(ec_key, digest, self._backend)

        max_size = self._backend._lib.ECDSA_size(ec_key)
        self._backend.openssl_assert(max_size > 0)

        sigbuf = self._backend._ffi.new("unsigned char[]", max_size)
        siglen_ptr = self._backend._ffi.new("unsigned int[]", 1)
        res = self._backend._lib.ECDSA_sign(
            0,
            digest,
            len(digest),
            sigbuf,
            siglen_ptr,
            ec_key
        )
        self._backend.openssl_assert(res == 1)
        return self._backend._ffi.buffer(sigbuf)[:siglen_ptr[0]]

@utils.register_interface(AsymmetricVerificationContext)
class _ECDSAVerificationContext(object):
    def __init__(self, backend, public_key, signature, algorithm):
        self._backend = backend
        self._public_key = public_key
        self._signature = signature
        self._digest = hashes.Hash(algorithm, backend)

    def update(self, data):
        self._digest.update(data)

    def verify(self):
        ec_key = self._public_key._ec_key

        digest = self._digest.finalize()

        digest = _truncate_digest_for_ecdsa(ec_key, digest, self._backend)

        res = self._backend._lib.ECDSA_verify(
            0,
            digest,
            len(digest),
            self._signature,
            len(self._signature),
            ec_key
        )
        if res != 1:
            self._backend._consume_errors()
            raise InvalidSignature
        return True

@utils.register_interface(ec.EllipticCurvePrivateKeyWithSerialization)
class _EllipticCurvePrivateKey(object):
    def __init__(self, backend, ec_key_cdata, evp_pkey):
        self._backend = backend
        _mark_asn1_named_ec_curve(backend, ec_key_cdata)
        self._ec_key = ec_key_cdata
        self._evp_pkey = evp_pkey

        sn = _ec_key_curve_sn(backend, ec_key_cdata)
        self._curve = _sn_to_elliptic_curve(backend, sn)

    curve = utils.read_only_property("_curve")

    def signer(self, signature_algorithm):
        if isinstance(signature_algorithm, ec.ECDSA):
            return _ECDSASignatureContext(
                self._backend, self, signature_algorithm.algorithm
            )
        else:
            raise UnsupportedAlgorithm(
                "Unsupported elliptic curve signature algorithm.",
                _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM)

    def exchange(self, algorithm, peer_public_key):
        if not (
            self._backend.elliptic_curve_exchange_algorithm_supported(
                algorithm, self.curve
            )
        ):
            raise UnsupportedAlgorithm(
                "This backend does not support the ECDH algorithm.",
                _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM
            )

        if peer_public_key.curve.name != self.curve.name:
            raise ValueError(
                "peer_public_key and self are not on the same curve"
            )

        group = self._backend._lib.EC_KEY_get0_group(self._ec_key)
        z_len = (self._backend._lib.EC_GROUP_get_degree(group) + 7) // 8
        self._backend.openssl_assert(z_len > 0)
        z_buf = self._backend._ffi.new("uint8_t[]", z_len)
        peer_key = self._backend._lib.EC_KEY_get0_public_key(
            peer_public_key._ec_key
        )

        r = self._backend._lib.ECDH_compute_key(
            z_buf, z_len, peer_key, self._ec_key, self._backend._ffi.NULL
        )
        self._backend.openssl_assert(r > 0)
        return self._backend._ffi.buffer(z_buf)[:z_len]

    def public_key(self):
        group = self._backend._lib.EC_KEY_get0_group(self._ec_key)
        self._backend.openssl_assert(group != self._backend._ffi.NULL)

        curve_nid = self._backend._lib.EC_GROUP_get_curve_name(group)

        public_ec_key = self._backend._lib.EC_KEY_new_by_curve_name(curve_nid)
        self._backend.openssl_assert(public_ec_key != self._backend._ffi.NULL)
        public_ec_key = self._backend._ffi.gc(
            public_ec_key, self._backend._lib.EC_KEY_free
        )

        point = self._backend._lib.EC_KEY_get0_public_key(self._ec_key)
        self._backend.openssl_assert(point != self._backend._ffi.NULL)

        res = self._backend._lib.EC_KEY_set_public_key(public_ec_key, point)
        self._backend.openssl_assert(res == 1)

        evp_pkey = self._backend._ec_cdata_to_evp_pkey(public_ec_key)

        return _EllipticCurvePublicKey(self._backend, public_ec_key, evp_pkey)

    def private_numbers(self):
        bn = self._backend._lib.EC_KEY_get0_private_key(self._ec_key)
        private_value = self._backend._bn_to_int(bn)
        return ec.EllipticCurvePrivateNumbers(
            private_value=private_value,
            public_numbers=self.public_key().public_numbers()
        )

    def private_bytes(self, encoding, format, encryption_algorithm):
        return self._backend._private_key_bytes(
            encoding,
            format,
            encryption_algorithm,
            self._evp_pkey,
            self._ec_key
        )

    def sign(self, data, signature_algorithm):
        signer = self.signer(signature_algorithm)
        signer.update(data)
        return signer.finalize()

@utils.register_interface(ec.EllipticCurvePublicKeyWithSerialization)
class _EllipticCurvePublicKey(object):
    def __init__(self, backend, ec_key_cdata, evp_pkey):
        self._backend = backend
        _mark_asn1_named_ec_curve(backend, ec_key_cdata)
        self._ec_key = ec_key_cdata
        self._evp_pkey = evp_pkey

        sn = _ec_key_curve_sn(backend, ec_key_cdata)
        self._curve = _sn_to_elliptic_curve(backend, sn)

    curve = utils.read_only_property("_curve")

    def verifier(self, signature, signature_algorithm):
        if not isinstance(signature, bytes):
            raise TypeError("signature must be bytes.")

        if isinstance(signature_algorithm, ec.ECDSA):
            return _ECDSAVerificationContext(
                self._backend, self, signature, signature_algorithm.algorithm
            )
        else:
            raise UnsupportedAlgorithm(
                "Unsupported elliptic curve signature algorithm.",
                _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM)

    def public_numbers(self):
        set_func, get_func, group = (
            self._backend._ec_key_determine_group_get_set_funcs(self._ec_key)
        )
        point = self._backend._lib.EC_KEY_get0_public_key(self._ec_key)
        self._backend.openssl_assert(point != self._backend._ffi.NULL)

        with self._backend._tmp_bn_ctx() as bn_ctx:
            bn_x = self._backend._lib.BN_CTX_get(bn_ctx)
            bn_y = self._backend._lib.BN_CTX_get(bn_ctx)

            res = get_func(group, point, bn_x, bn_y, bn_ctx)
            self._backend.openssl_assert(res == 1)

            x = self._backend._bn_to_int(bn_x)
            y = self._backend._bn_to_int(bn_y)

        return ec.EllipticCurvePublicNumbers(
            x=x,
            y=y,
            curve=self._curve
        )

    def public_bytes(self, encoding, format):
        if format is serialization.PublicFormat.PKCS1:
            raise ValueError(
                "EC public keys do not support PKCS1 serialization"
            )

        return self._backend._public_key_bytes(
            encoding,
            format,
            self,
            self._evp_pkey,
            None
        )

    def verify(self, signature, data, signature_algorithm):
        verifier = self.verifier(signature, signature_algorithm)
        verifier.update(data)
        verifier.verify()


text:
function New-IBObject
{
    [CmdletBinding(SupportsShouldProcess)]
    param(
        [Parameter(Mandatory,Position=0)]
        [Alias('type')]
        [string]$ObjectType,
        [Parameter(Mandatory,Position=1,ValueFromPipeline)]
        [PSObject]$IBObject,
        [Alias('fields','ReturnFields')]
        [string[]]$ReturnField,
        [Alias('base','ReturnBaseFields')]
        [switch]$ReturnBase,
        [switch]$BatchMode,
        [ValidateRange(1,2147483647)]
        [int]$BatchGroupSize = 1000,

        [ValidateScript({Test-ValidProfile $_ -ThrowOnFail})]
        [string]$ProfileName,
        [ValidateScript({Test-NonEmptyString $_ -ThrowOnFail})]
        [Alias('host')]
        [string]$WAPIHost,
        [ValidateScript({Test-VersionString $_ -ThrowOnFail})]
        [Alias('version')]
        [string]$WAPIVersion,
        [PSCredential]$Credential,
        [switch]$SkipCertificateCheck
    )

    Begin {

        # grab the variables we'll be using for our REST calls
        try { $opts = Initialize-CallVars @PSBoundParameters } catch { $PsCmdlet.ThrowTerminatingError($_) }

        $querystring = [String]::Empty

        # process the return fields
        if ($ReturnField.Count -gt 0) {
            if ($ReturnBase) {
                $querystring = "?_return_fields%2B=$($ReturnField -join ',')"
            }
            else {
                $querystring = "?_return_fields=$($ReturnField -join ',')"
            }
        }
        elseif ($ReturnBase) {
            $querystring = "?_return_fields%2B"
        }

        if ($BatchMode) {
            # create a list to save the objects in
            $deferredObjects = [Collections.Generic.List[PSObject]]::new()
        }
    }

    Process {

        if ($BatchMode) {
            # add the object to the list for processing during End{}
            $deferredObjects.Add($IBObject)
            return
        }

        # process the object now
        $queryParams = @{
            Query = '{0}{1}' -f $ObjectType,$querystring
            Method = 'Post'
            Body = $IBObject
        }
        if ($PSCmdlet.ShouldProcess($queryParams.Uri, "POST")) {
            Invoke-IBWAPI @queryParams @opts
        }
    }

    End {
        if (-not $BatchMode -or $deferredObjects.Count -eq 0) { return }
        Write-Verbose "BatchMode deferred objects: $($deferredObjects.Count), group size $($BatchGroupSize)"

        # build the 'args' value for each object
        $retArgs = @{}
        if ($ReturnField.Count -gt 0) {
            if ($ReturnBase) {
                $retArgs.'_return_fields+' = $ReturnField -join ','
            } else {
                $retArgs.'_return_fields'  = $ReturnField -join ','
            }
        } else {
            $retArgs.'_return_fields+' = ''
        }

        # make calls based on the group size
        for ($i=0; $i -lt $deferredObjects.Count; $i += $BatchGroupSize) {
            $groupEnd = [Math]::Min($deferredObjects.Count, ($i+$BatchGroupSize-1))

            # build the json for this group's objects
            $body = $deferredObjects[$i..$groupEnd] | ForEach-Object {
                @{
                    method = 'POST'
                    object = $ObjectType
                    data = $_
                    args = $retArgs
                }
            }

            if ($PSCmdlet.ShouldProcess($opts.WAPIHost, 'POST')) {
                Invoke-IBWAPI -Query 'request' -Method 'POST' -Body $body @opts
            }
        }

    }
}


text:
package org.hisp.dhis.analytics;

import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.Date;

import org.hisp.dhis.common.DimensionItemType;
import org.hisp.dhis.common.DimensionType;
import org.hisp.dhis.common.DimensionalItemObject;
import org.hisp.dhis.common.DimensionalObject;
import org.hisp.dhis.common.TotalAggregationType;
import org.hisp.dhis.common.ValueType;
import org.hisp.dhis.period.Period;
import org.hisp.dhis.program.Program;
import org.hisp.dhis.program.ProgramStage;

/**
 * Item part of meta data analytics response.
 *
* @author Lars Helge Overland
*/
public class MetadataItem
{
    private String name;

    private String legendSet;

    private String uid;

    private String code;

    private String description;

    private DimensionItemType dimensionItemType;

    private DimensionType dimensionType;

    private ValueType valueType;

    private AggregationType aggregationType;

    private TotalAggregationType totalAggregationType;

    private Date startDate;

    private Date endDate;

    // -------------------------------------------------------------------------
    // Constructors
    // -------------------------------------------------------------------------

    public MetadataItem( String name )
    {
        this.name = name;
    }

    public MetadataItem( String name, String uid, String code )
    {
        this.name = name;
        this.uid = uid;
        this.code = code;
    }

    public MetadataItem( String name, DimensionalItemObject dimensionalItemObject )
    {
        this.name = name;
        setDataItem( dimensionalItemObject );
    }

    public MetadataItem( String name, DimensionalObject dimensionalObject )
    {
        this.name = name;
        setDataItem( dimensionalObject );
    }

    public MetadataItem( String name, Program program )
    {
        this.name = name;

        if ( program == null )
        {
            return;
        }

        this.uid = program.getUid();
        this.code = program.getCode();
        this.description = program.getDescription();
    }

    public MetadataItem( String name, ProgramStage programStage )
    {
        this.name = name;

        if ( programStage == null )
        {
            return;
        }

        this.uid = programStage.getUid();
        this.code = programStage.getCode();
        this.description = programStage.getDescription();
    }

    // -------------------------------------------------------------------------
    // Logic
    // -------------------------------------------------------------------------

    private void setDataItem( DimensionalItemObject dimensionalItemObject )
    {
        if ( dimensionalItemObject == null )
        {
            return;
        }

        this.uid = dimensionalItemObject.getUid();
        this.code = dimensionalItemObject.getCode();
        this.dimensionItemType = dimensionalItemObject.getDimensionItemType();
        this.description = dimensionalItemObject.getDescription();
        this.aggregationType = dimensionalItemObject.getAggregationType();
        this.totalAggregationType = dimensionalItemObject.getTotalAggregationType();

        if ( dimensionalItemObject.hasLegendSet() )
        {
            this.legendSet = dimensionalItemObject.getLegendSet().getUid();
        }

        // TODO introduce start/end date marker interface instead

        if ( dimensionalItemObject instanceof Period )
        {
            Period period = (Period) dimensionalItemObject;
            this.startDate = period.getStartDate();
            this.endDate = period.getEndDate();
        }
    }

    private void setDataItem( DimensionalObject dimensionalObject )
    {
        if ( dimensionalObject == null )
        {
            return;
        }

        this.uid = dimensionalObject.getUid();
        this.code = dimensionalObject.getCode();
        this.dimensionType = dimensionalObject.getDimensionType();
        this.description = dimensionalObject.getDescription();
        this.aggregationType = dimensionalObject.getAggregationType();
    }

    // -------------------------------------------------------------------------
    // Get and set
    // -------------------------------------------------------------------------

    @JsonProperty
    public String getUid()
    {
        return uid;
    }

    public void setUid( String uid )
    {
        this.uid = uid;
    }

    @JsonProperty
    public String getCode()
    {
        return code;
    }

    public void setCode( String code )
    {
        this.code = code;
    }

    @JsonProperty
    public String getDescription()
    {
        return description;
    }

    public void setDescription( String description )
    {
        this.description = description;
    }

    @JsonProperty
    public DimensionType getDimensionType()
    {
        return dimensionType;
    }

    public void setDimensionType( DimensionType type )
    {
        this.dimensionType = type;
    }

    @JsonProperty
    public AggregationType getAggregationType()
    {
        return aggregationType;
    }

    public void setAggregationType( AggregationType itemSpecificType )
    {
        this.aggregationType = itemSpecificType;
    }

    @JsonProperty
    public DimensionItemType getDimensionItemType()
    {
        return dimensionItemType;
    }

    public void setDimensionItemType( DimensionItemType dimensionItemType )
    {
        this.dimensionItemType = dimensionItemType;
    }

    @JsonProperty
    public String getName()
    {
        return name;
    }

    public void setName( String name )
    {
        this.name = name;
    }

    @JsonProperty
    public String getLegendSet()
    {
        return legendSet;
    }

    public void setLegendSet( String legendSet )
    {
        this.legendSet = legendSet;
    }

    @JsonProperty
    public ValueType getValueType()
    {
        return valueType;
    }

    public void setValueType( ValueType valueType )
    {
        this.valueType = valueType;
    }

    @JsonProperty
    public TotalAggregationType getTotalAggregationType()
    {
        return totalAggregationType;
    }

    public void setTotalAggregationType( TotalAggregationType totalAggregationType )
    {
        this.totalAggregationType = totalAggregationType;
    }

    @JsonProperty
    public Date getStartDate()
    {
        return startDate;
    }

    public void setStartDate( Date startDate )
    {
        this.startDate = startDate;
    }

    @JsonProperty
    public Date getEndDate()
    {
        return endDate;
    }

    public void setEndDate( Date endDate )
    {
        this.endDate = endDate;
    }
}


text:
![Logo](http://majestic3.com/wp-content/uploads/2015/01/m3logosLONGie.png)

# Welcome to the Majestic 3 Open Source effort

#### GETTING STARTED

A great place to get up-to-speed quickly is the Majestic 3 Wiki and Website

http://www.majestic3.com

https://wiki.majestic3.com

### QUESTIONS AND FEEDBACK

Online documentation can be found at https://wiki.majestic3.com/category/frequently-asked-questions

If you find code in this repository behaving in an unexpected manner or
contrary to its documented behavior, please create an issue in our GitHub
issue tracker:

https://github.com/ettienem3/majestic3-open-source/issues/new

## Reporting Potential Security Issues

If you have encountered a potential security vulnerability in Majestic 3, please report it to us. We will work with you to verify the vulnerability and patch it.

When reporting issues, please provide the following information:

- Component(s) affected
- A description indicating how to reproduce the issue
- A summary of the security vulnerability and impact

We request that you contact us via the email address below and give the project contributors a chance to resolve the vulnerability and issue a new release prior to any public exposure; this helps protect Majestic 3 users and provides them with a chance to upgrade and/or update in order to protect their applications.

issues@majestic3.com

### LICENSE

This project and its source code is made freely available for you to change, adapt, improve, break, base other work on it, redistribute etc.

By no means what so ever will Majestic3.com, any of their employees and staff, any affiliates of their business, service providers, share holders, stake holders or consultants be held responsible for any problems, issues, service problems, environmental factors, experience levels, loss of business, financial loss, reputational risk and damage, intended and unintended failures, loss of information either by security leaks, hacks, improper design, invalid certificates, man in the middle attackes, the list goes. The software is provided as is and with no warrenties or guarentees.

In summary, we will not be held responsible for anything and by using any of the code provided, you agree to the terms and conditions.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

    Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

    Neither the name of Majestic 3, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The files in this archive are released under the Apache License, Version 2.0.
You can find a copy of this license in [LICENCE.md](LICENCE.md).


text:
module AccountsHelper

  def get_slug
    account = Account.find @current_user.current_account_id
    return account.slug
  end
end


text:
#include <zephyr.h>
#include <kernel.h>
#include <misc/printk.h>

/* This function will allow execute from sram region.
 * This is needed only for this sample because by default all soc will
 * disable the execute from SRAM.
 * An application that requires that the code be executed from SRAM will
 *  have to configure the region appropriately in arm_mpu_regions.c.
 */

#ifdef CONFIG_ARM_MPU
#include <arch/arm/cortex_m/cmsis.h>
void disable_mpu_rasr_xn(void)
{
	u32_t index;
	/* Kept the max index as 8(irrespective of soc) because the sram
	 * would most likely be set at index 2.
	 */
	for (index = 0U; index < 8; index++) {
		MPU->RNR = index;
		if (MPU->RASR & MPU_RASR_XN_Msk) {
			MPU->RASR ^= MPU_RASR_XN_Msk;
		}
	}

}
#endif	/* CONFIG_ARM_MPU */

extern void function_in_sram2(void);
extern void function_in_split_multiple(void);

void main(void)
{
#ifdef CONFIG_ARM_MPU
	disable_mpu_rasr_xn();
#endif	/* CONFIG_ARM_MPU */

	printk("Address of main function %p\n\n", &main);
	function_in_sram2();
	function_in_split_multiple();
}


text:
#!/usr/bin/env python
# Copyright (c) 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""This script will check out llvm and clang, and then package the results up
to a tgz file."""

import argparse
import fnmatch
import itertools
import os
import shutil
import subprocess
import sys
import tarfile

# Path constants.
THIS_DIR = os.path.dirname(__file__)
THIRD_PARTY_DIR = os.path.join(THIS_DIR, '..', '..', '..', 'third_party')
LLVM_DIR = os.path.join(THIRD_PARTY_DIR, 'llvm')
LLVM_BOOTSTRAP_DIR = os.path.join(THIRD_PARTY_DIR, 'llvm-bootstrap')
LLVM_BOOTSTRAP_INSTALL_DIR = os.path.join(THIRD_PARTY_DIR,
                                          'llvm-bootstrap-install')
LLVM_BUILD_DIR = os.path.join(THIRD_PARTY_DIR, 'llvm-build')
LLVM_RELEASE_DIR = os.path.join(LLVM_BUILD_DIR, 'Release+Asserts')
STAMP_FILE = os.path.join(LLVM_BUILD_DIR, 'cr_build_revision')

def Tee(output, logfile):
  logfile.write(output)
  print output,

def TeeCmd(cmd, logfile, fail_hard=True):
  """Runs cmd and writes the output to both stdout and logfile."""
  # Reading from PIPE can deadlock if one buffer is full but we wait on a
  # different one.  To work around this, pipe the subprocess's stderr to
  # its stdout buffer and don't give it a stdin.
  # shell=True is required in cmd.exe since depot_tools has an svn.bat, and
  # bat files only work with shell=True set.
  proc = subprocess.Popen(cmd, bufsize=1, shell=sys.platform == 'win32',
                          stdin=open(os.devnull), stdout=subprocess.PIPE,
                          stderr=subprocess.STDOUT)
  for line in iter(proc.stdout.readline,''):
    Tee(line, logfile)
    if proc.poll() is not None:
      break
  exit_code = proc.wait()
  if exit_code != 0 and fail_hard:
    print 'Failed:', cmd
    sys.exit(1)

def PrintTarProgress(tarinfo):
  print 'Adding', tarinfo.name
  return tarinfo

def main():
  if sys.platform == 'win32':
    try:
      subprocess.check_output(['grep', '--help'], shell=True)
    except subprocess.CalledProcessError:
      print 'Add gnuwin32 to your PATH, then try again.'
      return 1

  parser = argparse.ArgumentParser(description='build and package clang')
  parser.add_argument('--gcc-toolchain',
                      help="the prefix for the GCC version used for building. "
                           "For /opt/foo/bin/gcc, pass "
                           "'--gcc-toolchain '/opt/foo'")

  args = parser.parse_args()

  with open('buildlog.txt', 'w') as log:
    Tee('Diff in llvm:\n', log)
    TeeCmd(['svn', 'stat', LLVM_DIR], log, fail_hard=False)
    TeeCmd(['svn', 'diff', LLVM_DIR], log, fail_hard=False)
    Tee('Diff in llvm/tools/clang:\n', log)
    TeeCmd(['svn', 'stat', os.path.join(LLVM_DIR, 'tools', 'clang')],
           log, fail_hard=False)
    TeeCmd(['svn', 'diff', os.path.join(LLVM_DIR, 'tools', 'clang')],
           log, fail_hard=False)
    # TODO(thakis): compiler-rt is in projects/compiler-rt on Windows but
    # llvm/compiler-rt elsewhere. So this diff call is currently only right on
    # Windows.
    Tee('Diff in llvm/compiler-rt:\n', log)
    TeeCmd(['svn', 'stat', os.path.join(LLVM_DIR, 'projects', 'compiler-rt')],
           log, fail_hard=False)
    TeeCmd(['svn', 'diff', os.path.join(LLVM_DIR, 'projects', 'compiler-rt')],
           log, fail_hard=False)
    Tee('Diff in llvm/projects/libcxx:\n', log)
    TeeCmd(['svn', 'stat', os.path.join(LLVM_DIR, 'projects', 'libcxx')],
           log, fail_hard=False)
    TeeCmd(['svn', 'diff', os.path.join(LLVM_DIR, 'projects', 'libcxx')],
           log, fail_hard=False)
    Tee('Diff in llvm/projects/libcxxabi:\n', log)
    TeeCmd(['svn', 'stat', os.path.join(LLVM_DIR, 'projects', 'libcxxabi')],
           log, fail_hard=False)
    TeeCmd(['svn', 'diff', os.path.join(LLVM_DIR, 'projects', 'libcxxabi')],
           log, fail_hard=False)

    Tee('Starting build\n', log)

    # Do a clobber build.
    shutil.rmtree(LLVM_BOOTSTRAP_DIR, ignore_errors=True)
    shutil.rmtree(LLVM_BOOTSTRAP_INSTALL_DIR, ignore_errors=True)
    shutil.rmtree(LLVM_BUILD_DIR, ignore_errors=True)

    build_cmd = [sys.executable, os.path.join(THIS_DIR, 'update.py'),
                 '--bootstrap', '--force-local-build', '--run-tests']
    if args.gcc_toolchain is not None:
      build_cmd.extend(['--gcc-toolchain', args.gcc_toolchain])
    TeeCmd(build_cmd, log)

  stamp = open(STAMP_FILE).read().rstrip()
  pdir = 'clang-' + stamp
  print pdir
  shutil.rmtree(pdir, ignore_errors=True)

  # Copy a whitelist of files to the directory we're going to tar up.
  # This supports the same patterns that the fnmatch module understands.
  exe_ext = '.exe' if sys.platform == 'win32' else ''
  want = ['bin/llvm-symbolizer' + exe_ext,
          'lib/clang/*/asan_blacklist.txt',
          'lib/clang/*/cfi_blacklist.txt',
          # Copy built-in headers (lib/clang/3.x.y/include).
          'lib/clang/*/include/*',
          ]
  if sys.platform == 'win32':
    want.append('bin/clang-cl.exe')
    want.append('bin/lld-link.exe')
  else:
    so_ext = 'dylib' if sys.platform == 'darwin' else 'so'
    want.extend(['bin/clang',
                 'lib/libFindBadConstructs.' + so_ext,
                 'lib/libBlinkGCPlugin.' + so_ext,
                 ])
  if sys.platform == 'darwin':
    want.extend(['bin/libc++.1.dylib',
                 # Copy only the OSX (ASan and profile) and iossim (ASan)
                 # runtime libraries:
                 'lib/clang/*/lib/darwin/*asan_osx*',
                 'lib/clang/*/lib/darwin/*asan_iossim*',
                 'lib/clang/*/lib/darwin/*profile_osx*',
                 ])
  elif sys.platform.startswith('linux'):
    # Copy only
    # lib/clang/*/lib/linux/libclang_rt.{[atm]san,san,ubsan,profile}-*.a ,
    # but not dfsan.
    want.extend(['lib/clang/*/lib/linux/*[atm]san*',
                 'lib/clang/*/lib/linux/*ubsan*',
                 'lib/clang/*/lib/linux/*libclang_rt.san*',
                 'lib/clang/*/lib/linux/*profile*',
                 'lib/clang/*/msan_blacklist.txt',
                 ])
  elif sys.platform == 'win32':
    want.extend(['lib/clang/*/lib/windows/clang_rt.asan*.dll',
                 'lib/clang/*/lib/windows/clang_rt.asan*.lib',
                 'lib/clang/*/include_sanitizer/*',
                 ])
  if args.gcc_toolchain is not None:
    # Copy the stdlibc++.so.6 we linked Clang against so it can run.
    want.append('lib/libstdc++.so.6')

  for root, dirs, files in os.walk(LLVM_RELEASE_DIR):
    # root: third_party/llvm-build/Release+Asserts/lib/..., rel_root: lib/...
    rel_root = root[len(LLVM_RELEASE_DIR)+1:]
    rel_files = [os.path.join(rel_root, f) for f in files]
    wanted_files = list(set(itertools.chain.from_iterable(
        fnmatch.filter(rel_files, p) for p in want)))
    if wanted_files:
      # Guaranteed to not yet exist at this point:
      os.makedirs(os.path.join(pdir, rel_root))
    for f in wanted_files:
      src = os.path.join(LLVM_RELEASE_DIR, f)
      dest = os.path.join(pdir, f)
      shutil.copy(src, dest)
      # Strip libraries.
      if sys.platform == 'darwin' and f.endswith('.dylib'):
        # Fix LC_ID_DYLIB for the ASan dynamic libraries to be relative to
        # @executable_path.
        # TODO(glider): this is transitional. We'll need to fix the dylib
        # name either in our build system, or in Clang. See also
        # http://crbug.com/344836.
        subprocess.call(['install_name_tool', '-id',
                         '@executable_path/' + os.path.basename(dest), dest])
        subprocess.call(['strip', '-x', dest])
      elif (sys.platform.startswith('linux') and
            os.path.splitext(f)[1] in ['.so', '.a']):
        subprocess.call(['strip', '-g', dest])

  # Set up symlinks.
  if sys.platform != 'win32':
    os.symlink('clang', os.path.join(pdir, 'bin', 'clang++'))
    os.symlink('clang', os.path.join(pdir, 'bin', 'clang-cl'))
  if sys.platform == 'darwin':
    os.symlink('libc++.1.dylib', os.path.join(pdir, 'bin', 'libc++.dylib'))
    # Also copy libc++ headers.
    shutil.copytree(os.path.join(LLVM_BOOTSTRAP_INSTALL_DIR, 'include', 'c++'),
                    os.path.join(pdir, 'include', 'c++'))

  # Copy buildlog over.
  shutil.copy('buildlog.txt', pdir)

  # Create archive.
  tar_entries = ['bin', 'lib', 'buildlog.txt']
  if sys.platform == 'darwin':
    tar_entries += ['include']
  with tarfile.open(pdir + '.tgz', 'w:gz') as tar:
    for entry in tar_entries:
      tar.add(os.path.join(pdir, entry), arcname=entry, filter=PrintTarProgress)

  if sys.platform == 'darwin':
    platform = 'Mac'
  elif sys.platform == 'win32':
    platform = 'Win'
  else:
    platform = 'Linux_x64'

  print 'To upload, run:'
  print ('gsutil cp -a public-read %s.tgz '
         'gs://chromium-browser-clang/%s/%s.tgz') % (pdir, platform, pdir)

  # Zip up gold plugin on Linux.
  if sys.platform.startswith('linux'):
    golddir = 'llvmgold-' + stamp
    shutil.rmtree(golddir, ignore_errors=True)
    os.makedirs(os.path.join(golddir, 'lib'))
    shutil.copy(os.path.join(LLVM_RELEASE_DIR, 'lib', 'LLVMgold.so'),
                os.path.join(golddir, 'lib'))
    with tarfile.open(golddir + '.tgz', 'w:gz') as tar:
      tar.add(os.path.join(golddir, 'lib'), arcname='lib',
              filter=PrintTarProgress)
    print ('gsutil cp -a public-read %s.tgz '
           'gs://chromium-browser-clang/%s/%s.tgz') % (golddir, platform,
                                                       golddir)

  # FIXME: Warn if the file already exists on the server.

if __name__ == '__main__':
  sys.exit(main())


text:
@interface RSDeviceConfigViewController : RSBaseModalViewController

@property (nonatomic, strong) RSDevice *device;

@end


text:
/**
 * socket io communication class for cleaning project request to server
 */
var CleanProjectSocket = (function () {
    /**
     * create new instance
     * @param socket socket io instance
     */
    function CleanProjectSocket(socket) {
        this.socket = socket;
    }
    /**
     * Adds a listener for this event that will be invoked a single time before being automatically removed
     * @param callback The function to call when we get the event
     */
    CleanProjectSocket.prototype.onEvent = function (callback) {
        this.socket.once(CleanProjectSocket.eventName, callback);
    };
    /**
     * emit to server for cleaning project
     * @param projectPath project path name
     * @param callback The function to call when we get the event
     */
    CleanProjectSocket.prototype.emit = function (projectPath, callback) {
        this.onEvent(callback);
        this.socket.emit(CleanProjectSocket.eventName, projectPath);
    };
    return CleanProjectSocket;
}());
/**
 * event name
 */
CleanProjectSocket.eventName = 'cleanProject';
//# sourceMappingURL=cleanProjectSocket.js.map


text:
sendhub-python
==============


text:
var test = require('tap').test,
    ecstatic = require('../'),
    http = require('http'),
    request = require('request');

test('range', function (t) {
  t.plan(4);
  var server = http.createServer(ecstatic(__dirname + '/public/subdir'));
  t.on('end', function () { server.close() })

  server.listen(0, function () {
    var port = server.address().port;
    var opts = {
      uri: 'http://localhost:' + port + '/e.html',
      headers: { range: '3-5' }
    };
    request.get(opts, function (err, res, body) {
      t.ifError(err);
      t.equal(res.statusCode, 206, 'partial content status code');
      t.equal(body, 'e!!');
      t.equal(parseInt(res.headers['content-length']), body.length);
    });
  });
});

test('range past the end', function (t) {
  t.plan(4);
  var server = http.createServer(ecstatic(__dirname + '/public/subdir'));
  t.on('end', function () { server.close() })

  server.listen(0, function () {
    var port = server.address().port;
    var opts = {
      uri: 'http://localhost:' + port + '/e.html',
      headers: { range: '3-500' }
    };
    request.get(opts, function (err, res, body) {
      t.ifError(err);
      t.equal(res.statusCode, 206, 'partial content status code');
      t.equal(body, 'e!!\n');
      t.equal(parseInt(res.headers['content-length']), body.length);
    });
  });
});

test('NaN range', function (t) {
  t.plan(3);
  var server = http.createServer(ecstatic(__dirname + '/public/subdir'));
  t.on('end', function () { server.close() })

  server.listen(0, function () {
    var port = server.address().port;
    var opts = {
      uri: 'http://localhost:' + port + '/e.html',
      headers: { range: 'abc-def' }
    };
    request.get(opts, function (err, res, body) {
      t.ifError(err);
      t.equal(res.statusCode, 416, 'range error status code');
      t.equal(body, 'Requested range not satisfiable');
    });
  });
});

test('flipped range', function (t) {
  t.plan(3);
  var server = http.createServer(ecstatic(__dirname + '/public/subdir'));
  t.on('end', function () { server.close() })

  server.listen(0, function () {
    var port = server.address().port;
    var opts = {
      uri: 'http://localhost:' + port + '/e.html',
      headers: { range: '333-222' }
    };
    request.get(opts, function (err, res, body) {
      t.ifError(err);
      t.equal(res.statusCode, 416, 'range error status code');
      t.equal(body, 'Requested range not satisfiable');
    });
  });
});

test('partial range', function (t) {
  t.plan(5);
  var server = http.createServer(ecstatic(__dirname + '/public/subdir'));
  t.on('end', function () { server.close() })

  server.listen(0, function () {
    var port = server.address().port;
    var opts = {
      uri: 'http://localhost:' + port + '/e.html',
      headers: { range: '3-' }
    };
    request.get(opts, function (err, res, body) {
      t.ifError(err);
      t.equal(res.statusCode, 206, 'partial content status code');
      t.equal(body, 'e!!\n');
      t.equal(parseInt(res.headers['content-length']), body.length);
      t.equal(res.headers['content-range'], 'bytes 3-10/11');
    });
  });
});


text:
package st.domain.ggviario.secret.dao;

import android.content.Context;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import st.domain.ggviario.secret.fragments.CreditPayBottomSheetDialogFragment;
import st.domain.ggviario.secret.model.Client;
import st.domain.ggviario.secret.model.Credit;
import st.domain.ggviario.secret.model.CreditProduct;
import st.domain.ggviario.secret.model.Measure;
import st.domain.ggviario.secret.model.Product;
import st.zudamue.support.android.sql.OnQueryResult;
import st.zudamue.support.android.sql.SQLRow;

/**
 *
 * Created by dchost on 10/02/17.
 */

public class CreditsDao extends Dao<Credit> {

    public CreditsDao(Context context) {
        super(context);
    }

    public void loadCreditClient( Client client, final OnLoadData<Credit> onLoadData ) {
        query(
                select("*")
                    .from($credit)
                    .where( credit.credi_cli_id ).equal( value( client.getId() ) )
        );

        onQueryResult(new OnQueryResult() {
            @Override
            public boolean accept(SQLRow row) {
                Credit credit = mount(row);
                return onLoadData.onLoad(credit, row );
            }
        });
    }

    private Credit mount(SQLRow row ) {

        final List<CreditProduct> list = new LinkedList<>();
        query(
                select("*")
                .from($creditproduct)
                .where(creditproduct.crediprod_credi_id).equal( value( row.integer( credit.credi_id ) ) )

        ).forLoopCursor( new OnAllQueryResults() {
            @Override
            protected void onRow(SQLRow row) {
                CreditProduct creditProduct = mountCreditProduct( row );
                list.add(creditProduct);
            }
        });

        return new Credit(
                row.integer(credit.credi_id),
                row.real( credit.credi_valuetotal ),
                row.date( credit.credi_dtreg ),
                list,
                row.real( credit.credi_valuepay),
                row.integer( credit.credi_state )
        );
    }

    private CreditProduct mountCreditProduct(SQLRow row) {

        ProductDao productDao = new ProductDao( this.getContext() );
        Product product = productDao.getProduct(row.integer( creditproduct.crediprod_prod_id ) );
        Measure measure = productDao.getMeasureById( row.integer( creditproduct.crediprod_meas_id ) );

        return new CreditProduct(
                row.integer( creditproduct.crediprod_id ),
                product,
                row.realDouble( creditproduct.crediprod_quantity ),
                row.real( creditproduct.crediprod_price),
                measure,
                row.real( creditproduct.crediprod_pricequantity )
        );
    }

    public boolean registerCredit(Client client, Date dateFinisher, double valueTotal, List< CreditProduct > creditProducts) {

        execute(
                insertInto($credit)
                .columns(
                        credit.credi_cli_id,
                        credit.credi_dtfinalizar,
                        credit.credi_user_id,
                        credit.credi_valuetotal
                ) . values (
                        client.getId(),
                        date( dateFinisher ),
                        super.getCurrentUserId(),
                        valueTotal
                )
        );

        long idCredit = getResultExecut();

        for( CreditProduct item: creditProducts ) {

            execute(
                    insertInto($creditproduct).columns(
                            creditproduct.crediprod_credi_id,
                            creditproduct.crediprod_prod_id,
                            creditproduct.crediprod_quantity,
                            creditproduct.crediprod_user_id,
                            creditproduct.crediprod_price,
                            creditproduct.crediprod_pricequantity,
                            creditproduct.crediprod_meas_id
                    ) . values(
                            idCredit,
                            item.getProduct().getId(),
                            item.getQuantity(),
                            getCurrentUserId(),
                            item.getPrice(),
                            item.getPriceQuantity(),
                            item.getMeasure().getId()
                    )
            );
        }

        return true;
    }

    public boolean payCredit(Credit vCredit, float value, String documentPayment) {
        if( vCredit.getState() > 0 ){
            int newState = vCredit.getValuePay() + value == vCredit.getValueTotal()? 0 : 2;

            AccountDao accountDao = new AccountDao( this.getContext() );
            boolean result = accountDao.regMovementAccount( 1, value, 0, "Pagamento de "+value+" para credito "+vCredit.getId(), documentPayment, $credit, vCredit.getId() );
            if( !result ) return false;

            execute(
                    update( $credit )
                        .set( credit.credi_valuepay , argumentOperation( credit.credi_valuepay, " + ", value( value ) ) )
                        .set( credit.credi_state, value( newState ))
                        .where( credit.credi_id ).equal( value( vCredit.getId() ))
            );
        }
        return false;
    }
}


text:
.class public final Lcom/google/android/gms/plus/model/people/Person$Gender;
.super Ljava/lang/Object;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/google/android/gms/plus/model/people/Person;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x19
    name = "Gender"
.end annotation

# static fields
.field public static final FEMALE:I = 0x1

.field public static final MALE:I = 0x0

.field public static final OTHER:I = 0x2

# direct methods
.method private constructor <init>()V
    .locals 0

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method


text:
package exemplo12.polimorfismo;

public class Gato implements Barulhento {

	@Override
	public void fazBarulho() {
		System.out.println("miauuu miauuu");

	}

}


text:
package org.esupportail.pstage.domain;

import java.util.List;

import org.esupportail.pstagedata.domain.dto.AffectationDTO;
import org.esupportail.pstagedata.domain.dto.PersonnelCentreGestionDTO;
import org.esupportail.pstagedata.exceptions.AffectationAlreadyExistingForCodeException;
import org.esupportail.pstagedata.exceptions.DataAddException;
import org.esupportail.pstagedata.exceptions.DataDeleteException;
import org.esupportail.pstagedata.exceptions.DataUpdateException;
import org.esupportail.pstagedata.exceptions.PersonalAlreadyExistingForCentreException;
import org.esupportail.pstagedata.exceptions.WebServiceDataBaseException;
import org.esupportail.pstagedata.remote.RemoteServices;
import org.springframework.dao.DataAccessException;

/**
 * PersonnelCentreGestion Domain service impl.
 */
/**
 * @author Florian Garot : florian.garot@univ-artois.fr
 *
 */
public class PersonnelCentreGestionDomainServiceImpl implements PersonnelCentreGestionDomainService {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * Code Universite
	 */
	String codeUniversite;

	/**
	 * ListeDomainService
	 */
	private NomenclatureDomainService nomenclatureDomainService;

	/**
	 * @return the nomenclatureDomainService
	 */
	public NomenclatureDomainService getNomenclatureDomainService() {
		return nomenclatureDomainService;
	}

	/**
	 * @param nomenclatureDomainService the nomenclatureDomainService to set
	 */
	public void setNomenclatureDomainService(
			NomenclatureDomainService nomenclatureDomainService) {
		this.nomenclatureDomainService = nomenclatureDomainService;
	}

	/**
	 * CentreGestionDomainService
	 */
	private CentreGestionDomainService centreGestionDomainService;

	/**
	 * @return the centreGestionDomainService
	 */
	public CentreGestionDomainService getCentreGestionDomainService() {
		return centreGestionDomainService;
	}
	/**
	 * @param CentreGestionDomainService the CentreGestionDomainService to set
	 */
	public void setCentreGestionDomainService(CentreGestionDomainService centreGestionDomainService) {
		this.centreGestionDomainService = centreGestionDomainService;
	}
	/**
	 * RemoteServices
	 */
	private RemoteServices remoteServices;

	/**
	 * @return the remoteServices
	 */
	public RemoteServices getRemoteServices(){
		return remoteServices;
	}

	/**
	 * @param remoteServices the remoteServices to set
	 */
	public void setRemoteServices(RemoteServices remoteServices) {
		this.remoteServices = remoteServices;
	}

	/**
	 * @see org.esupportail.pstage.domain.PersonnelCentreGestionDomainService#getPersonnelCentreGestionList(int)
	 */
	public List<PersonnelCentreGestionDTO> getPersonnelCentreGestionList(int idCentreGestion){
		List<PersonnelCentreGestionDTO> l = this.remoteServices.getPersonnelCentreGestionList(idCentreGestion);
		setObjectsForPersonnel(l);
		return l;
	}
	/**
	 * @see org.esupportail.pstage.domain.PersonnelCentreGestionDomainService#getNombrePersonnelCentreGestion(int)
	 */
	public int getNombrePersonnelCentreGestion(int idCentreGestion){
		return this.remoteServices.getNombrePersonnelCentreGestion(idCentreGestion);
	}
	/**
	 * @see org.esupportail.pstage.domain.PersonnelCentreGestionDomainService#getPersonnelCentreGestion(int)
	 */
	public PersonnelCentreGestionDTO getPersonnelCentreGestion(int idPersonnelCentreGestion){
		PersonnelCentreGestionDTO p = this.remoteServices.getPersonnelCentreGestion(idPersonnelCentreGestion);
		setObjectsForPersonnel(p);
		return p;
	}

	/**
	 * @see org.esupportail.pstage.domain.PersonnelCentreGestionDomainService#getInterlocuteur(int)
	 */
	public List<PersonnelCentreGestionDTO> getInterlocuteur(int idCentreGestion){
		List <PersonnelCentreGestionDTO> l = this.remoteServices.getInterlocuteur(idCentreGestion);
		setObjectsForPersonnel(l);
		return l;
	}

	/**
	 * @see org.esupportail.pstage.domain.PersonnelCentreGestionDomainService#getPersonnelCentreGestionFromUidAndCentre(String,int)
	 */
	public PersonnelCentreGestionDTO getPersonnelCentreGestionFromUidAndCentre(String uidPersonnelCentreGestion, int idCentreGestion){
		PersonnelCentreGestionDTO p = this.remoteServices.getPersonnelCentreGestionFromUidAndCentre(uidPersonnelCentreGestion, idCentreGestion);
		setObjectsForPersonnel(p);
		return p;
	}

	/**
	 * @see org.esupportail.pstage.domain.PersonnelCentreGestionDomainService#getPersonnelCentreGestionFromUid(String,String)
	 */
	public List<PersonnelCentreGestionDTO> getPersonnelCentreGestionFromUid(String uidPersonnel,String codeUniversite){
		List<PersonnelCentreGestionDTO> l = this.remoteServices.getPersonnelCentreGestionFromUid(uidPersonnel, codeUniversite);
		setObjectsForPersonnel(l);
		return l;
	}

	/**
	 * @see org.esupportail.pstage.domain.PersonnelCentreGestionDomainService#getPersonnelCentreGestionFromNom(String,String)
	 */
	public PersonnelCentreGestionDTO getPersonnelCentreGestionFromNom(String nom, String codeUniversite){
		PersonnelCentreGestionDTO p = this.remoteServices.getPersonnelCentreGestionFromNom(nom, codeUniversite);
		setObjectsForPersonnel(p);
		return p;
	}

	/**
	 * @throws PersonalAlreadyExistingForCentreException
	 * @throws DataAddException
	 * @throws WebServiceDataBaseException
	 * @see org.esupportail.pstage.domain.PersonnelCentreGestionDomainService#addPersonnelCentreGestion(org.esupportail.pstagedata.domain.dto.PersonnelCentreGestionDTO)
	 */
	public int addPersonnelCentreGestion(PersonnelCentreGestionDTO pg) throws DataAccessException, WebServiceDataBaseException, DataAddException, PersonalAlreadyExistingForCentreException{
		return this.remoteServices.addPersonnelCentreGestion(pg);
	}

	/**
	 * @throws WebServiceDataBaseException
	 * @throws DataUpdateException
	 * @see org.esupportail.pstage.domain.PersonnelCentreGestionDomainService#updatePersonnelCentreGestion(org.esupportail.pstagedata.domain.dto.PersonnelCentreGestionDTO)
	 */
	public boolean updatePersonnelCentreGestion(PersonnelCentreGestionDTO pg) throws DataAccessException, DataUpdateException, WebServiceDataBaseException{
		return this.remoteServices.updatePersonnelCentreGestion(pg);
	}

	/**
	 * @throws DataDeleteException
	 * @throws WebServiceDataBaseException
	 * @see org.esupportail.pstage.domain.PersonnelCentreGestionDomainService#deletePersonnelCentreGestion(int)
	 */
	public boolean deletePersonnelCentreGestion(int idCentreGestion, int idPersonnelCentreGestion) throws DataAccessException, WebServiceDataBaseException, DataDeleteException{
		return this.remoteServices.deletePersonnelCentreGestion(idCentreGestion, idPersonnelCentreGestion);
	}

	/**
	 * @see org.esupportail.pstage.domain.PersonnelCentreGestionDomainService#getNombreAffectation()
	 */
	public int getNombreAffectation(){
		return this.remoteServices.getNombreAffectation();
	}

	/**
	 * @throws AffectationAlreadyExistingForCodeException
	 * @see org.esupportail.pstage.domain.PersonnelCentreGestionDomainService#addAffectation(org.esupportail.pstagedata.domain.dto.AffectationDTO)
	 */
	public int addAffectation(AffectationDTO a) throws DataAddException,WebServiceDataBaseException, AffectationAlreadyExistingForCodeException{
		return this.remoteServices.addAffectation(a);
	}

	/**
	 * Rempli les divers objets (Pays, TypeStructure, ...) depuis les listes en caches
	 * @param ls
	 */
	public void setObjectsForPersonnel(List<PersonnelCentreGestionDTO> lp){
		if(lp!=null){
			for(PersonnelCentreGestionDTO p : lp){
				setObjectsForPersonnel(p);
			}
		}
	}

	/**
	 * Rempli les divers objets depuis les listes en caches
	 * @param s
	 */
	public void setObjectsForPersonnel(PersonnelCentreGestionDTO p){
		if(p!=null){
			if (p.getCodeAffectation() != null)
				p.setAffectation(this.nomenclatureDomainService.getAffectationFromCode(p.getCodeAffectation(), codeUniversite));
			if (p.getIdDroitAdmin() > 0)
				p.setDroitAdmin(this.nomenclatureDomainService.getDroitAdministrationFromId(p.getIdDroitAdmin()));
			if (p.getIdCentreGestion() > 0)
				p.setCentreGestion(this.centreGestionDomainService.getCentreGestion(p.getIdCentreGestion()));
			if (p.getIdCivilite() > 0)
				p.setCivilite(this.nomenclatureDomainService.getCiviliteFromId(p.getIdCivilite()));
		}
	}

	/**
	 * @return the codeUniversite
	 */
	public String getCodeUniversite() {
		return codeUniversite;
	}

	/**
	 * @param codeUniversite the codeUniversite to set
	 */
	public void setCodeUniversite(String codeUniversite) {
		this.codeUniversite = codeUniversite;
	}

}


text:
Some text on sa4 line 3.

    This text on sa4 line 5 will disappear.
    Text from sa4 line 6 is filled into slot1.
    This text on sa4 line 7 will disappear.

This is some text on sa4 line 9.


text:
def main():
    pass

# code from the actual twilioquest task

# standard main guard
if ("__main__" == __name__):
    main()


text:
<html>
<head><title>rich text</title></head>
<script>
function start() {
    window.frames["richtext"].document.designMode="on";
}
</script>
<body onload="start();">
    <iframe id="richtext" name="richtext"/>
</body>
</html>


text:
/*global define*/
define([
    'jquery',
    'underscore',
    'backbone',
    'handlebars',
    'utils',
    'views/listing-preview-slide',
    'text!templates/listing-preview.hbs'
], function ($, _, Backbone, Handlebars, Utils, ListingPreviewSlideView, listingPreviewTemplate) {
    'use strict';

    var ListingPreviewView = Backbone.View.extend({

        template: Handlebars.compile(listingPreviewTemplate),

        initialize: function (options) {
            this.listingPreviewSlideView = new ListingPreviewSlideView(options);
        },

        render: function () {

            this.$el.html(this.template());

            var subviews = {
                '.subview-listing-preview-slide':this.listingPreviewSlideView
            };

            Utils.assignSubviews.apply(this, [subviews]);

            return this;
        },

        onClose: function () {
            var views = [
                this.listingPreviewSlideView
            ];

            _.each(views, function(view) {
                if (view) {
                    view.remove();
                    if (view.onClose) {
                        view.onClose();
                    }
                }
            });
        }
    });

    return ListingPreviewView;
});


text:
@interface ReaderContentPage : UIView

- (instancetype)initWithDocument:(CGPDFDocumentRef)pdfDocumentRef page:(NSInteger)page;

- (id)processSingleTap:(UITapGestureRecognizer *)recognizer;

@end

#pragma mark -

//
//	ReaderDocumentLink class interface
//

@interface ReaderDocumentLink : NSObject <NSObject>

@property (nonatomic, assign, readonly) CGRect rect;

@property (nonatomic, assign, readonly) CGPDFDictionaryRef dictionary;

+ (instancetype)newWithRect:(CGRect)linkRect dictionary:(CGPDFDictionaryRef)linkDictionary;

@end


text:
angular.module('dashboard.directives.ModelFieldFile', [
  "dashboard.services.GeneralModel"
])

.directive('modelFieldFileView', function($compile) {
  return {
    restrict: 'E',
    template: '{{ field.label }}: {{ data[field.name] }}',
    scope: {
      field: '=options',
      data: '=ngModel'
    },
    link: function(scope, element, attrs) {

    }
  };
})

.directive('modelFieldFileEdit', function($compile, $document, $window, GeneralModelService, SessionService) {
  return {
    restrict: 'E',
    template: '<button class="btn btn-default select-file" ng-hide="disabled">Select File</button> \
      <input type="file" ng-file-select="onFileSelect($files)" ng-hide="disabled"> \
      <button ng-if="filename" class="btn btn-danger fa fa-trash" ng-click="clear($event)" ng-hide="disabled"></button> \
        {{ filename }}  (download | preview) \

Drop File Here
',
    scope: {
      key: "=key",
      options: '=options',
      disabled: '=ngDisabled',
      data: '=ngModel',
      modelData: '=modelData'
    },
    link: function(scope, element, attrs) {

        /**
         * scope.data updates async from controller so need to watch for the first change only
         */
        var unwatch = scope.$watch('data', function(data) {
          if (data) {
            unwatch(); //Remove the watch
            if (scope.data && scope.data && scope.data.filename) {
              //expects scope.data to be an object with {filename, fileUrl}
              scope.filename = scope.data.filename;
              scope.fileUrl = scope.data.fileUrl;
              scope.previewUrl = scope.data.previewUrl;
            } else if (typeof scope.data === 'string') {
              scope.fileUrl = scope.data.replace(/%2F/g, "/");
              var pos = scope.fileUrl.lastIndexOf("/");
              scope.filename = scope.fileUrl.substring(pos+1);
            } else if (typeof scope.data.file === 'object') {
              var s3Path = scope.options.path; //S3 path needed when getting S3 Credentials for validation;
              scope.data = {path: s3Path, file: scope.data.file};
              scope.filename = scope.data.file.name;
              scope.fileUrl = null;
              scope.previewUrl = null;
            }
          }
       });

        scope.getFileIcon = function(filename) {
          var extension = filename.substring(filename.lastIndexOf("."));
          switch(extension.toLowerCase()) {
          case ".txt":
            return "fa-file-text-o";
          case ".doc":
          case ".docx":
            return "fa-file-word-o";
          case ".wav":
          case ".mp3":
          case ".aif":
            return "fa-file-audio-o";
          case ".m4v":
          case ".mov":
          case ".mp4":
          case ".avi":
            return "fa-file-video-o";
          case ".jpg":
          case ".jpeg":
          case ".png":
          case ".gif":
          case ".bmp":
          case ".tif":
            return "fa-file-image-o";
          case ".xls":
          case ".xlsx":
             return "fa-file-excel-o";
          case ".ppt":
          case ".pptx":
             return "fa-file-excel-o";
          case ".pdf":
             return "fa-file-pdf-o";
          default:
            return "fa-file-o";
          }
        };

        scope.onFileSelect = function($files) {
          //$files: an array of files selected, each file has name, size, and type.
          if ($files.length < 1) return;
          var selectedFile = $files[0];
          var s3Path = scope.options.path; //S3 path needed when getting S3 Credentials for validation;
          scope.data = {path: s3Path, file: selectedFile};
          scope.filename = selectedFile.name;
          scope.fileUrl = null;

        };

        scope.clear = function(e) {
          e.preventDefault();
          if (scope.options.confirm) {
            // Requires confirmation alert
            if (!confirm('Are you sure you would like to clear the file?')) {
              return;
            }
          }
          scope.data = null;
          scope.filename = null;
          scope.fileUrl = null;
        };

        //Prevent accidental file drop
        $document.on("drop", function(event) {
          if (event.target.nodeName != "INPUT") {
            event.preventDefault();
          }
        });
        $document.on("dragover", function( event ) {
          event.preventDefault();
          //Show Drop Target
          element.find(".file-drop").addClass("show");
        });

        $(window).on("mouseleave", function() {
          //Hide Drop Target
          element.find(".file-drop").removeClass("show");
        });

        scope.$on('$destroy', function() {
          //event clean up
          $document.off("drop");
          $document.off("dragover");
          $(window).off("mouseleave");
        });

    }
  };
})

;


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 1.0 Transitional//EN">

        <META http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link rel="stylesheet" href="../includes/main.css" type="text/css">
        <link rel="shortcut icon" href="../favicon.ico" type="image/x-icon">
        <title>Apache CloudStack | The Power Behind Your Cloud</title>

						Apache CloudStack 4.14.1.0-SNAPSHOT Root Admin API Reference

enableOutOfBandManagementForCluster

Enables out-of-band management for a cluster

Request parameters

                                            Parameter Name	Description	Required

                                            clusterid	the ID of the cluster	true

Response Tags

                                            Response Name	Description

                                            action	the out-of-band management action (if issued)

                                            address	the out-of-band management interface address

                                            description	the operation result description

                                            driver	the out-of-band management driver for the host

                                            enabled	true if out-of-band management is enabled for the host

                                            hostid	the ID of the host

                                            password	the out-of-band management interface password

                                            port	the out-of-band management interface port

                                            powerstate	the out-of-band management interface powerState of the host

                                            status	the operation result

                                            username	the out-of-band management interface username

                            Copyright © 2015 The Apache Software Foundation, Licensed under the
                   Apache License, Version 2.0.

                                            Apache, CloudStack, Apache CloudStack, the Apache CloudStack logo, the CloudMonkey logo  and the Apache feather logo are trademarks of The Apache Software Foundation.


text:
<?xml version="1.0"?>
<!-- Copyright (C) 2010-2015 Free Software Foundation, Inc.

     Copying and distribution of this file, with or without modification,
     are permitted in any medium without royalty provided the copyright
     notice and this notice are preserved.  -->

<!DOCTYPE target SYSTEM "gdb-target.dtd">
<target>
  <architecture>tic6x</architecture>
  <osabi>GNU/Linux</osabi>
  <xi:include href="tic6x-core.xml"/>
  <xi:include href="tic6x-gp.xml"/>
</target>


text:
'use strict';

var acceptLanguageParser = require('accept-language-parser');
var Cache = require('nice-cache');
var Domain = require('domain');
var format = require('stringformat');
var vm = require('vm');
var _ = require('underscore');

var applyDefaultValues = require('./apply-default-values');
var Client = require('../../../../client');
var detective = require('../../domain/plugins-detective');
var eventsHandler = require('../../domain/events-handler');
var GetComponentRetrievingInfo = require('./get-component-retrieving-info');
var NestedRenderer = require('../../domain/nested-renderer');
var RequireWrapper = require('../../domain/require-wrapper');
var sanitiser = require('../../domain/sanitiser');
var settings = require('../../../resources/settings');
var strings = require('../../../resources');
var urlBuilder = require('../../domain/url-builder');
var validator = require('../../domain/validators');

module.exports = function(conf, repository){

  var client = new Client(),
      cache = new Cache({
        verbose: !!conf.verbosity,
        refreshInterval: conf.refreshInterval
      });

  var renderer = function(options, cb){

    var nestedRenderer = new NestedRenderer(renderer, options.conf),
        retrievingInfo = new GetComponentRetrievingInfo(options),
        responseHeaders;

    var getLanguage = function(){
      var paramOverride = !!options.parameters && options.parameters['__ocAcceptLanguage'];
      return paramOverride || options.headers['accept-language'];
    };

    var callback = function(result){

      if(!!result.response.error){
        retrievingInfo.extend(result.response);
      }

      _.extend(result.response, {
        name: options.name,
        requestVersion: options.version || ''
      });

      eventsHandler.fire('component-retrieved', retrievingInfo.getData());
      return cb(result);
    };

    var conf = options.conf,
        acceptLanguage = getLanguage(),
        componentCallbackDone = false,
        requestedComponent = {
          name: options.name,
          version: options.version || '',
          parameters: options.parameters
        };

    repository.getComponent(requestedComponent.name, requestedComponent.version, function(err, component){

      // check route exist for component and version
      if(err){
        return callback({
          status: 404,
          response: {
            code: 'NOT_FOUND',
            error: err
          }
        });
      }

      // check component requirements are satisfied by registry
      var pluginsCompatibility = validator.validatePluginsRequirements(component.oc.plugins, conf.plugins);

      if(!pluginsCompatibility.isValid){
        return callback({
          status: 501,
          response: {
            code: 'PLUGIN_MISSING_FROM_REGISTRY',
            error: format(strings.errors.registry.PLUGIN_NOT_IMPLEMENTED, pluginsCompatibility.missing.join(', ')),
            missingPlugins: pluginsCompatibility.missing
          }
        });
      }

      // sanitise and check params
      var appliedParams = applyDefaultValues(requestedComponent.parameters, component.oc.parameters),
          params = sanitiser.sanitiseComponentParameters(appliedParams, component.oc.parameters),
          validationResult = validator.validateComponentParameters(params, component.oc.parameters);

      if(!validationResult.isValid){
        return callback({
          status: 400,
          response: {
            code: 'NOT_VALID_REQUEST',
            error: validationResult.errors.message
          }
        });
      }

      var returnComponent = function(err, data){

        if(componentCallbackDone){ return; }
        componentCallbackDone = true;

        if(!!err || !data){
          err = err || new Error(strings.errors.registry.DATA_OBJECT_IS_UNDEFINED);
          return callback({
            status: 500,
            response: {
              code: 'GENERIC_ERROR',
              error: format(strings.errors.registry.COMPONENT_EXECUTION_ERROR, err.message || ''),
              details: { message: err.message, stack: err.stack, originalError: err }
            }
          });
        }

        var componentHref = urlBuilder.component({
          name: component.name,
          version: requestedComponent.version,
          parameters: params
        }, conf.baseUrl);

        var isUnrendered = options.headers.accept === settings.registry.acceptUnrenderedHeader,
            renderMode = isUnrendered ? 'unrendered' : 'rendered';

        var response = {
          type: conf.local ? 'oc-component-local' : 'oc-component',
          version: component.version,
          requestVersion: requestedComponent.version,
          name: requestedComponent.name,
          renderMode: renderMode
        };

        if(!options.omitHref){
          response.href = componentHref;
        }

        retrievingInfo.extend({
          href: componentHref,
          version: component.version,
          renderMode: renderMode
        });

        if(isUnrendered){
          callback({
            status: 200,
            response: _.extend(response, {
              data: data,
              template: {
                src: repository.getStaticFilePath(component.name, component.version, 'template.js'),
                type: component.oc.files.template.type,
                key: component.oc.files.template.hashKey
              }
            })
          });
        } else {

          var cacheKey = format('{0}/{1}/template.js', component.name, component.version),
              cached = cache.get('file-contents', cacheKey),
              key = component.oc.files.template.hashKey,
              renderOptions = {
                href: componentHref,
                key: key,
                version: component.version,
                name: component.name,
                templateType: component.oc.files.template.type,
                container: component.oc.container,
                renderInfo: component.oc.renderInfo
              };

          var returnResult = function(template){
            client.renderTemplate(template, data, renderOptions, function(err, html){

              if(err){
                return callback({
                  status: 500,
                  response: {
                    code: 'INTERNAL_SERVER_ERROR',
                    error: err
                  }
                });
              }

              if (responseHeaders) {
                response.headers = responseHeaders;
              }

              callback({
                status: 200,
                response: _.extend(response, { html: html })
              });
            });
          };

          if(!!cached && !conf.hotReloading){
            returnResult(cached);
          } else {
            repository.getCompiledView(component.name, component.version, function(err, templateText){
              var context = { jade: require('jade/runtime.js')};
              vm.runInNewContext(templateText, context);
              var template = context.oc.components[key];
              cache.set('file-contents', cacheKey, template);
              returnResult(template);
            });
          }
        }
      };

      if(!component.oc.files.dataProvider){
        returnComponent(null, {});
      } else {

        var cacheKey = format('{0}/{1}/server.js', component.name, component.version),
            cached = cache.get('file-contents', cacheKey),
            domain = Domain.create(),
            contextObj = {
              acceptLanguage: acceptLanguageParser.parse(acceptLanguage),
              baseUrl: conf.baseUrl,
              env: conf.env,
              params: params,
              plugins: conf.plugins,
              renderComponent: nestedRenderer.renderComponent,
              renderComponents: nestedRenderer.renderComponents,
              requestHeaders: options.headers,
              staticPath: repository.getStaticFilePath(component.name, component.version, '').replace('https:', ''),
              setHeader: function(header, value) {
                responseHeaders = responseHeaders || {};
                responseHeaders[header] = value;
              }
            };

        var setCallbackTimeout = function(){
          if(!!conf.executionTimeout){
            setTimeout(function(){
              returnComponent({
                message: format('timeout ({0}ms)', conf.executionTimeout * 1000)
              });
            }, conf.executionTimeout * 1000);
          }
        };

        if(!!cached && !conf.hotReloading){
          domain.on('error', returnComponent);

          try {
            domain.run(function(){
              cached(contextObj, returnComponent);
              setCallbackTimeout();
            });
          } catch(e){
            return returnComponent(e);
          }
        } else {
          repository.getDataProvider(component.name, component.version, function(err, dataProcessorJs){

            if(err){
              componentCallbackDone = true;

              return callback({
                status: 502,
                response: {
                  code: 'DATA_RESOLVING_ERROR',
                  error: strings.errors.registry.RESOLVING_ERROR
                }
              });
            }

            var context = {
              require: new RequireWrapper(conf.dependencies),
              module: { exports: {}},
              console: conf.local ? console : { log: _.noop },
              setTimeout: setTimeout,
              Buffer: Buffer
            };

            var handleError = function(err){

              if(err.code === 'DEPENDENCY_MISSING_FROM_REGISTRY'){
                componentCallbackDone = true;

                return callback({
                  status: 501,
                  response: {
                    code: err.code,
                    error: format(strings.errors.registry.DEPENDENCY_NOT_FOUND, err.missing.join(', ')),
                    missingDependencies: err.missing
                  }
                });
              }

              var usedPlugins = detective.parse(dataProcessorJs),
                  unRegisteredPlugins = _.difference(usedPlugins, _.keys(conf.plugins));

              if(!_.isEmpty(unRegisteredPlugins)){
                componentCallbackDone = true;

                return callback({
                  status: 501,
                  response: {
                    code: 'PLUGIN_MISSING_FROM_COMPONENT',
                    error: format(strings.errors.registry.PLUGIN_NOT_FOUND, unRegisteredPlugins.join(' ,')),
                    missingPlugins: unRegisteredPlugins
                  }
                });
              }

              returnComponent(err);
            };

            try {
              vm.runInNewContext(dataProcessorJs, context);
              var processData = context.module.exports.data;
              cache.set('file-contents', cacheKey, processData);

              domain.on('error', handleError);
              domain.run(function(){
                processData(contextObj, returnComponent);
                setCallbackTimeout();
              });
            } catch(err){
              handleError(err);
            }
          });
        }
      }
    });
  };

  return renderer;
};


text:
package org.nutz.lang.meta;

public abstract class Issue1288BasicEntity<T> {

    private T id;

    public T getId() {
        return id;
    }

    public void setId(T id) {
        this.id = id;
    }

}


text:
/* Created On: May 25, 2005 */
package edu.unl.act.rma.console.acis;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Properties;

import org.omg.CORBA.Any;
import org.omg.CORBA.ORB;
import org.omg.CORBA.ORBPackage.InvalidName;

import pi.UcanSecure;
import pi.UcanSecureHelper;
import Broker.UCANBrokerPackage.BrokerBusy;
import Broker.UCANBrokerPackage.InvalidUserId;
import Broker.UCANBrokerPackage.NullAttribute;
import edu.unl.act.rma.console.web.NWSDataServiceManager;
import edu.unl.act.rma.firm.core.LogManager;
import edu.unl.act.rma.firm.core.Logger;
import edu.unl.act.rma.firm.core.Loggers;

/**
 * @author Ian Cottingham
 *
 */
public class ACISGateway {

	private Logger LOG = LogManager.getLogger(Loggers.SYSTEM_LOG, ACISGateway.class);

	private static ACISGateway instance = new ACISGateway();

	private ORB orb;
	private String ior;
	private Broker.UCANBroker ubroker;
	private String user_id;
	private UcanSecure u_secure;

	private ACISGateway() {
		InputStream is = null;
		String userID = "";
		String password = "";

		try {
			NWSDataServiceManager manager = NWSDataServiceManager.getInstance();

			userID = manager.getAcisUser();
			password = manager.getAcisPassword();
			StringBuffer broker = new StringBuffer();
			broker.append("http://");
			broker.append(userID);
			broker.append(":");
			broker.append(password);
			broker.append("@");
			broker.append(manager.getBrokerIORPath());

	        	URL u = new URL(broker.toString());
	        	URLConnection uc = u.openConnection();

			is = uc.getInputStream();
	        	byte[] b = new byte[1024];
			StringBuffer sb = new StringBuffer();

	        	while ( is.read(b) > -1 )
	            sb.append(new String(b));

	        this.ior = sb.toString().trim();
	        LOG.info("obtained ACIS reference "+ior);
		} catch ( MalformedURLException mfe ) {
			LOG.error("invalid URL for IOR lookup", mfe);
		} catch ( IOException ioe ) {
			LOG.error("error reading IOR", ioe);
		} catch ( Exception e ) {
			LOG.error("unknown error getting IORR", e);
		} finally {
			try {
				is.close();
			} catch ( Exception ex ) {
				LOG.error("unknown error exiting", ex);
			}
		}

		try {
	        Properties props = new Properties();
	        props.put("org.omg.PortableInterceptor.ORBInitializerClass.UcanSecureORBInitializer", ""); 	// Create and initialize the ORB
	        this.orb = ORB.init(new String[0], props);

	        org.omg.CORBA.Object o = orb.string_to_object(ior);

	        this.ubroker = Broker.UCANBrokerHelper.narrow(o);
	        this.user_id = ubroker.getUserTicket(userID, password);
	        this.u_secure = UcanSecureHelper.narrow(orb.resolve_initial_references("UcanSecure"));
	        this.u_secure.setToken(user_id);

	        LOG.info("bound to ACIS");
		} catch ( BrokerBusy bb ) {
			LOG.error("ACIS ORB broker busy", bb);
		} catch ( InvalidUserId iid ) {
			LOG.error("invalid user id for ORB access", iid);
		} catch ( NullAttribute na ) {
			LOG.error("null attribute", na);
		} catch ( InvalidName in ) {
			LOG.error("invalid broker name for ORB", in);
		} catch ( Exception e ) {
			LOG.error("unknown exception", e);
		}
	}

	public static ACISGateway getInstance() {
		return instance;
	}

	protected static void reset() {
		if ( instance != null )
			instance = new ACISGateway();
	}

    public Any getAny() { return orb.create_any(); }
    public Meta.MetaFactory getMetaFactory() throws Exception { return (Meta.MetaFactory) this.ubroker.getServer(this.user_id, "MetaFactory", ""); }
    public Data.TSVarFactory getTSVarFactory() throws Exception { return (Data.TSVarFactory) this.ubroker.getServer(this.user_id, "DailyData", ""); }
}


text:
require 'tc_helper.rb'

class TestNumVal < Test::Unit::TestCase

  def setup
    @num_val = Axlsx::NumVal.new :v => 1
  end

  def test_initialize
    assert_equal(@num_val.format_code, "General")
    assert_equal(@num_val.v, "1")
  end

  def test_format_code
    assert_raise(ArgumentError) {@num_val.format_code = 7}
    assert_nothing_raised {@num_val.format_code = 'foo_bar'}
  end

  def test_to_xml_string
    str = '<?xml version="1.0" encoding="UTF-8"?>'
    str << '<c:chartSpace xmlns:c="' << Axlsx::XML_NS_C << '">'
    str << @num_val.to_xml_string(0)
    doc = Nokogiri::XML(str)
    # lets see if this works?
    assert_equal(doc.xpath("//c:pt/c:v[text()='1']").size, 1)

  end

end