text:
<?php

namespace PHPMD\Renderer;

use PHPMD\PHPMD;
use PHPMD\Report;
use PHPMD\Renderer\JSONRenderer;

/**
 * This class will render a SARIF (Static Analysis
 * Results Interchange Format) report.
 */
class SARIFRenderer extends JSONRenderer
{
    /**
     * Create report data and add renderer meta properties
     *
     * @return array
     */
    protected function initReportData()
    {
        $data = array(
            'version' => '2.1.0',
            '$schema' =>
                'https://raw.githubusercontent.com/oasis-tcs/' .
                'sarif-spec/master/Schemata/sarif-schema-2.1.0.json',
            'runs' => array(
                array(
                    'tool' => array(
                        'driver' => array(
                            'name' => 'PHPMD',
                            'informationUri' => 'https://phpmd.org',
                            'version' => PHPMD::VERSION,
                            'rules' => array(),
                        ),
                    ),
                    'originalUriBaseIds' => array(
                        'WORKINGDIR' => array(
                            'uri' => static::pathToUri(getcwd()) . '/',
                        ),
                    ),
                    'results' => array(),
                ),
            ),
        );

        return $data;
    }

    /**
     * Add violations, if any, to the report data
     *
     * @param Report $report The report with potential violations.
     * @param array $data The report output to add the violations to.
     * @return array The report output with violations, if any.
     */
    protected function addViolationsToReport(Report $report, array $data)
    {
        $rules = array();
        $results = array();
        $ruleIndices = array();

        /** @var RuleViolation $violation */
        foreach ($report->getRuleViolations() as $violation) {
            $rule = $violation->getRule();
            $ruleRef = str_replace(' ', '', $rule->getRuleSetName()) . '/' . $rule->getName();

            if (!isset($ruleIndices[$ruleRef])) {
                $ruleIndices[$ruleRef] = count($rules);

                $ruleData = array(
                    'id' => $ruleRef,
                    'name' => $rule->getName(),
                    'shortDescription' => array(
                        'text' => $rule->getRuleSetName() . ': ' . $rule->getName(),
                    ),
                    'messageStrings' => array(
                        'default' => array(
                            'text' => trim($rule->getMessage()),
                        ),
                    ),
                    'help' => array(
                        'text' => trim(str_replace("\n", ' ', $rule->getDescription())),
                    ),
                    'helpUri' => $rule->getExternalInfoUrl(),
                    'properties' => array(
                        'ruleSet' => $rule->getRuleSetName(),
                        'priority' => $rule->getPriority(),
                    ),
                );

                $examples = $rule->getExamples();
                if (!empty($examples)) {
                    $ruleData['help']['markdown'] =
                        $ruleData['help']['text'] .
                        "\n\n### Example\n\n```php\n" .
                        implode("\n```\n\n```php\n", array_map('trim', $examples)) . "\n```";
                }

                $since = $rule->getSince();
                if ($since) {
                    $ruleData['properties']['since'] = 'PHPMD ' . $since;
                }

                $rules[] = $ruleData;
            }

            $arguments = $violation->getArgs();
            if ($arguments === null) {
                $arguments = array();
            }

            $results[] = array(
                'ruleId' => $ruleRef,
                'ruleIndex' => $ruleIndices[$ruleRef],
                'message' => array(
                    'id' => 'default',
                    'arguments' => array_map('strval', $arguments),
                    'text' => $violation->getDescription(),
                ),
                'locations' => array(
                    array(
                        'physicalLocation' => array(
                            'artifactLocation' => static::pathToArtifactLocation($violation->getFileName()),
                            'region' => array(
                                'startLine' => $violation->getBeginLine(),
                                'endLine' => $violation->getEndLine(),
                            ),
                        ),
                    )
                ),
            );
        }

        $data['runs'][0]['tool']['driver']['rules'] = $rules;
        $data['runs'][0]['results'] = array_merge($data['runs'][0]['results'], $results);

        return $data;
    }

    /**
     * Add errors, if any, to the report data
     *
     * @param Report $report The report with potential errors.
     * @param array $data The report output to add the errors to.
     * @return array The report output with errors, if any.
     */
    protected function addErrorsToReport(Report $report, array $data)
    {
        $errors = $report->getErrors();
        if ($errors) {
            foreach ($errors as $error) {
                $data['runs'][0]['results'][] = array(
                    'level' => 'error',
                    'message' => array(
                        'text' => $error->getMessage(),
                    ),
                    'locations' => array(
                        array(
                            'physicalLocation' => array(
                                'artifactLocation' => static::pathToArtifactLocation($error->getFile()),
                            ),
                        )
                    ),
                );
            }
        }

        return $data;
    }

    /**
     * Makes an absolute path relative to the working directory
     * if possible, otherwise prepends the `file://` protocol
     * and returns the result as a SARIF `artifactLocation`
     *
     * @param string $path
     * @return array
     */
    protected static function pathToArtifactLocation($path)
    {
        $workingDir = getcwd();
        if (substr($path, 0, strlen($workingDir)) === $workingDir) {
            // relative path
            return array(
                'uri' => substr($path, strlen($workingDir) + 1),
                'uriBaseId' => 'WORKINGDIR',
            );
        }

        // absolute path with protocol
        return array(
            'uri' => static::pathToUri($path),
        );
    }

    /**
     * Converts an absolute path to a file:// URI
     *
     * @param string $path
     * @return string
     */
    protected static function pathToUri($path)
    {
        $path = str_replace(DIRECTORY_SEPARATOR, '/', $path);

        // file:///C:/... on Windows systems
        if (substr($path, 0, 1) !== '/') {
            $path = '/' . $path;
        }

        return 'file://' . $path;
    }
}


text:
require "rails_helper"

RSpec.describe ExpandedLinksPresenter do
  describe ".present" do
    subject { described_class.new(links).present }

    let(:prefix) { Plek.website_root }
    let(:base_path) { "/test-page" }
    let(:api_path) { "/api/content/test-page" }
    let(:links) do
      {
        link_group: [{ base_path:, api_path: }],
      }
    end

    context "production environment" do
      let(:production_prefix) { "https://www.gov.uk" }
      let(:expected) do
        {
          link_group: [
            a_hash_including(
              web_url: "#{production_prefix}#{base_path}",
              api_url: "#{production_prefix}#{api_path}",
            ),
          ],
        }
      end

      before { allow(Plek).to receive(:website_root).and_return(production_prefix) }

      it { is_expected.to include expected }
    end

    context "development environment" do
      let(:development_prefix) { "http://dev.gov.uk" }
      let(:expected) do
        {
          link_group: [
            a_hash_including(
              web_url: "#{development_prefix}#{base_path}",
              api_url: "#{development_prefix}#{api_path}",
            ),
          ],
        }
      end

      before { allow(Plek).to receive(:website_root).and_return(development_prefix) }

      it { is_expected.to include expected }
    end

    context "links with arbitrary custom fields" do
      let(:links) do
        {
          link_group: [{ foo: "bar", auth_bypass_ids: "secret" }],
        }
      end

      subject { described_class.new(links).present[:link_group][0] }

      it "contains the custom fields but does not contain fields marked as secret" do
        is_expected.to include(:foo)
        is_expected.not_to include(:auth_bypass_ids)
      end
    end

    context "groups of links" do
      let(:links) do
        {
          group_1: [
            { base_path: "/group-1/link-1", api_path: "/api/content/group-1/link-1" },
            { base_path: "/group-1/link-2", api_path: "/api/content/group-1/link-2" },
            { base_path: "/group-1/link-3", api_path: "/api/content/group-1/link-3" },
          ],
          group_2: [
            { base_path: "/group-2/link-1", api_path: "/api/content/group-2/link-1" },
            { base_path: "/group-2/link-2", api_path: "/api/content/group-2/link-2" },
            { base_path: "/group-2/link-3", api_path: "/api/content/group-2/link-3" },
          ],
        }
      end

      let(:expected) do
        {
          group_1: [
            a_hash_including(web_url: "#{prefix}/group-1/link-1", api_url: "#{prefix}/api/content/group-1/link-1"),
            a_hash_including(web_url: "#{prefix}/group-1/link-2", api_url: "#{prefix}/api/content/group-1/link-2"),
            a_hash_including(web_url: "#{prefix}/group-1/link-3", api_url: "#{prefix}/api/content/group-1/link-3"),
          ],
          group_2: [
            a_hash_including(web_url: "#{prefix}/group-2/link-1", api_url: "#{prefix}/api/content/group-2/link-1"),
            a_hash_including(web_url: "#{prefix}/group-2/link-2", api_url: "#{prefix}/api/content/group-2/link-2"),
            a_hash_including(web_url: "#{prefix}/group-2/link-3", api_url: "#{prefix}/api/content/group-2/link-3"),
          ],
        }
      end

      it { is_expected.to match expected }
    end

    context "link without api_path set" do
      let(:links) do
        {
          link_group: [{ base_path: }],
        }
      end
      let(:api_path) { "/api/content#{base_path}" }
      let(:expected) do
        {
          link_group: [
            a_hash_including(
              api_path:,
              api_url: "#{prefix}#{api_path}",
            ),
          ],
        }
      end

      it "prefixes a base path with '/api/content' to create API url" do
        is_expected.to match expected
      end
    end

    context "link without base_path" do
      let(:links) do
        {
          link_group: [{}],
        }
      end

      let(:expected_links) do
        {
          link_group: [
            {
              links: {},
            },
          ],
        }
      end

      it "does not include api_path, api_url or web_url" do
        is_expected.to match expected_links
      end
    end

    context "link with children" do
      let(:links) do
        { group: [{ base_path: "/grand-parent", links: parent }] }
      end

      let(:parent) do
        { group: [{ base_path: "/grand-parent/parent", links: child }] }
      end

      let(:child) do
        { group: [{ base_path: "/grand-parent/parent/child", links: {} }] }
      end

      let(:expected_links) do
        {
          group: [
            a_hash_including(
              web_url: "#{prefix}/grand-parent",
              links: expected_parent,
            ),
          ],
        }
      end

      let(:expected_parent) do
        {
          group: [
            a_hash_including(
              web_url: "#{prefix}/grand-parent/parent",
              links: expected_child,
            ),
          ],
        }
      end

      let(:expected_child) do
        {
          group: [
            a_hash_including(
              web_url: "#{prefix}/grand-parent/parent/child",
              links: {},
            ),
          ],
        }
      end

      it { is_expected.to match expected_links }
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package us.dot.its.jpo.ode.pdm;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.junit.runner.RunWith;

import mockit.Tested;
import mockit.integration.junit4.JMockit;
import us.dot.its.jpo.ode.plugin.RoadSideUnit.RSU;
import us.dot.its.jpo.ode.plugin.ServiceRequest;
import us.dot.its.jpo.ode.plugin.j2735.J2735ProbeDataManagment;

@RunWith(JMockit.class)
public class J2735PdmRequestTest {

    @Tested
    J2735PdmRequest testJ2735ProbeDataManagement;

    @Test
    public void testSetOdeAndGetOde() {

        int testOdeVersion = 3;

        ServiceRequest.OdeInternal testODE = new ServiceRequest.OdeInternal();
        testODE.setVersion(testOdeVersion);

        testJ2735ProbeDataManagement.setOde(testODE);
        assertEquals(testOdeVersion, testJ2735ProbeDataManagement.getOde().getVersion());
    }

