text:
<?php

namespace ETAP\EmpruntBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use ETAP\EmpruntBundle\Entity\Concession;
use ETAP\EmpruntBundle\Form\ConcessionType;

/**
 * Concession controller.
 *
 */
class ConcessionController extends Controller
{
    /**
     * Lists all Concession entities.
     *
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('EmpruntBundle:Concession')->findAll();

        return $this->render('EmpruntBundle:Concession:index.html.twig', array(
            'entities' => $entities,
        ));
    }

    /**
     * Creates a new Concession entity.
     *
     */
    public function createAction(Request $request)
    {
        $entity  = new Concession();
        $form = $this->createForm(new ConcessionType(), $entity);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('concession_show', array('id' => $entity->getId())));
        }

        return $this->render('EmpruntBundle:Concession:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Displays a form to create a new Concession entity.
     *
     */
    public function newAction()
    {
        $entity = new Concession();
        $form   = $this->createForm(new ConcessionType(), $entity);

        return $this->render('EmpruntBundle:Concession:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Finds and displays a Concession entity.
     *
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('EmpruntBundle:Concession')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Concession entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return $this->render('EmpruntBundle:Concession:show.html.twig', array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),        ));
    }

    /**
     * Displays a form to edit an existing Concession entity.
     *
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('EmpruntBundle:Concession')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Concession entity.');
        }

        $editForm = $this->createForm(new ConcessionType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        return $this->render('EmpruntBundle:Concession:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Edits an existing Concession entity.
     *
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('EmpruntBundle:Concession')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Concession entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createForm(new ConcessionType(), $entity);
        $editForm->bind($request);

        if ($editForm->isValid()) {
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('concession_edit', array('id' => $id)));
        }

        return $this->render('EmpruntBundle:Concession:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Deletes a Concession entity.
     *
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('EmpruntBundle:Concession')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Concession entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('concession'));
    }

    /**
     * Creates a form to delete a Concession entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder(array('id' => $id))
            ->add('id', 'hidden')
            ->getForm()
        ;
    }
}


text:
<?php

namespace WS\ReduceMigrations\Console\Formatter;

use WS\ReduceMigrations\Console\Console;

class Table {

    private $rows;
    private $title;
    private $console;

    /**
     * Table constructor.
     *
     * @param string $title
     * @param Console $console
     */
    public function __construct($title, $console) {
        $this->title = $title;
        $this->console = $console;
    }

    /**
     * @param $row
     * @param $color
     */
    public function addColorRow($row, $color) {
        $currentRow = array();
        foreach ($row as $item) {
            $currentRow[] = $this->console->colorize($item, $color);
        }
        $this->rows[] = $currentRow;
    }

    public function addRow() {
        $this->rows[] = func_get_args();
    }

    public function __toString() {
        $result = '';
        $result .= $this->title . "\n";
        $maxLen = array();
        foreach ($this->rows as $row) {
            foreach ($row as $index => $value) {
                if (!$maxLen[$index]) {
                    $maxLen[$index] = iconv_strlen($value);
                }
                if ($maxLen[$index] < iconv_strlen($value)) {
                    $maxLen[$index] = iconv_strlen($value);
                }
            }
        }

        foreach ($this->rows as $row) {
            foreach ($row as $index => $value) {
                $result .= mb_str_pad($value, $maxLen[$index] + 3);
            }
            $result .= "\n";
        }

        return $result;
    }
}

