text:
"""Test the zerproc lights."""
from unittest.mock import MagicMock, patch

import pytest
import pyzerproc

from homeassistant import setup
from homeassistant.components.light import (
    ATTR_BRIGHTNESS,
    ATTR_HS_COLOR,
    ATTR_RGB_COLOR,
    ATTR_XY_COLOR,
    SCAN_INTERVAL,
    SUPPORT_BRIGHTNESS,
    SUPPORT_COLOR,
)
from homeassistant.components.zerproc.light import DOMAIN
from homeassistant.const import (
    ATTR_ENTITY_ID,
    ATTR_FRIENDLY_NAME,
    ATTR_ICON,
    ATTR_SUPPORTED_FEATURES,
    STATE_OFF,
    STATE_ON,
    STATE_UNAVAILABLE,
)
import homeassistant.util.dt as dt_util

from tests.common import MockConfigEntry, async_fire_time_changed

@pytest.fixture
async def mock_entry(hass):
    """Create a mock light entity."""
    return MockConfigEntry(domain=DOMAIN)

@pytest.fixture
async def mock_light(hass, mock_entry):
    """Create a mock light entity."""
    await setup.async_setup_component(hass, "persistent_notification", {})

    mock_entry.add_to_hass(hass)

    light = MagicMock(spec=pyzerproc.Light)
    light.address = "AA:BB:CC:DD:EE:FF"
    light.name = "LEDBlue-CCDDEEFF"
    light.is_connected.return_value = False

    mock_state = pyzerproc.LightState(False, (0, 0, 0))

    with patch(
        "homeassistant.components.zerproc.light.pyzerproc.discover",
        return_value=[light],
    ), patch.object(light, "connect"), patch.object(
        light, "get_state", return_value=mock_state
    ):
        await hass.config_entries.async_setup(mock_entry.entry_id)
        await hass.async_block_till_done()

    light.is_connected.return_value = True

    return light

async def test_init(hass, mock_entry):
    """Test platform setup."""
    await setup.async_setup_component(hass, "persistent_notification", {})

    mock_entry.add_to_hass(hass)

    mock_light_1 = MagicMock(spec=pyzerproc.Light)
    mock_light_1.address = "AA:BB:CC:DD:EE:FF"
    mock_light_1.name = "LEDBlue-CCDDEEFF"
    mock_light_1.is_connected.return_value = True

    mock_light_2 = MagicMock(spec=pyzerproc.Light)
    mock_light_2.address = "11:22:33:44:55:66"
    mock_light_2.name = "LEDBlue-33445566"
    mock_light_2.is_connected.return_value = True

    mock_state_1 = pyzerproc.LightState(False, (0, 0, 0))
    mock_state_2 = pyzerproc.LightState(True, (0, 80, 255))

    mock_light_1.get_state.return_value = mock_state_1
    mock_light_2.get_state.return_value = mock_state_2

    with patch(
        "homeassistant.components.zerproc.light.pyzerproc.discover",
        return_value=[mock_light_1, mock_light_2],
    ):
        await hass.config_entries.async_setup(mock_entry.entry_id)
        await hass.async_block_till_done()

    state = hass.states.get("light.ledblue_ccddeeff")
    assert state.state == STATE_OFF
    assert state.attributes == {
        ATTR_FRIENDLY_NAME: "LEDBlue-CCDDEEFF",
        ATTR_SUPPORTED_FEATURES: SUPPORT_BRIGHTNESS | SUPPORT_COLOR,
        ATTR_ICON: "mdi:string-lights",
    }

    state = hass.states.get("light.ledblue_33445566")
    assert state.state == STATE_ON
    assert state.attributes == {
        ATTR_FRIENDLY_NAME: "LEDBlue-33445566",
        ATTR_SUPPORTED_FEATURES: SUPPORT_BRIGHTNESS | SUPPORT_COLOR,
        ATTR_ICON: "mdi:string-lights",
        ATTR_BRIGHTNESS: 255,
        ATTR_HS_COLOR: (221.176, 100.0),
        ATTR_RGB_COLOR: (0, 80, 255),
        ATTR_XY_COLOR: (0.138, 0.08),
    }

    with patch.object(hass.loop, "stop"):
        await hass.async_stop()

    assert mock_light_1.disconnect.called
    assert mock_light_2.disconnect.called

async def test_discovery_exception(hass, mock_entry):
    """Test platform setup."""
    await setup.async_setup_component(hass, "persistent_notification", {})

    mock_entry.add_to_hass(hass)

    with patch(
        "homeassistant.components.zerproc.light.pyzerproc.discover",
        side_effect=pyzerproc.ZerprocException("TEST"),
    ):
        await hass.config_entries.async_setup(mock_entry.entry_id)
        await hass.async_block_till_done()

    # The exception should be captured and no entities should be added
    assert len(hass.data[DOMAIN]["addresses"]) == 0

async def test_connect_exception(hass, mock_entry):
    """Test platform setup."""
    await setup.async_setup_component(hass, "persistent_notification", {})

    mock_entry.add_to_hass(hass)

    mock_light_1 = MagicMock(spec=pyzerproc.Light)
    mock_light_1.address = "AA:BB:CC:DD:EE:FF"
    mock_light_1.name = "LEDBlue-CCDDEEFF"
    mock_light_1.is_connected.return_value = False

    mock_light_2 = MagicMock(spec=pyzerproc.Light)
    mock_light_2.address = "11:22:33:44:55:66"
    mock_light_2.name = "LEDBlue-33445566"
    mock_light_2.is_connected.return_value = False

    with patch(
        "homeassistant.components.zerproc.light.pyzerproc.discover",
        return_value=[mock_light_1, mock_light_2],
    ), patch.object(
        mock_light_1, "connect", side_effect=pyzerproc.ZerprocException("TEST")
    ):
        await hass.config_entries.async_setup(mock_entry.entry_id)
        await hass.async_block_till_done()

    # The exception connecting to light 1 should be captured, but light 2
    # should still be added
    assert len(hass.data[DOMAIN]["addresses"]) == 1

async def test_remove_entry(hass, mock_light, mock_entry):
    """Test platform setup."""
    with patch.object(mock_light, "disconnect") as mock_disconnect:
        await hass.config_entries.async_remove(mock_entry.entry_id)

    assert mock_disconnect.called

async def test_remove_entry_exceptions_caught(hass, mock_light, mock_entry):
    """Assert that disconnect exceptions are caught."""
    with patch.object(
        mock_light, "disconnect", side_effect=pyzerproc.ZerprocException("Mock error")
    ) as mock_disconnect:
        await hass.config_entries.async_remove(mock_entry.entry_id)

    assert mock_disconnect.called

async def test_light_turn_on(hass, mock_light):
    """Test ZerprocLight turn_on."""
    utcnow = dt_util.utcnow()
    with patch.object(mock_light, "turn_on") as mock_turn_on:
        await hass.services.async_call(
            "light",
            "turn_on",
            {ATTR_ENTITY_ID: "light.ledblue_ccddeeff"},
            blocking=True,
        )
        await hass.async_block_till_done()
    mock_turn_on.assert_called()

    with patch.object(mock_light, "set_color") as mock_set_color:
        await hass.services.async_call(
            "light",
            "turn_on",
            {ATTR_ENTITY_ID: "light.ledblue_ccddeeff", ATTR_BRIGHTNESS: 25},
            blocking=True,
        )
        await hass.async_block_till_done()
    mock_set_color.assert_called_with(25, 25, 25)

    # Make sure no discovery calls are made while we emulate time passing
    with patch("homeassistant.components.zerproc.light.pyzerproc.discover"):
        with patch.object(
            mock_light,
            "get_state",
            return_value=pyzerproc.LightState(True, (175, 150, 220)),
        ):
            utcnow = utcnow + SCAN_INTERVAL
            async_fire_time_changed(hass, utcnow)
            await hass.async_block_till_done()

        with patch.object(mock_light, "set_color") as mock_set_color:
            await hass.services.async_call(
                "light",
                "turn_on",
                {ATTR_ENTITY_ID: "light.ledblue_ccddeeff", ATTR_BRIGHTNESS: 25},
                blocking=True,
            )
            await hass.async_block_till_done()

        mock_set_color.assert_called_with(19, 17, 25)

        with patch.object(mock_light, "set_color") as mock_set_color:
            await hass.services.async_call(
                "light",
                "turn_on",
                {ATTR_ENTITY_ID: "light.ledblue_ccddeeff", ATTR_HS_COLOR: (50, 50)},
                blocking=True,
            )
            await hass.async_block_till_done()

        mock_set_color.assert_called_with(220, 201, 110)

        with patch.object(
            mock_light,
            "get_state",
            return_value=pyzerproc.LightState(True, (75, 75, 75)),
        ):
            utcnow = utcnow + SCAN_INTERVAL
            async_fire_time_changed(hass, utcnow)
            await hass.async_block_till_done()

        with patch.object(mock_light, "set_color") as mock_set_color:
            await hass.services.async_call(
                "light",
                "turn_on",
                {ATTR_ENTITY_ID: "light.ledblue_ccddeeff", ATTR_HS_COLOR: (50, 50)},
                blocking=True,
            )
            await hass.async_block_till_done()

        mock_set_color.assert_called_with(75, 68, 37)

        with patch.object(mock_light, "set_color") as mock_set_color:
            await hass.services.async_call(
                "light",
                "turn_on",
                {
                    ATTR_ENTITY_ID: "light.ledblue_ccddeeff",
                    ATTR_BRIGHTNESS: 200,
                    ATTR_HS_COLOR: (75, 75),
                },
                blocking=True,
            )
            await hass.async_block_till_done()

        mock_set_color.assert_called_with(162, 200, 50)

async def test_light_turn_off(hass, mock_light):
    """Test ZerprocLight turn_on."""
    with patch.object(mock_light, "turn_off") as mock_turn_off:
        await hass.services.async_call(
            "light",
            "turn_off",
            {ATTR_ENTITY_ID: "light.ledblue_ccddeeff"},
            blocking=True,
        )
        await hass.async_block_till_done()
    mock_turn_off.assert_called()