    @Test
    public void testSetRsuListAndGetRsuList() {

        String testTarget = "testTarget123";

        RSU testRsu = new RSU();
        testRsu.setRsuTarget(testTarget);

        RSU[] testRsuList = new RSU[] { testRsu };

        testJ2735ProbeDataManagement.setRsuList(testRsuList);
        assertEquals(testTarget, testJ2735ProbeDataManagement.getRsuList()[0].getRsuTarget());
    }

    @Test
    public void testSetAndGetPdm() {

        int testDirections = 7;

        J2735ProbeDataManagment testPdm = new J2735ProbeDataManagment();
        testPdm.setDirections(testDirections);

        testJ2735ProbeDataManagement.setPdm(testPdm);
        assertEquals(testDirections, testJ2735ProbeDataManagement.getPdm().getDirections());
    }

}


text:
package net.grosinger.bookmetasearch.inventory;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import net.grosinger.bookmetasearch.R;
import net.grosinger.bookmetasearch.book.Book;

/**
 * Store information about a specific inventory item.
 * Contains a url for this item, who is providing it, and the book itself.
 *
 * @author Tony
 * @since 11/3/2013
 */
public class AvailableBook implements InventoryListItem, View.OnClickListener, Parcelable {
    private Book book;
    private Format format;
    private String link;
    private String provider;

    private volatile Activity activity;

    public static final Parcelable.Creator<AvailableBook> CREATOR = new Parcelable.Creator<AvailableBook>() {
        public AvailableBook createFromParcel(Parcel in) {
            return new AvailableBook(in);
        }

        public AvailableBook[] newArray(int size) {
            return new AvailableBook[size];
        }
    };

    private AvailableBook(Parcel parcel) {
        Log.d(getClass().getSimpleName(), "Un-parceling AvailableBook");

        book = parcel.readParcelable(Book.class.getClassLoader());
        format = parcel.readParcelable(Format.class.getClassLoader());
        link = parcel.readString();
        provider = parcel.readString();
    }

    public AvailableBook(Book book, Format format, String link, String provider) {
        this.book = book;
        this.format = format;
        this.link = link;
        this.provider = provider;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        Log.d(getClass().getSimpleName(), "Parceling AvailableBook");

        parcel.writeParcelable(book, i);
        parcel.writeParcelable(format, i);
        parcel.writeString(link);
        parcel.writeString(provider);
    }

    public Book getBook() {
        return book;
    }

    public Format getFormat() {
        return format;
    }

    public String getLink() {
        return link;
    }

    public String getProvider() {
        return provider;
    }

    @Override
    public View fillView(View view, LayoutInflater inflater) {
        Log.d(getClass().getSimpleName(), "Creating and filling view for list item: " + provider + " - " + format);
        if (view == null) {
            view = inflater.inflate(R.layout.inventory_item, null);
        }

        // While we are using the inflater, also get the activity
        activity = (Activity) inflater.getContext();

        ImageView imgType = (ImageView) view.findViewById(R.id.imageView_typeImg);
        TextView txtProvider = (TextView) view.findViewById(R.id.textView_provider);

        txtProvider.setText(getProvider());
        if (getFormat() == AvailableBook.Format.AUDIOBOOK) {
            imgType.setBackgroundResource(R.drawable.ic_audiobook);
        } else {
            imgType.setBackgroundResource(R.drawable.ic_ebook);
        }

        view.setOnClickListener(this);
        return view;
    }

    @Override
    public void onClick(View view) {
        Log.d(getClass().getSimpleName(), "InventoryItem clicked, launching link");
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setData(Uri.parse(link));
        activity.startActivity(i);
    }

    public static enum Format implements Parcelable {
        AUDIOBOOK, EBOOK;

        @Override
        public int describeContents() {
            return 0;
        }

        @Override
        public void writeToParcel(final Parcel parcel, final int flags) {
            parcel.writeInt(ordinal());
        }

        public static final Creator<Format> CREATOR = new Creator<Format>() {
            @Override
            public Format createFromParcel(final Parcel source) {
                return Format.values()[source.readInt()];
            }

            @Override
            public Format[] newArray(final int size) {
                return new Format[size];
            }
        };
    }
}


text:
/*
 * $Id: RefHash2KeysTableOf.hpp 568078 2007-08-21 11:43:25Z amassari $
 */

#if !defined(REFHASH2KEYSTABLEOF_HPP)
#define REFHASH2KEYSTABLEOF_HPP

#include <xercesc/util/HashBase.hpp>
#include <xercesc/util/IllegalArgumentException.hpp>
#include <xercesc/util/NoSuchElementException.hpp>
#include <xercesc/util/RuntimeException.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/HashXMLCh.hpp>
#include <xercesc/util/PlatformUtils.hpp>

XERCES_CPP_NAMESPACE_BEGIN

// This hash table is similar to RefHashTableOf with an additional integer as key2

//
//  Forward declare the enumerator so he can be our friend. Can you say
//  friend? Sure...
//
template <class TVal> class RefHash2KeysTableOfEnumerator;
template <class TVal> struct RefHash2KeysTableBucketElem;

//
//  This should really be a nested class, but some of the compilers we
//  have to support cannot deal with that!
//
template <class TVal> struct RefHash2KeysTableBucketElem
{
    RefHash2KeysTableBucketElem(void* key1, int key2, TVal* const value, RefHash2KeysTableBucketElem<TVal>* next)
		: fData(value), fNext(next), fKey1(key1), fKey2(key2)
        {
        }
    ~RefHash2KeysTableBucketElem() {};

    TVal*                           fData;
    RefHash2KeysTableBucketElem<TVal>*   fNext;
	void*							fKey1;
	int							fKey2;

private:
    // -----------------------------------------------------------------------
    //  Unimplemented constructors and operators
    // -----------------------------------------------------------------------
    RefHash2KeysTableBucketElem(const RefHash2KeysTableBucketElem<TVal>&);
    RefHash2KeysTableBucketElem<TVal>& operator=(const RefHash2KeysTableBucketElem<TVal>&);
};

template <class TVal> class RefHash2KeysTableOf : public XMemory
{
public:
    // -----------------------------------------------------------------------
    //  Constructors and Destructor
    // -----------------------------------------------------------------------
	// backwards compatability - default hasher is HashXMLCh
    RefHash2KeysTableOf
    (
        const unsigned int modulus
		, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager
    );
	// backwards compatability - default hasher is HashXMLCh
    RefHash2KeysTableOf
    (
        const unsigned int modulus
        , const bool adoptElems
        , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager
    );
	// if a hash function is passed in, it will be deleted when the hashtable is deleted.
	// use a new instance of the hasher class for each hashtable, otherwise one hashtable
	// may delete the hasher of a different hashtable if both use the same hasher.
    RefHash2KeysTableOf
    (
        const unsigned int modulus
        , const bool adoptElems
        , HashBase* hashBase
        , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager
    );
    ~RefHash2KeysTableOf();

    // -----------------------------------------------------------------------
    //  Element management
    // -----------------------------------------------------------------------
    bool isEmpty() const;
    bool containsKey(const void* const key1, const int key2) const;
    void removeKey(const void* const key1, const int key2);
    void removeKey(const void* const key1);
    void removeAll();
    void transferElement(const void* const key1, void* key2);

    // -----------------------------------------------------------------------
    //  Getters
    // -----------------------------------------------------------------------
    TVal* get(const void* const key1, const int key2);
    const TVal* get(const void* const key1, const int key2) const;

    MemoryManager* getMemoryManager() const;
    unsigned int   getHashModulus()   const;

    // -----------------------------------------------------------------------
    //  Putters
    // -----------------------------------------------------------------------
	void put(void* key1, int key2, TVal* const valueToAdopt);

private :
    // -----------------------------------------------------------------------
    //  Declare our friends
    // -----------------------------------------------------------------------
    friend class RefHash2KeysTableOfEnumerator<TVal>;

private:
    // -----------------------------------------------------------------------
    //  Unimplemented constructors and operators
    // -----------------------------------------------------------------------
    RefHash2KeysTableOf(const RefHash2KeysTableOf<TVal>&);
    RefHash2KeysTableOf<TVal>& operator=(const RefHash2KeysTableOf<TVal>&);

    // -----------------------------------------------------------------------
    //  Private methods
    // -----------------------------------------------------------------------
    RefHash2KeysTableBucketElem<TVal>* findBucketElem(const void* const key1, const int key2, unsigned int& hashVal);
    const RefHash2KeysTableBucketElem<TVal>* findBucketElem(const void* const key1, const int key2, unsigned int& hashVal) const;
    void initialize(const unsigned int modulus);
    void rehash();

    // -----------------------------------------------------------------------
    //  Data members
    //
    //  fAdoptedElems
    //      Indicates whether the values added are adopted or just referenced.
    //      If adopted, then they are deleted when they are removed from the
    //      hash table.
    //
    //  fBucketList
    //      This is the array that contains the heads of all of the list
    //      buckets, one for each possible hash value.
    //
    //  fHashModulus
    //      The modulus used for this hash table, to hash the keys. This is
    //      also the number of elements in the bucket list.
    //
    //  fCount
    //      The number of elements currently in the map
    //
    //  fHash
    //      The hasher for the key1 data type.
    // -----------------------------------------------------------------------
    MemoryManager*                      fMemoryManager;
    bool                                fAdoptedElems;
    RefHash2KeysTableBucketElem<TVal>** fBucketList;
    unsigned int                        fHashModulus;
    unsigned int                        fCount;
    HashBase*							fHash;
};

//
//  An enumerator for a value array. It derives from the basic enumerator
//  class, so that value vectors can be generically enumerated.
//
template <class TVal> class RefHash2KeysTableOfEnumerator : public XMLEnumerator<TVal>, public XMemory
{
public :
    // -----------------------------------------------------------------------
    //  Constructors and Destructor
    // -----------------------------------------------------------------------
    RefHash2KeysTableOfEnumerator(RefHash2KeysTableOf<TVal>* const toEnum
        , const bool adopt = false
        , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager);
    virtual ~RefHash2KeysTableOfEnumerator();

    // -----------------------------------------------------------------------
    //  Enum interface
    // -----------------------------------------------------------------------
    bool hasMoreElements() const;
    TVal& nextElement();
    void Reset();

    // -----------------------------------------------------------------------
    //  New interface
    // -----------------------------------------------------------------------
    void nextElementKey(void*&, int&);
    void setPrimaryKey(const void* key);

private :
    // -----------------------------------------------------------------------
    //  Unimplemented constructors and operators
    // -----------------------------------------------------------------------
    RefHash2KeysTableOfEnumerator(const RefHash2KeysTableOfEnumerator<TVal>&);
    RefHash2KeysTableOfEnumerator<TVal>& operator=(const RefHash2KeysTableOfEnumerator<TVal>&);

    // -----------------------------------------------------------------------
    //  Private methods
    // -----------------------------------------------------------------------
    void findNext();

    // -----------------------------------------------------------------------
    //  Data Members
    //
    //  fAdopted
    //      Indicates whether we have adopted the passed vector. If so then
    //      we delete the vector when we are destroyed.
    //
    //  fCurElem
    //      This is the current bucket bucket element that we are on.
    //
    //  fCurHash
    //      The is the current hash buck that we are working on. Once we hit
    //      the end of the bucket that fCurElem is in, then we have to start
    //      working this one up to the next non-empty bucket.
    //
    //  fToEnum
    //      The value array being enumerated.
    //
    //  fLockPrimaryKey
    //      Indicates that we are requested to iterate over the secondary keys
    //      associated with the given primary key
    //
    // -----------------------------------------------------------------------
    bool                                    fAdopted;
    RefHash2KeysTableBucketElem<TVal>*      fCurElem;
    unsigned int                            fCurHash;
    RefHash2KeysTableOf<TVal>*              fToEnum;
    MemoryManager* const                    fMemoryManager;
    const void*                             fLockPrimaryKey;
};