function mb_str_pad($input, $pad_length, $pad_string=' ', $pad_type=STR_PAD_RIGHT) {
    if (function_exists('mb_strlen')) {
        $diff = strlen($input) - mb_strlen($input);
        return str_pad($input, $pad_length + $diff, $pad_string, $pad_type);
    }
    return str_pad($input, $pad_length, $pad_string, $pad_type);
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * @file - sys_arch.c
 * System Architecture support routines for Sitara devices.
 *
 */

/*
 * Copyright (c) 2001-2003 Swedish Institute of Computer Science.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
 * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
 * OF SUCH DAMAGE.
 *
 * This file is part of the lwIP TCP/IP stack.
 *
 * Author: Adam Dunkels <adam@sics.se>
 *
 */

/* Copyright (c) 2010 Texas Instruments Incorporated */

/* lwIP includes. */
#include "lwip/opt.h"
#include "lwip/sys.h"

#if SYS_LIGHTWEIGHT_PROT

/* Sitara header files required for this interface driver. */
#include "interrupt.h"

/**
 * This function is used to lock access to critical sections when lwipopt.h
 * defines SYS_LIGHTWEIGHT_PROT. It disables interrupts and returns a value
 * indicating the interrupt enable state when the function entered. This
 * value must be passed back on the matching call to sys_arch_unprotect().
 *
 * @return the interrupt level when the function was entered.
 */
sys_prot_t
sys_arch_protect(void)
{
  sys_prot_t status;
  status = (IntMasterStatusGet() & 0xFF);

  IntMasterIRQDisable();
  return status;
}

/**
 * This function is used to unlock access to critical sections when lwipopt.h
 * defines SYS_LIGHTWEIGHT_PROT. It enables interrupts if the value of the lev
 * parameter indicates that they were enabled when the matching call to
 * sys_arch_protect() was made.
 *
 * @param lev is the interrupt level when the matching protect function was
 * called
 */
void
sys_arch_unprotect(sys_prot_t lev)
{
  /* Only turn interrupts back on if they were originally on when the matching
     sys_arch_protect() call was made. */
  if((lev & 0x80) == 0) {
    IntMasterIRQEnable();
  }
}

#endif /* SYS_LIGHTWEIGHT_PROT */


text:
#include <aws/email/model/Content.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

#include <utility>

using namespace Aws::Utils::Xml;
using namespace Aws::Utils;

namespace Aws
{
namespace SES
{
namespace Model
{

Content::Content() :
    m_dataHasBeenSet(false),
    m_charsetHasBeenSet(false)
{
}

Content::Content(const XmlNode& xmlNode) :
    m_dataHasBeenSet(false),
    m_charsetHasBeenSet(false)
{
  *this = xmlNode;
}

Content& Content::operator =(const XmlNode& xmlNode)
{
  XmlNode resultNode = xmlNode;

  if(!resultNode.IsNull())
  {
    XmlNode dataNode = resultNode.FirstChild("Data");
    if(!dataNode.IsNull())
    {
      m_data = StringUtils::Trim(dataNode.GetText().c_str());
      m_dataHasBeenSet = true;
    }
    XmlNode charsetNode = resultNode.FirstChild("Charset");
    if(!charsetNode.IsNull())
    {
      m_charset = StringUtils::Trim(charsetNode.GetText().c_str());
      m_charsetHasBeenSet = true;
    }
  }

  return *this;
}

void Content::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const
{
  if(m_dataHasBeenSet)
  {
      oStream << location << index << locationValue << ".Data=" << StringUtils::URLEncode(m_data.c_str()) << "&";
  }

  if(m_charsetHasBeenSet)
  {
      oStream << location << index << locationValue << ".Charset=" << StringUtils::URLEncode(m_charset.c_str()) << "&";
  }

}

void Content::OutputToStream(Aws::OStream& oStream, const char* location) const
{
  if(m_dataHasBeenSet)
  {
      oStream << location << ".Data=" << StringUtils::URLEncode(m_data.c_str()) << "&";
  }
  if(m_charsetHasBeenSet)
  {
      oStream << location << ".Charset=" << StringUtils::URLEncode(m_charset.c_str()) << "&";
  }
}

} // namespace Model
} // namespace SES
} // namespace Aws


text:
require "benchmark"

def all_prime_factors(num)
  prime_factors = []
  if prime?(num) == true
    return "number is prime"
  else
    until prime?(num) == true
      lowest_factor = lowest_factor(num)
      num = num / lowest_factor
      # if prime?(lowest_factor) == true
      prime_factors << lowest_factor
      # end
      # if prime?(num) == true
      # end
    end
    prime_factors << num
  end
  return prime_factors
end

def prime?(num)
  factors = []
  range = (2..num-1).to_a

  if num == 1
    return false

  elsif num == 2
    return true

  elsif lowest_factor(num) == nil
    return true

  else
    range.each do | poss_factor |
      if num % poss_factor == 0
        factors << poss_factor
      end
    end

    if factors.length == 0
      return true
    else
      return false
    end
  end
end

def lowest_factor(num)
  range = (2..num-1).to_a
  return range.find { |poss_factor| (num % poss_factor) == 0 } #finds the first possible factor
end

puts Benchmark.measure{all_prime_factors(123123123)}


text:
package com.intel.analytics.bigdl.dllib.nn.tf

import com.intel.analytics.bigdl.dllib.nn.abstractnn.Activity
import com.intel.analytics.bigdl.dllib.nn.ops.Operation
import com.intel.analytics.bigdl.dllib.tensor.TensorNumericMath.TensorNumeric
import com.intel.analytics.bigdl.dllib.utils.T

import scala.reflect.ClassTag

private[bigdl] class NoOp[T: ClassTag]()
  (implicit ev: TensorNumeric[T]) extends Operation[Activity, Activity, T] with WithoutInput{

  private val data = T()

  override def updateOutput(input: Activity): Activity = data
}


text:
@charset "utf-8";

/* ---------- BrandList ---------- */

div.brandList .list {
	margin-bottom: 10px;
	-webkit-border-radius: 3px;
	-moz-border-radius: 3px;
	border-radius: 3px;
	border: 1px solid #e8e8e8;
}

div.brandList .list li {
	width: 177px;
	height: 80px;
	float: left;
	text-align: center;
	border-bottom: solid 1px #f1f1f1;
}

div.brandList .list li:hover {
	border-bottom-color: #d6d6d6;
}

div.brandList .list li.last {
	border-bottom: none;
}

div.brandList .list li a {
	outline: none;
	blr: expression(this.hideFocus = true);
}

div.brandList .list li img {
	width: 97px;
	height: 50px;
}

div.brandList .list li span {
	line-height: 20px;
	display: block;
	text-align: center;
}

/* ---------- BrandContent ---------- */

div.brandContent .top {
	line-height: 60px;
	margin-bottom: 10px;
	border: solid 1px #e4e4e4;
}

div.brandContent .top img {
	vertical-align: middle;
}

div.brandContent .top strong {
	font-size: 14px;
	font-weight: bold;
	margin: 0px 10px;
}

div.brandContent .introduction {
	line-height: 30px;
	margin-bottom: 10px;
}

div.brandContent .introduction .title {
	height: 29px;
	line-height: 29px;
	margin-bottom: 10px;
	background-color: #d3d3d3;
}

div.brandContent .introduction .title strong {
	width: 120px;
	display: block;
	float: left;
	padding-left: 20px;
	color: #ffffff;
	font-size: 14px;
	font-weight: bold;
	font-family: "Microsoft YaHei";
	background-color: #909090;
}

div.brandContent .introduction .title span {
	width: 70px;
	display: block;
	float: left;
	background-color: #aaa8a9;
}

div.brandContent .product {
	height: 36px;
	margin-bottom: 10px;
	overflow: hidden;
}

div.brandContent .product ul {
	height: 30px;
	padding: 2px 1px;
	border: 1px solid #e4e4e4;
}

div.brandContent .product li {
	height: 30px;
	line-height: 30px;
	display: block;
	float: left;
	padding: 0px 20px;
	border-right: 1px solid #f1f1f1;
	border-left: 1px solid #ffffff;
}

div.brandContent .product .title {
	background-color: #f1f1f1;
}


text:
require_relative './integration_example_group'

module Bosh::Spec
  module BlockingDeployHelper
    extend IntegrationExampleGroup
    extend IntegrationSandboxHelpers

    def with_blocking_deploy(options={})
      first_deployment_manifest = Bosh::Spec::NetworkingManifest.deployment_manifest(name: 'blocking', instances: 1, job: 'job_with_blocking_compilation')
      task_id = Bosh::Spec::DeployHelper.start_deploy(first_deployment_manifest)

      director.wait_for_first_available_vm

      compilation_vm = director.vms.first
      expect(compilation_vm).to_not be_nil

      yield(task_id)

      task_id
    ensure
      if compilation_vm
        compilation_vm.unblock_package

        unless options[:skip_task_wait]
          _, first_success = Bosh::Spec::DeployHelper.wait_for_task(task_id)
          expect(first_success).to eq(true)
        end
      end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<ram-component manifest-version="2.0"
               name="ModelerModule" version="8" release="4" clevel="5" metamodel="9023">
    <description>
        <![CDATA[]]>
    </description>
    <dependencies>
    </dependencies>
    <contributors>
    </contributors>
    <roots>
      <root metaclass="ModuleComponent" name="ModelerModule" uuid="00000000-0000-2710-0000-000000000000"></root>
    </roots>
</ram-component>


text:
package org.jboss.weld.tests.event.observer.transactional;

import java.lang.annotation.Annotation;
import javax.annotation.Resource;
import javax.ejb.EJBException;
import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import static javax.ejb.TransactionManagementType.BEAN;
import javax.enterprise.inject.Default;
import javax.enterprise.inject.spi.BeanManager;
import javax.inject.Inject;
import javax.inject.Named;
import javax.transaction.UserTransaction;

@Stateless
@TransactionManagement(BEAN)
@Named
@Default
public class DogAgent implements Agent {

    public static String EVENT_FIRED = "afterEventFired";

    @Resource
    private UserTransaction userTransaction;

    @Inject
    private BeanManager jsr299Manager;

    @Override
    public void sendInTransaction(Object event, Annotation... annot) {
        try {
            userTransaction.begin();
            jsr299Manager.fireEvent(event, annot);
            Actions.add(EVENT_FIRED);
            userTransaction.commit();
        } catch (EJBException ejbException) {
            throw ejbException;
        } catch (Exception e) {
            throw new EJBException("Transaction failure", e);
        }
    }

    @Override
    public void sendInTransactionAndFail(Object event) throws Exception {
        userTransaction.begin();
        jsr299Manager.fireEvent(event);
        Actions.add(EVENT_FIRED);
        userTransaction.rollback();
    }

    @Override
    public void sendOutsideTransaction(Object event) {
        jsr299Manager.fireEvent(event);
        Actions.add(EVENT_FIRED);
    }
}


text:
function makePoint(x) {
    return {
        get x() {
            return x;
        }
    };
}
;
var point = makePoint(2);
var x = point.x;

////[declFileObjectLiteralWithOnlyGetter.d.ts]
declare function makePoint(x: number): {
    x: number;
};
declare var point: {
    x: number;
};
declare var x: number;


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>ReactiveX - Intro</title>

    <link href="/css/bootstrap.min.css" rel="stylesheet" />

    <link href="/css/prism.css" rel="stylesheet" />

    <link rel="stylesheet" href="/css/syntax.css" />

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            Toggle navigation

          </button>
           ReactiveX

Introduction

                Docs

Observable

Operators

Subject

Scheduler

                Languages

RxJava

RxJS

Rx.NET

RxScala

RxClojure

Others

                Resources

Tutorials

                Community

GitHub

Twitter

Others

ReactiveX

 ReactiveX is a library for composing asynchronous and event-based programs by using observable sequences.

 It extends the observer pattern to support
 sequences of data and/or events and adds operators that allow you to compose sequences together declaratively
 while abstracting away concerns about things like low-level threading, synchronization, thread-safety,
 concurrent data structures, and non-blocking I/O.

Observables fill the gap by being the ideal way to access asynchronous sequences of multiple items

	single items	multiple items

synchronous	T getData()	Iterable<T> getData()

asynchronous	Future<T> getData()	Observable<T> getData()

Why Use Observables?

 The ReactiveX Observable model allows you to treat streams of asynchronous events with the same sort of
 simple, composable operations that you use for collections of data items like arrays. It frees you from
 tangled webs of callbacks, and thereby makes your code more readable and less prone to bugs.

Observables Are Composable

 Techniques like Java
 Futures are straightforward to use for a single level of
 asynchronous execution but they start to add non-trivial
 complexity when they're nested.

 It is difficult to use Futures to optimally
 compose conditional asynchronous execution flows (or impossible, since latencies of each request vary at
 runtime). This can be done,
 of course, but it quickly becomes complicated (and thus error-prone) or it prematurely blocks on
 Future.get(), which eliminates the benefit of asynchronous execution.

 ReactiveX Observables, on the other hand, are intended for
 composing flows and sequences of
 asynchronous data.

Observables Are Flexible

 ReactiveX Observables support not just the emission of single scalar values (as Futures do), but also of
 sequences of values or even infinite streams. Observable is a single abstraction that can be used
 for any of these use cases. An Observable has all of the flexibility and elegance associated with its
 mirror-image cousin the Iterable.

An Observable is the asynchronous/push “dual” to the synchronous/pull Iterable

event	Iterable (pull)	Observable (push)

retrieve data	T next()	onNext(T)

discover error	throws Exception	onError(Exception)

complete	!hasNext()	onCompleted()

Observables Are Less Opinionated

 ReactiveX is not biased toward some particular source of concurrency or asynchronicity. Observables can be
 implemented using thread-pools, event loops, non-blocking I/O, actors (such as from Akka), or whatever
 implementation suits your needs, your style, or your expertise. Client code treats all of its interactions with
 Observables as asynchronous, whether your underlying implementation is blocking or non-blocking and however you
 choose to implement it.

How is this Observable implemented?

public Observable<data> getData();

From the Observer’s point of view, it doesn’t matter!

does it work synchronously on the same thread as the caller?

does it work asynchronously on a distinct thread?

does it divide its work over multiple threads that may return data to the caller in any order?

does it use an Actor (or multiple Actors) instead of a thread pool?

does it use NIO with an event-loop to do asynchronous network access?

does it use an event-loop to separate the work thread from the callback thread?

 And importantly: with ReactiveX you can later change your mind, and radically change the underlying nature of
 your Observable implementation, without breaking the consumers of your Observable.

Callbacks Have Their Own Problems

 Callbacks solve the problem of premature blocking on Future.get() by not allowing anything to
 block. They are naturally efficient because they execute when the response is ready.

 But as with Futures, while callbacks are easy to use with a single level of asynchronous execution,
 with nested composition they become unwieldy.

ReactiveX Is a Polyglot Implementation

 ReactiveX is currently implemented in a variety of languages, in ways that respect those languages’
 idioms, and more languages are being added at a rapid clip.

Reactive Programming

 ReactiveX provides a collection of operators with which you can
 filter, select, transform, combine, and compose Observables. This allows for efficient execution and
 composition.

 You can think of the Observable class as a "push" equivalent to
 Iterable, which is a "pull."
 With an Iterable, the consumer pulls values from the producer and the thread blocks until those values arrive.
 By contrast, with an Observable the producer pushes values to the consumer whenever values are available. This
 approach is more flexible, because values can arrive synchronously or asynchronously.

Example code showing how similar high-order functions can be applied to an Iterable and an Observable

Iterable	Observable

getDataFromLocalMemory()
  .skip(10)
  .take(5)
  .map({ s -> return s + " transformed" })
  .forEach({ println "next => " + it })

getDataFromNetwork()
  .skip(10)
  .take(5)
  .map({ s -> return s + " transformed" })
  .subscribe({ println "onNext => " + it })

 The Observable type adds two missing semantics to the
 Gang of Four's Observer pattern, to match those that are available in the Iterable type:

the ability for the producer to signal to the consumer that there is no more data available (a foreach loop
     on an Iterable completes and returns normally in such a case; an Observable calls its observer’s
     onCompleted method)

the ability for the producer to signal to the consumer that an error has occurred (an Iterable throws an
     exception if an error takes place during iteration; an Observable calls its observer’s
     onError method)

 With these additions, ReactiveX harmonizes the Iterable and Observable types. The only difference between them
 is the direction in which the data flows. This is very important because now any operation you can perform on
 an Iterable, you can also perform on an Observable.

Documentation

Observable

Operators

Subject

Scheduler

Languages

RxJava

RxJS

Rx.NET

RxScala

RxClojure

Others

Resources

Tutorials

Community

GitHub

Twitter

Others

            ReactiveX is a collection of open source projects. The content of this
            page is licensed under Creative Commons Attribution 3.0 License, and
            code samples are licensed under the BSD License.

    <link rel="import" href="/polymer/components/paper-tabs/paper-tabs.html" />

    <link rel="import" href="/polymer/elements/code-snippet.html" />
    <link rel="import" href="/polymer/elements/tabs-panel.html" />
    <link rel="import" href="/polymer/elements/tab-code.html" />


text:
All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to
[Semantic Versioning](http://semver.org/spec/v2.0.0.html).

## [Unreleased]
### Added
- Contribution and changelog files

## [1.0.2] - 2017-09-17
### Changed
- Updated license in `composer.json` to `MIT`

## [1.0.1] - 2017-09-17
### Changed
- Updated docs and other small cleanup (no breaking changes)

## 1.0.0 - 2017-09-17
### Added
- Initial release! See the documentation for features & installation instructions.

[Unreleased]: https://github.com/Stockbase-Connect/magento2-module/compare/1.0.2...HEAD
[1.0.2]: https://github.com/Stockbase-Connect/magento2-module/compare/1.0.1...1.0.2
[1.0.1]: https://github.com/Stockbase-Connect/magento2-module/compare/1.0.0...1.0.1


text:
#ifdef HAVE_CONFIG_H
#include "../../../../ext_config.h"
#endif

#include <php.h>
#include "../../../../php_ext.h"
#include "../../../../ext.h"

#include <Zend/zend_operators.h>
#include <Zend/zend_exceptions.h>
#include <Zend/zend_interfaces.h>

#include "kernel/main.h"

/**
 * Division by zero exception
 */
ZEPHIR_INIT_CLASS(ZendFramework_Math_BigInteger_Exception_DivisionByZeroException) {

	ZEPHIR_REGISTER_CLASS_EX(Zend\\Math\\BigInteger\\Exception, DivisionByZeroException, zendframework, math_biginteger_exception_divisionbyzeroexception, zendframework_math_biginteger_exception_runtimeexception_ce, NULL, 0);

	return SUCCESS;

}


text:
import os, mmap
from gppylib.test.behave_utils.utils import drop_database_if_exists, drop_table_if_exists

@given('database "{dbname}" does not exist')
def impl(context, dbname):
    drop_database_if_exists(context, dbname)

@given('the file "{file_name}" does not exist')
def impl(context, file_name):
    if os.path.isfile(file_name):
        os.remove(file_name)

@given('the file "{file_name}" exists and contains "{sql_query}"')
def impl(context, file_name, sql_query):
    if os.path.isfile(file_name):
        os.remove(file_name)
    file_dir = os.path.dirname(file_name)
    if not os.path.exists(file_dir):
        os.makedirs(file_dir)
    with open(file_name, 'w') as query_f:
            query_f.writelines(sql_query)

@given('the table "{rel_name}" does not exist in database "{db_name}"')
def impl(context, rel_name, db_name):
    drop_table_if_exists(context, rel_name, db_name)

@then('minirepro error should contain {output}')
def impl(context, output):
    pat = re.compile(output)
    if not pat.search(context.error_message):
        err_str = "Expected stderr string '%s', but found:\n'%s'" % (output, context.error_message)
        raise Exception(err_str)

@then('the output file "{output_file}" should exist')
def impl(context, output_file):
    if not os.path.isfile(output_file):
        err_str = "The output file '%s' does not exist.\n" % output_file
        raise Exception(err_str)

@then('the output file "{output_file}" should contain "{str_before}" before "{str_after}"')
def impl(context, output_file, str_before, str_after):
    with open(output_file, 'r') as output_f:
        s = mmap.mmap(output_f.fileno(), 0, access=mmap.ACCESS_READ)
        pos_before = s.find(str_before)
        pos_after = s.find(str_after)
        if pos_before == -1:
            raise Exception('%s not found.' % str_before)
        if pos_after == -1:
            raise Exception('%s not found.' % str_after)
        if pos_before >= pos_after:
            raise Exception('%s not before %s.' % (str_before, str_after))

@then('the output file "{output_file}" should contain "{search_str}"')
def impl(context, output_file, search_str):
    with open(output_file, 'r') as output_f:
        s = mmap.mmap(output_f.fileno(), 0, access=mmap.ACCESS_READ)
        if s.find(search_str) == -1:
            raise Exception('%s not found.' % search_str)

@then('the output file "{output_file}" should not contain "{search_str}"')
def impl(context, output_file, search_str):
    with open(output_file, 'r') as output_f:
        s = mmap.mmap(output_f.fileno(), 0, access=mmap.ACCESS_READ)
        if s.find(search_str) != -1:
            raise Exception('%s should not exist.' % search_str)

@then('the output file "{output_file}" should be loaded to database "{db_name}" without error')
def impl(context, output_file, db_name):
    drop_database_if_exists(context, db_name)
    create_database_if_not_exists(context, db_name)
    with open(output_file, "r") as fin:
        sql_command = fin.read().replace('\\connect ', '--\\connect ')
    with open(output_file, "w") as fout:
        fout.writelines(sql_command)
    run_gpcommand(context, 'psql -d %s -f %s' % (db_name, output_file))
    if 'ERROR:' in context.error_message:
        raise Exception('Database %s failed to run %s, error message: %s' % (db_name, output_file, context.error_message))

@then('the file "{query_file}" should be executed in database "{db_name}" without error')
def impl(context, query_file, db_name):
    run_gpcommand(context, 'psql -d %s -f %s' % (db_name, query_file))
    if 'ERROR:' in context.error_message:
        raise Exception('Database %s failed to run %s, error message: %s' % (db_name, query_file, context.error_message))
    drop_database_if_exists(context, db_name)


text:
package edu.cmu.cs.stage3.alice.core.question;

public class ScriptDefinedNumber extends AbstractScriptDefinedObject {
	public Class getValueClass() {
		return Number.class;
	}
	public Number getNumberValue() {
		return (Number)getValue();
	}
}


text:
package yalantis.com.sidemenu.sample.network.service;

import yalantis.com.sidemenu.sample.network.model.myteam.Team;

/**
 * Created by TheAppExperts on 25/10/2017.
 */

public interface OnPreviousFixtureClickListener {
    void onItemClick(Team team);
    void onItemUpClick(Team team);
}


text:
package me.chanjar;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication(exclude = { ArtemisAutoConfiguration.class })
@EnableScheduling
public class Application extends SpringBootServletInitializer {

  @Override
  protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(Application.class);
  }

  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }

}


