text:
/////////////////////////////////////////////////////////////////////////////
// Name:        wx/variant.h
// Purpose:     wxVariant class, container for any type
// Author:      Julian Smart
// Modified by:
// Created:     10/09/98
// RCS-ID:      $Id: variant.h 42997 2006-11-03 21:37:08Z VZ $
// Copyright:   (c) Julian Smart
// Licence:     wxWindows licence
/////////////////////////////////////////////////////////////////////////////

#ifndef _WX_VARIANT_H_
#define _WX_VARIANT_H_

#include "wx/defs.h"

#if wxUSE_VARIANT

#include "wx/object.h"
#include "wx/string.h"
#include "wx/arrstr.h"
#include "wx/list.h"
#include "wx/cpp.h"

#if wxUSE_DATETIME
    #include "wx/datetime.h"
#endif // wxUSE_DATETIME

#if wxUSE_ODBC
    #include "wx/db.h"  // will #include sqltypes.h
#endif //ODBC

#include "wx/iosfwrap.h"

/*
 * wxVariantData stores the actual data in a wxVariant object,
 * to allow it to store any type of data.
 * Derive from this to provide custom data handling.
 *
 * NB: To prevent addition of extra vtbl pointer to wxVariantData,
 *     we don't multiple-inherit from wxObjectRefData. Instead,
 *     we simply replicate the wxObject ref-counting scheme.
 *
 * NB: When you construct a wxVariantData, it will have refcount
 *     of one. Refcount will not be further increased when
 *     it is passed to wxVariant. This simulates old common
 *     scenario where wxVariant took ownership of wxVariantData
 *     passed to it.
 *     If you create wxVariantData for other reasons than passing
 *     it to wxVariant, technically you are not required to call
 *     DecRef() before deleting it.
 *
 * TODO: in order to replace wxPropertyValue, we would need
 * to consider adding constructors that take pointers to C++ variables,
 * or removing that functionality from the wxProperty library.
 * Essentially wxPropertyValue takes on some of the wxValidator functionality
 * by storing pointers and not just actual values, allowing update of C++ data
 * to be handled automatically. Perhaps there's another way of doing this without
 * overloading wxVariant with unnecessary functionality.
 */

class WXDLLIMPEXP_BASE wxVariantData: public wxObject
{
    friend class wxVariant;
public:
    wxVariantData()
        : wxObject(), m_count(1)
    { }

    // Override these to provide common functionality
    virtual bool Eq(wxVariantData& data) const = 0;

#if wxUSE_STD_IOSTREAM
    virtual bool Write(wxSTD ostream& WXUNUSED(str)) const { return false; }
#endif
    virtual bool Write(wxString& WXUNUSED(str)) const { return false; }
#if wxUSE_STD_IOSTREAM
    virtual bool Read(wxSTD istream& WXUNUSED(str)) { return false; }
#endif
    virtual bool Read(wxString& WXUNUSED(str)) { return false; }
    // What type is it? Return a string name.
    virtual wxString GetType() const = 0;
    // If it based on wxObject return the ClassInfo.
    virtual wxClassInfo* GetValueClassInfo() { return NULL; }

    void IncRef() { m_count++; }
    void DecRef()
    {
        if ( --m_count == 0 )
            delete this;
    }

    int GetRefCount() const { return m_count; }

protected:
    // Protected dtor should make some incompatible code
    // break more louder. That is, they should do data->DecRef()
    // instead of delete data.
    virtual ~wxVariantData() { }

private:
    int     m_count;

private:
    DECLARE_ABSTRACT_CLASS(wxVariantData)
};

/*
 * wxVariant can store any kind of data, but has some basic types
 * built in.
 */

class WXDLLIMPEXP_BASE wxVariant: public wxObject
{
public:
    wxVariant();

    wxVariant(const wxVariant& variant);
    wxVariant(wxVariantData* data, const wxString& name = wxEmptyString);
    virtual ~wxVariant();

    // generic assignment
    void operator= (const wxVariant& variant);

    // Assignment using data, e.g.
    // myVariant = new wxStringVariantData("hello");
    void operator= (wxVariantData* variantData);

    bool operator== (const wxVariant& variant) const;
    bool operator!= (const wxVariant& variant) const;

    // Sets/gets name
    inline void SetName(const wxString& name) { m_name = name; }
    inline const wxString& GetName() const { return m_name; }

    // Tests whether there is data
    bool IsNull() const;

    // For compatibility with wxWidgets <= 2.6, this doesn't increase
    // reference count.
    wxVariantData* GetData() const { return m_data; }
    void SetData(wxVariantData* data) ;

    // make a 'clone' of the object
    void Ref(const wxVariant& clone);

    // destroy a reference
    void UnRef();

    // Make NULL (i.e. delete the data)
    void MakeNull();

    // Delete data and name
    void Clear();

    // Returns a string representing the type of the variant,
    // e.g. "string", "bool", "stringlist", "list", "double", "long"
    wxString GetType() const;

    bool IsType(const wxString& type) const;
    bool IsValueKindOf(const wxClassInfo* type) const;

    // write contents to a string (e.g. for debugging)
    wxString MakeString() const;

    // double
    wxVariant(double val, const wxString& name = wxEmptyString);
    bool operator== (double value) const;
    bool operator!= (double value) const;
    void operator= (double value) ;
    inline operator double () const {  return GetDouble(); }
    inline double GetReal() const { return GetDouble(); }
    double GetDouble() const;

    // long
    wxVariant(long val, const wxString& name = wxEmptyString);
    wxVariant(int val, const wxString& name = wxEmptyString);
    wxVariant(short val, const wxString& name = wxEmptyString);
    bool operator== (long value) const;
    bool operator!= (long value) const;
    void operator= (long value) ;
    inline operator long () const {  return GetLong(); }
    inline long GetInteger() const { return GetLong(); }
    long GetLong() const;

    // bool
#ifdef HAVE_BOOL
    wxVariant(bool val, const wxString& name = wxEmptyString);
    bool operator== (bool value) const;
    bool operator!= (bool value) const;
    void operator= (bool value) ;
    inline operator bool () const {  return GetBool(); }
    bool GetBool() const ;
#endif

    // wxDateTime
#if wxUSE_DATETIME
    wxVariant(const wxDateTime& val, const wxString& name = wxEmptyString);
#if wxUSE_ODBC
    wxVariant(const DATE_STRUCT* valptr, const wxString& name = wxEmptyString);
    wxVariant(const TIME_STRUCT* valptr, const wxString& name = wxEmptyString);
    wxVariant(const TIMESTAMP_STRUCT* valptr, const wxString& name = wxEmptyString);
#endif
    bool operator== (const wxDateTime& value) const;
    bool operator!= (const wxDateTime& value) const;
    void operator= (const wxDateTime& value) ;
#if wxUSE_ODBC
    void operator= (const DATE_STRUCT* value) ;
    void operator= (const TIME_STRUCT* value) ;
    void operator= (const TIMESTAMP_STRUCT* value) ;
#endif
    inline operator wxDateTime () const { return GetDateTime(); }
    wxDateTime GetDateTime() const;
#endif

    // wxString
    wxVariant(const wxString& val, const wxString& name = wxEmptyString);
    wxVariant(const wxChar* val, const wxString& name = wxEmptyString); // Necessary or VC++ assumes bool!
    bool operator== (const wxString& value) const;
    bool operator!= (const wxString& value) const;
    void operator= (const wxString& value) ;
    void operator= (const wxChar* value) ; // Necessary or VC++ assumes bool!
    inline operator wxString () const {  return MakeString(); }
    wxString GetString() const;

    // wxChar
    wxVariant(wxChar val, const wxString& name = wxEmptyString);
    bool operator== (wxChar value) const;
    bool operator!= (wxChar value) const;
    void operator= (wxChar value) ;
    inline operator wxChar () const { return GetChar(); }
    wxChar GetChar() const ;

    // wxArrayString
    wxVariant(const wxArrayString& val, const wxString& name = wxEmptyString);
    bool operator== (const wxArrayString& value) const;
    bool operator!= (const wxArrayString& value) const;
    void operator= (const wxArrayString& value);
    inline operator wxArrayString () const { return GetArrayString(); }
    wxArrayString GetArrayString() const;

    // void*
    wxVariant(void* ptr, const wxString& name = wxEmptyString);
    bool operator== (void* value) const;
    bool operator!= (void* value) const;
    void operator= (void* value);
    inline operator void* () const {  return GetVoidPtr(); }
    void* GetVoidPtr() const;

    // wxObject*
    wxVariant(wxObject* ptr, const wxString& name = wxEmptyString);
    bool operator== (wxObject* value) const;
    bool operator!= (wxObject* value) const;
    void operator= (wxObject* value);
    wxObject* GetWxObjectPtr() const;

#if WXWIN_COMPATIBILITY_2_4
    wxDEPRECATED( wxVariant(const wxStringList& val, const wxString& name = wxEmptyString) );
    wxDEPRECATED( bool operator== (const wxStringList& value) const );
    wxDEPRECATED( bool operator!= (const wxStringList& value) const );
    wxDEPRECATED( void operator= (const wxStringList& value) );
    wxDEPRECATED( wxStringList& GetStringList() const );
#endif

    // ------------------------------
    // list operations
    // ------------------------------

    wxVariant(const wxList& val, const wxString& name = wxEmptyString); // List of variants
    bool operator== (const wxList& value) const;
    bool operator!= (const wxList& value) const;
    void operator= (const wxList& value) ;
    // Treat a list variant as an array
    wxVariant operator[] (size_t idx) const;
    wxVariant& operator[] (size_t idx) ;
    wxList& GetList() const ;

    // Return the number of elements in a list
    size_t GetCount() const;

    // Make empty list
    void NullList();

    // Append to list
    void Append(const wxVariant& value);

    // Insert at front of list
    void Insert(const wxVariant& value);

    // Returns true if the variant is a member of the list
    bool Member(const wxVariant& value) const;

    // Deletes the nth element of the list
    bool Delete(size_t item);

    // Clear list
    void ClearList();

public:
    // Type conversion
    bool Convert(long* value) const;
    bool Convert(bool* value) const;
    bool Convert(double* value) const;
    bool Convert(wxString* value) const;
    bool Convert(wxChar* value) const;
#if wxUSE_DATETIME
    bool Convert(wxDateTime* value) const;
#endif // wxUSE_DATETIME

// Attributes
protected:
    wxVariantData*  m_data;
    wxString        m_name;

private:
    DECLARE_DYNAMIC_CLASS(wxVariant)
};

#define DECLARE_VARIANT_OBJECT(classname) \
    DECLARE_VARIANT_OBJECT_EXPORTED(classname, wxEMPTY_PARAMETER_VALUE)

#define DECLARE_VARIANT_OBJECT_EXPORTED(classname,expdecl) \
expdecl classname& operator << ( classname &object, const wxVariant &variant ); \
expdecl wxVariant& operator << ( wxVariant &variant, const classname &object );

#define IMPLEMENT_VARIANT_OBJECT(classname) \
    IMPLEMENT_VARIANT_OBJECT_EXPORTED(classname, wxEMPTY_PARAMETER_VALUE)

