text:
package org.apache.hadoop.hbase.filter;

import com.google.protobuf.InvalidProtocolBufferException;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.hbase.exceptions.DeserializationException;
import org.apache.hadoop.hbase.protobuf.generated.ComparatorProtos;
import org.apache.hadoop.hbase.util.Bytes;

/**
 * A binary comparator which lexicographically compares against the specified
 * byte array using {@link org.apache.hadoop.hbase.util.Bytes#compareTo(byte[], byte[])}.
 */
@InterfaceAudience.Public
@InterfaceStability.Stable
public class BinaryComparator extends ByteArrayComparable {

  /**
   * Constructor
   * @param value value
   */
  public BinaryComparator(byte[] value) {
    super(value);
  }

  @Override
  public int compareTo(byte [] value, int offset, int length) {
    return Bytes.compareTo(this.value, 0, this.value.length, value, offset, length);
  }

  /**
   * @return The comparator serialized using pb
   */
  public byte [] toByteArray() {
    ComparatorProtos.BinaryComparator.Builder builder =
      ComparatorProtos.BinaryComparator.newBuilder();
    builder.setComparable(super.convert());
    return builder.build().toByteArray();
  }

  /**
   * @param pbBytes A pb serialized {@link BinaryComparator} instance
   * @return An instance of {@link BinaryComparator} made from bytes
   * @throws DeserializationException
   * @see #toByteArray
   */
  public static BinaryComparator parseFrom(final byte [] pbBytes)
  throws DeserializationException {
    ComparatorProtos.BinaryComparator proto;
    try {
      proto = ComparatorProtos.BinaryComparator.parseFrom(pbBytes);
    } catch (InvalidProtocolBufferException e) {
      throw new DeserializationException(e);
    }
    return new BinaryComparator(proto.getComparable().getValue().toByteArray());
  }

  /**
   * @param other
   * @return true if and only if the fields of the comparator that are serialized
   * are equal to the corresponding fields in other.  Used for testing.
   */
  boolean areSerializedFieldsEqual(ByteArrayComparable other) {
    if (other == this) return true;
    if (!(other instanceof BinaryComparator)) return false;

    return super.areSerializedFieldsEqual(other);
  }
}

redpajama_set_name: RedPajamaGithub


text:
aging = {

	submitForm: function(e){

		var thebutton = e.src();
		var theform = getObjectFromID("record");

		var command = getObjectFromID("command");

		if(thebutton.id == "runButton"){

			if(!validateForm(theform))
				return false;

			command.value = "run";

		} else
			command.value = "cancel";

		theform.submit();

		return true;

	}//end method

}//end class

/* OnLoad Listner ---------------------------------------- */
/* ------------------------------------------------------- */

connect(window,"onload",function() {

	var runButton = getObjectFromID("runButton");
	if(runButton)
		connect(runButton, "onclick", aging.submitForm);

	var cancelButton = getObjectFromID("cancelButton");
	if(cancelButton)
		connect(cancelButton, "onclick", aging.submitForm);

	var printStatements = getObjectFromID("printClientStatements");
	if(printStatements){

		var theURL;
		var printSummary = getObjectFromID("printSummary");
		var agingdate = getObjectFromID("agingdate")

		var ts = new Date();
		ts = ts.getTime();

                var tid = "tbld:c595dbe7-6c77-1e02-5e81-c2e215736e9c";
                var clientStatementUUID = "rpt:0df82ecf-5f05-56bd-18c3-e7cb27c0cf8a";
                var summaryUUID = "rpt:e25bdb7a-93be-b1d6-a292-cdec89c0c9fc";

		if(printStatements.value == 1){

			theURL = APP_PATH + "modules/bms/report/aritems_clientstatement.php?cmd=print";
                        theURL += "&sd=" + encodeURIComponent(agingdate.value);
                        theURL += "&tid=" + encodeURIComponent(tid);
                        theURL += "&rid=" + encodeURIComponent(clientStatementUUID);
                        theURL += "&ts=" + encodeURIComponent(ts);
                        theURL += "&ext=.pdf";
			window.open(theURL, 'phpBMSprint1');

		}//endif

		if(printSummary.value == 1){

			theURL = APP_PATH+"modules/bms/report/aritems_summary.php?cmd=print"
                        theURL += "&sd=" + encodeURIComponent(agingdate.value);
                        theURL += "&tid=" + encodeURIComponent(tid);
                        theURL += "&rid=" + encodeURIComponent(summaryUUID);
                        theURL += "&ts=" + encodeURIComponent(ts);
			window.open(theURL, 'phpBMSprint2');

		}//endif

	}//end if

})


text:
package org.neo4j.cypher.docgen

import org.junit.Assert._
import org.junit.Test
import org.neo4j.graphdb.Node
import org.neo4j.visualization.graphviz.{AsciiDocSimpleStyle, GraphStyle}

class OrderByTest extends DocumentingTestBase with SoftReset {
  override def graphDescription = List("A KNOWS B", "B KNOWS C")

  override protected def getGraphvizStyle: GraphStyle =
    AsciiDocSimpleStyle.withAutomaticRelationshipTypeColors()

  override val properties = Map(
    "A" -> Map("age" -> 34, "length"->170),
    "B" -> Map("age" -> 34),
    "C" -> Map("age" -> 32, "length"->185))

  def section = "Order by"

  @Test def sortByName() {
    testQuery(
      title = "Order nodes by property",
      text = "+ORDER BY+ is used to sort the output.",
      queryText = """match (n) return n order by n.name""",
      optionalResultExplanation = """The nodes are returned, sorted by their name.""",
      assertions = (p) => assertEquals(List(node("A"), node("B"), node("C")), p.columnAs[Node]("n").toList))
  }

  @Test def sortByNameReverse() {
    testQuery(
      title = "Order nodes in descending order",
      text = "By adding +DESC[ENDING]+ after the identifier to sort on, the sort will be done in reverse order.",
      queryText = """match (n) return n order by n.name DESC""",
      optionalResultExplanation = """The example returns the nodes, sorted by their name reversely.""",
      assertions = (p) => assertEquals(List(node("C"), node("B"), node("A")), p.columnAs[Node]("n").toList))
  }

  @Test def sortByMultipleColumns() {
    testQuery(
      title = "Order nodes by multiple properties",
      text = "You can order by multiple properties by stating each identifier in the +ORDER BY+" +
        " clause. Cypher will sort the result by the first identifier listed, and for equals values, " +
        "go to the next property in the `ORDER BY` clause, and so on.",
      queryText = """match (n) return n order by n.age, n.name""",
      optionalResultExplanation = """This returns the nodes, sorted first by their age, and then by their name.""",
      assertions = (p) => assertEquals(List(node("C"), node("A"), node("B")), p.columnAs[Node]("n").toList))
  }

  @Test def order_by_nullable_property() {
    testQuery(
      title = "Ordering NULL",
      text = "When sorting the result set, +NULL+ will always come at the end of the result set for" +
        " ascending sorting, and first when doing descending sort.",
      queryText = """match (n) return n.length, n order by n.length""",
      optionalResultExplanation = """The nodes are returned sorted by the length property, with a node without that property last.""",
      assertions = (p) => assertEquals(List(node("A"), node("C"), node("B")), p.columnAs[Node]("n").toList))
  }
}


text:
@interface MDDrawingCache : NSObject
-(void) bindTotalWidth:(int)w totalHeight:(int)h;
-(void) unbind;
-(GLuint) getTextureOutput;
@end


text:
import { TypeScriptVueExtensionConfiguration } from './TypeScriptVueExtensionConfiguration';
declare function assertTypeScriptVueExtensionSupport(configuration: TypeScriptVueExtensionConfiguration): void;
export { assertTypeScriptVueExtensionSupport };


text:
using System.Linq;
using LogFlow.Specifications.Flows;
using Machine.Specifications;

namespace LogFlow.Specifications
{
    [Subject(typeof(Flow))]
    public class when_adding_a_working_flow
    {
        static FlowBuilder builder = new FlowBuilder();

        Establish context = () => builder.BuildAndRegisterFlow(new WorkingFlow());

        private It should_be_saved
            = () => builder.Flows.Count.ShouldEqual(1);
    }

    [Subject(typeof(Flow))]
    public class when_adding_an_empty_flow
    {
        static FlowBuilder builder = new FlowBuilder();

        Establish context = () => builder.BuildAndRegisterFlow(new EmptyFlow());

        private It should_not_be_saved
            = () => builder.Flows.Count.ShouldEqual(0);
    }

    [Subject(typeof(Flow))]
    public class when_adding_a_flow_without_a_name
    {
        static FlowBuilder builder = new FlowBuilder();

        Establish context = () => builder.BuildAndRegisterFlow(new FlowWithoutName());

        private It should_be_saved
            = () => builder.Flows.Count.ShouldEqual(1);

        private It should_be_named_after_the_type
            = () => builder.Flows.Single().LogType.ShouldEqual("FlowWithoutName");
    }

    [Subject(typeof(Flow))]
    public class when_adding_a_flow_without_a_input
    {
        static FlowBuilder builder = new FlowBuilder();

        Establish context = () => builder.BuildAndRegisterFlow(new FlowWithoutInput());

        private It should_not_be_saved
            = () => builder.Flows.Count.ShouldEqual(0);
    }

    [Subject(typeof(Flow))]
    public class when_adding_a_flow_without_a_process
    {
        static FlowBuilder builder = new FlowBuilder();

        Establish context = () => builder.BuildAndRegisterFlow(new FlowWithoutProcess());

        private It should_not_be_saved
            = () => builder.Flows.Count.ShouldEqual(0);
    }

    [Subject(typeof(Flow))]
    public class when_adding_a_flow_with_the_same_name
    {
        static FlowBuilder builder = new FlowBuilder();

        Establish context = () =>
        {
            builder.BuildAndRegisterFlow(new WorkingFlow());
            builder.BuildAndRegisterFlow(new WorkingFlow());
        };

        private It should_not_be_saved
            = () => builder.Flows.Count.ShouldEqual(1);
    }

}


text:
package io.apiman.test.integration.ui.tests.apis;

import static io.apiman.test.integration.ui.support.selenide.SelenideUtils.open;

import static com.codeborne.selenide.Condition.*;

import io.apiman.manager.api.beans.apis.ApiBean;
import io.apiman.manager.api.beans.orgs.OrganizationBean;
import io.apiman.test.integration.ui.support.assertion.PageAssert;
import io.apiman.test.integration.ui.support.beanutils.ApiUtils;
import io.apiman.test.integration.ui.support.beanutils.OrgUtils;
import io.apiman.test.integration.ui.support.selenide.pages.apis.BrowseApiPage;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 * @author opontes
 */
