text:
var FontApiUrlBuilderTest = TestCase('FontApiUrlBuilderTest');

FontApiUrlBuilderTest.prototype.testThrowsExceptionIfNoFontFamilies =
    function() {
  var fontApiUrlBuilder = new webfont.FontApiUrlBuilder("http://moo");

  try {
    fontApiUrlBuilder.build();
    fail('build should have thrown an exception.');
  } catch (e) {
    // success
  }
};

FontApiUrlBuilderTest.prototype.testBuildProperUrl = function() {
  var fontApiUrlBuilder = new webfont.FontApiUrlBuilder("http://moo");

  fontApiUrlBuilder.setFontFamilies([ 'Font1', 'Font2' ]);
  assertEquals('http://moo?family=Font1%7CFont2', fontApiUrlBuilder.build());
};

FontApiUrlBuilderTest.prototype.testBuildProperDefaultUrl = function() {
  var fontApiUrlBuilder = new webfont.FontApiUrlBuilder();

  fontApiUrlBuilder.setFontFamilies([ 'Font1', 'Font2' ]);
  assertEquals("http:" + webfont.FontApiUrlBuilder.DEFAULT_API_URL +
      '?family=Font1%7CFont2', fontApiUrlBuilder.build());
};

FontApiUrlBuilderTest.prototype.testBuildProperUrlWithSubsets = function() {
  var fontApiUrlBuilder = new webfont.FontApiUrlBuilder();

  fontApiUrlBuilder.setFontFamilies([ 'Font1:bold:greek,cyrillic',
      'Font2:italic', 'Font3' ]);
  assertEquals("http:" + webfont.FontApiUrlBuilder.DEFAULT_API_URL +
	       '?family=Font1:bold%7CFont2:italic%7CFont3' +
      '&subset=greek,cyrillic', fontApiUrlBuilder.build());
};

FontApiUrlBuilderTest.prototype.testBuildProperUrlWithSubsetsNoVariations =
    function() {
  var fontApiUrlBuilder = new webfont.FontApiUrlBuilder();

  fontApiUrlBuilder.setFontFamilies([ 'Font1:bold,italic:greek,cyrillic',
      'Font2:italic', 'Font3::latin' ]);
  assertEquals("http:" + webfont.FontApiUrlBuilder.DEFAULT_API_URL +
	       '?family=Font1:bold,italic%7CFont2:italic%7CFont3' +
      '&subset=greek,cyrillic,latin', fontApiUrlBuilder.build());
};


text:
using namespace Glyph3;
//--------------------------------------------------------------------------------
App AppInstance; // Provides an instance of the application
//--------------------------------------------------------------------------------

//--------------------------------------------------------------------------------
App::App()
{
}
//--------------------------------------------------------------------------------
bool App::ConfigureEngineComponents()
{
	if ( !ConfigureRenderingEngineComponents( 1024, 800, D3D_FEATURE_LEVEL_11_0 ) ) {
		return( false );
	}

	if ( !ConfigureRenderingSetup() ) {
		return( false );
	}

	return( true );
}
//--------------------------------------------------------------------------------
void App::ShutdownEngineComponents()
{
	ShutdownRenderingSetup();
	ShutdownRenderingEngineComponents();
}
//--------------------------------------------------------------------------------
void App::Initialize()
{

	// Create the light parameters for use with this effect

	Vector4f LightParams = Vector4f( 0.2f, 0.2f, 0.2f, 0.7f );
	m_pLightColor = m_pRenderer11->m_pParamMgr->GetVectorParameterRef( std::wstring( L"LightColor" ) );
	m_pLightColor->InitializeParameterData( &LightParams );

	// Configure the camera, and the render view that will produce an image of the
	// from the camera's point of view of the scene.

	m_pCamera->Spatial().SetTranslation( Vector3f( 7.0f, 7.0f, -10.0f ) );
	m_pCamera->Spatial().SetRotation( Vector3f( 0.3f, -0.4f, 0.0f ) );
	m_pRenderView->SetColorClearValue( Vector4f( 0.1f, 0.1f, 0.3f, 0.0f ) );

	// Create a Kinect render view, and then attach it to the color and depth
	// visualization actors.  This will ensure that the render view is executed
	// prior to being used by either actor.

	m_pKinectView = new ViewKinect( *m_pRenderer11 );

	m_pColorActor = ActorGenerator::GenerateVisualizationTexture2D(
		*m_pRenderer11, m_pKinectView->GetColorResource(), 0 );
	m_pDepthActor = ActorGenerator::GenerateVisualizationTexture2D(
		*m_pRenderer11, m_pKinectView->GetDepthResource(),
		MaterialGeneratorDX11::GenerateKinectDepthBufferMaterial(*m_pRenderer11) );

	m_pColorActor->GetBody()->Visual.GetMaterial()->Params[VT_PERSPECTIVE].Tasks.push_back( m_pKinectView );
	m_pDepthActor->GetBody()->Visual.GetMaterial()->Params[VT_PERSPECTIVE].Tasks.push_back( m_pKinectView );

	m_pColorActor->GetNode()->Transform.Position() = Vector3f( -5.5f, 5.5f, 5.0f );
	m_pColorActor->GetNode()->Transform.Rotation().RotationY( -0.7f );
	m_pDepthActor->GetNode()->Transform.Position() = Vector3f( -5.5f, 0.0f, 5.0f );
	m_pDepthActor->GetNode()->Transform.Rotation().RotationY( -0.7f );

	// Create an actor to represent the 3D reconstruction of the scene.

	Actor* m_pDepthMapViewer = new Actor();

	GeometryPtr pGeometry = GeometryPtr( new GeometryDX11() );
	GeometryGeneratorDX11::GenerateTexturedPlane( pGeometry, 320, 240 );
	pGeometry->LoadToBuffers();
	pGeometry->SetPrimitiveType( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST );

	MaterialPtr pMaterial = MaterialGeneratorDX11::GenerateKinectReconstructionMaterial( *m_pRenderer11 );

	m_pDepthMapViewer->GetBody()->Visual.SetGeometry( pGeometry );
	m_pDepthMapViewer->GetBody()->Visual.SetMaterial( pMaterial );
	m_pDepthMapViewer->GetBody()->Visual.GetMaterial()->Params[VT_PERSPECTIVE].Tasks.push_back( m_pKinectView );

	m_pDepthMapViewer->GetNode()->Transform.Position() = Vector3f( 1.0f, 0.0f, 2.0f );
	m_pDepthMapViewer->GetNode()->Transform.Rotation().RotationX( 0.0f );
	m_pDepthMapViewer->GetNode()->Transform.Scale() = Vector3f( 7.0f, 7.0f, 7.0f );

	// Create a skeleton actor to show the joint tracking in the 3D representation.
	// It is then bound to the kinect render view for updating its values from the
	// SDK calculated joints.  It is then connected to the depth map viewer so that
	// any scaling applied matched between both of them.

	m_pSkeletonActor = new KinectSkeletonActor();
	m_pKinectView->SetSkeletonActor( m_pSkeletonActor );
	m_pDepthMapViewer->GetNode()->AttachChild( m_pSkeletonActor->GetNode() );

	// Add all our objects to the scene for rendering.

	m_pScene->AddActor( m_pColorActor );
	m_pScene->AddActor( m_pDepthActor );
	m_pScene->AddActor( m_pDepthMapViewer );

	SetMultiThreadedMode( false );

	// Do a one time initialization of the scene lighting parameters here
	Vector4f Ka( 0.2f, 0.2f, 0.2f, 0.2f );
	VectorParameterDX11* FactorKa = m_pRenderer11->m_pParamMgr->GetVectorParameterRef( std::wstring( L"Ka" ) );
	FactorKa->InitializeParameterData( &Ka );

	Vector4f Kd( 0.5f, 0.5f, 0.5f, 0.5f );
	VectorParameterDX11* FactorKd = m_pRenderer11->m_pParamMgr->GetVectorParameterRef( std::wstring( L"Kd" ) );
	FactorKd->InitializeParameterData( &Kd );

	Vector4f Ks( 1.0f, 1.0f, 1.0f, 1.0f );
	VectorParameterDX11* FactorKs = m_pRenderer11->m_pParamMgr->GetVectorParameterRef( std::wstring( L"Ks" ) );
	FactorKs->InitializeParameterData( &Ks );

	Vector4f LightPosition( 100.0f, 100.0f, -100.0f, 0.0f );
	VectorParameterDX11* FactorLightPosition = m_pRenderer11->m_pParamMgr->GetVectorParameterRef( std::wstring( L"LightPosition" ) );
	FactorLightPosition->InitializeParameterData( &LightPosition );

	Vector4f Ia( 0.25f, 0.25f, 0.25f, 0.25f );
	VectorParameterDX11* FactorIa = m_pRenderer11->m_pParamMgr->GetVectorParameterRef( std::wstring( L"Ia" ) );
	FactorIa->InitializeParameterData( &Ia );

	Vector4f Id( 0.5f, 0.5f, 0.5f, 1.0f );
	VectorParameterDX11* FactorId = m_pRenderer11->m_pParamMgr->GetVectorParameterRef( std::wstring( L"Id" ) );
	FactorId->InitializeParameterData( &Id );

	Vector4f Is( 1.0f, 1.0f, 1.0f, 1.0f );
	VectorParameterDX11* FactorIs = m_pRenderer11->m_pParamMgr->GetVectorParameterRef( std::wstring( L"Is" ) );
	FactorIs->InitializeParameterData( &Is );
}
//--------------------------------------------------------------------------------
void App::Update()
{
	// Update the timer to determine the elapsed time since last frame.  This can
	// then used for animation during the frame.

	m_pTimer->Update();

	// Send an event to everyone that a new frame has started.  This will be used
	// in later examples for using the material system with render views.

	EventManager::Get()->ProcessEvent( EvtFrameStartPtr( new EvtFrameStart( m_pTimer->Elapsed() ) ) );

	std::wstringstream out;
	out << L"Hieroglyph 3 : Kinect Playground" << std::endl;
	out << L"Color and depth are represented on the left, with a 3D reconstruction on the right." << std::endl;
	out << L"FPS: " << m_pTimer->Framerate();

	m_pTextOverlayView->WriteText( out.str(), Matrix4f::Identity(), Vector4f( 1.0f, 1.0f, 1.0f, 1.0f ) );

	// Update the scene, and then render all cameras within the scene.

	m_pScene->Update( m_pTimer->Elapsed() );
	m_pScene->Render( m_pRenderer11 );

	// Perform the rendering and presentation for the window.

	m_pRenderer11->Present( m_pWindow->GetHandle(), m_pWindow->GetSwapChain() );

}
//--------------------------------------------------------------------------------
void App::Shutdown()
{
	SAFE_DELETE( m_pKinectView );

	// Print the framerate out for the log before shutting down.

	std::wstringstream out;
	out << L"Max FPS: " << m_pTimer->MaxFramerate();
	Log::Get().Write( out.str() );
}
//--------------------------------------------------------------------------------
bool App::HandleEvent( EventPtr pEvent )
{
	eEVENT e = pEvent->GetEventType();

	if ( e == SYSTEM_KEYBOARD_KEYDOWN )
	{
		EvtKeyDownPtr pKeyDown = std::static_pointer_cast<EvtKeyDown>( pEvent );

		unsigned int key = pKeyDown->GetCharacterCode();
	}
	else if ( e == SYSTEM_KEYBOARD_KEYUP )
	{
		EvtKeyUpPtr pKeyUp = std::static_pointer_cast<EvtKeyUp>( pEvent );

		unsigned int key = pKeyUp->GetCharacterCode();
	}

	// Call the parent class's event handler if we haven't handled the event.

	return( RenderApplication::HandleEvent( pEvent ) );
}
//--------------------------------------------------------------------------------
std::wstring App::GetName( )
{
	return( std::wstring( L"KinectPlayground" ) );
}
//--------------------------------------------------------------------------------

redpajama_set_name: RedPajamaGithub


