text:
- General
- Directory Location
- Built-In Applications
- NuttShell (NSH) Built-In Commands
- Synchronous Built-In Commands
- Application Configuration File
- Example Built-In Application
- Building NuttX with Board-Specific Pieces Outside the Source Tree

## General

This folder provides various applications found in sub-directories. These
applications are not inherently a part of NuttX but are provided to help you
develop your own applications. The `apps/` directory is a _break away_ part of
the configuration that you may choose to use or not.

## Directory Location

The default application directory used by the NuttX build should be named
`apps/` (or `apps-x.y.z/` where `x.y.z` is the NuttX version number). This
`apps/` directory should appear in the directory tree at the same level as the
NuttX directory. Like:

```
 .
 |- nuttx
 |
 `- apps
```

If all of the above conditions are TRUE, then NuttX will be able to find the
application directory. If your application directory has a different name or is
location at a different position, then you will have to inform the NuttX build
system of that location. There are several ways to do that:

1) You can define `CONFIG_APPS_DIR` to be the full path to your application
   directory in the NuttX configuration file.
2) You can provide the path to the application directory on the command line
   like: `make APPDIR=<path>` or `make CONFIG_APPS_DIR=<path>`
3) When you configure NuttX using `tools/configure.sh`, you can provide that
   path to the application directory on the configuration command line like:
   `./configure.sh -a <app-dir> <board-name>:<config-name>`

## Built-In Applications

NuttX also supports applications that can be started using a name string. In
this case, application entry points with their requirements are gathered
together in two files:

- `builtin/builtin_proto.h` – Entry points, prototype function
- `builtin/builtin_list.h` – Application specific information and requirements

The build occurs in several phases as different build targets are executed: (1)
context, (2) depend, and (3) default (all). Application information is collected
during the make context build phase.

To execute an application function:

`exec_builtin()` is defined in the `apps/include/builtin/builtin.h`.

## NuttShell (NSH) Built-In Commands

One use of builtin applications is to provide a way of invoking your custom
application through the NuttShell (NSH) command line. NSH will support a
seamless method invoking the applications, when the following option is enabled
in the NuttX configuration file:

```conf
CONFIG_NSH_BUILTIN_APPS=y
```

Applications registered in the `apps/builtin/builtin_list.h` file will then be
accessible from the NSH command line. If you type `help` at the NSH prompt, you
will see a list of the registered commands.

## Synchronous Built-In Commands

By default, built-in commands started from the NSH command line will run
asynchronously with NSH. If you want to force NSH to execute commands then wait
for the command to execute, you can enable that feature by adding the following
to the NuttX configuration file:

```conf
CONFIG_SCHED_WAITPID=y
```

The configuration option enables support for the `waitpid()` RTOS interface.
When that interface is enabled, NSH will use it to wait, sleeping until the
built-in command executes to completion.

Of course, even with `CONFIG_SCHED_WAITPID=y` defined, specific commands can
still be forced to run asynchronously by adding the ampersand (`&`) after the
NSH command.

## Application Configuration File

The NuttX configuration uses `kconfig-frontends` tools and the NuttX
configuration file (`.config`) file. For example, the NuttX `.config` may have:

```conf
CONFIG_EXAMPLES_HELLO=y
```

This will select the `apps/examples/hello` in the following way:

- The top-level make will include `examples/Make.defs`
- `examples/Make.defs` will set `CONFIGURED_APPS += $(APPDIR)/examples/hello`
  like this:

```makefile
  ifneq ($(CONFIG_EXAMPLES_HELLO),)
  CONFIGURED_APPS += $(APPDIR)/examples/hello
  endif