public class FindApisIT {

    private static ApiBean firstApiBean;
    private static ApiBean secondApiBean;

    @BeforeClass
    public static void createApiBean(){
        OrganizationBean orgBean = OrgUtils.remote();
        firstApiBean = ApiUtils.remote(orgBean);
        secondApiBean = ApiUtils.remote(orgBean);
    }

    @Test
    public void shouldNotListAnyResultBeforeSearch() {
        BrowseApiPage browseApiPage = open(BrowseApiPage.class, "");

        browseApiPage.noContentInfo().shouldBe(present);
    }

    @Test
    public void shouldNotFindAnything() {
        BrowseApiPage browseApiPage = open(BrowseApiPage.class)
                .search("ThisOrganizationDoesNotExistForSure");

        browseApiPage.noContentInfo().shouldBe(present);
    }

    @Test
    public void shouldFindSingleResult() {
        BrowseApiPage browseApiPage = open(BrowseApiPage.class)
                .search(firstApiBean.getName());

        browseApiPage.noContentInfo().shouldNotBe(visible);
        browseApiPage.resultEntries().shouldHaveSize(1);
    }

    @Test
    public void shouldFindMultipleResults() {
        BrowseApiPage browseOrgPage = open(BrowseApiPage.class)
                .search(ApiUtils.TEST_API_NAME_BASE);

        browseOrgPage.noContentInfo().shouldNotBe(visible);
        browseOrgPage.resultEntries()
                .filterBy(or("name equal to", text(firstApiBean.getName()), text(secondApiBean.getName())))
                .shouldHaveSize(2);
    }

    @Test
    public void shouldLandOnCorrectPageWhenClickOnResult() {
        BrowseApiPage browseOrgPage = open(BrowseApiPage.class)
                .search(firstApiBean.getName());

        browseOrgPage.openResult(firstApiBean.getName());

        PageAssert.assertBrowseApiDetail(firstApiBean);
    }
}


text:
<?php
/**
 * DataObjects that use the Hierachy decorator can be be organised as a hierachy, with children and parents.
 * The most obvious example of this is SiteTree.
 * @package sapphire
 * @subpackage model
 */
class Hierarchy extends DataObjectDecorator {
	protected $markedNodes;
	protected $markingFilter;

	function augmentSQL(SQLQuery &$query) {
	}

	function augmentDatabase() {
	}

	function augmentWrite(&$manipulation) {
	}

	/**
	 * Returns the children of this DataObject as an XHTML UL. This will be called recursively on each child,
	 * so if they have children they will be displayed as a UL inside a LI.
	 * @param string $attributes Attributes to add to the UL.
	 * @param string $titleEval PHP code to evaluate to start each child - this should include '
'
	 * @param string $extraArg Extra arguments that will be passed on to children, for if they overload this function.
	 * @param boolean $limitToMarked Display only marked children.
	 * @param boolean $rootCall Set to true for this first call, and then to false for calls inside the recursion. You should not change this.
	 * @return string
	 */
	public function getChildrenAsUL($attributes = "", $titleEval = '"
" . $child->Title', $extraArg = null, $limitToMarked = false, $rootCall = true) {
		if($limitToMarked && $rootCall) {
			$this->markingFinished();
		}

		$children = $this->owner->AllChildrenIncludingDeleted($extraArg);

		if($children) {
			if($attributes) {
				$attributes = " $attributes";
			}

			$output = "
\n";

			foreach($children as $child) {
				if(!$limitToMarked || $child->isMarked()) {
					$foundAChild = true;
					$output .= eval("return $titleEval;") . "\n" .
					$child->getChildrenAsUL("", $titleEval, $extraArg, $limitToMarked, false) . "
\n";
				}
			}

			$output .= "
\n";
		}

		if(isset($foundAChild) && $foundAChild) {
			return $output;
		}
	}

	/**
	 * Mark a segment of the tree, by calling mark().
	 * The method performs a breadth-first traversal until the number of nodes is more than minCount.
	 * This is used to get a limited number of tree nodes to show in the CMS initially.
	 *
	 * This method returns the number of nodes marked.  After this method is called other methods
	 * can check isExpanded() and isMarked() on individual nodes.
	 *
	 * @param int $minCount The minimum amount of nodes to mark.
	 * @return int The actual number of nodes marked.
	 */
	public function markPartialTree($minCount = 30, $context = null) {
		$this->markedNodes = array($this->owner->ID => $this->owner);
		$this->owner->markUnexpanded();

		// foreach can't handle an ever-growing $nodes list
		while(list($id, $node) = each($this->markedNodes)) {
			$this->markChildren($node, $context);

			if($minCount && sizeof($this->markedNodes) >= $minCount) {
				break;
			}
		}
		return sizeof($this->markedNodes);
	}

	/**
	 * Filter the marking to only those object with $node->$parameterName = $parameterValue
	 * @param string $parameterName The parameter on each node to check when marking.
	 * @param mixed $parameterValue The value the parameter must be to be marked.
	 */
	public function setMarkingFilter($parameterName, $parameterValue) {
		$this->markingFilter = array(
			"parameter" => $parameterName,
			"value" => $parameterValue
		);
	}

	/**
	 * Filter the marking to only those where the function returns true.
	 * The node in question will be passed to the function.
	 * @param string $funcName The function name.
	 */
	public function setMarkingFilterFunction($funcName) {
		$this->markingFilter = array(
			"func" => $funcName,
		);
	}

	/**
	 * Returns true if the marking filter matches on the given node.
	 * @param DataObject $node Node to check.
	 * @return boolean
	 */
	public function markingFilterMatches($node) {
		if(!$this->markingFilter) {
			return true;
		}

		if(isset($this->markingFilter['parameter']) && $parameterName = $this->markingFilter['parameter']) {
			if(is_array($this->markingFilter['value'])){
				$ret = false;
				foreach($this->markingFilter['value'] as $value) {
					$ret = $ret||$node->$parameterName==$value;
					if($ret == true) {
						break;
					}
				}
				return $ret;
			} else {
				return ($node->$parameterName == $this->markingFilter['value']);
			}
		} else if ($funcName = $this->markingFilter['func']) {
			return $funcName($node);
		}
	}

	/**
	 * Mark all children of the given node that match the marking filter.
	 * @param DataObject $node Parent node.
	 */
	public function markChildren($node, $context = null) {
		$children = $node->AllChildrenIncludingDeleted($context);
		$node->markExpanded();
		if($children) {
			foreach($children as $child) {
				if(!$this->markingFilter || $this->markingFilterMatches($child)) {
					$child->markUnexpanded();
					$this->markedNodes[$child->ID] = $child;
				}
			}
		}
	}

	/**
	 * Ensure marked nodes that have children are also marked expanded.
	 * Call this after marking but before iterating over the tree.
	 */
	protected function markingFinished() {
		// Mark childless nodes as expanded.
		foreach($this->markedNodes as $id => $node) {
			if(!$node->isExpanded() && !$node->numChildren()) {
				$node->markExpanded();
			}
		}
	}

	/**
	 * Return CSS classes of 'unexpanded', 'closed', both, or neither, depending on
	 * the marking of this DataObject.
	 */
	public function markingClasses() {
		$classes = '';
		if(!$this->expanded) {
			$classes .= " unexpanded";
		}
		if(!$this->treeOpened) {
			$classes .= " closed";
		}
		return $classes;
	}