XERCES_CPP_NAMESPACE_END

#if !defined(XERCES_TMPLSINC)
#include <xercesc/util/RefHash2KeysTableOf.c>
#endif

#endif


text:
package com.cra.figaro.algorithm.factored.gibbs

import com.cra.figaro.algorithm.factored.factors._
import com.cra.figaro.algorithm.lazyfactored.Regular
import com.cra.figaro.util._
import scala.annotation.tailrec
import scala.collection.mutable.{LinkedHashMap, Map => MutableMap, PriorityQueue}
import com.cra.figaro.algorithm.factored.factors._
import scala.collection.mutable.{Map => MutableMap}

object BlockSampler {
  /**
   * Caches 1000 factors and uses a VE-like procedure to compute joint factors
   */
  def default = (blockInfo: Gibbs.BlockInfo) =>
    new SimpleBlockSampler(blockInfo) with Cached with FactorProduct

  /**
   * Like BlockSampler.default, but also uses Gaussian weighting scheme when there exist Element[Double]s that are results of Chains
   */
  def continuous(_variance: Double) = (blockInfo: Gibbs.BlockInfo) =>
    new SimpleBlockSampler(blockInfo) with Cached with GaussianWeight with FactorProduct { val variance = _variance }

  /**
   * Computes the joint distribution over the block by iterating through every combination of assignments of variables
   * Takes time exponential in the size of the block, and is only recommended for blocks with no determinism
   */
  def joint = (blockInfo: Gibbs.BlockInfo) =>
    new SimpleBlockSampler(blockInfo) with Cached
}

/**
 *  Class for handling sampling on a block
 *  @param blockInfo The pair containing the variables to sample and adjacent factors.
 */
abstract class BlockSampler(val blockInfo: Gibbs.BlockInfo) {
  val (block, adjacentFactors) = blockInfo

  /**
   * Get the factor from which to sample this block
   * Returns a non-logarithmic factor
   */
  def getSamplingFactor(currentSamples: MutableMap[Variable[_], Int]): Factor[Double]

  /**
   * Sample this block once
   */
  def sample(currentSamples: MutableMap[Variable[_], Int]): Unit = {
    // Get the joint factor over variables in this block conditioned on the samples
    val samplingFactor = getSamplingFactor(currentSamples)
    // Sample from the factor
    val sample = sampleFactor(samplingFactor)
    // Update currentSamples
    samplingFactor.variables.zip(sample).foreach(varAndSample => currentSamples(varAndSample._1) = varAndSample._2)
  }

  /**
   * Select a set of indices in the factor according to the weights in the factor
   * Works on a non-logarithmic factor
   */
  def sampleFactor(factor: Factor[Double]): List[Int] = {
    // This implementation closely mirrors the sampleMultinomial method in figaro.util
    val iterator = factor.getIndices.iterator
    @tailrec
    def helper(index: Double): List[Int] = {
      val next = iterator.next
      val prob = factor.get(next)
      if(index < prob) next
      else helper(index - prob)
    }
    helper(random.nextDouble)
  }
}

class SimpleBlockSampler(blockInfo: Gibbs.BlockInfo)
  extends BlockSampler(blockInfo) {

  // Work in log space to prevent underflow
  val semiring = LogSumProductSemiring()

  // Indices over possible assignments to variables in the block
  val indices = new Indices(block)

  // Maps a variable to its index in the block
  val indexMap = block.zipWithIndex.toMap

  // Override e.g. for caching
  def getSamplingFactor(currentSamples: MutableMap[Variable[_], Int]): Factor[Double] = computeSamplingFactor(currentSamples)

  def computeSamplingFactor(currentSamples: MutableMap[Variable[_], Int]): Factor[Double] = {
    // Sparse to make sampling faster when variables in the block are correlated
    val result = new SparseFactor[Double](block, List())
    // Loop through all possible assignments of variables in this block
    indices.iterator.foreach(blockIndex => {
      // An index corresponds to an assignment of values to each variable
      // The probability of selecting this index is the product of the probabilities of selecting this index in each adjacent factor
      val prob = adjacentFactors.map(factor => {
        // Have to convert block index into an index in the factor
        val factorIndex = factor.variables.map(v => if(block.contains(v)) blockIndex(indexMap(v)) else currentSamples(v))
        factor.get(factorIndex)
      }).foldLeft(semiring.one)(semiring.product)
      if(prob != semiring.zero) result.set(blockIndex, prob)
    })
    // Ensure the entries sum to 1 for sampling
    normalizeFactor(result)
  }

  /**
   * Normalize a factor so its weights sum to 1
   * Takes a logarithmic factor and returns a non-logarithmic factor
   */
  def normalizeFactor(factor: Factor[Double]): Factor[Double] = {
    val normalizingConstant = semiring.sumMany(factor.contents.values)
    if(normalizingConstant == semiring.zero) throw new ZeroTotalUnnormalizedProbabilityException
    factor.mapTo((d: Double) => math.exp(d - normalizingConstant), SumProductSemiring())
  }
}

/**
 * A VE-like procedure that works well on large but highly sparse blocks. For each adjacent factor, this
 * groups the rows of the factor into sub-factors according to possible Markov blanket assignments. Each
 * of these sub-factors is accumulated into a factor over factors, which essentially maps the Markov
 * blanket of the original factor to a conditional distribution over the block. This does not store any
 * new information, but rather takes the information in each factor and stores it in an easier to use
 * format. This trait is the reason why we currently choose ''not'' to place a Chain's parent and the
 * Chain itself in the same block, since we cannot efficiently compute the product of the sub-factors of
 * the adjacent ConditionalSelector factors. In other cases we can make use of a priority queue to
 * compute the product in an efficient order. For ConditionalSelectors there is no way to keep the
 * intermediate factors sparse, and computing this product takes exponential time.
 */
trait FactorProduct extends SimpleBlockSampler {
  lazy val mbLookupFactors = adjacentFactors.map(factor => {
    // Separate block and Markov blanket variables
    // Markov blanket consists of variables in this factor, but not in the block
    // Note how the code below allows duplicate variables in factors
    val (blockVarsAndIndices, mbVarsAndIndices) = factor.variables.zipWithIndex.partition(p => block.contains(p._1))
    val (blockVars, blockVarIndices) = blockVarsAndIndices.unzip
    val (mbVars, mbVarIndices) = mbVarsAndIndices.unzip

    // Collect the rows of the factor and group by Markov blanket assignments
    val mbMap = factor.getIndices.map(index => {
      val blockIndex = blockVarIndices.map(index(_))
      val mbIndex = mbVarIndices.map(index(_))
      (mbIndex, blockIndex, factor.get(index))
    }).groupBy(_._1)

    // The result maps a Markov blanket assignment to a sub-factor containing the rows consistent with this assignment
    val result = new SparseFactor[SparseFactor[Double]](mbVars, List())

    mbMap.foreach(pair => {
      val (mbIndex, rows) = pair
      val subResult = new SparseFactor[Double](blockVars, List(), semiring)
      // Fill the sub-factor with the possible rows in this block
      rows.foreach(row => {
        val (_, blockIndex, prob) = row
        // No reason to keep the zero probability rows when factors are sparse
        if(prob != semiring.zero) subResult.set(blockIndex, prob)
      })
      result.set(mbIndex, subResult)
    })
    result
  })

  lazy val ord = new Ordering[Factor[Double]] {
    def compare(x: Factor[Double], y: Factor[Double]): Int = {
      // Prioritize the factor with the fewest average entries per variable, i.e. most variables per entry
      val xSize = math.pow(x.contents.size, 1.0 / x.numVars.toDouble)
      val ySize = math.pow(y.contents.size, 1.0 / y.numVars.toDouble)
      math.signum(ySize - xSize).toInt
    }
  }

  override def computeSamplingFactor(currentSamples: MutableMap[Variable[_], Int]): Factor[Double] = {
    // Extract the rows from each factor and take their product
    val toMultiply: List[Factor[Double]] = mbLookupFactors.map(factor => factor.get(factor.variables.map(currentSamples(_))))
    /*
     * This priority queue helps ensure that all intermediate products remain sparse. Even though we know
     * the final product should be sparse, it's possible for intermediate factors to become exponentially
     * large in the size of the block if multiplied in the wrong order.
     */
    val queue = PriorityQueue(toMultiply:_*)(ord)
    while(queue.length > 1) {
      val product = queue.dequeue().product(queue.dequeue())
      queue.enqueue(product)
    }
    normalizeFactor(queue.dequeue())
  }
}

/**
 * Caches factors according to assignments of values in the Markov blanket, which avoids recomputing the same factors repeatedly
 * Takes advantage of the fact in Gibbs sampling, nearby samples tend to be highly correlated
 */
trait Cached extends SimpleBlockSampler {
  lazy val markovBlanket = (adjacentFactors.flatMap(_.variables).toSet -- block.toSet).toList

  // Maps an assignment of values to the Markov blanket to a distribution over variables in the block
  // Implemented as a LinkedHashMap so calling cache.head returns the oldest entry
  lazy val cache: MutableMap[List[Int], Factor[Double]] = LinkedHashMap()

  // Override to limit the cache size
  lazy val maxSize = 1000

  override def getSamplingFactor(currentSamples: MutableMap[Variable[_], Int]): Factor[Double] = {
    val key = markovBlanket.map(currentSamples(_))
    cache.get(key) match {
      // Return the cached factor
      case Some(factor) => factor
      // Otherwise compute the factor and store it, resizing the cache as necessary
      case None => {
        val factor = computeSamplingFactor(currentSamples)
        if(cache.size == maxSize) cache -= cache.head._1
        cache += key -> factor
        factor
      }
    }
  }
}

/**
 * Specialized sampling for continuous (i.e. of type Double) elements in Chains. This differs from the
 * default sampler in that it can override the zero probability states in ConditionalSelector factors.
 * The idea here is that we allow a technically inconsistent state according to the factors when the
 * value of the Chain and result element are close. This is needed for compound continuous elements
 * because sampling will always produce disjoint ranges for each result element of the Chain, which
 * creates determinism issues with the way we currently block variables. This solution has not been
 * fully tested for accuracy of results.
 */