text:
import sys
import struct

HEADER_STRING = "_A2ins_"

class BitReader:
	def __init__(self, data):
		self.data = data
		self.index = 0
		self.byte = 0
		self.byte_bit = 0

	def read_byte(self):
		if self.index >= len(self.data):
			raise IndexError("Reached end of decompress stream " +
			                 "(%i bytes)" % len(self.data))
		result, = struct.unpack("B", self.data[self.index:self.index+1])
		self.index += 1
		return result

	def read_bit(self):
		if self.byte_bit <= 0:
			self.byte = self.read_byte()
			self.byte_bit = 7
		else:
			self.byte_bit -= 1

		if (self.byte & (1 << self.byte_bit)) != 0:
			result = 1
		else:
			result = 0

		return result

	def read_bits(self, n):
		result = 0

		for i in range(n):
			result = (result << 1) + self.read_bit()

		return result

def read_gamma(reader):
	result = 1

	while True:
		result = (result << 1) | reader.read_bit()

		if reader.read_bit() == 0:
			break

	return result

def decompress(data, data_len):
	reader = BitReader(data)
	result = []
	lwm = 0
	last_offset = 0

	# First byte is an implied straight copy.
	result.append(reader.read_byte())

	while True:
		if reader.read_bit():
			if reader.read_bit():
				if reader.read_bit():
					# 111 = Copy byte from history,
					# up to 15 bytes back.
					#print "111 copy"

					offset = reader.read_bits(4)

					if offset == 0:
						result.append(0)
					else:
						b = result[len(result) - offset]
						result.append(b)

					lwm = 0
				else:
					#print "110 copy"
					# 110 = Copy 2-3 bytes from
					# further back in history

					offset = reader.read_byte()
					count = 2 + (offset & 0x01)
					offset = offset >> 1

					if offset == 0:
						break

					index = len(result) - offset
					for i in range(count):
						result += result[index:index+1]
						index += 1

					last_offset = offset
					lwm = 1
			else:
				# 10 = Copy from further away...

				offset = read_gamma(reader)

				if lwm == 0 and offset == 2:
					#print "10 copy type 1"
					count = read_gamma(reader)
					index = len(result) - last_offset
					for i in range(count):
						result += result[index:index+1]
						index += 1
				else:
					#print "10 copy type 2"
					if lwm == 0:
						offset -= 3
					else:
						offset -= 2

					offset = offset * 256 \
					       + reader.read_byte()

					count = read_gamma(reader)

					if offset >= 32000:
						count += 1
					if offset >= 1280:
						count += 1
					if offset < 128:
						count += 2

					index = len(result) - offset
					for i in range(count):
						result += result[index:index+1]
						index += 1

					last_offset = offset

				lwm = 1

		else:
			#print "Single byte output"

			# 0 = Straight-through byte copy.
			result.append(reader.read_byte())
			lwm = 0

		#print "len: %i" % len(result)

	return struct.pack("%iB" % len(result), *result)

FIELDS = [
	"m_am_vibrato_eg",
	"c_am_vibrato_eg",
	"m_ksl_volume",
	"c_ksl_volume",
	"m_attack_decay",
	"c_attack_decay",
	"m_sustain_release",
	"c_sustain_release",
	"m_waveform",
	"c_waveform",
	"feedback_fm",
	"panning",
	"finetune",
	"voice_type",
]

def decode_type_9(data):
	compressed_len, = struct.unpack("<H", data[0:2])
	compressed_data = data[2:2+compressed_len]
	decompressed_data = decompress(compressed_data, compressed_len)

	instr_data = {}

	# Decode main fields:

	for i in range(len(FIELDS)):
		instr_data[FIELDS[i]], = \
		    struct.unpack("B", decompressed_data[i:i+1])

	# Decode instrument name

	ps = decompressed_data[14:]
	instr_data["name"], = struct.unpack("%ip" % len(ps), ps)

	return instr_data

def read(filename):
	f = open(filename)
	data = f.read()
	f.close()

	hdrstr, crc, filever = struct.unpack("<7sHB", data[0:10])

	if hdrstr.lower() != HEADER_STRING.lower():
		raise Exception("Wrong file header ID string")

	# TODO: CRC?

	if filever == 9:
		return decode_type_9(data[10:])
	else:
		raise Exception("Unsupported file version: %i" % filever)

if __name__ == "__main__":
	for filename in sys.argv[1:]:
		print(filename)
		print(read(filename))


text:
layout: default
description: ArangoSearch is a C++ based full-text search engine including similarity ranking capabilities natively integrated into ArangoDB.
title: ArangoSearch - Integrated Full-text Search Engine
---
# ArangoSearch

ArangoSearch provides information retrieval features, natively integrated
into ArangoDB's query language and with support for all data models. It is
primarily a full-text search engine, a much more powerful alternative to the
[full-text index](indexing-fulltext.html) type.

ArangoSearch introduces the concept of **Views** which can be seen as
virtual collections. Each View represents an inverted index to provide fast
full-text searching over one or multiple linked collections and holds the
configuration for the search capabilities, such as the attributes to index.
It can cover multiple or even all attributes of the documents in the linked
collections. Search results can be sorted by their similarity ranking to
return the best matches first using popular scoring algorithms.

Configurable **Analyzers** are available for text processing, such as for
tokenization, language-specific word stemming, case conversion, removal of
diacritical marks (accents) from characters and more. Analyzers can be used
standalone or in combination with Views for sophisticated searching.

The ArangoSearch features are integrated into AQL as
[`SEARCH` operation](aql/operations-search.html) and a set of
[AQL functions](aql/functions-arangosearch.html).

Example use cases:
- Perform federated full-text searches over product descriptions for a
  web shop, with the product documents stored in various collections.
- Find information in a research database using stemmed phrases, case and
  accent insensitive, with irrelevant terms removed from the search index
  (stop word filtering), ranked by relevance based on term frequency (TFIDF).
- Query a movie dataset for titles with words in a particular order
  (optionally with wildcards), and sort the results by best matching (BM25)
  but favor movies with a longer duration.


text:
SELECT RUN_METRIC("android/android_cpu_agg.sql");

DROP VIEW IF EXISTS p_state_cpu_idle_counter;
CREATE VIEW p_state_cpu_idle_counter AS
SELECT
  ts,
  ts - LAG(ts) OVER (
    PARTITION BY track_id
    ORDER BY
      ts
  ) AS dur,
  cpu,
  iif(value = 4294967295, -1, cast(value AS int)) AS idle_value
FROM
  counter c
  JOIN cpu_counter_track t ON c.track_id = t.id
WHERE
  t.name = "cpuidle";

DROP TABLE IF EXISTS p_state_sched_freq_idle;
CREATE VIRTUAL TABLE p_state_sched_freq_idle USING span_join(
  cpu_freq_sched_per_thread PARTITIONED cpu,
  p_state_cpu_idle_counter PARTITIONED cpu
);