	/**
	 * Mark the children of the DataObject with the given ID.
	 * @param int $id ID of parent node.
	 * @param boolean $open If this is true, mark the parent node as opened.
	 */
	public function markById($id, $open = false) {
		if(isset($this->markedNodes[$id])) {
			$this->markChildren($this->markedNodes[$id]);
			if($open) {
				$this->markedNodes[$id]->markOpened();
			}
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Expose the given object in the tree, by marking this page and all it ancestors.
	 * @param DataObject $childObj
	 */
	public function markToExpose($childObj) {
		if(is_object($childObj)){
			$stack = array_reverse($childObj->parentStack());
			foreach($stack as $stackItem) {
				$this->markById($stackItem->ID, true);
			}
		}
	}

	/**
	 * Return an array of this page and its ancestors, ordered item -> root.
	 * @return array
	 */
	public function parentStack() {
		$p = $this->owner;

		while($p) {
			$stack[] = $p;
			$p = $p->ParentID ? $p->Parent() : null;
		}

		return $stack;
	}

	/**
	 * True if this DataObject is marked.
	 * @var boolean
	 */
	protected $marked = false;

	/**
	 * True if this DataObject is expanded.
	 * @var boolean
	 */
	protected $expanded = false;

	/**
	 * True if this DataObject is opened.
	 * @var boolean
	 */
	protected $treeOpened = false;

	/**
	 * Mark this DataObject as expanded.
	 */
	public function markExpanded() {
		$this->marked = true;
		$this->expanded = true;
	}

	/**
	 * Mark this DataObject as unexpanded.
	 */
	public function markUnexpanded() {
		$this->marked = true;
		$this->expanded = false;
	}

	/**
	 * Mark this DataObject's tree as opened.
	 */
	public function markOpened() {
		$this->marked = true;
		$this->treeOpened = true;
	}

	/**
	 * Check if this DataObject is marked.
	 * @return boolean
	 */
	public function isMarked() {
		return $this->marked;
	}

	/**
	 * Check if this DataObject is expanded.
	 * @return boolean
	 */
	public function isExpanded() {
		return $this->expanded;
	}

	/**
	 * Check if this DataObject's tree is opened.
	 */
	public function isTreeOpened() {
		return $this->treeOpened;
	}

	/**
	 * Return a partial tree as an HTML UL.
	 */
	public function partialTreeAsUL($minCount = 50) {
		$children = $this->owner->AllChildren();
		if($children) {
			if($attributes) $attributes = " $attributes";
			$output = "
\n";

			foreach($children as $child) {
				$output .= eval("return $titleEval;") . "\n" .
					$child->getChildrenAsUL("", $titleEval, $extraArg) . "
\n";
			}
			$output .= "
\n";
		}
		return $output;
	}

	/**
	 * Get a list of this DataObject's and all it's descendants IDs.
	 * @return int
	 */
	public function getDescendantIDList() {
		$idList = array();
		$this->loadDescendantIDListInto($idList);
		return $idList;
	}

	/**
	 * Get a list of this DataObject's and all it's descendants ID, and put it in $idList.
	 * @var array $idList Array to put results in.
	 */
	public function loadDescendantIDListInto(&$idList) {
		if($children = $this->AllChildren()) {
			foreach($children as $child) {
				if(in_array($child->ID, $idList)) {
					continue;
				}
				$idList[] = $child->ID;
				$child->loadDescendantIDListInto($idList);
			}
		}
	}

	/**
	 * Cached result for AllChildren().
	 * @var DataObjectSet
	 */
	protected $allChildren;

	/**
	 * Cached result for AllChildrenIncludingDeleted().
	 * @var DataObjectSet
	 */
	protected $allChildrenIncludingDeleted;

	/**
	 * Cached result for Children().
	 */
	protected $children;

	/**
	 * Get the children for this DataObject.
	 * @return DataObjectSet
	 */
	public function Children() {
		if(!$this->children) {
			$result = $this->owner->stageChildren(false);
		 	if(isset($result)) {
		 		$this->children = new DataObjectSet();
		 		foreach($result as $child) {
		 			if($child->canView()) {
		 				$this->children->push($child);
		 			}
		 		}
		 	}
		}
		return $this->children;
	}

	/**
	 * Return all children, including those 'not in menus'.
	 * @return DataObjectSet
	 */
	public function AllChildren() {
		// Cache the allChildren data, so that future requests will return the references to the same
		// object.  This allows the mark..() system to work appropriately.
		if(!$this->allChildren) {
			$this->allChildren = $this->owner->stageChildren(true);
		}

		return $this->allChildren;
	}

	/**
	 * Return all children, including those that have been deleted but are still in live.
	 * Deleted children will be marked as "DeletedFromStage"
	 * Added children will be marked as "AddedToStage"
	 * Modified children will be marked as "ModifiedOnStage"
	 * Everything else has "SameOnStage" set, as an indicator that this information has been looked up.
	 * @return DataObjectSet
	 */
	public function AllChildrenIncludingDeleted($context = null) {
		return $this->doAllChildrenIncludingDeleted($context);
	}

	/**
	 * @see AllChildrenIncludingDeleted
	 *
	 * @param unknown_type $context
	 * @return DataObjectSet
	 */
	public function doAllChildrenIncludingDeleted($context = null) {
		// Cache the allChildren data, so that future requests will return the references to the same
		// object.  This allows the mark..() system to work appropriately.

		if(!$this->allChildrenIncludingDeleted) {
			$baseClass = ClassInfo::baseDataClass($this->owner->class);
			if($baseClass) {
				$stageChildren = $this->owner->stageChildren(true);
				$this->allChildrenIncludingDeleted = $stageChildren;

				$this->owner->extend("augmentAllChildrenIncludingDeleted", $stageChildren, $context);

				// Add live site content, if required.
				if($this->owner->hasExtension('Versioned')) {
					// Get all the requisite data, and index it
					$liveChildren = $this->owner->liveChildren(true);

					if(isset($stageChildren)) {
						foreach($stageChildren as $child) {
							$idxStageChildren[$child->ID] = $child;
						}
					}

					if(isset($liveChildren)) {
						foreach($liveChildren as $child) {
							$idxLiveChildren[$child->ID] = $child;
						}
					}

					DataObject::disable_subclass_access();
					if(isset($idxStageChildren)) {
						$foundInLive = Versioned::get_by_stage( $baseClass, 'Live', "`{$baseClass}`.`ID` IN (" . implode(",", array_keys($idxStageChildren)) . ")", "" );
					}

					if(isset($idxLiveChildren)) {
						$foundInStage = Versioned::get_by_stage( $baseClass, 'Stage', "`{$baseClass}`.`ID` IN (" . implode(",", array_keys($idxLiveChildren)) . ")", "" );
					}
					DataObject::enable_subclass_access();

					if(isset($foundInLive)) {
						foreach($foundInLive as $child) {
							$idxFoundInLive[$child->ID] = $child;
						}
					}

					if(isset($foundInStage)) {
						foreach($foundInStage as $child) {
							$idxFoundInStage[$child->ID] = $child;
						}
					}

					$this->allChildrenIncludingDeleted = new DataObjectSet();

					// First, go through the stage children.  They will all be listed but may be different colours
					if($stageChildren) {
						foreach($stageChildren as $child) {
							$this->allChildrenIncludingDeleted->push($child);
						}
					}

					// Next, go through the live children.  Only some of these will be listed
					if($liveChildren) {
						foreach($liveChildren as $child) {
							// Not found on stage = deleted page.  Anything else is ignored
							if(!isset($idxFoundInStage[$child->ID])) {
								$this->allChildrenIncludingDeleted->push($child);
							}
						}
					}
				}

			} else {
				user_error("Hierarchy::AllChildren() Couldn't determine base class for '{$this->owner->class}'", E_USER_ERROR);
			}
		}

		return $this->allChildrenIncludingDeleted;
	}

	/**
	 * Return the number of children
	 * @return int
	 */
	public function numChildren() {
		$baseClass = ClassInfo::baseDataClass($this->owner->class);
		// We build the query in an extension-friendly way.
		$query = new SQLQuery("COUNT(*)","`$baseClass`","ParentID = " . (int)$this->owner->ID);
		$this->owner->extend('augmentSQL', $query);
		$this->owner->extend('augmentNumChildrenCountQuery', $query);
		return $query->execute()->value();
	}

	/**
	 * Return children from the stage site
	 * @param showAll Inlcude all of the elements, even those not shown in the menus.
	 * @return DataObjectSet
	 */
	public function stageChildren($showAll = false) {
		$extraFilter = $showAll ? '' : " AND ShowInMenus = 1";
		$baseClass = ClassInfo::baseDataClass($this->owner->class);
		$staged = DataObject::get($baseClass, "`{$baseClass}`.`ParentID` = " . (int)$this->owner->ID . " AND `{$baseClass}`.ID != " . (int)$this->owner->ID . $extraFilter, "");
		if(!$staged) $staged = new DataObjectSet();
		$this->owner->extend("augmentStageChildren", $staged, $showAll);
		return $staged;
	}

	/**
	 * Return children from the live site, if it exists.
	 * @param boolean $showAll Include all of the elements, even those not shown in the menus.
	 * @return DataObjectSet
	 */
	public function liveChildren($showAll = false) {
		$extraFilter = $showAll ? '' : " AND ShowInMenus = 1";
		$baseClass = ClassInfo::baseDataClass($this->owner->class);
		return Versioned::get_by_stage($baseClass, "Live", "`{$baseClass}`.`ParentID` = " . (int)$this->owner->ID . " AND `{$baseClass}`.ID != " . (int)$this->owner->ID. $extraFilter, "");
	}

	/**
	 * Get the parent of this class.
	 * @return DataObject
	 */
	public function getParent($filter = '') {
		if($p = $this->owner->__get("ParentID")) {
			$tableClasses = ClassInfo::dataClassesFor($this->owner->class);
			$baseClass = array_shift($tableClasses);
			$filter .= $filter?" AND ":""."`$baseClass`.ID = $p";
			return DataObject::get_one($this->owner->class, $filter);
		}
	}

	/**
	 * Get the next node in the tree of the type. If there is no instance of the className descended from this node,
	 * then search the parents.
	 *
	 * @todo Write!
	 */
	public function naturalPrev( $className, $afterNode = null ) {
		return null;
	}

	/**
	 * Get the next node in the tree of the type. If there is no instance of the className descended from this node,
	 * then search the parents.
	 * @param string $className Class name of the node to find.
	 * @param string|int $root ID/ClassName of the node to limit the search to
	 * @param DataObject afterNode Used for recursive calls to this function
	 * @return DataObject
	 */
	public function naturalNext( $className = null, $root = 0, $afterNode = null ) {
		// If this node is not the node we are searching from, then we can possibly return this
		// node as a solution
		if($afterNode && $afterNode->ID != $this->owner->ID) {
			if(!$className || ($className && $this->owner->class == $className)) {
				return $this->owner;
			}
		}

		$nextNode = null;
		$baseClass = ClassInfo::baseDataClass($this->owner->class);

		// Try searching for the next node of the given class in each of the children, but treat each
		// child as the root of the search. This will stop the recursive call from searching backwards.
		// If afterNode is given, then only search for the nodes after
		if(!$afterNode || $afterNode->ParentID != $this->owner->ID) {
			$children = $this->AllChildren();
		} else {
			$children = DataObject::get(ClassInfo::baseDataClass($this->owner->class), "`$baseClass`.`ParentID`={$this->owner->ID}" . ( ( $afterNode ) ? " AND `Sort` > " . sprintf( '%d', $afterNode->Sort ) : "" ), '`Sort` ASC');
		}

		// Try all the siblings of this node after the given node
		/*if( $siblings = DataObject::get( ClassInfo::baseDataClass($this->owner->class), "`ParentID`={$this->owner->ParentID}" . ( $afterNode ) ? "`Sort` > {$afterNode->Sort}" : "" , '`Sort` ASC' ) )
			$searchNodes->merge( $siblings );*/

		if($children) {
			foreach($children as $node) {
				if($nextNode = $node->naturalNext($className, $node->ID, $this->owner)) {
					break;
				}
			}

			if($nextNode) {
				return $nextNode;
			}
		}

		// if this is not an instance of the root class or has the root id, search the parent
		if(!(is_numeric($root) && $root == $this->owner->ID || $root == $this->owner->class) && ($parent = $this->owner->Parent())) {
			return $parent->naturalNext( $className, $root, $this->owner );
		}

		return null;
	}
}

?>


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

package com.camunda.demo.dmn.feel.operator;

import org.camunda.bpm.dmn.feel.impl.juel.FeelEngineFactoryImpl;
import org.camunda.bpm.dmn.feel.impl.juel.transform.FeelToJuelTransform;

public class CustomFeelEngineFactory extends FeelEngineFactoryImpl {

  @Override
  protected FeelToJuelTransform createFeelToJuelTransform() {
    return new CustomFeelToJuelTransform();
  }

}


text:
<?php

class Bootstrap_Starter {

	function __construct() {

		add_action( 'wp_enqueue_scripts', array( $this, 'wp_enqueue_scripts' ) );

	}

	function wp_enqueue_scripts() {
		wp_enqueue_script( 'test', get_stylesheet_directory_uri() . '/test.js' );
		wp_enqueue_style( 'bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css' );
		wp_enqueue_style( 'bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css' );
		wp_enqueue_script( 'bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js', array( 'jquery' ), '3.3.4', true );
	}

}
new Bootstrap_Starter();


text:
import RSVP from 'rsvp';
import { isEmpty } from '@ember/utils';
import { run, later, cancel } from '@ember/runloop';
import { A, makeArray } from '@ember/array';
import { warn } from '@ember/debug';
import { getOwner } from '@ember/application';
import assign from 'ember-simple-auth/utils/assign';
import Ember from 'ember';
import BaseAuthenticator from './base';
import fetch from 'fetch';
import isFastBoot from 'ember-simple-auth/utils/is-fastboot';

/**
  Authenticator that conforms to OAuth 2
  ([RFC 6749](http://tools.ietf.org/html/rfc6749)), specifically the _"Resource
  Owner Password Credentials Grant Type"_.

  This authenticator also automatically refreshes access tokens (see
  [RFC 6749, section 6](http://tools.ietf.org/html/rfc6749#section-6)) if the
  server supports it.

  @class OAuth2PasswordGrantAuthenticator
  @module ember-simple-auth/authenticators/oauth2-password-grant
  @extends BaseAuthenticator
  @public
*/
export default BaseAuthenticator.extend({
  /**
    Triggered when the authenticator refreshed the access token (see
    [RFC 6749, section 6](http://tools.ietf.org/html/rfc6749#section-6)).

    @event sessionDataUpdated
    @param {Object} data The updated session data
    @public
  */

  /**
    The client_id to be sent to the authentication server (see
    https://tools.ietf.org/html/rfc6749#appendix-A.1). __This should only be
    used for statistics or logging etc. as it cannot actually be trusted since
    it could have been manipulated on the client!__

    @property clientId
    @type String
    @default null
    @public
  */
  clientId: null,

  /**
    The endpoint on the server that authentication and token refresh requests
    are sent to.

    @property serverTokenEndpoint
    @type String
    @default '/token'
    @public
  */
  serverTokenEndpoint: '/token',

  /**
    The endpoint on the server that token revocation requests are sent to. Only
    set this if the server actually supports token revocation. If this is
    `null`, the authenticator will not revoke tokens on session invalidation.

    __If token revocation is enabled but fails, session invalidation will be
    intercepted and the session will remain authenticated (see
    {{#crossLink "OAuth2PasswordGrantAuthenticator/invalidate:method"}}{{/crossLink}}).__

    @property serverTokenRevocationEndpoint
    @type String
    @default null
    @public
  */
  serverTokenRevocationEndpoint: null,

  /**
    Sets whether the authenticator automatically refreshes access tokens if the
    server supports it.

    @property refreshAccessTokens
    @type Boolean
    @default true
    @public
  */
  refreshAccessTokens: true,

  /**
    The offset time in milliseconds to refresh the access token. This must
    return a random number. This randomization is needed because in case of
    multiple tabs, we need to prevent the tabs from sending refresh token
    request at the same exact moment.

    __When overriding this property, make sure to mark the overridden property
    as volatile so it will actually have a different value each time it is
    accessed.__

    @property tokenRefreshOffset
    @type Integer
    @default a random number between 5 and 10
    @public
  */
  get tokenRefreshOffset() {
    const min = 5;
    const max = 10;

    return (Math.floor(Math.random() * (max - min)) + min) * 1000;
  },

  _refreshTokenTimeout: null,

  /**
    Restores the session from a session data object; __will return a resolving
    promise when there is a non-empty `access_token` in the session data__ and
    a rejecting promise otherwise.

    If the server issues
    [expiring access tokens](https://tools.ietf.org/html/rfc6749#section-5.1)
    and there is an expired access token in the session data along with a
    refresh token, the authenticator will try to refresh the access token and
    return a promise that resolves with the new access token if the refresh was
    successful. If there is no refresh token or the token refresh is not
    successful, a rejecting promise will be returned.

    @method restore
    @param {Object} data The data to restore the session from
    @return {Ember.RSVP.Promise} A promise that when it resolves results in the session becoming or remaining authenticated. If restoration fails, the promise will reject with the server response (in case the access token had expired and was refreshed using a refresh token); however, the authenticator reads that response already so if you need to read it again you need to clone the response object first
    @public
  */
  restore(data) {
    return new RSVP.Promise((resolve, reject) => {
      const now = (new Date()).getTime();
      const refreshAccessTokens = this.get('refreshAccessTokens');
      if (!isEmpty(data['expires_at']) && data['expires_at'] < now) {
        if (refreshAccessTokens) {
          this._refreshAccessToken(data['expires_in'], data['refresh_token']).then(resolve, reject);
        } else {
          reject();
        }
      } else {
        if (!this._validate(data)) {
          reject();
        } else {
          this._scheduleAccessTokenRefresh(data['expires_in'], data['expires_at'], data['refresh_token']);
          resolve(data);
        }
      }
    });
  },

  /**
    Authenticates the session with the specified `identification`, `password`
    and optional `scope`; issues a `POST` request to the
    {{#crossLink "OAuth2PasswordGrantAuthenticator/serverTokenEndpoint:property"}}{{/crossLink}}
    and receives the access token in response (see
    http://tools.ietf.org/html/rfc6749#section-4.3).

    __If the credentials are valid (and the optionally requested scope is
    granted) and thus authentication succeeds, a promise that resolves with the
    server's response is returned__, otherwise a promise that rejects with the
    error as returned by the server is returned.

    __If the
    [server supports it](https://tools.ietf.org/html/rfc6749#section-5.1), this
    method also schedules refresh requests for the access token before it
    expires.__

    The server responses are expected to look as defined in the spec (see
    http://tools.ietf.org/html/rfc6749#section-5). The response to a successful
    authentication request should be:

    ```json
    HTTP/1.1 200 OK
    Content-Type: application/json;charset=UTF-8

    {
      "access_token":"2YotnFZFEjr1zCsicMWpAA",
      "token_type":"bearer",
      "expires_in":3600, // optional
      "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA" // optional
    }
    ```

    The response for a failing authentication request should be:

    ```json
    HTTP/1.1 400 Bad Request
    Content-Type: application/json;charset=UTF-8

    {
      "error":"invalid_grant"
    }
    ```

    A full list of error codes can be found
    [here](https://tools.ietf.org/html/rfc6749#section-5.2).

    @method authenticate
    @param {String} identification The resource owner username
    @param {String} password The resource owner password
    @param {String|Array} scope The scope of the access request (see [RFC 6749, section 3.3](http://tools.ietf.org/html/rfc6749#section-3.3))
    @param {Object} headers Optional headers that particular backends may require (for example sending 2FA challenge responses)
    @return {Ember.RSVP.Promise} A promise that when it resolves results in the session becoming authenticated. If authentication fails, the promise will reject with the server response; however, the authenticator reads that response already so if you need to read it again you need to clone the response object first
    @public
  */
  authenticate(identification, password, scope = [], headers = {}) {
    return new RSVP.Promise((resolve, reject) => {
      const data = { 'grant_type': 'password', username: identification, password };
      const serverTokenEndpoint = this.get('serverTokenEndpoint');

      const scopesString = makeArray(scope).join(' ');
      if (!isEmpty(scopesString)) {
        data.scope = scopesString;
      }
      this.makeRequest(serverTokenEndpoint, data, headers).then((response) => {
        run(() => {
          if (!this._validate(response)) {
            reject('access_token is missing in server response');
          }

          const expiresAt = this._absolutizeExpirationTime(response['expires_in']);
          this._scheduleAccessTokenRefresh(response['expires_in'], expiresAt, response['refresh_token']);
          if (!isEmpty(expiresAt)) {
            response = assign(response, { 'expires_at': expiresAt });
          }

          resolve(response);
        });
      }, (response) => {
        run(null, reject, response);
      });
    });
  },

  /**
    If token revocation is enabled, this will revoke the access token (and the
    refresh token if present). If token revocation succeeds, this method
    returns a resolving promise, otherwise it will return a rejecting promise,
    thus intercepting session invalidation.

    If token revocation is not enabled this method simply returns a resolving
    promise.

    @method invalidate
    @param {Object} data The current authenticated session data
    @return {Ember.RSVP.Promise} A promise that when it resolves results in the session being invalidated. If invalidation fails, the promise will reject with the server response (in case token revocation is used); however, the authenticator reads that response already so if you need to read it again you need to clone the response object first
    @public
  */
  invalidate(data) {
    const serverTokenRevocationEndpoint = this.get('serverTokenRevocationEndpoint');
    function success(resolve) {
      cancel(this._refreshTokenTimeout);
      delete this._refreshTokenTimeout;
      resolve();
    }
    return new RSVP.Promise((resolve) => {
      if (isEmpty(serverTokenRevocationEndpoint)) {
        success.apply(this, [resolve]);
      } else {
        const requests = [];
        A(['access_token', 'refresh_token']).forEach((tokenType) => {
          const token = data[tokenType];
          if (!isEmpty(token)) {
            requests.push(this.makeRequest(serverTokenRevocationEndpoint, {
              'token_type_hint': tokenType, token
            }));
          }
        });
        const succeed = () => {
          success.apply(this, [resolve]);
        };
        RSVP.all(requests).then(succeed, succeed);
      }
    });
  },

  /**
    Makes a request to the OAuth 2.0 server.

    @method makeRequest
    @param {String} url The request URL
    @param {Object} data The request data
    @param {Object} headers Additional headers to send in request
    @return {Promise} A promise that resolves with the response object
    @protected
  */
  makeRequest(url, data, headers = {}) {
    headers['Content-Type'] = 'application/x-www-form-urlencoded';

    const clientId = this.get('clientId');
    if (!isEmpty(clientId)) {
      data['client_id'] = this.get('clientId');
    }

    const body = Object.keys(data).map((key) => {
      return `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`;
    }).join('&');

    const options = {
      body,
      headers,
      method: 'POST'
    };

    return new RSVP.Promise((resolve, reject) => {
      fetch(url, options).then((response) => {
        response.text().then((text) => {
          try {
            let json = JSON.parse(text);
            if (!response.ok) {
              response.responseJSON = json;
              reject(response);
            } else {
              resolve(json);
            }
          } catch (SyntaxError) {
            response.responseText = text;
            reject(response);
          }
        });
      }).catch(reject);
    });
  },

  _scheduleAccessTokenRefresh(expiresIn, expiresAt, refreshToken) {
    const refreshAccessTokens = this.get('refreshAccessTokens') && !isFastBoot(getOwner(this));
    if (refreshAccessTokens) {
      const now = (new Date()).getTime();
      if (isEmpty(expiresAt) && !isEmpty(expiresIn)) {
        expiresAt = new Date(now + expiresIn * 1000).getTime();
      }
      const offset = this.get('tokenRefreshOffset');
      if (!isEmpty(refreshToken) && !isEmpty(expiresAt) && expiresAt > now - offset) {
        cancel(this._refreshTokenTimeout);
        delete this._refreshTokenTimeout;
        if (!Ember.testing) {
          this._refreshTokenTimeout = later(this, this._refreshAccessToken, expiresIn, refreshToken, expiresAt - now - offset);
        }
      }
    }
  },

  _refreshAccessToken(expiresIn, refreshToken) {
    const data = { 'grant_type': 'refresh_token', 'refresh_token': refreshToken };
    const serverTokenEndpoint = this.get('serverTokenEndpoint');
    return new RSVP.Promise((resolve, reject) => {
      this.makeRequest(serverTokenEndpoint, data).then((response) => {
        run(() => {
          expiresIn = response['expires_in'] || expiresIn;
          refreshToken = response['refresh_token'] || refreshToken;
          const expiresAt = this._absolutizeExpirationTime(expiresIn);
          const data = assign(response, { 'expires_in': expiresIn, 'expires_at': expiresAt, 'refresh_token': refreshToken });
          this._scheduleAccessTokenRefresh(expiresIn, null, refreshToken);
          this.trigger('sessionDataUpdated', data);
          resolve(data);
        });
      }, (response) => {
        warn(`Access token could not be refreshed - server responded with ${response.responseJSON}.`, false, { id: 'ember-simple-auth.failedOAuth2TokenRefresh' });
        reject();
      });
    });
  },

  _absolutizeExpirationTime(expiresIn) {
    if (!isEmpty(expiresIn)) {
      return new Date((new Date().getTime()) + expiresIn * 1000).getTime();
    }
  },

  _validate(data) {
    return !isEmpty(data['access_token']);
  }
});


text:
#region Copyright
//  ***********************************************************************
//  Copyright (c) 2016 Jamie Rees
//  File: CacheKeys.cs
//  Created By: Jamie Rees
//
//  Permission is hereby granted, free of charge, to any person obtaining
//  a copy of this software and associated documentation files (the
//  "Software"), to deal in the Software without restriction, including
//  without limitation the rights to use, copy, modify, merge, publish,
//  distribute, sublicense, and/or sell copies of the Software, and to
//  permit persons to whom the Software is furnished to do so, subject to
//  the following conditions:
//
//  The above copyright notice and this permission notice shall be
//  included in all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
//  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
//  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
//  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
//  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//  ***********************************************************************
#endregion
namespace NZBDash.UI.Helpers
{
    public class CacheKeys
    {
        public const string SabKey = "SabNzdb";
        public const string CouchPotatoKey = "CouchPotato";
        public const string SonarrKey = "Sonarr";
        public const string PlexKey = "Plex";
        public const string NzbGetKey = "NzbGet";
    }
}


text:
#ifndef Magnum_DebugMessage_h
#define Magnum_DebugMessage_h

/** @file
 * @deprecated Use @ref Magnum/DebugOutput.h instead.
 */

#include "Magnum/configure.h"

#ifdef MAGNUM_BUILD_DEPRECATED
#include "Magnum/DebugOutput.h"
CORRADE_DEPRECATED_FILE("use Magnum/DebugOutput.h instead")
#else
#error use Magnum/DebugOutput.h instead
#endif

#endif


text:
    When a Pod starts and the probe fails, Kubernetes will try failureThreshold times before giving up.

    Giving up in case of liveness probe means restarting the container.

    In case of readiness probe the Pod will be marked Unready. Defaults to 3. Minimum value is 1.


text:
Write-Host "a test package just installed. yo"
Add-Content "$env:temp\testpackage.txt" -value "test-package"


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

namespace _1.AmericanPie
{
    class Program
    {
        static void Main(string[] args)
        {
            uint A = uint.Parse(Console.ReadLine());
            uint B = uint.Parse(Console.ReadLine());
            uint C = uint.Parse(Console.ReadLine());
            uint D = uint.Parse(Console.ReadLine());

            double sumNominator = (double)A * D + (double)B * C;
            double sumDenominator = (double)B * D;
            if (sumNominator / sumDenominator >= 1)
            {
                Console.WriteLine((uint)(sumNominator / sumDenominator));
            }
            else
            {
                Console.WriteLine("{0:F20}", ((double)sumNominator / (double)sumDenominator));
            }
            Console.WriteLine("{0}/{1}", sumNominator, sumDenominator);
        }
    }
}


text:
from lxml import etree
import structlog
from netconf.nc_rpc.rpc import Rpc
import netconf.nc_common.error as ncerror

log = structlog.get_logger()

class DeleteConfig(Rpc):
    def __init__(self, request, request_xml, grpc_client, session,
                 capabilities):
        super(DeleteConfig, self).__init__(request, request_xml,
                                           grpc_client, session, capabilities)
        self._validate_parameters()

    def execute(self):
        log.info('delete-config-request', session=self.session.session_id)
        if self.rpc_response.is_error:
            return self.rpc_response

    def _validate_parameters(self):
        log.info('validate-parameters', session=self.session.session_id)


text:
(function(){
    "use strict";
        angular
        .module("myApp")
        .controller("MainCtrl",MainCtrl)

        function MainCtrl(fetchApi){
            var vm=this;
            vm.name="srinvias";
            vm.say =say;
            vm.fake=fake;

           function say(){
                alert("helllo")
            }

            function fake(){
                return fetchApi.getUser();
            }

            console.log(fetchApi)
        }
})();


text:
[![Build Status](https://travis-ci.org/davewwww/IspecReaderBundle.svg)](https://travis-ci.org/davewwww/IspecReaderBundle) [![Coverage Status](https://coveralls.io/repos/davewwww/IspecReaderBundle/badge.svg)](https://coveralls.io/r/davewwww/IspecReaderBundle)

IspecReaderBundle
-----------------

:TODO:


text:
package org.globus.gatekeeper;

import java.io.InputStream;

public interface ServiceRequest {

    public InputStream getInputStream();

}


text:
<?php
    require_once __DIR__ .'/../templates/header.inc.php';
    require_once __DIR__ .'/../templates/nav.inc.php';

    $newsLetter = new Itb\NewsLetter();

    if(isset($_POST['newsLetter']))
    {
        $NewsName = trim($_POST['NewsName']);
        $NewsEmail = trim($_POST['NewsEmail']);

        if($NewsName =="")
        {
            $error[] = "Please enter a name!";
        }else if($NewsEmail=="")
        {
            $error[] = "Please enter an email address";
        }else if (!filter_var($NewsEmail, FILTER_VALIDATE_EMAIL)){
            $error[] = "Please enter an valid email address";

        }else
        {
            if($newsLetter->newsLetter($NewsName,$NewsEmail))
            {
                $message = 'Thank You For Subscribing To Our NewsLetter!';
            }
        }
    }

    $login = new Itb\User();
    $auth_user = new Itb\User();

    if($login->is_loggedin())
    {
        $user_id = $_SESSION['user_session'];
        $stmt = $auth_user->runQuery("SELECT * FROM UserDatabase WHERE UserId=:UserId");
        $stmt->execute(array(":UserId"=>$user_id));
        $userRow=$stmt->fetch(PDO::FETCH_ASSOC);
        $loginMessage = "Logged In As: " .$userRow['UserName'];
    }
?>

        <?php
        if(isset($loginMessage))
        {
            ?>

<?php print $loginMessage; ?>

            <?php
        }
        ?>

Welcome

Welcome to the home page of News & Yarn.

About

We are a small news agents based in the heart of Blanchardstown village in Dublin 15.

The news agents has been open about 20 years.

We are a family run business.

We sell newspapers, stationary and our most popular item is yarn.

The shop provides a number of varieties of knitting equipment as well as yarn that is stocked daily.

Subscribe

        <?php
        if(isset($message))
        {
            ?>

<?php print $message; ?>

            <?php
        }else if(isset($error))
        {
            foreach($error as $error)
            {
                ?>

<?php print $error; ?>

                <?php
            }
        }else{
            print '
Subscribe to our news letter
to get the latest on our products.
';
        }

        ?>
        <form action="index.php" method="post" class="subscribe-form">
            <input type="text" name="NewsName" placeholder="Enter Name" value="<?php if(isset($error)){echo $NewsName;}?>">

            <input type="text" name="NewsEmail" placeholder="Enter Email" value="<?php if(isset($error)){echo $NewsEmail;}?>">

            <button type="submit" name="newsLetter" class="subscribe-submit">Subscribe</button>
        </form>

<?php
    require_once __DIR__ .'/../templates/footer.inc.php';
?>


text:
<?php
class RSA_Crypt {
	var $string;
	function encrypt($string) {
		$array = array();
		$publicKeyFile = file_get_contents("public.pem");
		$publicKey = openssl_pkey_get_public($publicKeyFile);

		if (!$publicKey) {
			$array['RSA_Crypt']['Encrypt']['STATUS'] = "false";
			$array['RSA_Crypt']['Encrypt']['INFO'] = "Bad public key";
		} else {
			if (!openssl_public_encrypt($string, $encrypted, $publicKey)) {
				$array['RSA_Crypt']['Encrypt']['STATUS'] = "false";
				$array['RSA_Crypt']['Encrypt']['INFO'] = "Error encrypting with public key";
			} else {
				$array['RSA_Crypt']['Encrypt']['STATUS'] = "true";
				$array['RSA_Crypt']['Encrypt']['String'] = base64_encode($encrypted);
			}
		}
		return(json_encode($array, JSON_FORCE_OBJECT));
	}

	function decrypt($string) {
		$data = base64_decode($string);
		$array = array();
		$privateKeyFile = file_get_contents("private.pem");
		$passphrase = "mypassword";
		$privateKey = openssl_pkey_get_private(array($privateKeyFile, $passphrase));
		if (!$privateKey) {
			$array['RSA_Crypt']['Decrypt']['STATUS'] = "false";
			$array['RSA_Crypt']['Decrypt']['INFO'] = "Bad private key";
		} else {
			if (!openssl_private_decrypt($data, $decrypted, $privateKey)) {
				$array['RSA_Crypt']['Decrypt']['STATUS'] = "false";
				$array['RSA_Crypt']['Decrypt']['INFO'] = "Error decrypting with private key";
			} else {
				$array['RSA_Crypt']['Decrypt']['STATUS'] = "true";
				$array['RSA_Crypt']['Decrypt']['String'] = $decrypted;
			}
		}
		return(json_encode($array, JSON_FORCE_OBJECT));
	}
}
?>


text:
title: "DFS 4.1 Basics of Cybercrime Investigation"
date: 2020-09-29
header:
  image: #/assets/images/headers/goClass.jpg
---

In this video, we discuss how investigators begin to investigate cybercrime. We discuss crime detection, evidence collection, analysis, and reporting.

Get started digital forensic science! Digital forensic science lets us recover data and investigate digital devices.

{% include video id="pM8yX-cr6S8" provider="youtube" %}


text:
<?php
function better_comments($comment, $args, $depth) {
 $GLOBALS['comment'] = $comment;
?>

		ddd

 <li <?php comment_class(); ?> id="li-comment-<?php comment_ID() ?>">
 <div id="comment-<?php comment_ID(); ?>" class="comment-body">

 <?php echo get_avatar($comment, $size = '45', $default = get_bloginfo('stylesheet_directory').'/images/default-avatar.png' ); ?>

 <?php printf(__('%s says:'), get_comment_author_link()) ?>

 <?php if ($comment->comment_approved == '0') : ?>
 <?php _e('Your comment is awaiting moderation.') ?>

 <?php endif; ?>

 <a href="<?php echo htmlspecialchars( get_comment_link( $comment->comment_ID ) ) ?>"><?php printf(__('%1$s at %2$s'), get_comment_date(),  get_comment_time()) ?>
 <?php edit_comment_link(__('(Edit)'),'  ','') ?>

 <?php comment_text() ?>

 <?php comment_reply_link(array_merge( $args, array('depth' => $depth, 'max_depth' => $args['max_depth']))) ?>

<?php
}
?>


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.core.test.policy;

import com.azure.core.http.ContentType;
import com.azure.core.http.HttpHeader;
import com.azure.core.http.HttpHeaders;
import com.azure.core.http.HttpPipelineCallContext;
import com.azure.core.http.HttpPipelineNextPolicy;
import com.azure.core.http.HttpResponse;
import com.azure.core.http.policy.HttpPipelinePolicy;
import com.azure.core.test.TestMode;
import com.azure.core.test.implementation.TestingHelpers;
import com.azure.core.test.models.NetworkCallError;
import com.azure.core.test.models.NetworkCallRecord;
import com.azure.core.test.models.RecordedData;
import com.azure.core.test.models.RecordingRedactor;
import com.azure.core.util.CoreUtils;
import com.azure.core.util.FluxUtil;
import com.azure.core.util.UrlBuilder;
import com.azure.core.util.logging.ClientLogger;
import reactor.core.Exceptions;
import reactor.core.publisher.Mono;
import reactor.util.function.Tuple2;
import reactor.util.function.Tuples;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.zip.GZIPInputStream;

/**
 * HTTP Pipeline policy that keeps track of each HTTP request and response that flows through the pipeline. Data is
 * recorded into {@link RecordedData}.
 */
public class RecordNetworkCallPolicy implements HttpPipelinePolicy {
    private static final int DEFAULT_BUFFER_LENGTH = 1024;
    private static final String CONTENT_TYPE = "Content-Type";
    private static final String CONTENT_ENCODING = "Content-Encoding";
    private static final String CONTENT_LENGTH = "Content-Length";
    private static final String X_MS_CLIENT_REQUEST_ID = "x-ms-client-request-id";
    private static final String X_MS_ENCRYPTION_KEY_SHA256 = "x-ms-encryption-key-sha256";
    private static final String X_MS_VERSION = "x-ms-version";
    private static final String USER_AGENT = "User-Agent";
    private static final String STATUS_CODE = "StatusCode";
    private static final String BODY = "Body";
    private static final String SIG = "sig";

    private static final TestMode TEST_MODE = TestingHelpers.getTestMode();

    private final ClientLogger logger = new ClientLogger(RecordNetworkCallPolicy.class);
    private final RecordedData recordedData;
    private final RecordingRedactor redactor;

    /**
     * Creates a policy that records network calls into {@code recordedData}.
     *
     * @param recordedData The record to persist network calls into.
     */
    public RecordNetworkCallPolicy(RecordedData recordedData) {
        this(recordedData, Collections.emptyList());
    }

    /**
     * Creates a policy that records network calls into {@code recordedData} by redacting sensitive information by
     * applying the provided redactor functions.
     * @param recordedData The record to persist network calls into.
     * @param redactors The custom redactor functions to apply to redact sensitive information from recorded data.
     */
    public RecordNetworkCallPolicy(RecordedData recordedData, List<Function<String, String>> redactors) {
        this.recordedData = recordedData;
        redactor = new RecordingRedactor(redactors);

    }

    @Override
    public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
        // If TEST_MODE isn't RECORD do not record.
        if (TEST_MODE != TestMode.RECORD) {
            return next.process();
        }

        final NetworkCallRecord networkCallRecord = new NetworkCallRecord();
        Map<String, String> headers = new HashMap<>();

        captureRequestHeaders(context.getHttpRequest().getHeaders(), headers,
            X_MS_CLIENT_REQUEST_ID,
            CONTENT_TYPE,
            X_MS_VERSION,
            USER_AGENT);

        networkCallRecord.setHeaders(headers);
        networkCallRecord.setMethod(context.getHttpRequest().getHttpMethod().toString());

        // Remove sensitive information such as SAS token signatures from the recording.
        UrlBuilder urlBuilder = UrlBuilder.parse(context.getHttpRequest().getUrl());
        redactedAccountName(urlBuilder);
        if (urlBuilder.getQuery().containsKey(SIG)) {
            urlBuilder.setQueryParameter(SIG, "REDACTED");
        }
        String uriString = urlBuilder.toString();
        networkCallRecord.setUri(uriString.endsWith("?") ? uriString.substring(0, uriString.length() - 2) : uriString);

        return next.process()
            .doOnError(throwable -> {
                networkCallRecord.setException(new NetworkCallError(throwable));
                recordedData.addNetworkCall(networkCallRecord);
                throw logger.logExceptionAsWarning(Exceptions.propagate(throwable));
            }).flatMap(httpResponse -> extractResponseData(httpResponse, redactor, logger)
                .map(responseAndSessionRecordData -> {
                    Map<String, String> sessionRecordData = responseAndSessionRecordData.getT2();
                    networkCallRecord.setResponse(sessionRecordData);
                    String body = sessionRecordData.get(BODY);

                    // Remove pre-added header if this is a waiting or redirection
                    if (body != null && body.contains("<Status>InProgress</Status>")
                        || Integer.parseInt(sessionRecordData.get(STATUS_CODE)) == HttpURLConnection.HTTP_MOVED_TEMP) {
                        logger.info("Waiting for a response or redirection.");
                    } else {
                        recordedData.addNetworkCall(networkCallRecord);
                    }

                    return responseAndSessionRecordData.getT1();
                }));
    }

    private static void redactedAccountName(UrlBuilder urlBuilder) {
        String originalHost = urlBuilder.getHost();
        int indexOf = originalHost.indexOf(".");
        if (indexOf == -1) {
            urlBuilder.setHost("REDACTED");
        } else {
            urlBuilder.setHost("REDACTED" + originalHost.substring(indexOf));
        }
    }

    private static void captureRequestHeaders(HttpHeaders requestHeaders, Map<String, String> captureHeaders,
        String... headerNames) {
        for (String headerName : headerNames) {
            if (requestHeaders.getValue(headerName) != null) {
                captureHeaders.put(headerName, requestHeaders.getValue(headerName));
            }
        }
    }

    private static Mono<Tuple2<HttpResponse, Map<String, String>>> extractResponseData(final HttpResponse response,
        final RecordingRedactor redactor, final ClientLogger logger) {
        final Map<String, String> responseData = new HashMap<>();
        responseData.put(STATUS_CODE, Integer.toString(response.getStatusCode()));

        boolean addedRetryAfter = false;
        for (HttpHeader header : response.getHeaders()) {
            String headerValueToStore = header.getValue();

            if (header.getName().equalsIgnoreCase("retry-after")) {
                headerValueToStore = "0";
                addedRetryAfter = true;
            } else if (header.getName().equalsIgnoreCase(X_MS_ENCRYPTION_KEY_SHA256)) {
                // The encryption key is sensitive information so capture it with a hidden value.
                headerValueToStore = "REDACTED";
            }

            responseData.put(header.getName(), headerValueToStore);
        }

        if (!addedRetryAfter) {
            responseData.put("retry-after", "0");
        }

        String contentType = response.getHeaderValue(CONTENT_TYPE);
        String contentLengthHeader = response.getHeaderValue(CONTENT_LENGTH);

        if (!CoreUtils.isNullOrEmpty(contentLengthHeader) && Long.parseLong(contentLengthHeader) == 0) {
            return Mono.just(Tuples.of(response, responseData));
        }

        final HttpResponse bufferedResponse = response.buffer();
        final Mono<byte[]> responseBody = FluxUtil.collectBytesInByteBufferStream(bufferedResponse.getBody());
        if (contentType == null) {
            return responseBody.switchIfEmpty(Mono.fromSupplier(() -> new byte[0]))
                .map(bytes -> {
                    if (bytes.length == 0) {
                        return Tuples.of(bufferedResponse, responseData);
                    }

                    String content = new String(bytes, StandardCharsets.UTF_8);
                    responseData.put(CONTENT_LENGTH, Integer.toString(content.length()));
                    responseData.put(BODY, content);
                    return Tuples.of(bufferedResponse, responseData);
                });
        } else if (contentType.equalsIgnoreCase(ContentType.APPLICATION_OCTET_STREAM)
            || "avro/binary".equalsIgnoreCase(contentType)) {
            return responseBody.switchIfEmpty(Mono.fromSupplier(() -> new byte[0]))
                .map(bytes -> {
                    if (bytes.length == 0) {
                        return Tuples.of(bufferedResponse, responseData);
                    }

                    responseData.put(BODY, Base64.getEncoder().encodeToString(bytes));
                    return Tuples.of(bufferedResponse, responseData);
                });
        } else if (contentType.contains("json") || response.getHeaderValue(CONTENT_ENCODING) == null) {
            return responseBody.map(bytes -> CoreUtils.bomAwareToString(bytes, response.getHeaderValue(CONTENT_TYPE)))
                .switchIfEmpty(Mono.just(""))
                .map(content -> {
                    responseData.put(BODY, redactor.redact(content));
                    return Tuples.of(bufferedResponse, responseData);
                });
        } else {
            return responseBody.switchIfEmpty(Mono.fromSupplier(() -> new byte[0]))
                .map(bytes -> {
                    if (bytes.length == 0) {
                        return Tuples.of(bufferedResponse, responseData);
                    }

                    String content;
                    if ("gzip".equalsIgnoreCase(response.getHeaderValue(CONTENT_ENCODING))) {
                        try (GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes));
                             ByteArrayOutputStream output = new ByteArrayOutputStream()) {
                            byte[] buffer = new byte[DEFAULT_BUFFER_LENGTH];
                            int position = 0;
                            int bytesRead = gis.read(buffer, position, buffer.length);

                            while (bytesRead != -1) {
                                output.write(buffer, 0, bytesRead);
                                position += bytesRead;
                                bytesRead = gis.read(buffer, position, buffer.length);
                            }

                            content = output.toString("UTF-8");
                        } catch (IOException e) {
                            throw logger.logExceptionAsWarning(Exceptions.propagate(e));
                        }
                    } else {
                        content = new String(bytes, StandardCharsets.UTF_8);
                    }

                    responseData.remove(CONTENT_ENCODING);
                    responseData.put(CONTENT_LENGTH, Integer.toString(content.length()));

                    responseData.put(BODY, content);
                    return Tuples.of(bufferedResponse, responseData);
                });
        }
    }
}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.scrollTo = exports.easeInOutCubic = exports.reqAnimFrame = undefined;

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

exports.getDefaultTarget = getDefaultTarget;
exports.getOffsetTop = getOffsetTop;

var _getScroll = require('../_util/getScroll');

var _getScroll2 = _interopRequireDefault(_getScroll);

var _getRequestAnimationFrame = require('../_util/getRequestAnimationFrame');

var _getRequestAnimationFrame2 = _interopRequireDefault(_getRequestAnimationFrame);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

var reqAnimFrame = exports.reqAnimFrame = (0, _getRequestAnimationFrame2["default"])();
var easeInOutCubic = exports.easeInOutCubic = function easeInOutCubic(t, b, c, d) {
    var cc = c - b;
    t /= d / 2;
    if (t < 1) {
        return cc / 2 * t * t * t + b;
    }
    return cc / 2 * ((t -= 2) * t * t + 2) + b;
};
function getDefaultTarget() {
    return typeof window !== 'undefined' ? window : null;
}
function getOffsetTop(element) {
    if (!element) {
        return 0;
    }
    if (!element.getClientRects().length) {
        return 0;
    }
    var rect = element.getBoundingClientRect();
    if (rect.width || rect.height) {
        var doc = element.ownerDocument;
        var docElem = doc.documentElement;
        return rect.top - docElem.clientTop;
    }
    return rect.top;
}
function _scrollTo(href) {
    var offsetTop = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
    var target = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : getDefaultTarget;
    var callback = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : function () {};

    var scrollTop = (0, _getScroll2["default"])(target(), true);
    var targetElement = document.getElementById(href.substring(1));
    if (!targetElement) {
        return;
    }
    var eleOffsetTop = getOffsetTop(targetElement);
    var targetScrollTop = scrollTop + eleOffsetTop - offsetTop;
    var startTime = Date.now();
    var frameFunc = function frameFunc() {
        var timestamp = Date.now();
        var time = timestamp - startTime;
        window.scrollTo(window.pageXOffset, easeInOutCubic(time, scrollTop, targetScrollTop, 450));
        if (time < 450) {
            reqAnimFrame(frameFunc);
        } else {
            callback();
        }
    };
    reqAnimFrame(frameFunc);
    history.pushState(null, '', href);
}
exports.scrollTo = _scrollTo;

var AnchorHelper = function () {
    function AnchorHelper() {
        (0, _classCallCheck3["default"])(this, AnchorHelper);

        this.links = [];
        this.currentAnchor = null;
        this._activeAnchor = '';
    }

    AnchorHelper.prototype.addLink = function addLink(link) {
        if (this.links.indexOf(link) === -1) {
            this.links.push(link);
        }
    };

    AnchorHelper.prototype.getCurrentActiveAnchor = function getCurrentActiveAnchor() {
        return this.currentAnchor;
    };

    AnchorHelper.prototype.setActiveAnchor = function setActiveAnchor(component) {
        this.currentAnchor = component;
    };

    AnchorHelper.prototype.getCurrentAnchor = function getCurrentAnchor() {
        var offsetTop = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
        var bounds = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 5;

        var activeAnchor = '';
        if (typeof document === 'undefined') {
            return activeAnchor;
        }
        var linksPositions = this.links.map(function (section) {
            var target = document.getElementById(section.substring(1));
            if (target && getOffsetTop(target) < offsetTop + bounds) {
                var top = getOffsetTop(target);
                if (top <= offsetTop + bounds) {
                    return {
                        section: section,
                        top: top,
                        bottom: top + target.clientHeight
                    };
                }
            }
            return null;
        }).filter(function (section) {
            return section !== null;
        });
        if (linksPositions.length) {
            var maxSection = linksPositions.reduce(function (prev, curr) {
                return curr.top > prev.top ? curr : prev;
            });
            return maxSection.section;
        }
        return '';
    };

    AnchorHelper.prototype.scrollTo = function scrollTo(href, offsetTop) {
        var target = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : getDefaultTarget;
        var callback = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : function () {};

        _scrollTo(href, offsetTop, target, callback);
    };

    return AnchorHelper;
}();

exports["default"] = AnchorHelper;


text:
from django.conf.urls import url
from wagtail.wagtailsearch.views import queries

urlpatterns = [
    url(r"^queries/chooser/$", queries.chooser, name="queries_chooser"),
    url(r"^queries/chooser/results/$", queries.chooserresults, name="queries_chooserresults"),
]


text:
RSpec.describe Licensee::Matchers::DistZilla do
  let(:mit) { Licensee::License.find('mit') }
  let(:content) { 'license = MIT' }
  let(:file) { Licensee::Project::LicenseFile.new(content, 'dist.ini') }
  subject { described_class.new(file) }