trait DoubleWeight extends SimpleBlockSampler {
  override val adjacentFactors = blockInfo._2.map(factor => {
    factor match {
      case _: ConditionalSelector[_] => {
        val List(selector, result) = factor.variables

        val newFactor = factor.createFactor(List(selector), List(result))
        factor.getIndices.foreach(index => {
          val factorProb = factor.get(index)
          if(factorProb != semiring.zero) newFactor.set(index, factorProb)
          else {
            val List(selectorIndex, resultIndex) = index
            val selectorExtended = selector.range(selectorIndex)
            val resultExtended = result.range(resultIndex)

            (selectorExtended, resultExtended) match {
              // This pattern matching basically just ensures that both the Chain and result are Doubles
              case (Regular(List(_, Regular(chainValue: Double))), Regular(resultValue: Double)) =>
                newFactor.set(index, logWeight(chainValue, resultValue))
              case _ => newFactor.set(index, semiring.zero)
            }
          }
        })
        newFactor
      }
      case _ => factor
    }
  })

  /**
   * Function with which to assign weights in place of -Infinity. It is assumed that if
   * chainValue == resultValue, the result is 0.0. Observe that setting this function to:
   * {{{if(chainValue == resultValue) 0.0 else Double.NegativeInfinity}}}
   * has the same effect as not using the DoubleWeight trait at all.
   */
  def logWeight(chainValue: Double, resultValue: Double): Double
}

/**
 * Assigns weights to continuous variables based on a Gaussian PDF with a static variance
 */
trait GaussianWeight extends DoubleWeight {
  /**
   * The static variance used to compute the compatibility function
   */
  val variance: Double

  def logWeight(resultValue: Double, chainValue: Double): Double = {
    val diff = resultValue - chainValue
    // No need to multiply by a constant at the front because we normalize later anyways
    // Moreover, we want this to return 0.0 when diff == 0.0
    - (diff * diff) / (2.0 * variance)
  }
}


text:
package griffon.swing;

import griffon.core.ApplicationPhase;
import griffon.core.GriffonApplication;
import griffon.core.ShutdownHandler;
import griffon.util.ConfigUtils;
import griffon.util.GriffonNameUtils;
import groovy.util.ConfigObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import static java.util.Arrays.asList;

/**
 * Controls a set of windows that belong to the application.

 * Windows that are controlled by a WindowManager can be shown/hidden
 * using a custom strategy ({@code WindowDisplayHandler})
 *
 * @author Andres Almiray
 * @see griffon.swing.WindowDisplayHandler
 * @since 0.3.1
 */
public final class WindowManager implements ShutdownHandler {
    private static final Logger LOG = LoggerFactory.getLogger(WindowManager.class);
    private final SwingGriffonApplication app;
    private final WindowHelper windowHelper = new WindowHelper();
    private final ComponentHelper componentHelper = new ComponentHelper();
    private final List<Window> windows = new CopyOnWriteArrayList<Window>();
    private boolean hideBeforeHandler = false;

    /**
     * Creates a new WindowManager tied to an specific application.
     *
     * @param app an application
     */
    public WindowManager(SwingGriffonApplication app) {
        this.app = app;
    }

    /**
     * Finds a Window by name.
     *
     * @param name the value of the name: property
     * @return a Window if a match is found, null otherwise.
     */
    public Window findWindow(String name) {
        if (!GriffonNameUtils.isBlank(name)) {
            for (Window window : windows) {
                if (name.equals(window.getName())) return window;
            }
        }
        return null;
    }

    /**
     * Convenience method to get a managed Window by index.

     * Follows the Groovy conventions for overriding the [] operator.
     *
     * @param index the index of the Window to be retrieved
     * @return the Window found at the specified index
     * @throws ArrayIndexOutOfBoundsException if the index is invalid (below 0 or greater than the size
     *                                        of the managed windows list)
     */
    public Window getAt(int index) {
        return windows.get(index);
    }

    /**
     * Finds the Window that should be displayed during the Ready phase of an application.

     * The WindowManager expects a configuration flag swing.windowManager.startingWindow. If it's not
     * present in order to determine which Window will be displayed during the Ready phase. If no configuration
     * found then the WindowManager will pick the first Window found in the list of managed windows.

     * The configuration flag accepts two value types:

     *
a String that defines the name of the Window. You must make sure the Window has a matching name property.

     *
a Number that defines the index of the Window in the list of managed windows.

     *

     *
     * @return a Window that matches the given criteria or null if no match is found.
     */
    public Window getStartingWindow() {
        Window window = null;
        Object value = ConfigUtils.getConfigValue(app.getConfig(), "swing.windowManager.startingWindow");
        if (LOG.isDebugEnabled()) {
            LOG.debug("swing.windowManager.startingWindow configured to " + value);
        }
        if (value == null || value instanceof ConfigObject) {
            if (windows.size() > 0) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("No startingWindow configured, selecting the first one in the list of windows");
                }
                window = windows.get(0);
            }
        } else if (value instanceof String) {
            String windowName = (String) value;
            if (LOG.isDebugEnabled()) {
                LOG.debug("Selecting window " + windowName + " as starting window");
            }
            window = findWindow(windowName);
        } else if (value instanceof Number) {
            int index = ((Number) value).intValue();
            if (index >= 0 && index < windows.size()) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Selecting window at index " + index + " as starting window");
                }
                window = windows.get(index);
            }
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Starting Window is " + window);
        }

        return window;
    }

    /**
     * Returns the list of windows managed by this manager.
     *
     * @return a List of currently managed windows
     */
    public List<Window> getWindows() {
        return Collections.<Window>unmodifiableList(windows);
    }

    /**
     * Registers a window on this manager if an only if the window is not null
     * and it's not registered already.
     *
     * @param window the window to be added to the list of managed windows
     */
    public void attach(Window window) {
        if (window == null || windows.contains(window)) return;
        window.addWindowListener(windowHelper);
        window.addComponentListener(componentHelper);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Attaching window with name: '" + window.getName() + "' at index " + windows.size() + " " + window);
        }
        windows.add(window);
    }

    /**
     * Removes the window from the list of manages windows if and only if it
     * is registered with this manager.
     *
     * @param window the window to be removed
     */
    public void detach(Window window) {
        if (window == null) return;
        if (windows.contains(window)) {
            window.removeWindowListener(windowHelper);
            window.removeComponentListener(componentHelper);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Detaching window with name: '" + window.getName() + "' at index " + windows.indexOf(window) + " " + window);
            }
            windows.remove(window);
        }
    }

    /**
     * Shows the window.

     * This method is executed SYNCHRONOUSLY in the UI thread.
     *
     * @param window the window to show
     */
    public void show(final Window window) {
        if (window == null) return;
        app.execSync(new Runnable() {
            public void run() {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Showing window with name: '" + window.getName() + "' at index " + windows.indexOf(window) + " " + window);
                }
                app.resolveWindowDisplayHandler().show(window, app);
            }
        });
    }

    /**
     * Shows the window.

     * This method is executed SYNCHRONOUSLY in the UI thread.
     *
     * @param name the name of window to show
     */
    public void show(String name) {
        show(findWindow(name));
    }

    /**
     * Hides the window.

     * This method is executed SYNCHRONOUSLY in the UI thread.
     *
     * @param window the window to hide
     */
    public void hide(final Window window) {
        if (window == null) return;
        app.execSync(new Runnable() {
            public void run() {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Hiding window with name: '" + window.getName() + "' at index " + windows.indexOf(window) + " " + window);
                }
                app.resolveWindowDisplayHandler().hide(window, app);
            }
        });
    }

    /**
     * Hides the window.

     * This method is executed SYNCHRONOUSLY in the UI thread.
     *
     * @param name the name of window to hide
     */
    public void hide(String name) {
        hide(findWindow(name));
    }

    public boolean canShutdown(GriffonApplication app) {
        return true;
    }

    /**
     * Hides all visible windows
     */
    public void onShutdown(GriffonApplication app) {
        for (Window window : windows) {
            if (window.isVisible()) hide(window);
        }
    }

    /**
     * Should the window be hidden before all ShutdownHandlers be called ?
     *
     * @return current value
     */
    public boolean isHideBeforeHandler() {
        return hideBeforeHandler;
    }

    /**
     * Set if the window should be hidden before all ShutdownHandler be called.
     *
     * @param hideBeforeHandler new value
     */
    public void setHideBeforeHandler(boolean hideBeforeHandler) {
        this.hideBeforeHandler = hideBeforeHandler;
    }

    /**
     * WindowAdapter that optionally invokes hide() when the window is about to be closed.
     *
     * @author Andres Almiray
     */
    private class WindowHelper extends WindowAdapter {
        public void windowClosing(WindowEvent event) {
            if (app.getPhase() == ApplicationPhase.SHUTDOWN) return;
            int visibleWindows = 0;
            for (Window window : windows) {
                if (window.isVisible()) {
                    visibleWindows++;
                }
            }

            if (isHideBeforeHandler() || visibleWindows > 1) hide(event.getWindow());

            Boolean autoShutdown = (Boolean) app.getConfig().flatten().get("application.autoShutdown");
            if (visibleWindows <= 1 && autoShutdown != null && autoShutdown) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Attempting to shutdown application");
                }
                if (!app.shutdown()) show(event.getWindow());
            }
        }
    }

    /**
     * ComponentAdapter that triggers application events when a window is shown/hidden.
     *
     * @author Andres Almiray
     */
    private class ComponentHelper extends ComponentAdapter {
        /**
         * Triggers a <tt>WindowShown</tt> event with the window as sole argument
         */
        public void componentShown(ComponentEvent event) {
            app.event(GriffonApplication.Event.WINDOW_SHOWN.getName(), asList(event.getSource()));
        }

        /**
         * Triggers a <tt>WindowHidden</tt> event with the window as sole argument
         */
        public void componentHidden(ComponentEvent event) {
            app.event(GriffonApplication.Event.WINDOW_HIDDEN.getName(), asList(event.getSource()));
        }
    }
}


text:
from dronekit import connect, VehicleMode, LocationGlobal, LocationGlobalRelative
from pymavlink import mavutil # Needed for command message definitions
from Find_serial_ports import serial_ports
from Sim_sensor_Down import Sim_engage_target_Down
import time
import math

# time_sleep = input("enter time sleep: ")
time_sleep = 0.25
vel_multiplier = 1.0/(time_sleep*2.0)
import argparse
parser = argparse.ArgumentParser(description='Control Copter and send commands in GUIDED mode ')
parser.add_argument('--connect',
                   help="Vehicle connection target string. If not specified, SITL automatically started and used.")
args = parser.parse_args()

connection_string = args.connect
sitl = None

#Start SITL if no connection string specified
if not connection_string:
    import dronekit_sitl
    sitl = dronekit_sitl.start_default()
    connection_string = sitl.connection_string()

# Connect to the Vehicle
print 'Connecting to vehicle on: %s' % connection_string
vehicle = connect(connection_string, wait_ready=True)

