text:
<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Trainingmodel extends CI_Model {

    /**
     * This is the constructor of a Model
     */
    function __construct() {
        // Call the Model constructor
        parent::__construct();
    }

    /**
     * will get all the records
     * @param integer $page [optional]
     * @param integer $limit [optional]
     * @return array of records
     */
    public function gettrainings() {

        $queryStr = " SELECT * from tbl_trainings";
        $queryRS = $this->db->query($queryStr);
        if ($queryRS->num_rows() > 0) {
            return $queryRS->result_array();
        } else
            return '';
    }

// for user Type
    public function getUserAccountType() {
        $queryStr = " SELECT * FROM tbl_user_account_type";
        $queryRS = $this->db->query($queryStr);
        if ($queryRS->num_rows() > 0) {
            return $queryRS->result_array();
        } else {
            return '';
        }
    }

    public function getTrainingCategories(){
		$queryStr 	= " SELECT * from tbl_category Where category_parent_id = 103";
		$queryRS	= $this->db->query($queryStr);
                if($queryRS->num_rows() >0){

		   return $queryRS->result_array();
		}else
			return '';

                }
    public function getkarmoraTraining($cat_id) {

            $queryStr = " SELECT * from tbl_trainings where fk_category_id = $cat_id and training_status = 'Active'";
            $queryRS = $this->db->query($queryStr);
            if ($queryRS->num_rows() > 0) {
                return $queryRS->result_array();
            } else
                return '';
        }
    public function getcharities() {

        $queryStr = "SELECT tbl_charity.* ,tbl_users.user_username,tbl_users.user_first_name ,tbl_users.user_last_name FROM tbl_users,tbl_charity WHERE tbl_users.pk_user_id = tbl_charity.fk_user_id";
        $queryRS = $this->db->query($queryStr);
        if ($queryRS->num_rows() > 0) {
            return $queryRS->result_array();
        } else
            return '';
    }
    public function gettriplepromtions() {

        $queryStr = " SELECT * from tbl_tripple_karmora_cash_promtion";
        $queryRS = $this->db->query($queryStr);
        if ($queryRS->num_rows() > 0) {
            return $queryRS->result_array();
        } else{
                return '';
            }
    }
    public function getCharityDetail($charityId) {
        $query = "SELECT tbl_charity.* ,tbl_users.user_username,tbl_users.user_email,tbl_users.user_first_name ,tbl_users.user_last_name FROM tbl_users,tbl_charity
                    WHERE tbl_users.pk_user_id = tbl_charity.fk_user_id
                    and tbl_charity.pk_charity_id = $charityId
                  ";
        $result = $this->db->query($query);
        if ($result->num_rows() > 0) {
            return $result->row();
        } else {
            return '';
        }
    }
}


text:
A simple text compression algorithm for English ASCII text.
The basic idea is that you have two modes when reading a compressed text: normal mode and ShiftEncoded mode.
In normal mode, simply read out the file as it is presented.
Once the FLAGCHAR is found though, switch to ShiftEncoded mode.
In this mode you continue to print out as expected however insert a space whenever you find an uppercase character and convert that character to lowercase.
This mode continues until you encounter a space or an end of line, at which point you switch back to normal mode.

redpajama_set_name: RedPajamaGithub


text:
package main

import (
	"fmt"
	"github.com/bitly/nsq/util/semver"
	"sort"
	"time"
)

type Topic struct {
	TopicName string
}
type Topics []*Topic

func TopicsForStrings(s []string) Topics {
	t := make(Topics, 0)
	for _, ss := range s {
		tt := &Topic{ss}
		t = append(t, tt)
	}
	return t
}

type Producer struct {
	Address          string          `json:"address"` //TODO: remove for 1.0
	Hostname         string          `json:"hostname"`
	BroadcastAddress string          `json:"broadcast_address"`
	TcpPort          int             `json:"tcp_port"`
	HttpPort         int             `json:"http_port"`
	Version          string          `json:"version"`
	VersionObj       *semver.Version `json:-`
	Topics           []string        `json:"topics"`
	OutOfDate        bool
}

type TopicHostStats struct {
	HostAddress  string
	Depth        int64
	MemoryDepth  int64
	BackendDepth int64
	MessageCount int64
	ChannelCount int
	Topic        string
	Aggregate    bool
}

type ChannelStats struct {
	HostAddress   string
	ChannelName   string
	Depth         int64
	MemoryDepth   int64
	BackendDepth  int64
	InFlightCount int64
	DeferredCount int64
	RequeueCount  int64
	TimeoutCount  int64
	MessageCount  int64
	ClientCount   int
	Selected      bool
	Topic         string
	HostStats     []*ChannelStats
	Clients       []*ClientInfo
	Paused        bool
}

type ClientInfo struct {
	HostAddress       string
	ClientVersion     string
	ClientIdentifier  string
	ConnectedDuration time.Duration
	InFlightCount     int
	ReadyCount        int
	FinishCount       int64
	RequeueCount      int64
	MessageCount      int64
}

type ChannelStatsList []*ChannelStats
type ChannelStatsByHost struct {
	ChannelStatsList
}
type ClientInfos []*ClientInfo
type ClientsByHost struct {
	ClientInfos
}
type TopicHostStatsList []*TopicHostStats
type TopicHostStatsByHost struct {
	TopicHostStatsList
}
type ProducerList []*Producer
type ProducersByHost struct {
	ProducerList
}

func (c ChannelStatsList) Len() int        { return len(c) }
func (c ChannelStatsList) Swap(i, j int)   { c[i], c[j] = c[j], c[i] }
func (c ClientInfos) Len() int             { return len(c) }
func (c ClientInfos) Swap(i, j int)        { c[i], c[j] = c[j], c[i] }
func (t TopicHostStatsList) Len() int      { return len(t) }
func (t TopicHostStatsList) Swap(i, j int) { t[i], t[j] = t[j], t[i] }
func (t ProducerList) Len() int            { return len(t) }
func (t ProducerList) Swap(i, j int)       { t[i], t[j] = t[j], t[i] }

func (c ChannelStatsByHost) Less(i, j int) bool {
	return c.ChannelStatsList[i].HostAddress < c.ChannelStatsList[j].HostAddress
}
func (c ClientsByHost) Less(i, j int) bool {
	if c.ClientInfos[i].ClientIdentifier == c.ClientInfos[j].ClientIdentifier {
		return c.ClientInfos[i].HostAddress < c.ClientInfos[j].HostAddress
	}
	return c.ClientInfos[i].ClientIdentifier < c.ClientInfos[j].ClientIdentifier
}
func (c TopicHostStatsByHost) Less(i, j int) bool {
	return c.TopicHostStatsList[i].HostAddress < c.TopicHostStatsList[j].HostAddress
}
func (c ProducersByHost) Less(i, j int) bool {
	return c.ProducerList[i].BroadcastAddress < c.ProducerList[j].BroadcastAddress
}

func (c *ChannelStats) AddHostStats(a *ChannelStats) {
	c.Depth += a.Depth
	c.MemoryDepth += a.MemoryDepth
	c.BackendDepth += a.BackendDepth
	c.InFlightCount += a.InFlightCount
	c.DeferredCount += a.DeferredCount
	c.RequeueCount += a.RequeueCount
	c.TimeoutCount += a.TimeoutCount
	c.MessageCount += a.MessageCount
	c.ClientCount += a.ClientCount
	if a.Paused {
		c.Paused = a.Paused
	}
	c.HostStats = append(c.HostStats, a)
	sort.Sort(ChannelStatsByHost{c.HostStats})
}

func (t *TopicHostStats) AddHostStats(a *TopicHostStats) {
	t.Aggregate = true
	t.Topic = a.Topic
	t.Depth += a.Depth
	t.MemoryDepth += a.MemoryDepth
	t.BackendDepth += a.BackendDepth
	t.MessageCount += a.MessageCount
	if a.ChannelCount > t.ChannelCount {
		t.ChannelCount = a.ChannelCount
	}
}

func (p *Producer) HTTPAddress() string {
	return fmt.Sprintf("%s:%d", p.BroadcastAddress, p.HttpPort)
}


text:
//-----------------------------------NOTICE----------------------------------//
// Some of this file is automatically filled in by a Python script.  Only    //
// add custom code in the designated areas or it will be overwritten during  //
// the next update.                                                          //
//-----------------------------------NOTICE----------------------------------//

//--BEGIN FILE HEAD CUSTOM CODE--//
//--END CUSTOM CODE--//

#include "../../include/FixLink.h"
#include "../../include/ObjectRegistry.h"
#include "../../include/NIF_IO.h"
#include "../../include/obj/NiPSysSpawnModifier.h"
using namespace Niflib;

//Definition of TYPE constant
const Type NiPSysSpawnModifier::TYPE("NiPSysSpawnModifier", &NiPSysModifier::TYPE );

NiPSysSpawnModifier::NiPSysSpawnModifier() : numSpawnGenerations((unsigned short)0), percentageSpawned(0.0f), minNumToSpawn((unsigned short)0), maxNumToSpawn((unsigned short)0), spawnSpeedChaos(0.0f), spawnDirChaos(0.0f), lifeSpan(0.0f), lifeSpanVariation(0.0f), unknownInt((int)0) {
	//--BEGIN CONSTRUCTOR CUSTOM CODE--//
	//--END CUSTOM CODE--//
}

NiPSysSpawnModifier::~NiPSysSpawnModifier() {
	//--BEGIN DESTRUCTOR CUSTOM CODE--//
	//--END CUSTOM CODE--//
}

const Type & NiPSysSpawnModifier::GetType() const {
	return TYPE;
}

NiObject * NiPSysSpawnModifier::Create() {
	return new NiPSysSpawnModifier;
}

void NiPSysSpawnModifier::Read( istream& in, list<unsigned int> & link_stack, const NifInfo & info ) {
	//--BEGIN PRE-READ CUSTOM CODE--//
	//--END CUSTOM CODE--//

	NiPSysModifier::Read( in, link_stack, info );
	NifStream( numSpawnGenerations, in, info );
	NifStream( percentageSpawned, in, info );
	NifStream( minNumToSpawn, in, info );
	NifStream( maxNumToSpawn, in, info );
	NifStream( spawnSpeedChaos, in, info );
	NifStream( spawnDirChaos, in, info );
	NifStream( lifeSpan, in, info );
	NifStream( lifeSpanVariation, in, info );
	if ( ( info.version >= 0x0A040001 ) && ( info.version <= 0x0A040001 ) ) {
		NifStream( unknownInt, in, info );
	};

	//--BEGIN POST-READ CUSTOM CODE--//
	//--END CUSTOM CODE--//
}

void NiPSysSpawnModifier::Write( ostream& out, const map<NiObjectRef,unsigned int> & link_map, list<NiObject *> & missing_link_stack, const NifInfo & info ) const {
	//--BEGIN PRE-WRITE CUSTOM CODE--//
	//--END CUSTOM CODE--//

	NiPSysModifier::Write( out, link_map, missing_link_stack, info );
	NifStream( numSpawnGenerations, out, info );
	NifStream( percentageSpawned, out, info );
	NifStream( minNumToSpawn, out, info );
	NifStream( maxNumToSpawn, out, info );
	NifStream( spawnSpeedChaos, out, info );
	NifStream( spawnDirChaos, out, info );
	NifStream( lifeSpan, out, info );
	NifStream( lifeSpanVariation, out, info );
	if ( ( info.version >= 0x0A040001 ) && ( info.version <= 0x0A040001 ) ) {
		NifStream( unknownInt, out, info );
	};

	//--BEGIN POST-WRITE CUSTOM CODE--//
	//--END CUSTOM CODE--//
}

std::string NiPSysSpawnModifier::asString( bool verbose ) const {
	//--BEGIN PRE-STRING CUSTOM CODE--//
	//--END CUSTOM CODE--//

	stringstream out;
	out << NiPSysModifier::asString();
	out << "  Num Spawn Generations:  " << numSpawnGenerations << endl;
	out << "  Percentage Spawned:  " << percentageSpawned << endl;
	out << "  Min Num to Spawn:  " << minNumToSpawn << endl;
	out << "  Max Num to Spawn:  " << maxNumToSpawn << endl;
	out << "  Spawn Speed Chaos:  " << spawnSpeedChaos << endl;
	out << "  Spawn Dir Chaos:  " << spawnDirChaos << endl;
	out << "  Life Span:  " << lifeSpan << endl;
	out << "  Life Span Variation:  " << lifeSpanVariation << endl;
	out << "  Unknown int:  " << unknownInt << endl;
	return out.str();

	//--BEGIN POST-STRING CUSTOM CODE--//
	//--END CUSTOM CODE--//
}