SELECT
  CREATE_VIEW_FUNCTION(
    'P_STATE_OVER_INTERVAL(start_ns LONG, end_ns LONG)',
    'cpu INT, freq_khz INT, idle_value INT, dur_ns INT',
    '
    WITH sched_freq_idle_windowed AS (
      SELECT
        freq_khz,
        idle_value,
        cpu,
        IIF(ts + dur <= $end_ns, ts + dur, $end_ns) - IIF(ts >= $start_ns, ts, $start_ns) AS dur
      FROM
        p_state_sched_freq_idle
      WHERE
        ts + dur > $start_ns
        AND ts < $end_ns
    )
    SELECT
      cast(cpu AS int) AS cpu,
      cast(freq_khz AS int) AS freq_khz,
      cast(idle_value AS int) AS idle_value,
      cast(sum(dur) AS int) AS dur_ns
    FROM
      sched_freq_idle_windowed
    WHERE
      freq_khz > 0
    GROUP BY
      cpu,
      freq_khz,
      idle_value
  '
  );


text:
package test.gov.nih.nci.security.threadsafe;
import test.gov.nih.nci.security.threadsafe.RandomIntGenerator;

import gov.nih.nci.security.SecurityServiceProvider;
import gov.nih.nci.security.UserProvisioningManager;
import gov.nih.nci.security.authorization.domainobjects.Group;
import gov.nih.nci.security.authorization.domainobjects.Privilege;
import gov.nih.nci.security.authorization.domainobjects.ProtectionElement;
import gov.nih.nci.security.authorization.domainobjects.ProtectionGroup;
import gov.nih.nci.security.authorization.domainobjects.Role;
import gov.nih.nci.security.authorization.domainobjects.User;
import gov.nih.nci.security.exceptions.CSConfigurationException;
import gov.nih.nci.security.exceptions.CSException;
import gov.nih.nci.security.exceptions.CSTransactionException;

public class PrimeCSMData {

	static UserProvisioningManager userProvisioningManager;
	//	Test Set-up variables
	private static int NumberOfUsersToTest 				= 10;
	private static int NumberOfGroupsToTest 				= 10;
	private static int NumberOfPrivilegesToTest 			= 5;
	private static int NumberOfProtectionElementsToTest 	= 50;  //Must be larger than NumberOfProtectionGroupsToTest?
	private static int NumberOfProtectionGroupsToTest 		= 10;
	private static int NumberOfRolesToTest 				= 5;

	private static String[][] UserStringArray 				= new String[NumberOfUsersToTest]				[9];
	private static String[][] RoleStringArray 				= new String[NumberOfRolesToTest]				[2];
	private static String[][] GroupStringArray 			= new String[NumberOfGroupsToTest]				[2];
	private static String[][] PrivilegeStringArray 		= new String[NumberOfPrivilegesToTest]			[2];
	private static String[][] ProtectionElementStringArray = new String[NumberOfProtectionElementsToTest+3]	[4];
	private static String[][] ProtectionGroupStringArray 	= new String[NumberOfProtectionGroupsToTest]	[4];
	private String[][] PG_PERelationship			= new String[NumberOfProtectionGroupsToTest]	[NumberOfProtectionElementsToTest];
	private String[][] Group_UserRelationship		= new String[NumberOfGroupsToTest]				[NumberOfUsersToTest];

	private static String	   StrangeCharacters			= new String("");  //-\\\\=[]\\;//,./{}:\"<>?-+/*&&||==.");

	public static void main(String[] args){
		System.out.println("Start Populating Users and Groups");
		intialiseStrings();
		createData();
		association();
		getUsers();
		System.out.println("Done....");

	}

	private static void getUsers() {
		try {
			userProvisioningManager = SecurityServiceProvider.getUserProvisioningManager("security");
			for(int i=1;i<10;i++){
				User user = userProvisioningManager.getUserById(""+i);
//				System.out.println(user.getLoginName()+" ,"+user.getPassword());
			}
		} catch (CSTransactionException e1) {

			e1.printStackTrace();
		} catch (CSConfigurationException e) {

			e.printStackTrace();
		} catch (CSException e) {

			e.printStackTrace();
		}

	}

	public static void intialiseStrings(){
		//	Initialize String Array
		InitializeUserStringArray();
		InitializeRoleStringArray();
		InitializeGroupStringArray();
		InitializePrivilegeStringArray();
		InitializeProtectionElementStringArray();
		InitializeProtectionGroupStringArray();
	}
	public static void createData(){
		try {
			userProvisioningManager = SecurityServiceProvider.getUserProvisioningManager("security");

			testCreateUser();
			testCreatePrivilege();
			testCreateProtectionElement();
			testCreateRole();
			testCreateGroup();
			testCreateProtectionGroup();

		} catch (CSTransactionException e1) {

			e1.printStackTrace();
		} catch (CSConfigurationException e) {

			e.printStackTrace();
		} catch (CSException e) {

			e.printStackTrace();
		}
	}

	public static void association(){
		try {
			userProvisioningManager = SecurityServiceProvider.getUserProvisioningManager("security");

			testAssignUserToGroup();

		} catch (CSTransactionException e1) {
			e1.printStackTrace();
		} catch (CSConfigurationException e) {
			e.printStackTrace();
		} catch (CSException e) {
			e.printStackTrace();
		}
	}

	private static void testAssignUserToGroup() throws CSTransactionException {
		for (int x=0; x<NumberOfUsersToTest; x++)
		{
			for(int k=0;k<10;k++){
			userProvisioningManager.assignUserToGroup(UserStringArray[x][0], GroupStringArray[k][0] );
			}
		}
	}

	private static void testCreateUser() throws CSTransactionException {
		for (int x=0; x<NumberOfUsersToTest; x++)
		{
			User tempUser = new User();
			java.util.Date CurrentTime = new java.util.Date();
			tempUser.setLoginName(UserStringArray[x][0]);
			tempUser.setFirstName(UserStringArray[x][1]);
			tempUser.setLastName(UserStringArray[x][2]);
			tempUser.setDepartment(UserStringArray[x][3]);
			tempUser.setEmailId(UserStringArray[x][4]);
			tempUser.setOrganization(UserStringArray[x][5]);
			tempUser.setPassword(UserStringArray[x][6]);
			tempUser.setTitle(UserStringArray[x][7]);
			tempUser.setPhoneNumber(UserStringArray[x][8]);

			tempUser.setEndDate(CurrentTime);
			tempUser.setStartDate(CurrentTime);
			tempUser.setUpdateDate(CurrentTime);

			userProvisioningManager.createUser(tempUser);
			//userList.add(x,tempUser);

		}
	}

//	Setup UserStringArray
	private static void InitializeUserStringArray()
	{
		for (int x=0; x<NumberOfUsersToTest; x++)
		{
			UserStringArray[x][0] = "TestUserLoginName" + StrangeCharacters + x;
			UserStringArray[x][1] = "TestUserFirstName" + StrangeCharacters + x;
			UserStringArray[x][2] = "TestUserLastName" + StrangeCharacters + x;
			UserStringArray[x][3] = "TestUserDepartment" + StrangeCharacters + x;
			UserStringArray[x][4] = "TestUserEmailID" + x + "@TestUserEmailID" + x + ".com";//TODO: Make a seperate StrangeCharacters variable to test this
			UserStringArray[x][5] = "TestUserOrganizationName" + StrangeCharacters + x;
			UserStringArray[x][6] = "TestUserPassword" + StrangeCharacters + x;
			UserStringArray[x][7] = "TestUserTitle" + StrangeCharacters + x;
			UserStringArray[x][8] = new String("###-###-####").replace('#',Integer.toString(x).charAt(0));
		}
	}

	private static void InitializeRoleStringArray()
	{
		for ( int x=0; x<NumberOfRolesToTest; x++)
		{
			//java.util.Date CurrentTime = new java.util.Date();
			RoleStringArray[x][0] = "TestRoleName" + StrangeCharacters + x;
			RoleStringArray[x][1] = "TestRoleDesc" + StrangeCharacters + x;
		}
	}

	private static void InitializeGroupStringArray()
	{
		for (int x=0; x<NumberOfGroupsToTest; x++)
		{
			GroupStringArray[x][0] = "TestGroupName" + StrangeCharacters + x;
			GroupStringArray[x][1] = "TestGroupDesc" + StrangeCharacters + x;
		}
	}

	private static void InitializePrivilegeStringArray()
	{
		for (int x=0; x<NumberOfPrivilegesToTest; x++)
		{
			PrivilegeStringArray[x][0] = "TestPrivilegeName" + StrangeCharacters + x;
			PrivilegeStringArray[x][1] = "TestPrivilegeDesc" + StrangeCharacters + x;
		}
	}

	private static void InitializeProtectionElementStringArray()
	{
		for (int x=0; x<NumberOfProtectionElementsToTest; x++)
		{
			ProtectionElementStringArray[x][0] = "TestProtectionElementName" + StrangeCharacters + x;
			ProtectionElementStringArray[x][1] = "TestProtectionElementDescription" + StrangeCharacters + x;
			ProtectionElementStringArray[x][2] = "TestProtectionElementObjectID" + StrangeCharacters + x;
			ProtectionElementStringArray[x][3] = "TestProtectionElementAttribute" + StrangeCharacters + x;
		}
	}

	private static void InitializeProtectionGroupStringArray()
	{
		for (int x=0; x<NumberOfProtectionGroupsToTest; x++)
		{
			ProtectionGroupStringArray[x][0] = "TestProtectionGroupName" + StrangeCharacters + x;
			ProtectionGroupStringArray[x][1] = "TestProtectionGroupDesc" + StrangeCharacters + x;
		}
	}

	private static void testCreatePrivilege() throws CSTransactionException {

		for (int x=0; x<NumberOfPrivilegesToTest; x++)
		{
			Privilege tempPrivilege = new Privilege();
			java.util.Date CurrentTime = new java.util.Date();
			tempPrivilege.setName(PrivilegeStringArray[x][0]);
			tempPrivilege.setDesc(PrivilegeStringArray[x][1]);
			tempPrivilege.setUpdateDate(CurrentTime);
			userProvisioningManager.createPrivilege(tempPrivilege);
		}
	}
	private static void testCreateProtectionElement() throws CSTransactionException
	{
		for (int x=0; x<NumberOfProtectionElementsToTest; x++)
		{
			ProtectionElement tempProtectionElement = new ProtectionElement();
			java.util.Date CurrentTime = new java.util.Date();
			tempProtectionElement.setProtectionElementName(ProtectionElementStringArray[x][0]);
			tempProtectionElement.setProtectionElementDescription(ProtectionElementStringArray[x][1]);
			tempProtectionElement.setObjectId(ProtectionElementStringArray[x][2]);
			tempProtectionElement.setAttribute(ProtectionElementStringArray[x][3]);
			tempProtectionElement.setUpdateDate(CurrentTime);

			userProvisioningManager.createProtectionElement(tempProtectionElement);

			tempProtectionElement = null;
		}
	}

	private static void testCreateRole() throws CSTransactionException
	{
		byte tempFlag = 0;

		for ( int x=0; x<NumberOfRolesToTest; x++)
		{
			Role tempRole = new Role();
			java.util.Date CurrentTime = new java.util.Date();
			tempRole.setName(RoleStringArray[x][0]);
			tempRole.setDesc(RoleStringArray[x][1]);
			tempRole.setUpdateDate(CurrentTime);

			tempRole.setActive_flag(tempFlag);
			if (tempFlag == 1)
				tempFlag = 0;
			else
				tempFlag = 1;

			userProvisioningManager.createRole(tempRole);
		}
	}