def arm_and_takeoff(aTargetAltitude):
    """
    Arms vehicle and fly to aTargetAltitude.
    """

    print "Basic pre-arm checks"
    #Don't let the user try to arm until autopilot is ready
    vehicle.gps_0.fix_type = 3
    vehicle._ekf_poshorizabs = True
    while not vehicle.is_armable:
        print " Waiting for vehicle to initialise..."
        print "gps: ", vehicle.gps_0.fix_type
        print "EKF: ", vehicle._ekf_poshorizabs
        print "VehicleMode: ", vehicle.mode
        time.sleep(1)

    print "Arming motors"
    # Copter should arm in GUIDED mode
    vehicle.mode = VehicleMode("GUIDED")
    vehicle.armed = True

    while not vehicle.armed:
        print " Waiting for arming..."
        time.sleep(1)

    print(vehicle.mode )

    print "Taking off!"
    vehicle.mode = VehicleMode("GUIDED")
    vehicle.simple_takeoff(aTargetAltitude) # Take off to target altitude
    # Wait until the vehicle reaches a safe height before processing the goto (otherwise the command
    #  after Vehicle.simple_takeoff will execute immediately).
    while True:
        print " Altitude: ", vehicle.location.global_relative_frame.alt
        print " vehicle mode: ", vehicle.mode
        if vehicle.location.global_relative_frame.alt>=aTargetAltitude*0.95: #Trigger just below target alt.
            print "Reached target altitude"
            break
        time.sleep(1)

def send_ned_velocity(velocity_x, velocity_y, velocity_z, duration,time_to_sleep):

    msg = vehicle.message_factory.set_position_target_local_ned_encode(
        0,       # time_boot_ms (not used)
        0, 0,    # target system, target component
        mavutil.mavlink.MAV_FRAME_LOCAL_NED, # frame
        0b0000111111000111, # type_mask (only speeds enabled)
        0, 0, 0, # x, y, z positions (not used)
        velocity_x, velocity_y, velocity_z, # x, y, z velocity in m/s
        0, 0, 0, # x, y, z acceleration (not supported yet, ignored in GCS_Mavlink)
        0, 0)    # yaw, yaw_rate (not supported yet, ignored in GCS_Mavlink)

    # send command to vehicle on 1 Hz cycle
    for x in range(0,duration):
        vehicle.send_mavlink(msg)
        time.sleep(time_to_sleep)

def update_pos():
    print(vehicle.locationport_names = serial_ports()

for name in port_names:
    print(name)
    print(type(name))
    try:
        import argparse
        parser = argparse.ArgumentParser(description='Control Copter and send commands in GUIDED mode ')
        parser.add_argument('--connect', default = name)
        args = parser.parse_args()
        connection_string = args.connect
        sensor_port = port_names[1]
        break
    except:
        sensor_port = name
        import argparse
        parser = argparse.ArgumentParser(description='Control Copter and send commands in GUIDED mode ')
        parser.add_argument('--connect', default = name[0])
        args = parser.parse_args()
        connection_string = args.connect
        break.global_relative_frame)
    print "vehicle heading: ", vehicle.heading
    print "clock time: ", time.time()
    current_North= vehicle.location.local_frame.north
    current_East = vehicle.location.local_frame.east
    current_alt = vehicle.location.local_frame.east

#Arm and take of to altitude of 5 meters
arm_and_takeoff(3)
update_pos()

time.sleep(4)

update_pos()
Down_data = [1,50,75,87,95,98,99,100,105,103]
w = [9,10,11,12,14,15,19,25,30,34]
h = [9,10,11,12,14,15,19,25,30,34]

# print(len(Down_data))
# print(len(w))
# print(len(h))

move_drone = Sim_engage_target_Down(Down_data[0],w[0],h[0],vel_multiplier)
update_pos()

for n in range(0,9):
    print(n)
    move_drone = Sim_engage_target_Down(Down_data[n],w[n],h[n],vel_multiplier)
    send_ned_velocity(0,0,move_drone.Down_velocity(),1,time_sleep)
    print "vehicle Down velocity is: ", move_drone.Down_velocity()
    update_pos()
send_ned_velocity(0,0,0,1,1)

time.sleep(5)

print("Setting LAND mode...")
vehicle.mode = VehicleMode("LAND")
# Close vehicle object before exiting script
print "Close vehicle object"
vehicle.close()


text:
package com.alachisoft.tayzgrid.integrations.hibernate.cache;

import com.alachisoft.tayzgrid.integrations.hibernate.cache.srategy.util.Timestamper;
import com.alachisoft.tayzgrid.integrations.hibernate.cache.regions.TayzGridCollectionRegion;
import com.alachisoft.tayzgrid.integrations.hibernate.cache.regions.TayzGridNaturalIdRegion;
import com.alachisoft.tayzgrid.integrations.hibernate.cache.regions.TayzGridQueryResultRegion;
import com.alachisoft.tayzgrid.integrations.hibernate.cache.regions.TayzGridTimestampsRegion;
import com.alachisoft.tayzgrid.integrations.hibernate.cache.regions.TayzGridEntityRegion;
import java.util.Properties;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.spi.CacheDataDescription;
import org.hibernate.cache.spi.CollectionRegion;
import org.hibernate.cache.spi.EntityRegion;
import org.hibernate.cache.spi.NaturalIdRegion;
import org.hibernate.cache.spi.QueryResultsRegion;
import org.hibernate.cache.spi.RegionFactory;
import org.hibernate.cache.spi.TimestampsRegion;
import org.hibernate.cache.spi.access.AccessType;
import org.hibernate.cfg.Settings;

public class TayzGridRegionFactory implements RegionFactory {

    /**
     * Life cycle callback to perform any necessary initialization of the
     * underlying cache implementation(s). Called exactly once during the
     * construction of a {@link org.hibernate.internal.SessionFactoryImpl}.
     *
     * @param settings The settings in effect.
     * @param properties The defined cfg properties
     *
     * @throws org.hibernate.cache.CacheException Indicates problems starting
     * the L2 cache impl; considered as a sign to stop
     * {@link org.hibernate.SessionFactory} building.
     */
    @Override
    public void start(Settings settings, Properties properties) throws CacheException {
    }

    /**
     * Life cycle callback to perform any necessary cleanup of the underlying
     * cache implementation(s). Called exactly once during
     * {@link org.hibernate.SessionFactory#close}.
     */
    @Override
    public void stop() {
    }

    /**
     * By default should we perform "minimal puts" when using this second level
     * cache implementation?
     *
     * @return True if "minimal puts" should be performed by default; false
     * otherwise.
     */
    @Override
    public boolean isMinimalPutsEnabledByDefault() {
        return false;
    }

    /**
     * Get the default access type for {@link EntityRegion entity} and
     * {@link CollectionRegion collection} regions.
     *
     * @return This factory's default access type.
     */
    @Override
    public AccessType getDefaultAccessType() {
        return  AccessType.READ_WRITE;
    }

    /**
     * Generate a timestamp.
     * <p/>
     * This is generally used for cache content locking/unlocking purposes
     * depending upon the access-strategy being used.
     *
     * @return The generated timestamp.
     */
    @Override
    public long nextTimestamp() {
        return Timestamper.next();
    }

    /**
     * Build a cache region specialized for storing entity data.
     *
     * @param regionName The name of the region.
     * @param properties Configuration properties.
     * @param metadata Information regarding the type of data to be cached
     *
     * @return The built region
     *
     * @throws CacheException Indicates problems building the region.
     */
    @Override
    public EntityRegion buildEntityRegion(String regionName, Properties properties, CacheDataDescription metadata) throws CacheException {
        return new TayzGridEntityRegion(regionName, properties, metadata);
    }

    /**
     * Build a cache region specialized for storing NaturalId to Primary Key
     * mappings.
     *
     * @param regionName The name of the region.
     * @param properties Configuration properties.
     * @param metadata Information regarding the type of data to be cached
     *
     * @return The built region
     *
     * @throws CacheException Indicates problems building the region.
     */
    @Override
    public NaturalIdRegion buildNaturalIdRegion(String regionName, Properties properties, CacheDataDescription metadata) throws CacheException {
        return new TayzGridNaturalIdRegion(regionName, properties, metadata);
    }

    /**
     * Build a cache region specialized for storing collection data.
     *
     * @param regionName The name of the region.
     * @param properties Configuration properties.
     * @param metadata Information regarding the type of data to be cached
     *
     * @return The built region
     *
     * @throws CacheException Indicates problems building the region.
     */
    @Override
    public CollectionRegion buildCollectionRegion(String regionName, Properties properties, CacheDataDescription metadata) throws CacheException {
        return new TayzGridCollectionRegion(regionName, properties, metadata);
    }

    /**
     * Build a cache region specialized for storing query results
     *
     * @param regionName The name of the region.
     * @param properties Configuration properties.
     *
     * @return The built region
     *
     * @throws CacheException Indicates problems building the region.
     */
    @Override
    public QueryResultsRegion buildQueryResultsRegion(String regionName, Properties properties) throws CacheException {
        return new TayzGridQueryResultRegion(regionName, properties);
    }

    /**
     * Build a cache region specialized for storing update-timestamps data.
     *
     * @param regionName The name of the region.
     * @param properties Configuration properties.
     *
     * @return The built region
     *
     * @throws CacheException Indicates problems building the region.
     */
    @Override
    public TimestampsRegion buildTimestampsRegion(String regionName, Properties properties) throws CacheException {
        return new TayzGridTimestampsRegion(regionName, properties);
    }
}


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

// Syntax highlighter

	$('pre:not(.debug) code').each(function()
	{
		$(this).addClass('brush: php, class-name: highlighted');
	});

	SyntaxHighlighter.config.tagName = 'code';
	// Don't show the toolbar or line-numbers.
	SyntaxHighlighter.defaults.gutter = false;
	SyntaxHighlighter.all();

	// Any link that has the current page as its href should be class="current"
	$('a[href="'+ window.location.pathname +'"]').addClass('current');

	// Breadcrumbs magic
	$('#breadcrumb li.last').each(function()
	{
		var $this = $(this);
		var $topics = $('#topics li').has('a.current').slice(0, -1);

		$topics.each(function()
		{
			// Create a copy of the menu link
			var $crumb = $(this).children('a:first, span:not(.toggle):first').clone();

			// Insert the menu link into the breadcrumbs
			$('

').html($crumb).insertBefore($this);
		});
	});

	// Collapsing menus
	$('#topics li:has(li)').each(function()
	{
		var $this = $(this);
		var toggle = $('');
		var menu = $this.find('>ul,>ol');

		toggle.click(function()
		{
			if (menu.is(':visible'))
			{
				menu.stop(true, true).slideUp('fast');
				toggle.html('+');
			}
			else
			{
				menu.stop(true, true).slideDown('fast');
				toggle.html('–');
			}
		});

		$this.find('>span').click(function()
		{
			// Menu without a link
			toggle.click();
		});

		if ( ! $this.is(':has(a.current)'))
		{
			menu.hide();
		}

		toggle.html(menu.is(':visible') ? '–' : '+').prependTo($this);
	});

// Show source links

	$('#kodoc-main .method-source').each(function()
	{
		var self = $(this);
		var togg = $(' [show]').appendTo($('h4', self));
		var code = self.find('pre').hide();

		togg.toggle(function()
		{
			togg.html('[hide]');
			code.stop(true, true).slideDown();
		},
		function()
		{
			togg.html('[show]');
			code.stop(true, true).slideUp();
		});
	});

	// "Link to this" link that appears when you hover over a header
	$('#body')
		.find('h1[id], h2[id], h3[id], h4[id], h5[id], h6[id]')
		.append(function(){
			var $this = $(this);
			return 'link to this';
		});
});


text:
package com.lixavier.console.req;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

import java.io.Serializable;
import java.util.Date;

public class MenuReq implements Serializable {

    /**
     * @Fields serialVersionUID : 序列化版本号
     */
    private static final long serialVersionUID = 1L;