text:
class log:
    @staticmethod
    def info(*args):
        # pprint(data, indent=4)
        print(*args)


text:
from __future__ import print_function
import numpy as np
import tensorflow as tf

# Create input data
X = np.random.randn(5, 2, 4)

# The second example is of length 6
X[1, 3:] = 0
X_lengths = [5, 3]

x = tf.placeholder(tf.float32, shape=[5, None, 4], name='Input')
x_lengths = tf.placeholder(tf.float32, shape=[None], name='lengths')

cell = tf.nn.rnn_cell.GRUCell(num_units=6)

outputs, last_states = tf.nn.dynamic_rnn(
    cell=cell,
    dtype=tf.float32,
    sequence_length=x_lengths,
    inputs=x,
    time_major=True)

with tf.Session() as sess:
    sess.run( tf.global_variables_initializer())
    out, last = sess.run([outputs, last_states], feed_dict={x:X, x_lengths:X_lengths})

print(np.shape(out), out)
print(np.shape(last), last)


text:
package com.elliottsj.ftw.activities

import java.util

import android.content.res.Configuration
import android.os.Bundle
import android.support.v4.widget.DrawerLayout
import android.support.v7.app.ActionBarDrawerToggle
import android.view.{MenuItem, View, ViewGroup}
import android.widget._
import com.elliottsj.ftw.R
import com.elliottsj.ftw.agencies.AddAgencyActivity
import com.elliottsj.ftw.preferences.Preferences
import com.elliottsj.ftw.stops.StopTabsFragment
import com.elliottsj.protobus.Agency
import org.scaloid.common.{Preferences => _, _}

import scala.collection.JavaConverters._

class MainActivity extends SActivity with Logger {

  private var mDrawerLayout: DrawerLayout = _
  private var mDrawerPanel: RelativeLayout = _
  private var mDrawerList: ListView = _
  private var mDrawerAdapter: ArrayAdapter[Agency] = _
  private var mDrawerToggle: ActionBarDrawerToggle = _
  private var mAddAgencyButton: TextView = _

  protected override def onCreate(savedInstanceState: Bundle): Unit = {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    // Enable the menu button
    getActionBar.setDisplayHomeAsUpEnabled(true)

    mDrawerLayout = find[DrawerLayout](R.id.drawer_layout)
    mDrawerPanel = find[RelativeLayout](R.id.drawer_panel)
    mDrawerList = find[ListView](android.R.id.list)
    mAddAgencyButton = find[TextView](R.id.add_agency)

    // Create an array adapter for the drawer and initialize with an empty list
    mDrawerAdapter = new ArrayAdapter[Agency](this, R.layout.drawer_item, new util.ArrayList[Agency]()) {
      /**
       * Set the TextView to contain the agency short title if it exists,
       * otherwise the full title.
       */
      override def getView(position: Int, convertView: View, parent: ViewGroup): View = {
        val nb = getItem(position).getNextbusFields
        val view = super.getView(position, convertView, parent)
        view.asInstanceOf[TextView].setText(nb.agencyShortTitle getOrElse nb.agencyTitle)
        view
      }
    }
    mDrawerList.setAdapter(mDrawerAdapter)
    mDrawerList.onItemClick(onDrawerItemClick _)

    // ActionBarDrawerToggle ties together the the proper interactions
    // between the sliding drawer and the action bar app icon
    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close)
    mDrawerLayout.setDrawerListener(mDrawerToggle)

    // Upon clicking on 'Add transit agency', start the activity
    mAddAgencyButton.onClick(startActivity[AddAgencyActivity])
  }

  override def onPostCreate(savedInstanceState: Bundle): Unit = {
    super.onPostCreate(savedInstanceState)
    // Sync the toggle state after onRestoreInstanceState has occurred.
    mDrawerToggle.syncState()
  }

  override def onResume(): Unit = {
    super.onResume()
    mDrawerAdapter.clear()
    mDrawerAdapter.addAll(Preferences(this).getAgencies.asJavaCollection)
  }

  override def onConfigurationChanged(newConfig: Configuration): Unit = {
    super.onConfigurationChanged(newConfig)
    // Pass any configuration change to the drawer toggles
    mDrawerToggle.onConfigurationChanged(newConfig)
  }

  override def onOptionsItemSelected(item: MenuItem): Boolean = {
    if (mDrawerToggle.onOptionsItemSelected(item))
      return true
    super.onOptionsItemSelected(item)
  }

  def onDrawerItemClick(parent: AdapterView[_], view: View, position: Int, id: Long): Unit = {
    getFragmentManager.beginTransaction().replace(R.id.content_frame, {
      val f = new StopTabsFragment()
      val args = new Bundle()
      args.putSerializable(StopTabsFragment.ARG_AGENCY, mDrawerAdapter.getItem(position))
      f.setArguments(args)
      f
    }).commit()

    mDrawerList.setItemChecked(position, true)
    mDrawerLayout.closeDrawer(mDrawerPanel)
  }

}


text:
import types
from copy import deepcopy

from xdis.codetype.code20 import Code2, Code2FieldTypes
from xdis.version_info import PYTHON_VERSION

# Below, in the Python 2.4 branch "bytes" is "str" since there may not be a "bytes" type.
Code3FieldTypes = deepcopy(Code2FieldTypes)
Code3FieldTypes.update({
    "co_kwonlyargcount": int,
})

class Code3(Code2):
    """Class for a Python3 code object used when a Python interpreter less than 3 is
    working on Python3 bytecode. It also functions as an object that can be used
    to build or write a Python3 code object, since we allow mutable structures.
    When done mutating, call method freeze().

    For convenience in generating code objects, fields like
    `co_consts`, co_names which are (immutable) tuples in the end-result can be stored
    instead as (mutable) lists. Likewise the line number table `co_lnotab`
    can be stored as a simple list of offset, line_number tuples.
    """

    def __init__(
        self,
        co_argcount,
        co_kwonlyargcount,
        co_nlocals,
        co_stacksize,
        co_flags,
        co_code,
        co_consts,
        co_names,
        co_varnames,
        co_filename,
        co_name,
        co_firstlineno,
        co_lnotab,
        co_freevars,
        co_cellvars,
    ):
        super(Code3, self).__init__(
            co_argcount,
            co_nlocals,
            co_stacksize,
            co_flags,
            co_code,
            co_consts,
            co_names,
            co_varnames,
            co_filename,
            co_name,
            co_firstlineno,
            co_lnotab,
            co_freevars,
            co_cellvars,
        )
        self.co_kwonlyargcount = co_kwonlyargcount
        self.fieldtypes = Code3FieldTypes

        if type(self) == Code3:
            self.check()
        return

    def encode_lineno_tab(self):
        co_lnotab = b""

        prev_line_number = self.co_firstlineno
        prev_offset = 0
        for offset, line_number in self.co_lnotab:
            offset_diff = offset - prev_offset
            line_diff = line_number - prev_line_number
            prev_offset = offset
            prev_line_number = line_number
            while offset_diff >= 256:
                co_lnotab += bytearray([255, 0])
                offset_diff -= 255
            while line_diff >= 256:
                co_lnotab += bytearray([0, 255])
                line_diff -= 255
            co_lnotab += bytearray([offset_diff, line_diff])

        self.co_lnotab = co_lnotab

    def freeze(self):
        for field in "co_consts co_names co_varnames co_freevars co_cellvars".split():
            val = getattr(self, field)
            if isinstance(val, list):
                setattr(self, field, tuple(val))

        # for field, typename in self.fieldtypes:
        #     pass

        if isinstance(self.co_lnotab, dict):
            d = self.co_lnotab
            self.co_lnotab = sorted(zip(d.keys(), d.values()), key=lambda tup: tup[0])
        if isinstance(self.co_lnotab, list):
            # We assume we have a list of tuples:
            # (offset, linenumber) which we convert
            # into the encoded format
            self.encode_lineno_tab()

        if isinstance(self.co_code, str) and PYTHON_VERSION >= 3.0:
            self.co_code = self.co_code.encode()

        if isinstance(self.co_lnotab, str):
            self.co_lnotab = self.co_lnotab.encode()

        return self

    def to_native(self):
        if not (3.0 <= PYTHON_VERSION <= 3.7):
            raise TypeError(
                "Python Interpreter needs to be in range 3.0..3.7; is %s"
                % PYTHON_VERSION
            )

        code = deepcopy(self)
        code.freeze()
        try:
            code.check()
        except AssertionError as e:
            raise TypeError(e)

        return types.CodeType(
            code.co_argcount,
            code.co_kwonlyargcount,
            code.co_nlocals,
            code.co_stacksize,
            code.co_flags,
            code.co_code,
            code.co_consts,
            code.co_names,
            code.co_varnames,
            code.co_filename,
            code.co_name,
            code.co_firstlineno,
            code.co_lnotab,
            code.co_freevars,
            code.co_cellvars,
        )


text:
var scada = scada || {};

scada.searchPhrases = {};