void NiPSysSpawnModifier::FixLinks( const map<unsigned int,NiObjectRef> & objects, list<unsigned int> & link_stack, list<NiObjectRef> & missing_link_stack, const NifInfo & info ) {
	//--BEGIN PRE-FIXLINKS CUSTOM CODE--//
	//--END CUSTOM CODE--//

	NiPSysModifier::FixLinks( objects, link_stack, missing_link_stack, info );

	//--BEGIN POST-FIXLINKS CUSTOM CODE--//
	//--END CUSTOM CODE--//
}

std::list<NiObjectRef> NiPSysSpawnModifier::GetRefs() const {
	list<Ref<NiObject> > refs;
	refs = NiPSysModifier::GetRefs();
	return refs;
}

std::list<NiObject *> NiPSysSpawnModifier::GetPtrs() const {
	list<NiObject *> ptrs;
	ptrs = NiPSysModifier::GetPtrs();
	return ptrs;
}

//--BEGIN MISC CUSTOM CODE--//
//--END CUSTOM CODE--//


text:
const socialTransformers = {
  facebook: id => `https://facebook.com/${id}`,
  twitter: id => `https://twitter.com/${id}`,
  linkedin: id => `https://www.linkedin.com/in/${id}`,
  youtube: id => `https://www.youtube.com/user/${id}`,
  instagram: id => `https://instagram.com/${id}`,
  github: id => `https://github.com/${id}`,
  bitcoin: id => `https://blockchain.info/address/${id}`,
  ethereum: id => `https://etherscan.io/address/${id}`,
};

export const transform = (socialId, id) => socialTransformers[socialId](id);

export const getFacebookShareURL = url => `https://facebook.com/sharer/sharer.php?u=${url}`;
export const getTwitterShareURL = (text, url) =>
  `https://twitter.com/intent/tweet/?text=${text}&url=${url}`;

export default [
  { id: 'facebook', icon: 'facebook', color: '#3b5998', name: 'Facebook' },
  { id: 'twitter', icon: 'twitter', color: '#00aced', name: 'Twitter' },
  { id: 'linkedin', icon: 'linkedin', color: '#007bb6', name: 'LinkedIn' },
  { id: 'youtube', icon: 'youtube', color: '#ff0202', name: 'YouTube' },
  { id: 'instagram', icon: 'instagram', color: '#8a3ab9', name: 'Instagram' },
  { id: 'github', icon: 'github', color: 'black', name: 'GitHub' },
  { id: 'bitcoin', icon: 'bitcoin', color: '#ff9900', name: 'Bitcoin' },
  { id: 'ethereum', icon: 'ethereum', color: '#3c3c3d', name: 'Ethereum' },
];


text:
package handler

import (
	"fmt"
	"github.com/MerlinDMC/dsapid"
	"github.com/MerlinDMC/dsapid/server/middleware"
	"github.com/MerlinDMC/dsapid/storage"
	"net/http"
	"runtime"
)

func CommonPing(encoder middleware.OutputEncoder, user middleware.User) (int, []byte) {
	pingResponse := map[string]interface{}{
		"ping":    "pong",
		"app":     dsapid.AppName,
		"version": dsapid.AppVersion,
		"dsapi":   true,
		"imgapi":  true,
	}

	if !user.IsGuest() {
		pingResponse["auth"] = user.GetAuthInfo()
	}

	return http.StatusOK, encoder.MustEncode(pingResponse)
}

func CommonStatus(encoder middleware.OutputEncoder, manifests storage.ManifestStorage) (int, []byte) {
	manifests_count, manifests_size := int64(0), int64(0)

	for manifest := range manifests.List() {
		manifests_count++

		for _, file := range manifest.Files {
			manifests_size += file.Size
		}
	}

	statusResponse := map[string]interface{}{
		"app":            fmt.Sprintf("%s/%s", dsapid.AppName, dsapid.AppVersion),
		"manifest_count": manifests_count,
		"manifest_size":  manifests_size,
		"num_goroutines": runtime.NumGoroutine(),
	}

	return http.StatusOK, encoder.MustEncode(statusResponse)
}


text:
<?php

namespace DanFinnie\GalleryBundle\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;

class PieceAdmin extends Admin
{
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->add('id', 'hidden')
            ->add('title')
            ->add('category')
            ->add('order')
            ->add('picture', 'sonata_type_model')
        ;
    }

    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper
        	->add('id')
            ->add('title')
            ->add('category')
            ->add('order')
            ->add('picture')
        ;
    }

    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->addIdentifier('id')
            ->add('title')
            ->add('category')
            ->add('order')
            ->add('picture')
        ;
    }
}


text:
package org.apache.felix.upnp.basedriver.util;
/*
* @author Felix Project Team
*/
public interface Constants {
	/**
	 * If this property is set on a UPnP Device means that the
	 * device service is been created by UPnP base Driver.

	 * The value of the does not carry any mean.

	 * The name of the property is "UPnP.device.import".
	 *
	 * @since 0.1
	 */
	public final static String UPNP_IMPORT = "UPnP.device.imported";

	/**
	 * Set the verbosity of the logging message of the bundle
	 *
	 * @since 0.1
	 */
	public final static String BASEDRIVER_LOG_PROP = "felix.upnpbase.log";

	/**
	 * If equal to "true" enables the CyberDomo UPnP SDK debugging messages
	 *
	 * @since 0.1
	 */
	public final static String CYBERDOMO_LOG_PROP = "felix.upnpbase.cyberdomo.log";

	/**
	 * If equal to "true" enables Exporter facility of the UPnP Base Driver
	 *
	 * @since 0.3
	 */
	public final static String EXPORTER_ENABLED_PROP = "felix.upnpbase.exporter.enabled";

	/**
	 * If equal to "true" enables Importer facility of the UPnP Base Driver
	 *
	 * @since 0.3
	 */
	public final static String IMPORTER_ENABLED_PROP = "felix.upnpbase.importer.enabled";

	/**
	 * If equal to "true" enables the use of NICs with IPv4 configured and only IPv4 addresses will be used
	 *
	 * @since 0.3
	 */
	public final static String NET_ONLY_IPV4_PROP = "felix.upnpbase.cyberdomo.net.onlyIPV4";

	/**
	 * If equal to "true" enables the use of NICs with IPv6 configured and only IPv6 addresses will be used

	 * NOTE:This property is used only on JDK 1.4 or greater
	 * @since 0.3
	 */
	public final static String NET_ONLY_IPV6_PROP = "felix.upnpbase.cyberdomo.net.onlyIPV6";

	/**
	 * If equal to "true" enables the use of Loopback addresses, either IPv6 and IPv4
	 *
	 * @since 0.3
	 */
	public final static String NET_USE_LOOPBACK_PROP = "felix.upnpbase.cyberdomo.net.loopback";

}


text:
Action

Another action

Something else here

Separated link

				    Click to Dropwdown

Action

Another action

Something else here

				            Dropdown 2

Action

Another action

Something else here

Separated link


text:
namespace IR
{

intptr_t const JnHelperMethodAddresses[] =
{
#define HELPERCALL(Name, Address, Attributes) reinterpret_cast<intptr_t>(Address),
// Because of order-of-initialization problems with the vtable address static field
// and this array, we're going to have to fill these in as we go along.
#include "JnHelperMethodList.h"
    NULL
};

intptr_t const *GetHelperMethods()
{
    return JnHelperMethodAddresses;
}

#if ENABLE_DEBUG_CONFIG_OPTIONS && defined(_CONTROL_FLOW_GUARD)
class HelperTableCheck
{
public:
    HelperTableCheck() {
        CheckJnHelperTable(JnHelperMethodAddresses);
    }
};

// Dummy global to trigger CheckJnHelperTable call at load time.
static HelperTableCheck LoadTimeHelperTableCheck;

void CheckJnHelperTable(intptr_t const* table)
{
    MEMORY_BASIC_INFORMATION memBuffer;

    // Make sure the helper table is in read-only memory for security reasons.
    SIZE_T byteCount;
    byteCount = VirtualQuery(table, &memBuffer, sizeof(memBuffer));

    Assert(byteCount);

    // Note: .rdata is merged with .text on x86.
    if (memBuffer.Protect != PAGE_READONLY && memBuffer.Protect != PAGE_EXECUTE_READ)
    {
        AssertMsg(false, "JnHelperMethodAddress table needs to be read-only for security reasons");

        Fatal();
    }
}
#endif

#ifdef ENABLE_SCRIPT_DEBUGGING
static intptr_t const helperMethodWrappers[] = {
    reinterpret_cast<intptr_t>(&Js::HelperMethodWrapper0),
    reinterpret_cast<intptr_t>(&Js::HelperMethodWrapper1),
    reinterpret_cast<intptr_t>(&Js::HelperMethodWrapper2),
    reinterpret_cast<intptr_t>(&Js::HelperMethodWrapper3),
    reinterpret_cast<intptr_t>(&Js::HelperMethodWrapper4),
    reinterpret_cast<intptr_t>(&Js::HelperMethodWrapper5),
    reinterpret_cast<intptr_t>(&Js::HelperMethodWrapper6),
    reinterpret_cast<intptr_t>(&Js::HelperMethodWrapper7),
    reinterpret_cast<intptr_t>(&Js::HelperMethodWrapper8),
    reinterpret_cast<intptr_t>(&Js::HelperMethodWrapper9),
    reinterpret_cast<intptr_t>(&Js::HelperMethodWrapper10),
    reinterpret_cast<intptr_t>(&Js::HelperMethodWrapper11),
    reinterpret_cast<intptr_t>(&Js::HelperMethodWrapper12),
    reinterpret_cast<intptr_t>(&Js::HelperMethodWrapper13),
    reinterpret_cast<intptr_t>(&Js::HelperMethodWrapper14),
    reinterpret_cast<intptr_t>(&Js::HelperMethodWrapper15),
    reinterpret_cast<intptr_t>(&Js::HelperMethodWrapper16),
};
#endif

///----------------------------------------------------------------------------
///
/// GetMethodAddress
///
///     returns the memory address of the helperMethod,
///     which can the address of debugger wrapper that intercept the original helper.
///
///----------------------------------------------------------------------------
intptr_t
GetMethodAddress(ThreadContextInfo * context, IR::HelperCallOpnd* opnd)
{
    Assert(opnd);
#ifdef ENABLE_SCRIPT_DEBUGGING
#if defined(_M_ARM32_OR_ARM64)
#define LowererMDFinal LowererMD
#else
#define LowererMDFinal LowererMDArch
#endif

    CompileAssert(_countof(helperMethodWrappers) == LowererMDFinal::MaxArgumentsToHelper + 1);

    if (opnd->IsDiagHelperCallOpnd())
    {
        // Note: all arguments are already loaded for the original helper. Here we just return the address.
        IR::DiagHelperCallOpnd* diagOpnd = (IR::DiagHelperCallOpnd*)opnd;

        if (0 <= diagOpnd->m_argCount && diagOpnd->m_argCount <= LowererMDFinal::MaxArgumentsToHelper)
        {
            return ShiftAddr(context, helperMethodWrappers[diagOpnd->m_argCount]);
        }
        else
        {
            AssertMsg(FALSE, "Unsupported arg count (need to implement).");
        }
    }
#endif
    return GetMethodOriginalAddress(context, opnd->m_fnHelper);
}

// TODO:  Remove this define once makes it into WINNT.h
#ifndef DECLSPEC_GUARDIGNORE
#if (_MSC_FULL_VER >= 170065501) && !defined(__clang__)
#define DECLSPEC_GUARDIGNORE  __declspec(guard(ignore))
#else
#define DECLSPEC_GUARDIGNORE
#endif
#endif

// We need the helper table to be in read-only memory for obvious security reasons.
// Import function ptr require dynamic initialization, and cause the table to be in read-write memory.
// Additionally, all function ptrs are automatically marked as safe CFG addresses by the compiler.
// __declspec(guard(ignore)) can be used on methods to have the compiler not mark these as valid CFG targets.
DECLSPEC_GUARDIGNORE  _NOINLINE intptr_t GetNonTableMethodAddress(ThreadContextInfo * context, JnHelperMethod helperMethod)
{
    switch (helperMethod)
    {
    //
    //  DllImport methods
    //
#if defined(_M_IX86)
    // These are internal CRT functions which don't use a standard calling convention
    case HelperDirectMath_Acos:
        return ShiftAddr(context, __libm_sse2_acos);

    case HelperDirectMath_Asin:
        return ShiftAddr(context, __libm_sse2_asin);

    case HelperDirectMath_Atan:
        return ShiftAddr(context, __libm_sse2_atan);

    case HelperDirectMath_Atan2:
        return ShiftAddr(context, __libm_sse2_atan2);

    case HelperDirectMath_Cos:
        return ShiftAddr(context, __libm_sse2_cos);

    case HelperDirectMath_Exp:
        return ShiftAddr(context, __libm_sse2_exp);

    case HelperDirectMath_Log:
        return ShiftAddr(context, __libm_sse2_log);

    case HelperDirectMath_Sin:
        return ShiftAddr(context, __libm_sse2_sin);

    case HelperDirectMath_Tan:
        return ShiftAddr(context, __libm_sse2_tan);

    case HelperAtomicStore64:
        return ShiftAddr(context, (double(*)(double))InterlockedExchange64);

    case HelperMemoryBarrier:
#ifdef _M_HYBRID_X86_ARM64
        AssertOrFailFastMsg(false, "The usage below fails to build for CHPE, and HelperMemoryBarrier is only required "
                                   "for WASM threads, which are currently disabled");
        return 0;
#else
        return ShiftAddr(context, (void(*)())MemoryBarrier);
#endif // !_M_HYBRID_X86_ARM64
#endif

    case HelperDirectMath_FloorDb:
        return ShiftStdcallAddr(context, Js::JavascriptMath::Floor);

    case HelperDirectMath_CeilDb:
        return ShiftStdcallAddr(context, Js::JavascriptMath::Ceil);

    case HelperDirectMath_FloorFlt:
        return ShiftStdcallAddr(context, Js::JavascriptMath::FloorF);

    case HelperDirectMath_CeilFlt:
        return ShiftStdcallAddr(context, Js::JavascriptMath::CeilF);

        //
        // These are statically initialized to an import thunk, but let's keep them out of the table in case a new CRT changes this
        //
    case HelperWMemCmp:
        return ShiftCdeclAddr(context, wmemcmp);

    case HelperMemCpy:
        return ShiftCdeclAddr(context, (void *(__cdecl *)(void *, void const*, size_t))memcpy);

#if defined(_M_X64) || defined(_M_ARM32_OR_ARM64)
    case HelperDirectMath_Acos:
        return ShiftCdeclAddr(context, (double(__cdecl *)(double))acos);

    case HelperDirectMath_Asin:
        return ShiftCdeclAddr(context, (double(__cdecl *)(double))asin);

    case HelperDirectMath_Atan:
        return ShiftCdeclAddr(context, (double(__cdecl *)(double))atan);

    case HelperDirectMath_Atan2:
        return ShiftCdeclAddr(context, (double(__cdecl *)(double, double))atan2);

    case HelperDirectMath_Cos:
        return ShiftCdeclAddr(context, (double(__cdecl *)(double))cos);

    case HelperDirectMath_Exp:
        return ShiftCdeclAddr(context, (double(__cdecl *)(double))exp);

    case HelperDirectMath_Log:
        return ShiftCdeclAddr(context, (double(__cdecl *)(double))log);

    case HelperDirectMath_Sin:
        return ShiftCdeclAddr(context, (double(__cdecl *)(double))sin);

    case HelperDirectMath_Tan:
        return ShiftCdeclAddr(context, (double(__cdecl *)(double))tan);
#endif

        //
        // Methods that we don't want to get marked as CFG targets as they make unprotected calls
        //

#ifdef _CONTROL_FLOW_GUARD
    case HelperGuardCheckCall:
        return  (intptr_t)__guard_check_icall_fptr; // OOP JIT: ntdll load at same address across all process
#endif

    case HelperOp_TryCatch:
        return ShiftStdcallAddr(context, Js::JavascriptExceptionOperators::OP_TryCatch);

    case HelperOp_TryFinally:
        return ShiftStdcallAddr(context, Js::JavascriptExceptionOperators::OP_TryFinally);

    case HelperOp_TryFinallyNoOpt:
        return ShiftStdcallAddr(context, Js::JavascriptExceptionOperators::OP_TryFinallyNoOpt);

        //
        // Methods that we don't want to get marked as CFG targets as they dump all registers to a controlled address
        //
    case HelperSaveAllRegistersAndBailOut:
        return ShiftStdcallAddr(context, LinearScanMD::SaveAllRegistersAndBailOut);
    case HelperSaveAllRegistersAndBranchBailOut:
        return ShiftStdcallAddr(context, LinearScanMD::SaveAllRegistersAndBranchBailOut);

#ifdef _M_IX86
    case HelperSaveAllRegistersNoSse2AndBailOut:
        return ShiftStdcallAddr(context, LinearScanMD::SaveAllRegistersNoSse2AndBailOut);
    case HelperSaveAllRegistersNoSse2AndBranchBailOut:
        return ShiftStdcallAddr(context, LinearScanMD::SaveAllRegistersNoSse2AndBranchBailOut);
#endif

    }

    Assume(UNREACHED);

    return 0;
}

///----------------------------------------------------------------------------
///
/// GetMethodOriginalAddress
///
///     returns the memory address of the helperMethod,
///     this one is never the intercepted by debugger helper.
///
///----------------------------------------------------------------------------
intptr_t GetMethodOriginalAddress(ThreadContextInfo * context, JnHelperMethod helperMethod)
{
    AssertOrFailFast(helperMethod >= 0 && helperMethod < IR::JnHelperMethodCount);
    intptr_t address = GetHelperMethods()[static_cast<WORD>(helperMethod)];
    if (address == 0)
    {
        return GetNonTableMethodAddress(context, helperMethod);
    }

    return ShiftAddr(context, address);
}

#if DBG_DUMP || defined(ENABLE_IR_VIEWER)

char16 const * const JnHelperMethodNames[] =
{
#define HELPERCALL(Name, Address, Attributes) _u("") STRINGIZEW(Name) _u(""),
#include "JnHelperMethodList.h"
    NULL
};

///----------------------------------------------------------------------------
///
/// GetMethodName
///
///     returns the string representing the name of the helperMethod.
///
///----------------------------------------------------------------------------

char16 const*
GetMethodName(JnHelperMethod helperMethod)
{
    return JnHelperMethodNames[static_cast<WORD>(helperMethod)];
}

#endif  //#if DBG_DUMP

} //namespace IR