	private static void testCreateGroup() throws CSTransactionException
	{

		for (int x=0; x<NumberOfGroupsToTest; x++)
		{
			Group tempGroup = new Group();
			java.util.Date CurrentTime = new java.util.Date();
			tempGroup.setGroupName(GroupStringArray[x][0]);
			tempGroup.setGroupDesc(GroupStringArray[x][1]);
			tempGroup.setUpdateDate(CurrentTime);

			userProvisioningManager.createGroup(tempGroup);
		}

	}

	private static void testCreateProtectionGroup() throws CSTransactionException
	{

		byte tempFlag = 0;
		for (int x=0; x<NumberOfProtectionGroupsToTest; x++)
		{
			ProtectionGroup tempProtectionGroup = new ProtectionGroup();
			java.util.Date CurrentTime = new java.util.Date();

			tempProtectionGroup.setProtectionGroupName(ProtectionGroupStringArray[x][0]);
			tempProtectionGroup.setProtectionGroupDescription(ProtectionGroupStringArray[x][1]);
			tempProtectionGroup.setUpdateDate(CurrentTime);

			tempProtectionGroup.setLargeElementCountFlag(tempFlag);
			if (tempFlag == 1)
				tempFlag = 0;
			else
				tempFlag = 1;

			userProvisioningManager.createProtectionGroup(tempProtectionGroup);
		}
	}

}


text:
using namespace llvm;

#define DEBUG_TYPE "faultmaps"

static const int FaultMapVersion = 1;
const char *FaultMaps::WFMP = "Fault Maps: ";

FaultMaps::FaultMaps(AsmPrinter &AP) : AP(AP) {}

void FaultMaps::recordFaultingOp(FaultKind FaultTy,
                                 const MCSymbol *FaultingLabel,
                                 const MCSymbol *HandlerLabel) {
  MCContext &OutContext = AP.OutStreamer->getContext();

  const MCExpr *FaultingOffset = MCBinaryExpr::createSub(
      MCSymbolRefExpr::create(FaultingLabel, OutContext),
      MCSymbolRefExpr::create(AP.CurrentFnSymForSize, OutContext), OutContext);

  const MCExpr *HandlerOffset = MCBinaryExpr::createSub(
      MCSymbolRefExpr::create(HandlerLabel, OutContext),
      MCSymbolRefExpr::create(AP.CurrentFnSymForSize, OutContext), OutContext);

  FunctionInfos[AP.CurrentFnSym].emplace_back(FaultTy, FaultingOffset,
                                              HandlerOffset);
}

void FaultMaps::serializeToFaultMapSection() {
  if (FunctionInfos.empty())
    return;

  MCContext &OutContext = AP.OutStreamer->getContext();
  MCStreamer &OS = *AP.OutStreamer;

  // Create the section.
  MCSection *FaultMapSection =
      OutContext.getObjectFileInfo()->getFaultMapSection();
  OS.SwitchSection(FaultMapSection);

  // Emit a dummy symbol to force section inclusion.
  OS.emitLabel(OutContext.getOrCreateSymbol(Twine("__LLVM_FaultMaps")));

  LLVM_DEBUG(dbgs() << "********** Fault Map Output **********\n");

  // Header
  OS.emitIntValue(FaultMapVersion, 1); // Version.
  OS.emitIntValue(0, 1);               // Reserved.
  OS.emitInt16(0);                     // Reserved.

  LLVM_DEBUG(dbgs() << WFMP << "#functions = " << FunctionInfos.size() << "\n");
  OS.emitInt32(FunctionInfos.size());

  LLVM_DEBUG(dbgs() << WFMP << "functions:\n");

  for (const auto &FFI : FunctionInfos)
    emitFunctionInfo(FFI.first, FFI.second);
}

void FaultMaps::emitFunctionInfo(const MCSymbol *FnLabel,
                                 const FunctionFaultInfos &FFI) {
  MCStreamer &OS = *AP.OutStreamer;

  LLVM_DEBUG(dbgs() << WFMP << "  function addr: " << *FnLabel << "\n");
  OS.emitSymbolValue(FnLabel, 8);

  LLVM_DEBUG(dbgs() << WFMP << "  #faulting PCs: " << FFI.size() << "\n");
  OS.emitInt32(FFI.size());

  OS.emitInt32(0); // Reserved

  for (auto &Fault : FFI) {
    LLVM_DEBUG(dbgs() << WFMP << "    fault type: "
                      << faultTypeToString(Fault.Kind) << "\n");
    OS.emitInt32(Fault.Kind);

    LLVM_DEBUG(dbgs() << WFMP << "    faulting PC offset: "
                      << *Fault.FaultingOffsetExpr << "\n");
    OS.emitValue(Fault.FaultingOffsetExpr, 4);

    LLVM_DEBUG(dbgs() << WFMP << "    fault handler PC offset: "
                      << *Fault.HandlerOffsetExpr << "\n");
    OS.emitValue(Fault.HandlerOffsetExpr, 4);
  }
}

const char *FaultMaps::faultTypeToString(FaultMaps::FaultKind FT) {
  switch (FT) {
  default:
    llvm_unreachable("unhandled fault type!");
  case FaultMaps::FaultingLoad:
    return "FaultingLoad";
  case FaultMaps::FaultingLoadStore:
    return "FaultingLoadStore";
  case FaultMaps::FaultingStore:
    return "FaultingStore";
  }
}

raw_ostream &llvm::
operator<<(raw_ostream &OS,
           const FaultMapParser::FunctionFaultInfoAccessor &FFI) {
  OS << "Fault kind: "
     << FaultMaps::faultTypeToString((FaultMaps::FaultKind)FFI.getFaultKind())
     << ", faulting PC offset: " << FFI.getFaultingPCOffset()
     << ", handling PC offset: " << FFI.getHandlerPCOffset();
  return OS;
}

raw_ostream &llvm::
operator<<(raw_ostream &OS, const FaultMapParser::FunctionInfoAccessor &FI) {
  OS << "FunctionAddress: " << format_hex(FI.getFunctionAddr(), 8)
     << ", NumFaultingPCs: " << FI.getNumFaultingPCs() << "\n";
  for (unsigned i = 0, e = FI.getNumFaultingPCs(); i != e; ++i)
    OS << FI.getFunctionFaultInfoAt(i) << "\n";
  return OS;
}

raw_ostream &llvm::operator<<(raw_ostream &OS, const FaultMapParser &FMP) {
  OS << "Version: " << format_hex(FMP.getFaultMapVersion(), 2) << "\n";
  OS << "NumFunctions: " << FMP.getNumFunctions() << "\n";

  if (FMP.getNumFunctions() == 0)
    return OS;

  FaultMapParser::FunctionInfoAccessor FI;

  for (unsigned i = 0, e = FMP.getNumFunctions(); i != e; ++i) {
    FI = (i == 0) ? FMP.getFirstFunctionInfo() : FI.getNextFunctionInfo();
    OS << FI;
  }

  return OS;
}


text:
package io.dropwizard.configuration;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import com.fasterxml.jackson.databind.node.TreeTraversingParser;

import javax.annotation.Nullable;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static java.util.Objects.requireNonNull;

/**
 * A generic factory class for loading configuration files, binding them to configuration objects, and
 * validating their constraints. Allows for overriding configuration parameters from system properties.
 *
 * @param <T> the type of the configuration objects to produce
 */
public abstract class BaseConfigurationFactory<T> implements ConfigurationFactory<T> {

    private static final Pattern ESCAPED_COMMA_PATTERN = Pattern.compile("\\\\,");
    private static final Pattern ESCAPED_COMMA_SPLIT_PATTERN = Pattern.compile("(?<!\\\\),");
    private static final Pattern ESCAPED_DOT_PATTERN = Pattern.compile("\\\\\\.");
    private static final Pattern ESCAPED_DOT_SPLIT_PATTERN = Pattern.compile("(?<!\\\\)\\.");

    private final Class<T> klass;
    private final String propertyPrefix;
    protected final ObjectMapper mapper;
    private final ConfigurationMetadata configurationMetadata;

    @Nullable
    private final Validator validator;

    private final String formatName;
    private final JsonFactory parserFactory;

    /**
     * Creates a new configuration factory for the given class.
     *
     * @param parserFactory  the factory that creates the parser used
     * @param formatName     the name of the format parsed by this factory (used in exceptions)
     * @param klass          the configuration class
     * @param validator      the validator to use
     * @param propertyPrefix the system property name prefix used by overrides
     */
    public BaseConfigurationFactory(JsonFactory parserFactory,
                                    String formatName,
                                    Class<T> klass,
                                    @Nullable Validator validator,
                                    ObjectMapper objectMapper,
                                    String propertyPrefix) {
        this.klass = klass;
        this.formatName = formatName;
        this.propertyPrefix = propertyPrefix.endsWith(".") ? propertyPrefix : propertyPrefix + '.';
        this.mapper = objectMapper;
        this.parserFactory = parserFactory;
        this.validator = validator;
        this.configurationMetadata = new ConfigurationMetadata(mapper, klass);
    }

    @Override
    public T build(ConfigurationSourceProvider provider, String path) throws IOException, ConfigurationException {
        try (InputStream input = provider.open(requireNonNull(path))) {
            final JsonNode node = mapper.readTree(createParser(input));

            if (node == null) {
                throw ConfigurationParsingException
                    .builder("Configuration at " + path + " must not be empty")
                    .build(path);
            }

            return build(node, path);
        } catch (JsonParseException e) {
            throw ConfigurationParsingException
                .builder("Malformed " + formatName)
                .setCause(e)
                .setLocation(e.getLocation())
                .setDetail(e.getMessage())
                .build(path);
        }
    }

    protected JsonParser createParser(InputStream input) throws IOException {
        return parserFactory.createParser(input);
    }

    @Override
    public T build() throws IOException, ConfigurationException {
        try {
            final T instance = klass.getDeclaredConstructor().newInstance();
            final JsonNode node = mapper.valueToTree(instance);
            return build(node, "default configuration");
        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | SecurityException
                | NoSuchMethodException | InvocationTargetException e) {
            throw new IllegalArgumentException("Unable to create an instance " +
                "of the configuration class: '" + klass.getCanonicalName() + "'", e);
        }
    }

    protected T build(JsonNode node, String path) throws IOException, ConfigurationException {
        for (Map.Entry<Object, Object> pref : System.getProperties().entrySet()) {
            final String prefName = (String) pref.getKey();
            if (prefName.startsWith(propertyPrefix)) {
                final String configName = prefName.substring(propertyPrefix.length());
                addOverride(node, configName, System.getProperty(prefName));
            }
        }

        try {
            final T config = mapper.readValue(new TreeTraversingParser(node, mapper), klass);
            validate(path, config);
            return config;
        } catch (UnrecognizedPropertyException e) {
            final List<String> properties = e.getKnownPropertyIds().stream()
                .map(Object::toString)
                .collect(Collectors.toList());
            throw ConfigurationParsingException.builder("Unrecognized field")
                .setFieldPath(e.getPath())
                .setLocation(e.getLocation())
                .addSuggestions(properties)
                .setSuggestionBase(e.getPropertyName())
                .setCause(e)
                .build(path);
        } catch (InvalidFormatException e) {
            final String sourceType = e.getValue().getClass().getSimpleName();
            final String targetType = e.getTargetType().getSimpleName();
            throw ConfigurationParsingException.builder("Incorrect type of value")
                .setDetail("is of type: " + sourceType + ", expected: " + targetType)
                .setLocation(e.getLocation())
                .setFieldPath(e.getPath())
                .setCause(e)
                .build(path);
        } catch (JsonMappingException e) {
            throw ConfigurationParsingException.builder("Failed to parse configuration")
                .setDetail(e.getMessage())
                .setFieldPath(e.getPath())
                .setLocation(e.getLocation())
                .setCause(e)
                .build(path);
        }
    }