scada.searchForm = {
    // The popup dialogs manipulation object.
    popup: scada.popupLocator.getPopup(),
    // The modal dialog options.
    modalOptions: new scada.ModalOptions([scada.ModalButtons.OK, scada.ModalButtons.CANCEL]),
    // The URL template of the web form to create an entity.
    createUrlTemplate: "",
    // The URL template of the web form to edit an entity.
    editUrlTemplate: "",

    // Converts GridView pagers to Bootstrap pagers.
    convertPagers: function () {
        $(".gv-pager table").each(function () {
            var gvPagerTable = $(this);
            var bsPager = $("

");

            gvPagerTable.find("td").each(function () {
                var pageElem = $(this).children().clone();
                var itemElem = $("
");

                if (pageElem.is("span")) {
                    itemElem.addClass("active");
                }

                itemElem.append(pageElem).appendTo(bsPager);
            });

            gvPagerTable.replaceWith(bsPager);
        });
    },

    // Builds a URL for creating or editing an entity according to the template.
    buildUrl: function (jqParamElem, templateUrl) {
        var hiddens = jqParamElem.siblings("input:hidden");
        var url = templateUrl;

        for (let i = 0; i < hiddens.length; i++) {
            url = url.replace("{" + i + "}", hiddens.eq(i).val());
        }

        return url;
    },

    // Binds the form events.
    bindEvents: function () {
        var thisObj = this;

        // open a modal dialog to create a new entity
        $(".search-new")
            .off("click")
            .on("click", function () {
                if (thisObj.popup && thisObj.createUrlTemplate) {
                    var createUrl = thisObj.buildUrl($(this), thisObj.createUrlTemplate);

                    thisObj.popup.showModal(createUrl, thisObj.modalOptions, function (dialogResult, extraParams) {
                        if (dialogResult) {
                            // refresh displayed data
                            $(".search-refresh").click();
                        }
                    });
                }

                return false;
            });

        // open a modal dialog to edit an entity
        $(".search-row-edit")
            .off("click")
            .on("click", function () {
                if (thisObj.popup && thisObj.editUrlTemplate) {
                    var editUrl = thisObj.buildUrl($(this), thisObj.editUrlTemplate);

                    popup.showModal(editUrl, thisObj.modalOptions, function (dialogResult, extraParams) {
                        if (dialogResult) {
                            // refresh displayed data
                            $(".search-refresh").click();
                        }
                    });
                }

                return false;
            });

        // confirm delete of a row
        $(".search-row-del")
            .off("click")
            .on("click", function () {
                if (!confirm(scada.searchPhrases.deleteRowConfirm)) {
                    return false;
                }
            });
    }
}

// Performs necessary actions after asynchronous request.
function asyncEndRequest() {
    scada.searchForm.convertPagers();
    scada.searchForm.bindEvents();
    scada.utils.scrollTo($(".main-content:first"), $(".alert"));
}

$(document).ready(function () {
    scada.searchForm.convertPagers();
    scada.searchForm.bindEvents();
});


text:
package com.haskforce.parsing.srcExtsDatatypes;

/**
 *  VarName l (Name l)
 */
public class VarName extends CNameTopType {
    public SrcInfoSpan srcInfoSpan;
    public NameTopType name;

    @Override
    public String toString() {
        return "VarName{" +
                "name=" + name +
                '}';
    }
}


text: My personal user page


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <artifactId>Itinerary</artifactId>
    <groupId>web_service</groupId>
    <version>1.0-SNAPSHOT</version>
<dependencies>
</dependencies>

</project>


text:
package javax.time.format;

import static org.testng.Assert.assertEquals;

import java.io.IOException;
import java.time.format.DateTimePrintException;

import org.testng.annotations.Test;

/**
 * Test DateTimePrintException.
 */
@Test
public class TCKDateTimePrintException {

  @Test(groups = { "tck" })
  public void test_constructor_String() throws Exception {

    DateTimePrintException ex = new DateTimePrintException("TEST");
    assertEquals(ex.getMessage(), "TEST");
  }

  @Test(groups = { "tck" })
  public void test_constructor_StringThrowable_notIOException_equal() throws Exception {

    IllegalArgumentException iaex = new IllegalArgumentException("INNER");
    DateTimePrintException ex = new DateTimePrintException("TEST", iaex);
    assertEquals(ex.getMessage(), "TEST");
    assertEquals(ex.getCause(), iaex);
    ex.rethrowIOException(); // no effect
  }

  @Test(expectedExceptions = IOException.class, groups = { "tck" })
  public void test_constructor_StringThrowable_IOException() throws Exception {

    IOException ioex = new IOException("INNER");
    DateTimePrintException ex = new DateTimePrintException("TEST", ioex);
    assertEquals(ex.getMessage(), "TEST");
    assertEquals(ex.getCause(), ioex);
    ex.rethrowIOException(); // rethrows
  }

}


text:
If you have a question, find a bug, or just want to say hi, please open an issue on GitHub.

## Preview
![screenshot of Halve](/images/halve-home-image.png)

See a [live version of my blog](http://mohammedchisti.com) hosted on GitHub.


text:
Write a function that takes a number as input
and returns the number of times '1' appears in the given number.

##Examples

countTheOnes(467) ==> 0

countTheOnes(81511) ==> 3

countTheOnes(123) ==> 1


text:
using Microsoft.SharePoint.Client;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OfficeDevPnP.Core.Enums;
using OfficeDevPnP.Core.Framework.Provisioning.Model;
using OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers;
using OfficeDevPnP.Core.Tests.Framework.Functional.Validators;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;

namespace OfficeDevPnP.Core.Tests.Framework.Functional
{
    /// <summary>
    /// Test cases for the provisioning engine search settings functionality
    /// </summary>
    [TestClass]
   public class RegionalSettingsTests : FunctionalTestBase
    {
        #region Construction
        public RegionalSettingsTests()
        {
            //debugMode = true;
            //centralSiteCollectionUrl = "https://bertonline.sharepoint.com/sites/TestPnPSC_12345_23939b71-a69c-4d57-a818-5448a1cdaf28";
            //centralSubSiteUrl = "https://bertonline.sharepoint.com/sites/TestPnPSC_12345_23939b71-a69c-4d57-a818-5448a1cdaf28/sub";
        }
        #endregion

        #region Test setup
        [ClassInitialize()]
        public static void ClassInit(TestContext context)
        {
            ClassInitBase(context);
        }

        [ClassCleanup()]
        public static void ClassCleanup()
        {
            ClassCleanupBase();
        }
        #endregion

        #region Site collection test cases
        /// <summary>
        /// Site RegionalSettings Test
        /// </summary>
        [TestMethod]
        [Timeout(15 * 60 * 1000)]
        public void SiteCollectionRegionalSettingsTest()
        {
            using (var cc = TestCommon.CreateClientContext(centralSiteCollectionUrl))
            {
                var result = TestProvisioningTemplate(cc, "regionalsettings_add.xml", Handlers.RegionalSettings);
                RegionalSettingsValidator rv = new RegionalSettingsValidator();
                Assert.IsTrue(rv.Validate(result.SourceTemplate.RegionalSettings, result.TargetTemplate.RegionalSettings, result.TargetTokenParser));

                var result2 = TestProvisioningTemplate(cc, "regionalsettings_delta_1.xml", Handlers.RegionalSettings);
                RegionalSettingsValidator rv2 = new RegionalSettingsValidator();
                Assert.IsTrue(rv2.Validate(result2.SourceTemplate.RegionalSettings, result2.TargetTemplate.RegionalSettings, result2.TargetTokenParser));
            }
        }
        #endregion

        #region Web test cases
        /// <summary>
        /// Web RegionalSettings test
        /// </summary>
        [TestMethod]
        [Timeout(15 * 60 * 1000)]
        public void WebRegionalSettingsTest()
        {
            using (var cc = TestCommon.CreateClientContext(centralSubSiteUrl))
            {
                var result = TestProvisioningTemplate(cc, "regionalsettings_add.xml", Handlers.RegionalSettings);
                RegionalSettingsValidator rv = new RegionalSettingsValidator();
                Assert.IsTrue(rv.Validate(result.SourceTemplate.RegionalSettings, result.TargetTemplate.RegionalSettings, result.TargetTokenParser));

                var result2 = TestProvisioningTemplate(cc, "regionalsettings_delta_1.xml", Handlers.RegionalSettings);
                RegionalSettingsValidator rv2 = new RegionalSettingsValidator();
                Assert.IsTrue(rv2.Validate(result2.SourceTemplate.RegionalSettings, result2.TargetTemplate.RegionalSettings, result2.TargetTokenParser));
            }
        }
        #endregion
    }
}


text:
using Genus.Migrator.Migrations.Operations;
using Genus.Migrator.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Genus.Migrator.DependecyInjection;
using Microsoft.Extensions.Options;
using Genus.Migrator.Model.Builder;

namespace Genus.Migrator.Migrations.Design
{
    public class MigrationCommands
    {

        public MigrationCommands(IOrmAdapter adapter)
        {
            if (adapter == null)
                throw new ArgumentNullException(nameof(adapter));
            if (string.IsNullOrWhiteSpace(adapter.Environment))
                adapter.Environment = "Development";
            OrmAdapter = adapter;
            ServiceProvider = adapter.ServiceProvider;
        }

        protected IOrmAdapter OrmAdapter { get; }

        public IServiceProvider ServiceProvider
        {
            get;
        }

        public void AddMigration(
            string targetAssemblyName,
            IModel currentModel,
            IModel targetModel,
            string outputDir,
            bool skipEmptyMigration
            )
        {
            if (string.IsNullOrEmpty(targetAssemblyName))
                throw new ArgumentException("Required not empty value", nameof(targetAssemblyName));
            if (targetModel == null)
                throw new ArgumentNullException(nameof(targetModel));
            if (string.IsNullOrWhiteSpace(outputDir))
                throw new ArgumentException("Need value", nameof(outputDir));

            var assembly = Assembly.Load(new AssemblyName(targetAssemblyName));

            var comparer = ServiceProvider.GetRequiredService<IModelComparer>();
            var upOperations = comparer.CompareModel(currentModel, targetModel);
            if (!upOperations.Any())
                return;
            var downOperations = upOperations.Any()
                ? comparer.CompareModel(targetModel, currentModel)
                : Enumerable.Empty<MigrationOperation>();

            var factory = ServiceProvider.GetRequiredService<ICodeGeneratorFactory>();
            var ns = GetNamespace(targetAssemblyName);
            var id = GetMigrationId(targetAssemblyName);
            var className = "_" + id;
            var codeGenerator = factory.MigrationCodeGenerator(ns, className);
            var migrationStringBuilder = new IndentedStringBuilder();
            codeGenerator.GenerateMigration(upOperations, downOperations, migrationStringBuilder);

            var targetModelStringBuilder = new IndentedStringBuilder();
            codeGenerator.GenerateTargetModel(targetModel, targetModelStringBuilder);

            var snapshotName = GetSnapshotName(targetAssemblyName);
            var snapshotGenerator = factory.SnapshotGenerator(ns, snapshotName);
            var snapshotBuilder = new IndentedStringBuilder();
            snapshotGenerator.Generate(targetModel, snapshotBuilder);

            if (!Directory.Exists(outputDir))
                Directory.CreateDirectory(outputDir);

            File.WriteAllText(Path.Combine(outputDir, id+codeGenerator.Extension), migrationStringBuilder.ToString());
            File.WriteAllText(Path.Combine(outputDir, $"{id}.Designer{codeGenerator.Extension}"), targetModelStringBuilder.ToString());
            File.WriteAllText(Path.Combine(outputDir, snapshotName+ snapshotGenerator.Extension), snapshotBuilder.ToString());

        }

        protected virtual string GetNamespace(string targetAssemblyName)
        {
            return targetAssemblyName + ".Migrations";
        }

        protected virtual string GetMigrationId(string targetAssemblyName)
        {
            return $"{DateTime.Now:yyMMddHHmmssff}";
        }

        protected virtual string GetSnapshotName(string targetAssemblyName)
        {
            var name = targetAssemblyName.Split('.').Last();
            return name+"Snapshot";
        }

        public void RemoveMigration()
        {
            var migrationsSource = ServiceProvider.GetRequiredService<IMigrationsSource>();
            var migrationLog = ServiceProvider.GetRequiredService<IMigrationLog>();

            var migrations = migrationsSource.GetMigrations(OrmAdapter.StartupAssembly);
            if (migrations.Any())
            {
                var migrationInfo = migrations.Last.Value;
                var targetMigrationInfo = migrations.Last.Previous.Value;
                var migration = migrationsSource.CreateMigration(migrationInfo.Value);

                if (migrationLog.AppliedMigrations.Contains(migrationInfo.Key))
                    throw new InvalidOperationException($"Unapply migration: {migrationInfo.Key}");

                Migration targetMigration = null;

                if (migrations.Last.Previous != null)
                    targetMigration = migrationsSource.CreateMigration(targetMigrationInfo.Value);

                var targetAssemblyName = migrationInfo.Value.Assembly.GetName().FullName;

                var migrationCodeGeneratorFactory = ServiceProvider.GetRequiredService<ICodeGeneratorFactory>();
                var migrationCodeGenerator = migrationCodeGeneratorFactory.MigrationCodeGenerator("a", "b");
                var migrationsDir = GetMigrationsDir( targetMigrationInfo.Value);
                var migrationFileWithOutExt = Path.Combine(migrationsDir, migrationInfo.Key);
                var migrationFile = migrationFileWithOutExt + migrationCodeGenerator.Extension;
                var metadataFile = migrationFileWithOutExt + ".Designer" + migrationCodeGenerator.Extension;
                var modelSnapshotName = GetSnapshotName(targetAssemblyName);
                var modelSnapshotFile = Path.Combine(migrationsDir, modelSnapshotName + migrationCodeGenerator.Extension);

                if (File.Exists(migrationFile))
                    File.Delete(migrationFile);
                if (File.Exists(metadataFile))
                    File.Delete(metadataFile);

                if (targetMigration == null && File.Exists(modelSnapshotFile))
                    File.Delete(modelSnapshotFile);
                else
                {
                    var snapshotGenerator = migrationCodeGeneratorFactory.SnapshotGenerator(GetNamespace(targetAssemblyName), modelSnapshotName);
                    var targetModelBuilder = new ModelBuilder();
                    targetMigration.BuildTargetModel(targetModelBuilder);
                    var snapshotBuilder = new IndentedStringBuilder();
                    snapshotGenerator.Generate(targetModelBuilder.Build(), snapshotBuilder);

                    File.WriteAllText(modelSnapshotFile, snapshotBuilder.ToString());
                }
            }
        }

        protected virtual string GetMigrationsDir(TypeInfo migrationTypeInfo)
            => "Migrations";

        public virtual string ApplyMigration(string migrationName, ProviderName providerName, bool onlyScript=false)
        {
            if (string.IsNullOrWhiteSpace(migrationName))
                throw new ArgumentException("Need migration name.");

            var currentMigrationName = ServiceProvider.GetRequiredService<IMigrationLog>().AppliedMigrations.LastOrDefault();
            bool isDownMigration;
            var migrations = GetMigartionsForApply(currentMigrationName, migrationName, out isDownMigration);
            var sqlGenerator = GetSqlGenerator(providerName);
            var sqlScripts = GetSqlScriptsByMigration(sqlGenerator, isDownMigration, migrations);
            var sb = new StringBuilder();
            foreach (var item in sqlScripts)
            {
                sb.Append("--")
                    .AppendLine(item.Key)
                    .AppendLine(sqlGenerator.BatchTerminator);
                foreach (var script in item.Value)
                {
                    sb.AppendLine(script);
                    sb.AppendLine(sqlGenerator.BatchTerminator);
                    sb.AppendLine();
                    if (onlyScript == false)
                        OrmAdapter.ExecuteSql(script);
                }
            }
            return sb.ToString();
        }

        protected virtual SqlGenerator GetSqlGenerator(ProviderName providerName)
        {
            var sqlGenerators = ServiceProvider.GetRequiredService<IOptions<MigratorOptions>>().Value.SqlGenerators;
            Lazy<SqlGenerator> geneartorFactory;
            if (sqlGenerators.TryGetValue(providerName, out geneartorFactory))
                return geneartorFactory.Value;
            return null;
        }

        protected virtual IEnumerable<KeyValuePair<string, TypeInfo>> GetMigartionsForApply(
            string currentMigrationName,
            string migrationName,
            out bool down)
        {
            Dictionary<string, TypeInfo> applied = new Dictionary<string, TypeInfo>();
            Dictionary<string, TypeInfo> notApplied = new Dictionary<string, TypeInfo>();

            var a = false;
            var source = ServiceProvider.GetRequiredService<IMigrationsSource>();
            foreach (var migrationInfo in source.GetMigrations(null).OrderByDescending(_=>_.Key))
            {
                if (migrationInfo.Key.Substring(1) == currentMigrationName)
                    a = true;
                if (a == true)
                {
                    applied.Add(migrationInfo.Key, migrationInfo.Value);
                }
                else {
                    notApplied.Add(migrationInfo.Key, migrationInfo.Value);
                }
            }
            if (applied.ContainsKey(migrationName)
                || migrationName.Equals("0", StringComparison.OrdinalIgnoreCase) == true)
            {
                down = true;
                return applied.TakeWhile(m => m.Key != migrationName);
            }
            if (notApplied.ContainsKey(migrationName)
                || migrationName.Equals("last", StringComparison.OrdinalIgnoreCase) == true)
            {
                down = false;
                return notApplied.TakeWhile(m => m.Key != migrationName);
            }
            throw new InvalidOperationException($"Migration {migrationName} not found");
        }

        protected virtual IEnumerable<KeyValuePair<string, IEnumerable<string>>> GetSqlScriptsByMigration(
            SqlGenerator sqlGenerator,
            bool isDownMigration,
            IEnumerable<KeyValuePair<string, TypeInfo>> migrations)
        {
            var migrationLog = ServiceProvider.GetRequiredService<IMigrationLog>();
            if (!migrationLog.IsExist())
                yield return new KeyValuePair<string, IEnumerable<string>>("Migrator log table", new[] { migrationLog.GetCreateSqlScript() });
            if (!isDownMigration)
                migrations = migrations.Reverse();
            foreach (var migration in migrations)
            {
                var migrationId = migration.Key.Substring(1);
                var migrationInst = ServiceProvider.GetRequiredService<IMigrationsSource>().CreateMigration(migration.Value);
                var operations = isDownMigration
                                    ? migrationInst.DownOperations
                                    : migrationInst.UpOperations;
                yield return new KeyValuePair<string, IEnumerable<string>>(migrationId, sqlGenerator.Generate(operations));
                if (isDownMigration)
                    yield return new KeyValuePair<string, IEnumerable<string>>(
                                            "Delete migation from log",
                                            new[] { migrationLog.GetDeleteScript(migrationId) });
                else
                    yield return new KeyValuePair<string, IEnumerable<string>>(
                                            "Insert migation to log",
                                            new[] { migrationLog.GetInsertScript(migrationId) });
            }
        }
    }
}


text:
#ifndef _MACHINE_H
#define _MACHINE_H

#include <stdio.h>
#include <sys/types.h>

typedef struct {
    /* virtual method table */
    void* (*ctor)(void);
    int   (*show)(FILE*, int, const char*, const void*);
    void  (*dtor)(void*);

    /* mutable object data */
    void*   data;
} MachineInfo;

extern void initMachineInfo(MachineInfo* machine);
extern int printYAMLMachineInfo(FILE *out, int indent, const char* tag,
                               const MachineInfo* machine);
extern void deleteMachineInfo(MachineInfo* machine);

#endif /* _MACHINE_H */


text:
package org.pepstock.charba.client.items;

import org.pepstock.charba.client.commons.Key;
import org.pepstock.charba.client.commons.NativeObject;

/**
 * Maps the out-of-the-box CHART.JS element used to represents bars on the charts.
 *
 * @author Andrea "Stock" Stocchero
 */
public class BarElement extends ChartElement {

	/**
	 * BAR element type.
	 */
	public static final String TYPE = "bar";
	/**
	 * Static instance for the BAR element factory
	 */
	public static final ChartElementFactory FACTORY = new BarElementFactory();

	/**
	 * Name of properties of native object.
	 */
	private enum Property implements Key
	{
		BASE("base"),
		HEIGHT("height"),
		HORIZONTAL("horizontal"),
		WIDTH("width");

		// name value of property
		private final String value;

		/**
		 * Creates with the property value to use in the native object.
		 *
		 * @param value value of property name
		 */
		private Property(String value) {
			this.value = value;
		}

		/*
		 * (non-Javadoc)
		 *
		 * @see org.pepstock.charba.client.commons.Key#value()
		 */
		@Override
		public String value() {
			return value;
		}

	}

	/**
	 * Creates the item using a native java script object which contains all properties.
	 *
	 * @param nativeObject native java script object which contains all properties.
	 */
	BarElement(NativeObject nativeObject) {
		super(TYPE, nativeObject);
	}

	/**
	 * Returns the element options.
	 *
	 * @return the element options.
	 */
	@Override
	public BarElementOptions getOptions() {
		return (BarElementOptions) super.getOptions();
	}

	/**
	 * Returns if is an horizontal view.
	 *
	 * @return true if is an horizontal view.
	 */
	public boolean isHorizontal() {
		return getValue(Property.HORIZONTAL, Undefined.BOOLEAN);
	}

	/**
	 * Returns the base value of data set.
	 *
	 * @return the base value of data set.
	 */
	public double getBase() {
		return getValue(Property.BASE, Undefined.DOUBLE);
	}

	/**
	 * Returns the width of data set item in pixel.
	 *
	 * @return the width of data set item in pixel.
	 */
	public double getWidth() {
		return getValue(Property.WIDTH, Undefined.DOUBLE);
	}

	/**
	 * Returns the height of data set item in pixel.
	 *
	 * @return the height of data set item in pixel.
	 */
	public double getHeight() {
		return getValue(Property.HEIGHT, Undefined.DOUBLE);
	}

	/**
	 * Inner class to create BAR data element by a native object.
	 *
	 * @author Andrea "Stock" Stocchero
	 */
	private static class BarElementFactory implements ChartElementFactory {

		/*
		 * (non-Javadoc)
		 *
		 * @see org.pepstock.charba.client.commons.NativeObjectContainerFactory#create(org.pepstock.charba.client.commons.NativeObject)
		 */
		@Override
		public BarElement create(NativeObject nativeObject) {
			return new BarElement(nativeObject);
		}

		/*
		 * (non-Javadoc)
		 *
		 * @see org.pepstock.charba.client.items.ElementFactory#getType()
		 */
		@Override
		public String getType() {
			return TYPE;
		}

		/*
		 * (non-Javadoc)
		 *
		 * @see org.pepstock.charba.client.items.ChartElementFactory#createOptions(org.pepstock.charba.client.items.ChartElement, org.pepstock.charba.client.commons.NativeObject)
		 */
		@Override
		public BarElementOptions createOptions(ChartElement parent, NativeObject nativeObject) {
			return new BarElementOptions(nativeObject);
		}
	}

}


text:
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.uix.behaviors import CompoundSelectionBehavior
from kivy.app import runTouchApp
from kivy.core.window import Window

class SelectableGrid(CompoundSelectionBehavior, GridLayout):

    def __init__(self, **kwargs):
        super(SelectableGrid, self).__init__(**kwargs)
        keyboard = Window.request_keyboard(None, self)
        keyboard.bind(on_key_down=self.select_with_key_down,
                      on_key_up=self.select_with_key_up)

        def print_selection(*l):
            print('selected: ', [x.text for x in self.selected_nodes])
        self.bind(selected_nodes=print_selection)

    def goto_node(self, key, last_node, last_node_idx):
        ''' This function is used to go to the node by typing the number
        of the text of the button.
        '''
        node, idx = super(SelectableGrid, self).goto_node(key, last_node,
                                                          last_node_idx)
        if node == last_node:
            children = self.children
            for i in range(len(children)):
                if children[i].text == key:
                    return children[i], i
        return node, idx

    def select_node(self, node):
        node.background_color = (1, 0, 0, 1)
        return super(SelectableGrid, self).select_node(node)

    def deselect_node(self, node):
        node.background_color = (1, 1, 1, 1)
        super(SelectableGrid, self).deselect_node(node)

    def do_touch(self, instance, touch):
        if ('button' in touch.profile and touch.button in
            ('scrollup', 'scrolldown', 'scrollleft', 'scrollright')) or\
            instance.collide_point(*touch.pos):
            self.select_with_touch(instance, touch)
        else:
            return False
        return True

root = SelectableGrid(cols=5, up_count=5, multiselect=True, scroll_count=1)
for i in range(40):
    c = Button(text=str(i))
    c.bind(on_touch_down=root.do_touch)
    root.add_widget(c)

runTouchApp(root)


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>Finding The Way Home</title>
    <meta name="description" content="blog - " />

    <meta name="HandheldFriendly" content="True" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="shortcut icon" href="/blog/assets/images/favicon.ico" >

    <link rel="stylesheet" type="text/css" href="/blog/assets/css/screen.css" />
    <link rel="stylesheet" type="text/css"
          href="//fonts.googleapis.com/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400" />
    <link rel="stylesheet" type="text/css" href="/blog/assets/css/syntax.css" />

    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.3.0/styles/default.min.css">

        <link rel="canonical" href="/blog/" />
    <meta name="referrer" content="origin" />
    <link rel="next" href="/blog/page2/" />

    <meta property="og:site_name" content="blog" />
    <meta property="og:type" content="website" />
    <meta property="og:title" content="blog" />
    <meta property="og:description" content="" />
    <meta property="og:url" content="/blog/" />
    <meta property="og:image" content="/blog/assets/images/cover1.jpg" />

    <meta name="twitter:card" content="summary_large_image" />
    <meta name="twitter:title" content="blog" />
    <meta name="twitter:description" content="" />
    <meta name="twitter:url" content="/blog/" />
    <meta name="twitter:image:src" content="/blog/assets/images/cover1.jpg" />

    <meta name="generator" content="Jekyll 3.0.0" />
    <link rel="alternate" type="application/rss+xml" title="blog" href="/blog/feed.xml" />

Menu

        Close

Home

About

Technical

Author

    Subscribe

            Menu

blog

    Scroll Down

     Page 1 of 1

Test

Test post.
 »

            Nikos Papasarantopoulos

                on

                       Technical

            <time class="post-date" datetime="2014-08-12">12 Aug 2014</time>

     Page 1 of 1

blog © 2016

Proudly published with Jekyll using Jasper


text:
package robot.commands.autonomous;

import robot.PolarCoordinate;
import robot.Robot;
import robot.subsystems.ChassisSubsystem.DriveMode;
import robot.subsystems.ChassisSubsystem.PIDEnable;
import edu.wpi.first.wpilibj.DriverStation;
import edu.wpi.first.wpilibj.command.Command;

public class AutonomousDelayCommand extends Command {

	long delay;
	long initTime;

	public AutonomousDelayCommand(long delay) {
		this.delay = delay;
	}

	@Override
	protected void initialize() {
		initTime = System.currentTimeMillis();
	}

	@Override
	protected void execute() {
	}

	@Override
	protected boolean isFinished() {
		return (System.currentTimeMillis() - initTime > delay) || !DriverStation.getInstance().isAutonomous();
	}

	@Override
	protected void end() {
	}

	@Override
	protected void interrupted() {
	}

}


text:
FROM dockerfile/ubuntu

# Install Supervisor.
RUN \
  apt-get update && \
  apt-get install -y supervisor && \
  rm -rf /var/lib/apt/lists/* && \
  sed -i 's/^\(\[supervisord\]\)$/\1\nnodaemon=true/' /etc/supervisor/supervisord.conf

# Define mountable directories.
VOLUME ["/etc/supervisor/conf.d"]

# Define working directory.
WORKDIR /etc/supervisor/conf.d

# Define default command.
CMD ["supervisord", "-c", "/etc/supervisor/supervisord.conf"]


text:
require 'spec_helper'

RSpec.describe Groups::BoardsController do
  let(:group) { create(:group) }
  let(:user)  { create(:user) }

  before do
    group.add_maintainer(user)
    sign_in(user)
  end

  describe 'GET index' do
    it 'creates a new board when group does not have one' do
      expect { list_boards }.to change(group.boards, :count).by(1)
    end

    context 'when format is HTML' do
      it 'renders template' do
        list_boards

        expect(response).to render_template :index
        expect(response.content_type).to eq 'text/html'
      end

      context 'with unauthorized user' do
        before do
          expect(Ability).to receive(:allowed?).with(user, :log_in, :global).and_call_original
          allow(Ability).to receive(:allowed?).with(user, :read_cross_project, :global).and_return(true)
          allow(Ability).to receive(:allowed?).with(user, :read_group, group).and_return(true)
          allow(Ability).to receive(:allowed?).with(user, :read_board, group).and_return(false)
        end

        it 'returns a not found 404 response' do
          list_boards

          expect(response).to have_gitlab_http_status(:not_found)
          expect(response.content_type).to eq 'text/html'
        end
      end

      context 'when user is signed out' do
        let(:group) { create(:group, :public) }

        it 'renders template' do
          sign_out(user)

          board = create(:board, group: group)
          create(:board_group_recent_visit, group: board.group, board: board, user: user)

          list_boards

          expect(response).to render_template :index
          expect(response.content_type).to eq 'text/html'
        end
      end
    end

    context 'when format is JSON' do
      it 'return an array with one group board' do
        create(:board, group: group)

        expect(Boards::VisitsFinder).not_to receive(:new)

        list_boards format: :json

        expect(response).to match_response_schema('boards')
        expect(json_response.length).to eq 1
      end

      context 'with unauthorized user' do
        before do
          expect(Ability).to receive(:allowed?).with(user, :log_in, :global).and_call_original
          allow(Ability).to receive(:allowed?).with(user, :read_cross_project, :global).and_return(true)
          allow(Ability).to receive(:allowed?).with(user, :read_group, group).and_return(true)
          allow(Ability).to receive(:allowed?).with(user, :read_board, group).and_return(false)
        end

        it 'returns a not found 404 response' do
          list_boards format: :json

          expect(response).to have_gitlab_http_status(:not_found)
          expect(response.content_type).to eq 'application/json'
        end
      end
    end

    it_behaves_like 'disabled when using an external authorization service' do
      subject { list_boards }
    end

    def list_boards(format: :html)
      get :index, params: { group_id: group }, format: format
    end
  end

  describe 'GET show' do
    let!(:board) { create(:board, group: group) }

    context 'when format is HTML' do
      it 'renders template' do
        expect { read_board board: board }.to change(BoardGroupRecentVisit, :count).by(1)

        expect(response).to render_template :show
        expect(response.content_type).to eq 'text/html'
      end

      context 'with unauthorized user' do
        before do
          expect(Ability).to receive(:allowed?).with(user, :log_in, :global).and_call_original
          allow(Ability).to receive(:allowed?).with(user, :read_cross_project, :global).and_return(true)
          allow(Ability).to receive(:allowed?).with(user, :read_group, group).and_return(true)
          allow(Ability).to receive(:allowed?).with(user, :read_board, group).and_return(false)
        end

        it 'returns a not found 404 response' do
          read_board board: board

          expect(response).to have_gitlab_http_status(:not_found)
          expect(response.content_type).to eq 'text/html'
        end
      end

      context 'when user is signed out' do
        let(:group) { create(:group, :public) }

        it 'does not save visit' do
          sign_out(user)

          expect { read_board board: board }.to change(BoardGroupRecentVisit, :count).by(0)

          expect(response).to render_template :show
          expect(response.content_type).to eq 'text/html'
        end
      end
    end

    context 'when format is JSON' do
      it 'returns project board' do
        expect(Boards::Visits::CreateService).not_to receive(:new)

        read_board board: board, format: :json

        expect(response).to match_response_schema('board')
      end

      context 'with unauthorized user' do
        before do
          expect(Ability).to receive(:allowed?).with(user, :log_in, :global).and_call_original
          allow(Ability).to receive(:allowed?).with(user, :read_cross_project, :global).and_return(true)
          allow(Ability).to receive(:allowed?).with(user, :read_group, group).and_return(true)
          allow(Ability).to receive(:allowed?).with(user, :read_group, group).and_return(false)
        end

        it 'returns a not found 404 response' do
          read_board board: board, format: :json

          expect(response).to have_gitlab_http_status(:not_found)
          expect(response.content_type).to eq 'application/json'
        end
      end
    end

    context 'when board does not belong to group' do
      it 'returns a not found 404 response' do
        another_board = create(:board)

        read_board board: another_board

        expect(response).to have_gitlab_http_status(:not_found)
      end
    end

    it_behaves_like 'disabled when using an external authorization service' do
      subject { read_board board: board }
    end

    def read_board(board:, format: :html)
      get :show, params: {
                   group_id: group,
                   id: board.to_param
                 },
                 format: format
    end
  end
end


text:
/* GENERATED SOURCE. DO NOT MODIFY. */
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html#License
/**
 *******************************************************************************
 * Copyright (C) 2000-2015, International Business Machines Corporation and
 * others. All Rights Reserved.
 *******************************************************************************
 */
package android.icu.dev.test.timezone;
import java.util.Date;

import org.junit.Test;

import android.icu.dev.test.TestFmwk;
import android.icu.dev.test.TestUtil;
import android.icu.dev.test.TestUtil.JavaVendor;
import android.icu.text.DateFormat;
import android.icu.util.Calendar;
import android.icu.util.SimpleTimeZone;
import android.icu.util.TimeZone;

/**
 * A test which discovers the boundaries of DST programmatically and verifies
 * that they are correct.
 */
public class TimeZoneBoundaryTest extends TestFmwk
{
    static final int ONE_SECOND = 1000;
    static final int ONE_MINUTE = 60*ONE_SECOND;
    static final int ONE_HOUR = 60*ONE_MINUTE;
    static final long ONE_DAY = 24*ONE_HOUR;
    static final long ONE_YEAR = (long)(365.25 * ONE_DAY);
    static final long SIX_MONTHS = ONE_YEAR / 2;

    static final int MONTH_LENGTH[] = {31,29,31,30,31,30,31,31,30,31,30,31};

    // These values are empirically determined to be correct
    static final long PST_1997_BEG  = 860320800000L;
    static final long PST_1997_END  = 877856400000L;

    // Minimum interval for binary searches in ms; should be no larger
    // than 1000.
    static final long INTERVAL = 10; // Milliseconds

    // [3Jan01 Liu] Updated for 2000f data
    static final String AUSTRALIA = "Australia/Adelaide";
    static final long AUSTRALIA_1997_BEG = 877797000000L;
    static final long AUSTRALIA_1997_END = 859653000000L;

    /**
     * Date.toString().substring() Boundary Test
     * Look for a DST changeover to occur within 6 months of the given Date.
     * The initial Date.toString() should yield a string containing the
     * startMode as a SUBSTRING.  The boundary will be tested to be
     * at the expectedBoundary value.
     */
    void findDaylightBoundaryUsingDate(Date d, String startMode, long expectedBoundary)
    {
        // Given a date with a year start, find the Daylight onset
        // and end.  The given date should be 1/1/xx in some year.

        if (d.toString().indexOf(startMode) == -1)
        {
            logln("Error: " + startMode + " not present in " + d);
        }

        // Use a binary search, assuming that we have a Standard
        // time at the midpoint.
        long min = d.getTime();
        long max = min + SIX_MONTHS;

        while ((max - min) >  INTERVAL)
        {
            long mid = (min + max) >> 1;
            String s = new Date(mid).toString();
            // logln(s);
            if (s.indexOf(startMode) != -1)
            {
                min = mid;
            }
            else
            {
                max = mid;
            }
        }

        logln("Date Before: " + showDate(min));
        logln("Date After:  " + showDate(max));
        long mindelta = expectedBoundary - min;
        // not used long maxdelta = max - expectedBoundary;
        if (mindelta >= 0 && mindelta <= INTERVAL &&
            mindelta >= 0 && mindelta <= INTERVAL)
            logln("PASS: Expected boundary at " + expectedBoundary);
        else
            errln("FAIL: Expected boundary at " + expectedBoundary);
    }

    // This test cannot be compiled until the inDaylightTime() method of GregorianCalendar
    // becomes public.
    //    static void findDaylightBoundaryUsingCalendar(Date d, boolean startsInDST)
    //    {
    //  // Given a date with a year start, find the Daylight onset
    //  // and end.  The given date should be 1/1/xx in some year.
    //
    //  GregorianCalendar cal = new GregorianCalendar();
    //  cal.setTime(d);
    //  if (cal.inDaylightTime() != startsInDST)
    //  {
    //      logln("Error: inDaylightTime(" + d + ") != " + startsInDST);
    //  }
    //
    //  // Use a binary search, assuming that we have a Standard
    //  // time at the midpoint.
    //  long min = d.getTime();
    //  long max = min + (long)(365.25 / 2 * 24*60*60*1000);
    //
    //  while ((max - min) >  INTERVAL)
    //  {
    //      long mid = (min + max) >> 1;
    //      cal.setTime(new Date(mid));
    //      if (cal.inDaylightTime() == startsInDST)
    //      {
    //      min = mid;
    //      }
    //      else
    //      {
    //      max = mid;
    //      }
    //  }
    //
    //  logln("Calendar Before: " + showDate(min));
    //  logln("Calendar After:  " + showDate(max));
    //    }

    void findDaylightBoundaryUsingTimeZone(Date d, boolean startsInDST, long expectedBoundary)
    {
        findDaylightBoundaryUsingTimeZone(d, startsInDST, expectedBoundary,
                                          TimeZone.getDefault());
    }

    void findDaylightBoundaryUsingTimeZone(Date d, boolean startsInDST,
                                           long expectedBoundary, TimeZone tz)
    {
        // Given a date with a year start, find the Daylight onset
        // and end.  The given date should be 1/1/xx in some year.

        // Use a binary search, assuming that we have a Standard
        // time at the midpoint.
        long min = d.getTime();
        long max = min + SIX_MONTHS;

        if (tz.inDaylightTime(d) != startsInDST)
        {
            errln("FAIL: " + tz.getID() + " inDaylightTime(" +
                  d + ") != " + startsInDST);
            startsInDST = !startsInDST; // Flip over; find the apparent value
        }

        if (tz.inDaylightTime(new Date(max)) == startsInDST)
        {
            errln("FAIL: " + tz.getID() + " inDaylightTime(" +
                  (new Date(max)) + ") != " + (!startsInDST));
            return;
        }

        while ((max - min) >  INTERVAL)
        {
            long mid = (min + max) >> 1;
            boolean isIn = tz.inDaylightTime(new Date(mid));
            if (isIn == startsInDST)
            {
                min = mid;
            }
            else
            {
                max = mid;
            }
        }

        logln(tz.getID() + " Before: " + showDate(min, tz));
        logln(tz.getID() + " After:  " + showDate(max, tz));

        long mindelta = expectedBoundary - min;
        // not used long maxdelta = max - expectedBoundary;
        DateFormat fmt = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);
        fmt.setTimeZone(tz);
        if (mindelta >= 0 && mindelta <= INTERVAL &&
            mindelta >= 0 && mindelta <= INTERVAL)
            logln("PASS: Expected boundary at " + expectedBoundary + " = " + fmt.format(new Date(expectedBoundary)));
        else
            errln("FAIL: Expected boundary at " + expectedBoundary + " = " + fmt.format(new Date(expectedBoundary)));
    }

    private static String showDate(long l)
    {
        return showDate(new Date(l));
    }

    private static String showDate(Date d)
    {
        java.util.Calendar cal = java.util.Calendar.getInstance();
        cal.setTime(d);
        return "" + (cal.get(Calendar.YEAR) - 1900) + "/" +
               showNN(cal.get(Calendar.MONTH) + 1) + "/" +
               showNN(cal.get(Calendar.DAY_OF_MONTH)) + " " +
               showNN(cal.get(Calendar.HOUR_OF_DAY)) + ":"
               + showNN(cal.get(Calendar.MINUTE)) + " \"" + d + "\" = " +
               d.getTime();
    }

    private static String showDate(long l, TimeZone z)
    {
        return showDate(new Date(l), z);
    }

    private static String showDate(Date d, TimeZone zone)
    {
        DateFormat fmt = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);
        fmt.setTimeZone(zone);
        java.util.Calendar cal = java.util.Calendar.getInstance();
        cal.setTime(d);
        return "" + (cal.get(Calendar.YEAR) - 1900) + "/" +
               showNN(cal.get(Calendar.MONTH) + 1) + "/" +
               showNN(cal.get(Calendar.DAY_OF_MONTH)) + " " +
               showNN(cal.get(Calendar.HOUR_OF_DAY)) + ":" +
               showNN(cal.get(Calendar.MINUTE)) + " \"" + d + "\" = " +
               fmt.format(d) + " = " + d.getTime();
    }

    private static String showNN(int n)
    {
        return ((n < 10) ? "0" : "") + n;
    }

    /**
     * Given a date, a TimeZone, and expected values for inDaylightTime,
     * useDaylightTime, zone and DST offset, verify that this is the case.
     */
    void verifyDST(String tag, Calendar cal, TimeZone time_zone,
                   boolean expUseDaylightTime, boolean expInDaylightTime,
                   int expRawOffset, int expOffset)
    {
        Date d = cal.getTime();

        logln("-- " + tag + ": " + d +
              " in zone " + time_zone.getID() + " (" +
              d.getTime()/3600000.0 + ")");

        if (time_zone.inDaylightTime(d) == expInDaylightTime)
            logln("PASS: inDaylightTime = " + time_zone.inDaylightTime(d));
        else
            errln("FAIL: inDaylightTime = " + time_zone.inDaylightTime(d));

        if (time_zone.useDaylightTime() == expUseDaylightTime)
            logln("PASS: useDaylightTime = " + time_zone.useDaylightTime());
        else
            errln("FAIL: useDaylightTime = " + time_zone.useDaylightTime());

        if (time_zone.getRawOffset() == expRawOffset)
            logln("PASS: getRawOffset() = " + expRawOffset/(double)ONE_HOUR);
        else
            errln("FAIL: getRawOffset() = " + time_zone.getRawOffset()/(double)ONE_HOUR +
                  "; expected " + expRawOffset/(double)ONE_HOUR);

        //GregorianCalendar gc = new GregorianCalendar(time_zone);
        //gc.setTime(d);
        int offset = time_zone.getOffset(cal.get(Calendar.ERA), cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
                                         cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.DAY_OF_WEEK),
                                         ((cal.get(Calendar.HOUR_OF_DAY) * 60 +
                                           cal.get(Calendar.MINUTE)) * 60 +
                                          cal.get(Calendar.SECOND)) * 1000 +
                                         cal.get(Calendar.MILLISECOND));
        if (offset == expOffset)
            logln("PASS: getOffset() = " + offset/(double)ONE_HOUR);
        else {
            logln("era=" + cal.get(Calendar.ERA) +
                  ", year=" + cal.get(Calendar.YEAR) +
                  ", month=" + cal.get(Calendar.MONTH) +
                  ", dom=" + cal.get(Calendar.DAY_OF_MONTH) +
                  ", dow=" + cal.get(Calendar.DAY_OF_WEEK) +
                  ", time-of-day=" + (((cal.get(Calendar.HOUR_OF_DAY) * 60 +
                               cal.get(Calendar.MINUTE)) * 60 +
                              cal.get(Calendar.SECOND)) * 1000 +
                             cal.get(Calendar.MILLISECOND)) / 3600000.0 +
                            " hours");
            errln("FAIL: getOffset() = " + offset/(double)ONE_HOUR +
                  "; expected " + expOffset/(double)ONE_HOUR);
        }
    }

    /**
     * Check that the given year/month/dom/hour maps to and from the
     * given epochHours.  This verifies the functioning of the
     * calendar and time zone in conjunction with one another,
     * including the calendar time->fields and fields->time and
     * the time zone getOffset method.
     *
     * @param epochHours hours after Jan 1 1970 0:00 GMT.
     */
    void verifyMapping(Calendar cal, int year, int month, int dom, int hour,
                       double epochHours) {
        double H = 3600000.0;
        cal.clear();
        cal.set(year, month, dom, hour, 0, 0);
        Date d = cal.getTime();
        double e = d.getTime() / H;
        Date ed = new Date((long)(epochHours * H));
        if (e == epochHours) {
            logln("Ok: " + year + "/" + (month+1) + "/" + dom + " " + hour + ":00 => " +
                  e + " (" + ed + ")");
        } else {
            errln("FAIL: " + year + "/" + (month+1) + "/" + dom + " " + hour + ":00 => " +
                  e + " (" + new Date((long)(e * H)) + ")" +
                  ", expected " + epochHours + " (" + ed + ")");
        }
        cal.setTime(ed);
        if (cal.get(Calendar.YEAR) == year &&
            cal.get(Calendar.MONTH) == month &&
            cal.get(Calendar.DATE) == dom &&
            cal.get(Calendar.MILLISECONDS_IN_DAY) == hour * 3600000) {
            logln("Ok: " + epochHours + " (" + ed + ") => " +
                  cal.get(Calendar.YEAR) + "/" +
                  (cal.get(Calendar.MONTH)+1) + "/" +
                  cal.get(Calendar.DATE) + " " +
                  cal.get(Calendar.MILLISECONDS_IN_DAY)/H);
        } else {
            errln("FAIL: " + epochHours + " (" + ed + ") => " +
                  cal.get(Calendar.YEAR) + "/" +
                  (cal.get(Calendar.MONTH)+1) + "/" +
                  cal.get(Calendar.DATE) + " " +
                  cal.get(Calendar.MILLISECONDS_IN_DAY)/H +
                  ", expected " + year + "/" + (month+1) + "/" + dom +
                  " " + hour);
        }
    }

// NOTE: Enable this code to check the behavior of the underlying JDK,
// using a JDK Calendar object.
//
//    int millisInDay(java.util.Calendar cal) {
//        return ((cal.get(Calendar.HOUR_OF_DAY) * 60 +
//                 cal.get(Calendar.MINUTE)) * 60 +
//                cal.get(Calendar.SECOND)) * 1000 +
//            cal.get(Calendar.MILLISECOND);
//    }
//
//    void verifyMapping(java.util.Calendar cal, int year, int month, int dom, int hour,
//                       double epochHours) {
//        cal.clear();
//        cal.set(year, month, dom, hour, 0, 0);
//        Date d = cal.getTime();
//        double e = d.getTime() / 3600000.0;
//        Date ed = new Date((long)(epochHours * 3600000));
//        if (e == epochHours) {
//            logln("Ok: " + year + "/" + (month+1) + "/" + dom + " " + hour + ":00 => " +
//                  e + " (" + ed + ")");
//        } else {
//            errln("FAIL: " + year + "/" + (month+1) + "/" + dom + " " + hour + ":00 => " +
//                  e + " (" + new Date((long)(e * 3600000)) + ")" +
//                  ", expected " + epochHours + " (" + ed + ")");
//        }
//        cal.setTime(ed);
//        if (cal.get(Calendar.YEAR) == year &&
//            cal.get(Calendar.MONTH) == month &&
//            cal.get(Calendar.DATE) == dom &&
//            millisInDay(cal) == hour * 3600000) {
//            logln("Ok: " + epochHours + " (" + ed + ") => " +
//                  cal.get(Calendar.YEAR) + "/" +
//                  (cal.get(Calendar.MONTH)+1) + "/" +
//                  cal.get(Calendar.DATE) + " " +
//                  millisInDay(cal)/3600000.0);
//        } else {
//            errln("FAIL: " + epochHours + " (" + ed + ") => " +
//                  cal.get(Calendar.YEAR) + "/" +
//                  (cal.get(Calendar.MONTH)+1) + "/" +
//                  cal.get(Calendar.DATE) + " " +
//                  millisInDay(cal)/3600000.0 +
//                  ", expected " + year + "/" + (month+1) + "/" + dom +
//                  " " + hour);
//        }
//    }

    @Test
    public void TestBoundaries()
    {
        TimeZone save = TimeZone.getDefault();

        // Check basic mappings.  We had a problem with this for ICU
        // 2.8 after migrating to using pass-through time zones.  The
        // problem appeared only on JDK 1.3.
        TimeZone pst = safeGetTimeZone("PST");
        Calendar tempcal = Calendar.getInstance(pst);
        verifyMapping(tempcal, 1997, Calendar.APRIL, 3,  0, 238904.0);
        verifyMapping(tempcal, 1997, Calendar.APRIL, 4,  0, 238928.0);
        verifyMapping(tempcal, 1997, Calendar.APRIL, 5,  0, 238952.0);
        verifyMapping(tempcal, 1997, Calendar.APRIL, 5, 23, 238975.0);
        verifyMapping(tempcal, 1997, Calendar.APRIL, 6,  0, 238976.0);
        verifyMapping(tempcal, 1997, Calendar.APRIL, 6,  1, 238977.0);
        verifyMapping(tempcal, 1997, Calendar.APRIL, 6,  3, 238978.0);

        TimeZone utc = safeGetTimeZone("UTC");
        Calendar utccal = Calendar.getInstance(utc);
        verifyMapping(utccal, 1997, Calendar.APRIL, 6, 0, 238968.0);

// NOTE: Enable this code to check the behavior of the underlying JDK,
// using a JDK Calendar object.
//
//        java.util.TimeZone jdkpst = java.util.TimeZone.getTimeZone("PST");
//        java.util.Calendar jdkcal = java.util.Calendar.getInstance(jdkpst);
//        verifyMapping(jdkcal, 1997, Calendar.APRIL, 5,  0, 238952.0);
//        verifyMapping(jdkcal, 1997, Calendar.APRIL, 5, 23, 238975.0);
//        verifyMapping(jdkcal, 1997, Calendar.APRIL, 6,  0, 238976.0);
//        verifyMapping(jdkcal, 1997, Calendar.APRIL, 6,  1, 238977.0);
//        verifyMapping(jdkcal, 1997, Calendar.APRIL, 6,  3, 238978.0);

        tempcal.clear();
        tempcal.set(1997, Calendar.APRIL, 6);
        Date d = tempcal.getTime();

        try {
            TimeZone.setDefault(pst);

            // DST changeover for PST is 4/6/1997 at 2 hours past midnight
            // at 238978.0 epoch hours.

            // i is minutes past midnight standard time
            for (int i=-120; i<=180; i+=60)
            {
                boolean inDST = (i >= 120);
                tempcal.setTimeInMillis(d.getTime() + i*60*1000);
                verifyDST("hour=" + i/60,
                          tempcal, pst, true, inDST, -8*ONE_HOUR,
                          inDST ? -7*ONE_HOUR : -8*ONE_HOUR);
            }
        } finally {
            TimeZone.setDefault(save);
        }

        // We no longer use ICU TimeZone implementation for Java
        // default TimeZone.  Java 1.3 or older version do not
        // support historic transitions, therefore, the test below
        // will fail on such environment (with the latest TimeZone
        // patch for US 2007+ rule).
        /* J2ObjC: always execute. */
        if (true) {
            // This only works in PST/PDT
            TimeZone.setDefault(safeGetTimeZone("PST"));
            logln("========================================");
            tempcal.set(1997, 0, 1);
            findDaylightBoundaryUsingDate(tempcal.getTime(), "PST", PST_1997_BEG);
            logln("========================================");
            tempcal.set(1997, 6, 1);
            findDaylightBoundaryUsingDate(tempcal.getTime(), "PDT", PST_1997_END);
        }

        //  if (true)
        //  {
        //      logln("========================================");
        //      findDaylightBoundaryUsingCalendar(new Date(97,0,1), false);
        //      logln("========================================");
        //      findDaylightBoundaryUsingCalendar(new Date(97,6,1), true);
        //  }

        if (true)
        {
            // Southern hemisphere test
            logln("========================================");
            TimeZone z = safeGetTimeZone(AUSTRALIA);
            tempcal.set(1997, 0, 1);
            findDaylightBoundaryUsingTimeZone(tempcal.getTime(), true, AUSTRALIA_1997_END, z);
            logln("========================================");
            tempcal.set(1997, 6, 1);
            findDaylightBoundaryUsingTimeZone(tempcal.getTime(), false, AUSTRALIA_1997_BEG, z);
        }

        if (true)
        {
            logln("========================================");
            tempcal.set(1997, 0, 1);
            findDaylightBoundaryUsingTimeZone(tempcal.getTime(), false, PST_1997_BEG);
            logln("========================================");
            tempcal.set(1997, 6, 1);
            findDaylightBoundaryUsingTimeZone(tempcal.getTime(), true, PST_1997_END);
        }

        // This just shows the offset for April 4-7 in 1997.  This is redundant
        // with a test above, so we disable it.
        if (false)
        {
            TimeZone z = TimeZone.getDefault();
            tempcal.set(1997, 3, 4);
            logln(z.getOffset(1, 97, 3, 4, 6, 0) + " " + tempcal.getTime());
            tempcal.set(1997, 3, 5);
            logln(z.getOffset(1, 97, 3, 5, 7, 0) + " " + tempcal.getTime());
            tempcal.set(1997, 3, 6);
            logln(z.getOffset(1, 97, 3, 6, 1, 0) + " " + tempcal.getTime());
            tempcal.set(1997, 3, 7);
            logln(z.getOffset(1, 97, 3, 7, 2, 0) + " " + tempcal.getTime());
        }
    }

    //----------------------------------------------------------------------
    // Can't do any of these without a public inDaylightTime in GC
    //----------------------------------------------------------------------

    //    static GregorianCalendar cal = new GregorianCalendar();
    //
    //    static void _testUsingBinarySearch(Date d, boolean startsInDST)
    //    {
    //  // Given a date with a year start, find the Daylight onset
    //  // and end.  The given date should be 1/1/xx in some year.
    //
    //  // Use a binary search, assuming that we have a Standard
    //  // time at the midpoint.
    //  long min = d.getTime();
    //  long max = min + (long)(365.25 / 2 * ONE_DAY);
    //
    //  // First check the max
    //  cal.setTime(new Date(max));
    //  if (cal.inDaylightTime() == startsInDST)
    //  {
    //      logln("Error: inDaylightTime(" + (new Date(max)) + ") != " + (!startsInDST));
    //  }
    //
    //  cal.setTime(d);
    //  if (cal.inDaylightTime() != startsInDST)
    //  {
    //      logln("Error: inDaylightTime(" + d + ") != " + startsInDST);
    //  }
    //
    //  while ((max - min) >  INTERVAL)
    //  {
    //      long mid = (min + max) >> 1;
    //      cal.setTime(new Date(mid));
    //      if (cal.inDaylightTime() == startsInDST)
    //      {
    //      min = mid;
    //      }
    //      else
    //      {
    //      max = mid;
    //      }
    //  }
    //
    //  logln("Binary Search Before: " + showDate(min));
    //  logln("Binary Search After:  " + showDate(max));
    //    }
    //
    //    static void _testUsingMillis(Date d, boolean startsInDST)
    //    {
    //  long millis = d.getTime();
    //  long max = millis + (long)(370 * ONE_DAY); // A year plus extra
    //
    //  boolean lastDST = startsInDST;
    //  while (millis < max)
    //  {
    //      cal.setTime(new Date(millis));
    //      boolean inDaylight = cal.inDaylightTime();
    //
    //      if (inDaylight != lastDST)
    //      {
    //      logln("Switch " + (inDaylight ? "into" : "out of")
    //                 + " DST at " + (new Date(millis)));
    //      lastDST = inDaylight;
    //      }
    //
    //      millis += 15*ONE_MINUTE;
    //  }
    //    }
    //
    //    static void _testUsingFields(int y, boolean startsInDST)
    //    {
    //  boolean lastDST = startsInDST;
    //  for (int m = 0; m < 12; ++m)
    //  {
    //      for (int d = 1; d <= MONTH_LENGTH[m]; ++d)
    //      {
    //      for (int h = 0; h < 24; ++h)
    //      {
    //          for (int min = 0; min < 60; min += 15)
    //          {
    //          cal.clear();
    //          cal.set(y, m, d, h, min);
    //          boolean inDaylight = cal.inDaylightTime();
    //          if (inDaylight != lastDST)
    //          {
    //              lastDST = inDaylight;
    //              log("Switch " + (lastDST ? "into" : "out of")
    //                       + " DST at " + y + "/" + (m+1) + "/" + d
    //                       + " " + showNN(h) + ":" + showNN(min));
    //              logln(" " + cal.getTime());
    //
    //              cal.set(y, m, d, h-1, 45);
    //              log("Before = "
    //+ y + "/" + (m+1) + "/" + d
    //+ " " + showNN(h-1) + ":" + showNN(45));
    //              logln(" " + cal.getTime());
    //          }
    //          }
    //      }
    //      }
    //  }
    //    }
    //
    //    public void Test1()
    //    {
    //  logln(Locale.getDefault().getDisplayName());
    //  logln(TimeZone.getDefault().getID());
    //  logln(new Date(0));
    //
    //  if (true)
    //  {
    //      logln("========================================");
    //      _testUsingBinarySearch(new Date(97,0,1), false);
    //      logln("========================================");
    //      _testUsingBinarySearch(new Date(97,6,1), true);
    //  }
    //
    //  if (true)
    //  {
    //      logln("========================================");
    //      logln("Stepping using millis");
    //      _testUsingMillis(new Date(97,0,1), false);
    //  }
    //
    //  if (true)
    //  {
    //      logln("========================================");
    //      logln("Stepping using fields");
    //      _testUsingFields(1997, false);
    //  }
    //
    //  if (false)
    //  {
    //      cal.clear();
    //      cal.set(1997, 3, 5, 10, 0);
    //      //  cal.inDaylightTime();
    //      logln("Date = " + cal.getTime());
    //      logln("Millis = " + cal.getTime().getTime()/3600000);
    //  }
    //    }

    //----------------------------------------------------------------------
    //----------------------------------------------------------------------
    //----------------------------------------------------------------------

    void _testUsingBinarySearch(SimpleTimeZone tz, Date d, long expectedBoundary)
    {
        // Given a date with a year start, find the Daylight onset
        // and end.  The given date should be 1/1/xx in some year.

        // Use a binary search, assuming that we have a Standard
        // time at the midpoint.
        long min = d.getTime();
        long max = min + (long)(365.25 / 2 * ONE_DAY);

        // First check the boundaries
        boolean startsInDST = tz.inDaylightTime(d);

        if (tz.inDaylightTime(new Date(max)) == startsInDST)
        {
            errln("Error: inDaylightTime(" + (new Date(max)) + ") != " + (!startsInDST));
        }

        while ((max - min) >  INTERVAL)
        {
            long mid = (min + max) >> 1;
            if (tz.inDaylightTime(new Date(mid)) == startsInDST)
            {
                min = mid;
            }
            else
            {
                max = mid;
            }
        }

        logln("Binary Search Before: " + showDate(min));
        logln("Binary Search After:  " + showDate(max));

        long mindelta = expectedBoundary - min;
        // not used long maxdelta = max - expectedBoundary;
        if (mindelta >= 0 && mindelta <= INTERVAL &&
            mindelta >= 0 && mindelta <= INTERVAL)
            logln("PASS: Expected boundary at " + expectedBoundary);
        else
            errln("FAIL: Expected boundary at " + expectedBoundary);
    }

    /*
      static void _testUsingMillis(Date d, boolean startsInDST)
      {
      long millis = d.getTime();
      long max = millis + (long)(370 * ONE_DAY); // A year plus extra

      boolean lastDST = startsInDST;
      while (millis < max)
      {
      cal.setTime(new Date(millis));
      boolean inDaylight = cal.inDaylightTime();

      if (inDaylight != lastDST)
      {
      logln("Switch " + (inDaylight ? "into" : "out of")
      + " DST at " + (new Date(millis)));
      lastDST = inDaylight;
      }

      millis += 15*ONE_MINUTE;
      }
      }
      */

    /**
     * Test new rule formats.
     */
    @Test
    public void TestNewRules()
    {
        //logln(Locale.getDefault().getDisplayName());
        //logln(TimeZone.getDefault().getID());
        //logln(new Date(0));

        if (true)
        {
            // Doesn't matter what the default TimeZone is here, since we
            // are creating our own TimeZone objects.

            SimpleTimeZone tz;
            java.util.Calendar tempcal = java.util.Calendar.getInstance();
            tempcal.clear();

            logln("-----------------------------------------------------------------");
            logln("Aug 2ndTues .. Mar 15");
            tz = new SimpleTimeZone(-8*ONE_HOUR, "Test_1",
                                    Calendar.AUGUST, 2, Calendar.TUESDAY, 2*ONE_HOUR,
                                    Calendar.MARCH, 15, 0, 2*ONE_HOUR);
            //logln(tz.toString());
            logln("========================================");
            tempcal.set(1997, 0, 1);
            _testUsingBinarySearch(tz, tempcal.getTime(), 858416400000L);
            logln("========================================");
            tempcal.set(1997, 6, 1);
            _testUsingBinarySearch(tz, tempcal.getTime(), 871380000000L);

            logln("-----------------------------------------------------------------");
            logln("Apr Wed>=14 .. Sep Sun<=20");
            tz = new SimpleTimeZone(-8*ONE_HOUR, "Test_2",
                                    Calendar.APRIL, 14, -Calendar.WEDNESDAY, 2*ONE_HOUR,
                                    Calendar.SEPTEMBER, -20, -Calendar.SUNDAY, 2*ONE_HOUR);
            //logln(tz.toString());
            logln("========================================");
            tempcal.set(1997, 0, 1);
            _testUsingBinarySearch(tz, tempcal.getTime(), 861184800000L);
            logln("========================================");
            tempcal.set(1997, 6, 1);
            _testUsingBinarySearch(tz, tempcal.getTime(), 874227600000L);
        }

        /*
          if (true)
          {
          logln("========================================");
          logln("Stepping using millis");
          _testUsingMillis(new Date(97,0,1), false);
          }

          if (true)
          {
          logln("========================================");
          logln("Stepping using fields");
          _testUsingFields(1997, false);
          }

          if (false)
          {
          cal.clear();
          cal.set(1997, 3, 5, 10, 0);
          //    cal.inDaylightTime();
          logln("Date = " + cal.getTime());
          logln("Millis = " + cal.getTime().getTime()/3600000);
          }
          */
    }

    //----------------------------------------------------------------------
    //----------------------------------------------------------------------
    //----------------------------------------------------------------------
    // Long Bug
    //----------------------------------------------------------------------
    //----------------------------------------------------------------------
    //----------------------------------------------------------------------

    //public void Test3()
    //{
    //    findDaylightBoundaryUsingTimeZone(new Date(97,6,1), true);
    //}

    /**
     * Find boundaries by stepping.
     */
    void findBoundariesStepwise(int year, long interval, TimeZone z, int expectedChanges)
    {
        java.util.Calendar tempcal = java.util.Calendar.getInstance();
        tempcal.clear();
        tempcal.set(year, Calendar.JANUARY, 1);
        Date d = tempcal.getTime();
        long time = d.getTime(); // ms
        long limit = time + ONE_YEAR + ONE_DAY;
        boolean lastState = z.inDaylightTime(d);
        int changes = 0;
        logln("-- Zone " + z.getID() + " starts in " + year + " with DST = " + lastState);
        logln("useDaylightTime = " + z.useDaylightTime());
        while (time < limit)
        {
            d.setTime(time);
            boolean state = z.inDaylightTime(d);
            if (state != lastState)
            {
                logln((state ? "Entry " : "Exit ") +
                      "at " + d);
                lastState = state;
                ++changes;
            }
            time += interval;
        }
        if (changes == 0)
        {
            if (!lastState && !z.useDaylightTime()) logln("No DST");
            else errln("FAIL: DST all year, or no DST with true useDaylightTime");
        }
        else if (changes != 2)
        {
            errln("FAIL: " + changes + " changes seen; should see 0 or 2");
        }
        else if (!z.useDaylightTime())
        {
            errln("FAIL: useDaylightTime false but 2 changes seen");
        }
        if (changes != expectedChanges)
        {
            errln("FAIL: " + changes + " changes seen; expected " + expectedChanges);
        }
    }

    @Test
    public void TestStepwise()
    {
        findBoundariesStepwise(1997, ONE_DAY, safeGetTimeZone("America/New_York"), 2);
        // disabled Oct 2003 aliu; ACT could mean anything, depending on the underlying JDK, as of 2.8
        // findBoundariesStepwise(1997, ONE_DAY, safeGetTimeZone("ACT"), 2);
        findBoundariesStepwise(1997, ONE_DAY, safeGetTimeZone("America/Phoenix"), 0); // Added 3Jan01
        findBoundariesStepwise(1997, ONE_DAY, safeGetTimeZone(AUSTRALIA), 2);
    }
}