#if DBG_DUMP || defined(ENABLE_IR_VIEWER)
const char16 *GetVtableName(VTableValue value)
{
    switch (value)
    {
#if !defined(_M_X64)
    case VtableJavascriptNumber:
        return _u("vtable JavascriptNumber");
        break;
#endif
    case VtableDynamicObject:
        return _u("vtable DynamicObject");
        break;
    case VtableInvalid:
        return _u("vtable Invalid");
        break;
    case VtablePropertyString:
        return _u("vtable PropertyString");
        break;
    case VtableJavascriptBoolean:
        return _u("vtable JavascriptBoolean");
        break;
    case VtableJavascriptArray:
        return _u("vtable JavascriptArray");
        break;
    case VtableInt8Array:
        return _u("vtable Int8Array");
        break;
    case VtableUint8Array:
        return _u("vtable Uint8Array");
        break;
    case VtableUint8ClampedArray:
        return _u("vtable Uint8ClampedArray");
        break;
    case VtableInt16Array:
        return _u("vtable Int16Array");
        break;
    case VtableUint16Array:
        return _u("vtable Uint16Array");
        break;
    case VtableInt32Array:
        return _u("vtable Int32Array");
        break;
    case VtableUint32Array:
        return _u("vtable Uint32Array");
        break;
    case VtableFloat32Array:
        return _u("vtable Float32Array");
        break;
    case VtableFloat64Array:
        return _u("vtable Float64Array");
        break;
    case VtableJavascriptPixelArray:
        return _u("vtable JavascriptPixelArray");
        break;
    case VtableInt64Array:
        return _u("vtable Int64Array");
        break;
    case VtableUint64Array:
        return _u("vtable Uint64Array");
        break;
    case VtableInt8VirtualArray:
        return _u("vtable Int8VirtualArray");
        break;
    case VtableUint8VirtualArray:
        return _u("vtable Uint8VirtualArray");
        break;
    case VtableUint8ClampedVirtualArray:
        return _u("vtable Uint8ClampedVirtualArray");
        break;
    case VtableInt16VirtualArray:
        return _u("vtable Int16VirtualArray");
        break;
    case VtableUint16VirtualArray:
        return _u("vtable Uint16VirtualArray");
        break;
    case VtableInt32VirtualArray:
        return _u("vtable Int32VirtualArray");
        break;
    case VtableUint32VirtualArray:
        return _u("vtable Uint32VirtualArray");
        break;
    case VtableFloat32VirtualArray:
        return _u("vtable Float32VirtualArray");
        break;
    case VtableFloat64VirtualArray:
        return _u("vtable Float64VirtualArray");
        break;
    case VtableBoolArray:
        return _u("vtable BoolArray");
        break;
    case VtableCharArray:
        return _u("vtable CharArray");
        break;
    case VtableNativeIntArray:
        return _u("vtable NativeIntArray");
        break;
    case VtableNativeFloatArray:
        return _u("vtable NativeFloatArray");
        break;
    case VtableJavascriptNativeIntArray:
        return _u("vtable JavascriptNativeIntArray");
        break;
    case VtableJavascriptRegExp:
        return _u("vtable JavascriptRegExp");
        break;
    case VtableStackScriptFunction:
        return _u("vtable StackScriptFunction");
        break;
    case VtableScriptFunctionWithInlineCacheAndHomeObj:
        return _u("vtable ScriptFunctionWithInlineCacheAndHomeObj");
        break;
    case VtableScriptFunctionWithInlineCacheHomeObjAndComputedName:
        return _u("vtable ScriptFunctionWithInlineCacheHomeObjAndComputedName");
        break;
    case VtableConcatStringMulti:
        return _u("vtable ConcatStringMulti");
        break;
    case VtableCompoundString:
        return _u("vtable CompoundString");
        break;
    default:
        Assert(false);
        break;
    }

    return _u("vtable unknown");
}
#endif

namespace HelperMethodAttributes
{

// Position: same as in JnHelperMethod enum.
// Value: one or more of OR'ed HelperMethodAttribute values.
static const BYTE JnHelperMethodAttributes[] =
{
#define HELPERCALL(Name, Address, Attributes) Attributes,
#include "JnHelperMethodList.h"
};

// Returns true if the helper can throw non-OOM / non-SO exception.
bool CanThrow(IR::JnHelperMethod helper)
{
    return (JnHelperMethodAttributes[helper] & AttrCanThrow) != 0;
}

bool IsInVariant(IR::JnHelperMethod helper)
{
    return (JnHelperMethodAttributes[helper] & AttrInVariant) != 0;
}

bool CanBeReentrant(IR::JnHelperMethod helper)
{
    return (JnHelperMethodAttributes[helper] & AttrCanNotBeReentrant) == 0;
}

bool TempObjectProducing(IR::JnHelperMethod helper)
{
    return (JnHelperMethodAttributes[helper] & AttrTempObjectProducing) != 0;
}

#ifdef DBG_DUMP
struct ValidateHelperHeaders
{
    ValidateHelperHeaders()
    {
#define HELPERCALL(Name, Address, Attributes)
#define HELPERCALLCHK(Name, Address, Attributes) \
        Assert(JitHelperUtils::helper##Name##_implemented);
#include "../Backend/JnHelperMethodList.h"
    }
};
ValidateHelperHeaders validateHelperHeaders;
#endif

} //namespace HelperMethodAttributes


text:
//
// Copyright (c) KU Leuven Research and Development - iMinds-DistriNet
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Administrative Contact: dnet-project-office@cs.kuleuven.be
// Technical Contact: stefan.walraven@cs.kuleuven.be
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Ninject.Modules;
using TravelApplicationNET.Travel.Features.Price;
using TravelApplicationNET.Travel.Management;

namespace TravelApplicationNET.Travel.Modules
{
    public class TravelServiceModule : NinjectModule
    {
        public override void Load()
        {
            this.Bind<IBookingService>().To<BookingService>();
            this.Bind<IPriceCalculation>().To<DefaultPriceCalculation>();
            this.Bind<IManagementService>().To<ManagementService>();
        }
    }
}


text:
title: "Fall is Here!"
date: "2017-10-06 00:00:00 -06:00"
categories:
- whats-blooming
layout: "post"
blog-banner: "whats-blooming-now-fall.jpg"
post-date: "October, 06 2017"
post-time: "6:02 AM"
blog-image: "2017-10-06-wbn.jpg"
published: true
---

Fall is definitely here. The days are shorter, the temperatures are cooler and the leaves have changed. On your way to check out the beautiful colors in our mountains, stop by Red Butte Garden and wander through ours while viewing the huge variety of fall-blooming plants.

Red Butte Garden's conifers really make the fall colors of the deciduous trees pop!

Red Heart Rose of Sharon    Hibiscus syriacus  'Red Heart'

This dandy Rose of Sharon variety can be found in the Water Saver terrace of the Water Conservation Garden.

Dwarf Rubber Rabbitbrush    Chrysothamnus nauseosus  var.  nauseosus

A native variety of Rabbitbrush, this little guy stays nice and compact.

Iris    Iris germanica cv.

While most Iris cultivars only bloom once, there are a few that are reblooming!

Painted Lady Butterfly    Vanessa cardui

Don't cut back your fading flowers yet!! Painted Lady Butterflies could sure use the extra nectar on their migration south.

Don't miss this view. It won't last too much longer.

Garden After Dark isn't far away. Check our calendar for days and times.

Photos by Jason W. Baker


text:
using System;

namespace Umbraco.Web.Mvc
{
    /// <summary>
    /// Represents some metadata about the controller
    /// </summary>
    internal class PluginControllerMetadata
    {
        internal Type ControllerType { get; set; }
        internal string ControllerName { get; set; }
        internal string ControllerNamespace { get; set; }
        internal string AreaName { get; set; }

