text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.Composition.ReflectionModel;
using System.Globalization;
using System.Reflection;
using Microsoft.Internal;
using Microsoft.Internal.Collections;
using System.ComponentModel.Composition.Primitives;

namespace System.ComponentModel.Composition.ReflectionModel
{
    internal class ReflectionMemberImportDefinition : ReflectionImportDefinition
    {
        private LazyMemberInfo _importingLazyMember;

        public ReflectionMemberImportDefinition(
            LazyMemberInfo importingLazyMember,
            string contractName,
            string requiredTypeIdentity,
            IEnumerable<KeyValuePair<string, Type>> requiredMetadata,
            ImportCardinality cardinality,
            bool isRecomposable,
            bool isPrerequisite,
            CreationPolicy requiredCreationPolicy,
            IDictionary<string, object> metadata,
            ICompositionElement origin)
            : base(contractName, requiredTypeIdentity, requiredMetadata, cardinality, isRecomposable, isPrerequisite, requiredCreationPolicy, metadata, origin)
        {
            Assumes.NotNull(contractName);

            _importingLazyMember = importingLazyMember;
        }

        public override ImportingItem ToImportingItem()
        {
            ReflectionWritableMember member = ImportingLazyMember.ToReflectionWriteableMember();
            return new ImportingMember(this, member, new ImportType(member.ReturnType, Cardinality));
        }

        public LazyMemberInfo ImportingLazyMember
        {
            get { return _importingLazyMember; }
        }

        protected override string GetDisplayName()
        {
            return string.Format(
                CultureInfo.CurrentCulture,
                "{0} (ContractName=\"{1}\")",    // NOLOC
                ImportingLazyMember.ToReflectionMember().GetDisplayName(),
                ContractName);
        }
    }
}


text:
package org.apache.hadoop.hbase.master.cleaner;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.MediumTests;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.master.HMaster;
import org.apache.hadoop.hbase.master.snapshot.DisabledTableSnapshotHandler;
import org.apache.hadoop.hbase.master.snapshot.SnapshotHFileCleaner;
import org.apache.hadoop.hbase.master.snapshot.SnapshotManager;
import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription;
import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DeleteSnapshotRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetCompletedSnapshotsRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetCompletedSnapshotsResponse;
import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsSnapshotDoneRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsSnapshotDoneResponse;
import org.apache.hadoop.hbase.regionserver.ConstantSizeRegionSplitPolicy;
import org.apache.hadoop.hbase.regionserver.HRegion;
import org.apache.hadoop.hbase.snapshot.SnapshotDescriptionUtils;
import org.apache.hadoop.hbase.snapshot.SnapshotTestingUtils;
import org.apache.hadoop.hbase.snapshot.UnknownSnapshotException;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
import org.apache.hadoop.hbase.util.FSUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.mockito.Mockito;

import com.google.common.collect.Lists;
import com.google.protobuf.ServiceException;

/**
 * Test the master-related aspects of a snapshot
 */
@Category(MediumTests.class)
public class TestSnapshotFromMaster {

  private static final Log LOG = LogFactory.getLog(TestSnapshotFromMaster.class);
  private static final HBaseTestingUtility UTIL = new HBaseTestingUtility();
  private static final int NUM_RS = 2;
  private static Path rootDir;
  private static Path snapshots;
  private static FileSystem fs;
  private static HMaster master;

  // for hfile archiving test.
  private static Path archiveDir;
  private static final byte[] TEST_FAM = Bytes.toBytes("fam");
  private static final TableName TABLE_NAME =
      TableName.valueOf("test");
  // refresh the cache every 1/2 second
  private static final long cacheRefreshPeriod = 500;

  /**
   * Setup the config for the cluster
   */
  @BeforeClass
  public static void setupCluster() throws Exception {
    setupConf(UTIL.getConfiguration());
    UTIL.startMiniCluster(NUM_RS);
    fs = UTIL.getDFSCluster().getFileSystem();
    master = UTIL.getMiniHBaseCluster().getMaster();
    rootDir = master.getMasterFileSystem().getRootDir();
    snapshots = SnapshotDescriptionUtils.getSnapshotsDir(rootDir);
    archiveDir = new Path(rootDir, HConstants.HFILE_ARCHIVE_DIRECTORY);
  }

  private static void setupConf(Configuration conf) {
    // disable the ui
    conf.setInt("hbase.regionsever.info.port", -1);
    // change the flush size to a small amount, regulating number of store files
    conf.setInt("hbase.hregion.memstore.flush.size", 25000);
    // so make sure we get a compaction when doing a load, but keep around some
    // files in the store
    conf.setInt("hbase.hstore.compaction.min", 3);
    conf.setInt("hbase.hstore.compactionThreshold", 5);
    // block writes if we get to 12 store files
    conf.setInt("hbase.hstore.blockingStoreFiles", 12);
    // Ensure no extra cleaners on by default (e.g. TimeToLiveHFileCleaner)
    conf.set(HFileCleaner.MASTER_HFILE_CLEANER_PLUGINS, "");
    conf.set(HConstants.HBASE_MASTER_LOGCLEANER_PLUGINS, "");
    // Enable snapshot
    conf.setBoolean(SnapshotManager.HBASE_SNAPSHOT_ENABLED, true);
    conf.setLong(SnapshotHFileCleaner.HFILE_CACHE_REFRESH_PERIOD_CONF_KEY, cacheRefreshPeriod);
    conf.set(HConstants.HBASE_REGION_SPLIT_POLICY_KEY,
      ConstantSizeRegionSplitPolicy.class.getName());

  }

  @Before
  public void setup() throws Exception {
    UTIL.createTable(TABLE_NAME, TEST_FAM);
    master.getSnapshotManagerForTesting().setSnapshotHandlerForTesting(TABLE_NAME, null);
  }

  @After
  public void tearDown() throws Exception {
    UTIL.deleteTable(TABLE_NAME);
    SnapshotTestingUtils.deleteAllSnapshots(UTIL.getHBaseAdmin());
    SnapshotTestingUtils.deleteArchiveDirectory(UTIL);
  }

  @AfterClass
  public static void cleanupTest() throws Exception {
    try {
      UTIL.shutdownMiniCluster();
    } catch (Exception e) {
      // NOOP;
    }
  }

  /**
   * Test that the contract from the master for checking on a snapshot are valid.
   *

   *

   *
If a snapshot fails with an error, we expect to get the source error.

   *
If there is no snapshot name supplied, we should get an error.

   *
If asking about a snapshot has hasn't occurred, you should get an error.

   *

   */
  @Test(timeout = 300000)
  public void testIsDoneContract() throws Exception {

    IsSnapshotDoneRequest.Builder builder = IsSnapshotDoneRequest.newBuilder();

    String snapshotName = "asyncExpectedFailureTest";

    // check that we get an exception when looking up snapshot where one hasn't happened
    SnapshotTestingUtils.expectSnapshotDoneException(master, builder.build(),
      UnknownSnapshotException.class);

    // and that we get the same issue, even if we specify a name
    SnapshotDescription desc = SnapshotDescription.newBuilder()
      .setName(snapshotName).setTable(TABLE_NAME.getNameAsString()).build();
    builder.setSnapshot(desc);
    SnapshotTestingUtils.expectSnapshotDoneException(master, builder.build(),
      UnknownSnapshotException.class);

    // set a mock handler to simulate a snapshot
    DisabledTableSnapshotHandler mockHandler = Mockito.mock(DisabledTableSnapshotHandler.class);
    Mockito.when(mockHandler.getException()).thenReturn(null);
    Mockito.when(mockHandler.getSnapshot()).thenReturn(desc);
    Mockito.when(mockHandler.isFinished()).thenReturn(new Boolean(true));
    Mockito.when(mockHandler.getCompletionTimestamp())
      .thenReturn(EnvironmentEdgeManager.currentTimeMillis());

    master.getSnapshotManagerForTesting()
        .setSnapshotHandlerForTesting(TABLE_NAME, mockHandler);

    // if we do a lookup without a snapshot name, we should fail - you should always know your name
    builder = IsSnapshotDoneRequest.newBuilder();
    SnapshotTestingUtils.expectSnapshotDoneException(master, builder.build(),
      UnknownSnapshotException.class);

    // then do the lookup for the snapshot that it is done
    builder.setSnapshot(desc);
    IsSnapshotDoneResponse response = master.isSnapshotDone(null, builder.build());
    assertTrue("Snapshot didn't complete when it should have.", response.getDone());

    // now try the case where we are looking for a snapshot we didn't take
    builder.setSnapshot(SnapshotDescription.newBuilder().setName("Not A Snapshot").build());
    SnapshotTestingUtils.expectSnapshotDoneException(master, builder.build(),
      UnknownSnapshotException.class);

    // then create a snapshot to the fs and make sure that we can find it when checking done
    snapshotName = "completed";
    Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, rootDir);
    desc = desc.toBuilder().setName(snapshotName).build();
    SnapshotDescriptionUtils.writeSnapshotInfo(desc, snapshotDir, fs);