text:
// Copyright (c) 2012 Nezametdinov E. Ildus
// Licensed under the MIT License (see LICENSE.txt for details)

#ifndef GLES_TEXTURE_H
#define GLES_TEXTURE_H

#include "../../../../../Engine/Core/Resources/Texture/Texture.h"
#include <GLES2/gl2.h>

namespace selene
{

        /**
         * \addtogroup Android
         * @{
         */

        /**
         * Represents OpenGL ES texture.
         */
        class GlesTexture: public Texture
        {
        public:
                /**
                 * \brief Constructs OpenGL ES texture with given name.
                 * \param[in] name name of the texture
                 */
                GlesTexture(const char* name = nullptr);
                GlesTexture(const GlesTexture&) = delete;
                ~GlesTexture();
                GlesTexture& operator =(const GlesTexture&) = delete;

                // Texture interface implementation
                bool retain();
                void discard();

        private:
                friend class GlesTextureHandler;

                GLuint texture_;

                /**
                 * \brief Destroys OpenGL ES texture data.
                 */
                void destroy();

        };

        /**
         * @}
         */

}

#endif


text:
<?php

namespace Temp\MediaConverter\Converter;

use Temp\MediaConverter\Format\Specification;

/**
 * Video converter
 */
class ConverterResolver
{
    /**
     * @var ConverterInterface[]
     */
    private $converters;