        /// <summary>
        /// This is determined by another attribute [IsBackOffice] which slightly modifies the route path
        /// allowing us to determine if it is indeed a back office request or not
        /// </summary>
        internal bool IsBackOffice { get; set; }
    }
}


text:
name: cljs.core/not-empty
see also:
  - cljs.core/empty
---

## Summary

## Details

Returns nil if `coll` is empty, else returns `coll`.

## Examples


text:
package notaql.engines.mongodb.model.vdata;

import notaql.model.EvaluationException;
import notaql.model.vdata.FunctionVData;
import notaql.model.vdata.VData;

/**
 * Provides the option to hash input
 */
public class HashFunctionVData implements FunctionVData {
    private static final long serialVersionUID = -3148243399501926262L;
    private VData path;

    public VData getPath() {
        return path;
    }

    @Override
    public void init(VData... vDatas) {
        if(vDatas.length != 1)
            throw new EvaluationException("HASH expects one parameter which specifies the path to the list");

        this.path = vDatas[0];
    }

    @Override
    public String toString() {
        return "HASH(" + path.toString() + ")";
    }
}


text:
import sys
import unittest
import random
from mongodb_store.message_store import MessageStoreProxy
from std_msgs.msg import String
from geometry_msgs.msg import Pose, Point, Quaternion
import rospy

class TestMessageStoreProxy(unittest.TestCase):

    def test_add_message(self):
        msg_store = MessageStoreProxy()
        POSE_NAME = "__test__pose__"
        p = Pose(Point(0, 1, 2), Quaternion(0, 0, 0, 1))

        # insert a pose object with a name
        msg_store.insert_named(POSE_NAME, p)

        # get it back with a name
        stored, meta = msg_store.query_named(POSE_NAME, Pose._type)

        self.assertIsInstance(stored, Pose)
        self.assertEqual(stored.position.x, p.position.x)
        self.assertEqual(stored.position.y, p.position.y)
        self.assertEqual(stored.position.z, p.position.z)

        self.assertEqual(stored.orientation.x, p.orientation.x)
        self.assertEqual(stored.orientation.y, p.orientation.y)
        self.assertEqual(stored.orientation.z, p.orientation.z)
        self.assertEqual(stored.orientation.w, p.orientation.w)

        p.position.x = 666

        msg_store.update_named(POSE_NAME, p)

        # get it back with a name
        updated = msg_store.query_named(POSE_NAME, Pose._type)[0]

        self.assertEqual(updated.position.x, p.position.x)

        # # try to get it back with an incorrect name
        wrong_name = "thid name does not exist in the datacentre"
        none_item = msg_store.query_named(wrong_name, Pose._type)[0]
        self.assertIsNone(none_item)

        # # get all non-existant typed objects, so get an empty list back
        none_query = msg_store.query( "not my type")
        self.assertEqual(len(none_query), 0)

        # add 100 query and sort by date inserted.
        for i in range(100):
            p = Pose(Point(0, 0, 0), Quaternion(i, 0, 100, 1))
            msg_store.insert(p)

        result = msg_store.query(Pose._type, message_query={ 'orientation.z': {'$gt': 10} }, sort_query=[("$natural", -1)])
        self.assertEqual(len(result), 100)
        self.assertEqual(result[0][0].orientation.x, 99)

        # get documents with limit
        result_limited = msg_store.query(Pose._type, message_query={'orientation.z': {'$gt': 10} }, sort_query=[("$natural", 1)], limit=10)
        self.assertEqual(len(result_limited), 10)
        self.assertListEqual([int(doc[0].orientation.x) for doc in result_limited], range(10))

	#get documents without "orientation" field
	result_no_id = msg_store.query(Pose._type, message_query={}, projection_query={"orientation": 0})
        for doc in result_no_id:
		self.assertEqual(int(doc[0].orientation.z),0 )

        # must remove the item or unittest only really valid once
        print meta["_id"]
        print str(meta["_id"])
        deleted = msg_store.delete(str(meta["_id"]))
        self.assertTrue(deleted)

    def test_add_message_no_wait(self):
        msg_store = MessageStoreProxy()
        count_before_insert = len(msg_store.query(Pose._type, meta_query={ "no_wait": True }))
        p = Pose(Point(0, 1, 2), Quaternion(0, 0, 0, 1))
        for i in range(10):
            msg_store.insert(p, meta={"no_wait": True }, wait=False)
        rospy.sleep(2)
        count_after_insert = len(msg_store.query(Pose._type, meta_query={ "no_wait": True }))
        self.assertTrue(count_after_insert > count_before_insert)

    def test_non_ascii(self):
        msg_store = MessageStoreProxy()
        msg = String(data="こんにちは")  # non ascii string
        doc_id = msg_store.insert(msg)

        try:
            qmsg, _ = msg_store.query_id(doc_id, String._type)
            self.assertEqual(msg.data, qmsg.data)
        except rospy.service.ServiceException:
            self.fail("non ascii unicode string cannot be queried")

if __name__ == '__main__':
    import rostest
    PKG = 'mongodb_store'
    rospy.init_node('test_message_store_proxy')
    rostest.rosrun(PKG, 'test_message_store_proxy', TestMessageStoreProxy)


text:
using System.Windows;

namespace SocialStream.Helpers
{
    /// <summary>
    /// Provides a "Flipped" attached property, used on flipping ScatterViewItems.
    /// </summary>
    public static class ScatterFlip
    {
        #region IsFlipped

        /// <summary>
        /// Gets the value of the IsFlipped attached property.
        /// </summary>
        /// <param name="obj">The element from which to read the property value.</param>
        /// <returns>The value of the IsFlipped attached property.</returns>
        public static bool GetIsFlipped(DependencyObject obj)
        {
            if (obj == null)
            {
                return false;
            }

            return (bool)obj.GetValue(IsFlippedProperty);
        }

        /// <summary>
        /// Sets the value of the IsFlipped attached property.
        /// </summary>
        /// <param name="obj">The element on which to set the IsFlipped attached property.</param>
        /// <param name="value">The property value to set.</param>
        public static void SetIsFlipped(DependencyObject obj, bool value)
        {
            if (obj == null)
            {
                return;
            }

            obj.SetValue(IsFlippedProperty, value);
        }

        /// <summary>
        /// Identifies the IsFlipped attached property.
        /// </summary>
        public static readonly DependencyProperty IsFlippedProperty = DependencyProperty.RegisterAttached("IsFlipped", typeof(bool), typeof(ScatterFlip), new UIPropertyMetadata(false));

        #endregion
    }
}


text:
// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace Burrows.Testing.Factories
{
    using System;
    using ScenarioBuilders;
    using Scenarios;
    using TestInstanceConfigurators;

    public interface IConsumerTestFactory<TScenario, TConsumer>
        where TConsumer : class
        where TScenario : ITestScenario
    {
        ConsumerTest<TScenario, TConsumer> New(Action<IConsumerTestInstanceConfigurator<TScenario, TConsumer>> configureTest);
    }

	public class ConsumerTestFactory<TScenario, TConsumer> :
		IConsumerTestFactory<TScenario, TConsumer>
		where TConsumer : class, IConsumer
	    where TScenario : ITestScenario
	{
		readonly Func<IScenarioBuilder<TScenario>> _scenarioBuilderFactory;

		public ConsumerTestFactory(Func<IScenarioBuilder<TScenario>> scenarioBuilderFactory)
		{
			_scenarioBuilderFactory = scenarioBuilderFactory;
		}

		public ConsumerTest<TScenario, TConsumer> New(
			Action<IConsumerTestInstanceConfigurator<TScenario, TConsumer>> configureTest)
		{
			var configurator = new ConsumerTestInstanceConfigurator<TScenario, TConsumer>(_scenarioBuilderFactory);

			configureTest(configurator);

			return configurator.Build();
		}
	}
}


text:
@if(session()->has('errors'))

        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>

Following errors occurred:

            @foreach($errors->all() as $error)

{{ $error }}

            @endforeach

@endif


text:
module SpatialFeatures
  module Importers
    class Geomark < KMLFile
      def initialize(geomark, **options)
        super geomark_url(geomark), **options
      end

      private

      def geomark_url(geomark)
        "http://apps.gov.bc.ca/pub/geomark/geomarks/#{geomark}/parts.kml?srid=4326"
      end
    end
  end
end


text:
@SuppressWarnings("UnusedDeclaration")
public class SubClassOfClassImplementingExternalizable extends ClassImplementingExternalizable {
}


text:
###########################
#
# Python rewrite of multilateration technique by André Andersen in his [blog post](http://blog.andersen.im/2012/07/signal-emitter-positioning-using-multilateration).
#
############################

from numpy import *
from numpy.linalg import *
import json
#speed of sound in medium
v = 3450
numOfDimensions = 3
nSensors = 5
region = 3
sensorRegion = 2

#choose a random sensor location
emitterLocation = region * ( random.random_sample(numOfDimensions) - 0.5 )
sensorLocations = [ sensorRegion * ( random.random_sample(numOfDimensions)-0.5 ) for n in range(nSensors) ]
p = matrix( sensorLocations ).T

#Time from emitter to each sensor
sensorTimes = [ sqrt( dot(location-emitterLocation,location-emitterLocation) ) / v for location in sensorLocations ]

c = argmin(sensorTimes)
cTime = sensorTimes[c]

#sensors delta time relative to sensor c
t = sensorDeltaTimes = [ sensorTime - cTime for sensorTime in sensorTimes ]

ijs = range(nSensors)
del ijs[c]

A = zeros([nSensors-1,numOfDimensions])
b = zeros([nSensors-1,1])
iRow = 0
rankA = 0

for i in ijs:
	for j in ijs:
		A[iRow,:] = 2*( v*(t[j])*(p[:,i]-p[:,c]).T - v*(t[i])*(p[:,j]-p[:,c]).T )
		b[iRow] = v*(t[i])*(v*v*(t[j])**2-p[:,j].T*p[:,j]) + \
		(v*(t[i])-v*(t[j]))*p[:,c].T*p[:,c] + \
		v*(t[j])*(p[:,i].T*p[:,i]-v*v*(t[i])**2)
		rankA = matrix_rank(A)
		if rankA >= numOfDimensions :
			break
		iRow += 1
	if rankA >= numOfDimensions:
		break

calculatedLocation = asarray( lstsq(A,b)[0] )[:,0]

print "Emitter location: %s " % emitterLocation
print "Calculated position of emitter: %s " % calculatedLocation


text:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Caching;

namespace Carrotware.CMS.DBUpdater {

	public class DatabaseUpdate {
		public static SqlException LastSQLError { get; set; }

		public static string CurrentDbVersion { get { return "20200915"; } }

		public static string DbVersion00 { get { return "20150829"; } }

		public static string DbVersion01 { get { return "20151001"; } }

		public static string DbVersion02 { get { return "20200915"; } }

		public DatabaseUpdate() { }

		public DatabaseUpdate(bool clearTest) {
			if (clearTest) {
				DatabaseUpdate.LastSQLError = null;
				TestDatabaseWithQuery();
			}
		}

		private void TestDatabaseWithQuery() {
			DatabaseUpdate.LastSQLError = null;

			string query = "select top 10 table_name, column_name, ordinal_position from [INFORMATION_SCHEMA].[COLUMNS] as isc " +
					" where isc.table_name like 'carrot%' " +
					" order by isc.table_name, isc.ordinal_position, isc.column_name";

			DataTable table1 = GetTestData(query);
		}

		private static string SetConn() {
			string _connStr = String.Empty;

			if (ConfigurationManager.ConnectionStrings["CarrotwareCMSConnectionString"] != null) {
				ConnectionStringSettings conString = ConfigurationManager.ConnectionStrings["CarrotwareCMSConnectionString"];
				_connStr = conString.ConnectionString;
			}

			return _connStr;
		}

		private static string ContentKey = "cms_SiteSetUpSQLState";

		public static bool FailedSQL {
			get {
				bool c = false;
				try { c = (bool)HttpContext.Current.Cache[ContentKey]; } catch { }
				return c;
			}
			set {
				HttpContext.Current.Cache.Insert(ContentKey, value, null, DateTime.Now.AddMinutes(3), Cache.NoSlidingExpiration);
			}
		}