    /**
     * @Fields id : 主键id
     */
    private Integer id;

    /**
     * @Fields menuName : 菜单名称
     */
    private String menuName;

    /**
     * @Fields menuCode : 菜单编码
     */
    private String menuCode;

    /**
     * @Fields urlLink : 菜单链接
     */
    private String urlLink;

    /**
     * @Fields urlIcon : 菜单图标
     */
    private String urlIcon;

    /**
     * @Fields parentId : 父类id
     */
    private Integer parentId;

    /**
     * @Fields numOrder : 排序
     */
    private Integer numOrder;

    /**
     * @Fields memo : 备注
     */
    private String memo;

    /**
     * @Fields numLevel : 级别
     */
    private Byte numLevel;

    /**
     * @Fields isShow : 是否展示 1.是 0.否
     */
    private Boolean isShow;

    /**
     * @Fields type : 0、管理员菜单 1、用户菜单 2、首页头部菜单
     */
    private Byte type;

    /**
     * @Fields createTime : 创建时间
     */
    private Date createTime;

    /**
     * @Fields updateTime : 更新时间
     */
    private Date updateTime;

    /**
     * @Fields delStatus : 是否删除:0.未删除,1.已删除
     */
    private Boolean delStatus;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getMenuName() {
        return menuName;
    }

    public void setMenuName(String menuName) {
        this.menuName = menuName;
    }

    public String getMenuCode() {
        return menuCode;
    }

    public void setMenuCode(String menuCode) {
        this.menuCode = menuCode;
    }

    public String getUrlLink() {
        return urlLink;
    }

    public void setUrlLink(String urlLink) {
        this.urlLink = urlLink;
    }

    public String getUrlIcon() {
        return urlIcon;
    }

    public void setUrlIcon(String urlIcon) {
        this.urlIcon = urlIcon;
    }

    public Integer getParentId() {
        return parentId;
    }

    public void setParentId(Integer parentId) {
        this.parentId = parentId;
    }

    public Integer getNumOrder() {
        return numOrder;
    }

    public void setNumOrder(Integer numOrder) {
        this.numOrder = numOrder;
    }

    public String getMemo() {
        return memo;
    }

    public void setMemo(String memo) {
        this.memo = memo;
    }

    public Byte getNumLevel() {
        return numLevel;
    }

    public void setNumLevel(Byte numLevel) {
        this.numLevel = numLevel;
    }

    public Boolean getIsShow() {
        return isShow;
    }

    public void setIsShow(Boolean isShow) {
        this.isShow = isShow;
    }

    public Byte getType() {
        return type;
    }

    public void setType(Byte type) {
        this.type = type;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    public Boolean getDelStatus() {
        return delStatus;
    }

    public void setDelStatus(Boolean delStatus) {
        this.delStatus = delStatus;
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
    }
}


text:
/*
 *  Lamp IO module header
 *  Author: Maarten Vandersteegen
 */

#ifndef LAMP_IO_READ_GREEN_H
#define LAMP_IO_READ_GREEN_H

#include <pthread.h>

/* I/O pin definitions */

#ifndef LAMP_IO_RED_PIN
#define LAMP_IO_RED_PIN     (int)23
#endif

#ifndef LAMP_IO_GREEN_PIN
#define LAMP_IO_GREEN_PIN   (int)21
#endif

enum LampStateRedGreen
{
    LAMP_STATE_OFF = 0,
    LAMP_STATE_GREEN,
    LAMP_STATE_RED,
    LAMP_STATE_BLINK_GREEN,
    LAMP_STATE_BLINK_RED,
    LAMP_STATE_ERROR
};

struct LampIoRedGreen
{
    int blinking_lamp;
    int thread_is_running;
    pthread_t thread_handle;
};

/*
 *  Initialize lamp IO
 *  self:   lamp state instance
 *  return: 0 on success, -1 on failure
 */
int lamp_io_red_green_init(struct LampIoRedGreen *self);

/*
 *  Deinit lamp IO
 *  self:   lamp state instance
 */
void lamp_io_red_green_deinit(struct LampIoRedGreen *self);

/*
 *  Set the state of the lamp
 *  self:       lamp state instance
 *  lamp_state: state of the lamp
 */
void lamp_io_red_green_set_state(struct LampIoRedGreen *self, enum LampStateRedGreen lamp_state);

#endif /* LAMP_IO_RED_GREEN_H */


text:
module.exports = {
    'baseURL': process.env.BASEURL ? process.env.BASEURL.replace(/\/$/, '') : 'http://localhost:4000',
    'waitTime': isNaN(parseInt(process.env.TIMEOUT, 10)) ? 5000 : parseInt(process.env.TIMEOUT, 10),
    'before': function() {
        /* eslint-disable no-console */
        console.log('WaitTime set to', this.waitTime);
        console.log('BaseURL set to', this.baseURL);
        /* eslint-enable no-console */
    },

    'API Reference: Communications: SOAP (verify number of endpoints)': function(browser) {
        const expectedNumberOfApiEndpoints = 13;

        browser
            .maximizeWindow()
            .url(this.baseURL + '/communications/api-reference/saas/soap/')
            .waitForElementVisible('[data-reactroot]', this.waitTime)

            .elements('css selector', '.endpoint-summary', function(result) {
                /* eslint-disable no-invalid-this */
                this.assert.equal(result.value.length, expectedNumberOfApiEndpoints, 'expected ' + expectedNumberOfApiEndpoints + ' endpoints, received ' + result.value.length);
                /* eslint-enable no-invalid-this */
            })
            .end();
    },
    'API Reference: Communications: Geocoding SOAP (verify number of endpoints)': function(browser) {
        const expectedNumberOfApiEndpoints = 4;

        browser
            .maximizeWindow()
            .url(this.baseURL + '/communications/api-reference/geocode/soap/')
            .waitForElementVisible('[data-reactroot]', this.waitTime)

            .elements('css selector', '.endpoint-summary', function(result) {
                /* eslint-disable no-invalid-this */
                this.assert.equal(result.value.length, expectedNumberOfApiEndpoints, 'expected ' + expectedNumberOfApiEndpoints + ' endpoints, received ' + result.value.length);
                /* eslint-enable no-invalid-this */
            })
            .end();
    }
};


text:
  <navbar></navbar>

Discover the Perfect Location Now

      <form ng-submit="results.getByTagOnly(results.search.keywords)">
        <md-input-container class="splash-search" layout="column" layout-align="center center">
          Start Searching Here
          <input type="text" ng-model="results.search.keywords" placeholder="aspen sierras"
                 onblur="if (this.value=='') { this.placeholder='aspen sierras' }" onfocus="this.placeholder=''"
                 id="splash-search-text" autocomplete="off">
        </md-input-container>
      </form>

  What We Do

  <md-content class="splash-content-text">
    We help you explore the world and discover the perfect site for your current production by geolocating crowd-sourced
    photos from photographers world-wide. Let Scout.IO show you what the world has to offer
    from your office.

  </md-content>

  Features

  <md-content class="splash-content-text">
    We're with you every step of the way, from finding the ideal location to managing your project portfolios. We give
    you the power to quickly and easily look through hundreds of photos that meet your specific criteria. Learn more
    about a specific location as you scroll through each thumbnail then organize a portfolio for others to see and
    comment. Whether your journey for the perfect location takes you out into nature or into the city, we're here to
    help you find it faster.

      <md-card class="splash-card">
        <md-card-title>
          <md-card-title-text>

Search

          </md-card-title-text>
        </md-card-title>
        <md-card-content>

            Search for hundreds of photos using keywords or refine your search by location, radius, and date range using
            our advanced search feature. Quickly browse through the results in the sidebar or explore the map.

        </md-card-content>
      </md-card>

      <md-card class="splash-card">
        <md-card-title>
          <md-card-title-text>

Organize

          </md-card-title-text>
        </md-card-title>
        <md-card-content>

            Found a photo you like?
 Save photos in a project portfolio for future viewing. Collaborate with others
            by sharing your portfolio with team members and leaving each other helpful comments.

        </md-card-content>
      </md-card>

      <md-card class="splash-card">
        <md-card-title>
          <md-card-title-text>

Learn

          </md-card-title-text>
        </md-card-title>
        <md-card-content>

            Learn about a location as you browse through search results and view the map. Hover over a thumbnail to see
            where the photo was taken. Click on the photo to see travel duration, distance and elevation information.

        </md-card-content>
      </md-card>

  </md-content>

  Meet the Team

  <md-content class="splash-content-text">

Nissa Wollum

Product Owner

Software Engineer

Jason Sigmon

Scrum Master

Software Engineer

Paul Bhorjee

Development Team

Software Engineer

Kristine Yabut

Development Team

Software Engineer

