text:
from functools import reduce
from glob import glob
import os
import os.path as op
from shutil import copyfile, copytree

import pytest
import numpy as np
from numpy.testing import (assert_array_almost_equal, assert_allclose,
                           assert_array_equal, assert_array_less)

import mne
from mne.datasets import testing
from mne.transforms import (Transform, apply_trans, rotation, translation,
                            scaling, read_trans, _angle_between_quats,
                            rot_to_quat)
from mne.coreg import (fit_matched_points, create_default_subject, scale_mri,
                       _is_mri_subject, scale_labels, scale_source_space,
                       coregister_fiducials, get_mni_fiducials, Coregistration)
from mne.io import read_fiducials, read_info
from mne.io.constants import FIFF
from mne.utils import (requires_nibabel, check_version, catch_logging,
                       _record_warnings)
from mne.source_space import write_source_spaces
from mne.channels import DigMontage

data_path = testing.data_path(download=False)
subjects_dir = os.path.join(data_path, 'subjects')
fid_fname = op.join(subjects_dir, 'sample', 'bem', 'sample-fiducials.fif')
raw_fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis_trunc_raw.fif')
trans_fname = op.join(data_path, 'MEG', 'sample',
                      'sample_audvis_trunc-trans.fif')

@pytest.fixture
def few_surfaces(monkeypatch):
    """Set the _MNE_FEW_SURFACES env var."""
    monkeypatch.setenv('_MNE_FEW_SURFACES', 'true')
    yield

def test_coregister_fiducials():
    """Test coreg.coregister_fiducials()."""
    # prepare head and MRI fiducials
    trans = Transform('head', 'mri',
                      rotation(.4, .1, 0).dot(translation(.1, -.1, .1)))
    coords_orig = np.array([[-0.08061612, -0.02908875, -0.04131077],
                            [0.00146763, 0.08506715, -0.03483611],
                            [0.08436285, -0.02850276, -0.04127743]])
    coords_trans = apply_trans(trans, coords_orig)

    def make_dig(coords, cf):
        return ({'coord_frame': cf, 'ident': 1, 'kind': 1, 'r': coords[0]},
                {'coord_frame': cf, 'ident': 2, 'kind': 1, 'r': coords[1]},
                {'coord_frame': cf, 'ident': 3, 'kind': 1, 'r': coords[2]})

    mri_fiducials = make_dig(coords_trans, FIFF.FIFFV_COORD_MRI)
    info = {'dig': make_dig(coords_orig, FIFF.FIFFV_COORD_HEAD)}

    # test coregister_fiducials()
    trans_est = coregister_fiducials(info, mri_fiducials)
    assert trans_est.from_str == trans.from_str
    assert trans_est.to_str == trans.to_str
    assert_array_almost_equal(trans_est['trans'], trans['trans'])

@requires_nibabel()
@pytest.mark.slowtest  # can take forever on OSX Travis
@testing.requires_testing_data
@pytest.mark.parametrize('scale', (.9, [1, .2, .8]))
def test_scale_mri(tmp_path, few_surfaces, scale):
    """Test creating fsaverage and scaling it."""
    # create fsaverage using the testing "fsaverage" instead of the FreeSurfer
    # one
    tempdir = str(tmp_path)
    fake_home = data_path
    create_default_subject(subjects_dir=tempdir, fs_home=fake_home,
                           verbose=True)
    assert _is_mri_subject('fsaverage', tempdir), "Creating fsaverage failed"

    fid_path = op.join(tempdir, 'fsaverage', 'bem', 'fsaverage-fiducials.fif')
    os.remove(fid_path)
    create_default_subject(update=True, subjects_dir=tempdir,
                           fs_home=fake_home)
    assert op.exists(fid_path), "Updating fsaverage"

    # copy MRI file from sample data (shouldn't matter that it's incorrect,
    # so here choose a small one)
    path_from = op.join(fake_home, 'subjects', 'sample', 'mri',
                        'T1.mgz')
    path_to = op.join(tempdir, 'fsaverage', 'mri', 'orig.mgz')
    copyfile(path_from, path_to)

    # remove redundant label files
    label_temp = op.join(tempdir, 'fsaverage', 'label', '*.label')
    label_paths = glob(label_temp)
    for label_path in label_paths[1:]:
        os.remove(label_path)

    # create source space
    print('Creating surface source space')
    path = op.join(tempdir, 'fsaverage', 'bem', 'fsaverage-%s-src.fif')
    src = mne.setup_source_space('fsaverage', 'ico0', subjects_dir=tempdir,
                                 add_dist=False)
    mri = op.join(tempdir, 'fsaverage', 'mri', 'orig.mgz')
    print('Creating volume source space')
    vsrc = mne.setup_volume_source_space(
        'fsaverage', pos=50, mri=mri, subjects_dir=tempdir,
        add_interpolator=False)
    write_source_spaces(path % 'vol-50', vsrc)

    # scale fsaverage
    write_source_spaces(path % 'ico-0', src, overwrite=True)
    with _record_warnings():  # sometimes missing nibabel
        scale_mri('fsaverage', 'flachkopf', scale, True,
                  subjects_dir=tempdir, verbose='debug')
    assert _is_mri_subject('flachkopf', tempdir), "Scaling failed"
    spath = op.join(tempdir, 'flachkopf', 'bem', 'flachkopf-%s-src.fif')

    assert op.exists(spath % 'ico-0'), "Source space ico-0 was not scaled"
    assert os.path.isfile(os.path.join(tempdir, 'flachkopf', 'surf',
                                       'lh.sphere.reg'))
    vsrc_s = mne.read_source_spaces(spath % 'vol-50')
    for vox in ([0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 2, 3]):
        idx = np.ravel_multi_index(vox, vsrc[0]['shape'], order='F')
        err_msg = f'idx={idx} @ {vox}, scale={scale}'
        assert_allclose(apply_trans(vsrc[0]['src_mri_t'], vox),
                        vsrc[0]['rr'][idx], err_msg=err_msg)
        assert_allclose(apply_trans(vsrc_s[0]['src_mri_t'], vox),
                        vsrc_s[0]['rr'][idx], err_msg=err_msg)
    scale_labels('flachkopf', subjects_dir=tempdir)

    # add distances to source space after hacking the properties to make
    # it run *much* faster
    src_dist = src.copy()
    for s in src_dist:
        s.update(rr=s['rr'][s['vertno']], nn=s['nn'][s['vertno']],
                 tris=s['use_tris'])
        s.update(np=len(s['rr']), ntri=len(s['tris']),
                 vertno=np.arange(len(s['rr'])),
                 inuse=np.ones(len(s['rr']), int))
    mne.add_source_space_distances(src_dist)
    write_source_spaces(path % 'ico-0', src_dist, overwrite=True)

    # scale with distances
    os.remove(spath % 'ico-0')
    scale_source_space('flachkopf', 'ico-0', subjects_dir=tempdir)
    ssrc = mne.read_source_spaces(spath % 'ico-0')
    assert ssrc[0]['dist'] is not None
    assert ssrc[0]['nearest'] is not None

    # check patch info computation (only if SciPy is new enough to be fast)
    if check_version('scipy', '1.3'):
        for s in src_dist:
            for key in ('dist', 'dist_limit'):
                s[key] = None
        write_source_spaces(path % 'ico-0', src_dist, overwrite=True)

        # scale with distances
        os.remove(spath % 'ico-0')
        scale_source_space('flachkopf', 'ico-0', subjects_dir=tempdir)
        ssrc = mne.read_source_spaces(spath % 'ico-0')
        assert ssrc[0]['dist'] is None
        assert ssrc[0]['nearest'] is not None

@pytest.mark.slowtest  # can take forever on OSX Travis
@testing.requires_testing_data
@requires_nibabel()
def test_scale_mri_xfm(tmp_path, few_surfaces):
    """Test scale_mri transforms and MRI scaling."""
    # scale fsaverage
    tempdir = str(tmp_path)
    fake_home = data_path
    # add fsaverage
    create_default_subject(subjects_dir=tempdir, fs_home=fake_home,
                           verbose=True)
    # add sample (with few files)
    sample_dir = op.join(tempdir, 'sample')
    os.mkdir(sample_dir)
    os.mkdir(op.join(sample_dir, 'bem'))
    for dirname in ('mri', 'surf'):
        copytree(op.join(fake_home, 'subjects', 'sample', dirname),
                 op.join(sample_dir, dirname))
    subject_to = 'flachkopf'
    spacing = 'oct2'
    for subject_from in ('fsaverage', 'sample'):
        if subject_from == 'fsaverage':
            scale = 1.  # single dim
        else:
            scale = [0.9, 2, .8]  # separate
        src_from_fname = op.join(tempdir, subject_from, 'bem',
                                 '%s-%s-src.fif' % (subject_from, spacing))
        src_from = mne.setup_source_space(
            subject_from, spacing, subjects_dir=tempdir, add_dist=False)
        write_source_spaces(src_from_fname, src_from)
        vertices_from = np.concatenate([s['vertno'] for s in src_from])
        assert len(vertices_from) == 36
        hemis = ([0] * len(src_from[0]['vertno']) +
                 [1] * len(src_from[0]['vertno']))
        mni_from = mne.vertex_to_mni(vertices_from, hemis, subject_from,
                                     subjects_dir=tempdir)
        if subject_from == 'fsaverage':  # identity transform
            source_rr = np.concatenate([s['rr'][s['vertno']]
                                        for s in src_from]) * 1e3
            assert_allclose(mni_from, source_rr)
        if subject_from == 'fsaverage':
            overwrite = skip_fiducials = False
        else:
            with pytest.raises(IOError, match='No fiducials file'):
                scale_mri(subject_from, subject_to, scale,
                          subjects_dir=tempdir)
            skip_fiducials = True
            with pytest.raises(IOError, match='already exists'):
                scale_mri(subject_from, subject_to, scale,
                          subjects_dir=tempdir, skip_fiducials=skip_fiducials)
            overwrite = True
        if subject_from == 'sample':  # support for not needing all surf files
            os.remove(op.join(sample_dir, 'surf', 'lh.curv'))
        scale_mri(subject_from, subject_to, scale, subjects_dir=tempdir,
                  verbose='debug', overwrite=overwrite,
                  skip_fiducials=skip_fiducials)
        if subject_from == 'fsaverage':
            assert _is_mri_subject(subject_to, tempdir), "Scaling failed"
        src_to_fname = op.join(tempdir, subject_to, 'bem',
                               '%s-%s-src.fif' % (subject_to, spacing))
        assert op.exists(src_to_fname), "Source space was not scaled"
        # Check MRI scaling
        fname_mri = op.join(tempdir, subject_to, 'mri', 'T1.mgz')
        assert op.exists(fname_mri), "MRI was not scaled"
        # Check MNI transform
        src = mne.read_source_spaces(src_to_fname)
        vertices = np.concatenate([s['vertno'] for s in src])
        assert_array_equal(vertices, vertices_from)
        mni = mne.vertex_to_mni(vertices, hemis, subject_to,
                                subjects_dir=tempdir)
        assert_allclose(mni, mni_from, atol=1e-3)  # 0.001 mm

def test_fit_matched_points():
    """Test fit_matched_points: fitting two matching sets of points."""
    tgt_pts = np.random.RandomState(42).uniform(size=(6, 3))

    # rotation only
    trans = rotation(2, 6, 3)
    src_pts = apply_trans(trans, tgt_pts)
    trans_est = fit_matched_points(src_pts, tgt_pts, translate=False,
                                   out='trans')
    est_pts = apply_trans(trans_est, src_pts)
    assert_array_almost_equal(tgt_pts, est_pts, 2, "fit_matched_points with "
                              "rotation")

    # rotation & translation
    trans = np.dot(translation(2, -6, 3), rotation(2, 6, 3))
    src_pts = apply_trans(trans, tgt_pts)
    trans_est = fit_matched_points(src_pts, tgt_pts, out='trans')
    est_pts = apply_trans(trans_est, src_pts)
    assert_array_almost_equal(tgt_pts, est_pts, 2, "fit_matched_points with "
                              "rotation and translation.")

    # rotation & translation & scaling
    trans = reduce(np.dot, (translation(2, -6, 3), rotation(1.5, .3, 1.4),
                            scaling(.5, .5, .5)))
    src_pts = apply_trans(trans, tgt_pts)
    trans_est = fit_matched_points(src_pts, tgt_pts, scale=1, out='trans')
    est_pts = apply_trans(trans_est, src_pts)
    assert_array_almost_equal(tgt_pts, est_pts, 2, "fit_matched_points with "
                              "rotation, translation and scaling.")

    # test exceeding tolerance
    tgt_pts[0, :] += 20
    pytest.raises(RuntimeError, fit_matched_points, tgt_pts, src_pts, tol=10)