```

## Example Built-In Application

An example application skeleton can be found under the `examples/hello`
sub-directory. This example shows how a builtin application can be added to the
project. One must:

 1. Create sub-directory as: progname

 2. In this directory there should be:

    - A `Make.defs` file that would be included by the `apps/Makefile`
    - A `Kconfig` file that would be used by the configuration tool (see the
      file `kconfig-language.txt` in the NuttX tools repository). This `Kconfig`
      file should be included by the `apps/Kconfig` file
    - A `Makefile`, and
    - The application source code.

 3. The application source code should provide the entry point:

    ```c
    main()
    ```

 4. Set the requirements in the file: `Makefile`, specially the lines:

    ```makefile
    PROGNAME   = progname
    PRIORITY   = SCHED_PRIORITY_DEFAULT
    STACKSIZE  = 768
    ASRCS      = asm source file list as a.asm b.asm ...
    CSRCS      = C source file list as foo1.c foo2.c ..
    ```

 5. The `Make.defs` file should include a line like:

    ```makefile
    ifneq ($(CONFIG_PROGNAME),)
    CONFIGURED_APPS += progname
    endif
    ```

## Building NuttX with Board-Specific Pieces Outside the Source Tree

Q: Has anyone come up with a tidy way to build NuttX with board- specific pieces
   outside the source tree?

A: Here are three:

   1) There is a make target called `make export`. It will build NuttX, then
      bundle all of the header files, libraries, startup objects, and other
      build components into a `.zip` file. You can move that `.zip` file into
      any build environment you want. You can even build NuttX under a DOS `CMD`
      window.

      This make target is documented in the top level `nuttx/README.txt`.

   2) You can replace the entire `apps/` directory. If there is nothing in the
      `apps/` directory that you need, you can define `CONFIG_APPS_DIR` in your
      `.config` file so that it points to a different, custom application
      directory.

      You can copy any pieces that you like from the old apps/directory to your
      custom apps directory as necessary.

      This is documented in `NuttX/boards/README.txt` and
      `nuttx/Documentation/NuttXPortingGuide.html` (Online at
      https://bitbucket.org/nuttx/nuttx/src/master/Documentation/NuttXPortingGuide.html#apndxconfigs
      under _Build options_). And in the `apps/README.txt` file.

   3) If you like the random collection of stuff in the `apps/` directory but
      just want to expand the existing components with your own, external
      sub-directory then there is an easy way to that too: You just create a
      symbolic link in the `apps/` directory that redirects to your application
      sub-directory.

      In order to be incorporated into the build, the directory that you link
      under the `apps/` directory should contain (1) a `Makefile` that supports
      the `clean` and `distclean` targets (see other `Makefile`s for examples),
      and (2) a tiny `Make.defs` file that simply adds the custom build
      directories to the variable `CONFIGURED_APPS` like:

      ```makefile
      CONFIGURED_APPS += my_directory1 my_directory2
      ```

      The `apps/Makefile` will always automatically check for the existence of
      subdirectories containing a `Makefile` and a `Make.defs` file. The
      `Makefile` will be used only to support cleaning operations. The Make.defs
      file provides the set of directories to be built; these directories must
      also contain a `Makefile`. That `Makefile` must be able to build the
      sources and add the objects to the `apps/libapps.a` archive. (see other
      `Makefile`s for examples). It should support the all, install, context,
      and depend targets.

      `apps/Makefile` does not depend on any hardcoded lists of directories.
      Instead, it does a wildcard search to find all appropriate directories.
      This means that to install a new application, you simply have to copy the
      directory (or link it) into the `apps/` directory. If the new directory
      includes a `Makefile` and `Make.defs` file, then it will automatically be
      included in the build.

      If the directory that you add also includes a `Kconfig` file, then it will
      automatically be included in the NuttX configuration system as well.
      `apps/Makefile` uses a tool at `apps/tools/mkkconfig.sh` that dynamically
      builds the `apps/Kconfig` file at pre-configuration time.

      You could, for example, create a script called `install.sh` that installs
      a custom application, configuration, and board specific directory:

      a) Copy `MyBoard` directory to `boards/MyBoard`.
      b) Add a symbolic link to `MyApplication` at `apps/external`.
      c) Configure NuttX, usually by:

      ```bash
      tools/configure.sh MyBoard:MyConfiguration
      ```

      Use of the name `apps/external` is suggested because that name is included
      in the `.gitignore` file and will save you some nuisance when working with
      GIT.

# Export restrictions

This distribution includes cryptographic software. The country in which you
currently reside may have restrictions on the import, possession, use, and/or
re-export to another country, of encryption software. BEFORE using any encryption
software, please check your country's laws, regulations and policies concerning
the import, possession, or use, and re-export of encryption software, to see if
this is permitted. See <http://www.wassenaar.org/> for more information.

The U.S. Government Department of Commerce, Bureau of Industry and Security (BIS),
has classified this software as Export Commodity Control Number (ECCN) 5D002.C.1,
which includes information security software using or performing cryptographic
functions with asymmetric algorithms. The form and manner of this Apache Software
Foundation distribution makes it eligible for export under the License Exception ENC
Technology Software Unrestricted (TSU) exception (see the BIS Export Administration
Regulations, Section 740.13) for both object code and source code.

The following provides more details on the included cryptographic software:
https://tls.mbed.org/supported-ssl-ciphersuites.


text:
<?php

namespace Acme\DemoBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Acme\DemoBundle\Entity\Test;
use Acme\DemoBundle\Form\TestType;

/**
 * Test controller.
 *
 * @Route("/test")
 */
class TestController extends Controller
{
    /**
     * Lists all Test entities.
     *
     * @Route("/", name="test")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getEntityManager();

        $entities = $em->getRepository('AcmeDemoBundle:Test')->findAll();

        return array('entities' => $entities);
    }

    /**
     * Finds and displays a Test entity.
     *
     * @Route("/{id}/show", name="test_show")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('AcmeDemoBundle:Test')->find($id);

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

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

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),        );
    }

    /**
     * Displays a form to create a new Test entity.
     *
     * @Route("/new", name="test_new")
     * @Template()
     */
    public function newAction()
    {
        $entity = new Test();
        $form   = $this->createForm(new TestType(), $entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView()
        );
    }

    /**
     * Creates a new Test entity.
     *
     * @Route("/create", name="test_create")
     * @Method("post")
     * @Template("AcmeDemoBundle:Test:new.html.twig")
     */
    public function createAction()
    {
        $entity  = new Test();
        $request = $this->getRequest();
        $form    = $this->createForm(new TestType(), $entity);
        $form->bindRequest($request);

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

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

        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView()
        );
    }

    /**
     * Displays a form to edit an existing Test entity.
     *
     * @Route("/{id}/edit", name="test_edit")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('AcmeDemoBundle:Test')->find($id);

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

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

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Edits an existing Test entity.
     *
     * @Route("/{id}/update", name="test_update")
     * @Method("post")
     * @Template("AcmeDemoBundle:Test:edit.html.twig")
     */
    public function updateAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('AcmeDemoBundle:Test')->find($id);

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

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

        $request = $this->getRequest();

        $editForm->bindRequest($request);

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

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

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Deletes a Test entity.
     *
     * @Route("/{id}/delete", name="test_delete")
     * @Method("post")
     */
    public function deleteAction($id)
    {
        $form = $this->createDeleteForm($id);
        $request = $this->getRequest();

        $form->bindRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getEntityManager();
            $entity = $em->getRepository('AcmeDemoBundle:Test')->find($id);

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

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

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

    private function createDeleteForm($id)
    {
        return $this->createFormBuilder(array('id' => $id))
            ->add('id', 'hidden')
            ->getForm()
        ;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.chaston.oakfunds.security;

import org.chaston.oakfunds.storage.StorageException;

/**
 * TODO(mchaston): write JavaDocs
 */
public interface UserAuthenticationManager {
  AuthenticationScope authenticateUser() throws StorageException, AuthenticationException;
}


text:
{-# LANGUAGE OverloadedStrings #-}
module Style where

import Text.LaTeX

import Commands

import Style.Outer (outerStyle)

presentationStyle :: Monad m => LaTeXT_ m
presentationStyle = do

  mode "presentation"

  useinnertheme ["shadow=true"] "rounded"

  outerStyle

  usecolortheme "beaver"

  setbeamerfont "block title" (raw "size={}")

  setbeamercolor "titlelike" "parent=structure,bg=white"

  mode "all"

  -- bullets style
  setbeamertemplate "itemize item" (usebeamercolor "fg" "title" <> large mvRightarrow)
  setbeamertemplate "itemize subitem" (usebeamercolor "fg" "title" <> flatsteel)
  setbeamertemplate "itemize subsubitem" (usebeamercolor "bg" "frametitle right" <> flatsteel)

  -- caption without stuff at the beginning
  setbeamertemplate "caption" (raggedright <> scriptsize insertcaption <> par)

  -- reduce the caption distance from the figure
  setlength abovecaptionskip (Pt 2)


text:
package kariminf.langpi.basic.hungarian;

import kariminf.langpi.basic.BasicInfo;

public class HuInfo implements BasicInfo {

	@Override
	public String getIndicator() {
		return "hu";
	}

	@Override
	public String getLangEnglishName() {
		return "Hungarian";
	}

	@Override
	public String getLangName() {
		return "magyar";
	}

	@Override
	public String getClassPrefix() {
		return "Hu";
	}

}


text:
package se.trixon.nbmpc.ui;

import javax.swing.JButton;
import se.trixon.almond.util.Dict;
import se.trixon.nbmpc.actions.ConnectAction;
import se.trixon.nbmpc.actions.DisconnectAction;

/**
 *
 * @author Patrik Karlsson
 */
public class ConnectionPanel extends javax.swing.JPanel {

    /**
     * Creates new form ConnectionPanel
     */
    public ConnectionPanel() {
        initComponents();

        ConnectAction muteAction = new ConnectAction();
        JButton connectButton = muteAction.getButton();

        DisconnectAction unmuteAction = new DisconnectAction();
        JButton disconnectButton = unmuteAction.getButton();

        buttonPanel.add(connectButton);
        buttonPanel.add(disconnectButton);
    }

    /**
     * This method is called from within the constructor to initialize the form. WARNING: Do NOT
     * modify this code. The content of this method is always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        buttonPanel = new javax.swing.JPanel();
        jCheckBox1 = new javax.swing.JCheckBox();
        hostPanel = new javax.swing.JPanel();
        hostLabel = new javax.swing.JLabel();
        hostTextField = new javax.swing.JTextField();
        portLabel = new javax.swing.JLabel();
        portSpinner = new javax.swing.JSpinner();
        passwordLabel = new javax.swing.JLabel();
        passwordField = new javax.swing.JPasswordField();

        setBorder(javax.swing.BorderFactory.createEtchedBorder());
        setLayout(new java.awt.GridBagLayout());

        buttonPanel.setLayout(new java.awt.GridLayout());
        add(buttonPanel, new java.awt.GridBagConstraints());

        jCheckBox1.setText(org.openide.util.NbBundle.getMessage(ConnectionPanel.class, "ConnectionPanel.jCheckBox1.text")); // NOI18N
        jCheckBox1.setAlignmentX(0.5F);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        add(jCheckBox1, gridBagConstraints);

        hostLabel.setText(Dict.HOST.toString());

        portLabel.setText(Dict.PORT.toString());

        portSpinner.setModel(new javax.swing.SpinnerNumberModel(6600, 1000, 65536, 1));
        portSpinner.setMinimumSize(new java.awt.Dimension(72, 26));

        passwordLabel.setText(Dict.PASSWORD.toString());

        javax.swing.GroupLayout hostPanelLayout = new javax.swing.GroupLayout(hostPanel);
        hostPanel.setLayout(hostPanelLayout);
        hostPanelLayout.setHorizontalGroup(
            hostPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(hostPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(hostPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(hostTextField)
                    .addGroup(hostPanelLayout.createSequentialGroup()
                        .addGroup(hostPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(hostLabel)
                            .addComponent(portLabel)
                            .addComponent(passwordLabel))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(portSpinner, javax.swing.GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE)
                    .addComponent(passwordField))
                .addContainerGap())
        );
        hostPanelLayout.setVerticalGroup(
            hostPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(hostPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(hostLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(hostTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(portLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(portSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(passwordLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(passwordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        add(hostPanel, gridBagConstraints);
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel buttonPanel;
    private javax.swing.JLabel hostLabel;
    private javax.swing.JPanel hostPanel;
    private javax.swing.JTextField hostTextField;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JPasswordField passwordField;
    private javax.swing.JLabel passwordLabel;
    private javax.swing.JLabel portLabel;
    private javax.swing.JSpinner portSpinner;
    // End of variables declaration//GEN-END:variables
}


text:
import os
import pytest
from flaky import flaky
from click.testing import CliRunner

from geth.accounts import create_new_account

from web3.utils.string import force_text

from populus.project import Project

from populus.utils.filesystem import (
    get_contracts_dir,
)

from populus.cli import main

@flaky
def test_initializing_local_chain(project_dir, write_project_file):
    write_project_file('populus.ini', "[chain:local_a]")
    project = Project()

    runner = CliRunner()

    chain = project.get_chain('local_a')

    deploy_from = force_text(
        create_new_account(chain.geth.data_dir, b'a-test-password')
    )

    with chain:
        chain.wait.for_unlock(chain.web3.eth.coinbase, timeout=30)
        funding_txn_hash = chain.web3.eth.sendTransaction({
            'from': chain.web3.eth.coinbase,
            'to': deploy_from,
            'value': int(chain.web3.toWei(10, 'ether')),
        })
        chain.wait.for_receipt(funding_txn_hash, timeout=60)

    result = runner.invoke(
        main,
        ['chain', 'init'],
        input=((
            "local_a\n"          # choose chain.
            "{0}\n"              # pick deploy account.
            "Y\n"                # set account as default
            "a-test-password\n"  # unlock account
            "".format(deploy_from)
        ))
    )

    assert result.exit_code == 0, result.output + str(result.exception)

    updated_project = Project()
    assert 'registrar' in updated_project.config.chains['local_a']
    assert 'deploy_from' in updated_project.config.chains['local_a']

@flaky
def test_initializing_with_unlocked_account(project_dir, write_project_file):
    write_project_file('populus.ini', "[chain:local_a]")
    runner = CliRunner()

    result = runner.invoke(
        main,
        ['chain', 'init'],
        input=((
            "local_a\n"          # choose chain.
            "0\n"              # pick deploy account.
            "Y\n"                # set account as default
        ))
    )

    assert result.exit_code == 0, result.output + str(result.exception)

    updated_project = Project()
    assert 'registrar' in updated_project.config.chains['local_a']
    assert 'deploy_from' in updated_project.config.chains['local_a']

@flaky
def test_initializing_with_specified_chain(project_dir, write_project_file):
    write_project_file('populus.ini', "[chain:local_a]")
    runner = CliRunner()

    result = runner.invoke(
        main,
        ['chain', 'init', 'local_a'],
        input=((
            "0\n"              # pick deploy account.
            "Y\n"                # set account as default
        ))
    )

    assert result.exit_code == 0, result.output + str(result.exception)

    updated_project = Project()
    assert 'registrar' in updated_project.config.chains['local_a']
    assert 'deploy_from' in updated_project.config.chains['local_a']

@flaky
def test_initializing_no_choices(project_dir, write_project_file):
    write_project_file('populus.ini', "[chain:local_a]")
    project = Project()

    with project.get_chain('local_a') as chain:
        project.config.set('chain:local_a', 'deploy_from', chain.web3.eth.coinbase)
        project.write_config()

    runner = CliRunner()

    result = runner.invoke(
        main,
        ['chain', 'init', 'local_a'],
    )

    assert result.exit_code == 0, result.output + str(result.exception)

    updated_project = Project()
    assert 'registrar' in updated_project.config.chains['local_a']
    assert 'deploy_from' in updated_project.config.chains['local_a']


text:
(function() {

  var squares = document.getElementsByClassName('board-square');
  var gsm = new GameStateManager();

  addClickListeners();

  function addClickListeners() {
    for (var i = 0; i < 9; i++) {
      var input_id = 'brd-in-' + (i + 1);
      var square_val = parseInt(document.getElementById(input_id).value);
      if (!square_val) {
        squares[i].addEventListener('click', submitForm);
      }
    }
  }

  function submitForm(e) {
    var squareNum = parseInt(e.target.id.replace('sq_', ''));
    var id = 'brd-in-' + squareNum;
    document.getElementById(id).value = gsm.getPlayerMove();
    document.getElementById('board-form').submit();
  }

})();


text:
var express = require('express');
var router = express.Router();

/* GET projects listing. */
router.get('/', function(req, res) {
  res.render('projects',{title:"raks437 | Code Playground"});
});

module.exports = router;


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>keyczar.keyczar.Keyczar</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Home

         Trees

         Indices

         Help

Keyczar

        Package keyczar ::
        Module keyczar ::
        Class Keyczar

[hide private]

[frames] | no frames]

Class Keyczar

source code

object --+
         |
        Keyczar

Known Subclasses:

Encrypter

, GenericKeyczar

, Verifier

Abstract Keyczar base class.

        Instance Methods
        [hide private]

          __init__(self,
        reader)

      x.__init__(...) initializes x; see x.__class__.__doc__ for signature

            source code

          __str__(self)

      str(x)

            source code

      keys.Key

          _ParseHeader(self,
        header)

      Parse the header and verify version, format info.

            source code

          IsAcceptablePurpose(self,
        purpose)

      Indicates whether purpose is valid.

            source code

      keys.Key

          GetKey(self,
        id)

      Returns the key associated with the given id, a hash or a version.

            source code

          _AddKey(self,
        version,
        key)

            source code

Inherited from object:
      __delattr__,
      __getattribute__,
      __hash__,
      __new__,
      __reduce__,
      __reduce_ex__,
      __repr__,
      __setattr__

        Static Methods
        [hide private]

      Keyczar

          Read(location)

      Return a Keyczar object created from FileReader at given location.

            source code

        Properties
        [hide private]

        versions

      List of versions in key set.

        primary_key

      The primary key for this key set.

Inherited from object:
      __class__

        Method Details
        [hide private]

__init__(self,
        reader)

(Constructor)

  	source code

x.__init__(...) initializes x; see x.__class__.__doc__ for
  signature

Overrides:
        object.__init__

(inherited documentation)

__str__(self)

(Informal representation operator)

  	source code

str(x)

Overrides:
        object.__str__

(inherited documentation)

_ParseHeader(self,
        header)

  	source code

Parse the header and verify version, format info. Return key if
  exists.

Parameters:

header (string) - the bytes of the header of Keyczar output

Returns: keys.Key

the key identified by the hash in the header

Raises:

BadVersionError - if header specifies an illegal version

KeyNotFoundError - if key specified in header doesn't exist

Read(location)

Static Method

  	source code

Return a Keyczar object created from FileReader at given location.

Parameters:

location (string) - pathname of the directory storing the key files

Returns: Keyczar

a Keyczar to manage the keys stored at the given location

IsAcceptablePurpose(self,
        purpose)

  	source code

Indicates whether purpose is valid. Abstract method.

GetKey(self,
        id)

  	source code

Returns the key associated with the given id, a hash or a version.

Parameters:

id (string or keydata.KeyVersion) - Either the hash identifier of the key or its version.

Returns: keys.Key

key associated with this id or None if id doesn't exist.

Raises:

KeyNotFoundError - if key with given id doesn't exist

        Property Details
        [hide private]

versions

List of versions in key set.

Get Method:

unreachable(self)

primary_key

The primary key for this key set.

Get Method:

unreachable(self)

         Home

         Trees

         Indices

         Help

Keyczar

    Generated by Epydoc 3.0.1 on Sun Aug 10 17:05:05 2008

      http://epydoc.sourceforge.net


text:
<?php

namespace JHWEB\SeguridadVialBundle\Repository;

/**
 * SvSenialInventarioMunicipioRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class SvSenialInventarioMunicipioRepository extends \Doctrine\ORM\EntityRepository
{
	//Obtiene el numero maximo de las inventario
    public function findMaximo($anio)
    {
        $em = $this->getEntityManager();
        $dql = "SELECT MAX(si.consecutivo) AS maximo
            FROM JHWEBSeguridadVialBundle:SvSenialInventarioMunicipio si
            WHERE YEAR(si.fecha) = :ANIO";
        $consulta = $em->createQuery($dql);
        $consulta->setParameter('ANIO', $anio);
        return $consulta->getOneOrNullResult();
    }
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">

	<title>MMRelationship Class Reference</title>

	<link rel="stylesheet" href="../css/style.css">
	<meta name="viewport" content="initial-scale=1, maximum-scale=1.4">
	<meta name="generator" content="appledoc 2.2.1 (build 1333)">

				MarshmallowOrmament

				KellyHuberty

Index

Hierarchy

							On This Page

							<select id="jump-to">
	<option value="top">Jump To…</option>

	<option value="tasks">Tasks</option>

	<optgroup label="Properties">

		<option value="//api/name/autoRelateName">autoRelateName</option>

		<option value="//api/name/autoRelateNumber">autoRelateNumber</option>

		<option value="//api/name/className">className</option>

		<option value="//api/name/cloudRelater">cloudRelater</option>

		<option value="//api/name/entityName">entityName</option>

		<option value="//api/name/hasMany">hasMany</option>

		<option value="//api/name/links">links</option>

		<option value="//api/name/name">name</option>

		<option value="//api/name/recordEntityName">recordEntityName</option>

		<option value="//api/name/shareable">shareable</option>

		<option value="//api/name/storeRelater">storeRelater</option>

	</optgroup>

	<optgroup label="Class Methods">

		<option value="//api/name/relationshipWithDictionary:">+ relationshipWithDictionary:</option>

	</optgroup>

	<optgroup label="Instance Methods">

		<option value="//api/name/addAllLinks:">- addAllLinks:</option>

		<option value="//api/name/allLinks">- allLinks</option>

		<option value="//api/name/log">- log</option>

		<option value="//api/name/onSelf">- onSelf</option>

	</optgroup>

</select>

MMRelationship Class Reference

	Inherits from
	MMSchemaObject : NSObject

	Declared in
	MMRelationship.h

  recordEntityName

@property (nonatomic, retain) NSString *recordEntityName

  entityName

@property (nonatomic, retain) NSString *entityName

  className

@property (nonatomic, retain) NSString *className

  links

@property (nonatomic, retain) MMSet *links

  name

@property (nonatomic, retain) NSString *name

  hasMany

@property (nonatomic) BOOL hasMany

  autoRelateNumber

@property (nonatomic, readonly) NSNumber *autoRelateNumber

  shareable

@property (nonatomic) BOOL shareable

  autoRelateName

@property (nonatomic, retain) NSString *autoRelateName

  cloudRelater

@property (nonatomic, retain) MMRelater *cloudRelater

  storeRelater

@property (nonatomic, retain) MMRelater *storeRelater

+ relationshipWithDictionary:

+ (instancetype)relationshipWithDictionary:(NSDictionary *)dict

– allLinks

- (NSArray *)allLinks

– addAllLinks:

- (void)addAllLinks:(NSArray *)links

– log

- (void)log

– onSelf

- (BOOL)onSelf

Copyright © 2015 KellyHuberty. All rights reserved. Updated: 2015-10-23

Generated by appledoc 2.2.1 (build 1333).


text:
*{concise,reliable,cross-platform} turnup of k8s clusters*

min-turnup has been renamed and moved to [kubernetes/kubernetes-anywhere](https://github.com/kubernetes/kubernetes-anywhere).


text:
using ePlanifViewModelsLib.ePlanifService;
using Nager.Date;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ViewModelLib;

namespace ePlanifViewModelsLib
{
	public class CalendarWeekRuleViewModelCollection:WCFViewModelCollection<CalendarWeekRuleViewModel,CalendarWeekRule>
	{

		public CalendarWeekRuleViewModelCollection(ePlanifServiceViewModel Service)
			:base(Service)
		{
		}

		protected override Task<bool> OnAddInModelAsync(IePlanifServiceClient Client, CalendarWeekRuleViewModel ViewModel)
		{
			throw new NotImplementedException();
		}
		protected override Task<bool> OnEditInModelAsync(IePlanifServiceClient Client, CalendarWeekRuleViewModel ViewModel)
		{
			throw new NotImplementedException();
		}
		protected override Task<bool> OnRemoveFromModelAsync(IePlanifServiceClient Client, CalendarWeekRuleViewModel ViewModel)
		{
			throw new NotImplementedException();
		}

		protected override Task<CalendarWeekRule> OnCreateEmptyModelAsync()
		{
			return Task.FromResult(CalendarWeekRule.FirstDay);
		}

		protected override Task<CalendarWeekRuleViewModel> OnCreateViewModelItem(Type ModelType)
		{
			return Task.FromResult(new CalendarWeekRuleViewModel(Service));
		}

		protected override async Task<IEnumerable<CalendarWeekRule>> OnLoadModelAsync(IePlanifServiceClient Client)
		{

			return await Task.FromResult(Enum.GetValues(typeof(CalendarWeekRule)).Cast<CalendarWeekRule>() );

		}

	}
}


text:
html, body {
  height: 100%;
  width: 100%;
  padding: 0;
  margin: 0;
}

body,
#container,
#main,
#navigation,
#content {
  background: #ffffff;
}

#content {
  background: no-repeat;
  background-image: url('../images/luchia-logo.png');
  background-position: right top;
  background-origin: content-box;
}

#navigation h2 {
  background: #cccccc;
  margin-right: 10px;
  border: 1px solid #cccccc;
  border-radius: 5px;
}
#content {
  height: 100%;
}
#about {
  display: none;
}
table.module_list td.name,
table.module_list td.summary,
table.function_list td.name,
table.function_list td.summary {
  background: #ffffff;
  border-color: gray;
}
a:link, a:visited {
  color: #BC101D;
}


text:
@implementation NSDictionary(SafeData)

- (id)objectSafeForKey:(NSString*)key
{
    id object = nil;
    if([self respondsToSelector:@selector(objectForKey:)] && key){
        object = [self objectForKey:key];
    }
    return object;
}
- (NSArray*)arraySafeForKey:(NSString*)key
{
    id object = nil;
    if([self respondsToSelector:@selector(objectForKey:)] && key){
        object = [self objectForKey:key];
    }
    if(![object isKindOfClass:[NSArray class]]){
        object = nil;
    }
    return object;
}
- (NSDictionary*)dictionarySafeForKey:(NSString*)key
{
    id object = nil;
    if([self respondsToSelector:@selector(objectForKey:)] && key){
        object = [self objectForKey:key];
    }
    if(![object isKindOfClass:[NSDictionary class]]){
        object = nil;
    }
    return object;
}
- (NSString*)stringSafeForKey:(NSString*)key
{
    id object = nil;
    if([self respondsToSelector:@selector(objectForKey:)] && key){
        object = [self objectForKey:key];
    }

    if([object isKindOfClass:[NSNumber class]]){

        NSNumber*number = (NSNumber*)object;
        object = [number stringValue];
    }

    if(![object isKindOfClass:[NSString class]] && ![object isKindOfClass:[NSNumber class]]){
        object = nil;
    }
    return object;
}
- (NSMutableArray*)mutableArraySafeForKey:(NSString*)key
{
    id object = nil;
    if([self respondsToSelector:@selector(objectForKey:)] && key){
        object = [self objectForKey:key];
    }
    if(![object isKindOfClass:[NSMutableArray class]]){
        object = nil;
    }
    return object;
}
- (NSMutableDictionary*)mutableDictionarySafeForKey:(NSString*)key
{
    id object = nil;
    if([self respondsToSelector:@selector(objectForKey:)] && key){
        object = [self objectForKey:key];
    }
    if(![object isKindOfClass:[NSMutableDictionary class]]){
        object = nil;
    }
    return object;
}
- (NSInteger)integerSafeForKey:(NSString*)key
{
    id object = nil;
    NSInteger num = 0;
    if([self respondsToSelector:@selector(objectForKey:)] && key){
        object = [self objectForKey:key];
    }
    if([object respondsToSelector:@selector(integerValue)]){
        num = [object integerValue];
    }
    return num;
}

- (long long)longlongSafeForKey:(NSString*)key
{
    id object = nil;
    long long num = 0;
    if([self respondsToSelector:@selector(objectForKey:)] && key){
        object = [self objectForKey:key];
    }
    if([object respondsToSelector:@selector(longLongValue)]){
        num = [object longLongValue];
    }
    return num;
}

- (CGFloat)floatSafeForKey:(NSString*)key
{
    id object = nil;
    CGFloat num = 0;
    if([self respondsToSelector:@selector(objectForKey:)] && key){
        object = [self objectForKey:key];
    }
    if([object respondsToSelector:@selector(floatValue)]){
        num = [object floatValue];
    }
    return num;
}
- (double)doubleSafeForKey:(NSString*)key
{
    id object = nil;
    double num = 0;
    if([self respondsToSelector:@selector(objectForKey:)] && key){
        object = [self objectForKey:key];
    }
    if([object respondsToSelector:@selector(doubleValue)]){
        num = [object doubleValue];
    }
    return num;
}
- (int)intSafeForKey:(NSString*)key
{
    id object = nil;
    int num = -1;
    if([self respondsToSelector:@selector(objectForKey:)] && key){
        object = [self objectForKey:key];
    }
    if([object respondsToSelector:@selector(intValue)]){
        num = [object intValue];
    }
    return num;
}

- (NSNumber*)numberSafeForKey:(NSString*)key
{
    id object = nil;
    NSNumber* num = nil;
    if([self respondsToSelector:@selector(objectForKey:)] && key){
        object = [self objectForKey:key];
    }
    if([object isKindOfClass:[NSNumber class]]){

        num = (NSNumber*)object;
    } else if ([object isKindOfClass:[NSString class]]) {
        num = [NSNumber numberWithFloat:[object floatValue]];
    }

    return num;
}

@end


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using JustGestures.Languages;

namespace JustGestures.OptionItems
{
    public partial class UC_blackList : UC_blackWhiteList
    {
        public UC_blackList()
        {
            InitializeComponent();
            this.Dock = DockStyle.Fill;
            m_name = new MyText("O_BL_name");
            m_caption = new MyText("O_BL_caption");
            I_infoText = new MyText("O_BL_info");
        }
    }
}


text:
package blgo

import (
	"io"
	"os"

	"github.com/gin-gonic/gin"
)

var config = loadConfig()

// Run and serve on 0.0.0.0:8080
func Run() {
	initDB()

	switch os.Getenv("ENV") {
	case "release":
		gin.SetMode(gin.ReleaseMode)
		logfile, _ := os.Create("blgo.log")
		gin.DefaultWriter = io.MultiWriter(logfile)
	}

	router := gin.Default()
	router.SetFuncMap(getFuncMap())

	router.LoadHTMLGlob("templates/*/*.html")

	router.Use(verifyDatabase())
	router.Static("/assets", "./assets")

	router.GET("/", rootHandler)
	router.GET("/feed", feedHandler)
	router.GET("/post/:slug", getPostHandler)
	router.GET("/new", newHandler)
	router.POST("/create", createPostHandler)
	router.POST("/delete", deletePostHandler)

	router.Run()
}


text:
package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"

	"github.com/emicklei/go-restful"
)

func main() {
	configFile := flag.String("config", "config.json", "-config <configfile>: use to override the default config file (config.json)")
	flag.Parse()
	config := ParseConfig(*configFile)
	if config.DBUser == "" {
		log.Fatalf("Could not read config file! exiting....")
	}

	cm := &CitationManager{}
	cm.AddSource(NewSampleGetter(config.DBUser, config.DBPassword, config.DBAddress, config.Database))

	ws := new(restful.WebService)
	ws.Path("/api").
		Consumes(restful.MIME_JSON).
		Produces(restful.MIME_JSON)

	ws.Route(ws.POST("citations/").To(cm.findAllCitationsForUser).
		Doc("Get all citations for a user given the correct params.").
		Param(ws.BodyParameter("last_name", "Last name of the person to get citations for.")).
		Param(ws.BodyParameter("dob", "The date of birth of the person to get citations for.")).
		Param(ws.BodyParameter("license_number", "License number of the person to get citations for.")).
		Writes(CitationResponse{}))

	restful.Filter(enableCORS)
	restful.Filter(restful.OPTIONSFilter())
	restful.Add(ws)

	log.Printf("Starting server on :%d", config.ServerPort)
	err := http.ListenAndServe(fmt.Sprintf("0.0.0.0:%d", config.ServerPort), nil)
	if err != nil {
		log.Fatalf("Error running server: %s", err)
	}
}

func enableCORS(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
	if origin := req.HeaderParameter(restful.HEADER_Origin); origin != "" {
		resp.AddHeader(restful.HEADER_AccessControlAllowOrigin, origin)
		resp.AddHeader(restful.HEADER_AccessControlAllowMethods, "GET,POST,OPTIONS,PUT,DELETE")
		resp.AddHeader(restful.HEADER_AccessControlAllowHeaders, fmt.Sprintf("%s,%s", restful.HEADER_AccessControlAllowOrigin, restful.HEADER_ContentType))
	}
	chain.ProcessFilter(req, resp)
}


text:
package io.motown.domain.api.chargingstation;

import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.util.Arrays;
import java.util.Collection;

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

@RunWith(Enclosed.class)
public class FirmwareStatusTest {

    @RunWith(Parameterized.class)
    public static class FromValueTest {
        private FirmwareStatus firmwareStatus;

        private String value;

        public FromValueTest(FirmwareStatus firmwareStatus, String value) {
            this.firmwareStatus = firmwareStatus;
            this.value = value;
        }

        @Parameterized.Parameters
        public static Collection<Object[]> data() {
            return Arrays.asList(new Object[][]{
                    {FirmwareStatus.DOWNLOAD_FAILED, "DownloadFailed"},
                    {FirmwareStatus.DOWNLOADED, "Downloaded"},
                    {FirmwareStatus.INSTALLATION_FAILED, "InstallationFailed"},
                    {FirmwareStatus.INSTALLED, "Installed"},
                    {FirmwareStatus.DOWNLOAD_FAILED, "DOWNLOADFAILED"},
                    {FirmwareStatus.DOWNLOADED, "DOWNLOADED"},
                    {FirmwareStatus.INSTALLATION_FAILED, "INSTALLATIONFAILED"},
                    {FirmwareStatus.INSTALLED, "INSTALLED"}
            });
        }

        @Test
        public void fromValueShouldReturnTheEnumForValue() {
            assertEquals(firmwareStatus, FirmwareStatus.fromValue(value));
        }

        @Test(expected = IllegalArgumentException.class)
        public void fromValueWithUnknownFirmwareStatusShouldThrowIllegalArgumentException() {
            FirmwareStatus.fromValue("NonExistentFirmwareStatus");
        }

        @Test(expected = NullPointerException.class)
        public void fromValueWithFirmwareStatusNullShouldThrowNullPointerException() {
            ComponentStatus.fromValue(null);
        }

        @Test
        public void toStringShouldReturnValue() {
            assertTrue(firmwareStatus.toString().equalsIgnoreCase(value));
        }
    }

    @RunWith(Parameterized.class)
    public static class ToStringTest {
        private FirmwareStatus firmwareStatus;

        private String value;

        public ToStringTest(FirmwareStatus firmwareStatus, String value) {
            this.firmwareStatus = firmwareStatus;
            this.value = value;
        }

        @Parameterized.Parameters
        public static Collection<Object[]> data() {
            return Arrays.asList(new Object[][]{
                    {FirmwareStatus.DOWNLOAD_FAILED, "DownloadFailed"},
                    {FirmwareStatus.DOWNLOADED, "Downloaded"},
                    {FirmwareStatus.INSTALLATION_FAILED, "InstallationFailed"},
                    {FirmwareStatus.INSTALLED, "Installed"}
            });
        }

        @Test
        public void toStringShouldReturnValue() {
            assertTrue(firmwareStatus.toString().equals(value));
        }
    }
}


text:
Redis Driver
==========

At this moment, this driver works with [SncRedisBundle](https://github.com/snc/SncRedisBundle), please install it if you want to use this driver.

/!\ WARNING /!\

Redis driver have to work with immediate delivery.

# 1) Define driver section on configuration

```yml
#config.yml
spy_timeline:
    drivers:
        redis:
            client:           ~ # snc_redis.default
            pipeline:         true
            prefix:           vlr_timeline
            classes:
                action:           'Spy\Timeline\Model\Action'
                component:        'Spy\Timeline\Model\Component'
                action_component: 'Spy\Timeline\Model\ActionComponent'