		public static void ResetFailedSQL() {
			HttpContext.Current.Cache.Insert(ContentKey, "False", null, DateTime.Now.AddMilliseconds(10), Cache.NoSlidingExpiration);
			HttpContext.Current.Cache.Remove(ContentKey);
		}

		public static bool SystemNeedsChecking(Exception ex) {
			//assumption is database is probably empty / needs updating, so trigger the under construction view

			if (ex is SqlException && ex != null) {
				string msg = ex.Message.ToLower();
				if (ex.InnerException != null) {
					msg += "\r\n" + ex.InnerException.Message.ToLower();
				}
				if (msg.Contains("the server was not found")) {
					return false;
				}

				if (msg.Contains("invalid object name")
					//|| msg.Contains("no process is on the other end of the pipe")
					|| msg.Contains("invalid column name")
					|| msg.Contains("could not find stored procedure")
					|| msg.Contains("not found")) {
					return true;
				}
			}

			return false;
		}

		public DatabaseUpdateResponse CreateCMSDatabase() {
			DatabaseUpdateResponse res = new DatabaseUpdateResponse();

			if (!DatabaseUpdate.FailedSQL) {
				bool bTestResult = SQLUpdateNugget.EvalNuggetKey("DoCMSTablesExist");

				if (!bTestResult) {
					res.LastException = ExecFileContents("Carrotware.CMS.DBUpdater.DataScripts.CREATE01.sql", false);
					res.Response = "Created Database";
					res.RanUpdate = true;
					// change version key when the DB creation is re-scripted
					SetDbSchemaVersion(DatabaseUpdate.DbVersion01);
					return res;
				}

				res.Response = "Database Already Created";
				return res;
			}

			res.Response = "*** Database Access Failed ***";
			return res;
		}

		public bool DoCMSTablesExist() {
			if (!DatabaseUpdate.FailedSQL) {
				bool bTestResult = SQLUpdateNugget.EvalNuggetKey("DoCMSTablesExist");

				if (bTestResult) {
					return bTestResult;
				}
			}

			return false;
		}

		public List<DatabaseUpdateMessage> MergeMessages(List<DatabaseUpdateMessage> lstMsgs1, List<DatabaseUpdateMessage> lstMsgs2) {
			if (lstMsgs1 == null) {
				lstMsgs1 = new List<DatabaseUpdateMessage>();
			}

			if (lstMsgs2 == null) {
				lstMsgs2 = new List<DatabaseUpdateMessage>();
			}

			if (lstMsgs2.Any()) {
				int iPad = lstMsgs1.Count;
				lstMsgs2.ToList().ForEach(x => x.Order = (x.Order + iPad));

				lstMsgs1 = lstMsgs1.Union(lstMsgs2).ToList();
			}

			return lstMsgs1;
		}

		public List<DatabaseUpdateMessage> HandleResponse(List<DatabaseUpdateMessage> lstMsgs, Exception ex) {
			if (lstMsgs == null) {
				lstMsgs = new List<DatabaseUpdateMessage>();
			}

			DatabaseUpdateResponse execMessage = new DatabaseUpdateResponse();
			execMessage.LastException = ex;
			execMessage.Response = "An error occurred.";

			HandleResponse(lstMsgs, "Error: ", execMessage);

			return lstMsgs;
		}

		public List<DatabaseUpdateMessage> HandleResponse(List<DatabaseUpdateMessage> lstMsgs, string sMsg) {
			if (lstMsgs == null) {
				lstMsgs = new List<DatabaseUpdateMessage>();
			}

			HandleResponse(lstMsgs, sMsg, null);

			return lstMsgs;
		}

		public List<DatabaseUpdateMessage> HandleResponse(List<DatabaseUpdateMessage> lstMsgs, string sMsg, DatabaseUpdateResponse execMessage) {
			if (lstMsgs == null) {
				lstMsgs = new List<DatabaseUpdateMessage>();
			}

			DatabaseUpdateMessage item = new DatabaseUpdateMessage();

			if (!String.IsNullOrEmpty(sMsg)) {
				item.Message = sMsg;

				if (execMessage != null) {
					item.AlteredData = execMessage.RanUpdate;
					item.Response = execMessage.Response;

					if (execMessage.LastException != null && !String.IsNullOrEmpty(execMessage.LastException.Message)) {
						item.HasException = true;
						item.ExceptionText = execMessage.LastException.Message;
						if (execMessage.LastException.InnerException != null && !String.IsNullOrEmpty(execMessage.LastException.InnerException.Message)) {
							item.InnerExceptionText = execMessage.LastException.InnerException.Message;
						}
					}
				}
			}

			item.Order = lstMsgs.Count + 1;

			lstMsgs.Add(item);

			return lstMsgs;
		}

		public string BuildUpdateString(int iCount) {
			return "Update " + (iCount).ToString() + " ";
		}

		private static object updateLocker = new Object();

		public DatabaseUpdateStatus PerformUpdates() {
			DatabaseUpdateStatus status = new DatabaseUpdateStatus();
			bool bUpdate = true;
			List<DatabaseUpdateMessage> lst = new List<DatabaseUpdateMessage>();

			lock (updateLocker) {
				if (!DoCMSTablesExist()) {
					HandleResponse(lst, "Create Database", CreateCMSDatabase());
				} else {
					HandleResponse(lst, "Database already exists");
				}

				bUpdate = DatabaseNeedsUpdate();

				DataInfo ver = GetDbSchemaVersion();

				int iUpdate = 1;

				if (bUpdate || (ver.DataValue != DatabaseUpdate.CurrentDbVersion)) {
					if (ver.DataValue != DatabaseUpdate.CurrentDbVersion) {
						ver = GetDbSchemaVersion();

						if (ver.DataValue != DatabaseUpdate.CurrentDbVersion) {
							ver = GetDbSchemaVersion();

							if (ver.DataValue.StartsWith("2015") || ver.DataValue.StartsWith("2016")) {
								HandleResponse(lst, BuildUpdateString(iUpdate++), AlterStep01());
								HandleResponse(lst, BuildUpdateString(iUpdate++), AlterStep02());
							}
						}
					} else {
						HandleResponse(lst, "Database up-to-date [" + ver.DataValue + "] ");
					}
				} else {
					HandleResponse(lst, "Database up-to-date [" + ver.DataValue + "] ");
				}

				ResetFailedSQL();

				ResetSQLState();

				bUpdate = DatabaseNeedsUpdate();

				status.NeedsUpdate = bUpdate;
				status.Messages = lst;
			}

			return status;
		}

		public bool TableExists(string testTableName) {
			string testQuery = "select * from [INFORMATION_SCHEMA].[COLUMNS] where table_name = @TableName ";
			List<SqlParameter> parms = new List<SqlParameter>();

			SqlParameter parmKey = new SqlParameter();
			parmKey.ParameterName = "@TableName";
			parmKey.SqlDbType = SqlDbType.VarChar;
			parmKey.Size = 2000;
			parmKey.Direction = ParameterDirection.Input;
			parmKey.Value = testTableName;

			parms.Add(parmKey);

			DataTable table1 = GetTestData(testQuery, parms);

			if (table1.Rows.Count < 1) {
				return false;
			}

			return true;
		}

		public List<string> GetTableColumns(string testTableName) {
			List<string> lst = new List<string>();

			string testQuery = "select * from [INFORMATION_SCHEMA].[COLUMNS] where table_name = @TableName ";

			List<SqlParameter> parms = new List<SqlParameter>();

			SqlParameter parmKey = new SqlParameter();
			parmKey.ParameterName = "@TableName";
			parmKey.SqlDbType = SqlDbType.VarChar;
			parmKey.Size = 2000;
			parmKey.Direction = ParameterDirection.Input;
			parmKey.Value = testTableName;

			parms.Add(parmKey);

			DataTable table1 = GetTestData(testQuery, parms);

			if (table1.Rows.Count > 1) {
				lst = (from d in table1.AsEnumerable()
					   select d.Field<string>("column_name")).ToList();
			}

			return lst;
		}

		public DatabaseUpdateResponse ApplyUpdateIfNotFound(string testQuery, string updateStatement, bool bIgnore) {
			DatabaseUpdateResponse res = new DatabaseUpdateResponse();
			DataTable table1 = GetTestData(testQuery);

			if (table1.Rows.Count < 1) {
				res.LastException = ExecScriptContents(updateStatement, bIgnore);
				res.Response = "Applied update";
				res.RanUpdate = true;
				return res;
			}

			res.Response = "Did not apply any updates";
			return res;
		}

		public DatabaseUpdateResponse ApplyUpdateIfFound(string testQuery, string updateStatement, bool bIgnore) {
			DatabaseUpdateResponse res = new DatabaseUpdateResponse();
			DataTable table1 = GetTestData(testQuery);

			if (table1.Rows.Count > 0) {
				res.LastException = ExecScriptContents(updateStatement, bIgnore);
				res.Response = "Applied update";
				res.RanUpdate = true;
				return res;
			}

			res.Response = "Did not apply any updates";
			return res;
		}

		private static object logLocker = new Object();

		public static void WriteDebugException(string sSrc, Exception objErr) {
			WriteDebugException(false, sSrc, objErr);
		}

		public static void WriteDebugException(bool bWriteError, string sSrc, Exception objErr) {
#if DEBUG
			bWriteError = true; // always write errors when debug build
#endif

			if (bWriteError && objErr != null) {
				StringBuilder sb = new StringBuilder();

				sb.AppendLine("----------------  " + sSrc.ToUpperInvariant() + " - " + DateTime.Now.ToString() + "  ----------------");

				sb.AppendLine("[" + objErr.GetType().ToString() + "] " + objErr.Message);

				if (objErr.StackTrace != null) {
					sb.AppendLine(objErr.StackTrace);
				}

				if (objErr.InnerException != null) {
					sb.AppendLine(objErr.InnerException.Message);
				}

				string filePath = HttpContext.Current.Server.MapPath("~/carrot_errors.txt");

				Encoding encode = Encoding.Default;
				lock (logLocker) {
					using (FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite)) {
						using (StreamWriter oWriter = new StreamWriter(fs, encode)) {
							oWriter.Write(sb.ToString());
						}
					}
				}
			}
		}

		private static string ContentSqlStateKey = "cms_SqlTablesIncomplete";

		public static bool TablesIncomplete {
			get {
				string tablesIncomplete = String.Empty;
				bool c = true;

				if (HttpContext.Current.Cache[ContentSqlStateKey] != null) {
					tablesIncomplete = HttpContext.Current.Cache[ContentSqlStateKey].ToString();
				} else {
					try {
						c = AreCMSTablesIncomplete();
					} catch (Exception ex) {
						c = false;
						WriteDebugException("tablesincomplete", ex);
					}

					tablesIncomplete = c.ToString();
					HttpContext.Current.Cache.Insert(ContentSqlStateKey, tablesIncomplete, null, DateTime.Now.AddMinutes(3), Cache.NoSlidingExpiration);
				}

				c = Convert.ToBoolean(tablesIncomplete);
				return c;
			}
		}

		public static void ResetSQLState() {
			if (HttpContext.Current.Cache[ContentSqlStateKey] != null) {
				HttpContext.Current.Cache.Remove(ContentSqlStateKey);
			}
		}

		public static bool AreCMSTablesIncomplete() {
			if (!DatabaseUpdate.FailedSQL) {
				bool bTestResult = false;

				DataInfo ver = GetDbSchemaVersion();
				bTestResult = ver.DataValue != DatabaseUpdate.CurrentDbVersion;
				if (bTestResult) {
					return true;
				}

				bTestResult = SQLUpdateNugget.EvalNuggetKey("AreCMSTablesIncomplete");
				if (bTestResult) {
					return true;
				}

				bTestResult = SQLUpdateNugget.EvalManditoryChecks();
				if (bTestResult) {
					return true;
				}
			}

			return false;
		}

		public bool DatabaseNeedsUpdate() {
			if (!DatabaseUpdate.FailedSQL) {
				bool bTestResult = false;

				DataInfo ver = GetDbSchemaVersion();
				bTestResult = ver.DataValue != DatabaseUpdate.CurrentDbVersion;
				if (bTestResult) {
					return true;
				}

				bTestResult = SQLUpdateNugget.EvalNuggetKey("DatabaseNeedsUpdate");
				if (bTestResult) {
					return true;
				}

				bTestResult = SQLUpdateNugget.EvalManditoryChecks();
				if (bTestResult) {
					return true;
				}
			}

			return false;
		}

		public static bool UsersExist {
			get {
				if (!DatabaseUpdate.FailedSQL) {
					try {
						bool bTestResult = SQLUpdateNugget.EvalNuggetKey("DoUsersExist");

						return bTestResult;
					} catch (Exception ex) { }
				}

				return false;
			}
		}