    /**
     * @param ConverterInterface[] $converters
     */
    public function __construct(array $converters)
    {
        foreach ($converters as $converter) {
            $this->addConverter($converter);
        }
    }

    /**
     * @param ConverterInterface $converter
     *
     * @return $this
     */
    private function addConverter(ConverterInterface $converter)
    {
        $this->converters[] = $converter;

        return $this;
    }

    /**
     * @param Specification $spec
     *
     * @return ConverterInterface
     */
    public function resolve(Specification $spec)
    {
        foreach ($this->converters as $converter) {
            if ($converter->accept($spec)) {
                return $converter;
            }
        }

        return null;
    }
}


text:
<?php

namespace backend\models;

use Yii;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
use yii\behaviors\BlameableBehavior;
use common\behaviors\TimestampBehavior;

class Admin extends \common\models\AdminBase implements IdentityInterface
{

    public $thumb_upload;

    /**
     * @return array
     */
    public function rules()
    {
        $rules =  parent::rules();
        $new_rules = [
            [['thumb_upload'], 'file', 'extensions' => 'jpg, png, jpeg, gif'],
        ];
        return array_merge($rules, $new_rules);
    }

    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    self::EVENT_BEFORE_INSERT => ['created_time', 'updated_time'],
                    self::EVENT_BEFORE_UPDATE => ['updated_time'],
                ]
            ],
            [
                'class' => BlameableBehavior::className(),
                'attributes' => [
                    'createdByAttribute' => 'created_by',
                    'updatedByAttribute' => 'updated_by',
                ]
            ]
        ];
    }

    /**
     * Finds an identity by the given ID.
     * @param string|integer $id the ID to be looked for
     * @return ActiveRecord
     * Null should be returned if such an identity cannot be found
     * or the identity is not in an active state (disabled, deleted, etc.)
     */
    public static function findIdentity($id)
    {
        // TODO: Implement findIdentity() method.
        $admin = static::find()->where(['id' => $id, 'status' => ADMIN_ACTIVE])->one();
        return (!empty($admin) ? $admin : null);
    }

    /**
     * Finds an identity by the given username.
     * @param string $username
     * @return IdentityInterface the identity object that matches the given ID.
     * Null should be returned if such an identity cannot be found
     * or the identity is not in an active state (disabled, deleted, etc.)
     */
    public static function findByUsername($username)
    {
        // TODO: Implement findIdentity() method.
        $admin = static::find()->where(['username' => $username, 'status' => ADMIN_ACTIVE])->one();
        return (!empty($admin) ? $admin : null);
    }

    /**
     * Finds an identity by the given token.
     * @param mixed $token the token to be looked for
     * @param mixed $type the type of the token. The value of this parameter depends on the implementation.
     * For example, [[\yii\filters\auth\HttpBearerAuth]] will set this parameter to be `yii\filters\auth\HttpBearerAuth`.
     * @return IdentityInterface the identity object that matches the given token.
     * Null should be returned if such an identity cannot be found
     * or the identity is not in an active state (disabled, deleted, etc.)
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        // TODO: Implement findIdentityByAccessToken() method.
    }

    /**
     * Returns an ID that can uniquely identify a user identity.
     * @return string|integer an ID that uniquely identifies a user identity.
     */
    public function getId()
    {
        // TODO: Implement getId() method.
        return $this->id;
    }

    /**
     * Returns a key that can be used to check the validity of a given identity ID.
     *
     * The key should be unique for each individual user, and should be persistent
     * so that it can be used to check the validity of the user identity.
     *
     * The space of such keys should be big enough to defeat potential identity attacks.
     *
     * This is required if [[User::enableAutoLogin]] is enabled.
     * @return string a key that is used to check the validity of a given identity ID.
     * @see validateAuthKey()
     */
    public function getAuthKey()
    {
        // TODO: Implement getAuthKey() method.
    }

    /**
     * Validates the given auth key.
     *
     * This is required if [[User::enableAutoLogin]] is enabled.
     * @param string $authKey the given auth key
     * @return boolean whether the given auth key is valid.
     * @see getAuthKey()
     */
    public function validateAuthKey($authKey)
    {
        // TODO: Implement validateAuthKey() method.
    }

    /**
     * Encrypt password
     * @param $password
     * @throws \yii\base\Exception
     */
    public function setPassword($password)
    {
        $this->password = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * Validate password
     * @param $password
     * @return bool
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password);
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Fusarium mauroi Av.-Saccá