  it 'stores the file' do
    expect(subject.file).to eql(file)
  end

  it 'has confidence' do
    expect(subject.confidence).to eql(90)
  end

  it 'matches' do
    expect(subject.match).to eql(mit)
  end

  {
    'spdx name'     => ['license = MIT', 'mit'],
    'non spdx name' => ['license = Mozilla_2_0', 'mpl-2.0']
  }.each do |description, license_declaration_and_key|
    context "with a #{description}" do
      let(:content) { license_declaration_and_key[0] }
      let(:license) { Licensee::License.find(license_declaration_and_key[1]) }

      it 'matches' do
        expect(subject.match).to eql(license)
      end
    end
  end
end


text:
'use strict'
import {
  GraphQLID,
  GraphQLList,
  GraphQLNonNull,
  GraphQLObjectType,
  GraphQLString
} from 'graphql'
import Animal from '../animals/type'
import Resolvers from './resolvers'

export default new GraphQLObjectType({
  description: `A user`,
  fields: () => ({
    email: {
      description: `The users's chosen email address.`,
      type: GraphQLString
    },
    following: {
      description: `Animals this user is currently following.`,
      resolve: Resolvers.following,
      type: new GraphQLList(Animal)
    },
    id: {
      description: `A unique identifier for this user in the humane society database.`,
      type: new GraphQLNonNull(GraphQLID)
    },
    name: {
      description: `The users's chosen name.`,
      type: new GraphQLNonNull(GraphQLString)
    },
    password: {
      description: `The users's account password.`,
      type: new GraphQLNonNull(GraphQLString)
    }
  }),
  name: `User`
})


text:
//
//  CoreData.m
//  NSRails
//
//  Created by Dan Hassin on 6/12/12.
//  Copyright (c) 2012 InContext LLC. All rights reserved.
//

#import "NSRAsserts.h"

@interface NSRRemoteObject (private_overrides)

- (Class) containerClassForRelationProperty:(NSString *)property;

@end

/** CoreData Mock Classes **/

@interface CDPost : NSRRemoteManagedObject

@property (nonatomic, strong) NSString *author, *content;
@property (nonatomic, strong) NSSet *responses;

@property BOOL shouldNotValidateUniqueness;

@end

@interface CDResponse : NSRRemoteManagedObject

@property (nonatomic, strong) NSString *content, *author;
@property (nonatomic, strong) CDPost *post;

@end

@implementation CDPost
@dynamic author, content, responses;
@synthesize shouldNotValidateUniqueness;

- (BOOL) validatesRemoteIDUniqueness
{
    if (shouldNotValidateUniqueness) {
        return NO;
    }
    return [super validatesRemoteIDUniqueness];
}

+ (NSString *) entityName
{
    return @"Post";
}

@end

@implementation CDResponse
@dynamic author, content, post;

+ (NSString *) entityName
{
    return @"Response";
}

- (BOOL) shouldOnlySendIDKeyForNestedObjectProperty:(NSString *)property
{
    return [property isEqualToString:@"post"];
}

@end

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

@interface CoreData : XCTestCase

@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;

@end

@implementation CoreData

- (void) test_exceptions
{
    [[NSRConfig defaultConfig] setManagedObjectContext:nil];

    XCTAssertThrows(([[CDPost alloc] initInserted]), @"");
    XCTAssertThrows([[NSRRemoteManagedObject alloc] initInserted], @"");

    [[NSRConfig defaultConfig] setManagedObjectContext:self.managedObjectContext];

    CDPost *p = [[CDPost alloc] initInserted];
    p.remoteID = @(15);
    [p saveContext];
}

- (void) test_crud
{
    //test server is rails 3
    [[NSRConfig defaultConfig] configureToRailsVersion:NSRRailsVersion3];

    NSError *e = nil;
    [[[NSRRequest GET] routeTo:@"404.html"] sendSynchronous:&e];
    NSRAssertNoServer([[e domain] isEqualToString:NSURLErrorDomain]);

    CDPost *p = [[CDPost alloc] initInserted];

    //shouldn't save the context
    XCTAssertTrue(p.hasChanges, @"");

    p.remoteID = @(15);

    XCTAssertTrue(p.hasChanges, @"");

    [p setPropertiesUsingRemoteDictionary:[NSDictionary dictionaryWithObjectsAndKeys:@"hi", @"author", @"hello", @"content", nil]];

    XCTAssertTrue(p.hasChanges, @"");

    XCTAssertTrue([p remoteCreate:nil], @"");
    XCTAssertTrue(p == [CDPost findObjectWithRemoteID:@(p.remoteID.integerValue)], @"should find obj with that ID (just made)");

    XCTAssertFalse(p.hasChanges, @"");

    CDResponse *r = [[CDResponse alloc] initInserted];
    r.author = @"yo";
    r.content = @"po";
    r.post = p;

    XCTAssertTrue([r remoteCreate:nil],@"");
    XCTAssertTrue(r == [CDResponse findObjectWithRemoteID:@(r.remoteID.integerValue)], @"should find obj with that ID (just made)");

    XCTAssertTrue([p remoteFetch:nil], @"");
    XCTAssertEqual(p.responses.count, (NSUInteger)1, @"");
    XCTAssertTrue([[p.responses anyObject] isKindOfClass:[CDResponse class]], @"");
    XCTAssertTrue([p.responses anyObject] == r, @"");
    XCTAssertEqual((CDPost *)[[p.responses anyObject] post], p, @"");

    p.content = @"changed!";

    XCTAssertTrue(p.isUpdated, @"");
    XCTAssertTrue([p remoteUpdate:nil], @"");
    XCTAssertFalse(p.hasChanges, @"");

    CDPost *retrieved = [CDPost findObjectWithRemoteID:@(p.remoteID.integerValue)];
    XCTAssertTrue(p == retrieved, @"");
    XCTAssertEqualObjects(retrieved.content, p.content, @"");
    XCTAssertEqualObjects(retrieved.author, p.author, @"");

    XCTAssertTrue([p remoteDestroy:nil],@"");

    XCTAssertNil([CDPost findObjectWithRemoteID:p.remoteID], @"");
}

- (void) test_finds
{
    XCTAssertNil([CDPost findObjectWithRemoteID:@(12)], @"should be nothing with rID 12");

    CDPost *p = [CDPost objectWithRemoteDictionary:@{@"id":@12}];

    XCTAssertNotNil(p, @"");
    XCTAssertEqualObjects(p.remoteID, @(12), @"");
    XCTAssertTrue(p.hasChanges, @"");

    CDPost *p2 = [CDPost findObjectWithRemoteID:@(12)];
    XCTAssertNotNil(p2,@"");
    XCTAssertTrue(p2 == p, @"");
    XCTAssertEqualObjects(p2.remoteID, @(12), @"");
    XCTAssertTrue(p2.hasChanges, @"");

    CDPost *p3 = [CDPost objectWithRemoteDictionary:@{@"id":@12,@"content":@"hi"}];

    XCTAssertNotNil(p3,@"");
    XCTAssertTrue(p3 == p2,@"");
    XCTAssertEqualObjects(p3.content, @"hi", @"");
    XCTAssertTrue(p3.hasChanges, @"");

    CDPost *p4 = [CDPost objectWithRemoteDictionary:@{@"content":@"hi"}];

    XCTAssertNotNil(p4,@"");
    XCTAssertEqualObjects(p4.remoteID, @(0));
    XCTAssertEqualObjects(p4.content, @"hi", @"");
    XCTAssertTrue(p4.hasChanges, @"");
}

- (void) test_remote_id_uniqueness_validation
{
    CDPost *p = [[CDPost alloc] initInserted];
    p.remoteID = @(99);

    XCTAssertNil([p saveContext]);

    CDPost *p2 = [[CDPost alloc] initInserted];
    p2.remoteID = @(99);

    XCTAssertNotNil([p2 saveContext]);
}

- (void) test_no_remote_id_uniqueness_validation
{
    CDPost *p = [[CDPost alloc] initInserted];
    p.remoteID = @(99);

    XCTAssertNil([p saveContext]);

    CDPost *p2 = [[CDPost alloc] initInserted];
    p2.remoteID = @(99);
    p2.shouldNotValidateUniqueness = YES;

    XCTAssertNil([p2 saveContext]);
}

- (void) test_nested_class_override
{
    CDPost *p = [CDPost objectWithRemoteDictionary:@{@"id":@12}];
    CDResponse *r = [CDResponse objectWithRemoteDictionary:@{@"id":@12}];

    Class responseClass = [p nestedClassForProperty:@"responses"];
    XCTAssertEqual(responseClass, [CDResponse class]);

    Class postClass = [r nestedClassForProperty:@"post"];
    XCTAssertEqual(postClass, [CDPost class]);
}

- (void) test_container_class_override
{
    CDPost *p = [CDPost objectWithRemoteDictionary:@{@"id":@12}];

    Class unorderedClass = [p containerClassForRelationProperty:@"responses"];
    XCTAssertEqual(unorderedClass, [NSMutableSet class]);

    Class orderedClass = [p containerClassForRelationProperty:@"orderedResponses"];
    XCTAssertEqual(orderedClass, [NSMutableOrderedSet class]);
}

/////////////////////////////////////////////

- (void) setUp
{
    NSBundle *bundle = [NSBundle bundleForClass:[self class]];
    NSURL *url = [bundle URLForResource:@"Test" withExtension:@"momd"];
    self.managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:url];