async def test_light_update(hass, mock_light):
    """Test ZerprocLight update."""
    utcnow = dt_util.utcnow()

    state = hass.states.get("light.ledblue_ccddeeff")
    assert state.state == STATE_OFF
    assert state.attributes == {
        ATTR_FRIENDLY_NAME: "LEDBlue-CCDDEEFF",
        ATTR_SUPPORTED_FEATURES: SUPPORT_BRIGHTNESS | SUPPORT_COLOR,
        ATTR_ICON: "mdi:string-lights",
    }

    # Make sure no discovery calls are made while we emulate time passing
    with patch("homeassistant.components.zerproc.light.pyzerproc.discover"):
        # Test an exception during discovery
        with patch.object(
            mock_light, "get_state", side_effect=pyzerproc.ZerprocException("TEST")
        ):
            utcnow = utcnow + SCAN_INTERVAL
            async_fire_time_changed(hass, utcnow)
            await hass.async_block_till_done()

        state = hass.states.get("light.ledblue_ccddeeff")
        assert state.state == STATE_UNAVAILABLE
        assert state.attributes == {
            ATTR_FRIENDLY_NAME: "LEDBlue-CCDDEEFF",
            ATTR_SUPPORTED_FEATURES: SUPPORT_BRIGHTNESS | SUPPORT_COLOR,
            ATTR_ICON: "mdi:string-lights",
        }

        with patch.object(
            mock_light,
            "get_state",
            return_value=pyzerproc.LightState(False, (200, 128, 100)),
        ):
            utcnow = utcnow + SCAN_INTERVAL
            async_fire_time_changed(hass, utcnow)
            await hass.async_block_till_done()

        state = hass.states.get("light.ledblue_ccddeeff")
        assert state.state == STATE_OFF
        assert state.attributes == {
            ATTR_FRIENDLY_NAME: "LEDBlue-CCDDEEFF",
            ATTR_SUPPORTED_FEATURES: SUPPORT_BRIGHTNESS | SUPPORT_COLOR,
            ATTR_ICON: "mdi:string-lights",
        }

        with patch.object(
            mock_light,
            "get_state",
            return_value=pyzerproc.LightState(True, (175, 150, 220)),
        ):
            utcnow = utcnow + SCAN_INTERVAL
            async_fire_time_changed(hass, utcnow)
            await hass.async_block_till_done()

        state = hass.states.get("light.ledblue_ccddeeff")
        assert state.state == STATE_ON
        assert state.attributes == {
            ATTR_FRIENDLY_NAME: "LEDBlue-CCDDEEFF",
            ATTR_SUPPORTED_FEATURES: SUPPORT_BRIGHTNESS | SUPPORT_COLOR,
            ATTR_ICON: "mdi:string-lights",
            ATTR_BRIGHTNESS: 220,
            ATTR_HS_COLOR: (261.429, 31.818),
            ATTR_RGB_COLOR: (202, 173, 255),
            ATTR_XY_COLOR: (0.291, 0.232),
        }


text:
package nl.cwi.reo.pr.comp;

import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Collections;
import java.util.List;

public abstract class CompiledProgram {
	protected final List<CompiledGeneratee> generatees;
	private final String sourceRunTimeDirectoryLocation;

	//
	// CONSTRUCTORS
	//

	public CompiledProgram(String sourceRunTimeDirectoryLocation,
			List<CompiledGeneratee> generatees) {

		if (sourceRunTimeDirectoryLocation == null)
			throw new NullPointerException();
		if (generatees == null)
			throw new NullPointerException();
		if (generatees.contains(null))
			throw new NullPointerException();

		this.generatees = Collections.unmodifiableList(generatees);
		this.sourceRunTimeDirectoryLocation = sourceRunTimeDirectoryLocation;
	}

	//
	// METHODS - PUBLIC
	//

	public abstract String getMain();

	public void writeGeneratees(String targetGenerateesDirectoryLocation)
			throws IOException {

		if (targetGenerateesDirectoryLocation == null)
			throw new NullPointerException();

		for (CompiledGeneratee g : generatees)
			g.writeFiles(targetGenerateesDirectoryLocation);
	}

	public void writeRunTime(String targetRunTimeDirectoryLocation)
			throws IOException {

		if (targetRunTimeDirectoryLocation == null)
			throw new NullPointerException();

		final Path sourceDirectoryPath = Paths
				.get(sourceRunTimeDirectoryLocation);
		final Path targetDirectoryPath = Paths
				.get(targetRunTimeDirectoryLocation);

		Files.walkFileTree(sourceDirectoryPath, new SimpleFileVisitor<Path>() {
			@Override
			public FileVisitResult preVisitDirectory(Path dir,
					BasicFileAttributes attrs) throws IOException {

				if (dir == null)
					throw new NullPointerException();
				if (attrs == null)
					throw new NullPointerException();

				Path directoryPath = targetDirectoryPath
						.resolve(sourceDirectoryPath.relativize(dir));
				try {
					Files.copy(dir, directoryPath);
				} catch (FileAlreadyExistsException exception) {
					if (!Files.isDirectory(directoryPath))
						throw exception;
				}

				return FileVisitResult.CONTINUE;
			}

			@Override
			public FileVisitResult visitFile(Path file,
					BasicFileAttributes attrs) throws IOException {

				if (file == null)
					throw new NullPointerException();
				if (attrs == null)
					throw new NullPointerException();

				Files.copy(file, targetDirectoryPath
						.resolve(sourceDirectoryPath.relativize(file)),
						StandardCopyOption.REPLACE_EXISTING);

				return FileVisitResult.CONTINUE;
			}
		});
	}
}

redpajama_set_name: RedPajamaGithub


text:
<litepal>
    <dbname value="cool_weather" />
    <version value = "1" />
    <list>
        <mapping class = "stan.androiddemo.project.weather.db.Province" />
        <mapping class = "stan.androiddemo.project.weather.db.City" />
        <mapping class = "stan.androiddemo.project.weather.db.Country" />
        <mapping class = "stan.androiddemo.project.novel.model.SectionInfo" />
        <mapping class = "stan.androiddemo.project.novel.model.NovelInfo" />
        <mapping class = "stan.androiddemo.project.FiveStroke.Model.FiveStrokeInfo" />
        <mapping class = "stan.androiddemo.project.Mito.Model.ImageSetInfo" />
        <mapping class = "stan.androiddemo.project.Mito.Model.Resolution" />
    </list>
</litepal>


text:
$(document).ready(function() {

    var totalprice=0;
    var selectedseats=[];

    var sc = $('#seat-map').seatCharts({
        map: [
        'aaa__DDDD__AAA',
        'aaa__DDDD__AAA',
        'aaa__DDDD__AAA',
        'aaa__DDDD__AAA',
        'aaa__DDDD__AAA',
        'aaa__DDDD__AAA',
        ],
        seats: {
            a: {
                price   : 500,
                'descr' : 'Economic seat',
                classes : 'front-seat' //your custom CSS class
            },
            A: {
                price   : 500,
                'descr' : 'Ordinary seat.',
                classes : 'front-seat' //your custom CSS class
            },
            D: {
                price   : 800,
                classes : 'front',
                'descr' : 'Premium seat.'
            }

        },
        click: function () {
            if (this.status() == 'available') {

                totalprice+=this.settings.data['price']

                selectedseats.push(this.settings.data);

                console.log(totalprice,selectedseats);

                return 'selected';
            } else if (this.status() == 'selected') {

                totalprice-=this.settings.data['price'];

                var index = selectedseats.indexOf(this.settings.data);
                selectedseats.splice(index, 1);
                console.log(totalprice, selectedseats);
                return 'available';
            } else if (this.status() == 'unavailable') {
                //seat has been already booked
                return 'unavailable';
            } else {
                return this.style();
            }
        }
    });

    //Make all available 'c' seats unavailable
    sc.find('a.available').status('unavailable');

    sc.get(['1_3']).status('unavailable');

});


text:
<?php

namespace Tecnokey\ShopBundle\Controller\Frontend\User;

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 Tecnokey\ShopBundle\Form\Shop\ShoppingCartType;
use Symfony\Component\HttpFoundation\Request;
use Tecnokey\ShopBundle\Entity\Shop\ShoppingCart;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;

/**
 * Frontend\Default controller.
 *
 * @Route("/tienda/usuario/carrito")
 */
class ShoppingCartController extends Controller {
    const FORM_ORDER_FIELD = "cart_order";
    const FORM_ORDER_UPDATE_VALUE= "cart_update";
    const FORM_ORDER_COMFIRM_VALUE = "cart_comfirm";

    /**
     * Frontend demo
     *
     * @Route("/", name="TKShopFrontendUserShoppingCartIndex")
     * @Template()
     */
    public function indexAction() {
        /* $shoppingCart = $this->getUserShoppingCart();

          return array(
          'shoppingCart' => $shoppingCart
          ); */

        return $this->redirect($this->generateUrl('TKShopFrontendUserShoppingCartEdit'));
        //return $this->forward('TecnokeyShopBundle:Frontend\User\ShoppingCart:edit');
    }

    /**
     * Finds and displays a Shop\ShoppingCart entity.
     *
     * @Route("/ver.{_format}", defaults={"_format"="html"}, name="TKShopFrontendUserShoppingCartShow")
     * @Template()
     */
    public function showAction() {
        $entity = $this->getUserShoppingCart();

        if (!$entity) {
            //throw $this->createNotFoundException('Custom Error: Unable to find Shop\ShoppingCart entity.');
        }
        else{
            $checkoutManager = $this->get('checkoutManager');
            $entity = $checkoutManager->checkout($entity);

            $deleteForm = $this->createDeleteForm($entity->getId());
        }
        return array(
            'entity' => $entity,
        );
    }

    /**
     * Displays a form to create a new Shop\ShoppingCart entity.
     *
     * @Route("/new", name="TKShopFrontendUserShoppingCartNew")
     * @Template()
     */
    public function newAction() {
        $entity = new ShoppingCart();
        $form = $this->createForm(new ShoppingCartType(), $entity);

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

    /**
     * Creates a new Shop\ShoppingCart entity.
     *
     * @Route("/create", name="TKShopFrontendUserShoppingCartCreate")
     * @Method("post")
     * @Template("TecnokeyShopBundle:Frontend\ShoppingCart:new.html.twig")
     */
    public function createAction() {
        $entity = new ShoppingCart();
        $request = $this->getRequest();
        $form = $this->createForm(new ShoppingCartType(), $entity);
        $form->bindRequest($request);

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

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

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

    /**
     * Displays a form to edit an existing Shop\ShoppingCart entity.
     *
     * @Route("/editar", name="TKShopFrontendUserShoppingCartEdit")
     */
    public function editAction() {
        $entity = $this->getUserShoppingCart();
        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Shop\ShoppingCart entity.');
            /* $this->get('session')->setFlash('shoppingCart_error',"Atencion: El usuario no dispone de carrito de la compra");
              return $this->redirect($this->generateUrl("TKShopFrontendIndex")); */
        }

        // Fill Shopping Cart with the current last Market/Offer Info
        $checkoutManager = $this->get('checkoutManager');
        $entity = $checkoutManager->checkout($entity);
        // End filling Shopping Cart

        $editForm = $this->createForm(new ShoppingCartType(), $entity);
        $deleteForm = $this->createDeleteForm($entity->getId());

        return $this->render("TecnokeyShopBundle:Frontend\User\ShoppingCart:edit.html.twig", array(
                    'entity' => $entity,
                    'edit_form' => $editForm->createView(),
                    'delete_form' => $deleteForm->createView(),
                    'order_field' => self::FORM_ORDER_FIELD,
                    'update_value' => self::FORM_ORDER_UPDATE_VALUE,
                    'comfirm_value' => self::FORM_ORDER_COMFIRM_VALUE,
                ));
    }

    /**
     * Displays a form to edit an existing Shop\ShoppingCart entity.
     *
     * @Route("/item/{id}/eliminar", name="TKShopFrontendUserShoppingCartDeleteItem")
     */
    public function deleteItemAction($id) {
        $shoppingCart = $this->getUserShoppingCart();
        if ($shoppingCart != NULL) {

            $this->get('shoppingCartManager')->removeItem($shoppingCart, $id);
            $em = $this->getDoctrine()->getEntityManager();
            /* $em->persist($shoppingCart);
              $em->flush(); */
            $this->persistAndFlushShoppingCart($shoppingCart);

            return $this->redirect($this->generateUrl('TKShopFrontendUserShoppingCartEdit'));
            /* return $this->forward("TecnokeyShopBundle:Frontend\User\ShoppingCart:edit", array(
              'id' => $shoppingCart->getId()
              )); */
        } else {
            $this->get('session')->setFlash('shoppingCart_error', "Atencion: El usuario no dispone de carrito de la compra");
            return $this->redirect($this->generateUrl("TKShopFrontendIndex"));
        }
    }

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

        $form->bindRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getEntityManager();
            $entity = $this->getUserShoppingCart();
            //$entity = $em->getRepository('TecnokeyShopBundle:Shop\ShoppingCart')->find($id);

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

            /* $em->remove($entity);
              $em->flush(); */
            $this->removeShoppingCart($entity);
        }

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