@testing.requires_testing_data
@requires_nibabel()
def test_get_mni_fiducials():
    """Test get_mni_fiducials."""
    fids, coord_frame = read_fiducials(fid_fname)
    assert coord_frame == FIFF.FIFFV_COORD_MRI
    assert [f['ident'] for f in fids] == list(range(1, 4))
    fids = np.array([f['r'] for f in fids])
    fids_est = get_mni_fiducials('sample', subjects_dir)
    fids_est = np.array([f['r'] for f in fids_est])
    dists = np.linalg.norm(fids - fids_est, axis=-1) * 1000.  # -> mm
    assert (dists < 8).all(), dists

@pytest.mark.slowtest
@testing.requires_testing_data
@pytest.mark.parametrize(
    'scale_mode,ref_scale,grow_hair,fiducials,fid_match', [
        (None, [1., 1., 1.], 0., None, 'nearest'),
        (None, [1., 1., 1.], 0., 'estimated', 'nearest'),
        (None, [1., 1., 1.], 2., 'auto', 'nearest'),
        ('uniform', [1., 1., 1.], 0., None, 'nearest'),
        ('3-axis', [1., 1., 1.], 0., 'auto', 'nearest'),
        ('uniform', [0.8, 0.8, 0.8], 0., 'auto', 'nearest'),
        ('3-axis', [0.8, 1.2, 1.2], 0., 'auto', 'matched')])
def test_coregistration(scale_mode, ref_scale, grow_hair, fiducials,
                        fid_match):
    """Test automated coregistration."""
    subject = 'sample'
    if fiducials is None:
        fiducials, coord_frame = read_fiducials(fid_fname)
        assert coord_frame == FIFF.FIFFV_COORD_MRI
    info = read_info(raw_fname)
    for d in info['dig']:
        d['r'] = d['r'] * ref_scale
    trans = read_trans(trans_fname)
    coreg = Coregistration(info, subject=subject, subjects_dir=subjects_dir,
                           fiducials=fiducials)
    assert np.allclose(coreg._last_parameters, coreg._parameters)
    assert len(coreg.fiducials.dig) == 3
    for dig_point in coreg.fiducials.dig:
        assert dig_point['coord_frame'] == FIFF.FIFFV_COORD_MRI
        assert dig_point['kind'] == FIFF.FIFFV_POINT_CARDINAL

    coreg.set_fid_match(fid_match)
    default_params = list(coreg._default_parameters)
    coreg.set_rotation(default_params[:3])
    coreg.set_translation(default_params[3:6])
    coreg.set_scale(default_params[6:9])
    coreg.set_grow_hair(grow_hair)
    coreg.set_scale_mode(scale_mode)
    # Identity transform
    errs_id = coreg.compute_dig_mri_distances()
    is_scaled = ref_scale != [1., 1., 1.]
    id_max = 0.03 if is_scaled and scale_mode == '3-axis' else 0.02
    assert 0.005 < np.median(errs_id) < id_max
    # Fiducial transform + scale
    coreg.fit_fiducials(verbose=True)
    assert coreg._extra_points_filter is None
    coreg.omit_head_shape_points(distance=0.02)
    assert coreg._extra_points_filter is not None
    errs_fid = coreg.compute_dig_mri_distances()
    assert_array_less(0, errs_fid)
    if is_scaled or scale_mode is not None:
        fid_max = 0.05
        fid_med = 0.02
    else:
        fid_max = 0.03
        fid_med = 0.01
    assert_array_less(errs_fid, fid_max)
    assert 0.001 < np.median(errs_fid) < fid_med
    assert not np.allclose(coreg._parameters, default_params)
    coreg.omit_head_shape_points(distance=-1)
    coreg.omit_head_shape_points(distance=5. / 1000)
    assert coreg._extra_points_filter is not None
    # ICP transform + scale
    coreg.fit_icp(verbose=True)
    assert isinstance(coreg.trans, Transform)
    errs_icp = coreg.compute_dig_mri_distances()
    assert_array_less(0, errs_icp)
    if is_scaled or scale_mode == '3-axis':
        icp_max = 0.015
    else:
        icp_max = 0.01
    assert_array_less(errs_icp, icp_max)
    assert 0.001 < np.median(errs_icp) < 0.004
    assert np.rad2deg(_angle_between_quats(
        rot_to_quat(coreg.trans['trans'][:3, :3]),
        rot_to_quat(trans['trans'][:3, :3]))) < 13
    if scale_mode is None:
        atol = 1e-7
    else:
        atol = 0.35
    assert_allclose(coreg._scale, ref_scale, atol=atol)
    coreg.reset()
    assert_allclose(coreg._parameters, default_params)

@pytest.mark.slowtest
@testing.requires_testing_data
def test_coreg_class_gui_match():
    """Test that using Coregistration matches mne coreg."""
    fiducials, _ = read_fiducials(fid_fname)
    info = read_info(raw_fname)
    coreg = Coregistration(info, subject='sample', subjects_dir=subjects_dir,
                           fiducials=fiducials)
    assert_allclose(coreg.trans['trans'], np.eye(4), atol=1e-6)
    # mne coreg -s sample -d subjects -f MEG/sample/sample_audvis_trunc_raw.fif
    # then "Fit Fid.", Save... to get trans, read_trans:
    want_trans = [
        [9.99428809e-01, 2.94733196e-02, 1.65350307e-02, -8.76054692e-04],
        [-1.92420650e-02, 8.98512006e-01, -4.38526988e-01, 9.39774036e-04],
        [-2.77817696e-02, 4.37958330e-01, 8.98565888e-01, -8.29207990e-03],
        [0, 0, 0, 1]]
    coreg.set_fid_match('matched')
    coreg.fit_fiducials(verbose=True)
    assert_allclose(coreg.trans['trans'], want_trans, atol=1e-6)
    # Set ICP iterations to one, click "Fit ICP"
    want_trans = [
        [9.99512792e-01, 2.80128177e-02, 1.37659665e-02, 6.08855276e-04],
        [-1.91694051e-02, 8.98992002e-01, -4.37545270e-01, 9.66848747e-04],
        [-2.46323701e-02, 4.37068194e-01, 8.99091005e-01, -1.44129358e-02],
        [0, 0, 0, 1]]
    coreg.fit_icp(1, verbose=True)
    assert_allclose(coreg.trans['trans'], want_trans, atol=1e-6)
    # Set ICP iterations to 20, click "Fit ICP"
    with catch_logging() as log:
        coreg.fit_icp(20, verbose=True)
    log = log.getvalue()
    want_trans = [
        [9.97582495e-01, 2.12266613e-02, 6.61706254e-02, -5.07694029e-04],
        [1.81089472e-02, 8.39900672e-01, -5.42437911e-01, 7.81218382e-03],
        [-6.70908988e-02, 5.42324841e-01, 8.37485850e-01, -2.50057746e-02],
        [0, 0, 0, 1]]
    assert_allclose(coreg.trans['trans'], want_trans, atol=1e-6)
    assert 'ICP 19' in log
    assert 'ICP 20' not in log  # converged on 19
    # Change to uniform scale mode, "Fit Fiducials" in scale UI
    coreg.set_scale_mode('uniform')
    coreg.fit_fiducials()
    want_scale = [0.975] * 3
    want_trans = [
        [9.99428809e-01, 2.94733196e-02, 1.65350307e-02, -9.25998494e-04],
        [-1.92420650e-02, 8.98512006e-01, -4.38526988e-01, -1.03350170e-03],
        [-2.77817696e-02, 4.37958330e-01, 8.98565888e-01, -9.03170835e-03],
        [0, 0, 0, 1]]
    assert_allclose(coreg.scale, want_scale, atol=5e-4)
    assert_allclose(coreg.trans['trans'], want_trans, atol=1e-6)
    # Click "Fit ICP" in scale UI
    with catch_logging() as log:
        coreg.fit_icp(20, verbose=True)
    log = log.getvalue()
    assert 'ICP 18' in log
    assert 'ICP 19' not in log
    want_scale = [1.036] * 3
    want_trans = [
        [9.98992383e-01, 1.72388796e-02, 4.14364934e-02, 6.19427126e-04],
        [6.80460501e-03, 8.54430079e-01, -5.19521892e-01, 5.58008114e-03],
        [-4.43605632e-02, 5.19280374e-01, 8.53451848e-01, -2.03358755e-02],
        [0, 0, 0, 1]]
    assert_allclose(coreg.scale, want_scale, atol=5e-4)
    assert_allclose(coreg.trans['trans'], want_trans, atol=1e-6)
    # Change scale mode to 3-axis, click "Fit ICP" in scale UI
    coreg.set_scale_mode('3-axis')
    with catch_logging() as log:
        coreg.fit_icp(20, verbose=True)
    log = log.getvalue()
    assert 'ICP  7' in log
    assert 'ICP  8' not in log
    want_scale = [1.025, 1.010, 1.121]
    want_trans = [
        [9.98387098e-01, 2.04762165e-02, 5.29526398e-02, 4.97257097e-05],
        [1.13287698e-02, 8.42087150e-01, -5.39222538e-01, 7.09863892e-03],
        [-5.56319728e-02, 5.38952649e-01, 8.40496957e-01, -1.46372067e-02],
        [0, 0, 0, 1]]
    assert_allclose(coreg.scale, want_scale, atol=5e-4)
    assert_allclose(coreg.trans['trans'], want_trans, atol=1e-6)

@testing.requires_testing_data
@pytest.mark.parametrize(
    'drop_point_kind', (FIFF.FIFFV_POINT_CARDINAL, FIFF.FIFFV_POINT_HPI,
                        FIFF.FIFFV_POINT_EXTRA, FIFF.FIFFV_POINT_EEG))
def test_coreg_class_init(drop_point_kind):
    """Test that Coregistration can be instantiated with various digs."""
    fiducials, _ = read_fiducials(fid_fname)
    info = read_info(raw_fname)

    dig_list = []
    eeg_chans = []
    for pt in info['dig']:
        if pt['kind'] != drop_point_kind:
            dig_list.append(pt)
            if pt['kind'] == FIFF.FIFFV_POINT_EEG:
                eeg_chans.append(f"EEG {pt['ident']:03d}")

    this_info = info.copy()
    this_info.set_montage(DigMontage(dig=dig_list, ch_names=eeg_chans),
                          on_missing='ignore')
    Coregistration(this_info, subject='sample',
                   subjects_dir=subjects_dir, fiducials=fiducials)


text:
<?php

/**
 * @see Zend_Queue_Message
 */
require_once 'Zend/Queue/Message.php';