    protected void addOverride(JsonNode root, String name, String value) {
        JsonNode node = root;
        final List<String> parts = Arrays.stream(ESCAPED_DOT_SPLIT_PATTERN.split(name))
                .map(String::trim)
                .map(key -> ESCAPED_DOT_PATTERN.matcher(key).replaceAll("."))
                .collect(Collectors.toList());
        for (int i = 0; i < parts.size(); i++) {
            final String key = parts.get(i);

            if (!(node instanceof ObjectNode)) {
                throw new IllegalArgumentException("Unable to override " + name + "; it's not a valid path.");
            }
            final ObjectNode obj = (ObjectNode) node;

            final String remainingPath = String.join(".", parts.subList(i, parts.size()));
            if (obj.has(remainingPath) && !remainingPath.equals(key)
                    && obj.get(remainingPath).isValueNode()) {
                obj.put(remainingPath, value);
                return;
            }

            JsonNode child;
            final boolean moreParts = i < parts.size() - 1;

            if (key.matches(".+\\[\\d+\\]$")) {
                final int s = key.indexOf('[');
                final int index = Integer.parseInt(key.substring(s + 1, key.length() - 1));
                child = obj.get(key.substring(0, s));
                if (child == null) {
                    throw new IllegalArgumentException("Unable to override " + name +
                        "; node with index not found.");
                }
                if (!child.isArray()) {
                    throw new IllegalArgumentException("Unable to override " + name +
                        "; node with index is not an array.");
                } else if (index >= child.size()) {
                    throw new ArrayIndexOutOfBoundsException("Unable to override " + name +
                        "; index is greater than size of array.");
                }
                if (moreParts) {
                    child = child.get(index);
                    node = child;
                } else {
                    final ArrayNode array = (ArrayNode) child;
                    array.set(index, TextNode.valueOf(value));
                    return;
                }
            } else if (moreParts) {
                child = obj.get(key);
                if (child == null) {
                    child = obj.objectNode();
                    obj.set(key, child);
                }
                if (child.isArray()) {
                    throw new IllegalArgumentException("Unable to override " + name +
                        "; target is an array but no index specified");
                }
                node = child;
            }

            if (!moreParts) {
                if ((node.get(key) != null && node.get(key).isArray())
                    || (node.get(key) == null && configurationMetadata.isCollectionOfStrings(name))) {
                    ArrayNode arrayNode = (ArrayNode) obj.get(key);
                    if (arrayNode == null) {
                        arrayNode = obj.arrayNode();
                        obj.set(key, arrayNode);
                    }
                    arrayNode.removeAll();
                    Arrays.stream(ESCAPED_COMMA_SPLIT_PATTERN.split(value))
                            .map(String::trim)
                            .map(val -> ESCAPED_COMMA_PATTERN.matcher(val).replaceAll(","))
                            .forEach(arrayNode::add);
                } else {
                    obj.put(key, value);
                }
            }
        }
    }

    private void validate(String path, T config) throws ConfigurationValidationException {
        if (validator != null) {
            final Set<ConstraintViolation<T>> violations = validator.validate(config);
            if (!violations.isEmpty()) {
                throw new ConfigurationValidationException(path, violations);
            }
        }
    }
}


text:
"use strict";

/*
 * # Level 1 Headers are Chapters (they get title pages)
 *
 * ## Level 2 Headers represent pages ("Location" or "Time: Location")
 *
 * ### Level 3 Headers are optional paragraphs, that show depending on choices
 * and terminated by an empty level 3 header (###)
 *
 * [ID: Text](path) at the end represent choices
 *
 * Standard markdown formatting otherwise applies.
 */

function parseStory( storyCode )
{
    var story = {
        chapters: [],
        currentChapter: emptyChapter(),
        currentPage: emptyPage(),
        currentText: emptyText(),
    };

    // Go line by line.
    storyCode.split( constants.newlineCharacter ).forEach( function ( line ) {

        var trimmedLine = rightTrim( line );

        if ( trimmedLine.startsWith("[") ) {

            // New choice link.
            story = endCurrentText( story );
            story = addChoiceLink( story,
                choiceLinkFromLink( trimmedLine ) );

        } else if ( trimmedLine.startsWith("###") ) {

            // New choice/content.
            story = endCurrentText( story );
            story = startNewText( story,
                choiceInfoFromHeader( trimmedLine ) );

        } else if ( trimmedLine.startsWith("##") ) {

            // New page/paragraph.
            story = endCurrentText( story );
            story = endCurrentPage( story );
            story = startNewPage( story,
                pageInfoFromHeader( trimmedLine ) );
            story = startNewText( story, emptyChoice() );

        } else if ( trimmedLine.startsWith("#") ) {

            // New chapter.
            story = endCurrentText( story );
            story = endCurrentPage( story );
            story = endCurrentChapter( story );
            story = startNewChapter( story,
                chapterInfoFromHeader( trimmedLine ) );

        } else {

            // Continued text.
            story = appendCurrentText( story, line );

        }

    });

    // Terminate open paragraphs/page/chapters.
    story = endCurrentText( story );
    story = endCurrentPage( story );
    story = endCurrentChapter( story );

    return story;
}

function emptyChapter()
{
    return {
        title: "",
        pages: [],
    };
}

function emptyPage()
{
    return {
        time: "",
        location: "",
        texts: [],
        links: [],
    };
}

function emptyText()
{
    return {
        content: "",
        choice: emptyChoice(),
    };
}

function emptyChoice()
{
    return {
        id: "",
        target: {
            path: "",
        },
    };
}

function isChapterEmpty( chapter )
{
    return !( chapter.pages.length || chapter.title.length );
}

function isPageEmpty( page )
{
    return !( page.texts.length || page.links.length ||
              page.time.length  || page.location.length );
}

function isTextEmpty( text )
{
    return !( text.content.length );
}

function startNewChapter( story, chapterInfo )
{
    story.currentChapter = emptyChapter();
    story.currentChapter.title = chapterInfo.title;
    return story;
}

function endCurrentChapter( story )
{
    if( !isChapterEmpty( story.currentChapter ) ) {
        story.chapters.push( story.currentChapter );
    }

    story.currentChapter = emptyChapter();
    return story;
}

function startNewPage( story, pageInfo )
{
    story.currentPage = emptyPage();
    story.currentPage.time = pageInfo.time;
    story.currentPage.location = pageInfo.location;
    return story;
}

function endCurrentPage( story )
{
    if ( !isPageEmpty( story.currentPage ) ) {
        story.currentChapter.pages.push( story.currentPage );
    }

    story.currentPage = emptyPage();
    return story;
}

function startNewText( story, textInfo )
{
    story.currentText = emptyText();
    story.currentText.choice.id = textInfo.id;
    story.currentText.choice.target = textInfo.target;
    return story;
}

function appendCurrentText( story, line )
{
    story.currentText.content += line + constants.newlineCharacter;
    return story;
}

function endCurrentText( story )
{
    if ( !isTextEmpty( trimText( story.currentText ) ) ) {
        story.currentPage.texts.push( trimText( story.currentText ) );
    }

    story.currentText = emptyText();
    return story;
}

function trimText( text )
{
    return {
        content: rightTrim( text.content ),
        choice: text.choice,
    }
}

function addChoiceLink( story, link )
{
    story.currentPage.links.push( link );
    return story;
}

function choiceInfoFromHeader( line )
{
    var fullChoice = everythingAfterSubstring( "###", line );
    var choiceId = "";
    var choicePath = "";

    if ( caseInsensitive( fullChoice ).startsWith( caseInsensitive( "Chose " ) ) ) {

        // Get everything after the opening keyword "Chose"
        var choiceIdAndPath = fullChoice.substring( "Chose ".length ).trim();

        // Choice ID either is:
        // 1. contained in bunny quotes, OR
        // 2. before the word "on", OR
        // 3. all text.
        if ( choiceIdAndPath.startsWith( '"' ) ) {

            var choiceIdAndOnAndPath = splitInTwoParts( '"',
                choiceIdAndPath.substring(1) );

            var onAndPath = splitInTwoParts( "on ",
                choiceIdAndOnAndPath.right );

            choiceId = choiceIdAndOnAndPath.left;
            choicePath = onAndPath.right;

        } else {

            var splitChoiceIdAndPath = splitInTwoParts( " on ",
                choiceIdAndPath );

            choiceId = splitChoiceIdAndPath.left;
            choicePath = splitChoiceIdAndPath.right;
        }

    }

    return {
        id: choiceId,
        target: {
            path: choicePath,
        },
    };
}

function choiceLinkFromLink( line )
{
    // [link id: link text](target page)
    // [link text](target page)
    var linkTextAndPath = splitInTwoParts( "](", line );
    var linkText = everythingAfterSubstring( "[", linkTextAndPath.left ).trim();
    var linkPath = linkTextAndPath.right.substring(
        0, linkTextAndPath.right.indexOf( ")" ) ).trim();
    var linkId = "";

    if ( linkText.includes( ":" ) ) {
        var linkIdAndText = splitInTwoParts( ":", linkText );
        linkId = linkIdAndText.left.trim();
        linkText = linkIdAndText.right.trim();
    }

    return {
        id: linkId,
        text: linkText,
        target: {
            path: linkPath,
        }
    }
}

function chapterInfoFromHeader( line )
{
    return {
        title: everythingAfterSubstring( "#", line )
    };
}

function pageInfoFromHeader( line )
{
    var pageTitle = everythingAfterSubstring( "##", line );

    // Default: title only specifies location.
    var location = pageTitle;
    var time = "";

    // Contains time and location.
    if ( pageTitle.indexOf( ":" ) >= 0 ) {
        var timeAndLocation = splitInTwoParts( ":", pageTitle );
        time = timeAndLocation.left;
        location = timeAndLocation.right;
    }

    return {
        time: time,
        location: location,
    }
}


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { browserHistory as history } from 'react-router';
import { connect } from 'react-redux';
import { withStyles } from 'material-ui/styles';
import { Typography } from 'material-ui';
import PaddedContent from '../../../common/paddedContent';
import ControlledModal from '../../../common/modals/controlledModal';
import { deleteCfeiRequest } from '../../../../reducers/deleteCfei';

const messages = {
  title: 'Are you sure you want to cancel this DS/R?',
  info: 'Please confirm that you want to cancel this direct selection/retention?',
  confirm: 'confirm',
};

const styleSheet = theme => ({
  text: {
    color: theme.palette.common.lightBlack,
  },
});

class CancelDsrModal extends Component {
  constructor(props) {
    super(props);
    this.confirm = this.confirm.bind(this);
  }

  confirm() {
    return this.props.deleteCfei().then(() => {
      history.push(this.props.previousPath);
    });
  }