		public DatabaseUpdateResponse AlterStep01() {
			DatabaseUpdateResponse res = new DatabaseUpdateResponse();

			bool bTestResult = SQLUpdateNugget.EvalNuggetKey("AlterStep01");

			if (bTestResult) {
				res.LastException = ExecFileContents("Carrotware.CMS.DBUpdater.DataScripts.ALTER01.sql", false);
				res.Response = "Update comment view";
				res.RanUpdate = true;
				SetDbSchemaVersion(DatabaseUpdate.DbVersion01);
				return res;
			} else {
				// if the db version is off, check leading tidbit against current and immediate prior
				DataInfo ver = GetDbSchemaVersion();

				if (DatabaseUpdate.DbVersion00.Substring(0, 6) == ver.DataValue.Substring(0, 6)
					|| DatabaseUpdate.DbVersion01.Substring(0, 6) == ver.DataValue.Substring(0, 6)
					|| "2015" == ver.DataValue.Substring(0, 4) || "2016" == ver.DataValue.Substring(0, 4)) {
					SetDbSchemaVersion(DatabaseUpdate.DbVersion01);
				}
			}

			res.Response = "Comment view update already applied";
			return res;
		}

		public DatabaseUpdateResponse AlterStep02() {
			DatabaseUpdateResponse res = new DatabaseUpdateResponse();

			bool bTestResult = SQLUpdateNugget.EvalNuggetKey("AlterStep02");

			if (bTestResult) {
				res.LastException = ExecFileContents("Carrotware.CMS.DBUpdater.DataScripts.ALTER02.sql", false);
				res.Response = "Update timezone sproc";
				res.RanUpdate = true;
				SetDbSchemaVersion(DatabaseUpdate.DbVersion02);
				return res;
			} else {
				// if the db version is off, check leading tidbit against current and immediate prior
				DataInfo ver = GetDbSchemaVersion();

				if (DatabaseUpdate.DbVersion01.Substring(0, 6) == ver.DataValue.Substring(0, 6)
					|| DatabaseUpdate.DbVersion02.Substring(0, 6) == ver.DataValue.Substring(0, 6)) {
					SetDbSchemaVersion(DatabaseUpdate.DbVersion02);
				}
			}

			res.Response = "Timezone sproc update already applied";
			return res;
		}

		private string ReadEmbededScript(string filePath) {
			string sFile = "";

			Assembly _assembly = Assembly.GetExecutingAssembly();

			using (StreamReader oTextStream = new StreamReader(_assembly.GetManifestResourceStream(filePath))) {
				sFile = oTextStream.ReadToEnd();
			}

			return sFile;
		}

		private List<string> SplitScriptAtGo(string sSQLQuery) {
			sSQLQuery += "\r\n\r\nGO\r\n\r\n";
			sSQLQuery = sSQLQuery.Replace("\r\n", "\n");

			string[] splitcommands = sSQLQuery.Split(new string[] { "GO\n" }, StringSplitOptions.RemoveEmptyEntries);
			List<string> commandList = new List<string>(splitcommands);
			return commandList;
		}

		#region Execute SQL statements

		public Exception ExecScriptContents(string sScriptContents, bool bIgnoreErr) {
			string _connStr = SetConn();

			return ExecScriptContents(_connStr, sScriptContents, bIgnoreErr);
		}

		public Exception ExecScriptContents(string sConnectionString, string sScriptContents, bool bIgnoreErr) {
			return ExecNonQuery(sConnectionString, sScriptContents, bIgnoreErr);
		}

		private Exception ExecFileContents(string sResourceName, bool bIgnoreErr) {
			string _connStr = SetConn();

			return ExecFileContents(_connStr, sResourceName, bIgnoreErr);
		}

		private Exception ExecFileContents(string sConnectionString, string sResourceName, bool bIgnoreErr) {
			string sScriptContents = ReadEmbededScript(sResourceName);

			Exception response = ExecScriptContents(sConnectionString, sScriptContents, bIgnoreErr);

			return response;
		}

		#endregion Execute SQL statements

		#region Work with data keys

		private static object schemaCheckLocker = new Object();

		//private static string SchemaKey = "cms_GetDbSchemaVersion";

		public static DataInfo GetDbSchemaVersion() {
			DataInfo di = null;
			lock (schemaCheckLocker) {
				//if (HttpContext.Current.Cache[ContentKey] != null) {
				//	try { di = (DataInfo)HttpContext.Current.Cache[ContentKey]; } catch { }
				//} else {
				//	di = GetDataKeyValue("DBSchema");
				//	HttpContext.Current.Cache.Insert(ContentKey, di, null, DateTime.Now.AddSeconds(5), Cache.NoSlidingExpiration);
				//}

				di = GetDataKeyValue("DBSchema");

				return di;
			}
		}

		public static void SetDbSchemaVersion(string dataKeyValue) {
			SetDataKeyValue("DBSchema", dataKeyValue);
		}

		public static DataInfo GetDataKeyValue(string dataKeyName) {
			string _connStr = SetConn();

			DataInfo d = new DataInfo();

			SQLUpdateNugget n = SQLUpdateNugget.GetNuggets("SchemaVersionCheck").FirstOrDefault();
			if (n != null) {
				List<SqlParameter> parms = new List<SqlParameter>();

				SqlParameter parmKey = new SqlParameter();
				parmKey.ParameterName = "@DataKey";
				parmKey.SqlDbType = SqlDbType.VarChar;
				parmKey.Size = 100;
				parmKey.Direction = ParameterDirection.Input;
				parmKey.Value = dataKeyName;

				parms.Add(parmKey);

				DataTable dt = ExecuteDataTableCommands(_connStr, n.SQLQuery, parms);

				if (dt.Rows.Count > 0) {
					DataRow dr = dt.Rows[0];

					d.DataKey = dr["DataKey"].ToString();
					d.DataValue = dr["DataValue"].ToString();
				}
			}

			if (d != null && String.IsNullOrEmpty(d.DataValue)) {
				d.DataValue = String.Empty;
			}

			return d;
		}

		public static void SetDataKeyValue(string dataKeyName, string dataKeyValue) {
			string _connStr = SetConn();

			SQLUpdateNugget n = SQLUpdateNugget.GetNuggets("SchemaVersionUpdate").FirstOrDefault();

			if (n != null) {
				List<SqlParameter> parms = new List<SqlParameter>();

				SqlParameter parmNewVal = new SqlParameter();
				parmNewVal.ParameterName = "@DataValue";
				parmNewVal.SqlDbType = SqlDbType.VarChar;
				parmNewVal.Size = 100;
				parmNewVal.Direction = ParameterDirection.Input;
				parmNewVal.Value = dataKeyValue;

				parms.Add(parmNewVal);

				SqlParameter parmKey = new SqlParameter();
				parmKey.ParameterName = "@DataKey";
				parmKey.SqlDbType = SqlDbType.VarChar;
				parmKey.Size = 100;
				parmKey.Direction = ParameterDirection.Input;
				parmKey.Value = dataKeyName;

				parms.Add(parmKey);

				ExecuteNonQueryCommands(_connStr, n.SQLQuery, parms);
			}
		}

		#endregion Work with data keys

		#region General database routines

		private Exception ExecNonQuery(string sConnectionString, string sSQLQuery, bool bIgnoreErr) {
			Exception exc = new Exception("");

			using (SqlConnection myConnection = new SqlConnection(sConnectionString)) {
				myConnection.Open();

				List<string> cmdLst = SplitScriptAtGo(sSQLQuery);

				if (!bIgnoreErr) {
					try {
						foreach (string cmdStr in cmdLst) {
							using (SqlCommand myCommand = myConnection.CreateCommand()) {
								myCommand.CommandText = cmdStr;
								myCommand.Connection = myConnection;
								myCommand.CommandTimeout = 360;
								int ret = myCommand.ExecuteNonQuery();
							}
						}
					} catch (Exception ex) {
						exc = ex;
					} finally {
						myConnection.Close();
					}
				} else {
					StringBuilder sb = new StringBuilder();
					foreach (string cmdStr in cmdLst) {
						try {
							using (SqlCommand myCommand = myConnection.CreateCommand()) {
								myCommand.CommandText = cmdStr;
								myCommand.Connection = myConnection;
								myCommand.CommandTimeout = 360;
								int ret = myCommand.ExecuteNonQuery();
							}
						} catch (Exception ex) {
							sb.Append(ex.Message.ToString() + "\n~~~~~~~~~~~~~~~~~~~~~~~~\n");
						}
					}
					exc = new Exception(sb.ToString());
					myConnection.Close();
				}
			}

			return exc;
		}

		private static void ExecuteNonQueryCommands(string sConnectionString, string sSQLQuery, List<SqlParameter> SqlParms) {
			DataTable dt = new DataTable();

			using (SqlConnection cn = new SqlConnection(sConnectionString)) {
				cn.Open();
				using (SqlCommand cmd = new SqlCommand(sSQLQuery, cn)) {
					cmd.CommandType = CommandType.Text;

					foreach (var p in SqlParms) {
						cmd.Parameters.Add(p);
					}

					int ret = cmd.ExecuteNonQuery();
				}
				cn.Close();
			}
		}

		private static DataTable ExecuteDataTableCommands(string sConnectionString, string sSQLQuery, List<SqlParameter> SqlParms) {
			DataTable dt = new DataTable();

			using (SqlConnection cn = new SqlConnection(sConnectionString)) {
				using (SqlCommand cmd = new SqlCommand(sSQLQuery, cn)) {
					cn.Open();
					cmd.CommandType = CommandType.Text;

					if (SqlParms != null) {
						foreach (var p in SqlParms) {
							cmd.Parameters.Add(p);
						}
					}

					using (SqlDataAdapter da = new SqlDataAdapter(cmd)) {
						da.Fill(dt);
					}
				}
				cn.Close();
			}

			return dt;
		}

		public static DataTable GetDataTable(string sSQLQuery) {
			string _connStr = SetConn();

			return GetDataTable(_connStr, sSQLQuery);
		}

		private static DataTable GetDataTable(string sConnectionString, string sSQLQuery) {
			DataTable dt = new DataTable();

			using (SqlConnection cn = new SqlConnection(sConnectionString)) {
				using (SqlCommand cmd = new SqlCommand(sSQLQuery, cn)) {
					cn.Open();
					cmd.CommandType = CommandType.Text;
					using (SqlDataAdapter da = new SqlDataAdapter(cmd)) {
						da.Fill(dt);
					}
					cn.Close();
				}
			}

			return dt;
		}

		public static DataTable GetTestData(string sSQLQuery) {
			return GetTestData(sSQLQuery, null);
		}

		public static DataTable GetTestData(string sSQLQuery, List<SqlParameter> SqlParms) {
			string _connStr = SetConn();

			return GetTestData(_connStr, sSQLQuery, SqlParms);
		}

		public static DataTable GetTestData(string sConnectionString, string sSQLQuery, List<SqlParameter> SqlParms) {
			DataTable dt = new DataTable();

			try {
				using (SqlConnection cn = new SqlConnection(sConnectionString)) {
					cn.Open(); // throws if invalid

					DatabaseUpdate.FailedSQL = false;

					using (SqlCommand cmd = cn.CreateCommand()) {
						cmd.CommandText = sSQLQuery;

						if (SqlParms != null) {
							foreach (var p in SqlParms) {
								cmd.Parameters.Add(p);
							}
						}

						using (SqlDataAdapter da = new SqlDataAdapter(cmd)) {
							da.Fill(dt);
						}
					}

					cn.Close();
				}
				DatabaseUpdate.LastSQLError = null;
			} catch (SqlException sqlEx) {
				DatabaseUpdate.LastSQLError = sqlEx;
				DatabaseUpdate.FailedSQL = true;
			}

			return dt;
		}

		private static DataSet GetDataSet(string sSQLQuery) {
			string _connStr = SetConn();

			return GetDataSet(_connStr, sSQLQuery);
		}

		private static DataSet GetDataSet(string sConnectionString, string sSQLQuery) {
			DataSet ds = new DataSet();

			using (SqlConnection cn = new SqlConnection(sConnectionString)) {
				using (SqlCommand cmd = new SqlCommand(sSQLQuery, cn)) {
					cn.Open();
					cmd.CommandType = CommandType.Text;
					using (SqlDataAdapter da = new SqlDataAdapter(cmd)) {
						da.Fill(ds);
					}
					cn.Close();
				}
			}

			return ds;
		}

		#endregion General database routines
	}

	//======================
	public class DatabaseUpdateStatus {
		public bool NeedsUpdate { get; set; }

		public List<DatabaseUpdateMessage> Messages { get; set; }

		public DatabaseUpdateStatus() {
			this.Messages = new List<DatabaseUpdateMessage>();
			this.NeedsUpdate = true;
		}
	}

	//======================
	public class DataInfo {
		public string DataKey { get; set; }
		public string DataValue { get; set; }
	}