    self.persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.managedObjectModel];
    [self.persistentStoreCoordinator addPersistentStoreWithType:NSInMemoryStoreType configuration:nil URL:nil options:nil error:NULL];

    self.managedObjectContext = [[NSManagedObjectContext alloc] init];
    [self.managedObjectContext setPersistentStoreCoordinator:self.persistentStoreCoordinator];

    [[NSRConfig defaultConfig] setManagedObjectContext:self.managedObjectContext];
}

+ (void)setUp
{
    [[NSRConfig defaultConfig] setRootURL:[NSURL URLWithString:@"http://localhost:3000"]];
    [[NSRConfig defaultConfig] setBasicAuthUsername:@"NSRails"];
    [[NSRConfig defaultConfig] setBasicAuthPassword:@"iphone"];
}

@end


text:
<?php

namespace Riak\Client\Command\MapReduce\Builder;

use Riak\Client\Core\Query\RiakLocation;
use Riak\Client\Command\MapReduce\Specification;
use Riak\Client\Command\MapReduce\BucketKeyMapReduce;
use Riak\Client\Command\MapReduce\Input\BucketKeyInput;
use Riak\Client\Command\MapReduce\Input\BucketKey\Input;

/**
 * Used to construct a BucketKeyMapReduce command.
 *
 * @author Fabio B. Silva <fabio.bat.silva@gmail.com>
 */