### Remarks
null


text:
/*
 * DO NOT EDIT.  THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-2.0-xr-w32-bld/build/dom/interfaces/events/nsIDOMPaintRequestList.idl
 */

#ifndef __gen_nsIDOMPaintRequestList_h__
#define __gen_nsIDOMPaintRequestList_h__

#ifndef __gen_domstubs_h__
#include "domstubs.h"
#endif

/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
class nsIDOMPaintRequest; /* forward declaration */

/* starting interface:    nsIDOMPaintRequestList */
#define NS_IDOMPAINTREQUESTLIST_IID_STR "01627136-fdd8-44b4-aac0-7d613608a3d4"

#define NS_IDOMPAINTREQUESTLIST_IID \
  {0x01627136, 0xfdd8, 0x44b4, \
    { 0xaa, 0xc0, 0x7d, 0x61, 0x36, 0x08, 0xa3, 0xd4 }}

class NS_NO_VTABLE NS_SCRIPTABLE nsIDOMPaintRequestList : public nsISupports {
 public:

  NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOMPAINTREQUESTLIST_IID)

  /* readonly attribute unsigned long length; */
  NS_SCRIPTABLE NS_IMETHOD GetLength(PRUint32 *aLength) = 0;

  /* nsIDOMPaintRequest item (in unsigned long index); */
  NS_SCRIPTABLE NS_IMETHOD Item(PRUint32 index, nsIDOMPaintRequest **_retval NS_OUTPARAM) = 0;

};

  NS_DEFINE_STATIC_IID_ACCESSOR(nsIDOMPaintRequestList, NS_IDOMPAINTREQUESTLIST_IID)