	//======================
	public class DatabaseUpdateMessage {
		public string Message { get; set; }
		public string ExceptionText { get; set; }
		public string InnerExceptionText { get; set; }
		public string Response { get; set; }
		public int Order { get; set; }
		public bool AlteredData { get; set; }
		public bool HasException { get; set; }

		public DatabaseUpdateMessage() {
			this.ExceptionText = null;
			this.InnerExceptionText = null;
			this.AlteredData = false;
			this.HasException = false;
			this.Message = "";
			this.Response = "";
			this.Order = -1;
		}
	}

	//======================
	public class DatabaseUpdateResponse {
		public Exception LastException { get; set; }
		public string Response { get; set; }
		public bool RanUpdate { get; set; }

		public DatabaseUpdateResponse() {
			this.LastException = null;
			this.Response = "";
			this.RanUpdate = false;
		}
	}
}


text:
package org.springframework.boot.devtools.restart;

import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadFactory;

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

import org.springframework.beans.factory.ObjectFactory;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;

/**
 * Mocked version of {@link Restarter}.
 *
 * @author Phillip Webb
 */
public class MockRestarter implements TestRule {

	private Map<String, Object> attributes = new HashMap<>();

	private Restarter mock = mock(Restarter.class);

	@Override
	public Statement apply(final Statement base, Description description) {
		return new Statement() {

			@Override
			public void evaluate() throws Throwable {
				setup();
				base.evaluate();
				cleanup();
			}

		};
	}

	@SuppressWarnings("rawtypes")
	private void setup() {
		Restarter.setInstance(this.mock);
		given(this.mock.getInitialUrls()).willReturn(new URL[] {});
		given(this.mock.getOrAddAttribute(anyString(), (ObjectFactory) any()))
				.willAnswer(new Answer<Object>() {

					@Override
					public Object answer(InvocationOnMock invocation) throws Throwable {
						String name = (String) invocation.getArguments()[0];
						ObjectFactory factory = (ObjectFactory) invocation
								.getArguments()[1];
						Object attribute = MockRestarter.this.attributes.get(name);
						if (attribute == null) {
							attribute = factory.getObject();
							MockRestarter.this.attributes.put(name, attribute);
						}
						return attribute;
					}

				});
		given(this.mock.getThreadFactory()).willReturn(new ThreadFactory() {

			@Override
			public Thread newThread(Runnable r) {
				return new Thread(r);
			}

		});
	}

	private void cleanup() {
		this.attributes.clear();
		Restarter.clearInstance();
	}

	public Restarter getMock() {
		return this.mock;
	}

}


text:
package com.longkaiwen.besttrainingforandroid;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

/**
 * Created by wlk on 2017/2/27.
 */

public class ThirdActivity extends AppCompatActivity {

    private static final String TAG = "ThirdActivity";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "onCreate: ");
        setContentView(R.layout.activity_third);

    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, "onResume: ");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i(TAG, "onPause: ");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG, "onStop: ");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy: ");
    }
}


text:
var GroundRoutes, _;

_ = require('underscore');

GroundRoutes = (function() {
  function GroundRoutes() {}

  GroundRoutes.prefix = '';

  GroundRoutes.routes = {};

  GroundRoutes.asRoutes = {};

  GroundRoutes.paths = {};

  GroundRoutes.bindReq = function(req) {
    req.paths = Object.create({}, this.pathPrototype());
    return req.paths.req = req;
  };

  GroundRoutes.pathPrototype = function() {
    return this._pathPrototype != null ? this._pathPrototype : this._pathPrototype = (function(_this) {
      return function() {
        var key, res, val, _fn, _ref;
        res = {};
        _ref = _this.asRoutes;
        _fn = function(val) {
          return res[key] = {
            get: function() {
              return val.replace(/:([\w\d_-]+)/g, (function(_this) {
                return function(match, p1) {
                  if (_this.req.params[p1] == null) {
                    throw new Error("param '" + p1 + "' not found.");
                  }
                  return _this.req.params[p1];
                };
              })(this));
            }
          };
        };
        for (key in _ref) {
          val = _ref[key];
          _fn(val);
        }
        return res;
      };
    })(this)();
  };

  GroundRoutes.sails = function() {
    var emit, generateRoute, result;
    result = {};
    emit = (function(_this) {
      return function(prefix, route, config) {
        var actions, as, bindPath, routePaths;
        routePaths = route.split(' ');
        bindPath = prefix + _.last(routePaths);
        if (bindPath.length > 1 && _.last(bindPath) === '/') {
          bindPath = bindPath.substring(0, bindPath.length - 1);
        }
        routePaths[routePaths.length - 1] = bindPath;
        if (config.as != null) {
          _this.asRoutes[config.as] = bindPath;
          as = config.as;
          (function(as) {
            return _this.paths[as] = function(params) {
              return _this.asRoutes[as].replace(/:([\w\d_-]+)/g, function(match, p1) {
                if (params[p1] == null) {
                  throw new Error("param '" + p1 + "' not found.");
                }
                return params[p1];
              });
            };
          })(as);
          delete config.as;
        }
        if (config.action != null) {
          actions = config.action.split('.');
          if (actions.length != null) {
            config = _.compact((config.controller || '').split('.').concat(actions)).join('.');
          }
        }
        if (config.controller != null) {
          config = config.controller;
        }
        return result[routePaths.join(' ')] = config;
      };
    })(this);
    generateRoute = function(routes, prefix) {
      var key, val, _results;
      if (prefix == null) {
        prefix = '';
      }
      if (!_.isObject(routes)) {
        return;
      }
      _results = [];
      for (key in routes) {
        val = routes[key];
        switch (false) {
          case !_.isString(val):
            _results.push(emit(prefix, key, val));
            break;
          case !(_.isObject(val) && ((val.controller != null) || (val.view != null) || (val.action != null))):
            _results.push(emit(prefix, key, val));
            break;
          case !_.isObject(val):
            _results.push(generateRoute(val, prefix + key));
            break;
          default:
            _results.push(void 0);
        }
      }
      return _results;
    };
    generateRoute(this.routes, this.prefix);
    return result;
  };

  return GroundRoutes;

})();

module.exports = GroundRoutes;


text:
package org.woehlke.btw17.importer.dimensions;

import lombok.extern.slf4j.Slf4j;
import org.junit.Ignore;
import org.junit.Test;

import java.io.*;

@Slf4j
public class WahlkreisImporter {

    private final static String dateiName = "etc/3nf/SELECT_wahlkreis_id_wahlkreis_name_FROM_.csv";
    private final static String dateiNameOut = "etc/3nf/insert-data-wahlkreis.sql";
    private final static String sqlStart = "INSERT INTO wahlkreis (id,wahlkreis_id,wahlkreis_name) VALUES (";

    @Ignore
    @Test
    public void createSql() throws Exception {
        BufferedWriter bw = new BufferedWriter(new FileWriter(dateiNameOut));
        BufferedReader br = new BufferedReader(new FileReader(dateiName));
        long id = 0;
        while (br.ready()){
            id++;
            String line = br.readLine();
            String output = sqlStart + id + ", "+line+" );\n";
            bw.write(output);
        }
        bw.close();
        br.close();
    }
}


text:
<?php
$this->import('blog.css');
$this->meta('viewport', 'width=device-width, initial-scale=1');
?>
<!DOCTYPE html>

<title><?php
if (isset($title))
  echo h($title) . ' | ';
echo h($blogTitle);
?></title>

<?php echo $this->block('meta'); ?>

<?php echo $this->resourceBlock(); ?>

<?php echo $Html->link(h($blogTitle), null, array('class' => 'title')); ?>

<?php echo $Html->link(tr('Home'), null); ?>

<?php if ($Auth->isLoggedIn()): ?>

<?php echo $Html->link(tr('Add post'), 'Posts::add'); ?>

<?php echo $Html->link(tr('Settings'), 'App::settings'); ?>

<?php echo $Html->link(tr('Log out'), 'App::logout'); ?>

<?php else: ?>

<?php echo $Html->link(tr('Admin'), 'App::login'); ?>

<?php endif; ?>

<?php if (isset($title)): ?>

<?php echo h($title); ?>

<?php endif; ?>

<?php foreach ($Notify as $message): ?>
<p class="flash flash-<?php echo $message->type; ?>"><?php echo $message; ?>

<?php endforeach; ?>

<?php echo $this->block('content'); ?>

<?php echo tr('Recent Posts'); ?>

<?php echo $Snippet('Sidebar\RecentPosts'); ?>

<?php echo tr('Recent Comments'); ?>

<?php echo $Snippet('Sidebar\RecentComments'); ?>


text:
ImportMapping.draw do |map|
  map.item 'Shop_item' do |item|
    item.elm 'Cislo', :to => :id_by_vendor
  end

end


text:
matrix.define( "message.js", "greeting.js, name.js, welcome.js, intro.js", function() {
	window.message = greeting + "," + name + "," + welcome + intro + ending;
} );


text:
// General object for throwing Exceptions
// Includes a Factory object inside to generate correct exception type

'use strict';

var status = require('./status.js');

/** UserNotFound Error
* Descripton: Thrown if user is not found
* Severity: NonFatal
* @class UserNotFoundError
* @constructor UserNotFoundError
* @param publickey PublicKey that was not found in the database
*/
function UserNotFoundError(publicKey){
  this.status = status.ARGUMENTS_INVALID.toString();
  this.name = 'UserNotFound';
  this.message = 'No user found with key: ' + publicKey;
}
UserNotFoundError.prototype = new Error();
UserNotFoundError.prototype.constructor = UserNotFoundError;

/** MissingParameter Error
* Description: Thrown if a URL query string parameter is missing
* Severity: NonFatal
* @class MissingParameterError
* @constructor MissingParameterError
* @param parameter Name of the expected paramter that was missing
*/
function MissingParameterError(parameter){
  this.status = status.ARGUMENTS_INVALID.toString();
  this.name = 'ParametersMissing';
  this.message = 'Could not find paramters:"' + parameter + '" in URL';
}
MissingParameterError.prototype = new Error();
MissingParameterError.prototype.constructor = MissingParameterError;

/** InvalidParameterError
* Description: Thrown if the URL query string parameter does not meet exected type
* Severity: NonFatal
* @class InvalidParameterError
* @constructor InvalidParameterError
* @param parameter Name of the invalid parameter
*/
function InvalidParameterError(parameter){
  this.status = status.ARGUMENTS_INVALID.toString();
  this.name='InvalidArgument';
  this.message = 'Value of the parameter:"' + parameter + '" is invalid';
}
InvalidParameterError.prototype = new Error();
InvalidParameterError.prototype.constructor = InvalidParameterError;

/** InvalidTimestampError
* Description: Thrown if the timestamp paramter is more than 10 minutes old
* Severity: NonFatal
* @class InvalidTimestampError
* @constructor InvalidTimestampError
*/
function InvalidTimestampError(){
  this.status = status.ARGUMENTS_INVALID.toString();
  this.name='InvalidTimestamp';
  this.message = 'The request is more than 10 minute old';
}
InvalidTimestampError.prototype = new Error();
InvalidTimestampError.prototype.constructor = InvalidTimestampError;

/** SignatureMismatch
* Description: Thrown if the signature does not match with computed signature
* Severity: NonFatal
* @class SignatureMismatchError
* @constructor SignatureMismatchError
*/
function SignatureMismatchError(){
  this.status = status.ARGUMENTS_INVALID.toString();
  this.name='SignatureMimatch';
  this.message = 'The signature of the request cannot be verified. Either you have invalid key or your request has been tampered with.';
}
SignatureMismatchError.prototype = new Error();
SignatureMismatchError.prototype.constructor = SignatureMismatchError;

/** MysqlError
* Description: Thrown by Mysql-node when encountering exception with MySql
* Severity: Depends on fatal parameter
* @class MysqlError
* @constructor MysqlError
* @param mysqlError Error generated from node.mysql
*/
function MysqlError(mysqlError){
  this.status = mysqlError.fatal ? status.SERVER_ERROR.toString(): status.ARGUMENTS_INVALID.toString();
  this.fatal = mysqlError.fatal;
  this.code = mysqlError.code;
  this.name = mysqlError.name;
  this.message = mysqlError.message;
}
MysqlError.prototype = new Error();
MysqlError.prototype.constructor = MysqlError;

/** SqliteError
* Description: Thrown when interacting with local Sqlite cache for Mysql
* Severity: Fatal, affects user functionality
* @class SqliteError
* @constructor SqliteError
* @param err Error generated by node.sqlite3 module
*/
function SqliteError(err){
  this.status = status.SERVER_ERROR.toString();
  this.name = err.name;
  this.message = err.message;
}
SqliteError.prototype = new Error();
SqliteError.prototype.constructor = SqliteError;