class BucketKeyMapReduceBuilder extends Builder
{
    /**
     * @var \Riak\Client\Command\MapReduce\Input\BucketKey\Input[]
     */
    private $inputs;

    /**
     * @param \Riak\Client\Command\MapReduce\Input\BucketKey\Input[] $inputs
     */
    public function __construct(array $inputs = [])
    {
        $this->inputs = $inputs;
    }

    /**
     * @param \Riak\Client\Core\Query\RiakLocation $location
     * @param mixed                                $data
     *
     * @return \Riak\Client\Command\MapReduce\Input\BucketKeyInput
     */
    public function withLocation(RiakLocation $location, $data = null)
    {
        $this->inputs[] = new Input($location, $data);

        return $this;
    }

    /**
     * Build a Bucket Key Map-Reduce command object
     *
     * @return \Riak\Client\Command\MapReduce\Input\BucketKeyInput
     */
    public function build()
    {
        $input = new BucketKeyInput($this->inputs);
        $spec  = new Specification($input, $this->phases, $this->timeout);

        return new BucketKeyMapReduce($spec);
    }
}


text:
title: "Leading by Omission : une conférence Ricardo Semler au MIT"
date:  2016-01-25 21:56
layout: post
category: ["conférence"]
embed_youtube: JJ0FQR2gXe0
illustration: /images/JJ0FQR2gXe0.jpg
tags: ["Ricardo Semler", "Semco"]
---