  </md-content>


text:
Name

Email

<?php
 $get_people_details= People::model()->find(array('select'=>'name','condition'=>" email='$_GET[people_email]' "));
		$people_name = $get_people_details->name;?>

<input type="text" name="names" id="names" class="names mail_css7"  readonly="readonly" value="<?php echo $people_name;?>"/>

<input type="text" name="email" id="email" class="emails mail_css8" readonly="readonly" value="<?php echo $_GET['people_email'];?>"/>

<input type="hidden" name="box_count" id="box_count" value="0" />

<?php echo CHtml::dropDownList('people','',CHtml::listData(People::model()->findAll(),'id','name'),array('empty'=>'None','class'=>'mail_css14'));?>

Mail Template

<?php echo CHtml::dropDownList('template','',CHtml::listData(Maildoc::model()->findAll(),'id','name'),array('empty'=>'None','class'=>'mail_css14'));?>

Mail Description

<?php echo CHtml::textArea('description','',array('class'=>'mail_css15'));?>

<input type="hidden" name="id_value" id="id_value" value="<?php echo $_GET['propert_id'];?>"/>


text:
title: What Is Gitter
---
# Gitter is a chat room system popular with open source projects.

![A screenshot from Gitter](//discourse-user-assets.s3.amazonaws.com/original/2X/9/901b6ff18a83b746b1b7e96cb6907440d531d977.png)

Gitter.im is a rapidly growing startup based in London.

Free Code Camp has hundreds of Gitter rooms. These are accessible through Gitter's website, as well as desktop and mobile apps.

You can view all of our rooms and join the ones you'd like to.

Gitter allows you to share formatted code with fellow campers.


text:
(function() {
	this.HorizontalListTest = AsyncTestCase("HorizontalList");

	this.HorizontalListTest.prototype.setUp = function() {
		this.sandbox = sinon.sandbox.create();
	};

	this.HorizontalListTest.prototype.tearDown = function() {
		this.sandbox.restore();
	};
	this.HorizontalListTest.prototype.testInterface = function(queue) {
		expectAsserts(2);

		queuedApplicationInit(
			queue,
			"lib/mockapplication",
			["antie/widgets/horizontallist","antie/widgets/list"],
			function(application, HorizontalList, List) {
				assertEquals('HorizontalList should be a function', 'function', typeof HorizontalList);
				assert('HorizontalList should extend from List', new HorizontalList() instanceof List);
		});
	};
 	this.HorizontalListTest.prototype.testRender = function(queue) {
		expectAsserts(1);

		queuedApplicationInit(
				queue,
				"lib/mockapplication",
				["antie/widgets/horizontallist", "antie/widgets/list"],
				function(application, HorizontalList, List) {
					var widget = new HorizontalList("id");
					widget.setRenderMode(List.RENDER_MODE_CONTAINER);

					var device = application.getDevice();
					var listRenderSpy = this.sandbox.spy(List.prototype, 'render');
					widget.render(device);
					assert(listRenderSpy.called);
				}
		);
	};
 	this.HorizontalListTest.prototype.testNavigation = function(queue) {
		expectAsserts(7);

		queuedApplicationInit(
				queue,
				"lib/mockapplication",
				["antie/widgets/horizontallist", "antie/widgets/list", "antie/widgets/button", "antie/events/keyevent"],
				function(application, HorizontalList, List, Button, KeyEvent) {
					var list = new HorizontalList("id");
					list.setRenderMode(List.RENDER_MODE_CONTAINER);
					var button1 = new Button();
					list.appendChildWidget(button1);
					var button2 = new Button();
					list.appendChildWidget(button2);
					var button3 = new Button();
					list.appendChildWidget(button3);

					assertSame("1", button1, list.getActiveChildWidget());
					list.bubbleEvent(new KeyEvent("keydown", KeyEvent.VK_LEFT));
					assertSame("2", button1, list.getActiveChildWidget());
					list.bubbleEvent(new KeyEvent("keydown", KeyEvent.VK_RIGHT));
					assertSame("3", button2, list.getActiveChildWidget());
					list.bubbleEvent(new KeyEvent("keydown", KeyEvent.VK_RIGHT));
					assertSame("4", button3, list.getActiveChildWidget());
					list.bubbleEvent(new KeyEvent("keydown", KeyEvent.VK_RIGHT));
					assertSame("5", button3, list.getActiveChildWidget());
					list.bubbleEvent(new KeyEvent("keydown", KeyEvent.VK_UP));
					assertSame("6", button3, list.getActiveChildWidget());
					list.bubbleEvent(new KeyEvent("keydown", KeyEvent.VK_DOWN));
					assertSame("7", button3, list.getActiveChildWidget());
				}
		);
	};

	this.HorizontalListTest.prototype.testNavigationWrapped = function(queue) {
		expectAsserts(8);

		queuedApplicationInit(
				queue,
				"lib/mockapplication",
				["antie/widgets/horizontallist", "antie/widgets/list", "antie/widgets/button", "antie/events/keyevent"],
				function(application, HorizontalList, List, Button, KeyEvent) {
					var list = new HorizontalList("id");
					list.setRenderMode(List.RENDER_MODE_CONTAINER);
					list.setWrapMode( HorizontalList.WRAP_MODE_WRAP );

					var button1 = new Button();
					list.appendChildWidget(button1);
					var button2 = new Button();
					list.appendChildWidget(button2);
					var button3 = new Button();
					list.appendChildWidget(button3);

					//button1 should be selected
					assertSame("1", button1, list.getActiveChildWidget());

					//move left - assert list has wrapped to button3
					list.bubbleEvent(new KeyEvent("keydown", KeyEvent.VK_LEFT));
					assertSame("2", button3, list.getActiveChildWidget());

					//move right - assert list has wrapped back to button1
					list.bubbleEvent(new KeyEvent("keydown", KeyEvent.VK_RIGHT));
					assertSame("3", button1, list.getActiveChildWidget());

					//move right - assert list has button2 selected
					list.bubbleEvent(new KeyEvent("keydown", KeyEvent.VK_RIGHT));
					assertSame("4", button2, list.getActiveChildWidget());

					//move right - assert list has button3 selected
					list.bubbleEvent(new KeyEvent("keydown", KeyEvent.VK_RIGHT));
					assertSame("5", button3, list.getActiveChildWidget());

					//move right - assert list has wrapped to button1
					list.bubbleEvent(new KeyEvent("keydown", KeyEvent.VK_RIGHT));
					assertSame("6", button1, list.getActiveChildWidget());

					list.bubbleEvent(new KeyEvent("keydown", KeyEvent.VK_UP));
					assertSame("7", button1, list.getActiveChildWidget());

					list.bubbleEvent(new KeyEvent("keydown", KeyEvent.VK_DOWN));
					assertSame("8", button1, list.getActiveChildWidget());
				}
		);
	};
})();


text:
''' Voronoi tesselation module -- Pyvoro version (about 3 times faster than Numpy,
but needs Pyvoro to be installed in the system)
'''

pass


text:
package test.ws;

import gov.nih.nci.cacoresdk.domain.inheritance.onechild.sametable.Currency;
import gov.nih.nci.cacoresdk.domain.inheritance.onechild.sametable.Note;

import java.util.ArrayList;
import java.util.Collection;

public class OneChildSametableWSTest extends SDKWSTestBase
{
	public static String getTestCaseName()
	{
		return "One Child Same Table WS Test Case";
	}

	protected Collection<Class> getClasses() throws Exception
	{
		Collection<Class> mappedKlasses = new ArrayList<Class>();

		mappedKlasses.add(Note.class);
		mappedKlasses.add(Currency.class);

		return mappedKlasses;
	}
	/**
	 * Uses Nested Search Criteria for search
	 * Verifies that the results are returned
	 * Verifies size of the result set
	 * Verifies that none of the attribute is null
	 *
	 * @throws Exception
	 */
	public void testEntireObjectNestedSearch1() throws Exception
	{
		Class targetClass = Currency.class;
		Currency criteria = new Currency();

		Object[] results = getQueryObjectResults(targetClass, criteria);

		assertNotNull(results);
		assertEquals(3,results.length);

		for (Object obj : results){
			Currency currency = (Currency)obj;
			assertNotNull(currency);
			assertNotNull(currency.getId());
			assertNotNull(currency.getCountry());
		}
	}

	/**
	 * Uses Nested Search Criteria for search
	 * Verifies that the results are returned
	 * Verifies size of the result set
	 * Verifies that none of the attribute is null
	 *
	 * @throws Exception
	 */
	public void testEntireObjectNestedSearch2() throws Exception
	{
		Class targetClass = Note.class;
		Currency criteria = new Note();

		Object[] results = getQueryObjectResults(targetClass, criteria);

		assertNotNull(results);
		assertEquals(3,results.length);

		for (Object obj : results){
			Note note = (Note)obj;
			assertNotNull(note);
			assertNotNull(note.getId());
			assertNotNull(note.getValue());
			assertNotNull(note.getCountry());
		}
	}

	/**
	 * Uses Nested Search Criteria for inheritance as association in search
	 * Verifies that the results are returned
	 * Verifies size of the result set
	 * Verifies that none of the attribute is null
	 *
	 * @throws Exception
	 */
	public void testAssociationNestedSearch1() throws Exception
	{
		//Class targetClass = Note.class;
		Class targetClass = Currency.class;
		Currency criteria = new Currency();
		criteria.setCountry("USA");

		Object[] results = getQueryObjectResults(targetClass, criteria);

		assertNotNull(results);
		assertEquals(1,results.length);

		Note note = (Note)results[0];
		assertNotNull(note);
		assertNotNull(note.getId());
		assertNotNull(note.getCountry());
		assertNotNull(note.getValue());
	}

	/**
	 * Uses Nested Search Criteria for inheritance as association in search
	 * Verifies that the results are returned
	 * Verifies size of the result set
	 * Verifies that none of the attribute is null
	 *
	 * @throws Exception
	 */
	public void testAssociationNestedSearch2() throws Exception
	{
		Class targetClass = Currency.class;
		Note criteria = new Note();
		criteria.setCountry("Germany");

		Object[] results = getQueryObjectResults(targetClass, criteria);

		assertNotNull(results);
		assertEquals(1,results.length);

		Currency currency = (Currency)results[0];
		assertNotNull(currency);
		assertNotNull(currency.getId());
		assertNotNull(currency.getCountry());
	}
}


text:
  <link rel="stylesheet" type="text/css" href="style.css">

<link href='https://fonts.googleapis.com/css?family=Roboto:100' rel='stylesheet' type='text/css'>

    <video id="bg" src="bg.mp4" preload autoplay muted loop />

Uber Swagger

So cool you'll freeze to death

Schedule Ubers On The Daily

Schedule Ubers On Fleek

Schedule Ubers On Time

FAQ

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer pulvinar, ligula a aliquam dignissim, nunc ligula ultricies magna, nec rhoncus orci ligula ut metus. Duis non ornare felis. Suspendisse fringilla mi vel tortor porta vestibulum. Curabitur tempus purus augue, consectetur egestas lectus malesuada in. Aenean arcu mi, vulputate quis pretium eget, lacinia sit amet diam. Suspendisse augue diam, aliquam id eros eu, rhoncus tristique nunc. Quisque vestibulum, massa quis dignissim tempus, lorem nisi eleifend quam, efficitur viverra neque lorem lacinia massa. Nam pharetra tristique leo non vehicula. Donec pellentesque cursus nulla, ac ultrices tortor porttitor sit amet. Duis quis bibendum mi. Praesent nec diam diam and diam.

About D Squad

Team's Bio

Alex's Bio

Adam's Bio

Kevin's Bio

Sam's Bio

Made with ❤ in SF

    <button>Contact</button>


text:
.. title:: clang-tidy - bugprone-misplaced-widening-cast

bugprone-misplaced-widening-cast
================================

This check will warn when there is a cast of a calculation result to a bigger
type. If the intention of the cast is to avoid loss of precision then the cast
is misplaced, and there can be loss of precision. Otherwise the cast is
ineffective.

Example code:

.. code-block:: c++

    long f(int x) {
        return (long)(x * 1000);
    }

The result ``x * 1000`` is first calculated using ``int`` precision. If the
result exceeds ``int`` precision there is loss of precision. Then the result is
casted to ``long``.

If there is no loss of precision then the cast can be removed or you can
explicitly cast to ``int`` instead.

If you want to avoid loss of precision then put the cast in a proper location,
for instance:

.. code-block:: c++

    long f(int x) {
        return (long)x * 1000;
    }

Implicit casts
--------------

Forgetting to place the cast at all is at least as dangerous and at least as
common as misplacing it. If :option:`CheckImplicitCasts` is enabled the check
also detects these cases, for instance:

.. code-block:: c++

    long f(int x) {
        return x * 1000;
    }

Floating point
--------------

Currently warnings are only written for integer conversion. No warning is
written for this code:

.. code-block:: c++

    double f(float x) {
        return (double)(x * 10.0f);
    }

Options
-------

.. option:: CheckImplicitCasts

   If non-zero, enables detection of implicit casts. Default is non-zero.


text:
package net.mattorama;

import ratpack.handling.Context;
import ratpack.handling.Handler;

import static ratpack.jackson.Jackson.json;

/**
 * Created by matt on 11/27/15.
 */
public class NoidHandler implements Handler {

    @Override
    public void handle(Context ctx) throws Exception {
        Noid n = new Noid();

        ctx.render(json(n));
    }
}


text:
{-# LANGUAGE CPP, MagicHash #-}

-- | Dynamically lookup up values from modules and loading them.
module DynamicLoading (
#ifdef GHCI
        -- * Loading plugins
        loadPlugins,

        -- * Force loading information
        forceLoadModuleInterfaces,
        forceLoadNameModuleInterface,
        forceLoadTyCon,

        -- * Finding names
        lookupRdrNameInModuleForPlugins,

        -- * Loading values
        getValueSafely,
        getHValueSafely,
        lessUnsafeCoerce
#endif
    ) where

#ifdef GHCI
import Linker           ( linkModule, getHValue )
import SrcLoc           ( noSrcSpan )
import Finder           ( findImportedModule, cannotFindModule )
import TcRnMonad        ( initTcInteractive, initIfaceTcRn )
import LoadIface        ( loadPluginInterface )
import RdrName          ( RdrName, ImportSpec(..), ImpDeclSpec(..)
                        , ImpItemSpec(..), mkGlobalRdrEnv, lookupGRE_RdrName
                        , gre_name, mkRdrQual )
import OccName          ( mkVarOcc )
import RnNames          ( gresFromAvails )
import DynFlags
import Plugins          ( Plugin, CommandLineOption )
import PrelNames        ( pluginTyConName )

import HscTypes
import BasicTypes       ( HValue )
import TypeRep          ( mkTyConTy, pprTyThingCategory )
import Type             ( Type, eqType )
import TyCon            ( TyCon )
import Name             ( Name, nameModule_maybe )
import Id               ( idType )
import Module           ( Module, ModuleName )
import Panic
import FastString
import ErrUtils
import Outputable
import Exception
import Hooks

import Data.Maybe        ( mapMaybe )
import GHC.Exts          ( unsafeCoerce# )

loadPlugins :: HscEnv -> IO [(ModuleName, Plugin, [CommandLineOption])]
loadPlugins hsc_env
  = do { plugins <- mapM (loadPlugin hsc_env) to_load
       ; return $ map attachOptions $ to_load `zip` plugins }
  where
    dflags  = hsc_dflags hsc_env
    to_load = pluginModNames dflags

    attachOptions (mod_nm, plug) = (mod_nm, plug, options)
      where
        options = [ option | (opt_mod_nm, option) <- pluginModNameOpts dflags
                            , opt_mod_nm == mod_nm ]

loadPlugin :: HscEnv -> ModuleName -> IO Plugin
loadPlugin hsc_env mod_name
  = do { let plugin_rdr_name = mkRdrQual mod_name (mkVarOcc "plugin")
             dflags = hsc_dflags hsc_env
       ; mb_name <- lookupRdrNameInModuleForPlugins hsc_env mod_name
                        plugin_rdr_name
       ; case mb_name of {
            Nothing ->
                throwGhcExceptionIO (CmdLineError $ showSDoc dflags $ hsep
                          [ ptext (sLit "The module"), ppr mod_name
                          , ptext (sLit "did not export the plugin name")
                          , ppr plugin_rdr_name ]) ;
            Just name ->

     do { plugin_tycon <- forceLoadTyCon hsc_env pluginTyConName
        ; mb_plugin <- getValueSafely hsc_env name (mkTyConTy plugin_tycon)
        ; case mb_plugin of
            Nothing ->
                throwGhcExceptionIO (CmdLineError $ showSDoc dflags $ hsep
                          [ ptext (sLit "The value"), ppr name
                          , ptext (sLit "did not have the type")
                          , ppr pluginTyConName, ptext (sLit "as required")])
            Just plugin -> return plugin } } }

-- | Force the interfaces for the given modules to be loaded. The 'SDoc' parameter is used
-- for debugging (@-ddump-if-trace@) only: it is shown as the reason why the module is being loaded.
forceLoadModuleInterfaces :: HscEnv -> SDoc -> [Module] -> IO ()
forceLoadModuleInterfaces hsc_env doc modules
    = (initTcInteractive hsc_env $
       initIfaceTcRn $
       mapM_ (loadPluginInterface doc) modules)
      >> return ()

-- | Force the interface for the module containing the name to be loaded. The 'SDoc' parameter is used
-- for debugging (@-ddump-if-trace@) only: it is shown as the reason why the module is being loaded.
forceLoadNameModuleInterface :: HscEnv -> SDoc -> Name -> IO ()
forceLoadNameModuleInterface hsc_env reason name = do
    let name_modules = mapMaybe nameModule_maybe [name]
    forceLoadModuleInterfaces hsc_env reason name_modules

-- | Load the 'TyCon' associated with the given name, come hell or high water. Fails if:
--
-- * The interface could not be loaded
-- * The name is not that of a 'TyCon'
-- * The name did not exist in the loaded module
forceLoadTyCon :: HscEnv -> Name -> IO TyCon
forceLoadTyCon hsc_env con_name = do
    forceLoadNameModuleInterface hsc_env (ptext (sLit "contains a name used in an invocation of loadTyConTy")) con_name

    mb_con_thing <- lookupTypeHscEnv hsc_env con_name
    case mb_con_thing of
        Nothing -> throwCmdLineErrorS dflags $ missingTyThingError con_name
        Just (ATyCon tycon) -> return tycon
        Just con_thing -> throwCmdLineErrorS dflags $ wrongTyThingError con_name con_thing
  where dflags = hsc_dflags hsc_env

-- | Loads the value corresponding to a 'Name' if that value has the given 'Type'. This only provides limited safety
-- in that it is up to the user to ensure that that type corresponds to the type you try to use the return value at!
--
-- If the value found was not of the correct type, returns @Nothing@. Any other condition results in an exception:
--
-- * If we could not load the names module
-- * If the thing being loaded is not a value
-- * If the Name does not exist in the module
-- * If the link failed

getValueSafely :: HscEnv -> Name -> Type -> IO (Maybe a)
getValueSafely hsc_env val_name expected_type = do
  mb_hval <- lookupHook getValueSafelyHook getHValueSafely dflags hsc_env val_name expected_type
  case mb_hval of
    Nothing   -> return Nothing
    Just hval -> do
      value <- lessUnsafeCoerce dflags "getValueSafely" hval
      return (Just value)
  where
    dflags = hsc_dflags hsc_env

getHValueSafely :: HscEnv -> Name -> Type -> IO (Maybe HValue)
getHValueSafely hsc_env val_name expected_type = do
    forceLoadNameModuleInterface hsc_env (ptext (sLit "contains a name used in an invocation of getHValueSafely")) val_name
    -- Now look up the names for the value and type constructor in the type environment
    mb_val_thing <- lookupTypeHscEnv hsc_env val_name
    case mb_val_thing of
        Nothing -> throwCmdLineErrorS dflags $ missingTyThingError val_name
        Just (AnId id) -> do
            -- Check the value type in the interface against the type recovered from the type constructor
            -- before finally casting the value to the type we assume corresponds to that constructor
            if expected_type `eqType` idType id
             then do
                -- Link in the module that contains the value, if it has such a module
                case nameModule_maybe val_name of
                    Just mod -> do linkModule hsc_env mod
                                   return ()
                    Nothing ->  return ()
                -- Find the value that we just linked in and cast it given that we have proved it's type
                hval <- getHValue hsc_env val_name
                return (Just hval)
             else return Nothing
        Just val_thing -> throwCmdLineErrorS dflags $ wrongTyThingError val_name val_thing
   where dflags = hsc_dflags hsc_env

-- | Coerce a value as usual, but:
--
-- 1) Evaluate it immediately to get a segfault early if the coercion was wrong
--
-- 2) Wrap it in some debug messages at verbosity 3 or higher so we can see what happened
--    if it /does/ segfault
lessUnsafeCoerce :: DynFlags -> String -> a -> IO b
lessUnsafeCoerce dflags context what = do
    debugTraceMsg dflags 3 $ (ptext $ sLit "Coercing a value in") <+> (text context) <> (ptext $ sLit "...")
    output <- evaluate (unsafeCoerce# what)
    debugTraceMsg dflags 3 $ ptext $ sLit "Successfully evaluated coercion"
    return output

-- | Finds the 'Name' corresponding to the given 'RdrName' in the
-- context of the 'ModuleName'. Returns @Nothing@ if no such 'Name'
-- could be found. Any other condition results in an exception:
--
-- * If the module could not be found
-- * If we could not determine the imports of the module
--
-- Can only be used for looking up names while loading plugins (and is
-- *not* suitable for use within plugins).  The interface file is
-- loaded very partially: just enough that it can be used, without its
-- rules and instances affecting (and being linked from!) the module
-- being compiled.  This was introduced by 57d6798.
--
-- See Note [Care with plugin imports] in LoadIface.
lookupRdrNameInModuleForPlugins :: HscEnv -> ModuleName -> RdrName -> IO (Maybe Name)
lookupRdrNameInModuleForPlugins hsc_env mod_name rdr_name = do
    -- First find the package the module resides in by searching exposed packages and home modules
    found_module <- findImportedModule hsc_env mod_name Nothing
    case found_module of
        Found _ mod -> do
            -- Find the exports of the module
            (_, mb_iface) <- initTcInteractive hsc_env $
                             initIfaceTcRn $
                             loadPluginInterface doc mod
            case mb_iface of
                Just iface -> do
                    -- Try and find the required name in the exports
                    let decl_spec = ImpDeclSpec { is_mod = mod_name, is_as = mod_name
                                                , is_qual = False, is_dloc = noSrcSpan }
                        imp_spec = ImpSpec decl_spec ImpAll
                        env = mkGlobalRdrEnv (gresFromAvails (Just imp_spec) (mi_exports iface))
                    case lookupGRE_RdrName rdr_name env of
                        [gre] -> return (Just (gre_name gre))
                        []    -> return Nothing
                        _     -> panic "lookupRdrNameInModule"

                Nothing -> throwCmdLineErrorS dflags $ hsep [ptext (sLit "Could not determine the exports of the module"), ppr mod_name]
        err -> throwCmdLineErrorS dflags $ cannotFindModule dflags mod_name err
  where
    dflags = hsc_dflags hsc_env
    doc = ptext (sLit "contains a name used in an invocation of lookupRdrNameInModule")

wrongTyThingError :: Name -> TyThing -> SDoc
wrongTyThingError name got_thing = hsep [ptext (sLit "The name"), ppr name, ptext (sLit "is not that of a value but rather a"), pprTyThingCategory got_thing]

missingTyThingError :: Name -> SDoc
missingTyThingError name = hsep [ptext (sLit "The name"), ppr name, ptext (sLit "is not in the type environment: are you sure it exists?")]

throwCmdLineErrorS :: DynFlags -> SDoc -> IO a
throwCmdLineErrorS dflags = throwCmdLineError . showSDoc dflags

throwCmdLineError :: String -> IO a
throwCmdLineError = throwGhcExceptionIO . CmdLineError
#endif


text:
local uv = require('luv')

local function init(app)
  _G.process = require('luvem.process').globalProcess()

  -- Load Resolver
  do
    local dns = require('luvem.dns')
    dns.loadResolver()
  end

  -- EPIPE ignore
  do
    local sig = uv.new_signal()
    uv.signal_start(sig, 'sigpipe')
    uv.unref(sig)
  end

  local success, err = xpcall(function ()
		app()
    uv.run()
  end,debug.traceback)

  if success then
    -- Allow actions to run at process exit.
    require('luvem.hooks'):emit('process.exit')
    uv.run()
  else
    _G.process.exitCode = -1
    require('luvem.pretty-print').stderr:write("Uncaught exception:\n" .. err .. "\n")
  end

  uv.walk(function (handle)
    if handle and not handle:is_closing() then handle:close() end
  end)
  uv.run()

	return _G.process.exitCode
end

return init