/** NoCustomQueryFound
* Description: Thrown when a Custom Request ID is not found in Mysql
* Severity: NonFatal
* @class NoCustomQueryFound
* @constructor NoCustomQueryFound
*/
function NoCustomQueryFound(publickey,requestid){
  this.status = status.ARGUMENTS_INVALID.toString();
  this.name='InvalidCustomQueryID';
  this.message = 'The custom request id:' + requestid + ' for publickey: ' + publickey + ' is invalid';
}
NoCustomQueryFound.prototype = new Error();
NoCustomQueryFound.prototype.constructor = NoCustomQueryFound;

module.exports = {
    UserNotFound: UserNotFoundError,
    MissingParameter: MissingParameterError,
    InvalidTimestamp: InvalidTimestampError,
    SignatureMismatch: SignatureMismatchError,
    InvalidParameter: InvalidParameterError,
    Mysql: MysqlError,
    Sqlite: SqliteError,
    NoCustomQueryFound: NoCustomQueryFound
  };


text:
/*
  Notes:

  This code has not yet been ported to non-WIN32 platforms...
  Remove this note when it has been ported and verified.
    -- Patric Ljung, 8/31/2009
*/

#ifndef XIPTIMER_H
#define XIPTIMER_H

#include <xip/common/XipCommon.h>

#include <xip/system/standard.h>

#ifdef WIN32
#include <windows.h>
#else //UNIX
#include <sys/time.h>
#endif //WIN32

#include <ctime>

/*
  Example:

  XipTimer timer;
  timer.start();

  -- Your code to be benchmarked --

  timer.stop();
  print timer.eplasedTime();
*/

class XIPCOMMON_API XipTimer
{
public:
    // Constructor.
    XipTimer();

    // Start the XipTimer
    inline XipTimer & start();

    // Stop the XipTimer (and freeze the elapsed time).
    inline XipTimer & stop();

    // Return the currently elapsed time in seconds.
    double elapsedTime();

protected:
#ifdef WIN32
    __uint64	mFreq;
    __uint64	mStart;
    __uint64	mStop;
#else //UNIX
    timeval     mStart;
    timeval     mStop;
#endif //WIN32
};

inline XipTimer & XipTimer::start()
{
#ifdef WIN32
    QueryPerformanceCounter((LARGE_INTEGER*)&mStart);
#else //UNIX
    //sys_clock_gettime(CLOCK_REALTIME, mStart);
    gettimeofday(&mStart, NULL);
#endif //WIN32
    return *this;
}

inline XipTimer & XipTimer::stop()
{
#ifdef WIN32
    QueryPerformanceCounter((LARGE_INTEGER*)&mStop);
#else //UNIX
    //sys_clock_gettime(CLOCK_REALTIME, mStart);
    gettimeofday(&mStop, NULL);
#endif //WIN32
    return *this;
}

#endif // XIPTIMER_H

/*
 *  COPYRIGHT NOTICE.  Copyright (C) 2005 Siemens Corporate Research,
 *  Inc. ("caBIG(tm) Participant"). eXtensible Imaging Platform (XIP)
 *  was created with NCI funding and is part of the caBIG(tm)
 *  initiative. The software subject to this notice and license
 *  includes both human readable source code form and machine
 *  readable, binary, object code form (the "caBIG(tm) Software").
 *
 *  This caBIG(tm) Software License (the "License") is between
 *  caBIG(tm) Participant and You.  "You (or "Your") shall mean a
 *  person or an entity, and all other entities that control, are
 *  controlled by, or are under common control with the entity.
 *  "Control" for purposes of this definition means (i) the direct or
 *  indirect power to cause the direction or management of such
 *  entity, whether by contract or otherwise, or (ii) ownership of
 *  fifty percent (50%) or more of the outstanding shares, or (iii)
 *  beneficial ownership of such entity.
 *
 *  LICENSE.  Provided that You agree to the conditions described
 *  below, caBIG(tm) Participant grants You a non-exclusive,
 *  worldwide, perpetual, fully-paid-up, no-charge, irrevocable,
 *  transferable and royalty-free right and license in its rights in
 *  the caBIG(tm) Software, including any copyright or patent rights
 *  therein that may be infringed by the making, using, selling,
 *  offering for sale, or importing of caBIG(tm) Software, to (i)
 *  use, install, access, operate, execute, reproduce, copy, modify,
 *  translate, market, publicly display, publicly perform, and
 *  prepare derivative works of the caBIG(tm) Software; (ii) make,
 *  have made, use, practice, sell, and offer for sale, and/or
 *  otherwise dispose of caBIG(tm) Software (or portions thereof);
 *  (iii) distribute and have distributed to and by third parties the
 *  caBIG(tm) Software and any modifications and derivative works
 *  thereof; and (iv) sublicense the foregoing rights set out in (i),
 *  (ii) and (iii) to third parties, including the right to license
 *  such rights to further third parties.  For sake of clarity, and
 *  not by way of limitation, caBIG(tm) Participant shall have no
 *  right of accounting or right of payment from You or Your
 *  sublicensees for the rights granted under this License.  This
 *  License is granted at no charge to You.  Your downloading,
 *  copying, modifying, displaying, distributing or use of caBIG(tm)
 *  Software constitutes acceptance of all of the terms and
 *  conditions of this Agreement.  If you do not agree to such terms
 *  and conditions, you have no right to download, copy, modify,
 *  display, distribute or use the caBIG(tm) Software.
 *
 *  1.	Your redistributions of the source code for the caBIG(tm)
 *      Software must retain the above copyright notice, this list
 *      of conditions and the disclaimer and limitation of
 *      liability of Article 6 below.  Your redistributions in
 *      object code form must reproduce the above copyright notice,
 *      this list of conditions and the disclaimer of Article 6 in
 *      the documentation and/or other materials provided with the
 *      distribution, if any.
 *  2.	Your end-user documentation included with the
 *      redistribution, if any, must include the following
 *      acknowledgment: "This product includes software developed
 *      by Siemens Corporate Research Inc."  If You do not include
 *      such end-user documentation, You shall include this
 *      acknowledgment in the caBIG(tm) Software itself, wherever
 *      such third-party acknowledgments normally appear.
 *  3.	You may not use the names "Siemens Corporate Research,
 *      Inc.", "The National Cancer Institute", "NCI", "Cancer
 *      Bioinformatics Grid" or "caBIG(tm)" to endorse or promote
 *      products derived from this caBIG(tm) Software.  This
 *      License does not authorize You to use any trademarks,
 *  	service marks, trade names, logos or product names of
 *      either caBIG(tm) Participant, NCI or caBIG(tm), except as
 *      required to comply with the terms of this License.
 *  4.	For sake of clarity, and not by way of limitation, You may
 *      incorporate this caBIG(tm) Software into Your proprietary
 *      programs and into any third party proprietary programs.
 *      However, if You incorporate the caBIG(tm) Software into
 *      third party proprietary programs, You agree that You are
 *      solely responsible for obtaining any permission from such
 *      third parties required to incorporate the caBIG(tm)
 *      Software into such third party proprietary programs and for
 *      informing Your sublicensees, including without limitation
 *      Your end-users, of their obligation to secure any required
 *      permissions from such third parties before incorporating
 *      the caBIG(tm) Software into such third party proprietary
 *      software programs.  In the event that You fail to obtain
 *      such permissions, You agree to indemnify caBIG(tm)
 *      Participant for any claims against caBIG(tm) Participant by
 *      such third parties, except to the extent prohibited by law,
 *      resulting from Your failure to obtain such permissions.
 *  5.	For sake of clarity, and not by way of limitation, You may
 *      add Your own copyright statement to Your modifications and
 *      to the derivative works, and You may provide additional or
 *      different license terms and conditions in Your sublicenses
 *      of modifications of the caBIG(tm) Software, or any
 *      derivative works of the caBIG(tm) Software as a whole,
 *      provided Your use, reproduction, and distribution of the
 *      Work otherwise complies with the conditions stated in this
 *      License.
 *  6.	THIS caBIG(tm) SOFTWARE IS PROVIDED "AS IS" AND ANY
 *      EXPRESSED OR IMPLIED WARRANTIES (INCLUDING, BUT NOT LIMITED
 *      TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, NON-
 *      INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE) ARE
 *      DISCLAIMED.  IN NO EVENT SHALL SIEMENS CORPORATE RESEARCH
 *      INC. OR ITS AFFILIATES BE LIABLE FOR ANY DIRECT, INDIRECT,
 *      INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 *      (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *      GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
 *      BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 *      LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 *      (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 *      OF THE USE OF THIS caBIG(tm) SOFTWARE, EVEN IF ADVISED OF
 *      THE POSSIBILITY OF SUCH DAMAGE.
 */


text:
/*
  This file is part of ethash.

  ethash is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  ethash is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with ethash.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file io.h
 * @author Lefteris Karapetsas <lefteris@ethdev.com>
 * @date 2015
 */
#pragma once
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include "ethash.h"

#ifdef __cplusplus
extern "C" {
#endif

typedef struct ethash_blockhash { uint8_t b[32]; } ethash_blockhash_t;

static const char DAG_FILE_NAME[] = "full";
static const char DAG_MEMO_NAME[] = "full.info";
// MSVC thinks that "static const unsigned int" is not a compile time variable. Sorry for the #define :(
#define DAG_MEMO_BYTESIZE 36

/// Possible return values of @see ethash_io_prepare
enum ethash_io_rc {
    ETHASH_IO_FAIL = 0,      ///< There has been an IO failure
    ETHASH_IO_MEMO_MISMATCH, ///< Memo file either did not exist or there was content mismatch
    ETHASH_IO_MEMO_MATCH,    ///< Memo file existed and contents matched. No need to do anything
};

/**
 * Prepares io for ethash
 *
 * Create the DAG directory if it does not exist, and check if the memo file matches.
 * If it does not match then it's deleted to pave the way for @ref ethash_io_write()
 *
 * @param dirname        A null terminated c-string of the path of the ethash
 *                       data directory. If it does not exist it's created.
 * @param seedhash       The seedhash of the current block number
 * @return               For possible return values @see enum ethash_io_rc
 */
enum ethash_io_rc ethash_io_prepare(char const *dirname, ethash_blockhash_t seedhash);
/**
 * Fully computes data and writes it to the file on disk.
 *
 * This function should be called after @see ethash_io_prepare() and only if
 * its return value is @c ETHASH_IO_MEMO_MISMATCH. Will write both the full data
 * and the memo file.
 *
 * @param[in] dirname        A null terminated c-string of the path of the ethash
 *                           data directory. Has to exist.
 * @param[in] params         An ethash_params object containing the full size
 *                           and the cache size
 * @param[in] seedhash       The seedhash of the current block number
 * @param[in] cache          The cache data. Would have usually been calulated by
 *                           @see ethash_prep_light().
 * @param[out] data          Pass a pointer to uint8_t by reference here. If the
 *                           function is succesfull then this point to the allocated
 *                           data calculated by @see ethash_prep_full(). Memory
 *                           ownership is transfered to the callee. Remember that
 *                           you eventually need to free this with a call to free().
 * @param[out] data_size     Pass a size_t by value. If the function is succesfull
 *                           then this will contain the number of bytes allocated
 *                           for @a data.
 * @return                   True for success and false in case of failure.
 */
bool ethash_io_write(char const *dirname,
                     ethash_params const* params,
                     ethash_blockhash_t seedhash,
                     void const* cache,
                     uint8_t **data,
                     size_t *data_size);

static inline void ethash_io_serialize_info(uint32_t revision,
                                            ethash_blockhash_t seed_hash,
                                            char *output)
{
    // if .info is only consumed locally we don't really care about endianess
    memcpy(output, &revision, 4);
    memcpy(output + 4, &seed_hash, 32);
}

static inline char *ethash_io_create_filename(char const *dirname,
                                              char const* filename,
                                              size_t filename_length)
{
    // in C the cast is not needed, but a C++ compiler will complain for invalid conversion
    char *name = (char*)malloc(strlen(dirname) + filename_length);
    if (!name) {
        return NULL;
    }

    name[0] = '\0';
    strcat(name, dirname);
    strcat(name, filename);
    return name;
}

#ifdef __cplusplus
}
#endif


text:
var registerElement = require('guestViewContainerElement').registerElement;
var GuestViewContainerElement =
    require('guestViewContainerElement').GuestViewContainerElement;
var ExtensionOptionsImpl = require('extensionOptions').ExtensionOptionsImpl;
var ExtensionOptionsConstants =
    require('extensionOptionsConstants').ExtensionOptionsConstants;

class ExtensionOptionsElement extends GuestViewContainerElement {
  static get observedAttributes() {
    return [ExtensionOptionsConstants.ATTRIBUTE_EXTENSION];
  }

  constructor() {
    super();
    privates(this).internal = new ExtensionOptionsImpl(this);
  }
}

registerElement('ExtensionOptions', ExtensionOptionsElement);