Conférence de Ricardo Semler au MIT réalisée le 22 septembre 2005.


text:
using System.Data;

namespace Shuttle.Esb.Management.Subscriptions
{
	public interface ISubscriptionQuery
	{
		DataTable All();
		DataTable AllUris();
		DataTable MessageTypes(string inboxWorkQueueUri);
		bool HasSubscriptionStructures();
		void Remove(string inboxWorkQueueUri, string messageType);
		bool Contains(string inboxWorkQueueUri, string messageType);
		void Add(string inboxWorkQueueUri, string messageType);
	}
}


text:
CREATE OR REPLACE FUNCTION _CDB_UserQuotaInBytes()
RETURNS int8 AS
$$
    -- 250 MB
    SELECT (250 * 1024 * 1024)::int8;
$$ LANGUAGE sql IMMUTABLE;

CREATE OR REPLACE FUNCTION CDB_UserDataSize(schema_name TEXT)
RETURNS bigint AS
$$
BEGIN
    -- 100 MB
    RETURN 100 * 1024 * 1024;
END;
$$ LANGUAGE 'plpgsql' VOLATILE;


text:
tags: perl
layout: post
title: "brian on Perl certification"
---

Perl Certifications are a hot topic (again) - <tt>brian d foy</tt> doesn't like Perl certification and I couldn't agree more. I recognize that it's difficult for companies to ascertain if someone actually knows what they're talking about in the absence of honest references. (Which, BTW, is a shameful side-effect of our lawsuit crazy culture.) But IMO certification is just another method The Man uses to treat you like a cog that can be measured by numbers rather than as a human being.