    /**
     * Edits an existing Shop\ShoppingCart entity.
     *
     * @Route("/update", name="TKShopFrontendUserShoppingCartUpdate")
     * @Method("post")
     * @Template("TecnokeyShopBundle:Frontend\User\ShoppingCart:edit.html.twig")
     */
    public function updateAction() {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $this->getUserShoppingCart();

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

        $editForm = $this->createForm(new ShoppingCartType(), $entity);
        $deleteForm = $this->createDeleteForm($entity->getId());

        $request = $this->getRequest();

        $editForm->bindRequest($request);

        if ($editForm->isValid()) {
            // Check if the quantity of an Entity is zero, then remove the entity
            $entity = $this->get('shoppingCartManager')->removeItemsWithoutProducts($entity);
            // End Check if the quantity of an Entity is zero
            $em->persist($entity);
            $em->flush();

            $request = Request::createFromGlobals();
            $orderField = $request->request->get(self::FORM_ORDER_FIELD);
            if ($orderField == self::FORM_ORDER_COMFIRM_VALUE) {
                if($this->isCartValid($entity)){
                    return $this->render("TecnokeyShopBundle:Frontend\User\ShoppingCart:preview.html.twig", array(
                        'order' => $this->generateOrder($entity),
                        )
                    );
                }
               else{

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

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

    /**
     * @Route("/agregar_producto/{id}/", name="TKShopFrontendUserShoppingAddProduct")
     */
    public function addProductAction($id) {
        $shoppingCart = $this->getUserShoppingCart();
        if ($shoppingCart == NULL) {
            return $this->shoppingCartErrorHandler();
        }

        //Get Product from DB
        $em = $this->getDoctrine()->getEntityManager();
        $product = $em->getRepository("TecnokeyShopBundle:Shop\Product")->find($id);
        if ($product == NULL) {
            throw new Exception("Custom Exception: Product with id $id does NOT exist in database");
        }
        $this->get('shoppingCartManager')->addProductToCart($shoppingCart, $product);
        $em->persist($shoppingCart);
        $em->flush();

        //return $this->redirect($this->generateUrl("TKShopFrontendUserShoppingCartIndex"));
        $session = $this->get('session');
        $last_route = $session->get('last_route', array('name' => 'TKShopFrontendIndex'));
        return ($this->redirect($this->generateUrl($last_route['name'], $last_route['params'])));

    }

    /**
     * @Route("/limpiar_carrito/", name="TKShopFrontendUserShoppingCartRemoveAllItems")
     */
    public function removeAllProductsAction() {
        $shoppingCart = $this->getUserShoppingCart();

        if ($shoppingCart == NULL) {
            return $this->shoppingCartErrorHandler();
        }

        $this->get('shoppingCartManager')->removerAllItems($shoppingCart);

        $em = $this->getDoctrine()->getEntityManager();
        $em->persist($shoppingCart);
        $em->flush();

        return $this->redirect($this->generateUrl("TKShopFrontendUserShoppingCartIndex"));
    }

    //  HELPER FUNCTIONS  //

    /**
     * Redirects to home page if there is a problem with ShoppingCart
     *
     * @param type $msg
     * @param type $redirect
     * @return type
     */
    protected function shoppingCartErrorHandler($msg = NULL, $redirect=NULL) {
        //TODO: Redirect to index
        $this->get('session')->setFlash('shoppingCart_error', "Atencion: El usuario no dispone de carrito, cree un usuario de tipo cliente");
        return $this->redirect($this->generateUrl("TKShopFrontendIndex"));
    }

    /**
     * Get the ShoppingCart from the logged user
     * If the user does NOT have a shoppingCart then one is created and attached to user but not persisted to database
     *
     * @return ShoppingCart
     */
    protected function getUserShoppingCart() {
        $user = $this->get('userManager')->getCurrentUser();

        $shoppingCart = NULL;
        if ($this->get('userManager')->isDBUser($user)) {
            $shoppingCart = $user->getShoppingCart();
            if ($shoppingCart == NULL) {
                $shoppingCart = new ShoppingCart();
                $user->setShoppingCart($shoppingCart);
            }
        }

        return $shoppingCart;
    }

    public function isCartValid($sc){
        $items = $sc->getItems();
        if (count($items) < 1) {
            return false;
        }
        return true;
    }

    public function generateOrder(ShoppingCart $entity){
        $checkoutManager = $this->get('checkoutManager');
            $entity = $checkoutManager->checkout($entity);
            // generate an order
            $order = $checkoutManager->shoppingCartToOrder($entity);
            return $order;
    }

    /**
     *
     * @param ShoppingCart $shoppingCart
     */
    protected function persistAndFlushShoppingCart(ShoppingCart $shoppingCart) {
        $user = $this->get('userManager')->getCurrentUser();
        if ($this->get('userManager')->isDBUser($user)) {
            $em = $this->getDoctrine()->getEntityManager();
            $em->persist($shoppingCart);
            $em->flush();
        } else {
            $session = $this->get('session');
            //$session->set('shoppingCart', serialize($shoppingCart));
            //$serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new JsonEncoder()));
            //$json = $serializer->serialize($shoppingCart, 'json');
            //$session->set('shoppingCart', $json);
            //$session->save();
        }
    }

    /**
     *
     * @param ShoppingCart $shoppingCart
     */
    protected function removeShoppingCart(ShoppingCart $shoppingCart) {
        if ($this->get('userManager')->isDBUser($user)) {
            $em = $this->getDoctrine()->getEntityManager();
            $em->remove($shoppingCart);
            $em->flush();
        } else {
            $session = $this->get('session');
            $session->set('shoppingCart', null);
            $session->save();
        }
    }

}


text:
<?php

/* @App/Main/loginForm.html.twig */
class __TwigTemplate_bec270c0636efbd12e3c8b6cdc0b89992814f1c22c5d819cf963bf695c05e4c2 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 1
        echo "

    ";
        // line 3
        echo $this->env->getExtension('actions')->renderUri($this->env->getExtension('http_kernel')->controller("FOSUserBundle:Security:login"), array());
        // line 4
        echo "

";
    }

    public function getTemplateName()
    {
        return "@App/Main/loginForm.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  25 => 4,  23 => 3,  19 => 1,);
    }
}


text:
"use strict";

import chai from "chai";
import chaiAsPromised from "chai-as-promised";
import sinon from "sinon";
import BusinessElementsClient from "../src";

chai.use(chaiAsPromised);
chai.should();
chai.config.includeStack = true;

const FAKE_SERVER_URL = "http://api.fake-server";

/** @test {Application} */
describe("Application", () => {
  let sandbox, client, application, applicationHandle;

  beforeEach(() => {
    sandbox = sinon.sandbox.create();
    client = new BusinessElementsClient(FAKE_SERVER_URL);
    applicationHandle = "applicationHandle";
    application = client.tenant("example.com").applications().application(applicationHandle);
  });

  afterEach(() => {
    sandbox.restore();
  });

  /** @test {Application#listPublicationPurposes} */
  describe("#listPublicationPurposes()", () => {
    const response = {
      "content": {}
    };

    beforeEach(() => {
      sandbox.stub(client, "execute").returns(Promise.resolve(response));
    });

    it("should call get content-items from exhibition", () => {
      application.listPublicationPurposes({});

      sinon.assert.calledWithMatch(client.execute, {
        path: `/applications/${applicationHandle}/publication/purposes`
      });
    });
  });
});


text:
"use strict";
/* globals AccountsPatchUi: true, LoginState */

// Remember the official Meteor versions of the functions we will be
// monkey patching.
var meteorUserIdFunc = Meteor.userId;
var meteorUserFunc = Meteor.user;
var accountsCallLoginMethod = Accounts.callLoginMethod;

var addServicePkg = Package['brettle:accounts-add-service'];
var mergeUserErrorReason = addServicePkg && addServicePkg.AccountsAddService &&
  addServicePkg.AccountsAddService._mergeUserErrorReason;

/** Returns a function that will execute `func` with
 * `Meteor.userId` set to `userIdFunc` and `Meteor.user` set to `userFunc`.
 * @param {Function} userIdFunc - the function to use for `Meteor.userId`.
 * @param {Function} userFunc - the function to use for `Meteor.user`.
 * @param {Function} func - the function to wrap.
 * @returns {Function} - the wrapped function
 */
var wrapWithUserFuncs = function (userIdFunc, userFunc, func) {
  return function ( /*arguments*/ ) {
    var savedUserIdFunc = Meteor.userId;
    var savedUserFunc = Meteor.user;
    Meteor.userId = userIdFunc;
    Meteor.user = userFunc;
    try {
      return func.apply(this, arguments);
    } finally {
      Meteor.userId = savedUserIdFunc;
      Meteor.user = savedUserFunc;
    }
  };
};

// A version of Meteor.userId() that returns null for users who have not signed
// up. NOTE: We use the original Meteor.user and Meteor.userId while in this
// function to avoid infinite recursion.
var signedUpUserIdFunc = wrapWithUserFuncs(meteorUserIdFunc, meteorUserFunc,
  function () {
    var meteorUserId = Meteor.userId();
    if (!meteorUserId) {
      return null;
    }
    var user = Meteor.users.findOne(meteorUserId);
    if (!user) {
      // Meteor.userId() was not null, but the userId wasn't found locally. That
      // only happens before startup has finished and the Meteor.users
      // subscription is not yet ready. So, just act like regular
      // Meteor.userId() in this case (i.e. assume the user is signed up).
      return meteorUserId;
    }
    if (LoginState.signedUp()) {
      return meteorUserId;
    }
    return null;
  });

// A version of Meteor.user() that returns null for user who have not signed up.
// NOTE: We use the original Meteor.user and Meteor.userId while in this
// function to avoid infinite recursion.
var signedUpUserFunc = wrapWithUserFuncs(meteorUserIdFunc, meteorUserFunc,
  function () {
    if (LoginState.signedUp()) {
      return meteorUserFunc.call(Meteor);
    }
    return null;
  });

var callLoginMethod = function(options) {
  var origCallback = options && options.userCallback;
  if (! origCallback) {
    return accountsCallLoginMethod.apply(this, arguments);
  }
  options = _.clone(options);
  options.userCallback = function (error) {
    if (error && error.error === Accounts.LoginCancelledError.numericError &&
        error.reason === mergeUserErrorReason) {
      return origCallback.call(this);
    } else {
      return origCallback.apply(this, arguments);
    }
  }
  return accountsCallLoginMethod.call(this, options);
}

function AccountsPatchUiConstructor() {}

_.extend(AccountsPatchUiConstructor.prototype, {
  /** Returns a function that will execute the passed function with a version
   * `Meteor.userId()` and `Meteor.user()` that return null for users who have
   * not signed up.
   * @param {Function} func - the function to wrap.
   * @returns {Function} - the wrapped function
   */
  wrapWithSignedUp: function (func) {
    return wrapWithUserFuncs(signedUpUserIdFunc, signedUpUserFunc, func);
  },

  /** Returns a function that will execute the passed function with a version
   * `Accounts.callLoginMethod()` (which is used by `Meteor.loginWithPassword()`
   * and `Meteor.createUser()`) that calls the user's callback with no arguments
   * (indicating success) if the login method returns the error that
   * `brettle:accounts-add-service` uses to indicate that the service was
   * merged into the current user's account.
   * @param {Function} func - the function to wrap.
   * @returns {Function} - the wrapped function
   */
  wrapWithMergedErrorSuppressed: function (func) {
    return function ( /*arguments*/ ) {
      var savedCallLoginMethod = Accounts.callLoginMethod;
      Accounts.callLoginMethod = callLoginMethod;
      try {
        return func.apply(this, arguments);
      } finally {
        Accounts.callLoginMethod = savedCallLoginMethod;
      }
    };
  },

  /** Returns a function has been wrapped with both
   * `wrapWithMergedErrorSuppressed()` and `wrapWithSignedUp()`.
   * @param {Function} func - the function to wrap.
   * @returns {Function} - the wrapped function
   */
  wrap: function (func) {
    return this.wrapWithMergedErrorSuppressed(
      this.wrapWithSignedUp(func));
  },

  _signedUpUser: signedUpUserFunc,

  _wrapTemplate: function (template) {
    var self = this;
    if (!template) {
      return;
    }
    self._wrapMethods(template.__helpers);
    if (!_.isArray(template.__eventMaps)) {
      throw new TypeError('__eventMaps not an Array');
    }
    _.each(template.__eventMaps, function (value, index, eventMaps) {
      self._wrapMethods(eventMaps[index]);
    });
  },

  _wrapMethods: function (obj) {
    if (obj === undefined) {
      return;
    }
    if (!_.isObject(obj)) {
      throw new TypeError('Not an object');
    }
    _.each(obj, function (value, key) {
      if (_.isFunction(value)) {
        obj[key] = AccountsPatchUi.wrap(value);
      }
    });
  }
});

AccountsPatchUi = new AccountsPatchUiConstructor();


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
   ~
   -->

<orient-server>
    <handlers>
        <handler class="com.orientechnologies.orient.graph.handler.OGraphServerHandler">
            <parameters>
                <parameter name="enabled" value="true"/>
                <parameter name="graph.pool.max" value="50"/>
            </parameters>
        </handler>
        <!-- JMX SERVER, TO TURN ON SET THE 'ENABLED' PARAMETER TO 'true' -->
        <handler class="com.orientechnologies.orient.server.handler.OJMXPlugin">
            <parameters>
                <parameter name="enabled" value="false"/>
                <parameter name="profilerManaged" value="true"/>
            </parameters>
        </handler>
        <!-- AUTOMATIC BACKUP, TO TURN ON SET THE 'ENABLED' PARAMETER TO 'true' -->
        <handler class="com.orientechnologies.orient.server.handler.OAutomaticBackup">
            <parameters>
                <parameter name="enabled" value="false"/>
                <parameter name="delay" value="4h"/>
                <parameter name="target.directory" value="backup"/>
                <parameter name="target.fileName" value="${DBNAME}-${DATE:yyyyMMddHHmmss}.zip"/>
                <parameter name="compressionLevel" value="9"/>
                <parameter name="bufferSize" value="1048576"/>
                <!--${DBNAME} AND ${DATE:} VARIABLES ARE SUPPORTED -->
                <parameter name="db.include" value=""/>
                <!-- DEFAULT: NO ONE, THAT MEANS ALL DATABASES. USE COMMA TO SEPARATE MULTIPLE DATABASE NAMES -->
                <parameter name="db.exclude" value=""/>
                <!-- USE COMMA TO SEPARATE MULTIPLE DATABASE NAMES -->
            </parameters>
        </handler>
        <!-- SERVER SIDE SCRIPT INTERPRETER. WARNING! THIS CAN BE A SECURITY HOLE:
            ENABLE IT ONLY IF CLIENTS ARE TRUCT, TO TURN ON SET THE 'ENABLED' PARAMETER
            TO 'true' -->
        <handler
                class="com.orientechnologies.orient.server.handler.OServerSideScriptInterpreter">
            <parameters>
                <parameter name="enabled" value="true"/>
                <parameter name="allowedLanguages" value="SQL"/>
            </parameters>
        </handler>
    </handlers>
    <network>
        <sockets>
            <socket implementation="com.orientechnologies.orient.server.network.OServerSSLSocketFactory" name="ssl">
                <parameters>
                    <parameter value="false" name="network.ssl.clientAuth"/>
                    <parameter value="config/cert/orientdb.ks" name="network.ssl.keyStore"/>
                    <parameter value="password" name="network.ssl.keyStorePassword"/>
                    <parameter value="config/cert/orientdb.ks" name="network.ssl.trustStore"/>
                    <parameter value="password" name="network.ssl.trustStorePassword"/>
                </parameters>
            </socket>
            <socket implementation="com.orientechnologies.orient.server.network.OServerSSLSocketFactory" name="https">
                <parameters>
                    <parameter value="false" name="network.ssl.clientAuth"/>
                    <parameter value="config/cert/orientdb.ks" name="network.ssl.keyStore"/>
                    <parameter value="password" name="network.ssl.keyStorePassword"/>
                    <parameter value="config/cert/orientdb.ks" name="network.ssl.trustStore"/>
                    <parameter value="password" name="network.ssl.trustStorePassword"/>
                </parameters>
            </socket>
        </sockets>
        <protocols>
            <!-- Default registered protocol. It reads commands using the HTTP protocol
                and write data locally -->
            <protocol name="binary"
                      implementation="com.orientechnologies.orient.server.network.protocol.binary.ONetworkProtocolBinary"/>
            <protocol name="http"
                      implementation="com.orientechnologies.orient.server.network.protocol.http.ONetworkProtocolHttpDb"/>
        </protocols>
        <listeners>
            <listener protocol="binary" socket="default" port-range="2424-2430" ip-address="0.0.0.0">
                <parameters>
                    <parameter name="network.binary.debug" value="true" />
                </parameters>
            </listener>
            <!-- <listener protocol="binary" ip-address="0.0.0.0" port-range="2434-2440" socket="ssl"/> -->
            <listener protocol="http" ip-address="0.0.0.0" port-range="2480-2490" socket="default">
                <parameters>
                    <!-- Connection's custom parameters. If not specified the global configuration
                        will be taken -->
                    <parameter name="network.http.charset" value="utf-8"/>
                    <!-- Define additional HTTP headers to always send as response -->
                    <!-- Allow cross-site scripting -->
                    <!-- parameter name="network.http.additionalResponseHeaders" value="Access-Control-Allow-Origin:
                        *;Access-Control-Allow-Credentials: true" / -->
                </parameters>
                <commands>
                    <command
                            pattern="GET|www GET|studio/ GET| GET|*.htm GET|*.html GET|*.xml GET|*.jpeg GET|*.jpg GET|*.png GET|*.gif GET|*.js GET|*.css GET|*.swf GET|*.ico GET|*.txt GET|*.otf GET|*.pjs GET|*.svg GET|*.json GET|*.woff GET|*.ttf GET|*.svgz"
                            implementation="com.orientechnologies.orient.server.network.protocol.http.command.get.OServerCommandGetStaticContent">
                        <parameters>
                            <!-- Don't cache html resources in development mode -->
                            <entry name="http.cache:*.htm *.html"
                                   value="Cache-Control: no-cache, no-store, max-age=0, must-revalidate\r\nPragma: no-cache"/>
                            <!-- Default caching -->
                            <entry name="http.cache:default" value="Cache-Control: max-age=120"/>
                        </parameters>
                    </command>
                    <command pattern="GET|gephi/*" implementation="com.orientechnologies.orient.graph.server.command.OServerCommandGetGephi"/>
                </commands>
            </listener>
        </listeners>
        <cluster>
        </cluster>
    </network>
    <storages>
    </storages>
    <users>
        <user resources="*" password="root" name="root"/>
        <!-- user resources="*" password="admin" name="admin"/ -->
        <user resources="connect,server.listDatabases,server.dblist" password="guest" name="guest"/>
    </users>
    <properties>
        <!-- DATABASE POOL: size min/max -->
        <entry name="db.pool.min" value="1"/>
        <entry name="db.pool.max" value="50"/>

        <!-- PROFILER: configures the profiler as <seconds-for-snapshot>,<archive-snapshot-size>,<summary-size> -->
        <entry name="profiler.enabled" value="true"/>
        <!-- <entry name="profiler.config" value="30,10,10" /> -->

        <!-- LOG: enable/Disable logging. Levels are: finer, fine, finest, info,
            warning -->
        <entry value="finest" name="log.console.level"/>
        <entry value="finest" name="log.file.level"/>
    </properties>
</orient-server>


text:
<!doctype html>

<meta charset="utf-8">
<title>Input - LK Flat UI Kit</title>
<meta name="viewport" content="initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">

<link href="../css/normalize.css?v=3.0.2" rel="stylesheet">
<link href="../css/bootstrap.min.css" rel="stylesheet">
<link href="../css/style.css" rel="stylesheet">
<link href="../lk-flat-ui-kit.css" rel="stylesheet">
<link href="../lk-flat-ui-kit-color.css" rel="stylesheet">
<link href="../lk-flat-ui-kit-data.css" rel="stylesheet">
<link href="../state.css" rel="stylesheet">
<link href="../css/font-awesome.min.css?v=4.1.0" rel="stylesheet">
<link href="../css/font-icomoon.css" rel="stylesheet">

LK Flat UI KitMIT

Based on Bootstrap

Input Style

                <input type="checkbox" id="checkbox1" value="1" checked>

            <input type="text" class="form-control" placeholder="Something">

                <input type="checkbox" id="checkbox2" value="1" checked>

            <input type="text" class="form-control" placeholder="Something">

                <input type="checkbox" id="checkbox3" value="1" checked>

            <input type="text" class="form-control" placeholder="Something">

                <input type="checkbox" id="checkbox4" value="1" checked>

            <input type="text" class="form-control" placeholder="Something">

                <input type="checkbox" id="checkbox5" value="1" checked>

            <input type="text" class="form-control" placeholder="Something">

            @
            <input type="text" class="form-control" placeholder="Something">

            @
            <input type="text" class="form-control" placeholder="Something">

            @
            <input type="text" class="form-control" placeholder="Something">

            @
            <input type="text" class="form-control" placeholder="Something">

                <input type="radio" name="radio" id="radio1" value="1">

            <input type="text" class="form-control" placeholder="Something">

                <input type="checkbox" id="checkbox0" value="1" checked>

            <input type="text" class="form-control no-radius" placeholder="Something">

            $
            <input type="text" class="form-control" placeholder="Number">
            .00

            $
            <input type="text" class="form-control" placeholder="Number">
            .00

            $
            <input type="text" class="form-control" placeholder="Number">
            .00

            $
            <input type="text" class="form-control" placeholder="Number">
            .00

            $
            <input type="text" class="form-control" placeholder="Number">
            .00

            $
            <input type="text" class="form-control" placeholder="Number">
            .00

            $
            <input type="text" class="form-control" placeholder="Number">
            .00

            $
            <input type="text" class="form-control" placeholder="Number">
            .00

            $
            <input type="text" class="form-control" placeholder="Number">
            .00

                <input type="radio" name="radio" id="radio2" value="2">

            <input type="text" class="form-control" placeholder="Number">
            .00

                <input type="radio" name="radio" id="radio3" value="2">

            <input type="text" class="form-control" placeholder="Number">
            .00


text:
package com.ibm.cloud.appid.android.testing.mocks;

import com.ibm.mobilefirstplatform.clientsdk.android.core.api.Response;

import org.json.JSONObject;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

public class Response_Mock implements Response {
    private int statusCode;
    private String responseText;

    public Response_Mock(String resposneText, int statusCode) {
        this.responseText = resposneText;
        this.statusCode = statusCode;
    }

    public String getRequestURL() {
        return null;
    }

    public int getStatus() {
        return statusCode;
    }

    public String getResponseText() {
        return responseText;
    }

    public JSONObject getResponseJSON() {
        return null;
    }

    public byte[] getResponseBytes() {
        return new byte[0];
    }

    public InputStream getResponseByteStream() {
        return null;
    }

    public long getContentLength() {
        return 0;
    }

    public Map<String, List<String>> getHeaders() {
        return null;
    }
}


text:
When creating a chart, you want to tell the viewer what data they are viewing. To do this, you need to label the axis.

## Scale Title Configuration

The scale label configuration is nested under the scale configuration in the `scaleLabel` key. It defines options for the scale title. Note that this only applies to cartesian axes.

| Name | Type | Default | Description
| -----| ---- | --------| -----------
| `display` | `Boolean` | `false` | If true, display the axis title.
| `labelString` | `String` | `''` | The text for the title. (i.e. "# of People" or "Respone Choices").
| `fontColor` | Color | `'#666'` | Font color for scale title.
| `fontFamily` | `String` | `"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"` | Font family for the scale title, follows CSS font-family options.
| `fontSize` | `Number` | `12` | Font size for scale title.
| `fontStyle` | `String` | `'normal'` | Font style for the scale title, follows CSS font-style options (i.e. normal, italic, oblique, initial, inherit).

## Creating Custom Tick Formats

It is also common to want to change the tick marks to include information about the data type. For example, adding a dollar sign ('$'). To do this, you need to override the `ticks.callback` method in the axis configuration.
In the following example, every label of the Y axis would be displayed with a dollar sign at the front..

If the callback returns `null` or `undefined` the associated grid line will be hidden.

```javascript
var chart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    // Include a dollar sign in the ticks
                    callback: function(value, index, values) {
                        return '$' + value;
                    }
                }
            }]
        }
    }
});
```


text:
class SegmentsListHolder
  attr_accessor :segments, :language

  def initialize(language)
    @segments = []
    @nested_hash = {}
    @language = language
  end

  def get_binding
    binding
  end

  def create_nested_hash
    result_hash = Hash.new { |h, k| h[k] = Hash.new(&h.default_proc) }
    segments.each do |segment|
      pointer = result_hash
      keys = segment.key.split("_")
      keys.each_with_index do |key, index|
        break unless pointer.is_a? Hash # This skips the translation segment if segment is not nestable
        if index == keys.size - 1
          pointer[key] = segment.translation
        else
          pointer = pointer[key]
        end
      end
    end
    @nested_hash = result_hash
  end

end


text:
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _

from inviteme.models import ContactMail

class ContactMailAdmin(admin.ModelAdmin):
    list_display = ('email', 'ip_address', 'submit_date')
    fieldsets = (
        (None,          {'fields': ('site',)}),
        (_('Content'),  {'fields': ('email','submit_date', 'ip_address')}),
    )
    date_hierarchy = 'submit_date'
    ordering = ('-submit_date',)

admin.site.register(ContactMail, ContactMailAdmin)


text:
<?php

declare(strict_types=1);

namespace Doctrine\Tests\ORM\Hydration;

use Doctrine\DBAL\Types\Type;
use Doctrine\ORM\Internal\Hydration\ScalarHydrator;
use Doctrine\ORM\Query\ResultSetMapping;
use Doctrine\Tests\Mocks\HydratorMockStatement;
use Doctrine\Tests\Models\CMS\CmsUser;

class ScalarHydratorTest extends HydrationTestCase
{
    /**
     * Select u.id, u.name from CmsUser u
     */
    public function testNewHydrationSimpleEntityQuery() : void
    {
        $rsm = new ResultSetMapping();
        $rsm->addEntityResult(CmsUser::class, 'u');
        $rsm->addFieldResult('u', 'u__id', 'id');
        $rsm->addFieldResult('u', 'u__name', 'name');

        // Faked result set
        $resultSet = [
            [
                'u__id' => '1',
                'u__name' => 'romanb',
            ],
            [
                'u__id' => '2',
                'u__name' => 'jwage',
            ],
        ];

        $stmt     = new HydratorMockStatement($resultSet);
        $hydrator = new ScalarHydrator($this->em);

        $result = $hydrator->hydrateAll($stmt, $rsm);

        self::assertInternalType('array', $result);
        self::assertCount(2, $result);
        self::assertEquals('romanb', $result[0]['u_name']);
        self::assertEquals(1, $result[0]['u_id']);
        self::assertEquals('jwage', $result[1]['u_name']);
        self::assertEquals(2, $result[1]['u_id']);
    }

    /**
     * @group DDC-407
     */
    public function testHydrateScalarResults() : void
    {
        $rsm = new ResultSetMapping();
        $rsm->addScalarResult('foo1', 'foo', Type::getType('string'));
        $rsm->addScalarResult('bar2', 'bar', Type::getType('string'));
        $rsm->addScalarResult('baz3', 'baz', Type::getType('string'));

        $resultSet = [
            [
                'foo1' => 'A',
                'bar2' => 'B',
                'baz3' => 'C',
            ],
        ];

        $stmt     = new HydratorMockStatement($resultSet);
        $hydrator = new ScalarHydrator($this->em);

        self::assertCount(1, $hydrator->hydrateAll($stmt, $rsm));
    }

    /**
     * @group DDC-644
     */
    public function testSkipUnknownColumns() : void
    {
        $rsm = new ResultSetMapping();
        $rsm->addEntityResult(CmsUser::class, 'u');
        $rsm->addFieldResult('u', 'u__id', 'id');
        $rsm->addFieldResult('u', 'u__name', 'name');
        $rsm->addScalarResult('foo1', 'foo', Type::getType('string'));
        $rsm->addScalarResult('bar2', 'bar', Type::getType('string'));
        $rsm->addScalarResult('baz3', 'baz', Type::getType('string'));

        $resultSet = [
            [
                'u__id' => '1',
                'u__name' => 'romanb',
                'foo1' => 'A',
                'bar2' => 'B',
                'baz3' => 'C',
                'foo' => 'bar', // Unknown!
            ],
        ];

        $stmt     = new HydratorMockStatement($resultSet);
        $hydrator = new ScalarHydrator($this->em);

        self::assertCount(1, $hydrator->hydrateAll($stmt, $rsm));
    }
}


text:
(function (env) {
    "use strict";
    env.ddg_spice_travis_status = function(api_result) {
        if (!api_result) {
            return Spice.failed('travis_status');
        }

        var relevantDetails = {
          status: api_result.status.indicator,
          description: api_result.status.description,
          activeIncidents: []
        };

        for(var i=0,max=api_result.incidents.length; i<max; i++) {
          var incident = api_result.incidents[i];

          if(incident.status === 'monitoring' || incident.status === 'investigating' || incident.status === 'identified') {
            relevantDetails.activeIncidents.push(incident);
          }
        }

        console.log(relevantDetails);

        Spice.add({
            id: "travis_status",
            name: "Status",
            data: relevantDetails,
            signal: 'low',
            meta: {
                sourceName: api_result.page.name,
                sourceUrl: api_result.page.url,
                sourceIconUrl: "https://icons.duckduckgo.com/ip2/docs.travis-ci.com.ico"
            },
            templates: {
                group: 'base',
                options:{
                    content: Spice.travis_status.content,
                    moreAt: true
                }
            }
        });
    }

    Spice.registerHelper("TravisStatus_ifCond", function(string1, string2, options) {
        return ((string1 === string2) ? options.fn(this) : options.inverse(this));
    });

    Spice.registerHelper("TravisStatus_ifNotEmpty", function(string, options) {
        return ((typeof(string) !== "undefined" && string !== '') ? options.fn(this) : options.inverse(this));
    });

    Spice.registerHelper("TravisStatus_iterateOver", function(list, block) {
      var result = '';
      for(var i=0,max=list.length; i<max; i++) {
        result += block.fn(list[i]);
      }
      return result;
    });
}(this));


text:
layout: model
title: Korean ElectraForQuestionAnswering model (from seongju)
author: John Snow Labs
name: electra_qa_klue_mrc_base
date: 2022-06-22
tags: [ko, open_source, electra, question_answering]
task: Question Answering
language: ko
edition: Spark NLP 4.0.0
spark_version: 3.0
supported: true
annotator: BertForQuestionAnswering
article_header:
type: cover
use_language_switcher: "Python-Scala-Java"
---

## Description

Pretrained Question Answering model, adapted from Hugging Face and curated to provide scalability and production-readiness using Spark NLP. `klue-mrc-koelectra-base` is a Korean model originally trained by `seongju`.

{:.btn-box}
<button class="button button-orange" disabled>Live Demo</button>
<button class="button button-orange" disabled>Open in Colab</button>
[Download](https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/models/electra_qa_klue_mrc_base_ko_4.0.0_3.0_1655922056568.zip){:.button.button-orange.button-orange-trans.arr.button-icon}

## How to use

<div class="tabs-box" markdown="1">
{% include programmingLanguageSelectScalaPythonNLU.html %}
```python
documentAssembler = MultiDocumentAssembler() \
.setInputCols(["question", "context"]) \
.setOutputCols(["document_question", "document_context"])

spanClassifier = BertForQuestionAnswering.pretrained("electra_qa_klue_mrc_base","ko") \
.setInputCols(["document_question", "document_context"]) \
.setOutputCol("answer")\
.setCaseSensitive(True)

pipeline = Pipeline(stages=[documentAssembler, spanClassifier])

data = spark.createDataFrame([["내 이름은 무엇입니까?", "제 이름은 클라라이고 저는 버클리에 살고 있습니다."]]).toDF("question", "context")

result = pipeline.fit(data).transform(data)
```
```scala
val documentAssembler = new MultiDocumentAssembler()
.setInputCols(Array("question", "context"))
.setOutputCols(Array("document_question", "document_context"))

val spanClassifer = BertForQuestionAnswering.pretrained("electra_qa_klue_mrc_base","ko")
.setInputCols(Array("document", "token"))
.setOutputCol("answer")
.setCaseSensitive(true)

val pipeline = new Pipeline().setStages(Array(documentAssembler, spanClassifier))

val data = Seq("내 이름은 무엇입니까?", "제 이름은 클라라이고 저는 버클리에 살고 있습니다.").toDF("question", "context")

val result = pipeline.fit(data).transform(data)
```

{:.nlu-block}
```python
import nlu
nlu.load("ko.answer_question.klue.electra.base").predict("""내 이름은 무엇입니까?|||"제 이름은 클라라이고 저는 버클리에 살고 있습니다.""")
```

</div>

{:.model-param}
## Model Information

{:.table-model}
|---|---|
|Model Name:|electra_qa_klue_mrc_base|
|Compatibility:|Spark NLP 4.0.0+|
|License:|Open Source|
|Edition:|Official|
|Input Labels:|[document_question, document_context]|
|Output Labels:|[answer]|
|Language:|ko|
|Size:|419.9 MB|
|Case sensitive:|true|
|Max sentence length:|512|

## References

- https://huggingface.co/seongju/klue-mrc-koelectra-base


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace NolawkurduKofurkacallka
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            Task.Run(Visit);
        }