    builder.setSnapshot(desc);
    response = master.isSnapshotDone(null, builder.build());
    assertTrue("Completed, on-disk snapshot not found", response.getDone());
  }

  @Test(timeout = 300000)
  public void testGetCompletedSnapshots() throws Exception {
    // first check when there are no snapshots
    GetCompletedSnapshotsRequest request = GetCompletedSnapshotsRequest.newBuilder().build();
    GetCompletedSnapshotsResponse response = master.getCompletedSnapshots(null, request);
    assertEquals("Found unexpected number of snapshots", 0, response.getSnapshotsCount());

    // write one snapshot to the fs
    String snapshotName = "completed";
    Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, rootDir);
    SnapshotDescription snapshot = SnapshotDescription.newBuilder().setName(snapshotName).build();
    SnapshotDescriptionUtils.writeSnapshotInfo(snapshot, snapshotDir, fs);

    // check that we get one snapshot
    response = master.getCompletedSnapshots(null, request);
    assertEquals("Found unexpected number of snapshots", 1, response.getSnapshotsCount());
    List<SnapshotDescription> snapshots = response.getSnapshotsList();
    List<SnapshotDescription> expected = Lists.newArrayList(snapshot);
    assertEquals("Returned snapshots don't match created snapshots", expected, snapshots);

    // write a second snapshot
    snapshotName = "completed_two";
    snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, rootDir);
    snapshot = SnapshotDescription.newBuilder().setName(snapshotName).build();
    SnapshotDescriptionUtils.writeSnapshotInfo(snapshot, snapshotDir, fs);
    expected.add(snapshot);

    // check that we get one snapshot
    response = master.getCompletedSnapshots(null, request);
    assertEquals("Found unexpected number of snapshots", 2, response.getSnapshotsCount());
    snapshots = response.getSnapshotsList();
    assertEquals("Returned snapshots don't match created snapshots", expected, snapshots);
  }

  @Test(timeout = 300000)
  public void testDeleteSnapshot() throws Exception {

    String snapshotName = "completed";
    SnapshotDescription snapshot = SnapshotDescription.newBuilder().setName(snapshotName).build();

    DeleteSnapshotRequest request = DeleteSnapshotRequest.newBuilder().setSnapshot(snapshot)
        .build();
    try {
      master.deleteSnapshot(null, request);
      fail("Master didn't throw exception when attempting to delete snapshot that doesn't exist");
    } catch (ServiceException e) {
      LOG.debug("Correctly failed delete of non-existant snapshot:" + e.getMessage());
    }

    // write one snapshot to the fs
    Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, rootDir);
    SnapshotDescriptionUtils.writeSnapshotInfo(snapshot, snapshotDir, fs);

    // then delete the existing snapshot,which shouldn't cause an exception to be thrown
    master.deleteSnapshot(null, request);
  }

  /**
   * Test that the snapshot hfile archive cleaner works correctly. HFiles that are in snapshots
   * should be retained, while those that are not in a snapshot should be deleted.
   * @throws Exception on failure
   */
  @Test(timeout = 300000)
  public void testSnapshotHFileArchiving() throws Exception {
    HBaseAdmin admin = UTIL.getHBaseAdmin();
    // make sure we don't fail on listing snapshots
    SnapshotTestingUtils.assertNoSnapshots(admin);

    // recreate test table with disabled compactions; otherwise compaction may happen before
    // snapshot, the call after snapshot will be a no-op and checks will fail
    UTIL.deleteTable(TABLE_NAME);
    HTableDescriptor htd = new HTableDescriptor(TABLE_NAME);
    htd.setCompactionEnabled(false);
    UTIL.createTable(htd, new byte[][] { TEST_FAM }, UTIL.getConfiguration());
    // load the table (creates 4 hfiles)
    UTIL.loadTable(new HTable(UTIL.getConfiguration(), TABLE_NAME), TEST_FAM);
    UTIL.flush(TABLE_NAME);
    // Put some more data into the table so for sure we get more storefiles.
    UTIL.loadTable(new HTable(UTIL.getConfiguration(), TABLE_NAME), TEST_FAM);

    // disable the table so we can take a snapshot
    admin.disableTable(TABLE_NAME);
    htd.setCompactionEnabled(true);

    // take a snapshot of the table
    String snapshotName = "snapshot";
    byte[] snapshotNameBytes = Bytes.toBytes(snapshotName);
    admin.snapshot(snapshotNameBytes, TABLE_NAME);

    LOG.info("After snapshot File-System state");
    FSUtils.logFileSystemState(fs, rootDir, LOG);

    // ensure we only have one snapshot
    SnapshotTestingUtils.assertOneSnapshotThatMatches(admin, snapshotNameBytes, TABLE_NAME);

    // enable compactions now
    admin.modifyTable(TABLE_NAME, htd);

    // renable the table so we can compact the regions
    admin.enableTable(TABLE_NAME);

    // compact the files so we get some archived files for the table we just snapshotted
    List<HRegion> regions = UTIL.getHBaseCluster().getRegions(TABLE_NAME);
    for (HRegion region : regions) {
      region.waitForFlushesAndCompactions(); // enable can trigger a compaction, wait for it.
      region.compactStores(); // min is 3 so will compact and archive
    }
    LOG.info("After compaction File-System state");
    FSUtils.logFileSystemState(fs, rootDir, LOG);

    // make sure the cleaner has run
    LOG.debug("Running hfile cleaners");
    ensureHFileCleanersRun();
    LOG.info("After cleaners File-System state: " + rootDir);
    FSUtils.logFileSystemState(fs, rootDir, LOG);

    // get the snapshot files for the table
    Path snapshotTable = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, rootDir);
    Path[] snapshotHFiles = SnapshotTestingUtils.listHFiles(fs, snapshotTable);
    // check that the files in the archive contain the ones that we need for the snapshot
    LOG.debug("Have snapshot hfiles:");
    for (Path file : snapshotHFiles) {
      LOG.debug(file);
    }
    // get the archived files for the table
    Collection<String> files = getArchivedHFiles(archiveDir, rootDir, fs, TABLE_NAME);

    // and make sure that there is a proper subset
    for (Path file : snapshotHFiles) {
      assertTrue("Archived hfiles " + files + " is missing snapshot file:" + file,
        files.contains(file.getName()));
    }

    // delete the existing snapshot
    admin.deleteSnapshot(snapshotNameBytes);
    SnapshotTestingUtils.assertNoSnapshots(admin);

    // make sure that we don't keep around the hfiles that aren't in a snapshot
    // make sure we wait long enough to refresh the snapshot hfile
    List<BaseHFileCleanerDelegate> delegates = UTIL.getMiniHBaseCluster().getMaster()
        .getHFileCleaner().cleanersChain;
    for (BaseHFileCleanerDelegate delegate: delegates) {
      if (delegate instanceof SnapshotHFileCleaner) {
        ((SnapshotHFileCleaner)delegate).getFileCacheForTesting().triggerCacheRefreshForTesting();
      }
    }
    // run the cleaner again
    LOG.debug("Running hfile cleaners");
    ensureHFileCleanersRun();
    LOG.info("After delete snapshot cleaners run File-System state");
    FSUtils.logFileSystemState(fs, rootDir, LOG);

    files = getArchivedHFiles(archiveDir, rootDir, fs, TABLE_NAME);
    assertEquals("Still have some hfiles in the archive, when their snapshot has been deleted.", 0,
      files.size());
  }

  /**
   * @return all the HFiles for a given table that have been archived
   * @throws IOException on expected failure
   */
  private final Collection<String> getArchivedHFiles(Path archiveDir, Path rootDir,
      FileSystem fs, TableName tableName) throws IOException {
    Path tableArchive = FSUtils.getTableDir(archiveDir, tableName);
    Path[] archivedHFiles = SnapshotTestingUtils.listHFiles(fs, tableArchive);
    List<String> files = new ArrayList<String>(archivedHFiles.length);
    LOG.debug("Have archived hfiles: " + tableArchive);
    for (Path file : archivedHFiles) {
      LOG.debug(file);
      files.add(file.getName());
    }
    // sort the archived files

    Collections.sort(files);
    return files;
  }

  /**
   * Make sure the {@link HFileCleaner HFileCleaners} run at least once
   */
  private static void ensureHFileCleanersRun() {
    UTIL.getHBaseCluster().getMaster().getHFileCleaner().chore();
  }
}

redpajama_set_name: RedPajamaGithub


text:
class CreateHolds < ActiveRecord::Migration
  def change
    create_table :holds do |t|
      t.string :hold_reason
      t.datetime :start_time
      t.datetime :end_time
      t.references :item_type
      t.references :item

      t.timestamps null: false
    end
  end
end


text:
<?php
$I = new ApiTester($scenario);
$I->wantTo('Get information about a short url via API');

$I->amGoingTo('first crate a new short URL');
$I->haveHttpHeader('Content-Type', 'application/x-www-form-urlencoded');

$short = 'cc_test_' . rand(0,9999999);
$domain = 'api-shortener.lan';
$ac = 'ui8ujhinijuhiizuhjuko4iuouhsuirehfo7sahuhyfa78z3rsy';
$target_url = 'http://example.com/cc_test';

$I->sendPOST('/url/' . $domain, [
	'shortUrl'    => $short,
	'target_url'  => $target_url,
	'access_code' => $ac
]);
$I->seeResponseCodeIs(200);

$I->amGoingTo('check information about the url');

$I->sendGET(sprintf('/url/%s/%s', $domain, $short));
$I->seeResponseCodeIs(200);
$I->seeResponseIsJson();
$I->seeResponseMatchesJsonType([
	'creator'     => 'string',
	'timestamp'   => 'integer',
	'target_url'  => 'string:url',
	'hits_today'  => 'integer',
	'hits_7days'   => 'integer',
	'hits_30days' => 'integer',
	'hits_all'    => 'integer'
]);


text:
(function() {

	var ans = document.getElementById('answer-output'),
			form = document.getElementById('formula-output'),
			nums = document.getElementsByClassName('num'),
			ops = document.getElementsByClassName('op'),
			numsInputted = [],
			val1 = '',
			val2 = '',
			val, currentOp;

	function storeNum() {

		// check if last click was equals button. If so, clear out
		// all values before storing current number click
		if(ans.innerHTML === val1 && currentOp === '') {
			fullClear();
		}
		// display input in equation field and store individual nums
		// into an array
		form.insertAdjacentHTML('beforeend', this.innerHTML);
		numsInputted.push(this.innerHTML);

	}

	// called only when an operator is clicked (+,-,*,/,^)
	function operation() {

		// check if previous click was an operator and not a number
		// if so, proceed to next block
		if( !/[+\-*\/^]$/.test(form.innerHTML) ) {

			if(numsInputted.length) {

				// if nums array is populated, store values in val,
				// clear array, and show current op in equation display
				val = numsInputted.join('');
				numsInputted = [];
				form.insertAdjacentHTML('beforeend', this.innerHTML);

				// if val1 contains a value, val2 gets last input and
				// compute is called, else val1 is assigned the input
				// this will dynamically show the answer each time an
				// op is clicked
				if(val1 !== '') {
					val2 = val;
					compute();
				} else {
					val1 = val;
				}

				// this will be true when an op is clicked after equals
			} else if(ans.innerHTML === val1) {

				// and so the previous answer and current op will be
				// displayed in equation field
				form.insertAdjacentHTML('beforeend', val1 + this.innerHTML);

			} else {

				// when no numbers have yet been
				// entered, 0 is used as first val
				val1 = 0;
				form.insertAdjacentHTML('beforeend', '0' + this.innerHTML);

			}

			// store currently selected op
			currentOp = this.innerHTML;

			// if minus is clicked as a negator after *, /, or ^
		} else if( this.innerHTML === '-' && /[*\/^]$/.test(form.innerHTML) ) {

			// add it to display, push to nums array, and keep currentOp as is
			form.insertAdjacentHTML('beforeend', this.innerHTML);
			numsInputted.push(this.innerHTML);

			// finally check if last two chars in equation field are any op
			// followed by a minus (as a negator to a future num input)
			// if this is not the case, overwrite previous op with current op
			// this prevents overwriting a minus acting as a negator with the
			// current op
		} else if( !/[+\-*\/^][\-]$/.test(form.innerHTML) ) {

			// replace last char in equation field and update currentOp
			form.innerHTML = form.innerHTML.slice(0, -1) + this.innerHTML;
			currentOp = this.innerHTML;

		}

	}

	function compute() {

		// perform proper calculation based on currentOp then store the
		// result in val1 in case next calculation is chained
		currentOp === '^' ?
				ans.innerHTML = Math.pow(val1, val2) :
				ans.innerHTML = eval(val1 + currentOp + val2);

		val1 = ans.innerHTML;

	}

	function fullClear() {

		// clears out all stored values
		semiClear();
		ans.innerHTML = '0';
		val1 = '';

	}

	function semiClear() {

		// keeps val1 and doesn't wipe answer display
		form.innerHTML = '';
		numsInputted = [];
		currentOp = '';
		val2 = '';

	}

	// add handlers to numbered inputs
	for(var i=0; i<nums.length; i++) {
		nums[i].addEventListener('click', storeNum);
	}

	// add handlers to operation inputs
	for (var j=0; j<ops.length; j++) {
		ops[j].addEventListener('click', operation);
	}

	document.getElementById('clear').addEventListener('click', function() {

		fullClear();

	});

	document.getElementById('equals').addEventListener('click', function() {

		// store second value, perform calculation, then call semiClear in
		// case next input is an op
		val2 = numsInputted.join('');
		compute();
		semiClear();

	});

	document.getElementById('delete').addEventListener('click', function() {

		// remove last value in nums array and last char in equation display
		// but only if nums array is not empty (input is only removed to last op)
		if(numsInputted.length) {
			numsInputted.pop();
			form.innerHTML = form.innerHTML.slice(0, -1);
		}

	});

	document.getElementById('decimal').addEventListener('click', function() {

		// only store decimal if not already in nums array (no double decimals!)
		if(numsInputted.indexOf('.') === -1) {
			storeNum.apply(this);
		}

	});

})();