#define IMPLEMENT_VARIANT_OBJECT_EXPORTED_NO_EQ(classname,expdecl) \
class classname##VariantData: public wxVariantData \
{ \
public:\
    classname##VariantData() {} \
    classname##VariantData( const classname &value ) { m_value = value; } \
\
    classname &GetValue() { return m_value; } \
\
    virtual bool Eq(wxVariantData& data) const; \
\
    virtual wxString GetType() const; \
    virtual wxClassInfo* GetValueClassInfo(); \
\
protected:\
    classname m_value; \
\
private: \
    DECLARE_CLASS(classname##VariantData) \
};\
\
IMPLEMENT_CLASS(classname##VariantData, wxVariantData)\
\
wxString classname##VariantData::GetType() const\
{\
    return m_value.GetClassInfo()->GetClassName();\
}\
\
wxClassInfo* classname##VariantData::GetValueClassInfo()\
{\
    return m_value.GetClassInfo();\
}\
\
expdecl classname& operator << ( classname &value, const wxVariant &variant )\
{\
    wxASSERT( wxIsKindOf( variant.GetData(), classname##VariantData ) );\
    \
    classname##VariantData *data = (classname##VariantData*) variant.GetData();\
    value = data->GetValue();\
    return value;\
}\
\
expdecl wxVariant& operator << ( wxVariant &variant, const classname &value )\
{\
    classname##VariantData *data = new classname##VariantData( value );\
    variant.SetData( data );\
    return variant;\
}

// implements a wxVariantData-derived class using for the Eq() method the
// operator== which must have been provided by "classname"
#define IMPLEMENT_VARIANT_OBJECT_EXPORTED(classname,expdecl) \
IMPLEMENT_VARIANT_OBJECT_EXPORTED_NO_EQ(classname,wxEMPTY_PARAMETER_VALUE expdecl) \
\
bool classname##VariantData::Eq(wxVariantData& data) const \
{\
    wxASSERT( wxIsKindOf((&data), classname##VariantData) );\
\
    classname##VariantData & otherData = (classname##VariantData &) data;\
\
    return otherData.m_value == m_value;\
}\

// implements a wxVariantData-derived class using for the Eq() method a shallow
// comparison (through wxObject::IsSameAs function)
#define IMPLEMENT_VARIANT_OBJECT_SHALLOWCMP(classname) \
    IMPLEMENT_VARIANT_OBJECT_EXPORTED_SHALLOWCMP(classname, wxEMPTY_PARAMETER_VALUE)
#define IMPLEMENT_VARIANT_OBJECT_EXPORTED_SHALLOWCMP(classname,expdecl) \
IMPLEMENT_VARIANT_OBJECT_EXPORTED_NO_EQ(classname,wxEMPTY_PARAMETER_VALUE expdecl) \
\
bool classname##VariantData::Eq(wxVariantData& data) const \
{\
    wxASSERT( wxIsKindOf((&data), classname##VariantData) );\
\
    classname##VariantData & otherData = (classname##VariantData &) data;\
\
    return (otherData.m_value.IsSameAs(m_value));\
}\

// Since we want type safety wxVariant we need to fetch and dynamic_cast
// in a seemingly safe way so the compiler can check, so we define
// a dynamic_cast /wxDynamicCast analogue.

#define wxGetVariantCast(var,classname) \
    ((classname*)(var.IsValueKindOf(&classname::ms_classInfo) ?\
                  var.GetWxObjectPtr() : NULL));

extern wxVariant WXDLLIMPEXP_BASE wxNullVariant;

#endif // wxUSE_VARIANT

#endif // _WX_VARIANT_H_


text:
<?php
/**
 * [PHPFOX_HEADER]
 */

defined('PHPFOX') or exit('NO DICE!');

/**
 *
 *
 * @copyright		[PHPFOX_COPYRIGHT]
 * @author  		Miguel Espinoza
 * @package 		Phpfox_Component
 * @version 		$Id: controller.class.php 103 2009-01-27 11:32:36Z Raymond_Benc $
 */
class Apps_Service_Category_Process extends Phpfox_Service
{
	/**
	 * Adds a category, called from the adminCP
	 * @param string $sName
	 * @return bool
	 */
	public function add($sName)
	{
		Phpfox::isAdmin(true);
		$this->database()->insert(Phpfox::getT('app_category'), array(
			'name' => Phpfox::getLib('parse.input')->clean($sName),
			'is_active' => '1'
		));
		return true;
	}

	/**
	 * Changes the name of a category
	 * Most commonly executed from an ajax call in the admincp
	 * @param int $iId
	 * @param string $sName
	 * @return bool
	 */
	public function updateCategory($iId, $sName)
	{
		Phpfox::isAdmin(true);
		$this->database()->update(Phpfox::getT('app_category'),array(
			'name' => Phpfox::getLib('parse.input')->clean($sName)
				), 'category_id = ' . (int)$iId);
		return true;
	}

	/**
	 * Deletes a category
	 * @param int $iId
	 * @return bool
	 */
	public function deleteCategory($iId)
	{
		Phpfox::isAdmin(true);
		$this->database()->delete(Phpfox::getT('app_category'), 'category_id = ' . (int)$iId);
		$this->database()->delete(Phpfox::getT('app_category_data'), 'category_id = ' . (int)$iId);
		return true;
	}
}

?>

redpajama_set_name: RedPajamaGithub


text:
package ru.vyarus.dropwizard.guice.test.jupiter.method;

import io.dropwizard.Application;
import io.dropwizard.Configuration;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.platform.testkit.engine.EngineTestKit;
import ru.vyarus.dropwizard.guice.GuiceBundle;
import ru.vyarus.dropwizard.guice.hook.GuiceyConfigurationHook;
import ru.vyarus.dropwizard.guice.test.EnableHook;
import ru.vyarus.dropwizard.guice.test.jupiter.env.EnableSetup;
import ru.vyarus.dropwizard.guice.test.jupiter.env.TestEnvironmentSetup;
import ru.vyarus.dropwizard.guice.test.jupiter.ext.TestGuiceyAppExtension;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClass;

/**
 * @author Vyacheslav Rusakov
 * @since 04.06.2022
 */
public class PerMethodSupportFieldsTest {

    static List<String> fields = new ArrayList<>();

    @Test
    void testNonStaticFields() {

        EngineTestKit.engine("junit-jupiter")
                .configurationParameter("junit.jupiter.conditions.deactivate", "org.junit.*DisabledCondition")
                .selectors(selectClass(FieldsTest.class))
                .execute()
                .testEvents()
                .debug()
                .assertStatistics(stats -> stats.succeeded(2));

        Assertions.assertEquals(Arrays.asList(
                "ssetup", "setup", "shook", "hook", "ssetup", "setup", "shook", "hook"), fields);
    }

    @Disabled // prevent direct execution
    public static class FieldsTest {
        @EnableHook
        static GuiceyConfigurationHook shook = it -> fields.add("shook");

        @EnableHook
        GuiceyConfigurationHook hook = it -> fields.add("hook");

        @EnableSetup
        static TestEnvironmentSetup ssetup = it -> fields.add("ssetup");

        @EnableSetup
        TestEnvironmentSetup setup = it -> fields.add("setup");

        @RegisterExtension
        TestGuiceyAppExtension ext = TestGuiceyAppExtension.forApp(App.class).create();

        @Test
        void test1() {
        }

        @Test
        void test2() {
        }
    }

    public static class App extends Application<Configuration> {

        @Override
        public void initialize(Bootstrap<Configuration> bootstrap) {
            bootstrap.addBundle(GuiceBundle.builder().build());
        }

        @Override
        public void run(Configuration configuration, Environment environment) throws Exception {
        }
    }
}


text:
package org.jcodec.samples.mux;

import java.io.File;

public class AVCMP4Demux {
    public static void main(String[] args) {
        if (args.length < 2) {
            System.out.println("Syntax: <in.264> <out.mp4>\n" + "\tWhere:\n"
                    + "\t-q\tLook for stream parameters only in the beginning of stream");
            return;
        }

        File in = new File(args[0]);
        File out = new File(args[1]);
    }

}


text:
package com.github.pires.obd.commands;

import static org.powermock.api.easymock.PowerMock.createMock;
import static org.powermock.api.easymock.PowerMock.expectLastCall;
import static org.powermock.api.easymock.PowerMock.replayAll;
import static org.powermock.api.easymock.PowerMock.verifyAll;
import static org.testng.Assert.assertEquals;

import java.io.IOException;
import java.io.InputStream;

import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import com.github.pires.obd.commands.fuel.FuelLevelCommand;

/**
 * Tests for FuelLevelCommand class.
 */
public class FuelLevelCommandTest {
    private FuelLevelCommand command = null;
    private InputStream mockIn = null;

    /**
     * @throws Exception
     */
    @BeforeMethod
    public void setUp() throws Exception {
        command = new FuelLevelCommand();
    }

    /**
     * Test for valid InputStream read, full tank
     *
     * @throws IOException
     */
    @Test
    public void testFullTank() throws IOException {
        // mock InputStream read
        mockIn = createMock(InputStream.class);
        mockIn.read();
        expectLastCall().andReturn((byte) '4');
        expectLastCall().andReturn((byte) '1');
        expectLastCall().andReturn((byte) ' ');
        expectLastCall().andReturn((byte) '2');
        expectLastCall().andReturn((byte) 'F');
        expectLastCall().andReturn((byte) ' ');
        expectLastCall().andReturn((byte) 'F');
        expectLastCall().andReturn((byte) 'F');
        expectLastCall().andReturn((byte) '>');

        replayAll();

        // call the method to test
        command.readResult(mockIn);
        assertEquals(command.getFuelLevel(), 100f);

        verifyAll();
    }

    /**
     * Test for valid InputStream read. 78.4%
     *
     * @throws IOException
     */
    @Test
    public void testSomeValue() throws IOException {
        // mock InputStream read
        mockIn = createMock(InputStream.class);
        mockIn.read();
        expectLastCall().andReturn((byte) '4');
        expectLastCall().andReturn((byte) '1');
        expectLastCall().andReturn((byte) ' ');
        expectLastCall().andReturn((byte) '2');
        expectLastCall().andReturn((byte) 'F');
        expectLastCall().andReturn((byte) ' ');
        expectLastCall().andReturn((byte) 'C');
        expectLastCall().andReturn((byte) '8');
        expectLastCall().andReturn((byte) '>');

        replayAll();

        // call the method to test
        command.readResult(mockIn);
        assertEquals(command.getFuelLevel(), 78.43137f);

        verifyAll();
    }

    /**
     * Test for valid InputStream read, empty tank
     *
     * @throws IOException
     */
    @Test
    public void testEmptyTank() throws IOException {
        // mock InputStream read
        mockIn = createMock(InputStream.class);
        mockIn.read();
        expectLastCall().andReturn((byte) '4');
        expectLastCall().andReturn((byte) '1');
        expectLastCall().andReturn((byte) ' ');
        expectLastCall().andReturn((byte) '2');
        expectLastCall().andReturn((byte) 'F');
        expectLastCall().andReturn((byte) ' ');
        expectLastCall().andReturn((byte) '0');
        expectLastCall().andReturn((byte) '0');
        expectLastCall().andReturn((byte) '>');

        replayAll();

        // call the method to test
        command.readResult(mockIn);
        assertEquals(command.getFuelLevel(), 0f);

        verifyAll();
    }

    /**
     * Clear resources.
     */
    @AfterClass
    public void tearDown() {
        command = null;
        mockIn = null;
    }

}


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="net.sabamiso.android.simplemqttviewer.SimpleMQTTViewerActivity" >

    <item
        android:id="@+id/action_publish_message"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="@string/action_publish_message"/>

    <item
        android:id="@+id/action_clear"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="@string/action_clear"/>

    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="@string/action_settings"/>
</menu>


text:
package genswagger

import (
	"github.com/gengo/grpc-gateway/protoc-gen-grpc-gateway/descriptor"
	"github.com/go-swagger/go-swagger/spec"
)

func messageRef(m *descriptor.Message) spec.Ref {
	return spec.MustCreateRef("#/definitions/" + m.GetModelName())
}


text:
package TBC.Combat.Effects;

import TBC.Combat.CombatEntity;

public interface IEffectFactory
{
	Object CreateEffect(CombatEntity user, CombatEntity target);
}


text:
<?php

namespace dosamigos\google\maps;

use yii\base\BaseObject;
use yii\base\InvalidConfigException;
use yii\base\InvalidParamException;

/**
 * Event
 *
 * Google maps event
 *
 * @author Antonio Ramirez <hola@2amigos.us>
 *
 * @link http://www.2amigos.us/
 * @package dosamigos\google\maps
 */
class Event extends BaseObject
{
    /**
     * @var string the action that will trigger the event
     */
    public $trigger;
    /**
     * @var string the javascript code to be executed
     */
    public $js;
    /**
     * @var bool whether to wrap the js code within a javascript function (ie `"function(){ $js }"`)
     */
    public $wrap = true;
    /**
     * @var string the type of event. Defaults to [[EventType::DEFAULT_EVENT]]
     */
    private $_type = EventType::DEFAULT_EVENT;

    /**
     * @inheritdoc
     */
    public function init()
    {
        if (empty($this->trigger)) {
            throw new InvalidConfigException('"$trigger" cannot be null.');
        }
        if (empty($this->js)) {
            throw new InvalidConfigException('"js" cannot be null.');
        }
        parent::init();
    }

    /**
     * Sets the type of event, by default Google Event
     *
     * @param string $value
     *
     * @throws \yii\base\InvalidParamException
     */
    public function setType($value)
    {
        if (!EventType::getIsValid($value)) {
            throw new InvalidParamException('Unrecognized event type');
        }
        $this->_type = $value;
    }

    /**
     * Returns type of event
     * @return string
     */
    public function getType()
    {
        return $this->_type;
    }

    /**
     * Returns the js function to be executed
     * @return string
     */
    public function getFunction()
    {
        return $this->wrap
            ? "function(event){{$this->js}}"
            : $this->js;
    }

    /**
     * Returns the javascript code for attaching a Google event to a javascript object
     *
     * @param string $name the javascript object name to attach the event to
     * @param bool $once whether to make a one time call event or not
     *
     * @return string
     */
    public function getEventJs($name, $once = false)
    {
        $once = ($once) ? 'Once' : '';
        return "google.maps.event.addListener$once($name, '{$this->trigger}', {$this->getFunction()});";
    }

    /**
     * Returns the javascript code for attaching a dom event to a javascript object
     *
     * @param string $name
     * @param bool $once
     *
     * @return string
     */
    public function getDomEventJs($name, $once = false)
    {
        $once = ($once) ? 'Once' : '';
        return "google.maps.event.addDomListener$once($name, '{$this->trigger}', {$this->getFunction()});";
    }

    /**
     * Returns the js code to attach a Google event or a Dom event to a js object
     *
     * @param string $name the object name
     *
     * @return string the js event
     */
    public function getJs($name)
    {
        switch ($this->getType()) {
            case EventType::DEFAULT_ONCE:
                return $this->getEventJs($name, true);
            case EventType::DOM:
                return $this->getDomEventJs($name);
            case EventType::DOM_ONCE:
                return $this->getDomEventJs($name, true);
            case EventType::DEFAULT_EVENT:
            default:
                return $this->getEventJs($name);
        }
    }
}


text:
import { existsSync, mkdirSync } from 'fs';
import { join } from 'path';
import { I18nOptions } from './i18n-options';

export function ensureOutputPaths(baseOutputPath: string, i18n: I18nOptions): Map<string, string> {
  const outputPaths: [string, string][] =
    i18n.shouldInline
      ? [...i18n.inlineLocales].map(l => [l, i18n.flatOutput ? baseOutputPath : join(baseOutputPath, l)])
      : [
          i18n.veCompatLocale
            ? [i18n.veCompatLocale, join(baseOutputPath, i18n.veCompatLocale)]
            : ['', baseOutputPath],
        ];

  for (const [, outputPath] of outputPaths) {
    if (!existsSync(outputPath)) {
      mkdirSync(outputPath, { recursive: true });
    }
  }

  return new Map(outputPaths);
}


text:
#include "tensorflow/compiler/xla/service/loop_schedule_linearizer.h"

#include "tensorflow/compiler/xla/service/dump.h"
#include "tensorflow/compiler/xla/service/graphcycles/graphcycles.h"

namespace xla {

namespace {

// Calculate ordering for HLO, for fast online checking of whether adding
// additional dependencies would create cycles.
struct ComputationInstructionOrdering {
  explicit ComputationInstructionOrdering(const HloComputation& computation) {
    for (const HloInstruction* instr : computation.instructions()) {
      for (const HloInstruction* control_pred : instr->control_predecessors()) {
        CHECK(this->InsertEdge(*control_pred, *instr))
            << "Graph already contained a cycle";
      }

      for (int op_id = 0; op_id < instr->operand_count(); op_id++) {
        const HloInstruction* op = instr->operand(op_id);
        CHECK(this->InsertEdge(*op, *instr))
            << "Graph already contained a cycle";
      }
    }
  }

  int32_t NodeIdForInstruction(const HloInstruction& instr) {
    int32_t instruction_id = instr.unique_id();
    auto it = node_id_to_graph_id.find(instruction_id);

    if (it != node_id_to_graph_id.end()) {
      return it->second;
    }
    int32_t node_id = graph_cycles.NewNode();
    node_id_to_graph_id[instruction_id] = node_id;
    return node_id;
  }

  // Returns `false` if adding an edge would have introduced a cycle. Does not
  // add an edge in that case. Returns `true` otherwise.
  bool InsertEdge(const HloInstruction& source, const HloInstruction& dest) {
    int32_t source_id = NodeIdForInstruction(source);
    int32_t dest_id = NodeIdForInstruction(dest);
    return graph_cycles.InsertEdge(source_id, dest_id);
  }

  absl::flat_hash_map<int32_t, int32_t> node_id_to_graph_id;

  tensorflow::GraphCycles graph_cycles;
};

}  // namespace

static StatusOr<bool> AddControlEdgesForLoopWrites(
    HloInstruction* xla_while, HloAliasAnalysis& alias_analysis) {
  HloDataflowAnalysis& dataflow = alias_analysis.dataflow_analysis();
  HloComputation* body = xla_while->while_body();
  HloInstruction* root = body->root_instruction();
  HloInstruction* input = body->parameter_instruction(0);

  bool changed = false;

  // Compute dependency ordering ourselves. The reason we don't reuse other
  // computations is because it is hard to extract the underlying graph from
  // those abstractions.
  ComputationInstructionOrdering ordering(*body);
  ShapeTree<bool> indices_to_copy(xla_while->shape());

  for (auto& p : indices_to_copy) {
    const ShapeIndex& index = p.first;

    if (index.empty()) {
      continue;
    }

    if (dataflow.GetValueSet(root, index).values().size() > 1 ||
        dataflow.GetValueSet(input, index).values().size() > 1) {
      VLOG(2) << "Index " << index.ToString() << " is associated with multiple "
              << "values, not attempting to introduce stricter dependencies";
    } else {
      HloValue& value_at_root = dataflow.GetUniqueValueAt(root, index);
      HloValue& value_at_input = dataflow.GetUniqueValueAt(input, index);

      if (value_at_root.shape().IsTuple()) {
        // TODO(cheshire): For simplicity we currently do not handle nested
        // tuples, as we haven't seen them in the examples we care about.
        continue;
      }

      // TODO(cheshire): This is too conservative and does not take aliasing
      // into account.
      HloInstruction* write = value_at_root.defining_instruction();

      for (const HloUse& use : value_at_input.GetUses()) {
        HloInstruction* read = use.instruction;

        if (read != write &&
            value_at_root != value_at_input

            // TODO(cheshire): Parents sometimes differ in case of e.g. nested
            // loops, where the value is read/written into in the inner loop.
            // For now we skip this case for simplicity (as the inner loop
            // performance is more important in any case)
            && read->parent() == write->parent()) {
          VLOG(2) << "Inside " << body->name() << ", index "
                  << index.ToString();
          if (!ordering.InsertEdge(*read, *write)) {
            VLOG(2) << "Not adding a control dependency from "
                    << read->ToShortString() << " to " << write->ToShortString()
                    << " as it would introduce a cycle";
            continue;
          }

          changed |= absl::c_linear_search(read->control_successors(), write);

          // Unless we want a copy, read should happen before write.
          TF_RETURN_IF_ERROR(read->AddControlDependencyTo(write));
          VLOG(2) << "Adding dependency: " << read->ToShortString()
                  << " before " << write->ToShortString();
        }
      }
    }
  }
  return changed;
}

StatusOr<bool> LoopScheduleLinearizer::Run(HloModule* module) {
  TF_ASSIGN_OR_RETURN(std::unique_ptr<HloAliasAnalysis> alias_analysis,
                      HloAliasAnalysis::Run(module, can_share_buffer_));

  bool changed = false;
  for (HloComputation* computation : module->MakeNonfusionComputations()) {
    for (HloInstruction* instruction :
         computation->MakeInstructionPostOrder()) {
      if (instruction->opcode() == HloOpcode::kWhile) {
        StatusOr<bool> updated_loop =
            AddControlEdgesForLoopWrites(instruction, *alias_analysis);
        TF_RETURN_IF_ERROR(updated_loop.status());
        changed |= *updated_loop;
      }
    }
  }
  DumpHloModuleDuringPassIfEnabled(
      name(), "after inserting control edges inside while loop bodies",
      *module);

  return changed;
}

}  // end namespace xla


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

<TITLE>
com.intel.hadoop.graphbuilder.test.partition
</TITLE>

<META NAME="date" CONTENT="2012-11-08">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

com.intel.hadoop.graphbuilder.test.partition

Classes

EdgeIngressTest

VrecordMapReduceTest


text:
from django.db import models
from django.contrib.auth.models import User

# Create your models here.
class Profile(models.Model):
    user = models.ForeignKey(User)
    stripe_id = models.CharField(max_length=300)
    timestamp = models.DateTimeField(auto_now_add=True)
    update = models.DateTimeField(auto_now_add=False, auto_now=True)

    def __unicode__(self):
        return str(self.user)

class Address(models.Model):
    user = models.ForeignKey(User)
    nickname = models.CharField(null=True, blank=True, max_length=120)
    address1 = models.CharField(max_length=300, default="")
    address2 = models.CharField(null=True, blank=True, max_length=300, default="")
    city = models.CharField(max_length=300)
    state = models.CharField(max_length=300)
    country = models.CharField(max_length=300)
    postal_code = models.CharField(max_length=300)
    timestamp = models.DateTimeField(auto_now_add=True)
    update = models.DateTimeField(auto_now_add=False, auto_now=True)
    default_address = models.BooleanField(default=False)
    billing_address = models.BooleanField(default=True)
    shipping_address = models.BooleanField(default=True)

    class Meta:
        verbose_name = ('Address')
        verbose_name_plural = ('Addresses')

    def __unicode__(self):
        return self.address1


text:
<?php

declare(strict_types=1);

namespace Genkgo\TestCamt\Util;

use Genkgo\Camt\Util\MoneyFactory;
use Money\Money;
use PHPUnit\Framework\TestCase;
use SimpleXMLElement;

class MoneyFactoryTest extends TestCase
{
    /**
     * @dataProvider providerCreate
     */
    public function testCreate(string $amount, ?string $CdtDbtInd, Money $expected): void
    {
        $factory = new MoneyFactory();

        $xmlAmount = new SimpleXMLElement($amount);
        $xmlCdtDbtInd = $CdtDbtInd ? new SimpleXMLElement($CdtDbtInd) : null;
        $actual = $factory->create($xmlAmount, $xmlCdtDbtInd);

        self::assertTrue($actual->equals($expected));
    }

    public function providerCreate(): array
    {
        return [
            ['<Amt Ccy="CHF">27.50</Amt>', null, Money::CHF(2750)],
            ['<Amt Ccy="CHF">27.50</Amt>', '<CdtDbtInd>DBIT</CdtDbtInd>', Money::CHF(-2750)],
            ['<Amt Ccy="CHF">27.50</Amt>', '<CdtDbtInd>CRDT</CdtDbtInd>', Money::CHF(2750)],
            ['<Amt Ccy="JPY">27</Amt>', null, Money::JPY(27)],
            ['<Amt Ccy="JPY">27</Amt>', '<CdtDbtInd>DBIT</CdtDbtInd>', Money::JPY(-27)],
            ['<Amt Ccy="JPY">27</Amt>', '<CdtDbtInd>CRDT</CdtDbtInd>', Money::JPY(27)],
        ];
    }
}


text:
/**
 * Unfex - unferno extentions
 *
 * @overview	Unfex provides a basic set of classes that can be used as a foundation for application development.
 * @author		taka:unferno.jp
 * @version		1.0.0
 * @see			http://unferno.jp/
 *
 * Licensed under the MIT License
 * http://www.opensource.org/licenses/mit-license.php
 */

using System.Collections;
using Unfex.Components;
using Unfex.Events;
using Unfex.Views.Core;
using UnityEngine;
using UnityEngine.UI;

namespace Unfex.Views {

	public class AlertDialog:DialogBase {

		#region Properties
		public Text messageText {
			get { return _messageText; }
		}
		[SerializeField] Text _messageText = null;

		public UXButton okButton {
			get { return _okButton; }
		}
		[SerializeField] UXButton _okButton = null;
		#endregion

		#region Static Methods
		public static AlertDialog GetPrefab() {
			GameObject gameObject = Resources.Load( "Unfex/Prefabs/Views/AlertDialog" ) as GameObject;

			AlertDialog prefab = gameObject.GetComponent<AlertDialog>();

			return prefab;
		}
		#endregion

		#region Methods
		public override IEnumerator Show() {
			yield return null;
		}

		public override IEnumerator Hide() {
			yield return null;
		}
		#endregion

		#region EventHandlers
		protected override void Awake() {
			base.Awake();
		}

		protected virtual void Init( string message ) {
			base.Init();

			_messageText.text = message;
		}

		protected override void Start() {
			base.Start();

			rectTransform.localPosition = new Vector3( 0, 0, 0 );
			rectTransform.anchorMin = new Vector2( 0, 0 );
			rectTransform.anchorMax = new Vector2( 1, 1 );
			rectTransform.sizeDelta = new Vector2( 0, 0 );

			UXEventDelegate.AddListener( _okButton, InputEventData.onClick, _okButtonOnClick );
		}

		protected override void OnDestroy() {
			base.OnDestroy();

			UXEventDelegate.RemoveListener( _okButton, InputEventData.onClick, _okButtonOnClick );
		}

		void _okButtonOnClick() {
			OK();
		}
		#endregion
	}
}


text:
{-# LANGUAGE NamedWildCards, ScopedTypeVariables, RankNTypes #-}
module WildcardInstantiations where

foo :: (Show _a, _) => _a -> _
foo x = show (succ x)

bar :: _ -> _ -> _
bar x y = y x


text:
package com.wandrell.tabletop.punkapocalyptic.model.availability;

import java.util.Collection;

import com.wandrell.tabletop.punkapocalyptic.model.unit.UnitTemplate;
import com.wandrell.tabletop.punkapocalyptic.model.unit.mutation.Mutation;

/**
 * Interface representing a unit's mutation availabilities.
 * <p>
 * This is used when setting up a unit.
 *
 * @author Bernardo Martínez Garrido
 */
public interface UnitMutationAvailability {

    /**
     * Returns the maximum allowed number of mutations which can be acquired.
     *
     * @return the mutations limit
     */
    public Integer getMaxMutations();

    /**
     * Returns all the mutations which can be acquired.
     *
     * @return the mutation options
     */
    public Collection<? extends Mutation> getMutationOptions();

    /**
     * The unit to which the availabilities are applied.
     *
     * @return the unit
     */
    public UnitTemplate getUnit();

}


text:
bool isDigit(char x);
bool isOperation(char x);
bool isBracket(char x);


text:
package org.anstis.client.grid.model;

/**
 * Interface defining a cell's value holder within a grid.
 * @param <T> The Type of value
 */
public interface IGridCell<T> {

    /**
     * Get the value holder for the cell. It should be noted there is intentionally no "setter" as
     * mutation of the value may require further mutation to other data within the grid. Therefore mutation
     * of cell values is via the IGridData interface to ensure the integrity of all data within the grid.
     * @return
     */
    IGridCellValue<T> getValue();

}


text:
import { SQLDialect } from "../dialect";
import { ColumnType, CoreColumnTypes, ColumnTypeMap } from "../ColumnType";
import * as log from "loglevel";
import { BaseSQLDialect } from "../BaseSQLDialect";

const intCT = new ColumnType("INT64", "integer");
const floatCT = new ColumnType("FLOAT64", "real");
const stringCT = new ColumnType("STRING", "string");
const boolCT = new ColumnType("BOOL", "boolean");

const dateCT = new ColumnType("DATE", "date", {
  stringRender: (val: any) => (val == null ? "" : val.value),
});
const timestampCT = new ColumnType("TIMESTAMP", "timestamp", {
  stringRender: (val: any) => (val == null ? "" : val.value),
});

class BigQueryDialectClass extends BaseSQLDialect {
  private static instance: BigQueryDialectClass;
  readonly dialectName: string = "bigquery";
  readonly coreColumnTypes: CoreColumnTypes = {
    integer: intCT,
    real: floatCT,
    string: stringCT,
    boolean: boolCT,
  };

  readonly columnTypes: ColumnTypeMap = {
    INT64: intCT,
    FLOAT64: floatCT,
    STRING: stringCT,
    BOOL: boolCT,
    DATE: dateCT,
    TIMESTAMP: timestampCT,
  };

  quoteCol(cid: string): string {
    return "`" + cid + "`";
  }

  ppAggNull(aggStr: string, subExpStr: string, colType: ColumnType): string {
    return `CAST(null as ${colType.sqlTypeName})`;
  }

  static getInstance(): BigQueryDialectClass {
    if (!BigQueryDialectClass.instance) {
      BigQueryDialectClass.instance = new BigQueryDialectClass();
    }
    return BigQueryDialectClass.instance;
  }
}

export const BigQueryDialect = BigQueryDialectClass.getInstance();


text:
@interface UQLKeyValueStoreTests : UQLTestCase
@property (nonatomic, strong) UQLDatabase *database;
@end

@implementation UQLKeyValueStoreTests

- (void)setUp
{
    [super setUp];

	self.database = [UQLDatabase database];
	NSError *error = nil;
	[self.database openWithOptions:UQLOpenCreate error:&error];
	STAssertNil(error, @"Can not create database. Error %@", error);
}

- (void)testStoreFetchValue
{
	NSData *key = [@"test store key" dataUsingEncoding:NSUTF8StringEncoding];
	NSData *value = [@"test value" dataUsingEncoding:NSUTF8StringEncoding];

	[self.database storeData:value forRawKey:key];
	NSData *data = [self.database dataForRawKey:key];
	STAssertNotNil(data, @"Can not fetch value for key");
	STAssertTrue([data isEqualToData:value], @"Fetched data is not equals to stored");
}

- (void)testAppendValue
{
	NSData *key = [@"test append key" dataUsingEncoding:NSUTF8StringEncoding];
	NSData *value1 = [@"test value1" dataUsingEncoding:NSUTF8StringEncoding];
	NSData *value2 = [@" value2" dataUsingEncoding:NSUTF8StringEncoding];
	NSMutableData *value = [NSMutableData dataWithData:value1];
	[value appendData:value2];

	[self.database storeData:value1 forRawKey:key];
	NSData *data1 = [self.database dataForRawKey:key];
	STAssertNotNil(data1, @"Can not fetch value for key");
	STAssertTrue([data1 isEqualToData:value1], @"Fetched data is not equals to stored");

	[self.database appendData:value2 forRawKey:key];
	NSData *data2 = [self.database dataForRawKey:key];
	STAssertNotNil(data2, @"Can not fetch value for key");
	STAssertTrue([data2 isEqualToData:value], @"Fetched data is not equals to stored");
}

- (void)testDeleteValue
{
	NSData *key = [@"test delete key" dataUsingEncoding:NSUTF8StringEncoding];
	NSData *value = [@"test value" dataUsingEncoding:NSUTF8StringEncoding];

	[self.database storeData:value forRawKey:key];
	NSData *data = [self.database dataForRawKey:key];
	STAssertNotNil(data, @"Can not fetch value for key");

	[self.database removeDataForRawKey:key];
	NSData *nilData = [self.database dataForRawKey:key];
	STAssertNil(nilData, @"Fetched removed value for key");
}

- (void)testFetchValueCallback
{
	NSData *key = [@"test fetch callback key" dataUsingEncoding:NSUTF8StringEncoding];
	NSMutableData *value = [[NSMutableData alloc] initWithLength:1024 * 1024 * 10];
	NSMutableData *data = [[NSMutableData alloc] init];

	[self.database storeData:value forRawKey:key];
	[self.database dataForRawKey:key callback:^BOOL(NSData *chunk) {
		[data appendData:chunk];
		return YES;
	}];
	STAssertTrue([data isEqualToData:value], @"Fetched data is not equals to stored");
}

@end


text:
using System;
using System.Linq;
using System.Web.UI;

using DotNetNuke.Common.Internal;
using DotNetNuke.Entities.Controllers;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Tabs;
using DotNetNuke.Framework.JavaScriptLibraries;
using DotNetNuke.UI.Utilities;

#endregion

namespace DotNetNuke.Framework
{
    /// -----------------------------------------------------------------------------
    /// Project	 : DotNetNuke
    /// Class	 : CDefault
    /// -----------------------------------------------------------------------------
    /// -----------------------------------------------------------------------------
    public class CDefault : PageBase
    {
        public string Author = string.Empty;
        public string Comment = string.Empty;
        public string Copyright = string.Empty;
        public string Description = string.Empty;
        public string Generator = string.Empty;
        public string KeyWords = string.Empty;
        public new string Title = string.Empty;

        private static readonly object InstallerFilesRemovedLock = new object();

        protected override void RegisterAjaxScript()
        {
            if (Page.Form != null)
            {
                if (ServicesFrameworkInternal.Instance.IsAjaxScriptSupportRequired)
                {
                    ServicesFrameworkInternal.Instance.RegisterAjaxScript(Page);
                }
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Allows the scroll position on the page to be moved to the top of the passed in control.
        /// </summary>
        /// <param name="objControl">Control to scroll to</param>
        /// -----------------------------------------------------------------------------
        public void ScrollToControl(Control objControl)
        {
            if (ClientAPI.BrowserSupportsFunctionality(ClientAPI.ClientFunctionality.Positioning))
            {
                JavaScript.RegisterClientReference(this, ClientAPI.ClientNamespaceReferences.dnn_dom_positioning);
                ClientAPI.RegisterClientVariable(this, "ScrollToControl", objControl.ClientID, true);
                DNNClientAPI.SetScrollTop(Page);
            }
        }

        protected void ManageInstallerFiles()
        {
            if (!HostController.Instance.GetBoolean("InstallerFilesRemoved"))
            {
                lock (InstallerFilesRemovedLock)
                {
                    if (!HostController.Instance.GetBoolean("InstallerFilesRemoved"))
                    {
                        Services.Upgrade.Upgrade.DeleteInstallerFiles();
                        HostController.Instance.Update("InstallerFilesRemoved", "True", true);
                    }
                }
            }
        }

        protected string AdvancedSettingsPageUrl
        {
            get
            {
                string result ;
                var tab = TabController.Instance.GetTabByName("Advanced Settings", PortalSettings.PortalId);
                var modules = ModuleController.Instance.GetTabModules(tab.TabID).Values;

                if (modules.Count > 0)
                {
                    var pmb = new PortalModuleBase();
                    result = pmb.EditUrl(tab.TabID, "", false, string.Concat("mid=", modules.ElementAt(0).ModuleID), "popUp=true", string.Concat("ReturnUrl=", Server.UrlEncode(TestableGlobals.Instance.NavigateURL())));
                }
                else
                {
                    result = TestableGlobals.Instance.NavigateURL(tab.TabID);
                }

                return result;
            }
        }

        #region Obsolete Methods

        [Obsolete("Deprecated in DotNetNuke 6.0.  Replaced by RegisterStyleSheet")]
        public void AddStyleSheet(string id, string href, bool isFirst)
        {
            RegisterStyleSheet(this, href, isFirst);
        }

        [Obsolete("Deprecated in DotNetNuke 6.0.  Replaced by RegisterStyleSheet")]
        public void AddStyleSheet(string id, string href)
        {
            RegisterStyleSheet(this, href, false);
        }

        #endregion
    }
}


text:
using EdjCase.JsonRpc.Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace EdjCase.JsonRpc.Client
{
	internal interface IRequestSerializer
	{
		string SerializeBulk(IList<RpcRequest> requests);
		string Serialize(RpcRequest request);
		List<RpcResponse> Deserialize(string json, IDictionary<RpcId, Type> typeMap);
	}

	public class DefaultRequestJsonSerializer : IRequestSerializer
	{
		private JsonSerializerSettings? jsonSerializerSettings { get; }
		private IDictionary<int, Type>? errorTypes { get; }
		internal DefaultRequestJsonSerializer(
			JsonSerializerSettings? jsonSerializerSettings = null,
			IDictionary<int, Type>? errorTypes = null)
		{
			this.jsonSerializerSettings = jsonSerializerSettings;
			this.errorTypes = errorTypes;
		}

		public List<RpcResponse> Deserialize(string json, IDictionary<RpcId, Type> typeMap)
		{
			using TextReader textReader = new StringReader(json);
			using JsonReader reader = new JsonTextReader(textReader)
			{
				//Prevent auto date parsing
				DateParseHandling = DateParseHandling.None
			};

			List<RpcResponse> responses;
			JToken token = JToken.Load(reader);
			switch (token.Type)
			{
				case JTokenType.Array:
					responses = token.Select(Deserialize).ToList();
					RpcResponse Deserialize(JToken t)
					{
						return this.DeserializeResponse(t, typeMap);
					}
					break;
				case JTokenType.Object:
					RpcResponse response = this.DeserializeResponse(token, typeMap);
					responses = new List<RpcResponse> { response };
					break;
				default:
					throw new ArgumentOutOfRangeException(nameof(token.Type));
			}
			return responses;
		}

		public RpcResponse DeserializeResponse(JToken token, IDictionary<RpcId, Type> typeMap)
		{
			JToken? idToken = token[JsonRpcContants.IdPropertyName];
			if (idToken == null)
			{
				throw new RpcClientParseException("Unable to parse request id.");
			}
			RpcId id;
			switch (idToken.Type)
			{
				case JTokenType.Null:
					id = new RpcId();
					break;
				case JTokenType.Integer:
					id = new RpcId(idToken.Value<long>());
					break;
				case JTokenType.String:
				case JTokenType.Guid:
					id = new RpcId(idToken.Value<string>());
					break;
				default:
					throw new RpcClientParseException("Unable to parse rpc id as string or integer.");
			}
			if(!typeMap.TryGetValue(id, out Type type))
			{
				throw new RpcClientParseException("Unable to detect result type, cannot deserialize.");
			}
			JToken? errorToken = token[JsonRpcContants.ErrorPropertyName];
			if (errorToken != null && errorToken.HasValues)
			{
				int code = errorToken.Value<int>(JsonRpcContants.ErrorCodePropertyName);
				string message = errorToken.Value<string>(JsonRpcContants.ErrorMessagePropertyName);
				JToken? dataToken = errorToken[JsonRpcContants.ErrorDataPropertyName];

				object? data = null;
				if (dataToken != null)
				{
					if (this.errorTypes != null && this.errorTypes.TryGetValue(code, out Type errorCodeType))
					{
						data = dataToken.ToObject(errorCodeType);
					}
					else
					{
						data = dataToken.ToString();
					}
				}
				var error = new RpcError(code, message, data: data);
				return new RpcResponse(id, error);
			}
			else
			{
				object? result;
				if (this.jsonSerializerSettings == null)
				{
					result = token[JsonRpcContants.ResultPropertyName]?.ToObject(type);
				}
				else
				{
					//TODo cache serializer?
					JsonSerializer serializer = JsonSerializer.Create(this.jsonSerializerSettings);
					result = token[JsonRpcContants.ResultPropertyName]?.ToObject(type, serializer);
				}
				return new RpcResponse(id, result);
			}
		}

		public string Serialize(RpcRequest request)
		{
			return this.SerializeInternal(new[] { request }, isBulkRequest: false);
		}

		public string SerializeBulk(IList<RpcRequest> requests)
		{
			return this.SerializeInternal(requests, isBulkRequest: true);
		}

		private string SerializeInternal(IEnumerable<RpcRequest> requests, bool isBulkRequest)
		{
			using StringWriter textWriter = new StringWriter();
			using (JsonTextWriter jsonWriter = new JsonTextWriter(textWriter))
			{
				if (isBulkRequest)
				{
					jsonWriter.WriteStartArray();
					foreach (RpcRequest request in requests)
					{
						this.SerializeRequest(request, jsonWriter);
					}
					jsonWriter.WriteEndArray();
				}
				else
				{
					this.SerializeRequest(requests.Single(), jsonWriter);
				}
			}
			return textWriter.ToString();

		}

		private void SerializeRequest(RpcRequest request, JsonTextWriter jsonWriter)
		{
			jsonWriter.WriteStartObject();
			jsonWriter.WritePropertyName(JsonRpcContants.IdPropertyName);
			jsonWriter.WriteValue(request.Id.Value);
			jsonWriter.WritePropertyName(JsonRpcContants.VersionPropertyName);
			jsonWriter.WriteValue("2.0");
			jsonWriter.WritePropertyName(JsonRpcContants.MethodPropertyName);
			jsonWriter.WriteValue(request.Method);
			jsonWriter.WritePropertyName(JsonRpcContants.ParamsPropertyName);
			if (!request.Parameters.HasValue)
			{
				//empty arrray
				jsonWriter.WriteStartArray();
				jsonWriter.WriteEndArray();
			}
			else
			{
				switch (request.Parameters.Type)
				{
					case RpcParametersType.Array:
						jsonWriter.WriteStartArray();
						foreach (object value in request.Parameters.ArrayValue)
						{
							this.SerializeValue(value, jsonWriter);
						}
						jsonWriter.WriteEndArray();
						break;
					case RpcParametersType.Dictionary:
						jsonWriter.WriteStartObject();
						foreach (KeyValuePair<string, object> value in request.Parameters.DictionaryValue)
						{
							jsonWriter.WritePropertyName(value.Key);
							this.SerializeValue(value.Value, jsonWriter);
						}
						jsonWriter.WriteEndObject();
						break;
				}
			}
			jsonWriter.WriteEndObject();
		}

		private void SerializeValue(object value, JsonTextWriter jsonWriter)
		{
			if (value != null)
			{
				string valueJson;
				if (this.jsonSerializerSettings == null)
				{
					valueJson = JsonConvert.SerializeObject(value);
				}
				else
				{
					valueJson = JsonConvert.SerializeObject(value, this.jsonSerializerSettings);
				}
				jsonWriter.WriteRawValue(valueJson);
			}
			else
			{
				jsonWriter.WriteNull();
			}
		}

	}
}


text:
layout: year
title: North West Provincial Gazettes 2007
jurisdiction: ZA-NW
jurisdiction_name: North West
provincial: true
year: "2007"
---


text:
package com.urbanairship.datacube;

import java.io.IOException;

/**
 * A service for translating byte[]s consistently into unique IDs. If the given byte[] has been
 * seen before, the same identifier will be returned as the previous call. If this is the first
 * time byte[] has been seen, a new identifier will be assigned.
 *
 * Different identifier lengths can be used to save space. For example, if you have a dimension
 * that stores a boolean, it can only have two distinct values, so you only need one byte to encode
 * datapoints in that dimension. On the other hand, to store the name of a city, you would need
 * more bytes to encode it since there are many cities.
 *
 * Implementations can assume that numIdBytes will never change over the life of a cube for a
 * given dimension.
 *
 * Implementations are required to be thread safe. Also, implementations must assume that other JVMs
 * will be sharing the underlying database, so some kind of external concurrency control is required
 * when assigning IDs. It's not OK for the same input to be translated differently; if a
 * particular input translates into a particular unique ID once, it must translate in the same
 * way everywhere else forever. Also, a unqiue ID must never be reused for different inputs. This
 * means you must use locks, transactions, or compare-and-swap on your database when assigning
 * IDs.
 */

public interface IdService {
    public byte[] getId(int dimensionNum, byte[] input, int numIdBytes) throws IOException, InterruptedException;

    /**
     * Utilities to make implementation of IdService easier.
     */
    public static class Validate {
        /**
         * @throws IllegalArgumentException if dimensionNum is ridiculously large or <0.
         */
        public static void validateDimensionNum(int dimensionNum) {
            if(dimensionNum > Short.MAX_VALUE) {
                throw new IllegalArgumentException("More than " + Short.MAX_VALUE +
                        " dimensions are not supported, saw " + dimensionNum);
            } else if (dimensionNum < 0) {
                throw new IllegalArgumentException("dimensionNum should be non-negative, saw " +
                        dimensionNum);
            }
        }

        public static void validateNumIdBytes(int numIdBytes) {
            if(numIdBytes <= 0 || numIdBytes > 7) {
                throw new IllegalArgumentException("Strange numIdBytes key " + numIdBytes);
            }
        }
    }
}


text:
class LearningAlgorithm {
public:
  LearningAlgorithm(const DataSet &);

  virtual Model *run() = 0;

protected:
  const DataSet &data; ///< Reference to data is kept.
};

#endif // LEARNINGALGORITHM_HH


text:
<?xml version="1.0"?>
<doc>
    <assembly>
        <name>Unity.AspNet.WebApi</name>
    </assembly>
    <members>
        <member name="T:Unity.AspNet.WebApi.UnityDependencyResolver">
            <summary>
            An implementation of the <see cref="T:System.Web.Http.Dependencies.IDependencyResolver"/> interface that wraps a Unity container.
            </summary>
        </member>
        <member name="M:Unity.AspNet.WebApi.UnityDependencyResolver.#ctor(Unity.IUnityContainer)">
            <summary>
            Initializes a new instance of the <see cref="T:Unity.AspNet.WebApi.UnityDependencyResolver"/> class for a container.
            </summary>
            <param name="container">The <see cref="T:Unity.IUnityContainer"/> to wrap with the <see cref="T:System.Web.Http.Dependencies.IDependencyResolver"/>
            interface implementation.</param>
        </member>
        <member name="M:Unity.AspNet.WebApi.UnityDependencyResolver.BeginScope">
            <summary>
            Reuses the same scope to resolve all the instances.
            </summary>
            <returns>The shared dependency scope.</returns>
        </member>
        <member name="M:Unity.AspNet.WebApi.UnityDependencyResolver.Dispose">
            <summary>
            Disposes the wrapped <see cref="T:Unity.IUnityContainer"/>.
            </summary>
        </member>
        <member name="M:Unity.AspNet.WebApi.UnityDependencyResolver.GetService(System.Type)">
            <summary>
            Resolves an instance of the default requested type from the container.
            </summary>
            <param name="serviceType">The <see cref="T:System.Type"/> of the object to get from the container.</param>
            <returns>The requested object.</returns>
        </member>
        <member name="M:Unity.AspNet.WebApi.UnityDependencyResolver.GetServices(System.Type)">
            <summary>
            Resolves multiply registered services.
            </summary>
            <param name="serviceType">The type of the requested services.</param>
            <returns>The requested services.</returns>
        </member>
        <member name="T:Unity.AspNet.WebApi.UnityHierarchicalDependencyResolver">
            <summary>
            An implementation of <see cref="T:System.Web.Http.Dependencies.IDependencyResolver"/> that wraps a Unity container and creates a new child container
            when <see cref="M:Unity.AspNet.WebApi.UnityHierarchicalDependencyResolver.BeginScope"/> is invoked.
            </summary>
            <remarks>
            Because each scope creates a new child Unity container, you can benefit from using the <see cref="T:Unity.Lifetime.HierarchicalLifetimeManager"/>
            lifetime manager.
            </remarks>
        </member>
        <member name="M:Unity.AspNet.WebApi.UnityHierarchicalDependencyResolver.#ctor(Unity.IUnityContainer)">
            <summary>
            Initializes a new instance of the <see cref="T:Unity.AspNet.WebApi.UnityDependencyResolver"/> class for a container.
            </summary>
            <param name="container">The <see cref="T:Unity.IUnityContainer"/> to wrap with the <see cref="T:System.Web.Http.Dependencies.IDependencyResolver"/>
            interface implementation.</param>
        </member>
        <member name="M:Unity.AspNet.WebApi.UnityHierarchicalDependencyResolver.BeginScope">
            <summary>
            Starts a resolution scope by creating a new child Unity container.
            </summary>
            <returns>The dependency scope.</returns>
        </member>
        <member name="M:Unity.AspNet.WebApi.UnityHierarchicalDependencyResolver.Dispose">
            <summary>
            Disposes the wrapped <see cref="T:Unity.IUnityContainer"/>.
            </summary>
        </member>
        <member name="M:Unity.AspNet.WebApi.UnityHierarchicalDependencyResolver.GetService(System.Type)">
            <summary>
            Resolves an instance of the default requested type from the container.
            </summary>
            <param name="serviceType">The <see cref="T:System.Type"/> of the object to get from the container.</param>
            <returns>The retrieved object.</returns>
        </member>
        <member name="M:Unity.AspNet.WebApi.UnityHierarchicalDependencyResolver.GetServices(System.Type)">
            <summary>
            Resolves multiply registered services.
            </summary>
            <param name="serviceType">The type of the requested services.</param>
            <returns>The requested services.</returns>
        </member>
    </members>
</doc>


text:
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSMissingModuleManifestField', '')]
param()

# Hashtable to define the environmental data
@{
    # Node specific data
    AllNodes = @(

       # All the WebServer has following identical information
       @{
            NodeName           = '*'
            WebsiteName        = 'FourthCoffee'
            SourcePath         = 'C:\BakeryWebsite\'
            DestinationPath    = 'C:\inetpub\FourthCoffee'
            DefaultWebSitePath = 'C:\inetpub\wwwroot'
       },

       @{
            NodeName           = 'WebServer1.fourthcoffee.com'
            Role               = 'Web'
        },

       @{
            NodeName           = 'WebServer2.fourthcoffee.com'
            Role               = 'Web'
        }
    );
}


text:
class BilligPaymentError < ApplicationRecord
  # attr_accessible :error, :failed, :message, :owner_cardno, :owner_email
end

# == Schema Information
#
# Table name: billig_payment_errors
#
#  error        :string
#  failed       :datetime
#  message      :string
#  owner_cardno :integer
#  owner_email  :string
#  created_at   :datetime         not null
#  updated_at   :datetime         not null
#


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

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <link rel="stylesheet" href="docgen-resources/docgen.css" type="text/css">
  <meta name="generator" content="FreeMarker Docgen (DocBook 5)">
  <title>
    FreeMarker Manual - XML Processing Guide
  </title>

        You are here:
          FreeMarker Manual
            >
          XML Processing Guide

Bookmarks:
Alpha. index, Expressions, ?builtins, #directives, .spec_vars, FAQ, Glossary, API, Home

Next page: Preface

Previous page

Parent page

Contents

Part IV   XML Processing Guide

              Part Contents

        Preface

        1   Exposing XML documents

        The DOM tree

        Putting the XML into the data-model

        2   Imperative XML processing

        Basics

        Details

        3   Declarative XML processing

        Basics

        Details

Next page: Preface

Previous page

Parent page

Contents

        You are here:
          FreeMarker Manual
            >
          XML Processing Guide

            FreeMarker Manual -- For FreeMarker 2.3.21

          HTML generated: 2014-10-12 18:53:30 GMT


text:
package ru.job4j;

public class MathUtil {
    public static double add(int left, int second) {
        return left + second;
    }

    public static double div(int left, int second) throws Exception {
        return left + second;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Gear.Modeling
{
    public class VertexSelection
    {
    }
}


text:
package com.amazonaws.auth.policy.actions;

import javax.annotation.Generated;

import com.amazonaws.auth.policy.Action;

/**
 * The available AWS access control policy actions for Route 53.
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum Route53Actions implements Action {

    /** Represents any action executed on Route 53. */
    AllRoute53Actions("route53:*"),

    /** Action for the AssociateVPCWithHostedZone operation. */
    AssociateVPCWithHostedZone("route53:AssociateVPCWithHostedZone"),
    /** Action for the ChangeResourceRecordSets operation. */
    ChangeResourceRecordSets("route53:ChangeResourceRecordSets"),
    /** Action for the ChangeTagsForResource operation. */
    ChangeTagsForResource("route53:ChangeTagsForResource"),
    /** Action for the CreateHealthCheck operation. */
    CreateHealthCheck("route53:CreateHealthCheck"),
    /** Action for the CreateHostedZone operation. */
    CreateHostedZone("route53:CreateHostedZone"),
    /** Action for the CreateQueryLoggingConfig operation. */
    CreateQueryLoggingConfig("route53:CreateQueryLoggingConfig"),
    /** Action for the CreateReusableDelegationSet operation. */
    CreateReusableDelegationSet("route53:CreateReusableDelegationSet"),
    /** Action for the CreateTrafficPolicy operation. */
    CreateTrafficPolicy("route53:CreateTrafficPolicy"),
    /** Action for the CreateTrafficPolicyInstance operation. */
    CreateTrafficPolicyInstance("route53:CreateTrafficPolicyInstance"),
    /** Action for the CreateTrafficPolicyVersion operation. */
    CreateTrafficPolicyVersion("route53:CreateTrafficPolicyVersion"),
    /** Action for the CreateVPCAssociationAuthorization operation. */
    CreateVPCAssociationAuthorization("route53:CreateVPCAssociationAuthorization"),
    /** Action for the DeleteHealthCheck operation. */
    DeleteHealthCheck("route53:DeleteHealthCheck"),
    /** Action for the DeleteHostedZone operation. */
    DeleteHostedZone("route53:DeleteHostedZone"),
    /** Action for the DeleteQueryLoggingConfig operation. */
    DeleteQueryLoggingConfig("route53:DeleteQueryLoggingConfig"),
    /** Action for the DeleteReusableDelegationSet operation. */
    DeleteReusableDelegationSet("route53:DeleteReusableDelegationSet"),
    /** Action for the DeleteTrafficPolicy operation. */
    DeleteTrafficPolicy("route53:DeleteTrafficPolicy"),
    /** Action for the DeleteTrafficPolicyInstance operation. */
    DeleteTrafficPolicyInstance("route53:DeleteTrafficPolicyInstance"),
    /** Action for the DeleteVPCAssociationAuthorization operation. */
    DeleteVPCAssociationAuthorization("route53:DeleteVPCAssociationAuthorization"),
    /** Action for the DisassociateVPCFromHostedZone operation. */
    DisassociateVPCFromHostedZone("route53:DisassociateVPCFromHostedZone"),
    /** Action for the GetAccountLimit operation. */
    GetAccountLimit("route53:GetAccountLimit"),
    /** Action for the GetChange operation. */
    GetChange("route53:GetChange"),
    /** Action for the GetCheckerIpRanges operation. */
    GetCheckerIpRanges("route53:GetCheckerIpRanges"),
    /** Action for the GetGeoLocation operation. */
    GetGeoLocation("route53:GetGeoLocation"),
    /** Action for the GetHealthCheck operation. */
    GetHealthCheck("route53:GetHealthCheck"),
    /** Action for the GetHealthCheckCount operation. */
    GetHealthCheckCount("route53:GetHealthCheckCount"),
    /** Action for the GetHealthCheckLastFailureReason operation. */
    GetHealthCheckLastFailureReason("route53:GetHealthCheckLastFailureReason"),
    /** Action for the GetHealthCheckStatus operation. */
    GetHealthCheckStatus("route53:GetHealthCheckStatus"),
    /** Action for the GetHostedZone operation. */
    GetHostedZone("route53:GetHostedZone"),
    /** Action for the GetHostedZoneCount operation. */
    GetHostedZoneCount("route53:GetHostedZoneCount"),
    /** Action for the GetHostedZoneLimit operation. */
    GetHostedZoneLimit("route53:GetHostedZoneLimit"),
    /** Action for the GetQueryLoggingConfig operation. */
    GetQueryLoggingConfig("route53:GetQueryLoggingConfig"),
    /** Action for the GetReusableDelegationSet operation. */
    GetReusableDelegationSet("route53:GetReusableDelegationSet"),
    /** Action for the GetReusableDelegationSetLimit operation. */
    GetReusableDelegationSetLimit("route53:GetReusableDelegationSetLimit"),
    /** Action for the GetTrafficPolicy operation. */
    GetTrafficPolicy("route53:GetTrafficPolicy"),
    /** Action for the GetTrafficPolicyInstance operation. */
    GetTrafficPolicyInstance("route53:GetTrafficPolicyInstance"),
    /** Action for the GetTrafficPolicyInstanceCount operation. */
    GetTrafficPolicyInstanceCount("route53:GetTrafficPolicyInstanceCount"),
    /** Action for the ListGeoLocations operation. */
    ListGeoLocations("route53:ListGeoLocations"),
    /** Action for the ListHealthChecks operation. */
    ListHealthChecks("route53:ListHealthChecks"),
    /** Action for the ListHostedZones operation. */
    ListHostedZones("route53:ListHostedZones"),
    /** Action for the ListHostedZonesByName operation. */
    ListHostedZonesByName("route53:ListHostedZonesByName"),
    /** Action for the ListQueryLoggingConfigs operation. */
    ListQueryLoggingConfigs("route53:ListQueryLoggingConfigs"),
    /** Action for the ListResourceRecordSets operation. */
    ListResourceRecordSets("route53:ListResourceRecordSets"),
    /** Action for the ListReusableDelegationSets operation. */
    ListReusableDelegationSets("route53:ListReusableDelegationSets"),
    /** Action for the ListTagsForResource operation. */
    ListTagsForResource("route53:ListTagsForResource"),
    /** Action for the ListTagsForResources operation. */
    ListTagsForResources("route53:ListTagsForResources"),
    /** Action for the ListTrafficPolicies operation. */
    ListTrafficPolicies("route53:ListTrafficPolicies"),
    /** Action for the ListTrafficPolicyInstances operation. */
    ListTrafficPolicyInstances("route53:ListTrafficPolicyInstances"),
    /** Action for the ListTrafficPolicyInstancesByHostedZone operation. */
    ListTrafficPolicyInstancesByHostedZone("route53:ListTrafficPolicyInstancesByHostedZone"),
    /** Action for the ListTrafficPolicyInstancesByPolicy operation. */
    ListTrafficPolicyInstancesByPolicy("route53:ListTrafficPolicyInstancesByPolicy"),
    /** Action for the ListTrafficPolicyVersions operation. */
    ListTrafficPolicyVersions("route53:ListTrafficPolicyVersions"),
    /** Action for the ListVPCAssociationAuthorizations operation. */
    ListVPCAssociationAuthorizations("route53:ListVPCAssociationAuthorizations"),
    /** Action for the TestDNSAnswer operation. */
    TestDNSAnswer("route53:TestDNSAnswer"),
    /** Action for the UpdateHealthCheck operation. */
    UpdateHealthCheck("route53:UpdateHealthCheck"),
    /** Action for the UpdateHostedZoneComment operation. */
    UpdateHostedZoneComment("route53:UpdateHostedZoneComment"),
    /** Action for the UpdateTrafficPolicyComment operation. */
    UpdateTrafficPolicyComment("route53:UpdateTrafficPolicyComment"),
    /** Action for the UpdateTrafficPolicyInstance operation. */
    UpdateTrafficPolicyInstance("route53:UpdateTrafficPolicyInstance"),

    ;

    private final String action;

    private Route53Actions(String action) {
        this.action = action;
    }

    public String getActionName() {
        return this.action;
    }
}


text:
package dokan

import (
	"log"
)

func ExampleMount() {
	var myFileSystem FileSystem // Should be the real filesystem implementation
	mp, err := Mount(&Config{FileSystem: myFileSystem, Path: `Q:`})
	if err != nil {
		log.Fatal("Mount failed:", err)
	}
	err = mp.BlockTillDone()
	if err != nil {
		log.Println("Filesystem exit:", err)
	}
}


text:
using System;
using System.Linq.Expressions;

namespace Nest
{
	public abstract class FieldNameQueryDescriptorBase<TDescriptor, TInterface, T>
		: QueryDescriptorBase<TDescriptor, TInterface>, IFieldNameQuery
		where TDescriptor : FieldNameQueryDescriptorBase<TDescriptor, TInterface, T>, TInterface
		where TInterface : class, IFieldNameQuery
		where T : class
	{
		Field IFieldNameQuery.Field { get; set; }

		bool IQuery.IsVerbatim { get; set; }

		bool IQuery.IsStrict { get; set; }

		public TDescriptor Field(Field field) => Assign(a => a.Field = field);

		public TDescriptor Field(Expression<Func<T, object>> objectPath) =>
			Assign(a => a.Field = objectPath);
	}
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Jahreskat. Wiener Bot. Tauschvereins 6. 1894

#### Original name
null

### Remarks
null


text:
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateComponentsTable extends Migration
{
    /**
     * Run the migrations.
     */
    public function up()
    {
        Schema::create('components', function (Blueprint $table) {
            $table->engine = 'InnoDB';

            $table->increments('id');
            $table->string('name');
            $table->text('description');
            $table->text('link');
            $table->integer('status');
            $table->integer('order');
            $table->integer('group_id');
            $table->integer('user_id');
            $table->timestamps();
            $table->softDeletes();

            $table->index('group_id');
            $table->index('user_id');
            $table->index('status');
            $table->index('order');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down()
    {
        Schema::drop('components');
    }
}


text:
class Fixnum < Integer

  def self.induced_from(obj)
    case obj
    when Fixnum
      return obj
    when Float, Bignum
      value = obj.to_i
      if value.is_a? Bignum
        raise RangeError, "Object is out of range for a Fixnum"
      else
        return value
      end
    else
      value = Rubinius::Type.coerce_to(obj, Integer, :to_int)
      return self.induced_from(value)
    end
  end

  #--
  # see README-DEVELOPERS regarding safe math compiler plugin
  #++

  alias_method :/, :divide
  alias_method :modulo, :%

  def fdiv(n)
    if n.kind_of?(Fixnum)
      to_f / n
    else
      redo_coerced :fdiv, n
    end
  end

  # taint and untaint are noops on Fixnum
  def taint
    self
  end

  def untaint
    self
  end
end


text:
'use strict';

var $ = require('jquery');
var SearchView = require('../views/search');
var searchView = new SearchView();

module.exports = {
  events: function () {
    $('.search__input').on('input', searchView.search);
  }
}


text:
package org.usc.demo.httpclient.practice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.fluent.Executor;
import org.apache.http.client.fluent.Request;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.message.BasicNameValuePair;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 *
 * @author Shunli
 */
public class ZiMuZuTvSignIn {
    private static final String URL = "http://www.zimuzu.tv/";
    private static final String LOGIN_URL = "http://www.zimuzu.tv/User/Login/ajaxLogin";
    private static final String SIGN_IN_PAGE_URL = "http://www.zimuzu.tv/user/sign";
    private static final String SIGN_IN_URL = "http://www.zimuzu.tv/user/sign/dosign";

    public static void main(String[] args) {
        List<Account> accounts = ImmutableList.of(
                new Account("account", "password")
                );

        for (Account account : accounts) {
            try {
                Executor executor = Executor.newInstance().cookieStore(new BasicCookieStore());
                if (login(executor, account)) {
                    signIn(executor, account);
                }
            } catch (Exception e) {
                System.out.println("【" + account.getUsrename() + "】签到异常");
            }

        }
    }

    private static boolean login(Executor executor, Account account) throws ClientProtocolException, IOException {
        String usrename = account.getUsrename();

        List<NameValuePair> formParams = Lists.newArrayList();
        formParams.add(new BasicNameValuePair("account", usrename));
        formParams.add(new BasicNameValuePair("password", account.getPassword()));
        formParams.add(new BasicNameValuePair("remember", "1"));
        formParams.add(new BasicNameValuePair("url_back", URL));

        String loginJson = executor.execute(Request.Post(LOGIN_URL).bodyForm(formParams)).returnContent().asString();
        JSONObject loginJsonParseObject = JSON.parseObject(loginJson);
        if (1 != loginJsonParseObject.getInteger("status")) {
            System.out.println("【" + usrename + "】登录失败:" + loginJsonParseObject.getString("info"));
            return false;
        }

        System.out.println("【" + usrename + "】登录成功");
        return true;
    }

    private static boolean signIn(Executor executor, Account account) throws ClientProtocolException, IOException, InterruptedException {
        String usrename = account.getUsrename();

        // first load signin page
        executor.execute(Request.Get(SIGN_IN_PAGE_URL));

        // sleep 15s+
        TimeUnit.SECONDS.sleep(20);

        String signInJson = executor.execute(Request.Get(SIGN_IN_URL)).returnContent().asString();
        JSONObject signInParseObject = JSON.parseObject(signInJson);
        Integer stauts = signInParseObject.getInteger("status");
        if (stauts != null) {
            if (0 == stauts) {
                System.out.println("【" + usrename + "】已经签到");
                return true;
            }

            if (1 == stauts) {
                System.out.println("【" + usrename + "】签到成功");
                return true;
            }
        }

        System.out.println("【" + usrename + "】签到失败:" + signInParseObject.getString("info"));
        return false;
    }

    static class Account {
        private String usrename;
        private String password;

        public Account(String usrename, String password) {
            this.usrename = usrename;
            this.password = password;
        }

        public String getUsrename() {
            return usrename;
        }

        public String getPassword() {
            return password;
        }

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


text:
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using NServiceKit.Common;
using NServiceKit.Net30;
using NServiceKit.Text;

namespace NServiceKit.Redis.Tests
{
    [TestFixture, Category("Integration")]
    public class RedisClientEvalTests : RedisClientTestsBase
    {
        public override void OnBeforeEachTest()
        {
            //base.OnBeforeEachTest();

            //Run on local build server
            Redis = new RedisClient(TestConfig.SingleHost);
            Redis.FlushAll();
        }

        [Test]
        public void Can_Eval_int()
        {
            var intVal = Redis.ExecLuaAsInt("return 3141591");
            Assert.That(intVal, Is.EqualTo(3141591));
        }

        [Test]
        public void Can_EvalSha_int()
        {
            var luaBody = "return 3141591";
            Redis.ExecLuaAsInt(luaBody);
            var sha1 = Redis.CalculateSha1(luaBody);
            var intVal = Redis.ExecLuaShaAsInt(sha1);
            Assert.That(intVal, Is.EqualTo(3141591));
        }

        [Test]
        public void Can_Eval_int_with_args()
        {
            var intVal = Redis.ExecLuaAsInt("return 3141591", "20", "30", "40");
            Assert.That(intVal, Is.EqualTo(3141591));
        }

        [Test]
        public void Can_Eval_int_with_keys_and_args()
        {
            var intVal = Redis.ExecLuaAsInt("return KEYS[1] + ARGV[1]", new[] { "20" }, new[] { "30", "40" });
            Assert.That(intVal, Is.EqualTo(50));
        }

        [Test]
        public void Can_Eval_int2()
        {
            var intVal = Redis.ExecLuaAsInt("return ARGV[1] + ARGV[2]", "10", "20");
            Assert.That(intVal, Is.EqualTo(30));
        }

        [Test]
        public void Can_Eval_string()
        {
            var strVal = Redis.ExecLuaAsString(@"return 'abc'");
            Assert.That(strVal, Is.EqualTo("abc"));
        }

        [Test]
        public void Can_Eval_HelloWorld_string()
        {
            var strVal = Redis.ExecLuaAsString(@"return 'Hello, ' .. ARGV[1] .. '!'", "Redis Lua");
            Assert.That(strVal, Is.EqualTo("Hello, Redis Lua!"));
        }

        [Test]
        public void Can_Eval_string_with_args()
        {
            var strVal = Redis.ExecLuaAsString(@"return 'abc'", "at", "dot", "com");
            Assert.That(strVal, Is.EqualTo("abc"));
        }

        [Test]
        public void Can_Eval_string_with_keys_an_args()
        {
            var strVal = Redis.ExecLuaAsString(@"return KEYS[1] .. ARGV[1]", new[] { "at" }, new[] { "dot", "com" });
            Assert.That(strVal, Is.EqualTo("atdot"));
        }

        [Test]
        public void Can_Eval_multidata_with_args()
        {
            var strVals = Redis.ExecLuaAsList(@"return {ARGV[1],ARGV[2],ARGV[3]}", "at", "dot", "com");
            Assert.That(strVals, Is.EquivalentTo(new List<string> { "at", "dot", "com" }));
        }

        [Test]
        public void Can_Eval_multidata_with_keys_and_args()
        {
            var strVals = Redis.ExecLuaAsList(@"return {KEYS[1],ARGV[1],ARGV[2]}", new[] { "at" }, new[] { "dot", "com" });
            Assert.That(strVals, Is.EquivalentTo(new List<string> { "at", "dot", "com" }));
        }

        [Test]
        public void Can_Load_and_Exec_script()
        {
            var luaBody = "return 'load script and exec'";
            var sha1 = Redis.LoadLuaScript(luaBody);
            var result = Redis.ExecLuaShaAsString(sha1);
            Assert.That(result, Is.EqualTo("load script and exec"));
        }

        [Test]
        public void Does_flush_all_scripts()
        {
            var luaBody = "return 'load script and exec'";
            var sha1 = Redis.LoadLuaScript(luaBody);
            var result = Redis.ExecLuaShaAsString(sha1);
            Assert.That(result, Is.EqualTo("load script and exec"));

            Redis.RemoveAllLuaScripts();

            try
            {
                result = Redis.ExecLuaShaAsString(sha1);
                Assert.Fail("script shouldn't exist");
            }
            catch (RedisResponseException ex)
            {
                Assert.That(ex.Message, Is.StringContaining("NOSCRIPT"));
            }
        }

        [Test]
        public void Can_detect_which_scripts_exist()
        {
            var sha1 = Redis.LoadLuaScript("return 'script1'");
            var sha2 = Redis.CalculateSha1("return 'script2'");
            var sha3 = Redis.LoadLuaScript("return 'script3'");

            Assert.That(Redis.HasLuaScript(sha1));

            var existsMap = Redis.WhichLuaScriptsExists(sha1, sha2, sha3);
            Assert.That(existsMap[sha1]);
            Assert.That(!existsMap[sha2]);
            Assert.That(existsMap[sha3]);
        }

        [Test]
        public void Can_create_ZPop_with_lua()
        {
            var luaBody = @"
                local val = redis.call('zrange', KEYS[1], 0, ARGV[1]-1)
                if val then redis.call('zremrangebyrank', KEYS[1], 0, ARGV[1]-1) end
                return val";

            var i = 0;
            var alphabet = 26.Times(c => ((char)('A' + c)).ToString());
            alphabet.ForEach(x => Redis.AddItemToSortedSet("zalphabet", x, i++));

            var letters = Redis.ExecLuaAsList(luaBody, keys: new[] { "zalphabet" }, args: new[] { "3" });

            letters.PrintDump();
            Assert.That(letters, Is.EquivalentTo(new[] { "A", "B", "C" }));
        }

        [Test]
        public void Can_create_ZRevPop_with_lua()
        {
            var luaBody = @"
                local val = redis.call('zrange', KEYS[1], -ARGV[1], -1)
                if val then redis.call('zremrangebyrank', KEYS[1], -ARGV[1], -1) end
                return val";

            var i = 0;
            var alphabet = 26.Times(c => ((char)('A' + c)).ToString());
            alphabet.ForEach(x => Redis.AddItemToSortedSet("zalphabet", x, i++));

            var letters = Redis.ExecLuaAsList(luaBody, keys: new[] { "zalphabet" }, args: new[] { "3" });

            letters.PrintDump();
            Assert.That(letters, Is.EquivalentTo(new[] { "X", "Y", "Z" }));
        }

        [Test]
        public void Can_return_DaysOfWeek_as_list()
        {
            Enum.GetNames(typeof (DayOfWeek)).ToList()
                .ForEach(x => Redis.AddItemToList("DaysOfWeek", x));
            Redis.ExecLuaAsList("return redis.call('LRANGE', 'DaysOfWeek', 0, -1)").PrintDump();
        }
    }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('symposion_schedule', '0001_initial'),
    ]

    operations = [
        migrations.AddField(
            model_name='slot',
            name='name',
            field=models.CharField(default='', editable=False, max_length=100),
            preserve_default=False,
        ),
    ]


text:
layout: post
date: '2015-07-17'
title: "QUINCEANERA DRESSES Sherri Hill 21171 Ball Gown Rosette Prom Dress"
category: QUINCEANERA DRESSES
tags: [QUINCEANERA DRESSES]
---
### QUINCEANERA DRESSES Sherri Hill 21171 Ball Gown Rosette Prom Dress
Just **$542.99**
###

Sherri Hill 21171 Ball Gown Rosette Prom Dress.

Available in sizes 0-18.

Buy it: [https://www.eudances.com/en/quinceanera-dresses/1695-sherri-hill-21171-ball-gown-rosette-prom-dress.html](https://www.eudances.com/en/quinceanera-dresses/1695-sherri-hill-21171-ball-gown-rosette-prom-dress.html)


text:
module FFWD
  module Plugin
    module KairosDB
      VERSION = "0.4.6"
    end
  end
end


text:
/**
* Energy reading from a Watts Up? Power Meter.
* Written for communications protocol serial data format 1.8.
* See:
* https://www.wattsupmeters.com/secure/downloads/CommunicationsProtocol090824.pdf
*
* @author Connor Imes
* @date 2016-02-08
*/
#include <assert.h>
#include <errno.h>
#include <inttypes.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "energymon.h"
#include "energymon-time-util.h"
#include "energymon-wattsup.h"
#include "wattsup-driver.h"

#ifdef ENERGYMON_DEFAULT
#include "energymon-default.h"
int energymon_get_default(energymon* em) {
  return energymon_get_wattsup(em);
}
#endif

// Environment variable to enable updating energy estimates b/w device reads.
// This can provide faster energy data, but risks the total energy being more
// inaccurate in the long run.
// Keeping this as an undocumented feature for now.
#define ENERGYMON_WATTSUP_ENABLE_ESTIMATES "ENERGYMON_WATTSUP_ENABLE_ESTIMATES"

// must wait at least one second between WattsUp polls
#define WU_MIN_INTERVAL_US 1000000
#define WU_POWER_INDEX 3
#define WU_BUFSIZE 256
// chosen empirically as a ridiculous value - never needed more than ~4 reads
#define WU_MAX_INITIAL_READS 100

typedef struct energymon_wattsup {
  energymon_wattsup_ctx* ctx;

  int poll;
  pthread_t thread;
  int use_estimates;

  uint64_t exec_us;
  uint64_t last_us;
  unsigned int deciwatts;
  int lock;
  uint64_t total_uj;
} energymon_wattsup;

static void lock_acquire(int* lock) {
  assert(lock != NULL);
#if defined(_WIN32)
  while (InterlockedExchange((long*) lock, 1)) {
#else
  while (__sync_lock_test_and_set(lock, 1)) {
#endif
    while (*lock);
  }
}

static void lock_release(int* lock) {
#if defined(_WIN32)
  InterlockedExchange((long*) lock, 0);
#else
  __sync_lock_release(lock);
#endif
}

/**
 * pthread function to poll the device at regular intervals.
 */
static void* wattsup_poll_sensors(void* args) {
  energymon_wattsup* state = (energymon_wattsup*) args;
  unsigned int i;
  unsigned int tmp;
  char buf[WU_BUFSIZE] = { 0 };
  char* saveptr;
  char* tok;
  int ret;
  int dummy_old_state; // not used but kept for portability (see pthread docs)

  state->deciwatts = 0;
  if (!(state->last_us = energymon_gettime_us())) {
    // must be that CLOCK_MONOTONIC is not supported
    perror("wattsup_poll_sensors");
    return (void*) NULL;
  }
  energymon_sleep_us(WU_MIN_INTERVAL_US, &state->poll);
  while (state->poll) {
#ifndef __ANDROID__
    // deadlock can occur during disconnect in some wattsup_driver impls if thread is canceled during I/O
    // disable thread cancel while we do I/O and later while we hold the lock
    pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &dummy_old_state);
#endif
    ret = wattsup_read(state->ctx, buf, WU_BUFSIZE);
    if (ret < 0) {
      perror("wattsup_poll_sensors:wattsup_read");
    } else {
      if (ret < WU_BUFSIZE) {
        buf[ret] = '\0';
      } else {
        // TODO: There is probably more data that needs to be read
        buf[WU_BUFSIZE - 1] = '\0';
      }
#ifdef ENERGYMON_WATTSUP_DEBUG
      fprintf(stdout, "Read %d characters:\n%s\n", ret, buf);
#endif
      // sometimes we get multiple (or at least parts of old) packets
      // skip over old data to beginning of most recent packet
      tok = strrchr(buf, '#');
      if (tok) {
        // TODO: It's possible that this is not a complete packet
        tok = strtok_r(tok, ",", &saveptr);
        for (i = 0; tok; i++) {
          // 1st index = command, starting with a '#'
          // 2nd index = subcommand (should be a '-', but we don't care)
          if (i == WU_POWER_INDEX) {
            // treat this is as the average power since last successful read
            errno = 0;
            tmp = strtoul(tok, NULL, 0);
            if (errno) {
              // keep old value of deciwatts
              perror("wattsup_poll_sensors:strtoul");
            } else {
              state->deciwatts = tmp;
            }
            break;
          }
          tok = strtok_r(NULL, ",", &saveptr);
        }
        if (i != WU_POWER_INDEX) {
          fprintf(stderr, "Failed to get power from WattsUp data: %s\n", buf);
        }
      } else {
        fprintf(stderr, "Bad data from WattsUp: %s\n", buf);
      }
    }

    // WattsUps are cranky - don't read for a whole second
    if (state->use_estimates) {
      lock_acquire(&state->lock);
    }
    state->exec_us = energymon_gettime_elapsed_us(&state->last_us);
    state->total_uj += state->deciwatts * state->exec_us / 10;
    if (state->use_estimates) {
      lock_release(&state->lock);
    }
#ifndef __ANDROID__
    pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &dummy_old_state);
#endif
    energymon_sleep_us(WU_MIN_INTERVAL_US, &state->poll);
  }
  return (void*) NULL;
}

static int wattsup_flush_read(energymon_wattsup_ctx* ctx) {
  assert(ctx != NULL);
  char buf[WU_BUFSIZE];
  int i;
  // do at most WU_MAX_INITIAL_READS reads, just so we don't read indefinitely
  for (i = 0; i < WU_MAX_INITIAL_READS; i++) {
    if (wattsup_read(ctx, buf, sizeof(buf)) != sizeof(buf)) {
      break;
    }
  }
  if (i == WU_MAX_INITIAL_READS) {
    // the device is just giving us garbage
    return -1;
  }
  // read (hopefully) the last of the junk
  wattsup_read(ctx, buf, sizeof(buf));
  return 0;
}

int energymon_init_wattsup(energymon* em) {
  if (em == NULL || em->state != NULL) {
    errno = EINVAL;
    return -1;
  }

  static const int IGNORE_INTERRUPT = 0;
  int err_save;
  const char* dev_file = getenv(ENERGYMON_WATTSUP_DEV_FILE);
  if (dev_file == NULL) {
    dev_file = ENERGYMON_WATTSUP_DEV_FILE_DEFAULT;
  }

  // create the state struct
  energymon_wattsup* state = calloc(1, sizeof(energymon_wattsup));
  if (state == NULL) {
    return -1;
  }

  // connect to the device
  if ((state->ctx = wattsup_connect(dev_file, ENERGYMON_WATTSUP_TIMEOUT_MS)) == NULL) {
    free(state);
    return -1;
  }

  // clear device memory
  if (wattsup_write(state->ctx, WU_CLEAR, strlen(WU_CLEAR)) < 0) {
    wattsup_disconnect(state->ctx);
    free(state);
    return -1;
  }

  // start device logging
  if (wattsup_write(state->ctx, WU_LOG_START_EXTERNAL, strlen(WU_LOG_START_EXTERNAL)) < 0) {
    wattsup_disconnect(state->ctx);
    free(state);
    return -1;
  }

  // must let the device start working before we read anything, otherwise we get garbage
  energymon_sleep_us(WU_MIN_INTERVAL_US, &IGNORE_INTERRUPT);

  // dummy reads - sometimes we get a bunch of junk to start with
  if (wattsup_flush_read(state->ctx)) {
    fprintf(stderr, "energymon_init_wattsup: Too much data from WattsUp\n");
    wattsup_disconnect(state->ctx);
    free(state);
    errno = ENODATA;
    return -1;
  }

  // set state properties
  state->use_estimates = getenv(ENERGYMON_WATTSUP_ENABLE_ESTIMATES) != NULL;

  // start polling thread
  state->poll = 1;
  err_save = pthread_create(&state->thread, NULL, wattsup_poll_sensors, state);
  if (err_save) {
    wattsup_disconnect(state->ctx);
    free(state);
    errno = err_save;
    return -1;
  }

  // This is hacky, but seems to be the most reliable way to provide accurate data:
  // give time for the polling thread to get a reading
  energymon_sleep_us(WU_MIN_INTERVAL_US, &IGNORE_INTERRUPT);

  em->state = state;
  return 0;
}

int energymon_finish_wattsup(energymon* em) {
  if (em == NULL || em->state == NULL) {
    errno = EINVAL;
    return -1;
  }

  int err_save = 0;
  energymon_wattsup* state = (energymon_wattsup*) em->state;

  // stop sensors polling thread and cleanup
  if (state->poll) {
    state->poll = 0;
#ifndef __ANDROID__
    pthread_cancel(state->thread);
#endif
    err_save = pthread_join(state->thread, NULL);
  }

  if (state->ctx != NULL) {
    // stop logging
    wattsup_write(state->ctx, WU_LOG_STOP, strlen(WU_LOG_STOP));
    // disconnect from device
    if (wattsup_disconnect(state->ctx)) {
      err_save = err_save ? err_save : errno;
    }
  }

  em->state = NULL;
  free(state);
  errno = err_save;

  return errno ? -1 : 0;
}

uint64_t energymon_read_total_wattsup(const energymon* em) {
  if (em == NULL || em->state == NULL) {
    errno = EINVAL;
    return 0;
  }
  energymon_wattsup* state = (energymon_wattsup*) em->state;
  if (state->use_estimates) {
    lock_acquire(&state->lock);
    state->exec_us = energymon_gettime_elapsed_us(&state->last_us);
    state->total_uj += state->deciwatts * state->exec_us / 10;
    lock_release(&state->lock);
  }
  return state->total_uj;
}

char* energymon_get_source_wattsup(char* buffer, size_t n) {
  return wattsup_get_implementation(buffer, n);
}

uint64_t energymon_get_interval_wattsup(const energymon* em) {
  if (em == NULL) {
    // we don't need to access em, but it's still a programming error
    errno = EINVAL;
    return 0;
  }
  return WU_MIN_INTERVAL_US;
}

uint64_t energymon_get_precision_wattsup(const energymon* em) {
  if (em == NULL) {
    errno = EINVAL;
    return 0;
  }
  // deciwatts at 1 second interval
  return WU_MIN_INTERVAL_US / 10;
}

int energymon_is_exclusive_wattsup(void) {
  return 1;
}

int energymon_get_wattsup(energymon* em) {
  if (em == NULL) {
    errno = EINVAL;
    return -1;
  }
  em->finit = &energymon_init_wattsup;
  em->fread = &energymon_read_total_wattsup;
  em->ffinish = &energymon_finish_wattsup;
  em->fsource = &energymon_get_source_wattsup;
  em->finterval = &energymon_get_interval_wattsup;
  em->fprecision = &energymon_get_precision_wattsup;
  em->fexclusive = &energymon_is_exclusive_wattsup;
  em->state = NULL;
  return 0;
}