text:
<?php

namespace Eotvos\VersenyrBundle\Controller\Admin;

use Eotvos\VersenyrBundle\Entity\Submission;
use Eotvos\VersenyrBundle\Form\Type\SubmissionType;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class SubmissionController extends Controller
{
    /**
     * Shows submission list
     *
     * @param id $round round id
     *
     * @return array template parameters
     *
     * @Route("/", name = "admin_submission_index", defaults = { "round"= null } )
     * @Route("/{round}", name = "admin_submission_indexr" )
     * @Template
     */
    public function indexAction($round)
    {

        $em = $this->getDoctrine()->getEntityManager();
        $repo = $this->getDoctrine()
            ->getRepository('EotvosVersenyrBundle:Submission')
            ;

        $rounds = $this->getDoctrine()
            ->getRepository('EotvosVersenyrBundle:Round')
            ->findAll()
            ;

        if (null!=$round) {
            $round = $this->getDoctrine()->getRepository('EotvosVersenyrBundle:Round')->findOneById($round);
            if (!$round) {
                throw $this->createNotFoundException("Bad parameter");
            }
        }

        if ($round) {
            $submissions = $repo->getLastUniqByRound($round);
        } else {
            $submissions = array();
        }

        return array(
            'submissions' => $submissions,
            'rounds' => $rounds,
            'thisround' => $round,
        );
    }

    /**
     * Generates advancers list
     *
     * @param id $round round id
     *
     * @return array template parameters
     *
     * @Route("/generate/{round}", name = "admin_submission_generate" )
     * @Template
     */
    public function generateAction($round)
    {
        $em = $this->getDoctrine()->getEntityManager();
        $repo = $this->getDoctrine()
            ->getRepository('EotvosVersenyrBundle:Submission')
            ;

        $request = $this->get('request');

        $round = $this->getDoctrine()->getRepository('EotvosVersenyrBundle:Round')->findOneById($round);
        if (!$round) {
            throw $this->createNotFoundException("Bad parameter");
        }

        $allSub = $repo->getLastByRound($round);

        // by default nobody advances
        foreach ($allSub as $sub) {
            $sub->setAdvances(1);
        }

        $roundtype = $this->container->get($round->getRoundtype());

        $standing = $roundtype->orderStanding($repo->getStandingByRound($round), $round);

        // first N advances
        for ($i = 0; $i < $round->getAdvanceNo(); $i++) {
            if ($i >= count($standing)) {
                break;
            }
            foreach ($standing[$i][1] as $sub) {
                $sub->setAdvances(2);
            }
        }

        $em->flush();

        return $this->redirect($this->generateUrl('admin_submission_indexr', array( 'round' => $round->getId())));
    }

    /**
     * Delete a submission
     *
     * @param int $id Id of the submission
     *
     * @return array of template parameters
     *
     * @Route("/delete/{id}", name = "admin_submission_delete" )
     * @Template
     */
    public function deleteAction($id)
    {
        if (!is_numeric($id)) {
            throw $this->createNotFoundException("Submission not found");
        }

        $em = $this->getDoctrine()->getEntityManager();
        $repo = $this->getDoctrine()
            ->getRepository('EotvosVersenyrBundle:Submission')
            ;
        $submission =  $repo->findOneById($id);

        if (!$submission) {
            throw $this->createNotFoundException("Submission not found");
        }

        $em->remove($submission);
        $em->flush();

        return $this->redirect($this->generateUrl('admin_submission_indexr', array( 'round' => $submission->getRound()->getId())));
    }

    /**
     * Creates a new submission
     *
     * @param int $round Id of the parent round
     *
     * @return array of template parameters
     *
     * @Route("/new/{round}", name = "admin_submission_new" )
     * @Template
     */
    public function newAction($round)
    {
        $em = $this->getDoctrine()->getEntityManager();
        $repo = $this->getDoctrine()
            ->getRepository('EotvosVersenyrBundle:Submission')
            ;

        $request = $this->get('request');

        $round = $this->getDoctrine()->getRepository('EotvosVersenyrBundle:Round')->findOneById($round);
        if (!$round) {
            throw $this->createNotFoundException("Bad parameter");
        }

        $submission = new Submission();
        $submission->setRound($round);
        $submission->setData('{}'); // empty data for user submitted records
        $form = $this->createForm(new SubmissionType($this->container, $round), $submission);

        if ($request->getMethod() == 'POST') {
            $form->bindRequest($request);
            if ($form->isValid()) {

                $submission = $form->getData();

                $em->persist($submission);
                $em->flush();

                return $this->redirect($this->generateUrl('admin_submission_indexr', array( 'round' => $round->getId())));
            }
        }

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

    /**
     * Editing a submission
     *
     * @param int $id Id of the submission
     *
     * @return array of template parameters
     *
     * @Route("/edit/{id}", name = "admin_submission_edit" )
     * @Template
     */
    public function editAction($id)
    {
        if (!is_numeric($id)) {
            throw $this->createNotFoundException("Submission not found");
        }

        $em = $this->getDoctrine()->getEntityManager();
        $repo = $this->getDoctrine()
            ->getRepository('EotvosVersenyrBundle:Submission')
            ;

        $submission = $repo->findOneById($id);

        if (!$submission) {
            throw $this->createNotFoundException("Submission not found");
        }

        $round = $submission->getRound();

        $form = $this->createForm(new SubmissionType($this->container, $round), $submission);

        $request = $this->get('request');

        if ($request->getMethod() == 'POST') {
            $form->bindRequest($request);
            if ($form->isValid()) {

                $submission = $form->getData();

                if ($submission->getId()!=$id) {
                    throw $this->createNotFoundException("Don't forge stupid updates");
                }

                $em->flush();

                return $this->redirect($this->generateUrl('admin_submission_indexr', array( 'round' => $round->getId())));
            }
        }

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

    /**
     * Shows a submission
     *
     * @param int $id Id of the submission
     *
     * @return array of template parameters
     *
     * @Route("/show/{id}", name = "admin_submission_show" )
     * @Template
     */
    public function showAction($id)
    {
        if (!is_numeric($id)) {
            throw $this->createNotFoundException("Submission not found");
        }

        $em = $this->getDoctrine()->getEntityManager();
        $repo = $this->getDoctrine()
            ->getRepository('EotvosVersenyrBundle:Submission')
            ;

        $submission = $repo->findOneById($id);

        if (!$submission) {
            throw $this->createNotFoundException("Submission not found");
        }

        return array(
            'submission' => $submission,
        );
    }

}


text:
import pytest
import yaml
from lain_sdk.yaml.validator import validate

def test_lain_yaml_validator_smoke(validation_yaml):
    source_data = yaml.load(validation_yaml)
    valid, msg = validate(source_data)
    assert valid

@pytest.mark.parametrize("data, want", [
    (
        """
appname: test
build:
  base: centos
  script:
    - echo "Success"
web:
  cmd: echo "Hello"
  memory: 128M
        """,
        True
    ),
    (
        """
appname: test
build:
  base: centos
  script:
    - echo "Success"
web:
  cmd: echo "Hello"
  memory: 2G
        """,
        True
    ),
    (
        """
appname: test
build:
  base: centos
  script:
    - echo "Success"
web:
  cmd: echo "Hello"
  memory: 128
        """,
        False
    ),
    (
        """
appname: test
build:
  base: centos
  script:
    - echo "Success"
web:
  cmd: echo "Hello"
  memory: 128a
        """,
        False
    ),
    (
        """
appname: test
build:
  base: centos
  script:
    - echo "Success"
web:
  cmd: echo "Hello"
  memory: M
        """,
        False
    ),
])
def test_memory_format(data, want):
    lain_config = yaml.safe_load(data)
    valid, msg = validate(lain_config)
    assert valid == want

redpajama_set_name: RedPajamaGithub


text:
using System;

namespace OrigoDB.Core.Modeling.Geo
{
    /// <summary>
    /// Distance between two points on the surface of the earth
    /// </summary>
    [Serializable]
    public class ArcDistance : IEquatable<ArcDistance>, IComparable<ArcDistance>
    {
        public ArcDistance(double radians)
        {
            Radians = radians;
        }

        public double ToKilometers()
        {
            return Radians * GeoPoint.EarthRadiusKm;
        }

        public double Radians { get; private set; }

        public bool Equals(ArcDistance other)
        {
            return CompareTo(other) == 0;
        }

        public int CompareTo(ArcDistance other)
        {
            return Math.Sign(Radians - other.Radians);
        }

        public override string ToString()
        {
            return ToKilometers() + " km";
        }
    }
}


text:
/* $Id: GraphicsCharacterString.java 1297404 2012-03-06 10:17:54Z vhennebert $ */

package org.apache.fop.afp.goca;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.CharacterCodingException;

import org.apache.fop.afp.fonts.CharacterSet;

/**
 * A GOCA graphics string
 */
public class GraphicsCharacterString extends AbstractGraphicsCoord {

    /** Up to 255 bytes of character data */
    protected static final int MAX_STR_LEN = 255;

    /** the string to draw */
    private final String str;

    /**
     * The character set encoding to use
     */
    private final CharacterSet charSet;

    /**
     * Constructor (absolute positioning)
     *
     * @param str the character string
     * @param x the x coordinate
     * @param y the y coordinate
     * @param charSet the character set
     */
    public GraphicsCharacterString(String str, int x, int y, CharacterSet charSet) {
        super(x, y);
        this.str = truncate(str, MAX_STR_LEN);
        this.charSet = charSet;
    }

    /** {@inheritDoc} */
    byte getOrderCode() {
        if (isRelative()) {
            return (byte)0x83;
        } else {
            return (byte)0xC3;
        }
    }

    /** {@inheritDoc} */
    public int getDataLength() {
        return super.getDataLength() + str.length();
    }

    /** {@inheritDoc} */
    public void writeToStream(OutputStream os) throws IOException {
        byte[] data = getData();
        byte[] strData = getStringAsBytes();
        System.arraycopy(strData, 0, data, 6, strData.length);
        os.write(data);
    }

    /**
     * Returns the text string as an encoded byte array
     *
     * @return the text string as an encoded byte array
     * @throws UnsupportedEncodingException, CharacterCodingException
     */
    private byte[] getStringAsBytes() throws UnsupportedEncodingException,
            CharacterCodingException {
        return charSet.encodeChars(str).getBytes();
    }

    /** {@inheritDoc} */
    public String toString() {
        return "GraphicsCharacterString{"
            + (coords != null ? "x=" + coords[0] + ", y=" + coords[1] : "")
            + "str='" + str + "'" + "}";
    }
}


text:
'use strict';

// Configuring the Articles module
angular.module('articles').run(['Menus',
	function(Menus) {
		// Set top bar menu items
		Menus.addMenuItem('topbar', 'Noveller', 'noveller', 'dropdown', '/articles(/create)?');
		Menus.addSubMenuItem('topbar', 'noveller', 'Visa alla', 'articles');
		Menus.addSubMenuItem('topbar', 'noveller', 'Skriv ny', 'articles/create');
	}
]);


text:
object Main:
    class Null
    type Optional[A] = A | Null

    val maybeInt: Optional[Int] = 1

    // simplest typeclass
    trait TC[F[_]]

    // given instances for our Optional and standard Option[_]
    given g1: TC[Optional] = ???
    given g2: TC[Option] = ???

    def summonTC[F[_], A](f: F[A])(using TC[F]): Unit = ???

    summonTC(Option(42))  // OK

    summonTC[Optional, Int](maybeInt) // OK

    summonTC(maybeInt)


text:
mapael-maps
===========

⚠ Important note : I do not maintain jQuery Mapael anymore. However, feel free to submit a pull request if you need a bugfix or a security fix. More information : *[Ending an Open Source project (Mapael)](https://www.vincentbroute.fr/blog/ending-an-open-source-project-mapael/)*.

Vector maps for [jQuery Mapael](https://github.com/neveldo/jQuery-Mapael)

Feel free to contribute to this repository by adding new maps !


text:
#ifndef DocumentLifecycleObserver_h
#define DocumentLifecycleObserver_h

#include "core/dom/Document.h"

namespace blink {

template<> void observeContext(Document*, LifecycleObserver<Document>*);
template<> void unobserveContext(Document*, LifecycleObserver<Document>*);

class DocumentLifecycleObserver : public LifecycleObserver<Document> {
public:
    explicit DocumentLifecycleObserver(Document*);
    virtual ~DocumentLifecycleObserver();
    virtual void documentWasDetached() { }
#if !ENABLE(OILPAN)
    virtual void documentWasDisposed() { }
#endif
};

} // namespace blink

#endif // DocumentLifecycleObserver_h


text:
//package org.trianacode.shiwaall.bundle;
//
//import org.jivesoftware.smack.XMPPException;
//import org.shiwa.desktop.data.description.SHIWABundle;
//import org.shiwa.desktop.data.description.bundle.BundleFile;
//import org.shiwa.desktop.data.description.core.Configuration;
//import org.shiwa.desktop.data.description.core.WorkflowImplementation;
//import org.shiwa.desktop.data.description.core.WorkflowSignature;
//import org.shiwa.desktop.data.description.resource.AggregatedResource;
//import org.shiwa.desktop.data.description.resource.ConfigurationResource;
//import org.shiwa.desktop.data.description.resource.ReferableResource;
//import org.shiwa.desktop.data.description.workflow.InputPort;
//import org.shiwa.desktop.data.description.workflow.OutputPort;
//import org.shiwa.desktop.data.transfer.WorkflowController;
//import org.shiwa.desktop.data.util.DataUtils;
//import org.shiwa.desktop.data.util.exception.SHIWADesktopIOException;
//import org.shiwa.desktop.data.util.monitors.BundleMonitor;
//import org.shiwa.desktop.gui.SHIWADesktop;
//import org.shiwa.desktop.gui.util.listener.DefaultBundleReceivedListener;
//import org.trianacode.annotation.CustomGUIComponent;
//import org.trianacode.annotation.Tool;
//import org.trianacode.enactment.logging.stampede.StampedeLog;
//import org.trianacode.error.ErrorEvent;
//import org.trianacode.error.ErrorTracker;
//import org.trianacode.gui.panels.DisplayDialog;
//import org.trianacode.shiwaall.handler.BundleUtils;
//import org.trianacode.shiwaall.utils.BrokerUtils;
//import org.trianacode.taskgraph.CableException;
//import org.trianacode.taskgraph.Node;
//import org.trianacode.taskgraph.NodeException;
//import org.trianacode.taskgraph.Task;
//import org.trianacode.taskgraph.annotation.TaskConscious;
//
//import javax.swing.*;
//import java.awt.*;
//import java.awt.event.ActionEvent;
//import java.awt.event.ActionListener;
//import java.io.File;
//import java.io.FileInputStream;
//import java.io.FileNotFoundException;
//import java.io.IOException;
//import java.nio.MappedByteBuffer;
//import java.nio.channels.FileChannel;
//import java.nio.charset.Charset;
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.List;
//import java.util.UUID;
//
////import org.shiwa.desktop.data.util.vocab.XSDDataType;
//
///**
//* Created by IntelliJ IDEA.
//* User: Ian Harvey
//* Date: 28/02/2012
//* Time: 16:54
//* To change this template use File | Settings | File Templates.
//*/
//@Tool
//public class BundleSubmit152 implements TaskConscious {
//
//    private HashMap<String, InputPort> inputPortMap;
//    private HashMap<String, OutputPort> outputPortMap;
//    private HashMap<String, Node> inputNodeMap;
//    private HashMap<String, Node> outputNodeMap;
//    private Task task;
//    private WorkflowController workflowController;
//    private ButtonGroup bundleSubmitButtonGroup;
//    private SHIWABundle shiwaBundle;
//    //    private String execBundleName;
//    private JTextField sendURLField;
//    private JTextField getURLField;
//    private JTextField ttlField;
//    private JTextField routingKeyField;
//    private int defaultTTL = 30000;
//
//    @org.trianacode.annotation.Process(gather = true, multipleOutputNodes = true)
//    public HashMap<Node, Object> process(List list) {
//        if (workflowController != null) {
//            if (task.getInputNodeCount() != inputPortMap.size()) {
//
//            } else {
//                if (list.size() > 0) {
//                    clearConfigs(workflowController.getWorkflowImplementation());
//                    Configuration config = createConfiguration(list);
//                    workflowController.getWorkflowImplementation().getAggregatedResources().add(config);
//                }
//            }
//            try {
//                BrokerUtils.prepareSubworkflow(
//                        task, UUID.randomUUID(), workflowController.getWorkflowImplementation()
//                );
//
//                File tempBundleFile = new File("testBundle.bundle");
//                DataUtils.bundle(tempBundleFile, workflowController.getWorkflowImplementation());
//
//                if (bundleSubmitButtonGroup.getSelection().getActionCommand().equals("cgiPool")) {
//                    doPool(tempBundleFile);
//                } else {
//                    return doBroker(tempBundleFile);
//                }
//            } catch (SHIWADesktopIOException e) {
//                e.printStackTrace();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//
//        }
//        return null;
//    }
//
//    private void doPool(File tempBundleFile) {
//        System.out.printf("Submitting bundle " + tempBundleFile.getAbsolutePath());
//        try {
//            fr.insalyon.creatis.shiwapool.client.Main.main(
//                    new String[]{"--submitBundle", tempBundleFile.getAbsolutePath()}
//            );
//        } catch (SHIWADesktopIOException e) {
//            e.printStackTrace();
//        } catch (XMPPException e) {
//            e.printStackTrace();
//        }
//    }
//
//    private HashMap<Node, Object> doBroker(File tempBundleFile) {
//        String execBundleName = workflowController.getWorkflowImplementation().getTitle()
//                + "-" + BrokerUtils.getTimeStamp();
//
//        String uuid = BrokerUtils.postBundle(
//                sendURLField.getText(), routingKeyField.getText(), execBundleName, tempBundleFile);
//
//        System.out.println("Sent");
//        int ttl;
//        try {
//            ttl = Integer.parseInt(ttlField.getText());
//        } catch (NumberFormatException ex) {
//            ttl = defaultTTL;
//        }
//        String key = BrokerUtils.waitForExec(getURLField.getText(), ttl, uuid, execBundleName);
//        System.out.println("Got key : " + key);
//        if (key != null) {
//            File bundle = BrokerUtils.getResultBundle(getURLField.getText(), key);
//
//            HashMap<String, ConfigurationResource> outputs = ShiwaBundleHelper152.getOutputs(bundle);
//            if (outputs != null) {
//                return compileOutputs(outputs);
//            } else {
//                return null;
//            }
//        }
//        return null;
//    }
//
//    private HashMap<Node, Object> compileOutputs(HashMap<String, ConfigurationResource> outputResources) {
//        HashMap<Node, Object> outputs = new HashMap<Node, Object>();
//        System.out.println(outputResources.size() + " output objects.");
//        for (String nodeName : outputResources.keySet()) {
//            Node node = outputNodeMap.get(nodeName);
//            ConfigurationResource resource = outputResources.get(nodeName);
//            String resourceString = resource.getValue();
//
//            if (resource.getRefType() == ConfigurationResource.RefTypes.INLINE_REF) {
//                outputs.put(node, resourceString);
//            } else if (resource.getRefType() == ConfigurationResource.RefTypes.URI_REF) {
//                outputs.put(node, resourceString);
//            } else if (resource.getRefType() == ConfigurationResource.RefTypes.FILE_REF) {
//                String tempBundleLocation = new String(resource.getBundleFile().getSystemPath());
//                System.out.println("BundleFile at node : " + node + " temp location : " + tempBundleLocation);
//                String outputString = BundleUtils.readFile(tempBundleLocation);
//                outputs.put(node, outputString);
//            }
//
//
//            System.out.println("Node " + node.getAbsoluteNodeIndex() + " named : " + nodeName
//                    + " outputs : " + outputs.get(node));
//        }
//        return outputs;
//    }
//
//
////    private HashMap<String, ConfigurationResource> getOutputs(File bundle) {
////
////        HashMap<String, ConfigurationResource> results = new HashMap<String, ConfigurationResource>();
////        try {
////            SHIWABundle shiwaBundle = new SHIWABundle(bundle);
////
////            WorkflowController workflowController = new WorkflowController(shiwaBundle);
////
////            for (Configuration configuration : workflowController.getConfigurations()) {
////                System.out.println("Config type : " + configuration.getType().getString());
////                if (configuration.getType() == Configuration.ConfigType.EXECUTION_CONFIGURATION) {
////                    System.out.println("Received bundle has an exec config");
////
////                    System.out.println(configuration.getAggregatedResources().size()
////                            + " aggregated resources");
////
////                    System.out.println("Exec config contains "
////                            + configuration.getResources().size() + " resources.");
////                    for (ConfigurationResource r : configuration.getResources()) {
////                        results.put(r.getReferableResource().getTitle(), r);
////                    }
////                    System.out.println(results.size() + " outputs found.");
////                    return results;
////                }
////            }
////        } catch (SHIWADesktopIOException e) {
////            System.out.println("Returned bundle was corrupt or null.");
////            ErrorTracker.getErrorTracker().broadcastError(
////                    new ErrorEvent(task, e, "Returned Bundle was corrupt or null")
////            );
////        }
////
////        return null;
////    }
//
//    @CustomGUIComponent
//    public Component getGUI() {
//        JPanel mainPane = new JPanel();
//        mainPane.setLayout(new BoxLayout(mainPane, BoxLayout.Y_AXIS));
//
//        JPanel bundlePanel = new JPanel(new BorderLayout());
//        JLabel locationLabel = new JLabel("Bundle : ");
//        JTextField locationField = new JTextField(20);
//        String filePath = "/Users/ian/stuff/concat-two.zip";
//        locationField.setText(filePath);
//        JButton locationButton = new JButton("Get bundle");
//        locationButton.addActionListener(new BundleParameter(mainPane, locationField));
//
//        bundlePanel.add(locationLabel, BorderLayout.WEST);
//        bundlePanel.add(locationField, BorderLayout.CENTER);
//        bundlePanel.add(locationButton, BorderLayout.EAST);
//
//        mainPane.add(bundlePanel);
//
//        final JPanel sendURLPanel = new JPanel(new BorderLayout());
//        final JLabel sendURLLabel = new JLabel("Send URL : ");
//        sendURLField = new JTextField("http://s-vmc.cs.cf.ac.uk:7025/Broker/broker");
//        sendURLPanel.add(sendURLLabel, BorderLayout.WEST);
//        sendURLPanel.add(sendURLField, BorderLayout.CENTER);
//
//        mainPane.add(sendURLPanel);
//
//        final JPanel getURLPanel = new JPanel(new BorderLayout());
//        JLabel getURLLabel = new JLabel("Results URL : ");
//        getURLField = new JTextField("http://s-vmc.cs.cf.ac.uk:7025/Broker/results");
//        getURLPanel.add(getURLLabel, BorderLayout.WEST);
//        getURLPanel.add(getURLField, BorderLayout.CENTER);
//
//        mainPane.add(getURLPanel);
//
//        final JPanel routingKeyPanel = new JPanel(new BorderLayout());
//        JLabel routingKeyLabel = new JLabel("Routing Key : ");
//        routingKeyField = new JTextField("*.triana");
//        routingKeyPanel.add(routingKeyLabel, BorderLayout.WEST);
//        routingKeyPanel.add(routingKeyField, BorderLayout.CENTER);
//
//        mainPane.add(routingKeyPanel);
//
//        JPanel ttlPanel = new JPanel(new BorderLayout());
//        JLabel ttlLabel = new JLabel("Execution wait time (ms) : ");
//        ttlField = new JTextField("" + defaultTTL);
//        ttlPanel.add(ttlLabel, BorderLayout.WEST);
//        ttlPanel.add(ttlField, BorderLayout.CENTER);
//
//        mainPane.add(ttlPanel);
//
//        JPanel sendToPanel = new JPanel();
//        sendToPanel.setLayout(new BoxLayout(sendToPanel, BoxLayout.Y_AXIS));
//        bundleSubmitButtonGroup = new ButtonGroup();
//
//        final JRadioButton cgiPoolRadio = new JRadioButton("CGI Pool");
//        final JRadioButton webServerRadio = new JRadioButton("Web server");
//
//        ActionListener radioListener = new ActionListener() {
//            @Override
//            public void actionPerformed(ActionEvent actionEvent) {
//                JRadioButton radioButton = (JRadioButton) actionEvent.getSource();
//                if (radioButton == webServerRadio) {
//                    if (radioButton.isSelected()) {
//                        setEnabling(sendURLPanel, true);
//                        setEnabling(getURLPanel, true);
//                        setEnabling(routingKeyPanel, true);
//                    }
//                }
//                if (radioButton == cgiPoolRadio) {
//                    if (radioButton.isSelected()) {
//                        setEnabling(sendURLPanel, false);
//                        setEnabling(getURLPanel, false);
//                        setEnabling(routingKeyPanel, false);
//                    }
//                }
//            }
//        };
//
//        cgiPoolRadio.setActionCommand("cgiPool");
//        cgiPoolRadio.addActionListener(radioListener);
//
//        webServerRadio.setSelected(true);
//        webServerRadio.setActionCommand("webServer");
//        webServerRadio.addActionListener(radioListener);
//
//
//        bundleSubmitButtonGroup.add(cgiPoolRadio);
//        bundleSubmitButtonGroup.add(webServerRadio);
//        sendToPanel.add(cgiPoolRadio);
//        sendToPanel.add(webServerRadio);
//
//        mainPane.add(sendToPanel);
//
//        JButton viewBundle = new JButton("View Bundle");
//        viewBundle.addActionListener(new ActionListener() {
//            @Override
//            public void actionPerformed(ActionEvent actionEvent) {
//                if (shiwaBundle != null) {
//                    SHIWADesktop shiwaDesktop = new SHIWADesktop(SHIWADesktop.ButtonOption.SHOW_TOOLBAR);
//                    try {
//                        shiwaDesktop.openBundle(shiwaBundle);
//                        new DisplayDialog(shiwaDesktop.getPanel(), "Shiwa Desktop");
//                    } catch (SHIWADesktopIOException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//        });
//        mainPane.add(viewBundle);
//
//        return mainPane;
//    }
//
//    private void setEnabling(Container parent, boolean enabled) {
//        for (Component component : parent.getComponents()) {
//            if (component instanceof Container) {
//                setEnabling((Container) component, enabled);
//            }
//            component.setEnabled(enabled);
//        }
//    }
//
//
//    @Override
//    public void setTask(Task task) {
//        this.task = task;
//        task.setParameter(StampedeLog.STAMPEDE_TASK_TYPE, StampedeLog.JobType.dax.desc);
//    }
//
//
//    private Configuration createConfiguration(List list) {
//        int inputObjectNo = 0;
//        Configuration config = new Configuration(Configuration.ConfigType.DATA_CONFIGURATION);
//
//        for (ReferableResource referableResource : workflowController.getWorkflowImplementation().getSignature().getPorts()) {
//            if (referableResource instanceof InputPort) {
//                ConfigurationResource configurationResource = new ConfigurationResource(referableResource);
//                //TODO serialize
//
//                Object inputObject = list.get(inputObjectNo);
//
//                if (inputObject instanceof File) {
//                    try {
//                        configurationResource.setRefType(ConfigurationResource.RefTypes.FILE_REF);
//                        BundleFile bf = DataUtils.createBundleFile((File) inputObject, config.getId() + "/");
//                        bf.setType(BundleFile.FileType.INPUT_FILE);
//                        config.getBundleFiles().add(bf);
//                        configurationResource.setBundleFile(bf);
//                    } catch (SHIWADesktopIOException e) {
//                        e.printStackTrace();
//                    }
//                } else {
//                    configurationResource.setValue(inputObject.toString());
//                    configurationResource.setRefType(ConfigurationResource.RefTypes.INLINE_REF);
//                }
//                inputObjectNo++;
//                config.addResourceRef(configurationResource);
//            }
//        }
//        return config;
//    }
//
//    private void clearConfigs(WorkflowImplementation workflowImplementation) {
//        ArrayList<Configuration> dataConfigs = new ArrayList<Configuration>();
//        for (AggregatedResource resource : workflowImplementation.getAggregatedResources()) {
//            if (resource instanceof Configuration) {
//                if (((Configuration) resource).getType() == Configuration.ConfigType.DATA_CONFIGURATION) {
//                    dataConfigs.add((Configuration) resource);
//                }
//            }
//        }
//        for (Configuration configuration : dataConfigs) {
//            workflowImplementation.getAggregatedResources().remove(configuration);
//        }
//    }
//
//    private void init(SHIWABundle shiwaBundle) {
//        workflowController = null;
//        try {
//            workflowController = new WorkflowController(shiwaBundle);
//            System.out.println("Loaded " + workflowController.getWorkflowImplementation().getTitle());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        inputPortMap = new HashMap<String, InputPort>();
//        ArrayList<String> inputDataTypes = new ArrayList<String>();
//        outputPortMap = new HashMap<String, OutputPort>();
//        ArrayList<String> outputDataTypes = new ArrayList<String>();
//        WorkflowSignature signature = workflowController.getWorkflowImplementation().getSignature();
//        for (ReferableResource referableResource : signature.getPorts()) {
//            if (referableResource instanceof InputPort) {
//                InputPort inputPort = (InputPort) referableResource;
////                Class dataClass = XSDDataType.getClass(inputPort.getDataType());
////                if (dataClass != null) {
////                    inputDataTypes.add(dataClass.getCanonicalName());
////                }
//                inputDataTypes.add(inputPort.getDataType());
//                inputPortMap.put(referableResource.getTitle(), inputPort);
//            }
//            if (referableResource instanceof OutputPort) {
//                OutputPort outputPort = (OutputPort) referableResource;
////                Class dataClass = XSDDataType.getClass(outputPort.getDataType());
////                if (dataClass != null) {
////                    outputDataTypes.add(dataClass.getCanonicalName());
////                }
//                outputDataTypes.add(outputPort.getDataType());
//                outputPortMap.put(referableResource.getTitle(), outputPort);
//            }
//        }
//
//        String[] inputTypes = new String[inputDataTypes.size()];
//        inputDataTypes.toArray(inputTypes);
//        task.setDataInputTypes(inputTypes);
//
//        String[] outputTypes = new String[outputDataTypes.size()];
//        outputDataTypes.toArray(outputTypes);
//        task.setDataOutputTypes(outputTypes);
//
//        System.out.println("Bundle sig has " + inputPortMap.size() +
//                " inputs. Current input nodes " + task.getInputNodeCount() +
//                " Bundle sig has " + outputPortMap.size() +
//                " outputs. Current output nodes " + task.getOutputNodeCount()
//        );
//
//        if (inputPortMap.size() < task.getInputNodeCount()) {
//            removeNodes(inputPortMap.size(), true);
//        }
//        if (inputPortMap.size() > task.getInputNodeCount()) {
//            try {
//                addNodes(inputPortMap.size(), true);
//            } catch (NodeException e) {
//                e.printStackTrace();
//            }
//        }
//
//        inputNodeMap = new HashMap<String, Node>();
//        String[] inputPorts = new String[inputPortMap.size()];
//        inputPortMap.keySet().toArray(inputPorts);
//        for (int i = 0; i < inputPorts.length; i++) {
//            String name = inputPorts[i];
//            inputNodeMap.put(name, task.getInputNode(i));
//        }
//
//        if (outputPortMap.size() < task.getOutputNodeCount()) {
//            removeNodes(outputPortMap.size(), false);
//        }
//        if (outputPortMap.size() > task.getOutputNodeCount()) {
//            try {
//                addNodes(outputPortMap.size(), false);
//            } catch (NodeException e) {
//                e.printStackTrace();
//            }
//        }
//        task.setDataInputTypes(new String[]{"java.lang.Object"});
//        task.setDataOutputTypes(new String[]{"java.lang.Object"});
//
//        outputNodeMap = new HashMap<String, Node>();
//        String[] outputPorts = new String[outputPortMap.size()];
//        outputPortMap.keySet().toArray(outputPorts);
//        for (int i = 0; i < outputPorts.length; i++) {
//            String name = outputPorts[i];
//            outputNodeMap.put(name, task.getOutputNode(i));
//        }
//    }
//
//    private void addNodes(int size, boolean input) throws NodeException {
//        if (input) {
//            while (task.getInputNodeCount() < size) {
//                task.addDataInputNode();
//            }
//        } else {
//            while (task.getOutputNodeCount() < size) {
//                task.addDataOutputNode();
//            }
//        }
//    }
//
//    private void removeNodes(int size, boolean input) {
//        if (input) {
//            while (task.getInputNodeCount() > size) {
//                Node node = task.getInputNode(task.getDataInputNodeCount() - 1);
//                try {
//                    task.getParent().disconnect(node.getCable());
//                } catch (CableException ignored) {
//                }
//                task.removeDataInputNode(node);
//            }
//        } else {
//            while (task.getOutputNodeCount() > size) {
//                Node node = task.getOutputNode(task.getDataOutputNodeCount() - 1);
//                try {
//                    task.getParent().disconnect(node.getCable());
//                } catch (CableException ignored) {
//                }
//                task.removeDataOutputNode(node);
//            }
//        }
//    }
//
//    private class BundleParameter extends DefaultBundleReceivedListener implements ActionListener {
//        private JPanel mainPane;
//        private JTextField locationField;
//
//        public BundleParameter(JPanel mainPane, JTextField locationField) {
//            this.mainPane = mainPane;
//            this.locationField = locationField;
//        }
//
//        @Override
//        public void actionPerformed(ActionEvent actionEvent) {
//            BundleMonitor.addListener(this);
//            open(mainPane);
//        }
//
//        @Override
//        public void acceptBundleFile(File file) {
//            if (file != null) {
//                try {
//                    shiwaBundle = new SHIWABundle(file);
//                    locationField.setText(file.getAbsolutePath());
//                    init(shiwaBundle);
//                } catch (SHIWADesktopIOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//
//        @Override
//        public void dispose() {
//        }
//    }
//
//
//}


text:
package debop4s.data.orm.config.servers

import java.util.Properties

import debop4s.data.orm.jpa.spring.AbstractJpaPostgreSqlConfiguration
import debop4s.data.orm.mapping.ScalaEmployee
import org.hibernate.cache.rediscala.SingletonRedisRegionFactory
import org.hibernate.cfg.AvailableSettings._
import org.springframework.context.annotation.Configuration
import org.springframework.data.jpa.repository.config.EnableJpaRepositories
import org.springframework.transaction.annotation.EnableTransactionManagement

/**
 * JpaPostgreSqlConfiguration
 * @author Sunghyouk Bae
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackageClasses = Array(classOf[ScalaEmployee]))
class JpaPostgreSqlConfiguration extends AbstractJpaPostgreSqlConfiguration {

  override def getMappedPackageNames: Array[String] =
    Array(classOf[ScalaEmployee].getPackage.getName)

  override def jpaProperties: Properties = {
    val props = super.jpaProperties

    props.setProperty(HBM2DDL_AUTO, "create")
    props.setProperty(SHOW_SQL, "true")

    // add second cache provider using redis
    props.setProperty(USE_SECOND_LEVEL_CACHE, "true")
    props.setProperty(USE_QUERY_CACHE, "true")
    props.setProperty(CACHE_REGION_PREFIX, "")
    props.setProperty(CACHE_REGION_FACTORY, classOf[SingletonRedisRegionFactory].getName)
    props.setProperty(CACHE_PROVIDER_CONFIG, "hibernate-redis.conf")

    props
  }
}


text:
/* eslint-disable */
/////////////////////////////////////////////////////////////////////////////////////////
//                                                                                //
// !!! DO NOT EDIT THIS FILE !!!                                                       //
//                                                                                //
// This file is auto-generated by scripts/generate-web-api-types.sh in the repository. //
// Please refer to the script code to learn how to update the source data.             //
//                                                                                //
/////////////////////////////////////////////////////////////////////////////////////////

import { WebAPICallResult } from '../WebClient';
export type AdminUsergroupsListChannelsResponse = WebAPICallResult & {
  channels?: Channel[];
  error?:    string;
  needed?:   string;
  ok?:       boolean;
  provided?: string;
};

export interface Channel {
  context_team_id?:            string;
  created?:                    number;
  creator?:                    string;
  date_connected?:             number;
  enterprise_id?:              string;
  id?:                         string;
  is_archived?:                boolean;
  is_channel?:                 boolean;
  is_ext_shared?:              boolean;
  is_general?:                 boolean;
  is_global_shared?:           boolean;
  is_group?:                   boolean;
  is_im?:                      boolean;
  is_member?:                  boolean;
  is_moved?:                   number;
  is_mpim?:                    boolean;
  is_org_default?:             boolean;
  is_org_mandatory?:           boolean;
  is_org_shared?:              boolean;
  is_pending_ext_shared?:      boolean;
  is_private?:                 boolean;
  is_shared?:                  boolean;
  name?:                       string;
  name_normalized?:            string;
  pending_connected_team_ids?: string[];
  pending_shared?:             string[];
  previous_names?:             string[];
  purpose?:                    Purpose;
  topic?:                      Purpose;
  unlinked?:                   number;
}

export interface Purpose {
  creator?:  string;
  last_set?: number;
  value?:    string;
}


text:
namespace fj {
    int ImportCommand::execute(std::string arg) {
        if (arg == "") {
            std::cout << "Syntax: import FILENAME" << std::endl;
            return -1;
        }
        if (!std::ifstream(arg).good()) {
            std::cout << "import: Failed to find or read file `"
                << arg << "'" << std::endl;
            return -1;
        }
        return import(arg);
    }

    int ImportCommand::import(std::string fileName) {
        std::ifstream stream(fileName);
        try {
            ParsedContext parsedContext;
            const std::string input((std::istreambuf_iterator< char >(stream) ),
                       (std::istreambuf_iterator< char >()));
            bool status = parseContent(parsedContext, input, fileName);

            if (!status) {
                std::cout << "import: Hit unknown parse error" << std::endl;
                return -2;
            }

            ContextBuilder builder;
            builder.buildAST(parsedContext);
            mode->setClassTable(builder.getClassTable());
        }
        catch (const pegtl::parse_error& e) {
            std::cout << "import: " << e.what() << std::endl;
        }
        return 0;
    }
}


text:
/**
 * Module dependencies.
 */
var express = require('express');
//var multer = require('multer');
var http = require('http');
var path = require('path');
var handlebars = require('express3-handlebars');
var mongoose = require('mongoose');
var formidable = require('formidable');
var fs = require('fs-extra');
var qt = require('quickthumb');
var hash = require('./pass').hash;

var index = require('./routes/index');
var page_A = require('./routes/page_A');
var page_B = require('./routes/page_B');

var bucket = require('./routes/bucket');
var friend = require('./routes/friend');
var adventure = require('./routes/adventure');
var login = require('./routes/login');
var start_adventure = require('./routes/start_adventure');

var createlogin = require('./routes/createlogin');
var add = require('./routes/add');
var util = require('util');
var app = express();
var bodyParser = require('body-parser');

app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', handlebars());
app.set('view engine', 'handlebars');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('Intro HCI secret key'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());

// development only
if ('development' == app.get('env')) {
    app.use(express.errorHandler());
}
//configuration
//mongoose.connect("mongodb://teamop:teamop170@olympia.modulusmongo.net:27017/quB6uvyz");
mongoose.connect("mongodb://teamop:teamop170@ds113680.mlab.com:13680/useraccount");
var UserSchema = new mongoose.Schema({
    username: String,
    password: String,
    salt: String,
    hash: String
});

var User = mongoose.model('users', UserSchema);

app.use(express.cookieParser('Authentication Tutorial '));
    app.use(express.session());

// Add routes here
app.get('/', index.view);
app.get('/page_A', page_A.viewA);
app.get('/page_B', page_B.viewB);
app.get('/feed', index.addToFeed);
app.get('/feed_A', page_A.addToFeedA);
app.get('/feed_B', page_B.addToFeedB);

app.get('/bucket', bucket.view);
app.get('/buckets', bucket.addToBucket);

app.get('/friend', friend.view);
//app.get('/map', map.view);
app.get('/adventure', adventure.view);
//app.get('/share', share.view);
app.get('/login', login.view);
app.get('/createlogin', createlogin.view);

app.get('/start_adventure', start_adventure.view);
app.get('/adventures', start_adventure.addToAdventure);
//app.get('/add', add.addAdventure);
app.get("/deleteFrom", start_adventure.delete);

app.use(qt.static(__dirname + '/'));
app.post('/upload', add.upload);
app.get('/upload', friend.view);

///////////////////////
app.use(function (req, res, next) {
    var err = req.session.error,
        msg = req.session.success;
    delete req.session.error;
    delete req.session.success;
    res.locals.message = '';
    if (err) res.locals.message = '
' + err + '
';
    if (msg) res.locals.message = '
' + msg + '
';
    next();
});

app.post("/createlogin", userExist, function (req, res) {
    var password = req.body.password;
    var username = req.body.username;

    hash(password, function (err, salt, hash) {
        if (err) throw err;
        var user = new User({
            username: username,
            salt: salt,
            hash: hash,
        }).save(function (err, newUser) {
            if (err) throw err;
            authenticate(newUser.username, password, function(err, user){
                if(user){
                    req.session.regenerate(function(){
                        req.session.user = user;
                        req.session.success = 'Authenticated as ' + user.username + ' click to logout. ' + ' You may now access /restricted.';
                        res.redirect('/');
                    });
                }
            });
        });
    });
});

app.post("/login", function (req, res) {
    authenticate(req.body.username, req.body.password, function (err, user) {

        if (user) {

            req.session.regenerate(function () {
                //  console.log(user);
                req.session.user = user; console.log('id: %s', user._id);
                req.session.success = 'Authenticated as ' + user.username + ' click to logout. ' + ' You may now access /restricted.';
                res.redirect('/');
            });
        } else {
            req.session.error = 'Authentication failed, please check your ' + ' username and password.';
            res.redirect('/login');
        }
    });
});

app.get('/logout', function (req, res) {
    req.session.destroy(function () {
        res.redirect('/');
    });
});

app.get('/profile', requiredAuthentication, function (req, res) {
    res.send('Profile page of '+ req.session.user.username +'
'+' click to logout');
});

/*
Helper Functions
*/
function authenticate(name, pass, fn) {
    if (!module.parent) console.log('authenticating %s:%s', name, pass);

    User.findOne({
        username: name
    },

    function (err, user) {
        if (user) {
            if (err) return fn(new Error('cannot find user'));
            hash(pass, user.salt, function (err, hash) {
                if (err) return fn(err);
                if (hash == user.hash) return fn(null, user);
                fn(new Error('invalid password'));
            });
        } else {
            return fn(new Error('cannot find user'));
        }
    });
}

function requiredAuthentication(req, res, next) {
    if (req.session.user) {
        next();
    } else {
        req.session.error = 'Access denied!';
        res.redirect('/login');
    }
}

function userExist(req, res, next) {
    User.count({
        username: req.body.username
    }, function (err, count) {
        if (count === 0) {
            next();
        } else {
            req.session.error = "User Exist"
            res.redirect("/createlogin");
        }
    });
}

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

http.createServer(app).listen(app.get('port'), function() {
    console.log('Express server listening on port ' + app.get('port'));
});


text:
package com.google.dataflow.sample.timeseriesflow.metrics.core.typeone;

import com.google.common.annotations.VisibleForTesting;
import com.google.dataflow.sample.timeseriesflow.TimeSeriesData.TSAccum;
import com.google.dataflow.sample.timeseriesflow.TimeSeriesData.TSDataPoint;
import com.google.dataflow.sample.timeseriesflow.combiners.BTypeOne;
import com.google.dataflow.sample.timeseriesflow.common.CommonUtils;
import com.google.dataflow.sample.timeseriesflow.datamap.AccumCoreNumericBuilder;
import org.apache.beam.sdk.annotations.Experimental;

@VisibleForTesting
@Experimental
/** This is a dummy class used as a test artifact only. */
public class TestSum extends BTypeOne {
  @Override
  public TSAccum addInput(TSAccum accumulator, TSDataPoint dataPoint) {
    AccumCoreNumericBuilder coreNumeric = new AccumCoreNumericBuilder(accumulator);
    coreNumeric.setSum(
        CommonUtils.sumNumericDataNullAsZero(coreNumeric.getSumOrNull(), dataPoint.getData()));
    return coreNumeric.build();
  }

  @Override
  public TSAccum mergeDataAccums(TSAccum a, TSAccum b) {
    AccumCoreNumericBuilder aBuilder = new AccumCoreNumericBuilder(a);
    AccumCoreNumericBuilder bBuilder = new AccumCoreNumericBuilder(b);
    aBuilder.setSum(
        CommonUtils.sumNumericDataNullAsZero(aBuilder.getSumOrNull(), bBuilder.getSumOrNull()));

    return aBuilder.build();
  }
}


text:
#ifndef PHPCXX_VECTOR_H_
#define PHPCXX_VECTOR_H_

#include "phpcxx.h"

#include <vector>
#include "emallocallocator.h"

namespace phpcxx {

/**
 * @brief `std::vector` with `EMallocAllocator`
 * @see @ref EMallocAllocator
 */
template<typename T> using vector = std::vector<T, EMallocAllocator<T> >;

}

#endif /* PHPCXX_VECTOR_H */


text:
package org.apache.cassandra.config;

import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

import junit.framework.Assert;

import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.apache.cassandra.OrderedJUnit4ClassRunner;
import org.apache.cassandra.SchemaLoader;
import org.apache.cassandra.db.Keyspace;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.exceptions.InvalidRequestException;
import org.apache.cassandra.gms.Gossiper;
import org.apache.cassandra.locator.SimpleStrategy;
import org.apache.cassandra.service.MigrationManager;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;

@RunWith(OrderedJUnit4ClassRunner.class)
public class DatabaseDescriptorTest
{
    @Test
    public void testCFMetaDataSerialization() throws ConfigurationException, InvalidRequestException
    {
        // test serialization of all defined test CFs.
        for (String keyspaceName : Schema.instance.getNonSystemKeyspaces())
        {
            for (CFMetaData cfm : Schema.instance.getKeyspaceMetaData(keyspaceName).values())
            {
                CFMetaData cfmDupe = CFMetaData.fromThrift(cfm.toThrift());
                assertNotNull(cfmDupe);
                assertEquals(cfm, cfmDupe);
            }
        }
    }

    @Test
    public void testKSMetaDataSerialization() throws ConfigurationException
    {
        for (KSMetaData ksm : Schema.instance.getKeyspaceDefinitions())
        {
            // Not testing round-trip on the KsDef via serDe() because maps
            KSMetaData ksmDupe = KSMetaData.fromThrift(ksm.toThrift());
            assertNotNull(ksmDupe);
            assertEquals(ksm, ksmDupe);
        }
    }

    // this came as a result of CASSANDRA-995
    @Test
    public void testTransKsMigration() throws ConfigurationException
    {
        SchemaLoader.cleanupAndLeaveDirs();
        DatabaseDescriptor.loadSchemas();
        assertEquals(0, Schema.instance.getNonSystemKeyspaces().size());

        Gossiper.instance.start((int)(System.currentTimeMillis() / 1000));
        Keyspace.setInitialized();

        try
        {
            // add a few.
            MigrationManager.announceNewKeyspace(KSMetaData.testMetadata("ks0", SimpleStrategy.class, KSMetaData.optsWithRF(3)));
            MigrationManager.announceNewKeyspace(KSMetaData.testMetadata("ks1", SimpleStrategy.class, KSMetaData.optsWithRF(3)));

            assertNotNull(Schema.instance.getKSMetaData("ks0"));
            assertNotNull(Schema.instance.getKSMetaData("ks1"));

            Schema.instance.clearKeyspaceDefinition(Schema.instance.getKSMetaData("ks0"));
            Schema.instance.clearKeyspaceDefinition(Schema.instance.getKSMetaData("ks1"));

            assertNull(Schema.instance.getKSMetaData("ks0"));
            assertNull(Schema.instance.getKSMetaData("ks1"));

            DatabaseDescriptor.loadSchemas();

            assertNotNull(Schema.instance.getKSMetaData("ks0"));
            assertNotNull(Schema.instance.getKSMetaData("ks1"));
        }
        finally
        {
            Gossiper.instance.stop();
        }
    }

    @Test
    public void testConfigurationLoader() throws Exception
    {
        // By default, we should load from the yaml
        Config config = DatabaseDescriptor.loadConfig();
        assertEquals("Test Cluster", config.cluster_name);
        Keyspace.setInitialized();

        // Now try custom loader
        ConfigurationLoader testLoader = new TestLoader();
        System.setProperty("cassandra.config.loader", testLoader.getClass().getName());

        config = DatabaseDescriptor.loadConfig();
        assertEquals("ConfigurationLoader Test", config.cluster_name);
    }

    public static class TestLoader implements ConfigurationLoader
    {
        public Config loadConfig() throws ConfigurationException
        {
            Config testConfig = new Config();
            testConfig.cluster_name = "ConfigurationLoader Test";;
            return testConfig;
        }
    }

    static NetworkInterface suitableInterface = null;
    static boolean hasIPv4andIPv6 = false;

    /*
     * Server only accepts interfaces by name if they have a single address
     * OS X seems to always have an ipv4 and ipv6 address on all interfaces which means some tests fail
     * if not checked for and skipped
     */
    @BeforeClass
    public static void selectSuitableInterface() throws Exception {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while(interfaces.hasMoreElements()) {
            NetworkInterface intf = interfaces.nextElement();

            System.out.println("Evaluating " + intf.getName());

            if (intf.isLoopback()) {
                suitableInterface = intf;

                boolean hasIPv4 = false;
                boolean hasIPv6 = false;
                Enumeration<InetAddress> addresses = suitableInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    if (addresses.nextElement().getClass() == Inet6Address.class)
                        hasIPv6 = true;
                    else
                        hasIPv4 = true;
                }
                hasIPv4andIPv6 = hasIPv4 && hasIPv6;
                return;
            }
        }
    }

    @Test
    public void testRpcInterface() throws Exception
    {
        Config testConfig = DatabaseDescriptor.loadConfig();
        testConfig.rpc_interface = suitableInterface.getName();
        testConfig.rpc_address = null;
        DatabaseDescriptor.applyAddressConfig(testConfig);

        /*
         * Confirm ability to select between IPv4 and IPv6
         */
        if (hasIPv4andIPv6)
        {
            testConfig = DatabaseDescriptor.loadConfig();
            testConfig.rpc_interface = suitableInterface.getName();
            testConfig.rpc_address = null;
            testConfig.rpc_interface_prefer_ipv6 = true;
            DatabaseDescriptor.applyAddressConfig(testConfig);

            assertEquals(DatabaseDescriptor.getRpcAddress().getClass(), Inet6Address.class);

            testConfig = DatabaseDescriptor.loadConfig();
            testConfig.rpc_interface = suitableInterface.getName();
            testConfig.rpc_address = null;
            testConfig.rpc_interface_prefer_ipv6 = false;
            DatabaseDescriptor.applyAddressConfig(testConfig);

            assertEquals(DatabaseDescriptor.getRpcAddress().getClass(), Inet4Address.class);
        }
        else
        {
            /*
             * Confirm first address of interface is selected
             */
            assertEquals(DatabaseDescriptor.getRpcAddress(), suitableInterface.getInetAddresses().nextElement());
        }
    }

    @Test
    public void testListenInterface() throws Exception
    {
        Config testConfig = DatabaseDescriptor.loadConfig();
        testConfig.listen_interface = suitableInterface.getName();
        testConfig.listen_address = null;
        DatabaseDescriptor.applyAddressConfig(testConfig);

        /*
         * Confirm ability to select between IPv4 and IPv6
         */
        if (hasIPv4andIPv6)
        {
            testConfig = DatabaseDescriptor.loadConfig();
            testConfig.listen_interface = suitableInterface.getName();
            testConfig.listen_address = null;
            testConfig.listen_interface_prefer_ipv6 = true;
            DatabaseDescriptor.applyAddressConfig(testConfig);

            assertEquals(DatabaseDescriptor.getListenAddress().getClass(), Inet6Address.class);

            testConfig = DatabaseDescriptor.loadConfig();
            testConfig.listen_interface = suitableInterface.getName();
            testConfig.listen_address = null;
            testConfig.listen_interface_prefer_ipv6 = false;
            DatabaseDescriptor.applyAddressConfig(testConfig);

            assertEquals(DatabaseDescriptor.getListenAddress().getClass(), Inet4Address.class);
        }
        else
        {
            /*
             * Confirm first address of interface is selected
             */
            assertEquals(DatabaseDescriptor.getRpcAddress(), suitableInterface.getInetAddresses().nextElement());
        }
    }

    @Test
    public void testListenAddress() throws Exception
    {
        Config testConfig = DatabaseDescriptor.loadConfig();
        testConfig.listen_address = suitableInterface.getInterfaceAddresses().get(0).getAddress().getHostAddress();
        testConfig.listen_interface = null;
        DatabaseDescriptor.applyAddressConfig(testConfig);
    }

    @Test
    public void testRpcAddress() throws Exception
    {
        Config testConfig = DatabaseDescriptor.loadConfig();
        testConfig.rpc_address = suitableInterface.getInterfaceAddresses().get(0).getAddress().getHostAddress();
        testConfig.rpc_interface = null;
        DatabaseDescriptor.applyAddressConfig(testConfig);

    }
}


text:
<?php

namespace Joomla\Event;

use InvalidArgumentException;

/**
 * Default Event class.
 *
 * @since  1.0
 */
class Event extends AbstractEvent
{
	/**
	 * Add an event argument, only if it is not existing.
	 *
	 * @param   string  $name   The argument name.
	 * @param   mixed   $value  The argument value.
	 *
	 * @return  Event  This method is chainable.
	 *
	 * @since   1.0
	 */
	public function addArgument($name, $value)
	{
		if (!isset($this->arguments[$name]))
		{
			$this->arguments[$name] = $value;
		}

		return $this;
	}

	/**
	 * Set the value of an event argument.
	 * If the argument already exists, it will be overridden.
	 *
	 * @param   string  $name   The argument name.
	 * @param   mixed   $value  The argument value.
	 *
	 * @return  Event  This method is chainable.
	 *
	 * @since   1.0
	 */
	public function setArgument($name, $value)
	{
		$this->arguments[$name] = $value;

		return $this;
	}

	/**
	 * Remove an event argument.
	 *
	 * @param   string  $name  The argument name.
	 *
	 * @return  mixed  The old argument value or null if it is not existing.
	 *
	 * @since   1.0
	 */
	public function removeArgument($name)
	{
		$return = null;

		if (isset($this->arguments[$name]))
		{
			$return = $this->arguments[$name];
			unset($this->arguments[$name]);
		}

		return $return;
	}

	/**
	 * Clear all event arguments.
	 *
	 * @return  array  The old arguments.
	 *
	 * @since   1.0
	 */
	public function clearArguments()
	{
		$arguments = $this->arguments;
		$this->arguments = array();

		return $arguments;
	}

	/**
	 * Stop the event propagation.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function stop()
	{
		$this->stopped = true;
	}

	/**
	 * Set the value of an event argument.
	 *
	 * @param   string  $name   The argument name.
	 * @param   mixed   $value  The argument value.
	 *
	 * @return  void
	 *
	 * @throws  InvalidArgumentException  If the argument name is null.
	 *
	 * @since   1.0
	 */
	public function offsetSet($name, $value)
	{
		if (is_null($name))
		{
			throw new InvalidArgumentException('The argument name cannot be null.');
		}

		$this->setArgument($name, $value);
	}

	/**
	 * Remove an event argument.
	 *
	 * @param   string  $name  The argument name.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function offsetUnset($name)
	{
		$this->removeArgument($name);
	}
}


text:
class CommandUpdater;
class LocationBarView;
class OmniboxEditController;
class OmniboxView;
class OmniboxViewViews;
class OmniboxViewWin;
class Profile;
class ToolbarModel;

namespace gfx {
class Font;
}

namespace views {
class View;
}

// Return |view| as an OmniboxViewViews, or NULL if it is of a different type.
OmniboxViewViews* GetOmniboxViewViews(OmniboxView* view);

// Return |view| as an OmniboxViewWin, or NULL if it is of a different type.
OmniboxViewWin* GetOmniboxViewWin(OmniboxView* view);

// Creates an OmniboxView of the appropriate type; Views or Win.
OmniboxView* CreateOmniboxView(OmniboxEditController* controller,
                               ToolbarModel* toolbar_model,
                               Profile* profile,
                               CommandUpdater* command_updater,
                               bool popup_window_mode,
                               LocationBarView* location_bar,
                               const gfx::Font& font,
                               int font_y_offset);

#endif  // CHROME_BROWSER_UI_VIEWS_OMNIBOX_OMNIBOX_VIEWS_H_


text:
<?php

namespace PHPExiftool\Driver\Tag\Nikon;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class LensIDNumber extends AbstractTag
{

    protected $Id = 'mixed';

    protected $Name = 'LensIDNumber';

    protected $FullName = 'mixed';

    protected $GroupName = 'Nikon';

    protected $g0 = 'MakerNotes';

    protected $g1 = 'Nikon';

    protected $g2 = 'Camera';

    protected $Type = 'int8u';

    protected $Writable = true;

    protected $Description = 'Lens ID Number';

    protected $flag_Permanent = true;

}


text:
/* -*-  Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2011, 2012 Centre Tecnologic de Telecomunicacions de Catalunya (CTTC)
 * Copyright (c) 2013 Budiarto Herman
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Original work authors (from lte-enb-rrc.cc):
 * - Nicola Baldo <nbaldo@cttc.es>
 * - Marco Miozzo <mmiozzo@cttc.es>
 * - Manuel Requena <manuel.requena@cttc.es>
 *
 * Converted to handover algorithm interface by:
 * - Budiarto Herman <budiarto.herman@magister.fi>
 */

#ifndef A2_A4_RSRQ_HANDOVER_ALGORITHM_H
#define A2_A4_RSRQ_HANDOVER_ALGORITHM_H

#include <ns3/lte-handover-algorithm.h>
#include <ns3/lte-handover-management-sap.h>
#include <ns3/lte-rrc-sap.h>
#include <ns3/simple-ref-count.h>
#include <ns3/ptr.h>
#include <map>

namespace ns3 {

/**
 * \brief Handover algorithm implementation based on RSRQ measurements, Event
 *        A2 and Event A4.
 *
 * Handover decision made by this algorithm is primarily based on Event A2
 * measurements (serving cell's RSRQ becomes worse than threshold). When the
 * event is triggered, the first condition of handover is fulfilled.
 *
 * Event A4 measurements (neighbour cell's RSRQ becomes better than threshold)
 * are used to detect neighbouring cells and their respective RSRQ. When a
 * neighbouring cell's RSRQ is higher than the serving cell's RSRQ by a certain
 * offset, then the second condition of handover is fulfilled.
 *
 * When the first and second conditions above are fulfilled, the algorithm
 * informs the eNodeB RRC to trigger a handover.
 *
 * The threshold for Event A2 can be configured in the `ServingCellThreshold`
 * attribute. The offset used in the second condition can also be configured by
 * setting the `NeighbourCellOffset` attribute.
 *
 * The following code snippet is an example of using and configuring the
 * handover algorithm in a simulation program:
 *
 *     Ptr<LteHelper> lteHelper = CreateObject<LteHelper> ();
 *
 *     NodeContainer enbNodes;
 *     // configure the nodes here...
 *
 *     lteHelper->SetHandoverAlgorithmType ("ns3::A2A4RsrqHandoverAlgorithm");
 *     lteHelper->SetHandoverAlgorithmAttribute ("ServingCellThreshold",
 *                                               UintegerValue (30));
 *     lteHelper->SetHandoverAlgorithmAttribute ("NeighbourCellOffset",
 *                                               UintegerValue (1));
 *     NetDeviceContainer enbLteDevs = lteHelper->InstallEnbDevice (enbNodes);
 *
 * \note Setting the handover algorithm type and attributes after the call to
 *       LteHelper::InstallEnbDevice does not have any effect to the devices
 *       that have already been installed.
 */
class A2A4RsrqHandoverAlgorithm : public LteHandoverAlgorithm
{
public:
  /// Creates an A2-A4-RSRQ handover algorithm instance.
  A2A4RsrqHandoverAlgorithm ();

  virtual ~A2A4RsrqHandoverAlgorithm ();

  // inherited from Object
  static TypeId GetTypeId ();

  // inherited from LteHandoverAlgorithm
  virtual void SetLteHandoverManagementSapUser (LteHandoverManagementSapUser* s);
  virtual LteHandoverManagementSapProvider* GetLteHandoverManagementSapProvider ();

  // let the forwarder class access the protected and private members
  friend class MemberLteHandoverManagementSapProvider<A2A4RsrqHandoverAlgorithm>;

protected:
  // inherited from Object
  virtual void DoInitialize ();
  virtual void DoDispose ();

  // inherited from LteHandoverAlgorithm as a Handover Management SAP implementation
  void DoReportUeMeas (uint16_t rnti, LteRrcSap::MeasResults measResults);

private:
  /**
   * Called when Event A2 is detected, then trigger a handover if needed.
   *
   * \param rnti The RNTI of the UE who reported the event.
   * \param servingCellRsrq The RSRQ of this cell as reported by the UE.
   */
  void EvaluateHandover (uint16_t rnti, uint8_t servingCellRsrq);

  /**
   * Determines if a neighbour cell is a valid destination for handover.
   * Currently always return true.
   *
   * \param cellId The cell ID of the neighbour cell.
   * \return True if the cell is a valid destination for handover.
   */
  bool IsValidNeighbour (uint16_t cellId);

  /**
   * Called when Event A4 is reported, then update the measurements table.
   * If the RNTI and/or cell ID is not found in the table, a corresponding
   * entry will be created. Only the latest measurements are stored in the
   * table.
   *
   * \param rnti The RNTI of the UE who reported the event.
   * \param cellId The cell ID of the measured cell.
   * \param rsrq The RSRQ of the cell as measured by the UE.
   */
  void UpdateNeighbourMeasurements (uint16_t rnti, uint16_t cellId,
                                    uint8_t rsrq);

  /// The expected measurement identity for A2 measurements.
  uint8_t m_a2MeasId;
  /// The expected measurement identity for A4 measurements.
  uint8_t m_a4MeasId;

  /**
   * Measurements reported by a UE for a cell ID. The values are quantized
   * according 3GPP TS 36.133 section 9.1.4 and 9.1.7.
   */
  class UeMeasure : public SimpleRefCount<UeMeasure>
  {
  public:
    uint16_t m_cellId;  ///< Cell ID.
    uint8_t m_rsrp;     ///< RSRP in quantized format. \todo Can be removed?
    uint8_t m_rsrq;     ///< RSRQ in quantized format.
  };

  /**
   * Measurements reported by a UE for several cells. The structure is a map
   * indexed by the cell ID.
   */
  typedef std::map<uint16_t, Ptr<UeMeasure> > MeasurementRow_t;

  /**
   * Measurements reported by several UEs. The structure is a map indexed by
   * the RNTI of the UE.
   */
  typedef std::map<uint16_t, MeasurementRow_t> MeasurementTable_t;

  /// Table of measurement reports from all UEs.
  MeasurementTable_t m_neighbourCellMeasures;

  /**
   * The `ServingCellThreshold` attribute. If the RSRQ of the serving cell is
   * worse than this threshold, neighbour cells are consider for handover.
   * Expressed in quantized range of [0..34] as per Section 9.1.7 of
   * 3GPP TS 36.133.
   */
  uint8_t m_servingCellThreshold;

  /**
   * The `NeighbourCellOffset` attribute. Minimum offset between the serving
   * and the best neighbour cell to trigger the handover. Expressed in
   * quantized range of [0..34] as per Section 9.1.7 of 3GPP TS 36.133.
   */
  uint8_t m_neighbourCellOffset;

  /// Interface to the eNodeB RRC instance.
  LteHandoverManagementSapUser* m_handoverManagementSapUser;
  /// Receive API calls from the eNodeB RRC instance.
  LteHandoverManagementSapProvider* m_handoverManagementSapProvider;

}; // end of class A2A4RsrqHandoverAlgorithm

} // end of namespace ns3

#endif /* A2_A4_RSRQ_HANDOVER_ALGORITHM_H */


text:
require 'fog/openstack/models/model'

module Fog
  module Metric
    class OpenStack
      class Metric < Fog::OpenStack::Model
        identity :id

        attribute :name
        attribute :resource_id
        attribute :unit
        attribute :created_by_project_id
        attribute :created_by_user_id
        attribute :definition
      end
    end
  end
end


text:
package de.bastiankrol.startexplorer.crossplatform;

import static de.bastiankrol.startexplorer.variables.VariableManager.*;
import static org.mockito.Mockito.*;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

import de.bastiankrol.startexplorer.Activator;
import de.bastiankrol.startexplorer.ActivatorInstanceInjector;
import de.bastiankrol.startexplorer.PluginContext;
import de.bastiankrol.startexplorer.variables.VariableManager;

/**
 * Test class
 *
 * @author Bastian Krol
 */
public class RuntimeExecCallsTest
{
  private RuntimeExecCallsWindows runtimeExecCalls;
  private String path;
  private String resourceName;
  private String extension;
  private File file;
  private List<File> fileList;

  @Mock
  private IRuntimeExecDelegate runtimeExecDelegateMock;

  @Mock
  private Activator activatorMock;

  @Mock
  private PluginContext pluginContextMock;

  @Mock
  private VariableManager variableManagerMock;

  /**
   * JUnite before
   */
  @Before
  public void setUp()
  {
    MockitoAnnotations.initMocks(this);

    this.path = "/path/to";
    this.resourceName = "resource";
    this.extension = "txt";
    this.file = new File(this.path + this.resourceName + "." + this.extension);

    this.fileList = new ArrayList<File>();
    this.fileList.add(new File("C:\\file\\to\\resource"));
    this.fileList.add(new File("/file/to/another/resource"));
    this.fileList
        .add(new File(
            "some weird string (RuntimeExecCalls doesn't check if it's a valid file"));

    this.runtimeExecCalls = new RuntimeExecCallsWindows();
    this.runtimeExecCalls.setRuntimeExecDelegate(this.runtimeExecDelegateMock);
  }

  /**
   * JUnit test method
   */
  @Test
  public void testStartWindowsExplorerForFile()
  {
    this.runtimeExecCalls.startFileManagerForFile(this.file, false);
    verify(this.runtimeExecDelegateMock).exec(
        new String[] { "Explorer.exe /e,\"" + this.file.getAbsolutePath()
            + "\"" }, null, true);
  }

  /**
   * JUnit test method
   */
  @Test
  public void testSelectFileInWindowsExplorer()
  {
    File fileMock = mock(File.class);
    when(fileMock.isFile()).thenReturn(true);
    when(fileMock.getAbsolutePath()).thenReturn("C:\\file\\to\\resource.txt");
    this.runtimeExecCalls.startFileManagerForFile(fileMock, true);
    verify(this.runtimeExecDelegateMock).exec(
        new String[] { "Explorer.exe /select,\"" + fileMock.getAbsolutePath()
            + "\"" }, null, true);
  }

  /**
   * JUnit test method
   */
  @Test
  public void testStartWindowsExplorerForFileList()
  {
    this.runtimeExecCalls.startFileManagerForFileList(this.fileList, false);
    for (File fileFromList : this.fileList)
    {
      verify(this.runtimeExecDelegateMock).exec(
          new String[] { "Explorer.exe /e,\"" + fileFromList.getAbsolutePath()
              + "\"" }, null, true);
    }
  }

  /**
   * JUnit test method
   */
  @Test
  public void testStartWindowsSystemApplicationForFile()
  {
    this.runtimeExecCalls.startSystemApplicationForFile(this.file);
    verify(this.runtimeExecDelegateMock).exec(
        new String[] { "cmd.exe /c \"" + this.file.getAbsolutePath() + "\"" },
        null, true);
  }

  /**
   * JUnit test method
   */
  @Test
  public void testStartWindowsSystemApplicationForFileList()
  {
    this.runtimeExecCalls.startSystemApplicationForFileList(this.fileList);
    for (File fileFromList : this.fileList)
    {
      verify(this.runtimeExecDelegateMock).exec(
          new String[] { "cmd.exe /c \"" + fileFromList.getAbsolutePath()
              + "\"" }, null, true);
    }
  }

  /**
   * JUnit test method
   */
  @Test
  public void testStartCmdExeForFile()
  {
    this.runtimeExecCalls.startShellForFile(this.file);
    verify(this.runtimeExecDelegateMock).exec(
        new String[] { "cmd.exe /c start /d \"" + this.file.getAbsolutePath()
            + "\"" }, null, true);
  }

  /**
   * JUnit test method
   */
  @Test
  public void testStartCmdExeForFileList()
  {
    this.runtimeExecCalls.startShellForFileList(this.fileList);
    for (File fileFromList : this.fileList)
    {
      verify(this.runtimeExecDelegateMock).exec(
          new String[] { "cmd.exe /c start /d \""
              + fileFromList.getAbsolutePath() + "\"" }, null, true);
    }
  }

  /**
   * JUnit test method
   */
  @Test
  public void testStartCustomCommandForFile()
  {
    // Prepare mocks that are only used for this test
    ActivatorInstanceInjector.injectDefaultInstanceForTest(this.activatorMock);
    ActivatorInstanceInjector.stubGetContextCall(this.activatorMock,
        this.pluginContextMock);
    when(this.pluginContextMock.getVariableManager()).thenReturn(
        this.variableManagerMock);

    final String[] cmdArray = new String[] { "parent: " + RESOURCE_PARENT_VAR, //
        "name: " + RESOURCE_NAME_VAR, //
        "complete path: " + RESOURCE_PATH_VAR, //
        "name without extension: " + RESOURCE_NAME_WIHTOUT_EXTENSION_VAR, //
        "extension: " + RESOURCE_EXTENSION_VAR //
    };
    final String[] cmdArrayWithVariablesReplaced = new String[] {//
    "parent: \"" + this.file.getParentFile().getAbsolutePath() + "\"", //
        "name: \"" + this.file.getName() + "\"", //
        "complete path: \"" + this.file.getAbsolutePath() + "\"", //
        "name without extension: " + this.resourceName, //
        "extension: " + this.extension //
    };
    doAnswer(new Answer<Object>()
    {
      @Override
      public Object answer(InvocationOnMock invocation) throws Throwable
      {
        // String[] cmdArray = (String[]) invocation.getArguments()[0];
        for (int i = 0; i < cmdArray.length; i++)
        {
          cmdArray[i] = cmdArrayWithVariablesReplaced[i];
        }
        return null;
      }
    }).when(this.variableManagerMock).replaceAllVariablesInCommand(cmdArray,
        this.file, true, false);

    this.runtimeExecCalls.startCustomCommandForFile(cmdArray, this.file);
    verify(this.runtimeExecDelegateMock).exec(cmdArrayWithVariablesReplaced,
        null, true);
  }
}


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

<title>Uses of Interface org.apache.poi.xslf.model.geom.PathCommand (POI API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV

NEXT

FRAMES

NO FRAMES

All Classes

Uses of Interface
org.apache.poi.xslf.model.geom.PathCommand

Packages that use PathCommand

Package
Description

org.apache.poi.xslf.model.geom

Uses of PathCommand in org.apache.poi.xslf.model.geom

Classes in org.apache.poi.xslf.model.geom that implement PathCommand

Modifier and Type
Class and Description

class
ArcToCommand

ArcTo command within a shape path in DrawingML:

 <arcTo wR="wr" hR="hr" stAng="stAng" swAng="swAng"/>

 Where wr and wh are the height and width radiuses
 of the supposed circle being used to draw the arc.

class
ClosePathCommand

Date: 10/25/11

class
CurveToCommand

Date: 10/25/11

class
LineToCommand

Date: 10/25/11

class
MoveToCommand

Date: 10/25/11

class
QuadToCommand

Date: 10/25/11

Methods in org.apache.poi.xslf.model.geom with parameters of type PathCommand

Modifier and Type
Method and Description

void
Path.addCommand(PathCommand cmd)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV

NEXT

FRAMES

NO FRAMES

All Classes

                Copyright 2014 The Apache Software Foundation or
        its licensors, as applicable.


text:
/****************************************************************************
 * Included Files
 ****************************************************************************/
#include <tinyara/config.h>

#include <debug.h>
#include <queue.h>
#include <tinyara/wdog.h>
#include <tinyara/clock.h>
#include <tinyara/time.h>
#include <tinyara/wdog.h>
#include <arch/board/stm32l4r9ai-disco-clocking.h>

#include "up_arch.h"
#include "stm32l4_lptim.h"
#include "chip/stm32l4xrxx_rcc.h"
#include "stm32l4xx_hal.h"
#include <tinyara/pm/pm.h>
#include "nvic.h"
#include "clock/clock.h"
#include "up_internal.h"
#include "up_arch.h"

#include "chip.h"
#include "stm32l4.h"
#include "stm32l4xx_hal_interface.h"
/****************************************************************************
 * Pre-processor Definitions
 ****************************************************************************/

#define MAX_TCNT UINT32_MAX	/* Max 32-bit timer-tick value */

/****************************************************************************
 * Type Definitions
 ****************************************************************************/
enum {
	TICKSUPPRESS_DISABLE,
	TICKSUPPRESS_ENABLE
} timertick_mode;

/****************************************************************************
 * Private Data
 ****************************************************************************/

static uint8_t g_tick_mode;		/* timer-tick mode  */
clock_t next_intval;			/* next delay interval  */
static TIM_HandleTypeDef htim2;		/* TIM handle  */

#define STM32L4_TICKLESS_IDLE_ACTIVITY		5
#define TIM2_PRESCALER				2

/****************************************************************************
 * Private Functions
 ****************************************************************************/

/****************************************************************************
 * Function:  stm32l4_get_next_delay
 *
 * Description:
 *  This function returns delay (in system ticks) from head of wdog active list.
 *  It calls wd_getdelay() provided by RTOS
 *
 ****************************************************************************/
static uint32_t stm32l4_get_next_delay(void)
{
	return (uint32_t)wd_getdelay();
}

/****************************************************************************
 * Function:  stm32l4_tim2_handler
 *
 * Description:
 *   The tim2 ISR to execute watddog expiration and modify ticks based on elapsed gap
 *
 ****************************************************************************/
int stm32l4_tim2_handler(int irq, uint32_t *regs)
{
	irqstate_t flags;
	uint32_t next_event = 0;
	uint32_t elapsed = 0;

	/* Clear interrupt pending */
	__HAL_TIM_CLEAR_IT(&htim2, TIM_IT_UPDATE);

	pm_activity(0, STM32L4_TICKLESS_IDLE_ACTIVITY);

	elapsed = next_intval;
	next_intval = 0;

	execute_waketime_interrupt(elapsed);

	return 0;
}

/****************************************************************************
 * Function:  tim2_set_trigger
 *
 * Description:
 *   This function is called to initialize and configure timer TIM2
 *   when the kernel next needs to execute
 *
 ****************************************************************************/
void tim2_set_trigger(int next_event)
{
	__HAL_RCC_TIM2_CLK_ENABLE();
	htim2.Instance = TIM2;
	htim2.Init.Prescaler = TIM2_PRESCALER;
	htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
	htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
	htim2.Init.RepetitionCounter = 0;
	htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
	htim2.Init.Period = (uint32_t)(next_event * USEC_PER_TICK * (BOARD_TIM2_FREQUENCY/(USEC_PER_SEC * TIM2_PRESCALER)));

	if(HAL_TIM_Base_Init(&htim2) != HAL_OK)
	{
		printf("HAL TIM Base Init Error\n");
	}

	/* Clear interrupt pending if any */
	__HAL_TIM_CLEAR_IT(&htim2, TIM_IT_UPDATE);

	HAL_NVIC_SetPriority(TIM2_IRQn, 1, 0);
	(void)irq_attach(STM32L4_IRQ_TIM2, stm32l4_tim2_handler, NULL);
	up_enable_irq(STM32L4_IRQ_TIM2);

	if(HAL_TIM_Base_Start_IT(&htim2) != HAL_OK)
	{
		printf("HAL TIM Base Start IT Error\n");
	}
}

/*****************************************************************************
 * Function:  schedule_expected_event
 *
 * Description:
 *   Get next expected event
 *   Enables tick suppression (disables periodic ticks), when system goes idle
 *
 *****************************************************************************/
void schedule_expected_event(void)
{
	irqstate_t flags;
	uint32_t next_delay;

	next_delay = stm32l4_get_next_delay();
	if (!next_delay) {
		next_delay = MAX_TCNT;
	}

	flags = irqsave();

	next_intval = next_delay;

	/* Configure timer when the kernel next needs to execute*/
	tim2_set_trigger(next_delay);

	irqrestore(flags);
}

/****************************************************************************
 * Public Functions
 ****************************************************************************/

/****************************************************************************
 * Function:  set_waketime_interrupt
 *
 * Description:
 *   This function configures an interrupt to bring MCU out of low
 *   power state after the expected idle time. This timer should be
 *   active even when the MCU is in low power state
 *
 ****************************************************************************/
extern void set_waketime_interrupt(void)
{
	if (g_tick_mode == TICKSUPPRESS_DISABLE) {
		g_tick_mode = TICKSUPPRESS_ENABLE;

		schedule_expected_event();
	}
}

/****************************************************************************
 * Function:  execute_waketime_interrupt
 *
 * Description:
 *   This function is called to disable the timer interrupt configured
 *   to bring MCU out of low power state after expected idle time.
 *   Checks and execute a watchdog function based on time gap
 *
 ****************************************************************************/
extern void execute_waketime_interrupt(int elapsed)
{
	if (g_tick_mode == TICKSUPPRESS_ENABLE)
	{
		g_tick_mode = TICKSUPPRESS_DISABLE;
		/* Check if it is time to execute a watchdog function */
		wd_timer_nohz(elapsed);
		/* Disable TIM2 */
		HAL_TIM_Base_Stop_IT(&htim2);
		HAL_NVIC_DisableIRQ(TIM2_IRQn);
		HAL_TIM_Base_DeInit(&htim2);
		__HAL_RCC_TIM2_CLK_DISABLE();
	}
}

/****************************************************************************
 * Function:  supress_ticks
 *
 * Description:
 *   This function is called to supress ticks
 *
 ****************************************************************************/
extern void supress_ticks(void)
{
	supress_hal_tick();

	/* Disable SysTick */
	SysTick->CTRL &= ~SysTick_CTRL_TICKINT_Msk;
}

/****************************************************************************
 * Function:  enable_ticks
 *
 * Description:
 *   This function is called to enable ticks
 *
 ****************************************************************************/
extern void enable_ticks(void)
{
	/* Enable SysTick */
	SysTick->CTRL  |= SysTick_CTRL_TICKINT_Msk;

	/* Enable HALTick */
	enable_hal_tick();
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="@dimen/nav_header_height"
    android:background="@drawable/side_nav_bar"
    android:gravity="top"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/coverImage"
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:scaleType="fitXY"/>

    <WebView
        android:id="@+id/characterView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="0dp"/>

</LinearLayout>


text:
package com.google.inject.internal;

import com.google.common.collect.ImmutableSet;
import com.google.inject.internal.ProvisionListenerStackCallback.ProvisionCallback;
import com.google.inject.spi.InjectionPoint;

import java.lang.reflect.InvocationTargetException;
import java.util.Set;

/**
 * Creates instances using an injectable constructor. After construction, all injectable fields and
 * methods are injected.
 *
 * @author crazybob@google.com (Bob Lee)
 */
final class ConstructorInjector<T> {

  private final ImmutableSet<InjectionPoint> injectableMembers;
  private final SingleParameterInjector<?>[] parameterInjectors;
  private final ConstructionProxy<T> constructionProxy;
  private final MembersInjectorImpl<T> membersInjector;

  ConstructorInjector(Set<InjectionPoint> injectableMembers,
      ConstructionProxy<T> constructionProxy,
      SingleParameterInjector<?>[] parameterInjectors,
      MembersInjectorImpl<T> membersInjector) {
    this.injectableMembers = ImmutableSet.copyOf(injectableMembers);
    this.constructionProxy = constructionProxy;
    this.parameterInjectors = parameterInjectors;
    this.membersInjector = membersInjector;
  }

  public ImmutableSet<InjectionPoint> getInjectableMembers() {
    return injectableMembers;
  }

  ConstructionProxy<T> getConstructionProxy() {
    return constructionProxy;
  }

  /**
   * Construct an instance. Returns {@code Object} instead of {@code T} because
   * it may return a proxy.
   */
  Object construct(final Errors errors, final InternalContext context,
      Class<?> expectedType, boolean allowProxy,
      ProvisionListenerStackCallback<T> provisionCallback)
      throws ErrorsException {
    final ConstructionContext<T> constructionContext = context.getConstructionContext(this);

    // We have a circular reference between constructors. Return a proxy.
    if (constructionContext.isConstructing()) {
      if(!allowProxy) {
        throw errors.circularProxiesDisabled(expectedType).toException();
      } else {
        // TODO (crazybob): if we can't proxy this object, can we proxy the other object?
        return constructionContext.createProxy(errors, expectedType);
      }
    }

    // If we're re-entering this factory while injecting fields or methods,
    // return the same instance. This prevents infinite loops.
    T t = constructionContext.getCurrentReference();
    if (t != null) {
      return t;
    }

    constructionContext.startConstruction();
    try {
      // Optimization: Don't go through the callback stack if we have no listeners.
      if (!provisionCallback.hasListeners()) {
        return provision(errors, context, constructionContext);
      } else {
        return provisionCallback.provision(errors, context, new ProvisionCallback<T>() {
          public T call() throws ErrorsException {
            return provision(errors, context, constructionContext);
          }
        });
      }
    } finally {
      constructionContext.removeCurrentReference();
      constructionContext.finishConstruction();
    }
  }

  /** Provisions a new T. */
  private T provision(Errors errors, InternalContext context,
      ConstructionContext<T> constructionContext) throws ErrorsException {
    try {
      T t;
      try {
        Object[] parameters = SingleParameterInjector.getAll(errors, context, parameterInjectors);
        t = constructionProxy.newInstance(parameters);
        constructionContext.setProxyDelegates(t);
      } finally {
        constructionContext.finishConstruction();
      }

      // Store reference. If an injector re-enters this factory, they'll get the same reference.
      constructionContext.setCurrentReference(t);

      membersInjector.injectMembers(t, errors, context, false);
      membersInjector.notifyListeners(t, errors);

      return t;
    } catch (InvocationTargetException userException) {
      Throwable cause = userException.getCause() != null
          ? userException.getCause()
          : userException;
      throw errors.withSource(constructionProxy.getInjectionPoint())
          .errorInjectingConstructor(cause).toException();
    }
  }
}


text:
package options_test

import (
	"flag"
	"fmt"
	"time"

	"github.com/mreiferson/go-options"
)

type Options struct {
	MaxSize     int64         `flag:"max-size" cfg:"max_size"`
	Timeout     time.Duration `flag:"timeout" cfg:"timeout"`
	Description string        `flag:"description" cfg:"description"`
}

func ExampleResolve() {
	flagSet := flag.NewFlagSet("example", flag.ExitOnError)
	flagSet.Int64("max-size", 1024768, "maximum size")
	flagSet.Duration("timeout", 1*time.Hour, "timeout setting")
	// parse command line arguments here
	// flagSet.Parse(os.Args[1:])
	flagSet.Parse([]string{"-timeout=5s"})

	opts := &Options{
		MaxSize: 1,
		Timeout: time.Second,
	}
	cfg := map[string]interface{}{
		"timeout": "1h",
	}

	fmt.Printf("%#v", opts)
	options.Resolve(opts, flagSet, cfg)
	fmt.Printf("%#v", opts)

}


text:
const fs = require("fs");
const sqlite3 = require("sqlite3").verbose();

const db = new sqlite3.Database("./db/db.sqlite3");
module.exports.db = db;

module.exports.randomString = function(len)
{
	const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!#¤%&/()=?@£$€{}[]-_.,;:<>|*";
	var secret = "";
	for (var i = 0; i < len; ++i) {
		var num = Math.floor(Math.random() * chars.length);
		secret += chars[num];
	}
	return secret;
};

module.exports.checkIfIdExistsInLayout = function(id, callbackYes, callbackElse)
{
	if (id === 0) {
		callbackElse("The seat does not exist in the layout");
	} else {
		db.get("SELECT * FROM data WHERE key = 'layout'", function(err, data) {
			if (err) {
				throw(err);
				callbackElse("500");
			} else {
				var layout = JSON.parse(data.value);

				var found = false;
				outerLoop:
				for (var i = 0; i < layout.length; ++i) {
					for (var j = 0; j < layout[i].length; ++j) {
						if (layout[i][j].id === Number(id)) {
							found = true;
							break outerLoop;
						}
					}
				}
				if (found)
					callbackYes();
				else
					callbackElse("The seat does not exist in the layout");
			}
		});
	}
};

module.exports.nameContainsInvalidChars = function(str)
{
	return (
		str.match(/[^ ] [^ ]/) === null ||                // two words (forename + surname)
		str.match(/\t/) !== null ||                       // tab chars
		str.match(/["'@#$%;:&_<>|/!\.\*\\]/) !== null ||  // other invalid chars
		str.match(/[0-9]/) !== null                       // numbers
	)
};

module.exports.send = function(res, data)
{
	if (typeof data === "string") {
		if (data.substr(0, 3) === "500")
			res.status(500).send("Internal Server Error");
		else if (data.substr(0, 3) === "404")
			res.status(404).send(data.substr(3));
		else if (data.substr(0, 3) === "400")
			res.status(400).send(data.substr(3));
		else
			res.send(data);
	}
	else
		res.send(data);
};

module.exports.params = function(req, res, params, callback)
{
	const data = {trans: req.trans, sessionId: req.sessionID};

	for (var i = 0; i < params.length; ++i) {
		if (typeof req.body[params[i]] === "undefined") {
			module.exports.send(res, "400Incorrect/not enough parameters");
			return;
		} else {
			data[params[i]] = req.body[params[i]];
		}
	}

	callback(data);
};

module.exports.errorHappened = function(data)
{
	if (typeof data !== "string") {
		return false;
	} else {
		if (data.substr(0, 3) === "500" || data.substr(0, 3) === "400" || data.substr(0, 3) === "404")
			return true;
		else
			return false;
	}
};


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/relativeLayoutMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/linearLayoutNavButtons"
        android:layout_alignParentTop="true" >
    </android.support.v4.view.ViewPager>

    <LinearLayout
        android:id="@+id/linearLayoutNavButtons"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true" >

        <Button
            android:id="@+id/buttonPrevious"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:enabled="false"
            android:text="Previous" />

        <Button
            android:id="@+id/buttonNext"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:enabled="false"
            android:text="Next" />
    </LinearLayout>

</RelativeLayout>


text:
package peapod.demo.classic;

import peapod.annotations.Edge;
import peapod.annotations.In;
import peapod.annotations.Out;

@Edge
public interface Knows {

    Float getWeight();

    @Out
    Person getPerson();

    @In
    Person getOtherPerson();

}


text:
package com.vmware.vim25;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for SnapshotRevertIssue complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="SnapshotRevertIssue">
 *   <complexContent>
 *     <extension base="{urn:vim25}MigrationFault">
 *       <sequence>
 *         <element name="snapshotName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="event" type="{urn:vim25}Event" maxOccurs="unbounded" minOccurs="0"/>
 *         <element name="errors" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SnapshotRevertIssue", propOrder = {
    "snapshotName",
    "event",
    "errors"
})
public class SnapshotRevertIssue
    extends MigrationFault
{

    protected String snapshotName;
    protected List<Event> event;
    protected boolean errors;

    /**
     * Gets the value of the snapshotName property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getSnapshotName() {
        return snapshotName;
    }

    /**
     * Sets the value of the snapshotName property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setSnapshotName(String value) {
        this.snapshotName = value;
    }

    /**
     * Gets the value of the event property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the event property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getEvent().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link Event }
     *
     *
     */
    public List<Event> getEvent() {
        if (event == null) {
            event = new ArrayList<Event>();
        }
        return this.event;
    }

    /**
     * Gets the value of the errors property.
     *
     */
    public boolean isErrors() {
        return errors;
    }

    /**
     * Sets the value of the errors property.
     *
     */
    public void setErrors(boolean value) {
        this.errors = value;
    }

}