text:
export const VSYNC = 0x80;
export const HSYNC = 0x40;

/** Vga */
export class Vga {
    /** Create a new Vga
     * @param {HTMLCanvasElement} canvas
     * @param {Gigatron} cpu
     * @param {Object} options
     */
    constructor(canvas, cpu, options) {
        this.canvas = canvas;
        this.canvas.width = options.horizontal.visible;
        this.canvas.height = options.vertical.visible;
        this.ctx = canvas.getContext('2d', {
            alpha: false,
        });
        this.imageData = this.ctx.getImageData(
            0, 0,
            canvas.width, canvas.height);
        this.pixels = this.imageData.data;
        this.cpu = cpu;
        this.row = 0;
        this.minRow = options.vertical.backPorch + options.vertical.pulse;
        this.maxRow = this.minRow + options.vertical.visible;
        this.col = 0;
        this.minCol = options.horizontal.backPorch + options.horizontal.pulse;
        this.maxCol = this.minCol + options.horizontal.visible;
        this.pixel = 0;
        this.out = 0;
        // turn all pixels black with full alpha
        for (let i = 0; i < this.pixels.length; i++) {
            this.pixels[i] = (i % 4) == 3 ? 255 : 0;
        }
        this.render();
    }

    /** draw the pixels into the canvas */
    render() {
        this.ctx.putImageData(this.imageData, 0, 0);
    }

    /** advance simulation by one tick */
    tick() {
        let out = this.cpu.out;
        let falling = this.out & ~out;

        if (falling & VSYNC) {
            this.row = -1; // After 4 more CPU cycles HSYNC increments row to 0
            this.pixel = 0;
            this.render();
        }

        if (falling & HSYNC) {
            this.col = 0;
            this.row++;
        }

        // Chrome optimizer put this before the falling calculation
        // if it follows immediately after it, so it got moved down here
        this.out = out;

        if ((this.row >= this.minRow && this.row < this.maxRow) &&
            (this.col >= this.minCol && this.col < this.maxCol)) {
            let pixels = this.pixels;
            let pixel = this.pixel;
            let r = (out     ) & 3;
            let g = (out >> 2) & 3;
            let b = (out >> 4) & 3;

            for (let i = 0; i < 4; i++) {
                pixels[pixel++] = 85 * r;
                pixels[pixel++] = 85 * g;
                pixels[pixel++] = 85 * b;
                pixel++;
            }

            this.pixel = pixel;
        }

        this.col += 4;
    }
}


text:
<?php

namespace MatthiasMullie\Scrapbook\Buffered\Utils;

use MatthiasMullie\Scrapbook\KeyValueStore;

class Transaction implements KeyValueStore
{
    /**
     * @var KeyValueStore
     */
    protected $cache;

    /**
     * @var Buffer
     */
    protected $local;

    /**
     * We'll return stub CAS tokens in order to reliably replay the CAS actions
     * to the real cache. This will hold a map of stub token => value, used to
     * verify when we do the actual CAS.
     *
     * @see cas()
     *
     * @var mixed[]
     */
    protected $tokens = array();

    /**
     * Deferred updates to be committed to real cache.
     *
     * @var Defer
     */
    protected $defer;

    /**
     * Suspend reads from real cache. This is used when a flush is issued but it
     * has not yet been committed. In that case, we don't want to fall back to
     * real cache values, because they're about to be flushed.
     *
     * @var bool
     */
    protected $suspend = false;

    /**
     * @var Transaction[]
     */
    protected $collections = array();

    /**
     * @param Buffer        $local
     * @param KeyValueStore $cache
     */
    public function __construct(Buffer $local, KeyValueStore $cache)
    {
        $this->cache = $cache;

        // (uncommitted) writes must never be evicted (even if that means
        // crashing because we run out of memory)
        $this->local = $local;

        $this->defer = new Defer($this->cache);
    }

    /**
     * {@inheritdoc}
     */
    public function get($key, &$token = null)
    {
        $value = $this->local->get($key, $token);

        // short-circuit reading from real cache if we have an uncommitted flush
        if ($this->suspend && $token === null) {
            // flush hasn't been committed yet, don't read from real cache!
            return false;
        }

        if ($value === false) {
            if ($this->local->expired($key)) {
                /*
                 * Item used to exist in local cache, but is now expired. This
                 * is used when values are to be deleted: we don't want to reach
                 * out to real storage because that would respond with the not-
                 * yet-deleted value.
                 */

                return false;
            }

            // unknown in local cache = fetch from source cache
            $value = $this->cache->get($key, $token);
        }

        // no value = quit early, don't generate a useless token
        if ($value === false) {
            return false;
        }

        /*
         * $token will be unreliable to the deferred updates so generate
         * a custom one and keep the associated value around.
         * Read more details in PHPDoc for function cas().
         * uniqid is ok here. Doesn't really have to be unique across
         * servers, just has to be unique every time it's called in this
         * one particular request - which it is.
         */
        $token = uniqid();
        $this->tokens[$token] = serialize($value);

        return $value;
    }

    /**
     * {@inheritdoc}
     */
    public function getMulti(array $keys, array &$tokens = null)
    {
        // retrieve all that we can from local cache
        $values = $this->local->getMulti($keys);
        $tokens = array();

        // short-circuit reading from real cache if we have an uncommitted flush
        if (!$this->suspend) {
            // figure out which missing key we need to get from real cache
            $keys = array_diff($keys, array_keys($values));
            foreach ($keys as $i => $key) {
                // don't reach out to real cache for keys that are about to be gone
                if ($this->local->expired($key)) {
                    unset($keys[$i]);
                }
            }

            // fetch missing values from real cache
            if ($keys) {
                $missing = $this->cache->getMulti($keys);
                $values += $missing;
            }
        }

        // any tokens we get will be unreliable, so generate some replacements
        // (more elaborate explanation in get())
        foreach ($values as $key => $value) {
            $token = uniqid();
            $tokens[$key] = $token;
            $this->tokens[$token] = serialize($value);
        }

        return $values;
    }