```

That's all

[index](https://github.com/stephpy/timeline-bundle/blob/master/Resources/doc/index.markdown)


text:
require_relative '../test_helper'

describe Rack::Prerender do

  bot = 'Baiduspider+(+http://www.baidu.com/search/spider.htm)'
  user = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36'

  before :each do
    @app = lambda do |params|
      [200, {}, ""]
    end

    @prerender = Rack::Prerender.new(@app)
  end

  it "should return a prerendered response for a crawler with the returned status code and headers" do
    request = Rack::MockRequest.env_for "/", "HTTP_USER_AGENT" => bot
    stub_request(:get, @prerender.build_api_url(request)).with(:headers => { 'User-Agent' => bot }).to_return(:body => "", :status => 301, :headers => { 'Location' => 'http://google.com'})
    response = Rack::Prerender.new(@app).call(request)

    assert_equal response[2].body, [""]
    assert_equal response[2].status, 301
    assert_equal( { 'location' => 'http://google.com', 'Content-Length' => '13'}, response[2].headers )
  end

  it "should return a prerendered reponse if user is a bot by checking for _escaped_fragment_" do
    request = Rack::MockRequest.env_for "/path?_escaped_fragment_=", "HTTP_USER_AGENT" => user
    stub_request(:get, @prerender.build_api_url(request)).with(:headers => { 'User-Agent' => user }).to_return(:body => "")
    response = Rack::Prerender.new(@app).call(request)

    assert_equal [""], response[2].body
  end

  it "should continue to app routes if the url is a bad url with _escaped_fragment_" do
    request = Rack::MockRequest.env_for "/path?query=string?_escaped_fragment_=", "HTTP_USER_AGENT" => user
    response = Rack::Prerender.new(@app).call(request)

    assert_equal "", response[2]
  end

  it "should continue to app routes if the request is not a GET" do
    request = Rack::MockRequest.env_for "/path?_escaped_fragment_=", { "HTTP_USER_AGENT" => user, "REQUEST_METHOD" => "POST" }
    response = Rack::Prerender.new(@app).call(request)

    assert_equal "", response[2]
  end

  it "should continue to app routes if user is not a bot by checking agent string" do
    request = Rack::MockRequest.env_for "/", "HTTP_USER_AGENT" => user
    response = Rack::Prerender.new(@app).call(request)

    assert_equal "", response[2]
  end

  it "should continue to app routes if user is a bot, but the bot is requesting a resource file" do
    request = Rack::MockRequest.env_for "/main.js?anyQueryParam=true", "HTTP_USER_AGENT" => bot
    response = Rack::Prerender.new(@app).call(request)

    assert_equal "", response[2]
  end

  it "should continue to app routes if the url is not part of the regex specific whitelist" do
    request = Rack::MockRequest.env_for "/saved/search/blah?_escaped_fragment_=", "HTTP_USER_AGENT" => bot
    response = Rack::Prerender.new(@app, whitelist: ['^/search', '/help']).call(request)

    assert_equal "", response[2]
  end

  it "should return a prerendered response if the url is part of the regex specific whitelist" do
    request = Rack::MockRequest.env_for "/search/things/123/page?_escaped_fragment_=", "HTTP_USER_AGENT" => bot
    stub_request(:get, @prerender.build_api_url(request)).to_return(:body => "")
    response = Rack::Prerender.new(@app, whitelist: ['^/search.*page', '/help']).call(request)

    assert_equal [""], response[2].body
  end

  it "should continue to app routes if the url is part of the regex specific blacklist" do
    request = Rack::MockRequest.env_for "/search/things/123/page", "HTTP_USER_AGENT" => bot
    response = Rack::Prerender.new(@app, blacklist: ['^/search', '/help']).call(request)

    assert_equal "", response[2]
  end

  it "should return a prerendered response if the url is not part of the regex specific blacklist" do
    request = Rack::MockRequest.env_for "/profile/search/blah", "HTTP_USER_AGENT" => bot
    stub_request(:get, @prerender.build_api_url(request)).to_return(:body => "")
    response = Rack::Prerender.new(@app, blacklist: ['^/search', '/help']).call(request)

    assert_equal [""], response[2].body
  end

  it "should continue to app routes if the referer is part of the regex specific blacklist" do
    request = Rack::MockRequest.env_for "/api/results", "HTTP_USER_AGENT" => bot, "HTTP_REFERER" => '/search'
    response = Rack::Prerender.new(@app, blacklist: ['^/search', '/help']).call(request)

    assert_equal "", response[2]
  end

  it "should return a prerendered response if the referer is not part of the regex specific blacklist" do
    request = Rack::MockRequest.env_for "/api/results", "HTTP_USER_AGENT" => bot, "HTTP_REFERER" => '/profile/search'
    stub_request(:get, @prerender.build_api_url(request)).to_return(:body => "")
    response = Rack::Prerender.new(@app, blacklist: ['^/search', '/help']).call(request)

    assert_equal [""], response[2].body
  end

  it "should return a prerendered response if a string is returned from before_render" do
    request = Rack::MockRequest.env_for "/", "HTTP_USER_AGENT" => bot
    response = Rack::Prerender.new(@app, before_render: Proc.new do |env| 'cached' end).call(request)

    assert_equal ["cached"], response[2].body
  end

  it "should return a prerendered response if a response is returned from before_render" do
    request = Rack::MockRequest.env_for "/", "HTTP_USER_AGENT" => bot
    response = Rack::Prerender.new(@app, before_render: Proc.new do |env| Rack::Response.new('cached2', 200, { 'test' => 'test2Header'}) end).call(request)

    assert_equal ["cached2"], response[2].body
    assert_equal response[2].status, 200
    assert_equal( { 'test' => 'test2Header', "Content-Length"=>"20"}, response[2].headers )
  end

  describe '#buildApiUrl' do
    it "should build the correct api url with the default url" do
      request = Rack::MockRequest.env_for "https://google.com/search?q=javascript"
      ENV['PRERENDER_SERVICE_URL'] = nil
      assert_equal 'http://service.prerender.io/https://google.com/search?q=javascript', @prerender.build_api_url(request)
    end

    it "should build the correct api url with an environment variable url" do
      ENV['PRERENDER_SERVICE_URL'] = 'http://prerenderurl.com'
      request = Rack::MockRequest.env_for "https://google.com/search?q=javascript"
      assert_equal 'http://prerenderurl.com/https://google.com/search?q=javascript', @prerender.build_api_url(request)
      ENV['PRERENDER_SERVICE_URL'] = nil
    end

    it "should build the correct api url with an initialization variable url" do
      @prerender = Rack::Prerender.new(@app, prerender_service_url: 'http://prerenderurl.com')
      request = Rack::MockRequest.env_for "https://google.com/search?q=javascript"
      assert_equal 'http://prerenderurl.com/https://google.com/search?q=javascript', @prerender.build_api_url(request)
    end

    # Check CF-Visitor header in order to Work behind CloudFlare with Flexible SSL (https://support.cloudflare.com/hc/en-us/articles/200170536)
    it "should build the correct api url for the Cloudflare Flexible SSL support" do
      request = Rack::MockRequest.env_for "http://google.com/search?q=javascript", { 'CF-VISITOR' => '"scheme":"https"'}
      ENV['PRERENDER_SERVICE_URL'] = nil
      assert_equal 'http://service.prerender.io/https://google.com/search?q=javascript', @prerender.build_api_url(request)
    end

    # Check X-Forwarded-Proto because Heroku SSL Support terminates at the load balancer
    it "should build the correct api url for the Heroku SSL Addon support with single value" do
      request = Rack::MockRequest.env_for "http://google.com/search?q=javascript", { 'X-FORWARDED-PROTO' => 'https'}
      ENV['PRERENDER_SERVICE_URL'] = nil
      assert_equal 'http://service.prerender.io/https://google.com/search?q=javascript', @prerender.build_api_url(request)
    end

    # Check X-Forwarded-Proto because Heroku SSL Support terminates at the load balancer
    it "should build the correct api url for the Heroku SSL Addon support with double value" do
      request = Rack::MockRequest.env_for "http://google.com/search?q=javascript", { 'X-FORWARDED-PROTO' => 'https,http'}
      ENV['PRERENDER_SERVICE_URL'] = nil
      assert_equal 'http://service.prerender.io/https://google.com/search?q=javascript', @prerender.build_api_url(request)
    end

    it "should build the correct api url for the protocol option" do
      @prerender = Rack::Prerender.new(@app, protocol: 'https')
      request = Rack::MockRequest.env_for "http://google.com/search?q=javascript"
      ENV['PRERENDER_SERVICE_URL'] = nil
      assert_equal 'http://service.prerender.io/https://google.com/search?q=javascript', @prerender.build_api_url(request)
    end
  end

end


text:
using System;
using System.Collections;
using System.Data;
using PCSComProduction.DCP.DS;
using PCSComProduction.WorkOrder.DS;
using PCSComUtils.Common;
using PCSComUtils.MasterSetup.DS;
using PCSComUtils.DataContext;
using System.Linq;
using System.Transactions;
using PCSComUtils.PCSExc;
using PCSComUtils.DataAccess;
using IsolationLevel = System.Transactions.IsolationLevel;

namespace PCSComProduction.WorkOrder.BO
{
	/// <summary>
	/// Multi WO Issue Material BO
	/// </summary>
	public class MultiWOIssueMaterialBO
	{
        private const string This = "PCSComProduction.WorkOrder.BO.MultiWOIssueMaterialBO";

		#region IMultiWOIssueMaterialBO Members

		public DataSet GetWorkingTime()
		{
			var dsShiftPattern = new PRO_ShiftPatternDS();
			return 	dsShiftPattern.GetWorkingTime();
		}
        public decimal GetOHQuantity(int iCcnid, int iBinId, int iLocationId, int iProductId)
        {
            using (var db = new PCSDataContext(Utils.Instance.ConnectionString))
            {
                var objBin = db.IV_BinCaches.SingleOrDefault(e => e.LocationID == iLocationId && e.BinID == iBinId && e.ProductID == iProductId);
                if (objBin != null)
                {
                    if (objBin.OHQuantity != null) return Convert.ToDecimal(objBin.OHQuantity.ToString());
                }
            }
            return 0;
        }

        public int AddAndReturnId(object pobjMaster, DataSet pdstDetailData)
		{
            const string methodName = "PCSComProduction.WorkOrder.BO.AddAndReturnID()";
			try
            {
                using (var trans = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions {IsolationLevel = IsolationLevel.ReadCommitted, Timeout = new TimeSpan(0, 1, 0)}))
                {
                    using (var db = new PCSDataContext(Utils.Instance.ConnectionString))
                    {
                        var serverDate = db.GetServerDate();
                        var tranTypeId = db.MST_TranTypes.FirstOrDefault(t => t.Code == TransactionTypeEnum.PROIssueMaterial.ToString()).TranTypeID;

                        #region add the master first

                        //add the master first
                        var objMaster = (PRO_IssueMaterialMasterVO)pobjMaster;
                        var issueMaster = new PRO_IssueMaterialMaster
                        {
                            MasterLocationID = objMaster.MasterLocationID,
                            PostDate = objMaster.PostDate,
                            IssueNo = objMaster.IssueNo,
                            CCNID = objMaster.CCNID,
                            IssuePurposeID = objMaster.IssuePurposeID,
                            ToLocationID = objMaster.ToLocationID,
                            ToBinID = objMaster.ToBinID,
                            ShiftID = objMaster.ShiftID
                        };
                        if (objMaster.WorkOrderMasterID > 0)
                            issueMaster.WorkOrderMasterID = objMaster.WorkOrderMasterID;
                        if (objMaster.WorkOrderDetailID > 0)
                            issueMaster.WorkOrderDetailID = objMaster.WorkOrderDetailID;

                        #endregion

                        #region insert issue detail

                        //update the detail
                        foreach (var issueDetail in
                           from DataRow dr in pdstDetailData.Tables[0].Rows
                           where dr.RowState != DataRowState.Deleted
                           select CreateIssueDetail(dr))
                        {
                            issueMaster.PRO_IssueMaterialDetails.Add(issueDetail);
                        }
                        db.PRO_IssueMaterialMasters.InsertOnSubmit(issueMaster);
                        db.SubmitChanges();

                        #endregion

                        #region cache data

                        foreach (var issueDetail in issueMaster.PRO_IssueMaterialDetails)
                        {
                            var allowNegative = issueDetail.ITM_Product.AllowNegativeQty.GetValueOrDefault(false);

                            #region subtract from source cache

                            #region bin cache

                            var sourceBin = db.IV_BinCaches.FirstOrDefault(e => e.LocationID == issueDetail.LocationID && e.BinID == issueDetail.BinID && e.ProductID == issueDetail.ProductID);
                            if (!allowNegative && (sourceBin == null || sourceBin.OHQuantity.GetValueOrDefault(0) < issueDetail.CommitQuantity))
                            {
                                var productError = new Hashtable
                                                       {
                                                           { ITM_ProductTable.PRODUCTID_FLD, issueDetail.ProductID },
                                                           { IV_BinCacheTable.OHQUANTITY_FLD, sourceBin == null ? 0 : sourceBin.OHQuantity.GetValueOrDefault(0) }
                                                       };
                                throw new PCSBOException(ErrorCode.MESSAGE_NOT_ENOUGH_COMPONENT_TO_COMPLETE, issueDetail.ITM_Product.Code, new Exception(), productError);
                            }
                            if (sourceBin != null)
                            {
                                sourceBin.OHQuantity = sourceBin.OHQuantity.GetValueOrDefault(0) - issueDetail.CommitQuantity;
                            }
                            else
                            {
                                // create new record
                                sourceBin = new IV_BinCache
                                {
                                    BinID = issueDetail.BinID.GetValueOrDefault(0),
                                    CCNID = issueMaster.CCNID,
                                    LocationID = issueDetail.LocationID,
                                    MasterLocationID = issueMaster.MasterLocationID,
                                    ProductID = issueDetail.ProductID,
                                    OHQuantity = -issueDetail.CommitQuantity
                                };
                                db.IV_BinCaches.InsertOnSubmit(sourceBin);
                            }

                            #endregion

                            #region location cache

                            var sourceLocation = db.IV_LocationCaches.FirstOrDefault(e => e.MasterLocationID == issueMaster.MasterLocationID && e.LocationID == issueDetail.LocationID && e.ProductID == issueDetail.ProductID);
                            if (!allowNegative && (sourceLocation == null || sourceLocation.OHQuantity.GetValueOrDefault(0) < issueDetail.CommitQuantity))
                            {
                                var productError = new Hashtable
                                                       {
                                                           { ITM_ProductTable.PRODUCTID_FLD, issueDetail.ProductID },
                                                           { IV_BinCacheTable.OHQUANTITY_FLD, sourceLocation == null ? 0 : sourceLocation.OHQuantity.GetValueOrDefault(0) }
                                                       };
                                throw new PCSBOException(ErrorCode.MESSAGE_NOT_ENOUGH_COMPONENT_TO_COMPLETE, issueDetail.ITM_Product.Code, new Exception(), productError);
                            }
                            if (sourceLocation != null)
                            {
                                sourceLocation.OHQuantity = sourceLocation.OHQuantity.GetValueOrDefault(0) - issueDetail.CommitQuantity;
                            }
                            else
                            {
                                // create new record
                                sourceLocation = new IV_LocationCache
                                {
                                    CCNID = issueMaster.CCNID,
                                    LocationID = issueDetail.LocationID,
                                    MasterLocationID = issueMaster.MasterLocationID,
                                    ProductID = issueDetail.ProductID,
                                    OHQuantity = -issueDetail.CommitQuantity
                                };
                                db.IV_LocationCaches.InsertOnSubmit(sourceLocation);
                            }

                            #endregion

                            #region master location cache

                            var sourceMasLocation = db.IV_MasLocCaches.FirstOrDefault(e => e.MasterLocationID == issueMaster.MasterLocationID && e.ProductID == issueDetail.ProductID);
                            if (!allowNegative && (sourceMasLocation == null || sourceMasLocation.OHQuantity.GetValueOrDefault(0) < issueDetail.CommitQuantity))
                            {
                                var productError = new Hashtable
                                                       {
                                                           { ITM_ProductTable.PRODUCTID_FLD, issueDetail.ProductID },
                                                           { IV_BinCacheTable.OHQUANTITY_FLD, sourceMasLocation == null ? 0 : sourceMasLocation.OHQuantity.GetValueOrDefault(0) }
                                                       };
                                throw new PCSBOException(ErrorCode.MESSAGE_NOT_ENOUGH_COMPONENT_TO_COMPLETE, issueDetail.ITM_Product.Code, new Exception(), productError);
                            }
                            if (sourceMasLocation != null)
                            {
                                sourceMasLocation.OHQuantity = sourceMasLocation.OHQuantity.GetValueOrDefault(0) - issueDetail.CommitQuantity;
                            }
                            else
                            {
                                // create new record
                                sourceMasLocation = new IV_MasLocCache
                                {
                                    CCNID = issueMaster.CCNID,
                                    MasterLocationID = issueMaster.MasterLocationID,
                                    ProductID = issueDetail.ProductID,
                                    OHQuantity = -issueDetail.CommitQuantity
                                };
                                db.IV_MasLocCaches.InsertOnSubmit(sourceMasLocation);
                            }

                            #endregion

                            #region Transaction history

                            var sourceHistory = new MST_TransactionHistory
                            {
                                CCNID = issueMaster.CCNID,
                                StockUMID = issueDetail.StockUMID,
                                MasterLocationID = issueMaster.MasterLocationID,
                                ProductID = issueDetail.ProductID,
                                LocationID = issueDetail.LocationID,
                                BinID = issueDetail.BinID,
                                RefMasterID = issueMaster.IssueMaterialMasterID,
                                RefDetailID = issueDetail.IssueMaterialDetailID,
                                PostDate = issueMaster.PostDate,
                                TransDate = serverDate,
                                Quantity = -issueDetail.CommitQuantity,
                                UserName = SystemProperty.UserName,
                                TranTypeID = tranTypeId,
                                BinCommitQuantity = sourceBin.CommitQuantity,
                                BinOHQuantity = sourceBin.OHQuantity,
                                IssuePurposeID = issueMaster.IssuePurposeID,
                                LocationCommitQuantity = sourceLocation.CommitQuantity,
                                LocationOHQuantity = sourceLocation.OHQuantity,
                                MasLocCommitQuantity = sourceMasLocation.CommitQuantity,
                                MasLocOHQuantity = sourceMasLocation.OHQuantity
                            };
                            db.MST_TransactionHistories.InsertOnSubmit(sourceHistory);

                            #endregion

                            #endregion

                            #region add to destination cache

                            #region bin cache

                            var destBin = db.IV_BinCaches.FirstOrDefault(e => e.LocationID == issueMaster.ToLocationID && e.BinID == issueMaster.ToBinID && e.ProductID == issueDetail.ProductID);
                            if (destBin != null)
                            {
                                destBin.OHQuantity = destBin.OHQuantity.GetValueOrDefault(0) + issueDetail.CommitQuantity;
                            }
                            else
                            {
                                // create new record
                                destBin = new IV_BinCache
                                {
                                    BinID = issueMaster.ToBinID.GetValueOrDefault(0),
                                    CCNID = issueMaster.CCNID,
                                    LocationID = issueMaster.ToLocationID.GetValueOrDefault(0),
                                    MasterLocationID = issueMaster.MasterLocationID,
                                    ProductID = issueDetail.ProductID,
                                    OHQuantity = issueDetail.CommitQuantity
                                };
                                db.IV_BinCaches.InsertOnSubmit(destBin);
                            }

                            #endregion

                            #region location cache

                            var destLocation = db.IV_LocationCaches.FirstOrDefault(e => e.MasterLocationID == issueMaster.MasterLocationID && e.LocationID == issueMaster.ToLocationID && e.ProductID == issueDetail.ProductID);
                            if (destLocation != null)
                            {
                                destLocation.OHQuantity = destLocation.OHQuantity.GetValueOrDefault(0) + issueDetail.CommitQuantity;
                            }
                            else
                            {
                                // create new record
                                destLocation = new IV_LocationCache
                                {
                                    CCNID = issueMaster.CCNID,
                                    LocationID = issueMaster.ToLocationID.GetValueOrDefault(0),
                                    MasterLocationID = issueMaster.MasterLocationID,
                                    ProductID = issueDetail.ProductID,
                                    OHQuantity = issueDetail.CommitQuantity
                                };
                                db.IV_LocationCaches.InsertOnSubmit(destLocation);
                            }

                            #endregion

                            #region master location cache

                            var destMasLocation = db.IV_MasLocCaches.FirstOrDefault(e => e.MasterLocationID == issueMaster.MasterLocationID && e.ProductID == issueDetail.ProductID);
                            if (destMasLocation != null)
                            {
                                destMasLocation.OHQuantity = destMasLocation.OHQuantity.GetValueOrDefault(0) + issueDetail.CommitQuantity;
                            }
                            else
                            {
                                // create new record
                                destMasLocation = new IV_MasLocCache
                                {
                                    CCNID = issueMaster.CCNID,
                                    MasterLocationID = issueMaster.MasterLocationID,
                                    ProductID = issueDetail.ProductID,
                                    OHQuantity = issueDetail.CommitQuantity
                                };
                                db.IV_MasLocCaches.InsertOnSubmit(destMasLocation);
                            }

                            #endregion

                            #region Transaction history

                            var destHistory = new MST_TransactionHistory
                            {
                                CCNID = issueMaster.CCNID,
                                StockUMID = issueDetail.StockUMID,
                                MasterLocationID = issueMaster.MasterLocationID,
                                ProductID = issueDetail.ProductID,
                                LocationID = issueMaster.ToLocationID,
                                BinID = issueMaster.ToBinID,
                                RefMasterID = issueMaster.IssueMaterialMasterID,
                                RefDetailID = issueDetail.IssueMaterialDetailID,
                                PostDate = issueMaster.PostDate,
                                TransDate = serverDate,
                                Quantity = issueDetail.CommitQuantity,
                                UserName = SystemProperty.UserName,
                                TranTypeID = tranTypeId,
                                BinCommitQuantity = destBin.CommitQuantity,
                                BinOHQuantity = destBin.OHQuantity,
                                IssuePurposeID = issueMaster.IssuePurposeID,
                                LocationCommitQuantity = destLocation.CommitQuantity,
                                LocationOHQuantity = destLocation.OHQuantity,
                                MasLocCommitQuantity = destMasLocation.CommitQuantity,
                                MasLocOHQuantity = destMasLocation.OHQuantity
                            };
                            db.MST_TransactionHistories.InsertOnSubmit(destHistory);

                            #endregion

                            #endregion

                            db.SubmitChanges();
                        }

                        #endregion

                        db.SubmitChanges();
                        trans.Complete();
                        return issueMaster.IssueMaterialMasterID;
                    }
                }
            }
            catch (PCSBOException ex)
            {
                if (ex.mCode == ErrorCode.SQLDUPLICATE_KEYCODE)
                    throw new PCSDBException(ErrorCode.DUPLICATE_KEY, methodName, ex);
                if (ex.mCode == ErrorCode.MESSAGE_NOT_ENOUGH_COMPONENT_TO_COMPLETE)
                    throw;
                throw new PCSDBException(ErrorCode.ERROR_DB, methodName, ex);
            }
		}

	    private static PRO_IssueMaterialDetail CreateIssueDetail(DataRow dr)
	    {
	        var objDetail = new PRO_IssueMaterialDetail();
	        if (dr[PRO_IssueMaterialDetailTable.LINE_FLD] != DBNull.Value)
	        {
	            objDetail.Line = Convert.ToInt32(dr[PRO_IssueMaterialDetailTable.LINE_FLD]);
	        }
	        if (dr[PRO_IssueMaterialDetailTable.COMMITQUANTITY_FLD] != DBNull.Value)
	        {
	            objDetail.CommitQuantity = Convert.ToDecimal(dr[PRO_IssueMaterialDetailTable.COMMITQUANTITY_FLD]);
	        }
	        if (dr[PRO_IssueMaterialDetailTable.PRODUCTID_FLD] != DBNull.Value)
	        {
	            objDetail.ProductID = Convert.ToInt32(dr[PRO_IssueMaterialDetailTable.PRODUCTID_FLD]);
	        }
	        if (dr[PRO_IssueMaterialDetailTable.LOCATIONID_FLD] != DBNull.Value)
	        {
	            objDetail.LocationID = Convert.ToInt32(dr[PRO_IssueMaterialDetailTable.LOCATIONID_FLD]);
	        }
	        if (dr[PRO_IssueMaterialDetailTable.BINID_FLD] != DBNull.Value)
	        {
	            objDetail.BinID = Convert.ToInt32(dr[PRO_IssueMaterialDetailTable.BINID_FLD]);
	        }
	        objDetail.Lot = dr[PRO_IssueMaterialDetailTable.LOT_FLD].ToString();
	        objDetail.Serial = dr[PRO_IssueMaterialDetailTable.SERIAL_FLD].ToString();
	        if (dr[PRO_IssueMaterialDetailTable.MASTERLOCATIONID_FLD] != DBNull.Value)
	        {
	            objDetail.MasterLocationID = Convert.ToInt32(dr[PRO_IssueMaterialDetailTable.MASTERLOCATIONID_FLD]);
	        }
	        if (dr[PRO_IssueMaterialDetailTable.STOCKUMID_FLD] != DBNull.Value)
	        {
	            objDetail.StockUMID = Convert.ToInt32(dr[PRO_IssueMaterialDetailTable.STOCKUMID_FLD]);
	        }
	        if (dr[PRO_IssueMaterialDetailTable.QASTATUS_FLD] != DBNull.Value)
	        {
	            objDetail.QAStatus = Convert.ToByte(dr[PRO_IssueMaterialDetailTable.QASTATUS_FLD]);
	        }
	        if (dr[PRO_IssueMaterialDetailTable.WORKORDERMASTERID_FLD] != DBNull.Value)
	        {
	            objDetail.WorkOrderMasterID = Convert.ToInt32(dr[PRO_IssueMaterialDetailTable.WORKORDERMASTERID_FLD]);
	        }
	        if (dr[PRO_IssueMaterialDetailTable.AVAILABLEQUANTITY_FLD] != DBNull.Value)
	        {
	            objDetail.AvailableQuantity = Convert.ToDecimal(dr[PRO_IssueMaterialDetailTable.AVAILABLEQUANTITY_FLD]);
	        }
	        if (dr[PRO_IssueMaterialDetailTable.WORKORDERDETAILID_FLD] != DBNull.Value)
	        {
	            objDetail.WorkOrderDetailID = Convert.ToInt32(dr[PRO_IssueMaterialDetailTable.WORKORDERDETAILID_FLD]);
	        }
	        if (dr[PRO_IssueMaterialDetailTable.BOMQUANTITY_FLD] != DBNull.Value)
	        {
	            objDetail.BomQuantity = Convert.ToDecimal(dr[PRO_IssueMaterialDetailTable.BOMQUANTITY_FLD]);
	        }
	        return objDetail;
	    }

		/// <summary>
		/// This method is used to get all the detail of the issue material
		/// Based on the Master ID of the table Issue Master Material
		/// </summary>
		/// <param name="pintMasterId"></param>
		/// <returns></returns>
		public DataSet GetDetailData(int pintMasterId)
		{
			var objProIssueMaterialDetailDS = new PRO_IssueMaterialDetailDS();
			DataSet dstDetailData = objProIssueMaterialDetailDS.GetDetailData(pintMasterId);
			return dstDetailData;
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="pstrLocationCode"></param>
		/// <returns>MST_LocationVO</returns>
		public string GetLocationNameByLocationCode(string pstrLocationCode)
		{
			var objDS = new MST_LocationDS();
			return objDS.GetNameFromCode(pstrLocationCode);
		}

		#endregion

	    /// <summary>
	    /// Delete transaction
	    /// </summary>
	    /// <param name="issueMasterId"></param>
        public void DeleteTransaction(int issueMasterId)
		{
            const string methodName = This + ".DeleteTransaction()";
            try
            {
                using (var trans = new TransactionScope())
                {
                    using (var db = new PCSDataContext(Utils.Instance.ConnectionString))
                    {
                        var tranTypeId = db.MST_TranTypes.FirstOrDefault(t => t.Code == TransactionTypeEnum.PROIssueMaterial.ToString()).TranTypeID;
                        var deleteTranTypeId = db.MST_TranTypes.FirstOrDefault(t => t.Code == TransactionTypeEnum.DeleteTransaction.ToString()).TranTypeID;
                        var serverDate = db.GetServerDate();

                        #region PRO_IssueMaterialMasters

                        var issueMaster = db.PRO_IssueMaterialMasters.FirstOrDefault(e => e.IssueMaterialMasterID == issueMasterId);
                        if (issueMaster == null)
                            return;

                        #endregion

                        #region old transaction history to be updated

                        var oldSourceHistory = db.MST_TransactionHistories.Where(e => e.RefMasterID == issueMasterId && e.TranTypeID == tranTypeId);
                        foreach (var history in oldSourceHistory)
                        {
                            // mark as delete transaction
                            history.TranTypeID = deleteTranTypeId;
                            history.UserName = SystemProperty.UserName;
                        }

                        #endregion

                        #region cache data

                        foreach (var issueDetail in issueMaster.PRO_IssueMaterialDetails)
                        {
                            var allowNegative = issueDetail.ITM_Product.AllowNegativeQty.GetValueOrDefault(false);

                            #region subtract from destionation cache

                            #region bin cache

                            var destBin = db.IV_BinCaches.FirstOrDefault(e => e.LocationID == issueMaster.ToLocationID && e.BinID == issueMaster.ToBinID && e.ProductID == issueDetail.ProductID);
                            if (!allowNegative && (destBin == null || destBin.OHQuantity.GetValueOrDefault(0) < issueDetail.CommitQuantity))
                            {
                                var productError = new Hashtable
                                                       {
                                                           { ITM_ProductTable.PRODUCTID_FLD, issueDetail.ProductID },
                                                           { IV_BinCacheTable.OHQUANTITY_FLD, destBin == null ? 0 : destBin.OHQuantity.GetValueOrDefault(0) }
                                                       };
                                throw new PCSBOException(ErrorCode.MESSAGE_NOT_ENOUGH_COMPONENT_TO_COMPLETE, issueDetail.ITM_Product.Code, new Exception(), productError);
                            }
                            if (destBin != null)
                            {
                                destBin.OHQuantity = destBin.OHQuantity.GetValueOrDefault(0) - issueDetail.CommitQuantity;
                            }
                            else
                            {
                                // create new record
                                destBin = new IV_BinCache
                                {
                                    BinID = issueMaster.ToBinID.GetValueOrDefault(0),
                                    CCNID = issueMaster.CCNID,
                                    LocationID = issueMaster.ToLocationID.GetValueOrDefault(0),
                                    MasterLocationID = issueMaster.MasterLocationID,
                                    ProductID = issueDetail.ProductID,
                                    OHQuantity = -issueDetail.CommitQuantity
                                };
                                db.IV_BinCaches.InsertOnSubmit(destBin);
                            }

                            #endregion

                            #region location cache

                            var destLocation = db.IV_LocationCaches.FirstOrDefault(e => e.MasterLocationID == issueMaster.MasterLocationID && e.LocationID == issueMaster.ToLocationID && e.ProductID == issueDetail.ProductID);
                            if (!allowNegative && (destLocation == null || destLocation.OHQuantity.GetValueOrDefault(0) < issueDetail.CommitQuantity))
                            {
                                var productError = new Hashtable
                                                       {
                                                           { ITM_ProductTable.PRODUCTID_FLD, issueDetail.ProductID },
                                                           { IV_BinCacheTable.OHQUANTITY_FLD, destLocation == null ? 0 : destLocation.OHQuantity.GetValueOrDefault(0) }
                                                       };
                                throw new PCSBOException(ErrorCode.MESSAGE_NOT_ENOUGH_COMPONENT_TO_COMPLETE, issueDetail.ITM_Product.Code, new Exception(), productError);
                            }
                            if (destLocation != null)
                            {
                                destLocation.OHQuantity = destLocation.OHQuantity.GetValueOrDefault(0) - issueDetail.CommitQuantity;
                            }
                            else
                            {
                                // create new record
                                destLocation = new IV_LocationCache
                                {
                                    CCNID = issueMaster.CCNID,
                                    LocationID = issueMaster.ToLocationID.GetValueOrDefault(0),
                                    MasterLocationID = issueMaster.MasterLocationID,
                                    ProductID = issueDetail.ProductID,
                                    OHQuantity = -issueDetail.CommitQuantity
                                };
                                db.IV_LocationCaches.InsertOnSubmit(destLocation);
                            }

                            #endregion

                            #region master location cache

                            var destMasLocation = db.IV_MasLocCaches.FirstOrDefault(e => e.MasterLocationID == issueMaster.MasterLocationID && e.ProductID == issueDetail.ProductID);
                            if (!allowNegative && (destMasLocation == null || destMasLocation.OHQuantity.GetValueOrDefault(0) < issueDetail.CommitQuantity))
                            {
                                var productError = new Hashtable
                                                       {
                                                           { ITM_ProductTable.PRODUCTID_FLD, issueDetail.ProductID },
                                                           { IV_BinCacheTable.OHQUANTITY_FLD, destMasLocation == null ? 0 : destMasLocation.OHQuantity.GetValueOrDefault(0) }
                                                       };
                                throw new PCSBOException(ErrorCode.MESSAGE_NOT_ENOUGH_COMPONENT_TO_COMPLETE, issueDetail.ITM_Product.Code, new Exception(), productError);
                            }
                            if (destMasLocation != null)
                            {
                                destMasLocation.OHQuantity = destMasLocation.OHQuantity.GetValueOrDefault(0) - issueDetail.CommitQuantity;
                            }
                            else
                            {
                                // create new record
                                destMasLocation = new IV_MasLocCache
                                {
                                    CCNID = issueMaster.CCNID,
                                    MasterLocationID = issueMaster.MasterLocationID,
                                    ProductID = issueDetail.ProductID,
                                    OHQuantity = -issueDetail.CommitQuantity
                                };
                                db.IV_MasLocCaches.InsertOnSubmit(destMasLocation);
                            }

                            #endregion

                            #region Transaction history

                            var destHistory = new MST_TransactionHistory
                            {
                                CCNID = issueMaster.CCNID,
                                StockUMID = issueDetail.StockUMID,
                                MasterLocationID = issueMaster.MasterLocationID,
                                ProductID = issueDetail.ProductID,
                                LocationID = issueMaster.ToLocationID,
                                BinID = issueMaster.ToBinID,
                                RefMasterID = issueMaster.IssueMaterialMasterID,
                                RefDetailID = issueDetail.IssueMaterialDetailID,
                                PostDate = issueMaster.PostDate,
                                TransDate = serverDate,
                                Quantity = -issueDetail.CommitQuantity,
                                UserName = SystemProperty.UserName,
                                TranTypeID = tranTypeId,
                                BinCommitQuantity = destBin.CommitQuantity,
                                BinOHQuantity = destBin.OHQuantity,
                                IssuePurposeID = issueMaster.IssuePurposeID,
                                LocationCommitQuantity = destLocation.CommitQuantity,
                                LocationOHQuantity = destLocation.OHQuantity,
                                MasLocCommitQuantity = destMasLocation.CommitQuantity,
                                MasLocOHQuantity = destMasLocation.OHQuantity
                            };
                            db.MST_TransactionHistories.InsertOnSubmit(destHistory);

                            #endregion

                            #endregion

                            #region add to source cache

                            #region bin cache

                            var sourceBin = db.IV_BinCaches.FirstOrDefault(e => e.LocationID == issueDetail.LocationID && e.BinID == issueDetail.BinID && e.ProductID == issueDetail.ProductID);
                            if (sourceBin != null)
                            {
                                sourceBin.OHQuantity = sourceBin.OHQuantity.GetValueOrDefault(0) + issueDetail.CommitQuantity;
                            }
                            else
                            {
                                // create new record
                                sourceBin = new IV_BinCache
                                {
                                    BinID = issueDetail.BinID.GetValueOrDefault(0),
                                    CCNID = issueMaster.CCNID,
                                    LocationID = issueDetail.LocationID,
                                    MasterLocationID = issueMaster.MasterLocationID,
                                    ProductID = issueDetail.ProductID,
                                    OHQuantity = issueDetail.CommitQuantity
                                };
                                db.IV_BinCaches.InsertOnSubmit(sourceBin);
                            }

                            #endregion

                            #region location cache

                            var sourceLocation = db.IV_LocationCaches.FirstOrDefault(e => e.MasterLocationID == issueMaster.MasterLocationID && e.LocationID == issueDetail.LocationID && e.ProductID == issueDetail.ProductID);
                            if (sourceLocation != null)
                            {
                                sourceLocation.OHQuantity = sourceLocation.OHQuantity.GetValueOrDefault(0) + issueDetail.CommitQuantity;
                            }
                            else
                            {
                                // create new record
                                sourceLocation = new IV_LocationCache
                                {
                                    CCNID = issueMaster.CCNID,
                                    LocationID = issueDetail.LocationID,
                                    MasterLocationID = issueMaster.MasterLocationID,
                                    ProductID = issueDetail.ProductID,
                                    OHQuantity = issueDetail.CommitQuantity
                                };
                                db.IV_LocationCaches.InsertOnSubmit(sourceLocation);
                            }

                            #endregion

                            #region master location cache

                            var sourceMasLocation = db.IV_MasLocCaches.FirstOrDefault(e => e.MasterLocationID == issueMaster.MasterLocationID && e.ProductID == issueDetail.ProductID);
                            if (sourceMasLocation != null)
                            {
                                sourceMasLocation.OHQuantity = sourceMasLocation.OHQuantity.GetValueOrDefault(0) + issueDetail.CommitQuantity;
                            }
                            else
                            {
                                // create new record
                                sourceMasLocation = new IV_MasLocCache
                                {
                                    CCNID = issueMaster.CCNID,
                                    MasterLocationID = issueMaster.MasterLocationID,
                                    ProductID = issueDetail.ProductID,
                                    OHQuantity = issueDetail.CommitQuantity
                                };
                                db.IV_MasLocCaches.InsertOnSubmit(sourceMasLocation);
                            }

                            #endregion

                            #region Transaction history

                            var sourceHistory = new MST_TransactionHistory
                            {
                                CCNID = issueMaster.CCNID,
                                StockUMID = issueDetail.StockUMID,
                                MasterLocationID = issueMaster.MasterLocationID,
                                ProductID = issueDetail.ProductID,
                                LocationID = issueDetail.LocationID,
                                BinID = issueDetail.BinID,
                                RefMasterID = issueMaster.IssueMaterialMasterID,
                                RefDetailID = issueDetail.IssueMaterialDetailID,
                                PostDate = issueMaster.PostDate,
                                TransDate = serverDate,
                                Quantity = issueDetail.CommitQuantity,
                                UserName = SystemProperty.UserName,
                                TranTypeID = tranTypeId,
                                BinCommitQuantity = sourceBin.CommitQuantity,
                                BinOHQuantity = sourceBin.OHQuantity,
                                IssuePurposeID = issueMaster.IssuePurposeID,
                                LocationCommitQuantity = sourceLocation.CommitQuantity,
                                LocationOHQuantity = sourceLocation.OHQuantity,
                                MasLocCommitQuantity = sourceMasLocation.CommitQuantity,
                                MasLocOHQuantity = sourceMasLocation.OHQuantity
                            };
                            db.MST_TransactionHistories.InsertOnSubmit(sourceHistory);

                            #endregion

                            #endregion

                            db.PRO_IssueMaterialDetails.DeleteOnSubmit(issueDetail);
                        }
                        #endregion

                        db.PRO_IssueMaterialMasters.DeleteOnSubmit(issueMaster);
                        db.SubmitChanges();
                        trans.Complete();
                    }
                }
            }
            catch (PCSBOException ex)
            {
                if (ex.mCode == ErrorCode.SQLDUPLICATE_KEYCODE)
                    throw new PCSDBException(ErrorCode.DUPLICATE_KEY, methodName, ex);
                if (ex.mCode == ErrorCode.MESSAGE_NOT_ENOUGH_COMPONENT_TO_COMPLETE)
                    throw;
                throw new PCSDBException(ErrorCode.ERROR_DB, methodName, ex);
            }
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="pintIssueMasterId"></param>
		/// <returns></returns>
		public DataTable GetMasterIssue(int pintIssueMasterId)
		{
			return (new PRO_IssueMaterialMasterDS()).GetMasterIssue(pintIssueMasterId);
		}
	}
}