  render() {
    const { classes, dialogOpen, handleDialogClose } = this.props;
    return (
      <div>
        <ControlledModal
          title={messages.title}
          trigger={dialogOpen}
          handleDialogClose={handleDialogClose}
          minwidth={40}
          buttons={{
            flat: {
              handleClick: handleDialogClose,
            },
            raised: {
              handleClick: this.confirm,
              label: messages.confirm,
            },
          }}
          content={
            <PaddedContent>
              <Typography className={classes.text}>{messages.info}</Typography>
            </PaddedContent>
          }
        />
      </div >
    );
  }
}

CancelDsrModal.propTypes = {
  classes: PropTypes.object.isRequired,
  dialogOpen: PropTypes.bool,
  deleteCfei: PropTypes.func,
  previousPath: PropTypes.string,
  handleDialogClose: PropTypes.func,
};

const mapStateToProps = (state, ownProps) => ({
  showLoading: state.publishCfei.status.loading,
  previousPath: state.routesHistory.previousPath || ownProps.defaultPath,
});

const mapDispatchToProps = (dispatch, ownProps) => ({
  deleteCfei: () => dispatch(deleteCfeiRequest(ownProps.id)),
});

const connected = connect(mapStateToProps, mapDispatchToProps)(CancelDsrModal);

export default withStyles(styleSheet, { name: 'CancelDsrModal' })(connected);


text:
'use strict';

angular.module('subtome')
.controller('SettingsController', ['$scope', 'services', function SettingsController($scope, services) {
  $scope.services = services;
  $scope.remove = function removeService(service) {
    services.removeService(service.name);
  };
}]);


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { postSession, setSession } from '../../actions';
import PageHeader from '../../components/PageHeader';
import FormField from '../../components/FormField';
import FormError from '../../components/FormError';
import Button from '../../components/Button';
import FormState from '../../utils/FormState';

const TITLE = 'Sign In';

class SignIn extends Component {

  constructor(props) {
    super(props);
    this._onCancel = this._onCancel.bind(this);
    this._onSignIn = this._onSignIn.bind(this);
    this._setSession = this._setSession.bind(this);
    const session = { email: props.email, password: '' };
    this.state = {
      formState: new FormState(session, this._setSession),
      errors: {},
    };
  }

  componentDidMount() {
    const { email, inline } = this.props;
    if (!inline) {
      document.title = TITLE;
    }
    if (email) {
      this._passwordRef.focus();
    } else {
      this._emailRef.focus();
    }
  }

  _onCancel() {
    const { history } = this.props;
    history.push('/');
  }

  _onSignIn(event) {
    const { dispatch, history, inline } = this.props;
    event.preventDefault();
    const { formState: { object } } = this.state;
    if (!object.email || !object.password) {
      const errors = {};
      if (!object.email) errors.email = 'required';
      if (!object.password) errors.password = 'required';
      this.setState({ errors });
    } else {
      postSession(object)
        .then((session) => {
          dispatch(setSession(session));
          if (!inline) {
            history.push('/');
          }
        })
        .catch(error => this.setState({ error }));
    }
  }

  _setSession(session) {
    this.setState({ formState: new FormState(session, this._setSession) });
  }

  render() {
    const {
      inline, onCancel, onSignUp, onVerifyEmail,
    } = this.props;
    const { formState, error, errors } = this.state;
    const session = formState.object;
    const classNames = ['form__container'];
    if (inline) {
      classNames.push('form__container--inline');
    }

    let header;
    let footerCancelControl;
    let verifyEmailControl;
    let signUpControl;
    if (inline) {
      header =

{TITLE}

;
      footerCancelControl = (
        <Button secondary={true} label="Cancel" onClick={onCancel} />
      );
      verifyEmailControl = Forgot password?;
      if (onSignUp) {
        signUpControl = (
          <Button secondary={true} label="Sign up" onClick={onSignUp} />
        );
      }
    } else {
      const actions = [
        <button key="cancel"
          type="button"
          className="button"
          onClick={this._onCancel}>
          Cancel
        </button>,
      ];
      header = <PageHeader title={TITLE} actions={actions} />;
      verifyEmailControl = <Link to="/verify-email">Forgot password?</Link>;
      signUpControl = (
        <Button secondary={true} label="Sign up" path="/sign-up" />
      );
    }

    let signUpFooter;
    if (signUpControl) {
      signUpFooter = [

          or

,

          {signUpControl}
        ,
      ];
    }

    return (

        <form className="form" action="/api/sessions" onSubmit={this._onSignIn}>
          {header}
          <FormError message={error} />

            <fieldset className="form__fields">
              <FormField name="email" label="Email" error={errors.email}>
                <input ref={(ref) => { this._emailRef = ref; }}
                  name="email"
                  type="email"
                  value={session.email || ''}
                  onChange={formState.change('email')} />
              </FormField>
              <FormField name="password" label="Password" error={errors.password}>
                <input ref={(ref) => { this._passwordRef = ref; }}
                  name="password"
                  type="password"
                  value={session.password || ''}
                  onChange={formState.change('password')} />
              </FormField>
            </fieldset>

              <button type="submit" className="button" onClick={this._onSignIn}>
                Sign In
              </button>
              {footerCancelControl}

              {verifyEmailControl}

            {signUpFooter}

        </form>

    );
  }
}

SignIn.propTypes = {
  dispatch: PropTypes.func.isRequired,
  email: PropTypes.string,
  history: PropTypes.any,
  inline: PropTypes.bool,
  onCancel: PropTypes.func,
  onSignUp: PropTypes.func,
  onVerifyEmail: PropTypes.func,
};

SignIn.defaultProps = {
  email: '',
  history: undefined,
  inline: false,
  onCancel: undefined,
  onSignUp: undefined,
  onVerifyEmail: undefined,
};

export default connect()(SignIn);


text:
using KeySndr.Base.Commands;
using KeySndr.Base.Domain;
using KeySndr.Base.Providers;
using KeySndr.Common;
using Moq;
using NUnit.Framework;

namespace KeySndr.Base.Tests.CommandTests
{
    [TestFixture]
    public class GetAppSettings_Tests
    {
        private IAppConfigProvider provider;
        private Mock<IAppConfigProvider> provicerMock;
        private GetAppSettings cmd;

        [SetUp]
        public void Setup()
        {
            provicerMock = new Mock<IAppConfigProvider>();
            provicerMock.Setup(p => p.AppConfig).Returns(new AppConfig());
            provider = provicerMock.Object;
            cmd = new GetAppSettings(provider);
        }

        [Test]
        public void ReturnAppConfig()
        {
            cmd.Execute();
            var result = cmd.Result;
            provicerMock.Verify(p => p.AppConfig, Times.Once);

            Assert.IsNotNull(result);
            Assert.IsInstanceOf<ApiResult<AppConfig>>(result);
        }
    }
}


text:
using frame::Entity;

REGISTER_FRAME_COMPONENT(GameEntityContainer);

GameEntityContainer* GameEntityContainer::add(Entity* e_game_entity) {

    // Add entity to child list
    game_entity_list.insert(e_game_entity);

    // Add container component to child entity if necessary
    auto game_entity = e_game_entity->get_or_add_component<GameEntity>();
    game_entity->container = entity;

    // Return this children for command chaining
    return this;
}

GameEntityContainer* GameEntityContainer::remove(Entity* e_game_entity) {

    // Remove the child from the child list.
    // If it wasn't in the list, stop here.
    if (game_entity_list.erase(e_game_entity) == 0)
        return this;

    // Clear the child's parent pointer
    auto game_entity = e_game_entity->get_component<GameEntity>();
    game_entity->container = 0;

    // Return this children for command chaining
    return this;
}

GameEntityContainer* GameEntityContainer::clear() {
    while (size())
        remove(*begin());
    return this;
}


text:
<?php

namespace Libs;

use Doctrine\ORM\Mapping as ORM;
use Kdyby\Doctrine\Entities\Attributes\Identifier;
use Kdyby\Doctrine\Entities\BaseEntity;
use Knp\DoctrineBehaviors\Model\Timestampable\Timestampable;
use Librette\Doctrine\Sortable\ISortable;
use Librette\Doctrine\Sortable\TSortable;

/**
 * @ORM\Entity
 */
class Haul extends BaseEntity implements ISortable
{
	use Identifier;
	use Timestampable;
	use TSortable;

	/**
	 * @var string
	 * @ORM\Column(type="string")
	 */
	protected $name;

	/**
	 * @var Widget
	 * @ORM\ManyToOne(targetEntity="Hook", inversedBy="haul")
	 * @ORM\JoinColumn(name="hook_id", referencedColumnName="id")
	 **/
	protected $hook;

	/**
	 * @var array
	 * @ORM\Column(type="array", nullable=true)
	 */
	protected $options;

	/**
	 * @var Widget
	 * @ORM\ManyToOne(targetEntity="Widget", inversedBy="widget_instances")
	 * @ORM\JoinColumn(name="widget_id", referencedColumnName="id")
	 **/
	protected $widget;

	/**
	 * @return string
	 */
	public function getName()
	{
		return $this->name;
	}

	/**
	 * @param string $name
	 */
	public function setName($name)
	{
		$this->name = $name;
	}

	/**
	 * @return Widget
	 */
	public function getHook()
	{
		return $this->hook;
	}

	/**
	 * @param Widget $hook
	 */
	public function setHook($hook)
	{
		$this->hook = $hook;
	}

	/**
	 * @return array
	 */
	public function getOptions()
	{
		return $this->options;
	}

	/**
	 * @param array $options
	 */
	public function setOptions($options)
	{
		$this->options = $options;
	}

	/**
	 * @return Widget
	 */
	public function getWidget()
	{
		return $this->widget;
	}

	/**
	 * @param Widget $widget
	 */
	public function setWidget($widget)
	{
		$this->widget = $widget;
	}

	/**
	 * @return array
	 */
	public function toArray()
	{
		/** TODO tohle je dočasné */
		return $this->getOptions();
	}
}


text:
//
//  KWGlobalFilterManager.h
//  KiwiFaceKitDemo
//
//  Created by zhaoyichao on 2017/3/4.
//  Copyright © 2017年 0dayZh. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "KWColorFilter.h"

@class KWGlobalFilter;

@interface KWGlobalFilterManager : NSObject

+ (instancetype)sharedManager;

/**
 Asynchronous mode reads all the sticker information from the file

 @param completion Read the callback after completion
 */
- (void)loadColorFiltersWithCompletion:(void (^)(NSMutableArray<KWGlobalFilter *> *filters))completion;

+ (void)removeAllColorFilters;

@end


text:
import pytest

from skidl import Part, Pin

from .setup_teardown import setup_function, teardown_function

def test_pin_search_1():
    codec = Part("xess.lib", "ak4520a")
    bidir = codec.get_pins(func=Pin.BIDIR)
    pwrin = codec.get_pins(func=Pin.PWRIN)
    assert len(bidir) == 24
    assert len(pwrin) == 4
    assert len(bidir) + len(pwrin) == len(codec)


text:
package org.apache.ignite.internal.processors.cache.distributed.dht;

import java.io.Externalizable;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.internal.GridDirectCollection;
import org.apache.ignite.internal.GridDirectMap;
import org.apache.ignite.internal.processors.cache.GridCacheContext;
import org.apache.ignite.internal.processors.cache.GridCacheEntryInfo;
import org.apache.ignite.internal.processors.cache.GridCacheSharedContext;
import org.apache.ignite.internal.processors.cache.distributed.GridDistributedTxPrepareResponse;
import org.apache.ignite.internal.processors.cache.transactions.IgniteTxKey;
import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
import org.apache.ignite.internal.util.tostring.GridToStringInclude;
import org.apache.ignite.internal.util.typedef.internal.CU;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.lang.IgniteUuid;
import org.apache.ignite.plugin.extensions.communication.MessageCollectionItemType;
import org.apache.ignite.plugin.extensions.communication.MessageReader;
import org.apache.ignite.plugin.extensions.communication.MessageWriter;