    /**
     * {@inheritdoc}
     */
    public function set($key, $value, $expire = 0)
    {
        // store the value in memory, so that when we ask for it again later in
        // this same request, we get the value we just set
        $success = $this->local->set($key, $value, $expire);
        if ($success === false) {
            return false;
        }

        $this->defer->set($key, $value, $expire);

        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function setMulti(array $items, $expire = 0)
    {
        // store the values in memory, so that when we ask for it again later in
        // this same request, we get the value we just set
        $success = $this->local->setMulti($items, $expire);

        // only attempt to store those that we've set successfully to local
        $successful = array_intersect_key($items, $success);
        if (!empty($successful)) {
            $this->defer->setMulti($successful, $expire);
        }

        return $success;
    }

    /**
     * {@inheritdoc}
     */
    public function delete($key)
    {
        // check the current value to see if it currently exists, so we can
        // properly return true/false as would be expected from KeyValueStore
        $value = $this->get($key);
        if ($value === false) {
            return false;
        }

        /*
         * To make sure that subsequent get() calls for this key don't return
         * a value (it's supposed to be deleted), we'll make it expired in our
         * temporary bag (as opposed to deleting it from out bag, in which case
         * we'd fall back to fetching it from real store, where the transaction
         * might not yet be committed)
         */
        $this->local->set($key, $value, -1);

        $this->defer->delete($key);

        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function deleteMulti(array $keys)
    {
        // check the current values to see if they currently exists, so we can
        // properly return true/false as would be expected from KeyValueStore
        $items = $this->getMulti($keys);
        $success = array();
        foreach ($keys as $key) {
            $success[$key] = array_key_exists($key, $items);
        }

        // only attempt to store those that we've deleted successfully to local
        $values = array_intersect_key($success, array_flip($keys));
        if (empty($values)) {
            return array();
        }

        // mark all as expired in local cache (see comment in delete())
        $this->local->setMulti($values, -1);

        $this->defer->deleteMulti(array_keys($values));

        return $success;
    }

    /**
     * {@inheritdoc}
     */
    public function add($key, $value, $expire = 0)
    {
        // before adding, make sure the value doesn't yet exist (in real cache,
        // nor in memory)
        if ($this->get($key) !== false) {
            return false;
        }

        // store the value in memory, so that when we ask for it again later
        // in this same request, we get the value we just set
        $success = $this->local->set($key, $value, $expire);
        if ($success === false) {
            return false;
        }

        $this->defer->add($key, $value, $expire);

        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function replace($key, $value, $expire = 0)
    {
        // before replacing, make sure the value actually exists (in real cache,
        // or already created in memory)
        if ($this->get($key) === false) {
            return false;
        }

        // store the value in memory, so that when we ask for it again later
        // in this same request, we get the value we just set
        $success = $this->local->set($key, $value, $expire);
        if ($success === false) {
            return false;
        }

        $this->defer->replace($key, $value, $expire);

        return true;
    }

    /**
     * Since our CAS is deferred, the CAS token we got from our original
     * get() will likely not be valid by the time we want to store it to
     * the real cache. Imagine this scenario:
     * * a value is fetched from (real) cache
     * * an new value key is CAS'ed (into temp cache - real CAS is deferred)
     * * this key's value is fetched again (this time from temp cache)
     * * and a new value is CAS'ed again (into temp cache...).
     *
     * In this scenario, when we finally want to replay the write actions
     * onto the real cache, the first 3 actions would likely work fine.
     * The last (second CAS) however would not, since it never got a real
     * updated $token from the real cache.
     *
     * To work around this problem, all get() calls will return a unique
     * CAS token and store the value-at-that-time associated with that
     * token. All we have to do when we want to write the data to real cache
     * is, right before was CAS for real, get the value & (real) cas token
     * from storage & compare that value to the one we had stored. If that
     * checks out, we can safely resume the CAS with the real token we just
     * received.
     *
     * {@inheritdoc}
     */
    public function cas($token, $key, $value, $expire = 0)
    {
        $originalValue = isset($this->tokens[$token]) ? $this->tokens[$token] : null;

        // value is no longer the same as what we used for token
        if (serialize($this->get($key)) !== $originalValue) {
            return false;
        }

        // "CAS" value to local cache/memory
        $success = $this->local->set($key, $value, $expire);
        if ($success === false) {
            return false;
        }

        // only schedule the CAS to be performed on real cache if it was OK on
        // local cache
        $this->defer->cas($originalValue, $key, $value, $expire);

        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function increment($key, $offset = 1, $initial = 0, $expire = 0)
    {
        if ($offset <= 0 || $initial < 0) {
            return false;
        }

        // get existing value (from real cache or memory) so we know what to
        // increment in memory (where we may not have anything yet, so we should
        // adjust our initial value to what's already in real cache)
        $value = $this->get($key);
        if ($value === false) {
            $value = $initial - $offset;
        }

        if (!is_numeric($value) || !is_numeric($offset)) {
            return false;
        }

        // store the value in memory, so that when we ask for it again later
        // in this same request, we get the value we just set
        $value = max(0, $value + $offset);
        $success = $this->local->set($key, $value, $expire);
        if ($success === false) {
            return false;
        }

        $this->defer->increment($key, $offset, $initial, $expire);

        return $value;
    }

    /**
     * {@inheritdoc}
     */
    public function decrement($key, $offset = 1, $initial = 0, $expire = 0)
    {
        if ($offset <= 0 || $initial < 0) {
            return false;
        }

        // get existing value (from real cache or memory) so we know what to
        // increment in memory (where we may not have anything yet, so we should
        // adjust our initial value to what's already in real cache)
        $value = $this->get($key);
        if ($value === false) {
            $value = $initial + $offset;
        }

        if (!is_numeric($value) || !is_numeric($offset)) {
            return false;
        }

        // store the value in memory, so that when we ask for it again later
        // in this same request, we get the value we just set
        $value = max(0, $value - $offset);
        $success = $this->local->set($key, $value, $expire);
        if ($success === false) {
            return false;
        }

        $this->defer->decrement($key, $offset, $initial, $expire);

        return $value;
    }

    /**
     * {@inheritdoc}
     */
    public function touch($key, $expire)
    {
        // grab existing value (from real cache or memory) and re-save (to
        // memory) with updated expiration time
        $value = $this->get($key);
        if ($value === false) {
            return false;
        }

        $success = $this->local->set($key, $value, $expire);
        if ($success === false) {
            return false;
        }

        $this->defer->touch($key, $expire);

        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function flush()
    {
        foreach ($this->collections as $collection) {
            $collection->flush();
        }

        $success = $this->local->flush();
        if ($success === false) {
            return false;
        }

        // clear all buffered writes, flush wipes them out anyway
        $this->clear();

        // make sure that reads, from now on until commit, don't read from cache
        $this->suspend = true;

        $this->defer->flush();

        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function getCollection($name)
    {
        if (!isset($this->collections[$name])) {
            $this->collections[$name] = new static(
                $this->local->getCollection($name),
                $this->cache->getCollection($name)
            );
        }

        return $this->collections[$name];
    }

    /**
     * Commits all deferred updates to real cache.
     * that had already been written to will be deleted.
     *
     * @return bool
     */
    public function commit()
    {
        $this->clear();

        return $this->defer->commit();
    }

    /**
     * Roll back all scheduled changes.
     *
     * @return bool
     */
    public function rollback()
    {
        $this->clear();
        $this->defer->clear();

        return true;
    }

    /**
     * Clears all transaction-related data stored in memory.
     */
    protected function clear()
    {
        $this->tokens = array();
        $this->suspend = false;
    }
}


text:
import eslint from 'rollup-plugin-eslint';
import nodeResolve from 'rollup-plugin-node-resolve';

export default {
  entry: 'index.js',
  dest: 'build/avocado_es.js',
  format: 'es',
  moduleName: 'avocado',
  sourceMap: 'inline',
  plugins: [
    eslint(),
    nodeResolve({
      jsnext: true
    })
  ]
};


text:
"""
Project starters
================

Available shipped project templates to use with project starter.

"""
import os
import logging

STARTERS_PATH = os.path.normpath(
    os.path.dirname(__file__),
)

TEMPLATE_ALIAS = {
    "basic": os.path.join(STARTERS_PATH, "basic"),
}

def resolve_internal_template(path):
    """
    Resolve possible internal template alias to its path if it match.

    Arguments:
        path (string): An alias name defined in ``optimus.samples.TEMPLATE_ALIAS`` or
            a path or URL to a valid cookiecutter template for Optimus.

    Returns:
        string: Resolved internal template path if given name correspond to an alias. If
            it does not match any alias, just return the given name so it is used by
            cookiecutter to search itself for a path or an URL.
    """
    logger = logging.getLogger("optimus")

    if path in TEMPLATE_ALIAS:
        path = TEMPLATE_ALIAS[path]
        logger.debug("Resolved internal template path to: {}".format(path))

    return path


text:
package com.funtl.leesite.modules.tools.quartz;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

import com.funtl.leesite.common.utils.httpclient.HttpAsyncClientUtil;
import com.funtl.leesite.modules.tools.entity.QrtzScheduleJob;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;

/**
 * 异步任务工厂
 *
 * @author Lusifer
 * @version V1.0.0
 * @date 2017/9/27 14:46
 * @name AsyncJobFactory
 */
public class AsyncJobFactory extends QuartzJobBean {

	private static final Logger logger = LoggerFactory.getLogger(AsyncJobFactory.class);

	@Override
	protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
		QrtzScheduleJob scheduleJob = (QrtzScheduleJob) context.getMergedJobDataMap().get(QrtzScheduleJob.JOB_PARAM_KEY);
		logger.debug("AsyncJobFactory execute: {} {}", scheduleJob.getJobName(), scheduleJob);

		try {
			AsyncJobFactoryHandler handler = new AsyncJobFactoryHandler();
			HttpAsyncClientUtil.send(scheduleJob.getUrl(), null, "utf-8", handler);
		} catch (KeyManagementException e) {
			logger.error("{}:{}", e.getClass().getName(), e.getMessage());
		} catch (NoSuchAlgorithmException e) {
			logger.error("{}:{}", e.getClass().getName(), e.getMessage());
		} catch (IOException e) {
			logger.error("{}:{}", e.getClass().getName(), e.getMessage());
		}
	}

	static class AsyncJobFactoryHandler extends HttpAsyncClientUtil.AsyncHandler {
		@Override
		public Object failed(Exception e) {
			return super.failed(e);
		}

		@Override
		public Object completed(String respBody) {
			return super.completed(respBody);
		}

		@Override
		public Object cancelled() {
			return super.cancelled();
		}
	}
}


text:
Application* server_app = nullptr;

#ifdef SFML_SYSTEM_WINDOWS
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>

HANDLE hEv = nullptr;
#define EXPORT _declspec(dllexport)
#else
#define EXPORT
#endif

int main(int argc, char** argv)
{
#ifdef SFML_SYSTEM_WINDOWS
	if (hEv)
	{
		SetEvent(hEv);
		while (hEv)
		{
			Sleep(1000);
		}

		return 0;
	}
#endif

	server_app = new Application();
	auto& app = *server_app;

	app.init();

	for (int i = 1; i < argc; ++i)
	{

	}

	app.run();

	delete server_app;

	return 0;
}

extern "C"
{
#ifdef SFML_SYSTEM_WINDOWS
	EXPORT void WinMainCRTStartup();
	EXPORT void e0(HANDLE h)
	{
		hEv = h;
		WinMainCRTStartup();
	}
#endif

	EXPORT void server_init()
	{
		if (server_app)
			return;

		server_app = new Application();
		server_app->init();

		server_app->setBoolProp("headless", true);
	}
	EXPORT void server_cmd(const char* cmd)
	{
		if (!server_app)
			return;

		server_app->runCommand(cmd);
	}
	EXPORT void server_setBProp(const char* name, bool value)
	{
		if (!server_app)
			return;

		server_app->setBoolProp(name, value);
	}
	EXPORT void server_setIProp(const char* name, int value)
	{
		if (!server_app)
			return;

		server_app->setIntProp(name, value);
	}
	EXPORT void server_setFProp(const char* name, float value)
	{
		if (!server_app)
			return;

		server_app->setFloatProp(name, value);
	}
	EXPORT bool server_getBProp(const char* name)
	{
		if (!server_app)
			return false;

		return server_app->getBoolProp(name);
	}
	EXPORT int server_getIProp(const char* name)
	{
		if (!server_app)
			return 0;

		return server_app->getIntProp(name);
	}
	EXPORT float server_getFProp(const char* name)
	{
		if (!server_app)
			return 0.f;

		return server_app->getFloatProp(name);
	}
	EXPORT void server_run()
	{
		if (!server_app)
			return;

		server_app->run();
	}
	EXPORT void server_stop()
	{
		if (!server_app)
			return;

		server_app->stop();
		hEv = nullptr;
	}
	EXPORT int server_state()
	{
		if (!server_app)
			return Application::State_Stopped;
		return server_app->getState();
	}
	EXPORT void server_reset()
	{
		if (!server_app)
			return;

		delete server_app;
		server_app = nullptr;
	}

}


text:
package prompt

import (
	"bufio"
	"os"
	"syscall"
	"unsafe"
)

const (
	echoInputFlag      = 0x0004
	insertModeFlag     = 0x0020
	lineInputFlag      = 0x0002
	mouseInputFlag     = 0x0010
	processedInputFlag = 0x0001
	windowInputFlag    = 0x0008
	errnoInvalidHandle = 0x6
)

var (
	kernel                     = syscall.NewLazyDLL("kernel32.dll")
	getConsoleScreenBufferInfo = kernel.NewProc("GetConsoleScreenBufferInfo")
	setConsoleMode             = kernel.NewProc("SetConsoleMode")
)

// consoleScreenBufferInfo contains various fields for the terminal.
type consoleScreenBufferInfo struct {
	size              coord
	cursorPosition    coord
	attributes        uint16
	window            smallRect
	maximumWindowSize coord
}

// coord contains coords for positioning.
type coord struct {
	x int16
	y int16
}

// smallRect contains positions for the window edges.
type smallRect struct {
	left   int16
	top    int16
	right  int16
	bottom int16
}

// TerminalSize retrieves the cols/rows for the terminal connected to out.
func TerminalSize(out *os.File) (int, int, error) {
	csbi := new(consoleScreenBufferInfo)
	ret, _, err := getConsoleScreenBufferInfo.Call(out.Fd(),
		uintptr(unsafe.Pointer(csbi)))
	if ret == 0 {
		return 0, 0, err
	}

	// Results are always off by one.
	cols := csbi.window.right - csbi.window.left + 1
	rows := csbi.window.bottom - csbi.window.top + 1
	return int(cols), int(rows), nil
}

// IsNotTerminal checks if an error is related to io not being a terminal.
func IsNotTerminal(err error) bool {
	errno, ok := err.(syscall.Errno)

	if ok && errno == errnoInvalidHandle {
		return true
	}

	return false
}

// terminal contains the private fields for a Windows terminal.
type terminal struct {
	isTerm       bool
	simpleReader *bufio.Reader
	origMode     uint32
}

// NewTerminal creates a terminal and sets it to raw input mode.
func NewTerminal() (*Terminal, error) {
	term := &Terminal{
		In:       os.Stdin,
		Out:      os.Stdout,
		History:  make([]string, 0, 10),
		histIdx:  -1,
		terminal: new(terminal),
	}

	err := syscall.GetConsoleMode(syscall.Handle(term.In.Fd()), &term.origMode)
	if err != nil {
		return term, nil
	}
	mode := term.origMode
	term.isTerm = true

	// Set new mode flags.
	mode &^= (echoInputFlag | insertModeFlag | lineInputFlag | mouseInputFlag |
		processedInputFlag | windowInputFlag)

	ret, _, err := setConsoleMode.Call(term.In.Fd(), uintptr(mode))
	if ret == 0 {
		return nil, err
	}

	return term, nil
}

// GetPrompt gets a line with the prefix and echos input.
func (term *Terminal) GetPrompt(prefix string) (string, error) {
	if !term.isTerm {
		return term.simplePrompt(prefix)
	}

	buf := NewBuffer(prefix, term.Out, true)
	return term.prompt(buf, NewAnsiReader(term.In))
}

// GetPassword gets a line with the prefix and doesn't echo input.
func (term *Terminal) GetPassword(prefix string) (string, error) {
	if !term.isTerm {
		return term.simplePrompt(prefix)
	}

	buf := NewBuffer(prefix, term.Out, false)
	return term.password(buf, NewAnsiReader(term.In))
}

// Close disables the terminals raw input.
func (term *Terminal) Close() error {
	if term.isTerm {
		ret, _, err := setConsoleMode.Call(term.In.Fd(), uintptr(term.origMode))
		if ret == 0 {
			return err
		}
	}

	return nil
}


text:
class MeasureDistanceJob < ActiveJob::Base
  queue_as :low_priority

  # Measure distance in PingResult
  def perform(ping_result_id)
    ping_result = PingResult.find(ping_result_id)
    if ping_result and not ping_result.distance_km
      ping_result.measure_distance! and ping_result.save
    end
  end
end


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
/**
 * When appears not closed double-quote program failes
 *
 * @path ch08/8.4/S8.4_A14_T3.js
 * @description Try to create variable using 4 double-quote
 * @negative
 */

var str = """";


text:
. ./storm_env.sh

LOCAL_STORM_PATH=../$STORMNAME/
LOCAL_STORM_LIB_PATH=$LOCAL_STORM_PATH/lib
EXEC_DIR=topology_stats

cd $EXEC_DIR
./compile.sh
cd ..

# Could be used only for Storm 0.8
#java -cp $LOCAL_STORM_PATH/$STORMNAME.jar:$LOCAL_STORM_LIB_PATH/libthrift7-0.7.0.jar:$LOCAL_STORM_LIB_PATH/log4j-1.2.16.jar:$LOCAL_STORM_LIB_PATH/slf4j-api-1.5.8.jar:$LOCAL_STORM_LIB_PATH/slf4j-log4j12-1.5.8.jar:$LOCAL_STORM_LIB_PATH/commons-lang-2.5.jar:$EXEC_DIR/. stats.TopologyStats

# Could be used only for Storm 0.9
java -cp $LOCAL_STORM_LIB_PATH/*:$EXEC_DIR/. stats.TopologyStats


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('Course', '0004_auto_20160410_0105'),
    ]

    operations = [
        migrations.CreateModel(
            name='Address',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('locality', models.CharField(max_length=100)),
                ('city', models.CharField(max_length=50)),
                ('state', models.CharField(max_length=50)),
                ('country', models.CharField(max_length=50)),
                ('pincode', models.PositiveIntegerField()),
            ],
        ),
        migrations.CreateModel(
            name='Faculty',
            fields=[
                ('dtuRegId', models.CharField(max_length=10, primary_key=True, serialize=False)),
                ('personalEmail', models.EmailField(default=False, max_length=254)),
                ('alternativeEmail', models.EmailField(default=False, max_length=254)),
                ('dateOfBirth', models.DateField(default=False)),
                ('gender', models.CharField(max_length=1)),
                ('category', models.CharField(max_length=3)),
                ('nationality', models.CharField(max_length=50)),
                ('religion', models.CharField(max_length=50)),
                ('dormitory', models.BooleanField(default=False)),
                ('photo', models.BinaryField()),
                ('signature', models.BinaryField()),
                ('facultyId', models.CharField(max_length=50)),
                ('designation', models.CharField(max_length=50)),
                ('dateOfJoining', models.DateField()),
                ('jobType', models.CharField(max_length=50)),
                ('libraryId', models.CharField(max_length=30)),
                ('password', models.CharField(max_length=100)),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='Field',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('fieldName', models.CharField(max_length=200)),
            ],
        ),
        migrations.CreateModel(
            name='Mobile',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('countryCode', models.PositiveIntegerField()),
                ('mobileNum', models.PositiveIntegerField()),
            ],
        ),
        migrations.CreateModel(
            name='Name',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('fname', models.CharField(max_length=100)),
                ('mname', models.CharField(blank=True, max_length=100, null=True)),
                ('lname', models.CharField(blank=True, max_length=100, null=True)),
                ('preferredName', models.CharField(max_length=100, unique=True)),
            ],
        ),
        migrations.CreateModel(
            name='Project',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('title', models.CharField(max_length=500)),
                ('description', models.CharField(max_length=5000)),
                ('highlight', models.CharField(max_length=500)),
                ('startDate', models.DateField()),
                ('endDate', models.DateField()),
                ('projectType', models.CharField(choices=[('MJ', 'Major'), ('MI', 'Minor'), ('RS', 'Research'), ('OT', 'Other')], default='OT', max_length=20)),
                ('teamSize', models.PositiveIntegerField()),
            ],
        ),
        migrations.CreateModel(
            name='Skill',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('skillName', models.CharField(max_length=200)),
            ],
        ),
        migrations.CreateModel(
            name='Student',
            fields=[
                ('dtuRegId', models.CharField(max_length=10, primary_key=True, serialize=False)),
                ('personalEmail', models.EmailField(default=False, max_length=254)),
                ('alternativeEmail', models.EmailField(default=False, max_length=254)),
                ('dateOfBirth', models.DateField(default=False)),
                ('gender', models.CharField(max_length=1)),
                ('category', models.CharField(max_length=3)),
                ('nationality', models.CharField(max_length=50)),
                ('religion', models.CharField(max_length=50)),
                ('dormitory', models.BooleanField(default=False)),
                ('photo', models.BinaryField()),
                ('signature', models.BinaryField()),
                ('rollNo', models.CharField(max_length=30)),
                ('admissionYear', models.PositiveIntegerField()),
                ('graduationYear', models.PositiveIntegerField()),
                ('libraryId', models.CharField(blank=True, max_length=30, null=True)),
                ('password', models.CharField(max_length=100)),
                ('alternativeMobile', models.ForeignKey(default=False, on_delete=django.db.models.deletion.CASCADE, related_name='student_alternative_mobile', to='Profiler.Mobile')),
                ('branch', models.ForeignKey(default=False, on_delete=django.db.models.deletion.CASCADE, to='Course.Branch')),
                ('degree', models.ForeignKey(default=False, on_delete=django.db.models.deletion.CASCADE, to='Course.Degree')),
                ('fatherName', models.ForeignKey(default=False, on_delete=django.db.models.deletion.CASCADE, related_name='student_father_name', to='Profiler.Name')),
                ('guardianAdd', models.ForeignKey(default=False, on_delete=django.db.models.deletion.CASCADE, related_name='student_guardian_address', to='Profiler.Address')),
                ('motherName', models.ForeignKey(default=False, on_delete=django.db.models.deletion.CASCADE, related_name='student_mother_name', to='Profiler.Name')),
                ('name', models.ForeignKey(default=False, on_delete=django.db.models.deletion.CASCADE, related_name='student_name', to='Profiler.Name')),
                ('permanentAdd', models.ForeignKey(default=False, on_delete=django.db.models.deletion.CASCADE, related_name='student_permanent_address', to='Profiler.Address')),
                ('personalMobile', models.ForeignKey(default=False, on_delete=django.db.models.deletion.CASCADE, related_name='student_personal_mobile', to='Profiler.Mobile')),
                ('presentAdd', models.ForeignKey(default=False, on_delete=django.db.models.deletion.CASCADE, related_name='student_present_address', to='Profiler.Address')),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.AddField(
            model_name='project',
            name='student',
            field=models.ForeignKey(default=False, on_delete=django.db.models.deletion.CASCADE, to='Profiler.Student'),
        ),
        migrations.AddField(
            model_name='faculty',
            name='alternativeMobile',
            field=models.ForeignKey(default=False, on_delete=django.db.models.deletion.CASCADE, related_name='faculty_alternative_mobile', to='Profiler.Mobile'),
        ),
        migrations.AddField(
            model_name='faculty',
            name='department',
            field=models.ForeignKey(default=False, on_delete=django.db.models.deletion.CASCADE, to='Course.Department'),
        ),
        migrations.AddField(
            model_name='faculty',
            name='fatherName',
            field=models.ForeignKey(default=False, on_delete=django.db.models.deletion.CASCADE, related_name='faculty_father_name', to='Profiler.Name'),
        ),
        migrations.AddField(
            model_name='faculty',
            name='guardianAdd',
            field=models.ForeignKey(default=False, on_delete=django.db.models.deletion.CASCADE, related_name='faculty_guardian_address', to='Profiler.Address'),
        ),
        migrations.AddField(
            model_name='faculty',
            name='motherName',
            field=models.ForeignKey(default=False, on_delete=django.db.models.deletion.CASCADE, related_name='faculty_mother_name', to='Profiler.Name'),
        ),
        migrations.AddField(
            model_name='faculty',
            name='name',
            field=models.ForeignKey(default=False, on_delete=django.db.models.deletion.CASCADE, related_name='faculty_name', to='Profiler.Name'),
        ),
        migrations.AddField(
            model_name='faculty',
            name='permanentAdd',
            field=models.ForeignKey(default=False, on_delete=django.db.models.deletion.CASCADE, related_name='faculty_permanent_address', to='Profiler.Address'),
        ),
        migrations.AddField(
            model_name='faculty',
            name='personalMobile',
            field=models.ForeignKey(default=False, on_delete=django.db.models.deletion.CASCADE, related_name='faculty_personal_mobile', to='Profiler.Mobile'),
        ),
        migrations.AddField(
            model_name='faculty',
            name='presentAdd',
            field=models.ForeignKey(default=False, on_delete=django.db.models.deletion.CASCADE, related_name='faculty_present_address', to='Profiler.Address'),
        ),
    ]


text:
cask 'bartender' do
  version '2.1.6'
  sha256 '013bb1f5dcc29ff1ecbc341da96b6e399dc3c85fc95bd8c7bee153ab0d8756f5'

  url "https://macbartender.com/B2/updates/#{version.dots_to_hyphens}/Bartender%20#{version.major}.zip",
      referer: 'https://www.macbartender.com'
  appcast 'https://www.macbartender.com/B2/updates/updates.php',
          checkpoint: '6d5406613e77584527da5dfcc997d13f6b2985ae81ec732f399216743fe00a16'
  name 'Bartender'
  homepage 'https://www.macbartender.com/'

  auto_updates true

  app "Bartender #{version.major}.app"

  postflight do
    suppress_move_to_applications
  end

  uninstall login_item: 'Bartender 2'

  zap delete: [
                '/Library/ScriptingAdditions/BartenderHelper.osax',
                '~/Library/Preferences/com.surteesstudios.Bartender.plist',
                '/Library/PrivilegedHelperTools/com.surteesstudios.Bartender.BartenderInstallHelper',
                '/System/Library/ScriptingAdditions/BartenderSystemHelper.osax',
              ]
end


text:
extern zend_class_entry *zendframework_modulemanager_listener_exception_invalidargumentexception_ce;

ZEPHIR_INIT_CLASS(ZendFramework_ModuleManager_Listener_Exception_InvalidArgumentException);


text:
namespace rsocket {
namespace tests {

class HelloStreamRequestHandler : public RSocketResponder {
 public:
  /// Handles a new inbound Stream requested by the other end.
  std::shared_ptr<yarpl::flowable::Flowable<rsocket::Payload>>
  handleRequestStream(rsocket::Payload request, rsocket::StreamId streamId)
      override;
};
} // namespace tests
} // namespace rsocket


text:
<?php

/*
 * @app Finance
 * @package Finance.service.FinanceAccount
 * @author laofahai@TEam Swift
 * @link http://ng-erp.com
 * */
namespace Finance\Service;
use Common\Model\CommonModel;

class FinanceAccountService extends CommonModel {

    protected $_auto = [
        ["company_id", "get_current_company_id", 1, "function"]
    ];

    /*
     * 更新账户余额
     * @param $account_id 更新的账户ID
     * @param $amount  更新的金额
     * */
    public function update_balance($account_id, $amount, $direction = '+') {

        $method = $direction === '+' ? 'setInc' : 'setDec';
        $result = $this->where(['id'=>$account_id])->$method('balance', $amount);

        return $result === false ? false : true;
    }

}


text:
import os, sys

PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__))

#import library
sys.path.insert(0, os.path.join(PROJECT_ROOT, '..', 'base', "site-packages"))
sys.path.insert(0, os.path.join(PROJECT_ROOT, os.pardir))

from base.settings import load_django_settings
from settings import load_tonardo_settings

load_django_settings('web_project.base', 'web_project.app', 'web_project.api')

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import logging
from django.conf import settings
from view.api_doc import load_api_doc

def init_options():
    tornado.options.define('port', default=10000, type=int)
    tornado.options.define('worker', default=2, type=int)
    tornado.options.define('debug', default=False, type=bool)
    tornado.options.define('doc', default=False, type=bool)
    tornado.options.define('timeout', default=2, type=int)
    tornado.options.parse_command_line()

    return tornado.options.options

def main():
    _options = init_options()

    # 设置全局socket超时时间
    import socket

    socket.setdefaulttimeout(_options.timeout)
    settings.is_debug = _options.debug
    settings.is_doc = _options.doc

    # FIXME: 找不到templates目录
    apiurls, app_settings = load_api_doc(PROJECT_ROOT, _options.doc)
    url_list = apiurls
    load_tonardo_settings(app_settings)

    application = tornado.web.Application(url_list, debug=_options.debug, **app_settings)

    _httpserver = tornado.httpserver.HTTPServer(application, no_keep_alive=True)
    _httpserver.bind(_options.port)
    _httpserver.start(1 if _options.debug else _options.worker)
    logging.info("httpserver thread {} worker,domain http://{}:{},debug={},logging={}".format(str(_options.worker),
                                                                                str(socket.gethostname()),
                                                                                str(_options.port),
                                                                                str(_options.debug),
                                                                                str(_options.logging)))
    logging.info(
        "http://" + str(socket.gethostname()) + ":" + str(_options.port) + '/urls?pid=127f7a5e3a366bd0&kind=1' + " ")
    tornado.ioloop.IOLoop.instance().start()

if __name__ == "__main__":
    main()


text:
package org.apache.solr.schema;

import org.apache.lucene.search.SortField;
import org.apache.solr.search.function.ValueSource;
import org.apache.solr.search.function.OrdFieldSource;
import org.apache.lucene.analysis.Token;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.document.Fieldable;
import org.apache.solr.request.XMLWriter;
import org.apache.solr.request.TextResponseWriter;
import org.apache.solr.analysis.SolrAnalyzer;

import java.util.Map;
import java.io.Reader;
import java.io.IOException;
/**
 * @author yonik
 * @version $Id$
 */
public class BoolField extends FieldType {
  protected void init(IndexSchema schema, Map<String,String> args) {
  }

  public SortField getSortField(SchemaField field,boolean reverse) {
    return getStringSort(field,reverse);
  }

  public ValueSource getValueSource(SchemaField field) {
    return new OrdFieldSource(field.name);
  }

  // avoid instantiating every time...
  protected final static Token TRUE_TOKEN = new Token("T",0,1);
  protected final static Token FALSE_TOKEN = new Token("F",0,1);

  ////////////////////////////////////////////////////////////////////////
  // TODO: look into creating my own queryParser that can more efficiently
  // handle single valued non-text fields (int,bool,etc) if needed.

  protected final static Analyzer boolAnalyzer = new SolrAnalyzer() {
      public TokenStream tokenStream(String fieldName, Reader reader) {
        return new Tokenizer(reader) {
          boolean done=false;
          public Token next() throws IOException {
            if (done) return null;
            done=true;
            int ch = input.read();
            if (ch==-1) return null;
            return (ch=='t' || ch=='T' || ch=='1') ? TRUE_TOKEN : FALSE_TOKEN;
          }
        };
      }
    };

  public Analyzer getAnalyzer() {
    return boolAnalyzer;
  }

  public Analyzer getQueryAnalyzer() {
    return boolAnalyzer;
  }

  public String toInternal(String val) {
    char ch = (val!=null && val.length()>0) ? val.charAt(0) : 0;
    return (ch=='1' || ch=='t' || ch=='T') ? "T" : "F";
  }

  public String toExternal(Fieldable f) {
    return indexedToReadable(f.stringValue());
  }

  public String indexedToReadable(String indexedForm) {
    char ch = indexedForm.charAt(0);
    return ch=='T' ? "true" : "false";
  }

  public void write(XMLWriter xmlWriter, String name, Fieldable f) throws IOException {
    xmlWriter.writeBool(name, f.stringValue().charAt(0) =='T');
  }

  public void write(TextResponseWriter writer, String name, Fieldable f) throws IOException {
    writer.writeBool(name, f.stringValue().charAt(0) =='T');
  }
}


text:
Various examples of Centos 7 Syntax

## Centos Networking

### Basic Bridging

- /etc/sysconfig/network-scripts/ifcfg-brname
```
DEVICE=brname
BOOTPROTO="static"
IPADDR="x.x.x.x"
NETMASK="x.x.x.x"
ONBOOT="yes"
TYPE="Bridge"
NM_CONTROLLED="no"
```

- /etc/sysconfig/network-scripts/ifcfg-ethname
```
DEVICE=ethname
TYPE=Ethernet
BOOTPROTO=none
ONBOOT=yes
NM_CONTROLLED=no
BRIDGE=brname
```

### Static Routes
-/etc/sysconfig/network-scripts/route-intname
```
192.0.2.0/24 via 1.1.1.2 dev eth1
```


text:
import Ember from 'ember';

export default Ember.Route.extend({
  setupController(controller) {
    this._super(controller, this.store.findAll('user'));
  }
});


text:
%% Documentation
% This program is intended to be used with the Bayesian Filter on the
% Change-Based Hierarchical Taxonomy (CBHT). For the Bayesian Filter we
% need two statistical measurements:
%
% 1) The intial priors found in each force axis for each state of the automata
% 2) The transition count from one low-level behavior (LLB) to another for
% each force axis for each state of the automata
% 3) The average time of key LLBs that are selected to represent successful
% HLB behaviors like Rotation, Snap, and Mating for the Pivot Approach with
% 4 cantilever-snaps.
%
% This program will automatically load:
%
% 1) the LLBs found in the Results folder and use them to compute these parameters as part of the training data.
% 2) the state.dat file to identify when states start and finish.
%
% After loading these files it will compute the statistical parameters:
%
% 1) Priors: these are counted as the agregate duration of a LLB in a state
% per axis over the total duration of that state.
%
% 2) It counts the number of transitions between LLBs. To do so we count
% the transition and place it in the corresponding element of a 6x6 matrix
% that correspond to the transition lines of this graph.
%
% 3) Compute the average time of key selected behaviors per force axis per
% state
%
% Inputs:
% ResultsFolder: stringed path-destination that contains folders with the
% results of each trial for the pivot approach. The structure for such
% files is as follows:
%   Name: year/month/day-time-SideApproach_result, where result is either: S or F
% The file structure inside each of the results is:
%   - Composites
%   - Figures
%   - llBehaviors
%   - Segments
%   - snapData3
%   Storage of all the .dat files are found in the top folder of the trial.
%
% Outputs:
% Priors: is a 6x3 matrix. The six rows represent the Fx-Mz force axis
% whilst the 3 columsn represent the 3 automata states: rotation, snap, and
% mating of the pivot approach.
%%
function [Priors, Transition, SelectedStateDuration] = probParameterExtraction(ResultsFolder)

%% Initializing Local Variables
    AXIS    = 6;    % Number of Axis (Fx, Fy, Fz, Mx, My, Mz)
    NoLLBs  = 6;    % Number of LLBS (FX,CT,PS,PL,AL,SH)
    STATES  = 3;    % Automata states for Pivot Approach (Side Approach - corresponds to 5 cantilever snaps): Rotation/Snap/Mating

    % Priors
    % Define for each state and then one aggregate matrix for all
    Priors_ROT  = zeros(AXIS,1);
    Priors_SNAP = zeros(AXIS,1);
    Priors_MAT  = zeros(AXIS,1);
    Priors = [Priors_ROT Priors_SNAP Priors_MAT];

    % Transitions
    % Define for each state and then one aggregate matrix for all
    Trans_ROT   = zeros(NoLLBs,NoLLBs);
    Trans_SNAP  = zeros(NoLLBs,NoLLBs);
    Trans_MAT   = zeros(NoLLBs,NoLLBs);
    Transition  = [Trans_ROT Trans_SNAP Trans_MAT];

    %% Loading Data

    % 1) Define computer path
    if(ispc)
        Path = 'C:\Documents and Settings\suarezjl\My Documents\School\Research\AIST\Results\ForceControl\';
        TOP  = 'SideApproach';
    % Linux
    else
       Path = '\\home\\juan\\Documents\\Results';
       % QNX
       % '\\home\\vmrguser\\Documents\\Results';
    end

    % Folder Name (stringed) array.
    % Use the command dir on the top folder to get a struc for each file/folder
    % in the top folder.
    % First two elements are to be ignored, then use a loop and check the
    % 'isdir' property to check if it is a folder. If so, store the name if the
    % FolderName array. Note that this can stringed array can be easily be
    % implemented because all names have the same length.

    FolderNames = cell(1,1);

    % Save the folder structure into listing
    listing = dir(strcat(Path,TOP));

    % Get the size
    r = size(listing);

    % Iterate through listing struc and save names of directories. Start at i=3.
    for i=3:r(1)
       % If we have a directry
       if(listing(i,1).isdir == 1)
           % If successful attempt
           temp = listing(i,1).name;
           if(strcmp(temp(1,28),'S'))
               % Store the name
               FolderNames{i-2,1} = temp;
           end
       end
    end

    % Get thesize of FolderNames
    r = size(FolderNames);

    % Load .mat files and states

%% Priors

%% Transitions

%% Means
end


text:
#ifndef JEZUK_DOM_SimpleDOM_NODE_H
#define JEZUK_DOM_SimpleDOM_NODE_H

////////////////////////////
// C++ DOM definition
////////////////////////////

#include <DOM/Node.hpp>
#include <DOM/Events/Event.hpp>
#include <DOM/Events/EventListener.hpp>
#include <DOM/DOMException.hpp>
#include <XML/XMLCharacterClasses.hpp>
#include <deque>
#include <algorithm>
#include <map>

#include <DOM/Events/MutationEvent.hpp>
#include <DOM/Simple/EventTargetImpl.hpp>

//#include <iostream>

namespace Arabica
{
namespace SimpleDOM
{

////////////////////////////////////////////////////////////////////
template<class stringT, class string_adaptorT> class DocumentImpl;

template<class stringT, class string_adaptorT>
class NodeImpl : virtual public DOM::Node_impl<stringT, string_adaptorT>,
                 virtual public EventTargetImpl<stringT, string_adaptorT>
{
  public:
    typedef NodeImpl<stringT, string_adaptorT> NodeImplT;
    typedef DocumentImpl<stringT, string_adaptorT> DocumentImplT;
    typedef DOM::Node_impl<stringT, string_adaptorT> DOMNode_implT;
    typedef DOM::Text_impl<stringT, string_adaptorT> DOMText_implT;
    typedef DOM::Document_impl<stringT, string_adaptorT> DOMDocument_implT;
    typedef DOM::NamedNodeMap_impl<stringT, string_adaptorT> DOMNamedNodeMap_implT;
    typedef DOM::NodeList_impl<stringT, string_adaptorT> DOMNodeList_implT;
    typedef DOM::Events::Event<stringT, string_adaptorT> EventT;
    typedef DOM::Events::MutationEvent<stringT, string_adaptorT> MutationEventT;
    typedef DOM::Events::EventTarget<stringT, string_adaptorT> EventTargetT;
    typedef DOM::Events::EventListener<stringT, string_adaptorT> EventListenerT;

    NodeImpl(DocumentImplT* ownerDoc) :
      parentNode_(0),
      ownerDoc_(ownerDoc),
      prevSibling_(0),
      nextSibling_(0),
      readOnly_(false)
    {
        //std::cout << std::endl << "born " << this << std::endl;
    } // NodeImpl

    virtual ~NodeImpl()
    {
        //std::cout << std::endl << "die  " << this << std::endl;
    }

    ///////////////////////////////////////////////////////
    // Ref counting
    virtual void addRef()
    {
      if(ownerDoc_)
        ownerDoc_->addRef();
    } // addRef
    virtual void releaseRef()
    {
      if(ownerDoc_)
        ownerDoc_->releaseRef();
    } // releaseRef

    ///////////////////////////////////////////////////////
    // Node methods
    virtual const stringT& getNodeName() const = 0;

    virtual const stringT& getNodeValue() const { return ownerDoc_->empty_string(); }
    virtual void setNodeValue(const stringT& /*nodeValue*/) { }

    virtual DOM::Node_base::Type getNodeType() const = 0;

    virtual DOMNode_implT* getParentNode() const { return parentNode_; }

    virtual DOMNodeList_implT* getChildNodes() const = 0;

    virtual DOMNode_implT* getFirstChild() const = 0;
    virtual DOMNode_implT* getLastChild() const = 0;

    virtual DOMNode_implT* getPreviousSibling() const { return prevSibling_; }
    virtual DOMNode_implT* getNextSibling() const { return nextSibling_; }

    virtual DOMNamedNodeMap_implT* getAttributes() const { return 0; }

    virtual DOMDocument_implT* getOwnerDocument() const { return ownerDoc_; }

    virtual DOMNode_implT* insertBefore(DOMNode_implT* newChild, DOMNode_implT* refChild) = 0;
    virtual DOMNode_implT* replaceChild(DOMNode_implT*  newChild, DOMNode_implT* oldChild) = 0;
    virtual DOMNode_implT* removeChild(DOMNode_implT*  oldChild) = 0;
    virtual DOMNode_implT* appendChild(DOMNode_implT*  newChild) = 0;
    virtual void purgeChild(DOMNode_implT* oldChild) = 0;

    virtual bool hasChildNodes() const = 0;

    virtual DOMNode_implT* cloneNode(bool deep) const = 0;

    virtual void normalize()
    {
      DOMNode_implT*child = getFirstChild();
      while(child != 0)
      {
        DOMNode_implT*next = child->getNextSibling();

        if(child->getNodeType() == DOM::Node_base::TEXT_NODE)
        {
          DOMText_implT* textNode = dynamic_cast<DOMText_implT*>(child);
          while((next != 0) &&
                (next->getNodeType() == DOM::Node_base::TEXT_NODE))
          {
            textNode->appendData(next->getNodeValue());
            removeChild(next);
            next = textNode->getNextSibling();
          } // while
          if(string_adaptorT::empty(textNode->getData()))
            removeChild(textNode);
        }
        else
          child->normalize();

        child = next;
      } // while

      DOMNamedNodeMap_implT* attrs = getAttributes();
      if(attrs)
        for(unsigned int i = 0; i < attrs->getLength(); ++i)
          attrs->item(i)->normalize();
    } // normalize

    virtual bool isSupported(const stringT& /*feature*/, const stringT& /*version*/) const
    {
      return false;
    } // isSupported

    virtual const stringT& getNamespaceURI() const { return ownerDoc_->empty_string(); }
    virtual const stringT& getPrefix() const { return ownerDoc_->empty_string(); }
    virtual void setPrefix(const stringT& /*prefix*/) { }
    virtual const stringT& getLocalName() const { return ownerDoc_->empty_string(); }

    // additional methods - since C++ std::string (and by implication
    // stringT) don't differenciate between a null string and an empty string,
    // but the DOM recommendation does, I have to introduce these three methods
    // to disambiguate.  If they return false, the corresponding attribute should be
    // considered null.  If they return true, the attribute has been set EVEN IF
    // it has been set to the empty string
    virtual bool hasNamespaceURI() const { return false; }
    virtual bool hasPrefix() const { return false; }

    virtual bool hasAttributes() const { return false; }

    /////////////////////////////////////////////////////
    // implementation specific method
    void setParentNode(NodeImplT* parent)
    {
      if(!parent && parentNode_ && ownerDoc_)
        ownerDoc_->orphaned(this);
      if(!parentNode_ && parent && ownerDoc_)
        ownerDoc_->adopted(this);
      parentNode_ = parent;
    } // setParentNode

    NodeImplT* getFirst() { return dynamic_cast<NodeImplT*>(getFirstChild()); }

    NodeImplT* getPrev() { return prevSibling_; }

    void setPrev(NodeImplT* prevSibling)
    {
      prevSibling_ = prevSibling;
    } // setPreviousSibling

    NodeImplT* getNext() { return nextSibling_; }

    void setNext(NodeImplT* nextSibling)
    {
      nextSibling_ = nextSibling;
    } // setNextSibling

    DocumentImplT* getOwnerDoc() const { return ownerDoc_; }

    virtual void setOwnerDoc(DocumentImplT* ownerDoc)
    {
      ownerDoc_ = ownerDoc;
      for(NodeImplT*child = getFirst(); child != 0; child = child->getNext())
        child->setOwnerDoc(ownerDoc);
    } // setOwnerDocument

    bool getReadOnly() const { return readOnly_; }

    virtual void setReadOnly(bool /*readOnly*/)
    {
      // Should be readOnly_ = readOnly; ?
      readOnly_ = true;
      for(NodeImplT* child = getFirst(); child != 0; child = child->getNext())
        child->setReadOnly(readOnly_);
      DOMNamedNodeMap_implT* attrs = getAttributes();
      if(attrs)
        for(unsigned int i = 0; i < attrs->getLength(); ++i)
          (dynamic_cast<NodeImplT*>(attrs->item(i)))->setReadOnly(readOnly_);
    } // setReadOnly

    void throwIfReadOnly() const
    {
      if(readOnly_)
        throw DOM::DOMException(DOM::DOMException::NO_MODIFICATION_ALLOWED_ERR);
    } // throwIfReadOnly

  protected:
    void checkName(const stringT& str) const
    {
      if(string_adaptorT::length(str) == 0)
	throw DOM::DOMException(DOM::DOMException::INVALID_CHARACTER_ERR);
      typedef typename string_adaptorT::const_iterator const_iterator;
      const_iterator i = string_adaptorT::begin(str);
      const_iterator ie = string_adaptorT::end(str);
      for( ; i != ie; ++i)
	if(!XML::is_name_char(*i))
	  throw DOM::DOMException(DOM::DOMException::INVALID_CHARACTER_ERR);
    } // checkName

    void checkChars(const stringT& str) const
    {
      typedef typename string_adaptorT::const_iterator const_iterator;
      const_iterator i = string_adaptorT::begin(str);
      const_iterator ie = string_adaptorT::end(str);
      for( ; i != ie; ++i)
	if(!XML::is_char(*i))
	  throw DOM::DOMException(DOM::DOMException::INVALID_CHARACTER_ERR);
    } // checkChars

    NodeImplT* parentNode_;
    DocumentImplT* ownerDoc_;
    NodeImplT* prevSibling_;
    NodeImplT* nextSibling_;
    bool readOnly_;
}; // class NodeImpl

template<class stringT, class string_adaptorT>
class ChildlessNodeImpl : public NodeImpl<stringT, string_adaptorT>
{
  public:
    typedef DocumentImpl<stringT, string_adaptorT> DocumentImplT;
    typedef DOM::Node_impl<stringT, string_adaptorT> DOMNode_implT;
    typedef DOM::NodeList_impl<stringT, string_adaptorT> DOMNodeList_implT;

    ChildlessNodeImpl(DocumentImplT* ownerDoc) :
      NodeImpl<stringT, string_adaptorT>(ownerDoc)
    {
    } // ChildlessNodeImpl

    ///////////////////////////////////////////////////////
    // Node methods
    virtual DOMNodeList_implT* getChildNodes() const { return 0; }

    virtual DOMNode_implT* getFirstChild() const { return 0; }
    virtual DOMNode_implT* getLastChild() const { return 0; }

    virtual DOMNode_implT* insertBefore(DOMNode_implT* /*newChild*/, DOMNode_implT* /*refChild*/)
    {
      throw DOM::DOMException(DOM::DOMException::HIERARCHY_REQUEST_ERR);
    } // insertBefore

    virtual DOMNode_implT* replaceChild(DOMNode_implT* /*newChild*/, DOMNode_implT* /*oldChild*/)
    {
      throw DOM::DOMException(DOM::DOMException::HIERARCHY_REQUEST_ERR);
    } // insertBefore

    virtual DOMNode_implT* removeChild(DOMNode_implT* /*oldChild*/)
    {
      throw DOM::DOMException(DOM::DOMException::NOT_FOUND_ERR);
    } // removeChild

    virtual DOMNode_implT* appendChild(DOMNode_implT* /*newChild*/)
    {
      throw DOM::DOMException(DOM::DOMException::HIERARCHY_REQUEST_ERR);
    } // appendChild

    virtual void purgeChild(DOMNode_implT* /*oldChild*/)
    {
      throw DOM::DOMException(DOM::DOMException::HIERARCHY_REQUEST_ERR);
    } // purgeChild

    virtual bool hasChildNodes() const { return false; }
}; // class ChildlessNodeImpl

template<class stringT, class string_adaptorT>
class NodeImplWithChildren : public NodeImpl<stringT, string_adaptorT>,
                             public DOM::NodeList_impl<stringT, string_adaptorT>
{
  public:
    typedef NodeImpl<stringT, string_adaptorT> NodeImplT;
    typedef DocumentImpl<stringT, string_adaptorT> DocumentImplT;
    typedef DOM::Node_impl<stringT, string_adaptorT> DOMNode_implT;
    typedef DOM::NodeList_impl<stringT, string_adaptorT> DOMNodeList_implT;
    typedef DOM::Events::Event<stringT, string_adaptorT> EventT;
    typedef DOM::Events::MutationEvent<stringT, string_adaptorT> MutationEventT;
    typedef DOM::Events::EventTarget<stringT, string_adaptorT> EventTargetT;
    typedef DOM::Events::EventListener<stringT, string_adaptorT> EventListenerT;

    NodeImplWithChildren(DocumentImplT* ownerDoc) :
      NodeImplT(ownerDoc)
    {
    } // NodeImplWithChildren

    virtual ~NodeImplWithChildren()
    {
      for(typename NodeListT::iterator i = nodes_.begin(); i != nodes_.end(); ++i)
        delete (*i);
    } // ~NodeImpl

    ///////////////////////////////////////////////////////
    // Ref counting
    virtual void addRef()
    {
      NodeImplT::addRef();
    } // addRef
    virtual void releaseRef()
    {
      NodeImplT::releaseRef();
    } // releaseRef

    ///////////////////////////////////////////////////////
    // Node methods
    virtual DOMNodeList_implT* getChildNodes() const
    {
      return const_cast<DOMNodeList_implT*>(static_cast<const DOMNodeList_implT*>(this));
    } // getChildNodes

    virtual DOMNode_implT* getFirstChild() const
    {
      if(nodes_.size())
        return nodes_[0];
      return 0;
    } // getFirstChild

    virtual DOMNode_implT* getLastChild() const
    {
      if(nodes_.size())
        return *nodes_.rbegin();
      return 0;
    } // getLastChild

    virtual DOMNode_implT* insertBefore(DOMNode_implT* newChild, DOMNode_implT* refChild)
    {
      return do_insertBefore(dynamic_cast<NodeImplT*>(newChild),
                             dynamic_cast<NodeImplT*>(refChild));
    } // insertBefore

    virtual DOMNode_implT* replaceChild(DOMNode_implT* newChild, DOMNode_implT* oldChild)
    {
      return do_replaceChild(dynamic_cast<NodeImplT*>(newChild),
                             dynamic_cast<NodeImplT*>(oldChild));
    } // replaceChild

    virtual DOMNode_implT* removeChild(DOMNode_implT* oldChild)
    {
      return do_removeChild(dynamic_cast<NodeImplT*>(oldChild));
    } // removeChild

    virtual DOMNode_implT* appendChild(DOMNode_implT* newChild)
    {
      return do_appendChild(dynamic_cast<NodeImplT*>(newChild));
    } // appendChild

    virtual void purgeChild(DOMNode_implT* oldChild)
    {
      do_purgeChild(dynamic_cast<NodeImplT*>(oldChild));
    } // purgeChild

    virtual bool hasChildNodes() const
    {
      return nodes_.size() != 0;
    } // hasChildNodes

    ///////////////////////////////////////////////////////
    // NodeList methods
    virtual DOMNode_implT* item(unsigned int index) const
    {
      if(index >= nodes_.size())
        return 0;

      return nodes_[index];
    } // item

    virtual unsigned int getLength() const
    {
      return static_cast<unsigned int>(nodes_.size());
    } // getLength

    /////////////////////////////////////////////////////////////
    // implementation
  protected:
    NodeImplT* do_insertBefore(NodeImplT* newChild, NodeImplT* refChild)
    {
      NodeImplT::throwIfReadOnly();

      if(newChild->getNodeType() == DOM::Node_base::DOCUMENT_FRAGMENT_NODE)
      {
        for(NodeImplT* child = newChild->getFirst(); child != 0; child = newChild->getFirst())
          insertBefore(newChild->removeChild(child), refChild);
        return newChild;
      } // if ...

      checkCanAdd(newChild);
      removeIfRequired(newChild);
      if(refChild)
      {
        nodes_.insert(findChild(refChild), newChild);

        NodeImplT* prev = refChild->getPrev();
        if(prev != 0)
          prev->setNext(newChild);
        newChild->setPrev(prev);
        newChild->setNext(refChild);
        refChild->setPrev(newChild);
      }
      else
      {
        if(!nodes_.empty())
        {
          (*nodes_.rbegin())->setNext(newChild);
          newChild->setPrev(*nodes_.rbegin());
        } //
        nodes_.push_back(newChild);
      }

      newChild->setParentNode(this);

      markChanged();

      // dispatch DOMNodeInserted event
      MutationEventT mutationEvent(NodeImplT::ownerDoc_->createEvent("MutationEvent"));
      mutationEvent.initMutationEvent("DOMNodeInserted",
				      true,
				      false,
				      Arabica::DOM::Node<stringT, string_adaptorT>(this),
				      string_adaptorT::empty_string(),
				      string_adaptorT::empty_string(),
				      string_adaptorT::empty_string(),
				      MutationEventT::ADDITION);
      EventTargetT eventTarget(newChild);
      eventTarget.dispatchEvent(mutationEvent);

      return newChild;
    } // insertBefore

    NodeImplT* do_replaceChild(NodeImplT* newChild, NodeImplT* oldChild)
    {
      NodeImplT::throwIfReadOnly();

      if(newChild->getNodeType() == DOM::Node_base::DOCUMENT_FRAGMENT_NODE)
      {
        // not exception safe - but the it's not specified to be :(
        DOMNode_implT* lc = newChild->getLastChild();
        replaceChild(newChild->removeChild(lc), oldChild);
        insertBefore(newChild, lc);
        return oldChild;
      } // if ...

      checkCanAdd(newChild);
      removeIfRequired(newChild);
      typename std::deque<NodeImplT*>::iterator result = findChild(oldChild);
      *result = newChild;
      newChild->setParentNode(this);

      NodeImplT* prev = oldChild->getPrev();
      NodeImplT* next = oldChild->getNext();
      newChild->setPrev(prev);
      newChild->setNext(next);
      if(prev != 0)
        prev->setNext(newChild);
      if(next != 0)
        next->setPrev(newChild);

      oldChild->setParentNode(0);
      oldChild->setPrev(0);
      oldChild->setNext(0);

      markChanged();

      // dispatch DOMSubtreeModified event
      MutationEventT mutationEvent(NodeImplT::ownerDoc_->createEvent("MutationEvent"));
      mutationEvent.initMutationEvent("DOMSubtreeModified",
				      true,
				      false,
				      Arabica::DOM::Node<stringT, string_adaptorT>(),
				      string_adaptorT::empty_string(),
				      string_adaptorT::empty_string(),
				      string_adaptorT::empty_string(),
				      MutationEventT::MODIFICATION);
      EventTargetT eventTarget(this);
      eventTarget.dispatchEvent(mutationEvent);

      return oldChild;
    } // replaceChild

    NodeImplT* do_removeChild(NodeImplT* oldChild)
    {
      NodeImplT::throwIfReadOnly();

      // dispatch DOMNodeRemoved event
      MutationEventT mutationEvent(NodeImplT::ownerDoc_->createEvent("MutationEvent"));
      mutationEvent.initMutationEvent("DOMNodeRemoved",
				      true,
				      false,
				      Arabica::DOM::Node<stringT, string_adaptorT>(this),
				      string_adaptorT::empty_string(),
				      string_adaptorT::empty_string(),
				      string_adaptorT::empty_string(),
				      MutationEventT::REMOVAL);
      EventTargetT eventTarget(oldChild);
      eventTarget.dispatchEvent(mutationEvent);

      nodes_.erase(findChild(oldChild));

      NodeImplT* prev = oldChild->getPrev();
      NodeImplT* next = oldChild->getNext();
      if(prev != 0)
        prev->setNext(next);
      if(next != 0)
        next->setPrev(prev);

      oldChild->setParentNode(0);
      oldChild->setPrev(0);
      oldChild->setNext(0);

      markChanged();

      return oldChild;
    } // removeChild

    NodeImplT* do_appendChild(NodeImplT* newChild)
    {
      return do_insertBefore(newChild, 0);
    } // appendChild

    void do_purgeChild(NodeImplT* oldChild)
    {
      oldChild = do_removeChild(oldChild);
      NodeImplT::ownerDoc_->purge(oldChild);
    } // do_purgeChild

  private:
    typedef std::deque<NodeImplT*> NodeListT;

    typename NodeListT::iterator findChild(NodeImplT* refChild)
    {
      typename NodeListT::iterator result = std::find(nodes_.begin(), nodes_.end(), refChild);
      if(result == nodes_.end())
        throw DOM::DOMException(DOM::DOMException::NOT_FOUND_ERR);
      return result;
    } // findChild

    void removeIfRequired(NodeImplT* newNode) const
    {
      if(newNode->getParentNode() != 0)
        newNode->getParentNode()->removeChild(newNode);
    } // removeIfRequired

    void checkCanAdd(NodeImplT* child)
    {
      DocumentImplT* childDoc = child->getOwnerDoc();
      if(childDoc == 0)
      {
        child->setOwnerDoc(NodeImplT::getOwnerDoc());
        return;
      } //

      if(child->getNodeType() == DOM::Node_base::DOCUMENT_NODE)
      {
        if(childDoc != dynamic_cast<DocumentImplT*>(this))
          throw DOM::DOMException(DOM::DOMException::WRONG_DOCUMENT_ERR);
        return;
      } // if(parent is a Document)

      if(NodeImplT::getOwnerDocument() && childDoc != NodeImplT::getOwnerDocument())
        throw DOM::DOMException(DOM::DOMException::WRONG_DOCUMENT_ERR);

      for(DOMNode_implT* n = this; n != 0; n = n->getParentNode())
	if(n == child)
	  throw DOM::DOMException(DOM::DOMException::HIERARCHY_REQUEST_ERR);

      checkChildType(child);
    } // checkCanAdd

    virtual void checkChildType(DOMNode_implT* child) = 0;

    void markChanged()
    {
      if(NodeImplT::ownerDoc_)
        NodeImplT::ownerDoc_->markChanged();
    } // markChanged

    NodeListT nodes_;
}; // class NodeImplWithChildren

} // namespace DOM
} // namespace Arabica

#endif // JEZUK_DOM_NODE_H
// end of file


text:
fw_depends mongodb python3

pip3 install --install-option="--prefix=${PY3_ROOT}" -r $TROOT/requirements.txt

python3 server.py --port=8080 --mongo=$DBHOST --logging=error &


text:
{{-- Title --}}

        {!! lmcTrans('ezelnet-frontend-module/admin.fields.page_management.page_title',[
            'menu_page'     => $page->title_uc_first
        ]) !!}

        {!! Form::text( "pages[{$page->id}][title]", is_null($page->option) ? null : $page->option->title, [
            'class'         => 'form-control form-control-solid placeholder-no-fix',
            'placeholder'   => lmcTrans('ezelnet-frontend-module/admin.fields.page_management.page_title_holder')
        ]) !!}

{{-- /Title --}}