/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIDOMPAINTREQUESTLIST \
  NS_SCRIPTABLE NS_IMETHOD GetLength(PRUint32 *aLength); \
  NS_SCRIPTABLE NS_IMETHOD Item(PRUint32 index, nsIDOMPaintRequest **_retval NS_OUTPARAM);

/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIDOMPAINTREQUESTLIST(_to) \
  NS_SCRIPTABLE NS_IMETHOD GetLength(PRUint32 *aLength) { return _to GetLength(aLength); } \
  NS_SCRIPTABLE NS_IMETHOD Item(PRUint32 index, nsIDOMPaintRequest **_retval NS_OUTPARAM) { return _to Item(index, _retval); }

/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIDOMPAINTREQUESTLIST(_to) \
  NS_SCRIPTABLE NS_IMETHOD GetLength(PRUint32 *aLength) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetLength(aLength); } \
  NS_SCRIPTABLE NS_IMETHOD Item(PRUint32 index, nsIDOMPaintRequest **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->Item(index, _retval); }

#if 0
/* Use the code below as a template for the implementation class for this interface. */

/* Header file */
class nsDOMPaintRequestList : public nsIDOMPaintRequestList
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSIDOMPAINTREQUESTLIST

  nsDOMPaintRequestList();

private:
  ~nsDOMPaintRequestList();

protected:
  /* additional members */
};

/* Implementation file */
NS_IMPL_ISUPPORTS1(nsDOMPaintRequestList, nsIDOMPaintRequestList)

nsDOMPaintRequestList::nsDOMPaintRequestList()
{
  /* member initializers and constructor code */
}

nsDOMPaintRequestList::~nsDOMPaintRequestList()
{
  /* destructor code */
}

/* readonly attribute unsigned long length; */
NS_IMETHODIMP nsDOMPaintRequestList::GetLength(PRUint32 *aLength)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* nsIDOMPaintRequest item (in unsigned long index); */
NS_IMETHODIMP nsDOMPaintRequestList::Item(PRUint32 index, nsIDOMPaintRequest **_retval NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* End of implementation class template. */
#endif

#endif /* __gen_nsIDOMPaintRequestList_h__ */