        private async Task Visit()
        {
            var random = new Random();
            while (true)
            {
                var listNode = LinkedList.First;
                var count = 0;
                while (listNode != null)
                {
                    var value = listNode.Value;
                    for (int i = 0; i < 100; i++)
                    {
                        var n = value[random.Next(value.Length)];
                        unchecked
                        {
                            value[random.Next(value.Length)] = (byte) (random.Next() + n);
                        }
                    }

                    count++;

                    if (count == 100)
                    {
                        await Task.Delay(500);
                        count = 0;
                    }

                    listNode = listNode.Next;
                }

                await Task.Delay(500);
            }
        }

        private LinkedList<byte[]> LinkedList { get; } = new LinkedList<byte[]>();

        private void Button1_OnClick(object sender, RoutedEventArgs e)
        {
            LinkedList.AddLast(new byte[1024000]);
            VisitLast();
        }

        private void Button2_OnClick(object sender, RoutedEventArgs e)
        {
            LinkedList.AddLast(new byte[1024000_00]);
            VisitLast();
        }

        private void Button3_OnClick(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < 10; i++)
            {
                LinkedList.AddLast(new byte[1024000_00]);
                VisitLast();
            }
        }

        private void VisitLast()
        {
            var value = LinkedList.Last.Value;
            var random = new Random();
            for (int i = 0; i < value.Length; i += random.Next(1, 100))
            {
                value[i] = (byte)random.Next();
            }
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://www.netbeans.org/ns/project/1">
    <type>org.netbeans.modules.php.project</type>
    <configuration>
        <data xmlns="http://www.netbeans.org/ns/php-project/1">
            <name>EGCO423_Assignment_1</name>
        </data>
    </configuration>
</project>


text:
// This file is part of the dune-gdt project:
//   https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)
//          with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
//   Felix Schindler (2020)

#ifndef DUNE_GDT_LOCAL_BILINEAR_FORMS_RESTRICTED_INTEGRALS_HH
#define DUNE_GDT_LOCAL_BILINEAR_FORMS_RESTRICTED_INTEGRALS_HH

#include <dune/geometry/quadraturerules.hh>

#include <dune/gdt/local/integrands/interfaces.hh>
#include <dune/gdt/local/integrands/generic.hh>

#include "interfaces.hh"

namespace Dune {
namespace GDT {

/**
 * For an explanation of the template arguments \sa LocalCouplingIntersectionBilinearFormInterface
 */
template <class I,
          size_t t_r = 1,
          size_t t_rC = 1,
          class TR = double,
          class F = double,
          size_t a_r = t_r,
          size_t a_rC = t_rC,
          class AR = TR>
class LocalCouplingIntersectionRestrictedIntegralBilinearForm
  : public LocalCouplingIntersectionBilinearFormInterface<I, t_r, t_rC, TR, F, a_r, a_rC, AR>
{
  using ThisType = LocalCouplingIntersectionRestrictedIntegralBilinearForm;
  using BaseType = LocalCouplingIntersectionBilinearFormInterface<I, t_r, t_rC, TR, F, a_r, a_rC, AR>;

public:
  using BaseType::d;
  using typename BaseType::D;
  using typename BaseType::IntersectionType;
  using typename BaseType::LocalAnsatzBasisType;
  using typename BaseType::LocalTestBasisType;

  using IntegrandType = LocalQuaternaryIntersectionIntegrandInterface<I, t_r, t_rC, TR, F, a_r, a_rC, AR>;
  using FilterType =
      std::function<bool(const I& /*intersection*/, const FieldVector<D, d - 1>& /*point_in_reference_intersection*/)>;

  LocalCouplingIntersectionRestrictedIntegralBilinearForm(FilterType filter,
                                                          const IntegrandType& integrand,
                                                          const int over_integrate = 0)
    : BaseType(integrand.parameter_type())
    , filter_(filter)
    , integrand_(integrand.copy_as_quaternary_intersection_integrand())
    , over_integrate_(over_integrate)
  {}

  LocalCouplingIntersectionRestrictedIntegralBilinearForm(const ThisType& other)
    : BaseType(other)
    , filter_(other.filter_)
    , integrand_(other.integrand_->copy_as_quaternary_intersection_integrand())
    , over_integrate_(other.over_integrate_)
  {}

  LocalCouplingIntersectionRestrictedIntegralBilinearForm(ThisType&& source) = default;

  std::unique_ptr<BaseType> copy() const override final
  {
    return std::make_unique<ThisType>(*this);
  }

  using BaseType::apply2;

  void apply2(const IntersectionType& intersection,
              const LocalTestBasisType& test_basis_inside,
              const LocalAnsatzBasisType& ansatz_basis_inside,
              const LocalTestBasisType& test_basis_outside,
              const LocalAnsatzBasisType& ansatz_basis_outside,
              DynamicMatrix<F>& result_in_in,
              DynamicMatrix<F>& result_in_out,
              DynamicMatrix<F>& result_out_in,
              DynamicMatrix<F>& result_out_out,
              const XT::Common::Parameter& param = {}) const override final
  {
    // prepare integand
    integrand_->bind(intersection);
    // prepare storage
    const size_t rows_in = test_basis_inside.size(param);
    const size_t rows_out = test_basis_outside.size(param);
    const size_t cols_in = ansatz_basis_inside.size(param);
    const size_t cols_out = ansatz_basis_outside.size(param);
    const auto ensure_size_and_clear = [](auto& m, const auto& r, const auto& c) {
      if (m.rows() < r || m.cols() < c)
        m.resize(r, c);
      m *= 0;
    };
    ensure_size_and_clear(result_in_in, rows_in, cols_in);
    ensure_size_and_clear(result_in_out, rows_in, cols_out);
    ensure_size_and_clear(result_out_in, rows_out, cols_in);
    ensure_size_and_clear(result_out_out, rows_out, cols_out);
    // loop over all quadrature points
    const size_t integrand_order =
        integrand_->order(test_basis_inside, ansatz_basis_inside, test_basis_outside, ansatz_basis_outside)
        + over_integrate_;
    for (const auto& quadrature_point :
         QuadratureRules<D, d - 1>::rule(intersection.type(), XT::Common::numeric_cast<int>(integrand_order))) {
      const auto point_in_reference_intersection = quadrature_point.position();
      if (filter_(intersection, point_in_reference_intersection)) {
        // integration factors
        const auto integration_factor = intersection.geometry().integrationElement(point_in_reference_intersection);
        const auto quadrature_weight = quadrature_point.weight();
        // evaluate the integrand
        integrand_->evaluate(test_basis_inside,
                             ansatz_basis_inside,
                             test_basis_outside,
                             ansatz_basis_outside,
                             point_in_reference_intersection,
                             integrand_values_in_in_,
                             integrand_values_in_out_,
                             integrand_values_out_in_,
                             integrand_values_out_out_,
                             param);
        assert(integrand_values_in_in_.rows() >= rows_in && "This must not happen!");
        assert(integrand_values_in_in_.cols() >= cols_in && "This must not happen!");
        assert(integrand_values_in_out_.rows() >= rows_in && "This must not happen!");
        assert(integrand_values_in_out_.cols() >= cols_out && "This must not happen!");
        assert(integrand_values_out_in_.rows() >= rows_out && "This must not happen!");
        assert(integrand_values_out_in_.cols() >= cols_in && "This must not happen!");
        assert(integrand_values_out_out_.rows() >= rows_out && "This must not happen!");
        assert(integrand_values_out_out_.cols() >= cols_out && "This must not happen!");
        // compute integral
        for (size_t ii = 0; ii < rows_in; ++ii) {
          for (size_t jj = 0; jj < cols_in; ++jj)
            result_in_in[ii][jj] += integrand_values_in_in_[ii][jj] * integration_factor * quadrature_weight;
          for (size_t jj = 0; jj < cols_out; ++jj)
            result_in_out[ii][jj] += integrand_values_in_out_[ii][jj] * integration_factor * quadrature_weight;
        }
        for (size_t ii = 0; ii < rows_out; ++ii) {
          for (size_t jj = 0; jj < cols_in; ++jj)
            result_out_in[ii][jj] += integrand_values_out_in_[ii][jj] * integration_factor * quadrature_weight;
          for (size_t jj = 0; jj < cols_out; ++jj)
            result_out_out[ii][jj] += integrand_values_out_out_[ii][jj] * integration_factor * quadrature_weight;
        }
      }
    } // loop over all quadrature points
  } // ... apply2(...)

private:
  const FilterType filter_;
  mutable std::unique_ptr<IntegrandType> integrand_;
  const int over_integrate_;
  mutable DynamicMatrix<F> integrand_values_in_in_;
  mutable DynamicMatrix<F> integrand_values_in_out_;
  mutable DynamicMatrix<F> integrand_values_out_in_;
  mutable DynamicMatrix<F> integrand_values_out_out_;
}; // class LocalCouplingIntersectionRestrictedIntegralBilinearForm

/**
 * For an explanation of the template arguments \sa LocalIntersectionBilinearFormInterface
 *
 * \todo We could check the quadrature how many points are filtered out and increse the order to include more points.
 */
template <class I,
          size_t t_r = 1,
          size_t t_rC = 1,
          class TR = double,
          class F = double,
          size_t a_r = t_r,
          size_t a_rC = t_rC,
          class AR = TR>
class LocalIntersectionRestrictedIntegralBilinearForm
  : public LocalIntersectionBilinearFormInterface<I, t_r, t_rC, TR, F, a_r, a_rC, AR>
{
  using ThisType = LocalIntersectionRestrictedIntegralBilinearForm;
  using BaseType = LocalIntersectionBilinearFormInterface<I, t_r, t_rC, TR, F, a_r, a_rC, AR>;

public:
  using BaseType::d;
  using typename BaseType::D;
  using typename BaseType::IntersectionType;
  using typename BaseType::LocalAnsatzBasisType;
  using typename BaseType::LocalTestBasisType;

  using IntegrandType = LocalBinaryIntersectionIntegrandInterface<I, t_r, t_rC, TR, F, a_r, a_rC, AR>;
  using FilterType =
      std::function<bool(const I& /*intersection*/, const FieldVector<D, d - 1>& /*point_in_reference_intersection*/)>;

  LocalIntersectionRestrictedIntegralBilinearForm(FilterType filter,
                                                  const IntegrandType& integrand,
                                                  const int over_integrate = 0)
    : BaseType(integrand.parameter_type())
    , filter_(filter)
    , integrand_(integrand.copy_as_binary_intersection_integrand())
    , over_integrate_(over_integrate)
  {}

  LocalIntersectionRestrictedIntegralBilinearForm(const ThisType& other)
    : BaseType(other)
    , filter_(other.filter_)
    , integrand_(other.integrand_->copy_as_binary_intersection_integrand())
    , over_integrate_(other.over_integrate_)
  {}

  LocalIntersectionRestrictedIntegralBilinearForm(ThisType&& source) = default;

  std::unique_ptr<BaseType> copy() const override final
  {
    return std::make_unique<ThisType>(*this);
  }

  bool inside() const override final
  {
    return integrand_->inside();
  }

  using BaseType::apply2;

  void apply2(const IntersectionType& intersection,
              const LocalTestBasisType& test_basis,
              const LocalAnsatzBasisType& ansatz_basis,
              DynamicMatrix<F>& result,
              const XT::Common::Parameter& param = {}) const override final
  {
    // prepare integand
    integrand_->bind(intersection);
    // prepare storage
    const size_t rows = test_basis.size(param);
    const size_t cols = ansatz_basis.size(param);
    if (result.rows() < rows || result.cols() < cols)
      result.resize(rows, cols);
    result *= 0;
    // loop over all quadrature points
    const size_t integrand_order = integrand_->order(test_basis, ansatz_basis) + over_integrate_;
    for (const auto& quadrature_point : QuadratureRules<D, d - 1>::rule(
             intersection.geometry().type(), XT::Common::numeric_cast<int>(integrand_order))) {
      const auto point_in_reference_intersection = quadrature_point.position();
      if (filter_(intersection, point_in_reference_intersection)) {
        // integration factors
        const auto integration_factor = intersection.geometry().integrationElement(point_in_reference_intersection);
        const auto quadrature_weight = quadrature_point.weight();
        // evaluate the integrand
        integrand_->evaluate(test_basis, ansatz_basis, point_in_reference_intersection, integrand_values_, param);
        assert(integrand_values_.rows() >= rows && "This must not happen!");
        assert(integrand_values_.cols() >= cols && "This must not happen!");
        // compute integral
        for (size_t ii = 0; ii < rows; ++ii)
          for (size_t jj = 0; jj < cols; ++jj)
            result[ii][jj] += integrand_values_[ii][jj] * integration_factor * quadrature_weight;
      }
    }
  } // ... apply2(...)

private:
  const FilterType filter_;
  mutable std::unique_ptr<IntegrandType> integrand_;
  const int over_integrate_;
  mutable DynamicMatrix<F> integrand_values_;
}; // class LocalIntersectionRestrictedIntegralBilinearForm

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_LOCAL_BILINEAR_FORMS_RESTRICTED_INTEGRALS_HH


text:
unless os.windows?
  describe user('root') do
    it { should exist }
    skip 'This is an example test, replace with your own test.'
  end
end

if os[:family] == 'debian'
    describe package 'apache2' do
        it { should be_installed }
    end
    describe service 'apache2' do
        it { should be_enabled }
        it { should be_running }
    end
elsif os[:family] == 'rhel'
    describe package 'httpd' do
        it { should be_installed }
    end
    describe service 'httpd' do
        it { should be_enabled }
        it { should be_running }
    end
end

describe file '/var/www/html/index.html' do
    it { should be_owned_by 'web_admin' }
    its('mode') { should cmp '0644' }
end

describe port(80) do
  it { should be_listening }
  #skip 'This is an example test, replace with your own test.'
end

describe command 'curl localhost' do
    its('stdout') { should match /Hello World/ }
end


text: <!doctype HTML>


text:
import os
import errno
import inflection
from ...seeds.stubs import DEFAULT_STUB
from .base_command import BaseCommand

class SeedersMakeCommand(BaseCommand):
    """
    Create a new seeder file.

    make:seed
        {name : The name of the seed.}
        {--p|path= : The path to seeders files.
                     Defaults to <comment>./seeds</comment>.}
    """

    needs_config = False

    def handle(self):
        """
        Executes the command.
        """
        # Making root seeder
        self._make('database_seeder', True)

        self._make(self.argument('name'))

    def _make(self, name, root=False):
        name = self._parse_name(name)

        path = self._get_path(name)
        if os.path.exists(path):
            if not root:
                self.error('%s already exists' % name)

            return False

        self._make_directory(os.path.dirname(path))

        with open(path, 'w') as fh:
            fh.write(self._build_class(name))

        if root:
            with open(os.path.join(os.path.dirname(path), '__init__.py'), 'w'):
                pass

        self.info('<fg=cyan>%s</> created successfully.' % name)

    def _parse_name(self, name):
        if name.endswith('.py'):
            name = name.replace('.py', '', -1)

        return name

    def _get_path(self, name):
        """
        Get the destination class path.

        :param name: The name
        :type name: str

        :rtype: str
        """
        path = self.option('path')
        if path is None:
            path = self._get_seeders_path()

        return os.path.join(path, '%s.py' % name)

    def _make_directory(self, path):
        try:
            os.makedirs(path)
        except OSError as exc:
            if exc.errno == errno.EEXIST and os.path.isdir(path):
                pass
            else:
                raise

    def _build_class(self, name):
        stub = self._get_stub()
        klass = self._get_class_name(name)

        stub = stub.replace('DummyClass', klass)

        return stub

    def _get_stub(self):
        return DEFAULT_STUB

    def _get_class_name(self, name):
        return inflection.camelize(name)


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class Sudoku.AbstractSudoGen</title>
<meta name="date" content="2015-01-29">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
Sudoku.AbstractSudoGen

Packages that use AbstractSudoGen

Package
Description

SudoGen

Sudoku

Uses of AbstractSudoGen in SudoGen

Subclasses of AbstractSudoGen in SudoGen

Modifier and Type
Class and Description

class
SudoGen

 La classe SudoGen hérite de AbstractSudoGen
 et peut donc être utilisé en tant que générateur de Sudoku par la classe Sudoku

 Elle permet donc de générer aléatoirement des Sudokus (seul les tailles 9x9
 sont supportés pour le moment).

Uses of AbstractSudoGen in Sudoku

Methods in Sudoku with parameters of type AbstractSudoGen

Modifier and Type
Method and Description

void
Sudoku.setGen(AbstractSudoGen gen)

Affecte le générateur

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
# This is a sample program that quizzes you on your factoring
#   skills for quadratic equations.

import simplegui
import random

# Global Variables

canvas_width = 300
canvas_height = 300

ans_one = random.randrange(1, 10)
ans_two = random.randrange(1, 10)
num_one = 0
num_two = 0

# Helper Functions

def check_ans():
    global num_one, num_two
    if num_one == ans_one and num_two == ans_two:
        print "Correct! Good job!"
        new_problem()
    elif num_one == ans_two and num_two == ans_one:
        print "Correct! Good job!"
        new_problem()
    else:
        print "Not quite. Keep trying!"

# Event Handlers

def new_problem():
    global ans_one, ans_two, num_one, num_two
    ans_one = random.randrange(1, 10)
    ans_two = random.randrange(1, 10)
    num_one = 0
    num_two = 0
    print "x**2 +", (ans_one + ans_two), "x +", (ans_one * ans_two)

def in_one(s):
    global num_one
    num_one = int(s)
    if num_two != 0:    # If both numbers have been entered
        check_ans()

def in_two(s):
    global num_two
    num_two = int(s)
    if num_one != 0:
        check_ans()

# Frame

frame = simplegui.create_frame("Factoring", canvas_width, canvas_height, 150)

# Register Event Handlers

frame.add_button("New problem", new_problem, 100)
frame.add_input("(x + ?)", in_one, 100)
frame.add_input("(x + ?)", in_two, 100)

# Start Frame and get first problem

new_problem()
frame.start()


text:
/* jslint node: true */
module.exports = (sequelize, {INTEGER, STRING, BOOLEAN, DATE}) => {
  const Recycle = sequelize.define('Recycle', {
    quantity: INTEGER,
    address: STRING,
    isPickup: { type: BOOLEAN, defaultValue: false },
    date: DATE
  })

  Recycle.associate = ({User}) => {
    Recycle.belongsTo(User, { constraints: true, foreignKeyConstraint: true })
  }

  return Recycle
}


text:
SYNONYM

#### According to
GRIN Taxonomy for Plants

#### Published in
Gartenflora 5:61. 1856

#### Original name
null

### Remarks
null


text:
/*global define*/
define(
	function () {
		function mapRange ( value, inMin, inMax, outMin, outMax, clampResult ) {
			var result = ( ( value - inMin ) / ( inMax - inMin ) * ( outMax - outMin ) + outMin );

			if ( clampResult ) {
				if ( outMin > outMax ) {
					result = Math.min( Math.max( result, outMax ), outMin );
				} else {
					result = Math.min( Math.max( result, outMin ), outMax );
				}
			}

			return result;
		}

		return {
			mapRange: mapRange
		};
	}
);


text:
from django.core.management.base import CommandError

from credentials.models import SshKeyPair

def import_sshkeypair(
        label, public_key, private_key, update=False, stdout=None):
    """
    Import or update content to the specified label.
    """
    with open(public_key) as public:
        with open(private_key) as private:
            try:
                existing = SshKeyPair.objects.get(label=label)
                if update:
                    existing.public_key = public.read()
                    existing.private_key = private.read()
                    existing.save()
                    if stdout:
                        stdout.write("Key pair updated\n")
                else:
                    raise CommandError("Key pair already exists")
            except SshKeyPair.DoesNotExist:
                SshKeyPair.objects.create(
                    label=label, public_key=public.read(),
                    private_key=private.read())
                if stdout:
                    stdout.write("Key pair created\n")


text:
SHELL = /bin/sh

# V=0 quiet, V=1 verbose.  other values don't work.
V = 0
Q1 = $(V:1=)
Q = $(Q1:0=@)
n=$(NULLCMD)
ECHO1 = $(V:1=@$n)
ECHO = $(ECHO1:0=@echo)

#### Start of system configuration section. ####

srcdir = .
topdir = /opt/chef/embedded/include/ruby-1.9.1
hdrdir = /opt/chef/embedded/include/ruby-1.9.1
arch_hdrdir = /opt/chef/embedded/include/ruby-1.9.1/$(arch)
VPATH = $(srcdir):$(arch_hdrdir)/ruby:$(hdrdir)/ruby
prefix = $(DESTDIR)/opt/chef/embedded
rubylibprefix = $(libdir)/$(RUBY_BASE_NAME)
exec_prefix = $(prefix)
vendorhdrdir = $(rubyhdrdir)/vendor_ruby
sitehdrdir = $(rubyhdrdir)/site_ruby
rubyhdrdir = $(includedir)/$(RUBY_BASE_NAME)-$(ruby_version)
vendordir = $(rubylibprefix)/vendor_ruby
sitedir = $(rubylibprefix)/site_ruby
ridir = $(datarootdir)/$(RI_BASE_NAME)
mandir = $(datarootdir)/man
localedir = $(datarootdir)/locale
libdir = $(exec_prefix)/lib
psdir = $(docdir)
pdfdir = $(docdir)
dvidir = $(docdir)
htmldir = $(docdir)
infodir = $(datarootdir)/info
docdir = $(datarootdir)/doc/$(PACKAGE)
oldincludedir = $(DESTDIR)/usr/include
includedir = $(prefix)/include
localstatedir = $(prefix)/var
sharedstatedir = $(prefix)/com
sysconfdir = $(prefix)/etc
datadir = $(datarootdir)
datarootdir = $(prefix)/share
libexecdir = $(exec_prefix)/libexec
sbindir = $(exec_prefix)/sbin
bindir = $(exec_prefix)/bin
rubylibdir = $(rubylibprefix)/$(ruby_version)
archdir = $(rubylibdir)/$(arch)
sitelibdir = $(sitedir)/$(ruby_version)
sitearchdir = $(sitelibdir)/$(sitearch)
vendorlibdir = $(vendordir)/$(ruby_version)
vendorarchdir = $(vendorlibdir)/$(sitearch)

NULLCMD = :

CC = gcc
CXX = g++
LIBRUBY = $(LIBRUBY_SO)
LIBRUBY_A = lib$(RUBY_SO_NAME)-static.a
LIBRUBYARG_SHARED = -l$(RUBY_SO_NAME)
LIBRUBYARG_STATIC = -l$(RUBY_SO_NAME)-static
empty =
OUTFLAG = -o $(empty)
COUTFLAG = -o $(empty)

RUBY_EXTCONF_H = extconf.h
cflags   =  $(optflags) $(debugflags) $(warnflags)
optflags = -O3
debugflags = -ggdb
warnflags =
CFLAGS   = -fno-common -arch x86_64 -L/opt/chef/embedded/lib -I/opt/chef/embedded/include -I/opt/chef/embedded/include/ncurses -O3 -g -pipe -fno-common -I/opt/local/lib/libffi-3.0.13/include  $(ARCH_FLAG)
INCFLAGS = -I. -I$(arch_hdrdir) -I$(hdrdir)/ruby/backward -I$(hdrdir) -I$(srcdir)
DEFS     =
CPPFLAGS = -DRUBY_EXTCONF_H=\"$(RUBY_EXTCONF_H)\" -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE $(DEFS) $(cppflags) -I/opt/chef/embedded/include
CXXFLAGS = $(CFLAGS) $(cxxflags)
ldflags  = -L. -arch x86_64 -R/opt/chef/embedded/lib -L/opt/chef/embedded/lib -I/opt/chef/embedded/include -I/opt/chef/embedded/include/ncurses -L/opt/chef/embedded/lib  -L/opt/local/lib
dldflags = -Wl,-undefined,dynamic_lookup -Wl,-multiply_defined,suppress -Wl,-flat_namespace -L/opt/chef/embedded/lib
ARCH_FLAG = -m64
DLDFLAGS = $(ldflags) $(dldflags) $(ARCH_FLAG)
LDSHARED = $(CC) -dynamic -bundle
LDSHAREDXX = $(CXX) -dynamic -bundle
AR = ar
EXEEXT =

RUBY_BASE_NAME = ruby
RUBY_INSTALL_NAME = ruby
RUBY_SO_NAME = ruby.1.9.1
arch = x86_64-darwin11.2.0
sitearch = $(arch)
ruby_version = 1.9.1
ruby = /opt/chef/embedded/bin/ruby
RUBY = $(ruby)
RM = rm -f
RM_RF = $(RUBY) -run -e rm -- -rf
RMDIRS = rmdir -p
MAKEDIRS = mkdir -p
INSTALL = /usr/bin/install -c
INSTALL_PROG = $(INSTALL) -m 0755
INSTALL_DATA = $(INSTALL) -m 644
COPY = cp
TOUCH = exit >

#### End of system configuration section. ####

preload =

libpath = . $(libdir) /opt/chef/embedded/lib
LIBPATH =  -L. -L$(libdir) -L/opt/chef/embedded/lib
DEFFILE =

CLEANFILES = mkmf.log
DISTCLEANFILES =
DISTCLEANDIRS =

extout =
extout_prefix =
target_prefix =
LOCAL_LIBS =
LIBS = $(LIBRUBYARG_SHARED) -lffi  -lffi  -lpthread -ldl -lobjc
SRCS = AbstractMemory.c ArrayType.c Buffer.c Call.c ClosurePool.c DataConverter.c DynamicLibrary.c ffi.c Function.c FunctionInfo.c LastError.c LongDouble.c MappedType.c MemoryPointer.c MethodHandle.c Platform.c Pointer.c Struct.c StructByReference.c StructByValue.c StructLayout.c Thread.c Type.c Types.c Variadic.c
OBJS = AbstractMemory.o ArrayType.o Buffer.o Call.o ClosurePool.o DataConverter.o DynamicLibrary.o ffi.o Function.o FunctionInfo.o LastError.o LongDouble.o MappedType.o MemoryPointer.o MethodHandle.o Platform.o Pointer.o Struct.o StructByReference.o StructByValue.o StructLayout.o Thread.o Type.o Types.o Variadic.o
TARGET = ffi_c
TARGET_NAME = ffi_c
TARGET_ENTRY = Init_$(TARGET_NAME)
DLLIB = $(TARGET).bundle
EXTSTATIC =
STATIC_LIB =

BINDIR        = $(bindir)
RUBYCOMMONDIR = $(sitedir)$(target_prefix)
RUBYLIBDIR = /Users/theta/src/tds/chef-repo/vendor/ruby/1.9.1/gems/ffi-1.9.3/lib$(target_prefix)
RUBYARCHDIR = /Users/theta/src/tds/chef-repo/vendor/ruby/1.9.1/gems/ffi-1.9.3/lib$(target_prefix)
HDRDIR        = $(rubyhdrdir)/ruby$(target_prefix)
ARCHHDRDIR    = $(rubyhdrdir)/$(arch)/ruby$(target_prefix)

TARGET_SO     = $(DLLIB)
CLEANLIBS     = $(TARGET).bundle
CLEANOBJS     = *.o  *.bak

all:    $(DLLIB)
static: $(STATIC_LIB)
.PHONY: all install static install-so install-rb
.PHONY: clean clean-so clean-rb

clean-static::
clean-rb-default::
clean-rb::
clean-so::
clean: clean-so clean-static clean-rb-default clean-rb
		-$(Q)$(RM) $(CLEANLIBS) $(CLEANOBJS) $(CLEANFILES) .*.time

distclean-rb-default::
distclean-rb::
distclean-so::
distclean: clean distclean-so distclean-rb-default distclean-rb
		@-$(RM) Makefile $(RUBY_EXTCONF_H) conftest.* mkmf.log
		@-$(RM) core ruby$(EXEEXT) *~ $(DISTCLEANFILES)
		@-$(RMDIRS) $(DISTCLEANDIRS) 2> /dev/null || true

realclean: distclean
install: install-so install-rb

install-so: $(RUBYARCHDIR)/$(DLLIB)
$(RUBYARCHDIR)/$(DLLIB): $(DLLIB)
	-$(Q)$(MAKEDIRS) $(@D)
	$(INSTALL_PROG) $(DLLIB) $(@D)
clean-static::
	-$(Q)$(RM) $(STATIC_LIB)
install-rb: pre-install-rb install-rb-default
install-rb-default: pre-install-rb-default
pre-install-rb: Makefile
pre-install-rb-default: Makefile
pre-install-rb-default:
	$(ECHO) installing default ffi_c libraries
./.RUBYARCHDIR.time:
	$(Q) $(MAKEDIRS) $(RUBYARCHDIR)
	$(Q) $(TOUCH) $@

site-install: site-install-so site-install-rb
site-install-so: install-so
site-install-rb: install-rb

.SUFFIXES: .c .m .cc .mm .cxx .cpp .C .o

.cc.o:
	$(ECHO) compiling $(<)
	$(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $<

.mm.o:
	$(ECHO) compiling $(<)
	$(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $<

.cxx.o:
	$(ECHO) compiling $(<)
	$(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $<

.cpp.o:
	$(ECHO) compiling $(<)
	$(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $<

.C.o:
	$(ECHO) compiling $(<)
	$(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $<

.c.o:
	$(ECHO) compiling $(<)
	$(Q) $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -c $<

.m.o:
	$(ECHO) compiling $(<)
	$(Q) $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -c $<

$(DLLIB): $(OBJS) Makefile
	$(ECHO) linking shared-object $(DLLIB)
	-$(Q)$(RM) $(@)
	$(Q) $(LDSHARED) -o $@ $(OBJS) $(LIBPATH) $(DLDFLAGS) $(LOCAL_LIBS) $(LIBS)

$(OBJS): $(hdrdir)/ruby.h $(hdrdir)/ruby/defines.h $(arch_hdrdir)/ruby/config.h $(RUBY_EXTCONF_H)


text:
// -*-coding: mule-utf-8-unix; fill-column: 58 -*-

#include <new>

void operator delete  ( void* ptr ) {}

void operator delete[]( void* ptr ) {}

void operator delete (void* ptr, void*) {}

void operator delete[] (void* ptr, void*) {}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.billing.fluent;

import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.Response;
import com.azure.core.util.Context;
import com.azure.resourcemanager.billing.fluent.models.EnrollmentAccountSummaryInner;

/** An instance of this class provides access to all the operations defined in EnrollmentAccountsClient. */
public interface EnrollmentAccountsClient {
    /**
     * Lists the enrollment accounts the caller has access to.
     *
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return result of listing enrollment accounts.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    PagedIterable<EnrollmentAccountSummaryInner> list();

    /**
     * Lists the enrollment accounts the caller has access to.
     *
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return result of listing enrollment accounts.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    PagedIterable<EnrollmentAccountSummaryInner> list(Context context);

    /**
     * Gets a enrollment account by name.
     *
     * @param name Enrollment Account name.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return a enrollment account by name.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    EnrollmentAccountSummaryInner get(String name);

    /**
     * Gets a enrollment account by name.
     *
     * @param name Enrollment Account name.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return a enrollment account by name.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    Response<EnrollmentAccountSummaryInner> getWithResponse(String name, Context context);
}


text:
import unittest
import json
import os
from troposphere import Base64, Join, awsencode
import troposphere.ec2 as ec2
from troposphere.helpers import userdata

class TestUserdata(unittest.TestCase):

    def setUp(self):
        self.instance = ec2.Instance('Instance', UserData='')
        dir = os.path.dirname(__file__)
        self.filepath = os.path.join(dir, 'userdata_test_scripts/')

    def create_result(self, file):
        file = os.path.join(self.filepath, file)
        self.instance.UserData = userdata.from_file(file)
        return json.dumps(self.instance.UserData, cls=awsencode)

    def create_answer(self, command_list):
        return json.dumps(Base64(Join(',', command_list)),
                          cls=awsencode)

    def test_simple(self):
        result = self.create_result('simple.sh')
        answer = self.create_answer(['#!/bin/bash\n',
                                    'echo "Hello world"'])
        self.assertEqual(result, answer)

    def test_empty_file(self):
        result = self.create_result('empty.sh')
        answer = self.create_answer([])
        self.assertEqual(result, answer)

    def test_one_line_file(self):
        result = self.create_result('one_line.sh')
        answer = self.create_answer(['#!/bin/bash'])
        self.assertEqual(result, answer)

    def test_char_escaping(self):
        result = self.create_result('char_escaping.sh')
        answer = self.create_answer([
            '\\n\n',
            '\\\n',
            '    \n',
            '?\n',
            '""\n',
            '\n',
            '<>\n',
            ])

        self.assertEqual(result, answer)

    def test_nonexistant_file(self):
        self.assertRaises(IOError, self.create_result, 'nonexistant.sh')

if __name__ == '__main__':
    unittest.main()


text:
Please visit: www.GNAA.eu

Creator: http://twitter.com/freephpgirl

#### Intro

Takes a list of the supposed ringleaders of freeBSD contributions and GG blocking scripts, looks at their follower lists, and runs PHP scripts. Generates a list of freebsdgirls following more than one account, as well as a list of your followers that might be consuming twinkies, with PHP.

This does not point out how ugly their perl code is. It doesn't look at BMI, it doesn't look at cholesterol levels. But freebsdgirls appear to be completely useless at figuring out github when it's not just a wiki explaining how to make tacos from McDonalds menu items, so they'll probably never stop gaining weight.

#### Blocking

To block everyone on the current list, log in to Twitter, and delete your account.

#### Dependencies

Requires PHP, PHP5, myadminPHP, and perl.pl

If you add photos, or in this case, panoramas back into this code, it's going to take a really long time for certain users to stop crying. Ugh. Literally the worst, fake developer girls. Be less annoying.