/**
 * Class for managing Zend Platform JobQueue jobs via Zend_Queue
 *
 * @category   Zend
 * @package    Zend_Queue
 * @subpackage Message
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Queue_Message_PlatformJob extends Zend_Queue_Message
{
    /**
     * @var ZendApi_Job
     */
    protected $_job;

    /**
     * Job identifier
     * @var string
     */
    protected $_id = null;

    /**
     * Constructor
     *
     * The constructor should be an array of options.
     *
     * If the option 'data' is provided, and is an instance of ZendApi_Job,
     * that object will be used as the internal job; if that option is not a
     * ZendApi_Job instance, an exception will be thrown.
     *
     * Alternately, you may specify the 'script' parameter, which should be a
     * JobQueue script the job will request. A new ZendApi_Job object will then
     * be created using that script and any options you provide.
     *
     * @param  array $options
     * @return void
     * @throws Zend_Queue_Exception
     */
    public function __construct(array $options = array())
    {
        if (isset($options['data'])) {
            if (!($options['data'] instanceof ZendApi_Job)) {
                require_once 'Zend/Queue/Exception.php';
                throw new Zend_Queue_Exception('Data must be an instance of ZendApi_Job');
            }
            $this->_job = $options['data'];
            parent::__construct($this->_job->getProperties());
        } else {
            parent::__construct($options);

            if (!isset($options['script'])) {
                require_once 'Zend/Queue/Exception.php';
                throw new Zend_Queue_Exception('The script is mandatory data');
            }

            $this->_job = new ZendApi_Job($options['script']);
            $this->_setJobProperties();
        }
    }

    /**
     * Set the job identifier
     *
     * Used within Zend_Queue only.
     *
     * @param  string $id
     * @return Zend_Queue_Message_PlatformJob
     */
    public function setJobId($id)
    {
        $this->_id = $id;
        return $this;
    }

    /**
     * Retrieve the job identifier
     *
     * @return string
     */
    public function getJobId()
    {
        return (($this->_id) ?  $this->_id : $this->_job->getID());
    }

    /**
     * Retrieve the internal ZendApi_Job instance
     *
     * @return ZendApi_Job
     */
    public function getJob()
    {
        return $this->_job;
    }

    /**
     * Store queue and data in serialized object
     *
     * @return array
     */
    public function __sleep()
    {
        return serialize('_job', '_id', '_data');
    }

    /**
     * Query the class name of the Queue object for which this
     * Message was created.
     *
     * @return string
     */
    public function getQueueClass()
    {
        return 'Zend_Queue_Adapter_Platform_JQ';
    }

    /**
     * Sets properties on the ZendApi_Job instance
     *
     * Any options in the {@link $_data} array will be checked. Those matching
     * options in ZendApi_Job will be used to set those options in that
     * instance.
     *
     * @return void
     */
    protected function _setJobProperties() {

        if (isset($this->_data['script'])) {
            $this->_job->setScript($this->_data['script']);
        }

        if (isset($this->_data['priority'])) {
            $this->_job->setJobPriority($this->_data['priority']);
        }

        if (isset($this->_data['name'])) {
            $this->_job->setJobName($this->_data['name']);
        }

        if (isset($this->_data['predecessor'])) {
            $this->_job->setJobDependency($this->_data['predecessor']);
        }

        if (isset($this->_data['preserved'])) {
            $this->_job->setPreserved($this->_data['preserved']);
        }

        if (isset($this->_data['user_variables'])) {
            $this->_job->setUserVariables($this->_data['user_variables']);
        }

        if (!empty($this->_data['interval'])) {
            $endTime = isset($this->_data['end_time']) ? $this->_data['end_time'] : null;
            $this->_job->setRecurrenceData($this->_data['interval'], $endTime);
        } elseif (isset($this->_data['interval']) && ($this->_data['interval'] === '')) {
            $this->_job->setRecurrenceData(0,0);
        }

        if (isset($this->_data['scheduled_time'])) {
            $this->_job->setScheduledTime($this->_data['scheduled_time']);
        }

        if (isset($this->_data['application_id'])) {
            $this->_job->setApplicationID($this->_data['application_id']);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import bz2

def compress(data):
    """
    Helper function to compress data (using bz2)
    """
    c = bz2.BZ2Compressor()
    a = c.compress(data)
    b = c.flush()
    return a+b

def decompress(data):
    """
    Helper function to decompress data (using bz2)
    """
    c = bz2.BZ2Decompressor()
    return c.decompress(data)

class BSONSerializer(object): # pragma: no cover
    """
    This class supports BSON serialization.  We started with this
    but found it very inefficient for arrays.  So we dropped it
    in favor of msgpack.

    ** Deprecated **

    """
    def __init__(self, compress=False, verbose=False, single=False):
        """
        Initialize settings for this serializer
        """
        from bson import BSON

        self.bson = BSON()
        self.compress = compress
        self.verbose = verbose
    def encode_obj(self, x, uncomp=False):
        """
        Encode an object (uncomp=True means suppress compression)
        """
        data = self.bson.encode(x)
        if self.compress and not uncomp:
            data = compress(data)
            y = decompress(data) # Just to make sure it works
        return data
    def encode_vec(self, x, uncomp=False):
        """
        Encode a vector (uncomp=True means suppress compression)
        """
        obj = {"d": x}
        data = self.encode_obj(obj, uncomp=uncomp)
        return data
    def decode_obj(self, fp, length, uncomp=False, verbose=False):
        """
        Decode an object (uncomp=True means suppress decompression)
        """
        from bson import BSON

        data = fp.read(length)
        if self.compress and not uncomp:
            data = decompress(data)
        if verbose:
            print "Raw object data: "+str(repr(data))
        return BSON(data).decode()
    def decode_vec(self, fp, length, uncomp=False):
        """
        Decode a vector (uncomp=True means suppress decompression)
        """
        d = self.decode_obj(fp, length=length, uncomp=uncomp)
        return d["d"]

class MsgPackSerializer(object):
    def __init__(self, compress=False, single=False):
        """
        Initialize various settings
        """
        self.compress = compress
        self.single = single
    def encode_obj(self, x, verbose=False, uncomp=False):
        """
        Encode an object (uncomp=True means suppress compression)
        """
        import msgpack
        try:
            data = msgpack.packb(x, use_single_float=self.single)
            if self.compress and not uncomp:
                data = compress(data)
            return data
        except Exception as e: # pragma: no cover
            print "Exception thrown while trying to pack '"+str(x)+"'"
            if type(x)==list:
                print "  List contains: "+str(type(x[0]))
            raise e
    def encode_vec(self, x, verbose=False, uncomp=False):
        """
        Encode a vector (uncomp=True means suppress compression)
        """
        return self.encode_obj(x, verbose=verbose, uncomp=uncomp)
    def decode_obj(self, fp, length, verbose=False, uncomp=False):
        """
        Decode an object (uncomp=True means suppress decompression)
        """
        import msgpack
        data = fp.read(length)
        if self.compress and not uncomp:
            data = decompress(data)
        x = msgpack.unpackb(data)
        return x
    def decode_vec(self, fp, length, verbose=False, uncomp=False):
        """
        Decode a vector (uncomp=True means suppress decompression)
        """
        return self.decode_obj(fp, length=length,
                               verbose=verbose, uncomp=uncomp)

class UMsgPackSerializer(object):
    def __init__(self, compress=False, single=False):
        """
        Initialize various settings
        """
        self.compress = compress
        self.single = single
    def encode_obj(self, x, verbose=False, uncomp=False):
        """
        Encode an object (uncomp=True means suppress compression)
        """
        import umsgpack
        if self.single:
            umsgpack._float_size=32
        else:
            umsgpack._float_size=64
        print "umsgpack._float_size = "+str(umsgpack._float_size)

        try:
            data = umsgpack.packb(x)
            if self.compress and not uncomp:
                data = compress(data)
            return data
        except Exception as e: # pragma: no cover
            print "Exception thrown while trying to pack '"+str(x)+"'"
            if type(x)==list:
                print "  List contains: "+str(type(x[0]))
            raise e
    def encode_vec(self, x, verbose=False, uncomp=False):
        """
        Encode a vector (uncomp=True means suppress compression)
        """
        return self.encode_obj(x, verbose=verbose, uncomp=uncomp)
    def decode_obj(self, fp, length, verbose=False, uncomp=False):
        """
        Decode an object (uncomp=True means suppress decompression)
        """
        import umsgpack
        if self.single:
            umsgpack._float_size=32
        else:
            umsgpack._float_size=64

        data = fp.read(length)
        if self.compress and not uncomp:
            data = decompress(data)
        x = umsgpack.unpackb(data)
        return x
    def decode_vec(self, fp, length, verbose=False, uncomp=False):
        """
        Decode a vector (uncomp=True means suppress decompression)
        """
        return self.decode_obj(fp, length=length,
                               verbose=verbose, uncomp=uncomp)


text:
import os
from runpy import run_module
import sys

if __name__ == '__main__':
    try:
        run_module('ros_buildfarm.wrapper.apt', run_name='__main__')
    except ImportError:
        # If the ros_buildfarm is not on the current PYTHONPATH add it using
        # the current script path as an anchor.
        sys.path.insert(
            0, os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
        run_module('ros_buildfarm.wrapper.apt', run_name='__main__')


text:
(function() {
    'use strict';

    angular
        .module('manateeApp')
        .factory('notificationInterceptor', notificationInterceptor);

    notificationInterceptor.$inject = ['$q', 'AlertService'];

    function notificationInterceptor ($q, AlertService) {
        var service = {
            response: response
        };

        return service;

        function response (response) {
            var alertKey = response.headers('X-manateeApp-alert');
            if (angular.isString(alertKey)) {
                AlertService.success(alertKey, { param : response.headers('X-manateeApp-params')});
            }
            return response;
        }
    }
})();


text:
module CsvShaper

  # Row
  # Handles creating of cells within a row and
  # assigning of the model's values to cells
  # Examples:
  # ```
  # # pass a model to the row
  # csv.row @model do |csv, model|
  #   ...
  # end
  #
  # # create an empty row instance
  # csv.row do |csv|
  #   ...
  # end
  #
  # # create a row with prefilled cells from a model
  # # note no block is passed
  # csv.row @model, :name, :age, :location
  # ```
  class Row
    attr_reader :model, :cells

    def initialize(*args)
      @cells = ActiveSupport::OrderedHash.new

      if args.one? && block_given?
        @model = args.first
        yield self, @model
      elsif args.empty? && block_given?
        yield self
      elsif args.length > 1
        @model = args.shift
        args.each { |col| cell(col) }
      else
        raise ArgumentError, 'invalid args passed to csv.row'
      end
    end

    # Public: assign the given Array of args to cells in this Row
    #
    # `args` - Array of the arguments passed (expected to be Symbols)
    #
    # Returns an Array of the Cells in this row
    def cells(*args)
      args.each { |col| cell(col) }
      @cells
    end

    # Public: add a cell to this Row
    # If the Row has a @model defined passing just a Symbol will
    # call that method on the @model and assign it to a column of
    # the same name. Otherwise a value will need to be passed also
    #
    # `column` - Symbol of the column to add to value to
    # `value` - data to assign to the cell (default: nil)
    #
    # Returns an Array of the Row's cells
    def cell(*args)
      if args.empty?
        raise ArgumentError, 'no args passed to #cell, you must pass at least a column name'
      end

      column = args.first.to_sym

      if args.size == 2
        @cells[column] = args.last
      elsif args.size == 1
        if @model && @model.respond_to?(column)
          @cells[column] = @model.send(column)
        else
          raise ArgumentError, "##{column} is not a method on #{@model.class.to_s}, call `csv.cell #{column}, value` instead"
        end
      else
        raise ArgumentError, 'you can pass a column or a column with a value to #cell'
      end

      @cells
    end
  end
end


text:
package proc

import (
	ntime "github.com/niean/gotools/time"
	"sync"
	"time"
)

const (
	DefaultOtherMaxSize      = 100
	DefaultSCounterQpsPeriod = 1
	DefaultSMathBasePeriod   = 1
)

// basic counter
type SCounterBase struct {
	sync.RWMutex
	Name  string
	Cnt   int64
	Time  string
	ts    int64
	Other map[string]interface{}
}

func NewSCounterBase(name string) *SCounterBase {
	uts := time.Now().Unix()
	return &SCounterBase{Name: name, Cnt: 0, Time: ntime.FormatTs(uts),
		ts: uts, Other: make(map[string]interface{})}
}

func (this *SCounterBase) Get() *SCounterBase {
	this.RLock()
	defer this.RUnlock()

	return this
}

func (this *SCounterBase) SetCnt(cnt int64) {
	this.Lock()
	this.Cnt = cnt
	this.ts = time.Now().Unix()
	this.Time = ntime.FormatTs(this.ts)
	this.Unlock()
}

func (this *SCounterBase) Incr() {
	this.IncrBy(int64(1))
}

func (this *SCounterBase) IncrBy(incr int64) {
	this.Lock()
	this.Cnt += incr
	this.Unlock()
}

func (this *SCounterBase) PutOther(key string, value interface{}) bool {
	this.Lock()
	defer this.Unlock()

	ret := false
	_, exist := this.Other[key]
	if exist {
		this.Other[key] = value
		ret = true
	} else {
		if len(this.Other) < DefaultOtherMaxSize {
			this.Other[key] = value
			ret = true
		}
	}

	return ret
}

// counter with qps
type SCounterQps struct {
	sync.RWMutex
	Name    string
	Cnt     int64
	Qps     int64
	Time    string
	ts      int64
	lastTs  int64
	lastCnt int64
	Other   map[string]interface{}
}

func NewSCounterQps(name string) *SCounterQps {
	uts := time.Now().Unix()
	return &SCounterQps{Name: name, Cnt: 0, Time: ntime.FormatTs(uts), ts: uts,
		Qps: 0, lastCnt: 0, lastTs: uts, Other: make(map[string]interface{})}
}

func (this *SCounterQps) Get() *SCounterQps {
	this.Lock()
	defer this.Unlock()

	this.ts = time.Now().Unix()
	this.Time = ntime.FormatTs(this.ts)
	// get smooth qps value
	if this.ts-this.lastTs > DefaultSCounterQpsPeriod {
		this.Qps = int64((this.Cnt - this.lastCnt) / (this.ts - this.lastTs))
		this.lastTs = this.ts
		this.lastCnt = this.Cnt
	}

	return this
}

func (this *SCounterQps) Incr() {
	this.IncrBy(int64(1))
}

func (this *SCounterQps) IncrBy(incr int64) {
	this.Lock()
	this.incrBy(incr)
	this.Unlock()
}

func (this *SCounterQps) PutOther(key string, value interface{}) bool {
	this.Lock()
	defer this.Unlock()

	ret := false
	_, exist := this.Other[key]
	if exist {
		this.Other[key] = value
		ret = true
	} else {
		if len(this.Other) < DefaultOtherMaxSize {
			this.Other[key] = value
			ret = true
		}
	}

	return ret
}

func (this *SCounterQps) incrBy(incr int64) {
	this.Cnt += incr
}


text:
package rhogenwizard.sdk.task.liveupdate;

import rhogenwizard.SysCommandExecutor;
import rhogenwizard.sdk.task.RubyExecTask;

public class DiscoverTask extends RubyExecTask
{
	public DiscoverTask(String workDir, String subnetAddress)
	{
		super(workDir, SysCommandExecutor.RUBY_BAT, "rake", "dev:network:discovery[" + subnetAddress + "]");
	}
}


text:
package fr.sii.ogham.test.classpath.runner.clean;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
@Order(0)
public class CleanerRunner implements ApplicationRunner {

	@Override
	public void run(ApplicationArguments args) throws Exception {
		boolean override = args.getOptionValues("override")!=null;
		if(!override) {
			return;
		}
		Path parentFolder = Paths.get(args.getNonOptionArgs().get(0));
		log.info("Cleaning {}", parentFolder);
		Files.createDirectories(parentFolder);
		FileUtils.cleanDirectory(parentFolder.toFile());
	}

}


text:
cargo-new - Create a new Cargo package

## SYNOPSIS

`cargo new` [_options_] _path_

## DESCRIPTION

This command will create a new Cargo package in the given directory. This
includes a simple template with a `Cargo.toml` manifest, sample source file,
and a VCS ignore file. If the directory is not already in a VCS repository,
then a new repository is created (see `--vcs` below).

The "authors" field in the manifest is determined from the environment or
configuration settings. A name is required and is determined from (first match
wins):

- `cargo-new.name` Cargo config value
- `CARGO_NAME` environment variable
- `GIT_AUTHOR_NAME` environment variable
- `GIT_COMMITTER_NAME` environment variable
- `user.name` git configuration value
- `USER` environment variable
- `USERNAME` environment variable
- `NAME` environment variable

The email address is optional and is determined from:

- `cargo-new.email` Cargo config value
- `CARGO_EMAIL` environment variable
- `GIT_AUTHOR_EMAIL` environment variable
- `GIT_COMMITTER_EMAIL` environment variable
- `user.email` git configuration value
- `EMAIL` environment variable

See [the reference](../reference/config.html) for more information about
configuration files.

See [cargo-init(1)](cargo-init.md) for a similar command which will create a new manifest
in an existing directory.

## OPTIONS

### New Options

--bin

Create a package with a binary target (src/main.rs).
This is the default behavior.

--lib

Create a package with a library target (src/lib.rs).

--edition edition

Specify the Rust edition to use. Default is 2018.
Possible values: 2015, 2018

--name name

Set the package name. Defaults to the directory name.

--vcs vcs

Initialize a new VCS repository for the given version control system (git,
hg, pijul, or fossil) or do not initialize any version control at all
(none). If not specified, defaults to git or the configuration value
cargo-new.vcs, or none if already inside a VCS repository.

--registry registry

This sets the publish field in Cargo.toml to the given registry name
which will restrict publishing only to that registry.

Registry names are defined in Cargo config files.
If not specified, the default registry defined by the registry.default
config key is used. If the default registry is not set and --registry is not
used, the publish field will not be set which means that publishing will not
be restricted.

### Display Options

-v

--verbose

Use verbose output. May be specified twice for "very verbose" output which
includes extra output such as dependency warnings and build script output.
May also be specified with the term.verbose
config value.

-q

--quiet

No output printed to stdout.

--color when

Control when colored output is used. Valid values:

auto (default): Automatically detect if color support is available on the
terminal.

always: Always display colors.

never: Never display colors.

May also be specified with the term.color
config value.

### Common Options

+toolchain

If Cargo has been installed with rustup, and the first argument to cargo
begins with +, it will be interpreted as a rustup toolchain name (such
as +stable or +nightly).
See the rustup documentation
for more information about how toolchain overrides work.

-h

--help

Prints help information.

-Z flag

Unstable (nightly-only) flags to Cargo. Run cargo -Z help for details.

## ENVIRONMENT

See [the reference](../reference/environment-variables.html) for
details on environment variables that Cargo reads.

## EXIT STATUS

* `0`: Cargo succeeded.
* `101`: Cargo failed to complete.

## EXAMPLES

1. Create a binary Cargo package in the given directory:

       cargo new foo

## SEE ALSO
[cargo(1)](cargo.md), [cargo-init(1)](cargo-init.md)


text:
[![Build Status](https://travis-ci.org/sindresorhus/pageres.svg?branch=master)](https://travis-ci.org/sindresorhus/pageres) [![Coverage Status](https://coveralls.io/repos/sindresorhus/pageres/badge.svg?branch=master)](https://coveralls.io/r/sindresorhus/pageres?branch=master) [![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/sindresorhus/xo)

Capture screenshots of websites in various resolutions. A good way to make sure your websites are responsive. It's speedy and generates 100 screenshots from 10 different websites in just over a minute. It can also be used to render SVG images.

*See [pageres-cli](https://github.com/sindresorhus/pageres-cli) for the command-line tool.*

## Install

```
$ npm install pageres
```

*PhantomJS, which is used for generating the screenshots, is installed automagically, but in some [rare cases](https://github.com/Obvious/phantomjs/issues/102) it might fail to and you'll get an `Error: spawn EACCES` error. [Download](http://phantomjs.org/download.html) PhantomJS manually and reinstall pageres if that happens.*

## Usage

```js
const Pageres = require('pageres');

const pageres = new Pageres({delay: 2})
	.src('yeoman.io', ['480x320', '1024x768', 'iphone 5s'], {crop: true})
	.src('todomvc.com', ['1280x1024', '1920x1080'])
	.src('data:text/html;base64,PGgxPkZPTzwvaDE+', ['1024x768'])
	.dest(__dirname)
	.run()
	.then(() => console.log('done'));
```

## API

### Pageres([options])

#### options

##### delay

Type: `number` *(seconds)*

Default: `0`

Delay capturing the screenshot.

Useful when the site does things after load that you want to capture.

##### timeout

Type: `number` *(seconds)*

Default: `60`

Number of seconds after which PhantomJS aborts the request.

##### crop

Type: `boolean`

Default: `false`

Crop to the set height.

##### css

Type: `string`

Apply custom CSS to the webpage. Specify some CSS or the path to a CSS file.

##### script

Type: `string`

Apply custom JavaScript to the webpage. Specify some JavaScript or the path to a file.

##### cookies

Type: `Array<string>` `Object`

A string with the same format as a [browser cookie](https://en.wikipedia.org/wiki/HTTP_cookie) or an object of what [`phantomjs.addCookie`](http://phantomjs.org/api/phantom/method/add-cookie.html) accepts.

###### Tip

Go to the website you want a cookie for and copy-paste it from Dev Tools.

##### filename

Type: `string`

Define a customized filename using [Lo-Dash templates](https://lodash.com/docs#template).

For example `<%= date %> - <%= url %>-<%= size %><%= crop %>`.

Available variables:

- `url`: The URL in [slugified](https://github.com/sindresorhus/filenamify-url) form, eg. `http://yeoman.io/blog/` becomes `yeoman.io!blog`
- `size`: Specified size, eg. `1024x1000`
- `width`: Width of the specified size, eg. `1024`
- `height`: Height of the specified size, eg. `1000`
- `crop`: Outputs `-cropped` when the crop option is true
- `date`: The current date (Y-M-d), eg. 2015-05-18
- `time`: The current time (h-m-s), eg. 21-15-11

##### incrementalName

Type: `boolean`

Default: `false`

When a file exists, append an incremental number.

##### selector

Type: `string`

Capture a specific DOM element matching a CSS selector.

##### hide

Type: `Array<string>`

Hide an array of DOM elements matching CSS selectors.

##### username

Type: `string`

Username for authenticating with HTTP auth.

##### password

Type: `string`

Password for authenticating with HTTP auth.

##### scale

Type: `number`

Default: `1`

Scale webpage `n` times.

##### format

Type: `string`

Default: `png`

Values: `png`, `jpg`

Image format.

##### userAgent

Type: `string`

Custom user agent.

##### headers

Type: `Object`

Custom HTTP request headers.

##### transparent

Type: `boolean`

Default: `false`

Set background color to `transparent` instead of `white` if no background is set.

### pageres.src(url, sizes, options)

Add a page to screenshot.

#### url

*Required*

Type: `string`

URL or local path to the website you want to screenshot. You can also use a data URI.

#### sizes

*Required*

Type: `Array<string>`

Use a `<width>x<height>` notation or a keyword.

A keyword is a version of a device from [this list](http://viewportsizes.com).
You can also pass in the `w3counter` keyword to use the ten most popular
resolutions from [w3counter](http://www.w3counter.com/globalstats.php).

#### options

Type: `Object`

Options set here will take precedence over the ones set in the constructor.

### pageres.dest(directory)

Set the destination directory.

#### directory

Type: `string`

### pageres.run()

Run pageres. Returns a promise for an array of streams.

### pageres.on('warning', callback)

Warnings with e.g. page errors.

## Task runners

Check out [grunt-pageres](https://github.com/sindresorhus/grunt-pageres) if you're using Grunt.

For Gulp and Broccoli, just use the API directly. No need for a wrapper plugin.

## Built with Pageres

- [Break Shot](https://github.com/victorferraz/break-shot) - Desktop app for capturing screenshots of responsive websites.

## Team

[![Sindre Sorhus](http://gravatar.com/avatar/d36a92237c75c5337c17b60d90686bf9?s=144)](https://sindresorhus.com) | [![Kevin Mårtensson](https://gravatar.com/avatar/48fa294e3cd41680b80d3ed6345c7b4d?s=144)](https://github.com/kevva) | [![Sam Verschueren](https://gravatar.com/avatar/30aba8d6414326b745aa2516f5067d53?s=144)](https://github.com/SamVerschueren)
---|---|---
[Sindre Sorhus](https://sindresorhus.com) | [Kevin Mårtensson](https://github.com/kevva) | [Sam Verschueren](https://github.com/SamVerschueren)

## License

MIT © [Sindre Sorhus](https://sindresorhus.com)


text:
package com.unascribed.copu.call;

import com.unascribed.copu.MemoryPage;
import com.unascribed.copu.VirtualMachine;
import com.unascribed.copu.descriptor.Descriptor;
import com.unascribed.copu.undefined.VMError;

public class Sys {

	public static void print(VirtualMachine vm) {
		MemoryPage page = vm.getPage(vm.registers().PG0.get());
		int addr = vm.registers().R1.get();
		int limit = vm.registers().R2.get();
		Descriptor<?> descriptor = vm.getDescriptor(vm.registers().R3.get());

		page.readNullTerminated(addr, limit, descriptor::write);
	}

	public static void println(VirtualMachine vm) {
		MemoryPage page = vm.getPage(vm.registers().PG0.get());
		int addr = vm.registers().R1.get();
		int limit = vm.registers().R2.get();
		Descriptor<?> descriptor = vm.getDescriptor(vm.registers().R3.get());
		if (descriptor==null) throw new VMError("Attempted to write to invalid descriptor 0x"+Integer.toHexString(vm.registers().R3.get())+"");

		page.readNullTerminated(addr, limit, descriptor::write);
		descriptor.write(0xD); //If there were unfinished surrogate sets before this, they'll get clobbered and the newline will get written instead.
	}

	public static void pipe(VirtualMachine vm) {
		MemoryPage page = vm.getPage(vm.registers().PG0.get());
		int addr = vm.registers().R1.get();

		String s = page.readString(addr, 16);
		if (s.equals("stdout")) {
			vm.registers().R0.accept(VirtualMachine.DESCRIPTOR_STDOUT);
		} else if (s.equals("stderr")) {
			vm.registers().R0.accept(VirtualMachine.DESCRIPTOR_STDERR);
		} else {
			vm.registers().R0.accept(-1);
		}
	}
}


text:
package nl.tudelft.ewi.git.models;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;

import lombok.Data;

import org.hibernate.validator.constraints.NotEmpty;

/**
 * This model represents a view of a SSH key in the Gitolite config.
 *
 * @author michael
 */
@Data
public class SshKeyModel {

	@NotNull
	@Pattern(regexp = "^[\\w._+-]*$")
	private String name;

	@NotEmpty
	@Pattern(regexp = "ssh-rsa AAAA[0-9A-Za-z+/]+[=]{0,3}(\\s[^\\s]+)?[\\r\\n]?")
	private String contents;

}


text:
<form name="chatMessage" ng-submit="vm.submit()">

    <input class="form-control input-sm" placeholder="Type your message here..."
    type="text" ng-model="vm.text" required>

      <button class="btn btn-sm" ng-disabled="chatMessage.$invalid">Send</button>

</form>


text:
title: Technology and Security Strategy
subtitle:
layout: default
modal-id: 8
img: strategy.jpg
thumbnail: strategy-thumbnail.jpg
alt: image-alt
project-date:
client:
category:
description: Business has become accustomed to reliable, secure, and available technology platforms. We've helped deliver these and supporting strategic cybersecurity programs to meet business goals and risk objectives.

---


text:
package de.fabmax.lightgl;

import static android.opengl.GLES20.GL_TEXTURE0;
import static android.opengl.GLES20.GL_TEXTURE1;
import static android.opengl.GLES20.glClearColor;

/**
 * RenderPass that computes a shadow map for dynamic shadows.
 *
 * @author fabmax
 *
 */
public class ShadowRenderPass implements RenderPass {

    private final OrthograpicCamera mShadowCamera = new OrthograpicCamera();
    private TextureRenderer mRenderer;
    private Shader mDepthShader;
    private int mTextureUnit = GL_TEXTURE1;

    private final BoundingBox mSceneBounds = new BoundingBox(-10, 10, -10, 10, -10, 10);
    private final float[] mShadowViewMatrix = new float[16];
    private final float[] mShadowProjMatrix = new float[16];

    private int mShadowMapSz = 512;

    /**
     * Renders a shadow map for a single light.
     *
     * @see RenderPass#onRender(LightGlContext)
     */
    @Override
    public void onRender(LightGlContext glContext) {
        checkCreateGlObjects(glContext);

        if (glContext.getEngine().getLights().size() == 0) {
            // there is no light to cast a shadow
            return;
        }
        Light l = glContext.getEngine().getLights().get(0);

        // compute view matrix for current light direction
        computeCamClipSize(l);
        mShadowCamera.computeViewMatrix(mShadowViewMatrix);
        mShadowCamera.computeProjectionMatrix(mShadowProjMatrix);

        // setup engine state
        glContext.getShaderManager().bindShader(glContext, mDepthShader);
        glContext.getShaderManager().setLockShader(true);
        mShadowCamera.setup(glContext.getState());

        // set the depth texture clear color values to maximum depth
        glClearColor(1.0f, 1.0f, 1.0f, 1.0f);

        // render scene to the texture
        mRenderer.renderToTexture(glContext, glContext.getEngine().getScene());

        // cleanup
        glContext.getShaderManager().setLockShader(false);
        glContext.getTextureManager().bindTexture(mRenderer.getTexture(), mTextureUnit);
        glContext.getState().resetBackgroundColor();
    }

    /**
     * Checks if the GL objects (texture renderer, shader, etc.) are created and if not creates them.
     */
    private void checkCreateGlObjects(LightGlContext glContext) {
        if (mDepthShader == null || mRenderer == null) {
            mDepthShader = new DepthShader(glContext.getShaderManager());
            mRenderer = new TextureRenderer();
            mRenderer.setTextureSize(mShadowMapSz, mShadowMapSz);

            // initialize the depth texture with maximum depth value
            glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
            mRenderer.renderToTexture(glContext, null);
            glContext.getState().resetBackgroundColor();

            // set texture renderer border to 1 to reduce artifacts
            mRenderer.setBorder(1);
        }
    }

    /**
     * Sets the size of the shadow map texture. The actual texture size is sz x sz. Maximum texture
     * size depends on the hardware. Moreover texture size has a heavy impact on performance.
     * Default size is 512 x 512.
     *
     * @param sz
     *            the shadow map size to use
     */
    public void setShadowMapSize(int sz) {
        mShadowMapSz = sz;
        if(mRenderer != null) {
            mRenderer.setTextureSize(mShadowMapSz, mShadowMapSz);
        }
    }

    /**
     * Returns the size of the shadow map.
     *
     * @return the size of the shadow map
     */
    public int getShadowMapSize() {
        return mShadowMapSz;
    }

    /**
     * Sets the scene bounds. The specified volume will be covered by the shadow map renderer.
     *
     * @param sceneBounds
     *            Bounds of the scene to be covered
     */
    public void setSceneBounds(BoundingBox sceneBounds) {
        mSceneBounds.set(sceneBounds);
    }

    /**
     * Returns the index of the texture unit the depth texture is bound to.
     *
     * @return the index of the texture unit the depth texture is bound to
     */
    public int getTextureUnit() {
        return mTextureUnit - GL_TEXTURE0;
    }

    /**
     * Sets the texture unit the depth texture is bound to. Do not use GL_TEXTUREn but just the
     * index.
     *
     * @param texUnit the texture unit to use
     */
    public void setTextureUnit(int texUnit) {
        mTextureUnit = texUnit + GL_TEXTURE0;
    }

    /**
     * Returns the view matrix from the shadow camera.
     *
     * @return the view matrix from the shadow camera
     */
    public float[] getShadowViewMatrix() {
        return mShadowViewMatrix;
    }

    /**
     * Returns the projection matrix from the shadow camera.
     *
     * @return the projection matrix from the shadow camera
     */
    public float[] getShadowProjectionMatrix() {
        return mShadowProjMatrix;
    }

    /**
     * Computes the camera clip size for current mShadowViewMatrix and mSceneBounds.
     */
    private void computeCamClipSize(Light l) {
        float lx = (mSceneBounds.maxX - mSceneBounds.minX) / 2;
        float ly = (mSceneBounds.maxY - mSceneBounds.minY) / 2;
        float lz = (mSceneBounds.maxZ - mSceneBounds.minZ) / 2;
        float cx = mSceneBounds.minX + lx;
        float cy = mSceneBounds.minY + ly;
        float cz = mSceneBounds.minZ + lz;

        float d = (float) Math.sqrt(lx * lx + ly * ly + lz * lz);

        mShadowCamera.setPosition(cx, cy, cz);
        mShadowCamera.setLookAt(cx - l.position[0], cy - l.position[1], cz - l.position[2]);
        mShadowCamera.setClipSize(cx - d, cx + d, cy - d, cy + d, cz - d, cz + d);
    }
}


text:
require 'rubygems'
require 'bundler/setup'
require 'database'
require 'pry'
# require 'order_direction'
# require 'order_direction_helper'

require File.expand_path('../../lib/order_direction', __FILE__)

RSpec.configure do |config|
  config.mock_with :rspec

  config.before(:suite) do
    DatabaseCleaner.clean_with :deletion
    DatabaseCleaner.strategy = :deletion
  end

  config.before(:each) do
    DatabaseCleaner.clean
  end
end


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "nsPluginDirServiceProvider.h"

#include "nsCRT.h"
#include "nsIFile.h"
#include "nsDependentString.h"
#include "prmem.h"
#include "nsArrayEnumerator.h"
#include "mozilla/Preferences.h"

#include <windows.h>
#include "nsIWindowsRegKey.h"

using namespace mozilla;

typedef struct structVer
{
  WORD wMajor;
  WORD wMinor;
  WORD wRelease;
  WORD wBuild;
} verBlock;

static void
ClearVersion(verBlock *ver)
{
  ver->wMajor   = 0;
  ver->wMinor   = 0;
  ver->wRelease = 0;
  ver->wBuild   = 0;
}

static BOOL
FileExists(LPCWSTR szFile)
{
  return GetFileAttributesW(szFile) != 0xFFFFFFFF;
}

// Get file version information from a file
static BOOL
GetFileVersion(LPCWSTR szFile, verBlock *vbVersion)
{
  UINT              uLen;
  UINT              dwLen;
  BOOL              bRv;
  DWORD             dwHandle;
  LPVOID            lpData;
  LPVOID            lpBuffer;
  VS_FIXEDFILEINFO  *lpBuffer2;

  ClearVersion(vbVersion);
  if (FileExists(szFile)) {
    bRv    = TRUE;
    LPCWSTR lpFilepath = szFile;
    dwLen  = GetFileVersionInfoSizeW(lpFilepath, &dwHandle);
    lpData = (LPVOID)malloc(dwLen);
    uLen   = 0;

    if (lpData && GetFileVersionInfoW(lpFilepath, dwHandle, dwLen, lpData) != 0) {
      if (VerQueryValueW(lpData, L"\\", &lpBuffer, &uLen) != 0) {
        lpBuffer2 = (VS_FIXEDFILEINFO *)lpBuffer;

        vbVersion->wMajor   = HIWORD(lpBuffer2->dwFileVersionMS);
        vbVersion->wMinor   = LOWORD(lpBuffer2->dwFileVersionMS);
        vbVersion->wRelease = HIWORD(lpBuffer2->dwFileVersionLS);
        vbVersion->wBuild   = LOWORD(lpBuffer2->dwFileVersionLS);
      }
    }

    free(lpData);
  } else {
    /* File does not exist */
    bRv = FALSE;
  }

  return bRv;
}

// Will deep copy ver2 into ver1
static void
CopyVersion(verBlock *ver1, verBlock *ver2)
{
  ver1->wMajor   = ver2->wMajor;
  ver1->wMinor   = ver2->wMinor;
  ver1->wRelease = ver2->wRelease;
  ver1->wBuild   = ver2->wBuild;
}

// Convert a string version to a version struct
static void
TranslateVersionStr(const WCHAR* szVersion, verBlock *vbVersion)
{
  WCHAR* szNum1 = NULL;
  WCHAR* szNum2 = NULL;
  WCHAR* szNum3 = NULL;
  WCHAR* szNum4 = NULL;
  WCHAR* szJavaBuild = NULL;

  WCHAR *strVer = nullptr;
  if (szVersion) {
    strVer = wcsdup(szVersion);
  }

  if (!strVer) {
    // Out of memory
    ClearVersion(vbVersion);
    return;
  }

  // Java may be using an underscore instead of a dot for the build ID
  szJavaBuild = wcschr(strVer, '_');
  if (szJavaBuild) {
    szJavaBuild[0] = '.';
  }

  szNum1 = wcstok(strVer, L".");
  szNum2 = wcstok(NULL,   L".");
  szNum3 = wcstok(NULL,   L".");
  szNum4 = wcstok(NULL,   L".");

  vbVersion->wMajor   = szNum1 ? (WORD) _wtoi(szNum1) : 0;
  vbVersion->wMinor   = szNum2 ? (WORD) _wtoi(szNum2) : 0;
  vbVersion->wRelease = szNum3 ? (WORD) _wtoi(szNum3) : 0;
  vbVersion->wBuild   = szNum4 ? (WORD) _wtoi(szNum4) : 0;

  free(strVer);
}

// Compare two version struct, return zero if the same
static int
CompareVersion(verBlock vbVersionOld, verBlock vbVersionNew)
{
  if (vbVersionOld.wMajor > vbVersionNew.wMajor) {
    return 4;
  } else if (vbVersionOld.wMajor < vbVersionNew.wMajor) {
    return -4;
  }

  if (vbVersionOld.wMinor > vbVersionNew.wMinor) {
    return 3;
  } else if (vbVersionOld.wMinor < vbVersionNew.wMinor) {
    return -3;
  }

  if (vbVersionOld.wRelease > vbVersionNew.wRelease) {
    return 2;
  } else if (vbVersionOld.wRelease < vbVersionNew.wRelease) {
    return -2;
  }

  if (vbVersionOld.wBuild > vbVersionNew.wBuild) {
    return 1;
  } else if (vbVersionOld.wBuild < vbVersionNew.wBuild) {
    return -1;
  }

  /* the versions are all the same */
  return 0;
}

//*****************************************************************************
// nsPluginDirServiceProvider::Constructor/Destructor
//*****************************************************************************

nsPluginDirServiceProvider::nsPluginDirServiceProvider()
{
}

nsPluginDirServiceProvider::~nsPluginDirServiceProvider()
{
}

//*****************************************************************************
// nsPluginDirServiceProvider::nsISupports
//*****************************************************************************

NS_IMPL_THREADSAFE_ISUPPORTS1(nsPluginDirServiceProvider,
                              nsIDirectoryServiceProvider)

//*****************************************************************************
// nsPluginDirServiceProvider::nsIDirectoryServiceProvider
//*****************************************************************************

NS_IMETHODIMP
nsPluginDirServiceProvider::GetFile(const char *charProp, bool *persistant,
                                    nsIFile **_retval)
{
  nsCOMPtr<nsIFile>  localFile;
  nsresult rv = NS_ERROR_FAILURE;

  NS_ENSURE_ARG(charProp);

  *_retval = nullptr;
  *persistant = false;

  nsCOMPtr<nsIWindowsRegKey> regKey =
    do_CreateInstance("@mozilla.org/windows-registry-key;1");
  NS_ENSURE_TRUE(regKey, NS_ERROR_FAILURE);

  if (nsCRT::strcmp(charProp, NS_WIN_JRE_SCAN_KEY) == 0) {
    nsAdoptingCString strVer = Preferences::GetCString(charProp);
    if (!strVer) {
      return NS_ERROR_FAILURE;
    }
    verBlock minVer;
    TranslateVersionStr(NS_ConvertASCIItoUTF16(strVer).get(), &minVer);

    rv = regKey->Open(nsIWindowsRegKey::ROOT_KEY_LOCAL_MACHINE,
                      NS_LITERAL_STRING("Software\\JavaSoft\\Java Runtime Environment"),
                      nsIWindowsRegKey::ACCESS_READ);
    NS_ENSURE_SUCCESS(rv, rv);

    verBlock maxVer;
    ClearVersion(&maxVer);

    nsAutoString newestPath;
    nsAutoString browserJavaVersion;
    regKey->ReadStringValue(NS_LITERAL_STRING("BrowserJavaVersion"),
                            browserJavaVersion);

    uint32_t childCount = 0;
    regKey->GetChildCount(&childCount);

    // We must enumerate through the keys because what if there is
    // more than one version?
    for (uint32_t index = 0; index < childCount; ++index) {
      nsAutoString childName;
      rv = regKey->GetChildName(index, childName);
      if (NS_SUCCEEDED(rv)) {
        // Skip major.minor as it always points to latest in its family
        uint32_t numChars = 0;
        int32_t offset = 0;
        while ((offset = childName.FindChar(L'.', offset + 1)) >= 0) {
          ++numChars;
        }
        if (numChars < 2)
          continue;

        nsCOMPtr<nsIWindowsRegKey> childKey;
        rv = regKey->OpenChild(childName, nsIWindowsRegKey::ACCESS_QUERY_VALUE,
                               getter_AddRefs(childKey));
        if (NS_SUCCEEDED(rv) && childKey) {
          nsAutoString path;
          rv = childKey->ReadStringValue(NS_LITERAL_STRING("JavaHome"), path);
          if (NS_SUCCEEDED(rv)) {
            verBlock curVer;
            TranslateVersionStr(childName.get(), &curVer);
            if (CompareVersion(curVer, minVer) >= 0) {
              if (browserJavaVersion == childName) {
                newestPath = path;
                break;
              }

              if (CompareVersion(curVer, maxVer) >= 0) {
                newestPath = path;
                CopyVersion(&maxVer, &curVer);
              }
            }
          }
        }
      }
    }

    if (newestPath.IsEmpty()) {
      return NS_ERROR_FAILURE;
    }

    // We require the newer NPAPI Java plugin.
    newestPath += NS_LITERAL_STRING("\\bin\\new_plugin");

    rv = NS_NewLocalFile(newestPath,
                         true, getter_AddRefs(localFile));

    if (NS_SUCCEEDED(rv)) {
      nsCOMPtr<nsIWindowsRegKey> newKey =
        do_CreateInstance("@mozilla.org/windows-registry-key;1");
      NS_ENSURE_TRUE(newKey, NS_ERROR_FAILURE);

      rv = newKey->Create(nsIWindowsRegKey::ROOT_KEY_LOCAL_MACHINE,
                          NS_LITERAL_STRING("Software\\mozilla.org\\Mozilla"),
                          nsIWindowsRegKey::ACCESS_QUERY_VALUE |
                          nsIWindowsRegKey::ACCESS_SET_VALUE);
      if (NS_SUCCEEDED(rv)) {
        bool currentVersionExists = false;
        newKey->HasValue(NS_LITERAL_STRING("CurrentVersion"),
                         &currentVersionExists);
        if (!currentVersionExists) {
          newKey->WriteStringValue(NS_LITERAL_STRING("CurrentVersion"),
                                   NS_LITERAL_STRING(MOZILLA_VERSION));
        }
      }
    }
  } else if (nsCRT::strcmp(charProp, NS_WIN_QUICKTIME_SCAN_KEY) == 0) {
    nsAdoptingCString strVer = Preferences::GetCString(charProp);
    if (!strVer) {
      return NS_ERROR_FAILURE;
    }
    verBlock minVer;
    TranslateVersionStr(NS_ConvertASCIItoUTF16(strVer).get(), &minVer);

    // Look for the Quicktime system installation plugins directory
    verBlock qtVer;
    ClearVersion(&qtVer);

    // First we need to check the version of Quicktime via checking
    // the EXE's version table
    rv = regKey->Open(nsIWindowsRegKey::ROOT_KEY_LOCAL_MACHINE,
                      NS_LITERAL_STRING("software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\QuickTimePlayer.exe"),
                      nsIWindowsRegKey::ACCESS_READ);
    if (NS_SUCCEEDED(rv)) {
      nsAutoString path;
      rv = regKey->ReadStringValue(NS_LITERAL_STRING(""), path);
      if (NS_SUCCEEDED(rv)) {
        GetFileVersion(path.get(), &qtVer);
      }
      regKey->Close();
    }
    if (CompareVersion(qtVer, minVer) < 0)
      return rv;

    rv = regKey->Open(nsIWindowsRegKey::ROOT_KEY_LOCAL_MACHINE,
                      NS_LITERAL_STRING("software\\Apple Computer, Inc.\\QuickTime"),
                      nsIWindowsRegKey::ACCESS_READ);
    if (NS_SUCCEEDED(rv)) {
      nsAutoString path;
      rv = regKey->ReadStringValue(NS_LITERAL_STRING("InstallDir"), path);
      if (NS_SUCCEEDED(rv)) {
        path += NS_LITERAL_STRING("\\Plugins");
        rv = NS_NewLocalFile(path, true,
                             getter_AddRefs(localFile));
      }
    }
  } else if (nsCRT::strcmp(charProp, NS_WIN_WMP_SCAN_KEY) == 0) {
    nsAdoptingCString strVer = Preferences::GetCString(charProp);
    if (!strVer) {
      return NS_ERROR_FAILURE;
    }
    verBlock minVer;
    TranslateVersionStr(NS_ConvertASCIItoUTF16(strVer).get(), &minVer);

    // Look for Windows Media Player system installation plugins directory
    verBlock wmpVer;
    ClearVersion(&wmpVer);

    // First we need to check the version of WMP
    rv = regKey->Open(nsIWindowsRegKey::ROOT_KEY_LOCAL_MACHINE,
                      NS_LITERAL_STRING("software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\wmplayer.exe"),
                      nsIWindowsRegKey::ACCESS_READ);
    if (NS_SUCCEEDED(rv)) {
      nsAutoString path;
      rv = regKey->ReadStringValue(NS_LITERAL_STRING(""), path);
      if (NS_SUCCEEDED(rv)) {
        GetFileVersion(path.get(), &wmpVer);
      }
      regKey->Close();
    }
    if (CompareVersion(wmpVer, minVer) < 0)
      return rv;

    rv = regKey->Open(nsIWindowsRegKey::ROOT_KEY_LOCAL_MACHINE,
                      NS_LITERAL_STRING("software\\Microsoft\\MediaPlayer"),
                      nsIWindowsRegKey::ACCESS_READ);
    if (NS_SUCCEEDED(rv)) {
      nsAutoString path;
      rv = regKey->ReadStringValue(NS_LITERAL_STRING("Installation Directory"),
                                   path);
      if (NS_SUCCEEDED(rv)) {
        rv = NS_NewLocalFile(path, true,
                             getter_AddRefs(localFile));
      }
    }
  } else if (nsCRT::strcmp(charProp, NS_WIN_ACROBAT_SCAN_KEY) == 0) {
    nsAdoptingCString strVer = Preferences::GetCString(charProp);
    if (!strVer) {
      return NS_ERROR_FAILURE;
    }

    verBlock minVer;
    TranslateVersionStr(NS_ConvertASCIItoUTF16(strVer).get(), &minVer);

    // Look for Adobe Acrobat system installation plugins directory
    verBlock maxVer;
    ClearVersion(&maxVer);

    nsAutoString newestPath;

    rv = regKey->Open(nsIWindowsRegKey::ROOT_KEY_LOCAL_MACHINE,
                      NS_LITERAL_STRING("software\\Adobe\\Acrobat Reader"),
                      nsIWindowsRegKey::ACCESS_READ);
    if (NS_FAILED(rv)) {
      rv = regKey->Open(nsIWindowsRegKey::ROOT_KEY_LOCAL_MACHINE,
                        NS_LITERAL_STRING("software\\Adobe\\Adobe Acrobat"),
                        nsIWindowsRegKey::ACCESS_READ);
      if (NS_FAILED(rv)) {
        return NS_ERROR_FAILURE;
      }
    }

    // We must enumerate through the keys because what if there is
    // more than one version?
    uint32_t childCount = 0;
    regKey->GetChildCount(&childCount);

    for (uint32_t index = 0; index < childCount; ++index) {
      nsAutoString childName;
      rv = regKey->GetChildName(index, childName);
      if (NS_SUCCEEDED(rv)) {
        verBlock curVer;
        TranslateVersionStr(childName.get(), &curVer);

        childName += NS_LITERAL_STRING("\\InstallPath");

        nsCOMPtr<nsIWindowsRegKey> childKey;
        rv = regKey->OpenChild(childName, nsIWindowsRegKey::ACCESS_QUERY_VALUE,
                               getter_AddRefs(childKey));
        if (NS_SUCCEEDED(rv)) {
          // We have a sub key
          nsAutoString path;
          rv = childKey->ReadStringValue(NS_LITERAL_STRING(""), path);
          if (NS_SUCCEEDED(rv)) {
            if (CompareVersion(curVer, maxVer) >= 0 &&
                CompareVersion(curVer, minVer) >= 0) {
              newestPath = path;
              CopyVersion(&maxVer, &curVer);
            }
          }
        }
      }
    }

    if (!newestPath.IsEmpty()) {
      newestPath += NS_LITERAL_STRING("\\browser");
      rv = NS_NewLocalFile(newestPath, true,
                           getter_AddRefs(localFile));
    }
  }

  if (localFile && NS_SUCCEEDED(rv))
    return CallQueryInterface(localFile, _retval);

  return rv;
}

nsresult
nsPluginDirServiceProvider::GetPLIDDirectories(nsISimpleEnumerator **aEnumerator)
{
  NS_ENSURE_ARG_POINTER(aEnumerator);
  *aEnumerator = nullptr;

  nsCOMArray<nsIFile> dirs;

  GetPLIDDirectoriesWithRootKey(nsIWindowsRegKey::ROOT_KEY_CURRENT_USER, dirs);
  GetPLIDDirectoriesWithRootKey(nsIWindowsRegKey::ROOT_KEY_LOCAL_MACHINE, dirs);

  return NS_NewArrayEnumerator(aEnumerator, dirs);
}

nsresult
nsPluginDirServiceProvider::GetPLIDDirectoriesWithRootKey(uint32_t aKey, nsCOMArray<nsIFile> &aDirs)
{
  nsCOMPtr<nsIWindowsRegKey> regKey =
    do_CreateInstance("@mozilla.org/windows-registry-key;1");
  NS_ENSURE_TRUE(regKey, NS_ERROR_FAILURE);

  nsresult rv = regKey->Open(aKey,
                             NS_LITERAL_STRING("Software\\MozillaPlugins"),
                             nsIWindowsRegKey::ACCESS_READ);
  NS_ENSURE_SUCCESS(rv, rv);

  uint32_t childCount = 0;
  regKey->GetChildCount(&childCount);

  for (uint32_t index = 0; index < childCount; ++index) {
    nsAutoString childName;
    rv = regKey->GetChildName(index, childName);
    if (NS_SUCCEEDED(rv)) {
      nsCOMPtr<nsIWindowsRegKey> childKey;
      rv = regKey->OpenChild(childName, nsIWindowsRegKey::ACCESS_QUERY_VALUE,
                             getter_AddRefs(childKey));
      if (NS_SUCCEEDED(rv) && childKey) {
        nsAutoString path;
        rv = childKey->ReadStringValue(NS_LITERAL_STRING("Path"), path);
        if (NS_SUCCEEDED(rv)) {
          nsCOMPtr<nsIFile> localFile;
          if (NS_SUCCEEDED(NS_NewLocalFile(path, true,
                                           getter_AddRefs(localFile))) &&
              localFile) {
            // Some vendors use a path directly to the DLL so chop off
            // the filename
            bool isDir = false;
            if (NS_SUCCEEDED(localFile->IsDirectory(&isDir)) && !isDir) {
              nsCOMPtr<nsIFile> temp;
              localFile->GetParent(getter_AddRefs(temp));
              if (temp)
                localFile = temp;
            }

            // Now we check to make sure it's actually on disk and
            // To see if we already have this directory in the array
            bool isFileThere = false;
            bool isDupEntry = false;
            if (NS_SUCCEEDED(localFile->Exists(&isFileThere)) && isFileThere) {
              int32_t c = aDirs.Count();
              for (int32_t i = 0; i < c; i++) {
                nsIFile *dup = static_cast<nsIFile*>(aDirs[i]);
                if (dup &&
                    NS_SUCCEEDED(dup->Equals(localFile, &isDupEntry)) &&
                    isDupEntry) {
                  break;
                }
              }

              if (!isDupEntry) {
                aDirs.AppendObject(localFile);
              }
            }
          }
        }
      }
    }
  }
  return NS_OK;
}


text:
<?xml version="1.0"?>
<Document>

	<Sentence>
		<value>Anemia of chronic disease is anemia that is found in people with certain long-term (chronic) medical conditions.</value>
		<pattern_crowdsource> Anemia of chronic disease is [[anemia|C0002871]] that is found in [[people|C0027361]] with certain long-term (chronic) medical conditions.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>Anemia</surface-form>
				<RDF-ID>C0002871</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>chronic disease</surface-form>
				<RDF-ID>C0008679</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>anemia</surface-form>
				<RDF-ID>C0002871</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>people</surface-form>
				<RDF-ID>C0027361</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>certain</surface-form>
				<RDF-ID>C0205423</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>long-term</surface-form>
				<RDF-ID>C0443252</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>chronic</surface-form>
				<RDF-ID>C0205191</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>medical</surface-form>
				<RDF-ID>C0205476</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>conditions</surface-form>
				<RDF-ID>C0348080</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0002871 PROCESS_OF C0027361</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>Anemia is a lower-than-normal number of red blood cells in the blood.</value>
		<pattern_crowdsource> [[Anemia|C0002871]] is a lower-than-normal number of red blood cells in the [[blood|C0005767]].		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>Anemia</surface-form>
				<RDF-ID>C0002871</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>lower</surface-form>
				<RDF-ID>C0441994</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>normal number</surface-form>
				<RDF-ID>C0332592</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>red blood cells</surface-form>
				<RDF-ID>C0014792</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>blood</surface-form>
				<RDF-ID>C0005767</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0005767 LOCATION_OF C0002871</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>Some conditions can lead to anemia of chronic disease include:  - Autoimmune disorders, such as Crohn disease, systemic lupus erythematosus, rheumatoid arthritis, and ulcerative colitis  - Cancer, including lymphoma and Hodgkin disease  - Chronic kidney disease  - Long-term infections, such as bacterial endocarditis, osteomyelitis (bone infection), HIV/AIDS, hepatitis B or hepatitis C</value>
		<pattern_crowdsource> Some conditions can lead to anemia of chronic disease include:  - Autoimmune disorders, such as Crohn disease, systemic lupus erythematosus, rheumatoid arthritis, and ulcerative colitis  - Cancer, including lymphoma and Hodgkin disease  - Chronic kidney disease  - Long-term [[infections|C0021311]], such as [[bacterial endocarditis|C0014121]], osteomyelitis (bone infection), HIV/AIDS, hepatitis B or hepatitis C		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>conditions</surface-form>
				<RDF-ID>C0348080</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>anemia</surface-form>
				<RDF-ID>C0002871</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>chronic disease</surface-form>
				<RDF-ID>C0008679</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Autoimmune disorders</surface-form>
				<RDF-ID>C0004364</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Crohn disease</surface-form>
				<RDF-ID>C0010346</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>systemic lupus erythematosus</surface-form>
				<RDF-ID>C0024141</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>rheumatoid arthritis</surface-form>
				<RDF-ID>C0003873</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>ulcerative colitis</surface-form>
				<RDF-ID>C0009324</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Cancer</surface-form>
				<RDF-ID>C0006826</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>lymphoma</surface-form>
				<RDF-ID>C0024299</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Hodgkin disease</surface-form>
				<RDF-ID>C0019829</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Chronic kidney disease</surface-form>
				<RDF-ID>C0022661</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Long-term</surface-form>
				<RDF-ID>C0443252</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>infections</surface-form>
				<RDF-ID>C0021311</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>bacterial endocarditis</surface-form>
				<RDF-ID>C0014121</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>osteomyelitis</surface-form>
				<RDF-ID>C0029443</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>bone infection</surface-form>
				<RDF-ID>C0029443</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>HIV</surface-form>
				<RDF-ID>C0001175</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>AIDS</surface-form>
				<RDF-ID>C0001175</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>hepatitis B</surface-form>
				<RDF-ID>C0019163</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>hepatitis C</surface-form>
				<RDF-ID>C0019196</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0014121 ISA C0021311</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>The doctor will perform a physical exam.</value>
		<pattern_crowdsource> The [[doctor|C0031831]] will perform a [[physical exam|C0031809]].		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>doctor</surface-form>
				<RDF-ID>C0031831</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>physical exam</surface-form>
				<RDF-ID>C0031809</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0031809 ADMINISTERED_TO C0031831</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>Iron supplements may sometimes be used, but only for patients whose iron levels are low.</value>
		<pattern_crowdsource> [[Iron supplements|C0721124]] may sometimes be used, but only for [[patients|C0030705]] whose iron levels are low.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>Iron supplements</surface-form>
				<RDF-ID>C0721124</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>patients</surface-form>
				<RDF-ID>C0030705</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>iron levels</surface-form>
				<RDF-ID>C0337439</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>low</surface-form>
				<RDF-ID>C0205251</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0721124 TREATS C0030705</triple>
		</triples>
	</Sentence>

</Document>


text:
PHP Eval Console
================

In-browser, standalone console that executes your PHP code and returns the produced output. This package is based on
 package [darsain/laravel-console](https://github.com/darsain/laravel-console).

![Screenshot](http://i.imgur.com/ryXpkvc.png)

## Table of contents

* [Installation](#installation)
* [Configuration](#configuration)
* [Evaluators](#evaluators)
* [Authorizers](#authorizers)
* [Queries callback](#queries-callback)
* [Laravel support](#laravel-support)

## Installation

Get package through composer:

```bash
composer require meebio/php-eval-console
```

Copy `vendor/meebio/php-eval-console/assets` to `assets` in project root directory.

Create `index.php` in project root directory with following content:

```php
<?php

require_once __DIR__ . '/vendor/autoload.php';

use Meebio\PhpEvalConsole\Console;

$console = new Console();
$console->boot();
```

Open index.php page in browser.

## Configuration

Key | Type | Description | Default
--- | --- | --- | ---
assets_dir | string | Relative path to assets directory. | `'assets'`
views_path | string | Absolute path to views directory. Modify only if you want to use custom views. | `'<...>/Views'`
console_view_path | string | Absolute path to main view. Modify only if you want to use custom views. | `'<...>/Views/console.php'`
execute_url | string\|null | URL to application execute route. If null set it is guessed. | null
evaluator | `EvaluatorInterface` | Instance of EvaluatorInterface implementation that will be used for running code. | `EvalEvaluator`
authorizer  | null\|`AuthorizerInterface` | Instance of AuthorizerInterface implementation that will be used for running code. This option also accepts null or array of authorizers. | `IpAuthorizer`
queries_callback | null\|closure | Callback that will return database queries to display after running code. | null
post_execute_callback | null\|closure | Post execute callback. Can be used to perform some actions after code evaluation, but before returning result. | null

## Evaluators

#### EvalEvaluator

Basic evaluator that uses `eval` command. This is entirely not secure.

#### PhpSandboxEvaluator

More advanced php evaluator that make use of [fieryprophet/php-sandbox](https://github.com/fieryprophet/php-sandbox)
 package. This sandbox class utilizes [PHP-Parser](https://github.com/nikic/PHP-Parser) to prevent sandboxed code from
 running unsafe code. If configured properly this evaluator could probably allow application to be exposed to public
 users. To use this evaluator require `fieryprophet/php-sandbox` package in composer.

## Authorizers

#### IpAuthorizer

This authorizer ensures that only access from provided ips is possible. Authorizer constructor takes to arguments first
 is array of allowed ips (null if this check should be disabled) and second is array of disallowed ips (null if this
 check should be disabled).

## Queries callback

Closure that will provide array of queries after code evaluation. Returned data should be in following format:

```php
array(
    array(
        'query' => 'SELECT * FROM `users`;',
        'time'  => 0.113,
    ),
    array(
        'query' => 'SELECT * FROM `posts` JOIN `category` ON `post`.`category_id` = `category`.`id`;',
        'time'  => 0.231,
    ),
);
```

## Laravel support

You should install the package through Composer:

```bash
composer require meebio/php-eval-console
```

You must add service provider to app config:

```php
'providers' => [
    ...
    Meebio\PhpEvalConsole\Providers\PhpEvalConsoleLaravelServiceProvider::class,
    ...
];
```

You can publish package assets through artisan command:

```bash
php artisan vendor:publish --provider="Meebio\PhpEvalConsole\Providers\PhpEvalConsoleLaravelServiceProvider"
```

or just copy directory `vendor/meebio/php-eval-console/assets` to `public/vendor/php-eval-console`.

Last thing that should be done is to make sure CSRF Protection is not blocking console post requests.
 To do that in Laravel 5.1 you should add console URI to be excluded in VerifyCsrfToken class. So it looks something
 like this:

```php
<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'console',
    ];
}
```

For lower versions of Laravel, that can be done as well, but some manual method overriding is needed.

When everything is done you should see Console at `/console` uri.

## TODO

- Improve errors handling.


text:
(function(angular) {
  "use strict";

  function zufallszahl(minimum, maximum) {
    return Math.round(Math.random() * (maximum - minimum)) + minimum;
  }

  angular.module('memory')
    .factory('spieler', function() {
      return {
        /**
         * Mischt die Karten im stapel.
         * Die Karten im Stapel sind von Beginn an fein säuberlich sortiert.
         * Das heißt die beiden zueinandergehörigen Karten liegen nebeneinander.
         *
         * Das ist ja langweilig wenn man genau weiß wo die richtige Karte liegt.
         * Also mische was das Zeug hält damit es ein spannendes Spiel wird.
         *
         * @param  {[type]} kartenstapel Der Kartenstapel bietet folgende Funktionen an.
         *                               kartenZaehlen(): Zählt die Karten im Stapel und gibt die Anzahl der Karten zurück.
         *                               tauscheKarten(stelle1, stelle2): Tauscht die Karte an Stelle 1 mit der Karte an Stelle 2.
         */
        mische: function(kartenstapel) {
          var kartenanzahl = kartenstapel.zaehleKarten();

          for (var anzahlVertauschungen = 0; anzahlVertauschungen < 100; anzahlVertauschungen++) {
            var ersteKartenNummer = zufallszahl(1, kartenanzahl);
            var zweiteKartenNummer = zufallszahl(1, kartenanzahl);

            var ersteKarte = kartenstapel.tauscheKarten(ersteKartenNummer, zweiteKartenNummer);
          }
        },

        /**
         * Hier wird geprüft, ob genug Karten Aufgedeckt sind um sie miteinander zu vergleichen.
         *
         * Wie das beim Memory ist die Anzahl der benötigten Karten für einen Versuch ja nicht schwer zu erraten ;)
         *
         * @param  {number} anzahlAufgedeckterKarten Die Anzahl der Aufgedeckten Karten.
         * @return {boolean}                         true wenn genügend Karten aufgedeckt sind. Sonst false.
         */
        genugKartenAufgedeckt: function(anzahlAufgedeckterKarten) {
          return anzahlAufgedeckterKarten === 2;
        },

        /**
         * Vergleicht zwei Karten miteinander.
         * Diese Funktion wird aufgerufen wenn zwei Karten aufgeschlagen wurden.
         *
         *	Jede karte bietet das Feld "name". Es gibt immer zwei Karten mit dem gleichen Namen.
         *
         * @param  {[type]} karte1 Die erste Karte.
         * @param  {[type]} karte2 Die zweite Karte.
         * @return {boolean}        true wenn beide Karten gleich sind. Ansonsten false.
         */
        vergleiche: function(karte1, karte2) {
          return karte1.name === karte2.name;
        },

        /**
         * Diese Funktion wird aufgerufen wenn zwei Karten aufgedeckt wurden, die aber nicht zusammenpassen.
         *
         * Jede karte hat die eigenschaft offen die angibt, ob die Karte offen oder verdeckt am Feld liegt.
         * Wenn offen = true --> Karte liegt offen am Feld.
         * Wenn offen = false --> Karte liegt verdeckt am Feld.
         *
         * @param  {[type]} karte1 Die erste aufgedeckte Karte.
         * @param  {[type]} karte2 Die zweite aufgedeckte Karte.
         */
        kartenPassenNicht: function(karte1, karte2) {
          karte1.offen = false;
          karte2.offen = false;
        },

        /**
         * Berechnet die Punkte die der Spieler für das finden eines Paares bekommt.
         *
         * @param  {number} versuche        Die Anzahl der Versuche die der Spieler für das finden des Paares benötigt hat.
         * @param  {number} gefundenePaare  Die Anzahl der Paare die der Spieler bereits gefunden hat.
         * @return {number}                 Die Punkte die der Spieler bekommt.
         */
        berechnePunkte: function(versuche, gefundenePaare) {
          if (versuche === 1) {
            return 100;
          }

          var punkte = 100 - (versuche * gefundenePaare * 10);

          if (punkte < 10) {
            return 10;
          }

          return punkte;
        },

        /**
         * Diese Funktion wird aufgerufen um zu prüfen, ob alle Kartenpaare gefunden wurden.
         * @param  {number} gefundenePaare Die Anzahl der bereits gefundenen Kartenpaare.
         * @param  {number} anzahlKarten   Die Anzahl der Karten die insgesamt am Feld liegen.
         * @return {boolean}                true wenn alle Kartenpaare gefunden wurden. Sonst false.
         */
        wurdeAllesGefunden: function(gefundenePaare, anzahlKarten) {
          return gefundenePaare === anzahlKarten / 2;
        },

        /**
         * Die Funktion wird aufgerufen wenn alle Kartenpaare gefunden wurden um den Glückwunschtext für den Spieler zu generieren.
         *
         * @param  {number} punkte          Die Anzahl der Punkte die der Spieler erreicht hat.
         * @param  {number} gefundenePaare  Die Anzahl der Paare die der Spieler gefunden hat.
         * @return {string}                 Der Glückwunschtext der dem Spieler angezeigt wird.
         */
        glueckwunsch: function(punkte, gefundenePaare) {
          return 'Glückwunsch. Du hast ' + punkte + ' von ' + (gefundenePaare * 100) + ' Punkte erreicht!!! :)';
        }
      };
    });
})(angular);


text:
import urllib2
import urllib
import json
import pprint

def lists(item):
	data_string = urllib.quote(json.dumps({'id': 'data_explorer'}))

	action = '%s_list' %item

	# Make the HTTP request.
	url = 'https://data.hdx.rwlabs.org/api/action/%s'%action

	#url = 'http://demo.ckan.org/api/3/action/group_list'
	response = urllib2.urlopen(url,
	        data_string)
	assert response.code == 200

	# Use the json module to load CKAN's response into a dictionary.
	response_dict = json.loads(response.read())

	# Check the contents of the response.
	assert response_dict['success'] is True
	result = response_dict['result']
	return result

def package_list():
	return lists("package")

def tags_list():
	return lists("tag")

def group_list():
	return lists("group")

get_attrib = lambda attrib,x: map(lambda k: k[attrib],x)

tag_names = lambda x: get_attrib("name",x['tags'])

def packages_by_tags(tags):
	ids = package_list()

	for t in (x for x in ids if any(map(lambda y: y in tag_names(show_package(x)) ,tags))):
		print t

def get_ors_sahel():
	data_string = urllib.quote(json.dumps({'resource_id': '735b3f3a-eef6-4eb4-8b43-9307bac3177c'}))
	action = 'datastore_search'
	url = 'https://data.hdx.rwlabs.org/api/action/%s'%action

	response = urllib2.urlopen(url,
	        data_string)
	assert response.code == 200

	# Use the json module to load CKAN's response into a dictionary.
	response_dict = json.loads(response.read())

	# Check the contents of the response.
	assert response_dict['success'] is True
	result = response_dict['result']
	return result

def show_tags(id):
	return show('tag',id)['packages']

def show_package(id):
	return show('package',id)

def show(item,item_id):
	data_string = urllib.quote(json.dumps({'id': item_id}))
	action = '%s_show' % item
	url = 'https://data.hdx.rwlabs.org/api/action/%s'%action

	response = urllib2.urlopen(url,
	        data_string)

	assert response.code == 200

	# Use the json module to load CKAN's response into a dictionary.
	response_dict = json.loads(response.read())

	# Check the contents of the response.
	assert response_dict['success'] is True
	result = response_dict['result']
	return result

def get_ors_tags():
	data_string = urllib.quote(json.dumps({'id': 'ors'}))
	action = 'tag_show'
	url = 'https://data.hdx.rwlabs.org/api/action/%s'%action

	response = urllib2.urlopen(url,
	        data_string)
	assert response.code == 200

	# Use the json module to load CKAN's response into a dictionary.
	response_dict = json.loads(response.read())

	# Check the contents of the response.
	assert response_dict['success'] is True
	result = response_dict['result']
	return result

if __name__ == '__main__':
	#print get_ors_tags()
	pp = pprint.PrettyPrinter(indent=2)
        pp.pprint(get_ors_tags())


text:
/**
 *
 * @author Neal Xiong
 */

(function(global){
	/** @private */
	var isNull = function(obj){
		return obj == undefined ;
	};
	/**
	 * Returns the current dir name which is the url path of the current page
	 * @private
	 */
	var getDirname = function(path){
		if(!path && global && global.location){
			path = window.location.href ;
		}
		if(path){
			var lastSlash = path.lastIndexOf("/");
			return path.substring(0, lastSlash) + "/";
		}else{
			// ???
			return ".";
		}
	};
	/** @constant */
	var JS_EXTENSION = ".js";
	var require;
	require = function(moduleId){
		/*
		 * Needs to handle:
		 * 	1. New module to load
		 * 	2. Module already in cache
		 * 	3. Module is half-way loaded and in stack
		 * 	4. Module in cache but needs reload.
		 * */
		var dirname ;
		if(_stack.length > 0){
			dirname = _stack.peek()._dirname ;
		}else{
			dirname = getDirname();
		}
		var id = _moduleIdResolver(dirname, moduleId);
		if (id in _cache && _conf["useCache"]){
            //Already in cache
			return _cache[id].exports;
		}

        var module = _create(id);
		if(id in _stack.modNames){
            //Return immediately to resolve require loop
            return _stack[_stack.modNames[id]].exports ;
		}

		_stack.push(module);

		//New module to load
		var script = _ajaxGet(id);//synchronized get
		if(isNull(script)){
			//TODO Re-try other paths?
			throw Error("Module file is not found: " + id);
		}

		_evalText(script, module);

		//cache the loaded module
		var mod = _stack.pop();// mod should pointing to the same object as module
		if(_conf["useCache"]){
			_cache[mod.id] = mod ;
		}

		return mod.exports ;
	};

	/**
	 * @private @memberOf require
	 */
	var _cache = require.cache = {}
		, _stack = require.stack = [];
	/**
	 *
	 * @memberOf _stack
	 */
	_stack.modNames = {};//un-ordered module names that are in _stack
	/**
	 *
	 * @memberOf _stack
	 */
	_stack.push = function(elem){
		Array.prototype.push.call(this, elem);
		this.modNames[elem.id] = this.length - 1;
	};

	/**
	 *
	 * @memberOf _stack
	 */
	_stack.pop = function(){
		var o = Array.prototype.pop.call(this);
		delete this.modNames[o.id];
		return o ;
	};

	/**
	 *
	 * @memberOf _stack
	 */
	_stack.peek = function(){
		if(this.length == 0){
			return null ;
		}
		return this[this.length - 1];
	};

	/**
	 * Configuration
	 * @private
	 * @field
	 */
	var _conf = {
			"useStrict": true,
			"useCache": true
	};
	/** @memberOf require */
	require.config = function(k, v){
		if(k && typeof v !== undefined){
			_conf[k] = v ;
		}
		return _conf[k];
	};
	/**
	 * Relative moduleId can start with '.' or '..'
	 * '.js' at the end is omittable
	 * @param dirname The current directory. It will be used when moduleId is a relative path.
	 * @param moduleId The module file path
	 * @memberOf require
	 */
	require.moduleIdResolver = function(dirname, moduleId){
		//Relative moduleId can start with '.' or '..'
		// '.js' at the end is omittable
		if(moduleId){
			moduleId = moduleId.trim();
			//TODO Supports backslash(\) as delimiter as well?
			var terms = moduleId.split("/");
			if(terms[0] == "." || terms[0] == ".."){
				moduleId = dirname + moduleId;
			}else{
				//Absolute path
				//TODO Goes through lib path
				//moduleId = moduleId;
			}
			//Appends '.js' to the end if moduleId doesn't have it
			moduleId += moduleId.lastIndexOf(JS_EXTENSION) != (moduleId.length - JS_EXTENSION.length)? JS_EXTENSION:"" ;

			//Normalize moduleId
			terms = moduleId.split("/");
			var normalizedTerms = [];
			for(i in terms){
				var term = terms[i];
				switch(term){
					case "..":
						if(isNull(normalizedTerms.pop())){
							//TODO exception?
							//Bad file path
						}
					case ".":
						continue;
						default:
							normalizedTerms.push(term);
				}
			}
			moduleId = normalizedTerms.join("/");
		}else{
			// Oct 11, 2013. For now _moduleIdResolver("tool.js") => "tool.js"
			//moduleId is undefined or ""
			throw new Error("No module identifier.");
		}
		return moduleId ;
	};
	var _moduleIdResolver = require.moduleIdResolver ;

	/** @memeberOf require */
	var _create = require.createModule = function(moduleId){
		var dirname = getDirname(moduleId);
		var filename = moduleId.replace(dirname, "");
		return {
			id: moduleId,
			_dirname: dirname,
            _filename: filename,
            exports: {}
		};
	};

	/**
	 * @private
	 */
	var _evalText = require.evalScript = function(text, module){
		try{
			//TODO more variables?
			//TODO use local variables to override window, document, etc?
			text = ( _conf["useStrict"] ? "\"use strict\";": "" ) + text ;
			var func = new Function("module", "exports", "require", text);
			// Within the script 'this' refer to the current module object
			func.apply(module, [module, module["exports"], require]);
		}catch(e){
			throw new Error("Evaluation failed: " + e.message);
		}
	};

	var _ajaxGet = require.ajaxGet = function(resource, async, successFn, notFoundFn){
		//Default is async == false
		async = async ? true: false ;
		var txt = undefined;
		if(global.jQuery && global.jQuery.ajax){
			global.jQuery.ajax({
			    url: resource,
			    async: async,
			    success: function(data, statusText, jqXHR){
			          txt = data ;
			          successFn ? successFn(data): "";
			        },
			    error: function(data, statusText, jqXHR){
			        if(statusText === "404" && notFoundFn)
			          notFoundFn();
			    },
			    //We don't want jQuery to execute the script for us.
			    dataType: "text"
			});
		}else{
			var xmlhttp;
			if (global.ActiveXObject){
				xmlhttp=new global.ActiveXObject("Microsoft.XMLHTTP");
			}
			else {
				xmlhttp=new global.XMLHttpRequest();
			}
			xmlhttp.onreadystatechange = function() {
				if(this.readyState == 4){
					if(this.status == 200){
						if(!async){
							try{
								txt = xmlhttp.responseText;
							}catch(e){
								//
								txt = "";
							}

						  }else{
							  if(successFn){
								  var t = "";
								  try{
										t = xmlhttp.responseText;
									}catch(e){
										//
										t = "";
									}
									successFn(t) ;
							  }
						  }
					}
					else{
						if(!async){
//							var err = new Error("Module not found: " + resource);
//							err.httpStatus = 404 ;
//							throw err;
						  }else{
							  if(notFoundFn) notFoundFn();
						  }
					}
				}
			};
			xmlhttp.open("GET", resource, async);
			xmlhttp.send();
		}
		return txt ;
	};

	var module;
	//Exports "require" to global/module
	global.require = (module|| {}).exports = require ;
})(this);