/**
 * DHT transaction prepare response.
 */
public class GridDhtTxPrepareResponse extends GridDistributedTxPrepareResponse {
    /** */
    private static final long serialVersionUID = 0L;

    /** Evicted readers. */
    @GridToStringInclude
    @GridDirectCollection(IgniteTxKey.class)
    private Collection<IgniteTxKey> nearEvicted;

    /** Future ID.  */
    private IgniteUuid futId;

    /** Mini future ID. */
    private IgniteUuid miniId;

    /** Invalid partitions. */
    @GridToStringInclude
    @GridDirectCollection(int.class)
    private Collection<Integer> invalidParts;

    /** Invalid partitions by cache ID. */
    @GridDirectMap(keyType = Integer.class, valueType = int[].class)
    private Map<Integer, int[]> invalidPartsByCacheId;

    /** Preload entries. */
    @GridDirectCollection(GridCacheEntryInfo.class)
    private List<GridCacheEntryInfo> preloadEntries;

    /**
     * Empty constructor required by {@link Externalizable}.
     */
    public GridDhtTxPrepareResponse() {
        // No-op.
    }

    /**
     * @param xid Xid version.
     * @param futId Future ID.
     * @param miniId Mini future ID.
     */
    public GridDhtTxPrepareResponse(GridCacheVersion xid, IgniteUuid futId, IgniteUuid miniId) {
        super(xid);

        assert futId != null;
        assert miniId != null;

        this.futId = futId;
        this.miniId = miniId;
    }

    /**
     * @param xid Xid version.
     * @param futId Future ID.
     * @param miniId Mini future ID.
     * @param err Error.
     */
    public GridDhtTxPrepareResponse(GridCacheVersion xid, IgniteUuid futId, IgniteUuid miniId, Throwable err) {
        super(xid, err);

        assert futId != null;
        assert miniId != null;

        this.futId = futId;
        this.miniId = miniId;
    }

    /**
     * @return Evicted readers.
     */
    public Collection<IgniteTxKey> nearEvicted() {
        return nearEvicted;
    }

    /**
     * @param nearEvicted Evicted readers.
     */
    public void nearEvicted(Collection<IgniteTxKey> nearEvicted) {
        this.nearEvicted = nearEvicted;
    }

    /**
     * @return Future ID.
     */
    public IgniteUuid futureId() {
        return futId;
    }

    /**
     * @return Mini future ID.
     */
    public IgniteUuid miniId() {
        return miniId;
    }

    /**
     * @return Invalid partitions.
     */
    public Collection<Integer> invalidPartitions() {
        return invalidParts;
    }

    /**
     * @param invalidParts Invalid partitions.
     */
    public void invalidPartitions(Collection<Integer> invalidParts) {
        this.invalidParts = invalidParts;
    }

    /**
     * @return Map from cacheId to an array of invalid partitions.
     */
    public Map<Integer, int[]> invalidPartitionsByCacheId() {
        return invalidPartsByCacheId;
    }

    /**
     * @param invalidPartsByCacheId Map from cache ID to an array of invalid partitions.
     */
    public void invalidPartitionsByCacheId(Map<Integer, Set<Integer>> invalidPartsByCacheId) {
        this.invalidPartsByCacheId = CU.convertInvalidPartitions(invalidPartsByCacheId);
    }

    /**
     * Gets preload entries found on backup node.
     *
     * @return Collection of entry infos need to be preloaded.
     */
    public Collection<GridCacheEntryInfo> preloadEntries() {
        return preloadEntries == null ? Collections.<GridCacheEntryInfo>emptyList() : preloadEntries;
    }

    /**
     * Adds preload entry.
     *
     * @param info Info to add.
     */
    public void addPreloadEntry(GridCacheEntryInfo info) {
        assert info.cacheId() != 0;

        if (preloadEntries == null)
            preloadEntries = new ArrayList<>();

        preloadEntries.add(info);
    }

    /** {@inheritDoc}
     * @param ctx*/
    @Override public void prepareMarshal(GridCacheSharedContext ctx) throws IgniteCheckedException {
        super.prepareMarshal(ctx);

        if (nearEvicted != null) {
            for (IgniteTxKey key : nearEvicted) {
                GridCacheContext cctx = ctx.cacheContext(key.cacheId());

                key.prepareMarshal(cctx);
            }
        }

        if (preloadEntries != null) {
            for (GridCacheEntryInfo info : preloadEntries) {
                GridCacheContext cctx = ctx.cacheContext(info.cacheId());

                info.marshal(cctx);
            }
        }
    }

    /** {@inheritDoc} */
    @Override public void finishUnmarshal(GridCacheSharedContext ctx, ClassLoader ldr) throws IgniteCheckedException {
        super.finishUnmarshal(ctx, ldr);

        if (nearEvicted != null) {
            for (IgniteTxKey key : nearEvicted) {
                GridCacheContext cctx = ctx.cacheContext(key.cacheId());

                key.finishUnmarshal(cctx, ldr);
            }
        }

        if (preloadEntries != null) {
            for (GridCacheEntryInfo info : preloadEntries) {
                GridCacheContext cctx = ctx.cacheContext(info.cacheId());

                info.unmarshal(cctx, ldr);
            }
        }
    }

    /** {@inheritDoc} */
    @Override public String toString() {
        return S.toString(GridDhtTxPrepareResponse.class, this, "super", super.toString());
    }

    /** {@inheritDoc} */
    @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
        writer.setBuffer(buf);

        if (!super.writeTo(buf, writer))
            return false;

        if (!writer.isHeaderWritten()) {
            if (!writer.writeHeader(directType(), fieldsCount()))
                return false;

            writer.onHeaderWritten();
        }

        switch (writer.state()) {
            case 8:
                if (!writer.writeIgniteUuid("futId", futId))
                    return false;

                writer.incrementState();

            case 9:
                if (!writer.writeCollection("invalidParts", invalidParts, MessageCollectionItemType.INT))
                    return false;

                writer.incrementState();

            case 10:
                if (!writer.writeMap("invalidPartsByCacheId", invalidPartsByCacheId, MessageCollectionItemType.INT, MessageCollectionItemType.INT_ARR))
                    return false;

                writer.incrementState();

            case 11:
                if (!writer.writeIgniteUuid("miniId", miniId))
                    return false;

                writer.incrementState();

            case 12:
                if (!writer.writeCollection("nearEvicted", nearEvicted, MessageCollectionItemType.MSG))
                    return false;

                writer.incrementState();

            case 13:
                if (!writer.writeCollection("preloadEntries", preloadEntries, MessageCollectionItemType.MSG))
                    return false;

                writer.incrementState();

        }

        return true;
    }

    /** {@inheritDoc} */
    @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {
        reader.setBuffer(buf);

        if (!reader.beforeMessageRead())
            return false;

        if (!super.readFrom(buf, reader))
            return false;

        switch (reader.state()) {
            case 8:
                futId = reader.readIgniteUuid("futId");

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

            case 9:
                invalidParts = reader.readCollection("invalidParts", MessageCollectionItemType.INT);

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

            case 10:
                invalidPartsByCacheId = reader.readMap("invalidPartsByCacheId", MessageCollectionItemType.INT, MessageCollectionItemType.INT_ARR, false);

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

            case 11:
                miniId = reader.readIgniteUuid("miniId");

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

            case 12:
                nearEvicted = reader.readCollection("nearEvicted", MessageCollectionItemType.MSG);

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

            case 13:
                preloadEntries = reader.readCollection("preloadEntries", MessageCollectionItemType.MSG);

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

        }

        return reader.afterMessageRead(GridDhtTxPrepareResponse.class);
    }

    /** {@inheritDoc} */
    @Override public byte directType() {
        return 35;
    }

    /** {@inheritDoc} */
    @Override public byte fieldsCount() {
        return 14;
    }
}


text:
<form>

                Search the Web with
                <SELECT NAME=cp>
                <OPTION VALUE="Netscape">Netscape
                </SELECT><INPUT SIZE=30 NAME=searchstring> <INPUT TYPE=submit
VALUE=Search>

                Classifieds<
/A>   Net
Search   Find Web
Sites
                  What's
Cool   What's New
People Finder   Yellow Pages

        Download Netscape Communicator 4.5

Click Here!

        	Hassle-Free Upgrades

                Contact : Address Book - Discussions - Instant Messenger - Long Distance - Members - WebMail<
/A>

</form>


text:
package com.bubblegum.traceratops.app.ui.fragments;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bubblegum.traceratops.app.R;
import com.bubblegum.traceratops.app.TraceratopsApplication;
import com.bubblegum.traceratops.app.model.BaseEntry;
import com.bubblegum.traceratops.app.profiles.AppProfile;
import com.bubblegum.traceratops.app.profiles.ProfileUpdateNotifier;
import com.bubblegum.traceratops.app.ui.adapters.plugins.PingEntryAdapter;

import java.util.List;

public class PingsFragment extends Fragment {

    private RecyclerView mRecyclerView;
    private PingEntryAdapter mEntryAdapter;

    private ProfileUpdateNotifier mNotifier;
    private AppProfile mProfile;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return LayoutInflater.from(getContext()).inflate(R.layout.fragment_pings, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        mRecyclerView = (RecyclerView) view.findViewById(R.id.pings_recycler_view);
        AppProfile profile = TraceratopsApplication.from(getActivity()).getCurrentAppProfile();
        if(profile!=null) {
            setAdapterProfile(profile);
        }

        super.onViewCreated(view, savedInstanceState);
    }

    private void setAdapterProfile(AppProfile profile) {
        mProfile = profile;
        mEntryAdapter = new PingEntryAdapter(getContext(), profile.getPingEntries());
        LinearLayoutManager llm = new LinearLayoutManager(getContext());
        llm.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(llm);
        mRecyclerView.setAdapter(mEntryAdapter);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mNotifier = new ProfileUpdateNotifier(TraceratopsApplication.from(getActivity()).getCurrentAppProfile()) {
            @Override
            protected void onProfileChanged(AppProfile newProfile, AppProfile oldProfile) {
                setAdapterProfile(newProfile);
            }

            @Override
            public void onEntryListUpdated(List<BaseEntry> mEntryList) {
                mEntryAdapter.notifyDataSetChanged();
                mEntryAdapter.updateDataSet(mProfile.getPingEntries());
            }

            @Override
            public void onEntryAdded(BaseEntry newEntry) {

            }

            @Override
            public void onEntriesCleared() {

            }
        };
        TraceratopsApplication.from(getActivity()).addProfileUpdateNotifier(mNotifier);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        TraceratopsApplication.from(getActivity()).removeProfileUpdateNotifier(mNotifier);
    }
}


text:
package io.delr3ves.sunshine.app.model;

import lombok.Data;

import java.io.Serializable;
import java.util.List;

/**
 * @author Sergio Arroyo - @delr3ves
 */
@Data
public class ForecastInformation implements Serializable {

    private List<DailyWeatherInfo> list;

}