Plus: how hardcore is brian to post this from Iraq? Wow.


text:
<?xml-stylesheet type="text/xsl" href="/style/testcase.xsl"?>
<t:test xmlns:t="http://xproc.org/ns/testsuite"
        xmlns:p="http://www.w3.org/ns/xproc"
        xmlns:c="http://www.w3.org/ns/xproc-step"
        xmlns:err="http://www.w3.org/ns/xproc-error"
	error="err:XC0054">

<t:title>Test err:XC0054 - #001</t:title>

<t:input port="source"
	 href="../doc/docbook-invalid.xml"/>

<t:input port="schema"
	 href="../doc/docbook.sch"/>

<t:pipeline>
<p:declare-step version='1.0' name="main" exclude-inline-prefixes="t c err">
<p:input port="parameters" kind="parameter"/>
<p:input port="source"/>
<p:input port="schema"/>
<p:output port="result">
  <p:pipe step="schematron" port="report"/>
</p:output>

<p:validate-with-schematron name="schematron" assert-valid="true">
  <p:input port="source">
    <p:pipe step="main" port="source"/>
  </p:input>
  <p:input port="schema">
    <p:pipe step="main" port="schema"/>
  </p:input>
</p:validate-with-schematron>

<p:sink/>

</p:declare-step>
</t:pipeline>

</t:test>