text:
using System;
using System.Xml;

namespace Xstream.Core
{
    public class XStream<TypeOfRoot> : XStreamBase where TypeOfRoot : class
    {
        public XStream()
        {
            AutoAlias(typeof(TypeOfRoot));
        }

        public TypeOfRoot FromXml(string xml)
        {
            return base.FromXml<TypeOfRoot>(xml);
        }

        public string ToXml(TypeOfRoot entity)
        {
            return base.ToXml(entity);
        }
        public new XStream<TypeOfRoot> AddIgnoreAttribute(Type ignoredAttributeType)
        {
            return base.AddIgnoreAttribute(ignoredAttributeType) as XStream<TypeOfRoot>;
        }

        public new XStream<TypeOfRoot> AddConverter(IConverter converter)
        {
            return base.AddConverter(converter) as XStream<TypeOfRoot>;
        }

        public new XStream<TypeOfRoot> AddCData<T>(string property_name)
        {
            return base.AddCData<T>(property_name) as XStream<TypeOfRoot>;
        }

        public new XStream<TypeOfRoot> Alias<T>(string alias)
        {
            return base.Alias<T>(alias) as XStream<TypeOfRoot>;
        }

        public new XStream<TypeOfRoot> ValidateDTD(string dtd)
        {
            return base.ValidateDTD(dtd) as XStream<TypeOfRoot>;
        }
    }

    /// <summary>
    /// Easy facade  class used to (de)serialize objects to and from XML.
    /// This class uses a default MarshalContext that is capable of (de)
    /// serializing almost all objects.
    /// </summary>
    public partial class XStream : XStreamBase
    {

        /// <summary>
        /// Converts the xml string parameter back to a class instance.
        /// </summary>
        [Obsolete]
        public virtual object FromXml(string xml)
        {
            if (base.dtd_for_validation != string.Empty) validate_string(dtd_for_validation + xml);
            object value = marshaller.FromXml(xml, context);
            if (value is GenericObjectHolder) value = ((GenericObjectHolder)value).Value;
            return value;
        }

        /// <summary>
        /// Adds a simple string alias for a specific Type.
        /// </summary>
        /// <param name="alias">String alias name.</param>
        /// <param name="type">Type to use the alias for.</param>
        [Obsolete]
        public XStream Alias(string alias, Type type)
        {
            context.Alias(alias, type);
            return this;
        }

        public new string ToXml(object value)
        {
            return base.ToXml(value);
        }

        public new XStream AutoAlias<TypeOfRoot>()
        {
            return base.AutoAlias<TypeOfRoot>() as XStream;
        }

        public new XStream AddIgnoreAttribute(Type ignoredAttributeType)
        {
            return base.AddIgnoreAttribute(ignoredAttributeType) as XStream;
        }

        public new XStream AddConverter(IConverter converter)
        {
            return base.AddConverter(converter) as XStream;
        }

        public new XStream AddCData<T>(string property_name)
        {
            return base.AddCData<T>(property_name) as XStream;
        }

        public new XStream Alias<T>(string alias)
        {
            return base.Alias<T>(alias) as XStream;
        }
        public new XStream ValidateDTD(string dtd)
        {
            return base.ValidateDTD(dtd) as XStream;
        }

        public new T FromXml<T>(string xml) where T : class
        {
            return base.FromXml<T>(xml);
        }

    }
}


text:
/*
 * ModeShape (http://www.modeshape.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.modeshape.test.integration;

import javax.ejb.Stateless;

/**
 * A stateless EJB that accesses a Repository and creates a JCR Session a variety of ways.
 * <p>
 * This class extends the {@link RepositoryProvider}, which has all the methods for obtaining repositories and using the sessions.
 * </p>
 */
@Stateless
public class StatelessRepositoryProvider extends RepositoryProvider {
}

redpajama_set_name: RedPajamaGithub


text:
'use strict'

import React from 'react'
import {Link} from 'react-router'

export default React.createClass({
  render () {
    const {isExpanded, onToggle} = this.props
    let styleClass = 'sidebar'

    if (!isExpanded) {
      styleClass = `${styleClass}-docked`
    }

    return (

<Link to={'/'} className="nav-item">Overview</Link>

<Link to={'/services'} className="nav-item">Services</Link>

<Link to={'/messages'} className="nav-item">Messages</Link>

<Link to={'/processes'} className="nav-item">Processes</Link>

<Link to={'/clients'} className="nav-item">Clients</Link>

    )
  }
})


text:
namespace Azure.Monitor.OpenTelemetry.Exporter
{
    internal enum TelemetryType
    {
        Request,
        Dependency,
        Message,
        Event
    }
}


text:
require 'google_spreadsheet2yml'
require 'rails'

module GoogleSpreadsheet2yml
  class Railtie < Rails::Railtie
    railtie_name :google_spreadsheet2yml

    rake_tasks do
      load "tasks/google_spreadsheet2yml.rake"
    end
  end
end


text:
<?php
class SumClosureAggregatorTest extends PHPUnit_Framework_TestCase
{

    public function testAggregatorInterface()
    {
        $a = new \CrazyCodr\Data\Grouper\SumClosureAggregator(function($data, $key){ return $data['age']; }, 'test');
        $this->assertInstanceOf('\CrazyCodr\Data\Grouper\AggregatorInterface', $a);
    }

    public function testClosureBasedInterface()
    {
        $a = new \CrazyCodr\Data\Grouper\SumClosureAggregator(function($data, $key){ return $data['age']; }, 'test');
        $this->assertInstanceOf('\CrazyCodr\Data\Grouper\ClosureBasedInterface', $a);
    }

    public function testClosureName()
    {
        $a = new \CrazyCodr\Data\Grouper\SumClosureAggregator(function($data, $key){ return $data['age']; }, 'test');
        $this->assertEquals($a->getName(), 'test');
        $a->setName('hello');
        $this->assertEquals($a->getName(), 'hello');
    }

    public function testClosureResult()
    {
        $a = new \CrazyCodr\Data\Grouper\SumClosureAggregator(function($data, $key){ return $data['age']; }, 'test');
        $b = new \CrazyCodr\Data\Grouper\AggregationValueContainer();
        $c = array('id' => 10, 'sex' => 'male', 'age' => 12);
        $d = array('id' => 11, 'sex' => 'male', 'age' => 18);
        $e = array('id' => 12, 'sex' => 'male', 'age' => 30);
        $a->aggregate($b, $c, 'test');
        $a->aggregate($b, $d, 'test');
        $a->aggregate($b, $e, 'test');
        $this->assertEquals($b->getAggregationValue('test'), 60);
    }

    public function testGetClosure()
    {
        $b = function($data, $key){ return false; };
        $c = function($data, $key){ return true; };
        $a = new \CrazyCodr\Data\Grouper\SumClosureAggregator($b, 'test');
        $this->assertEquals($a->getClosure(), $b);
    }

    public function testSetClosure()
    {
        $b = function($data, $key){ return false; };
        $c = function($data, $key){ return true; };
        $a = new \CrazyCodr\Data\Grouper\SumClosureAggregator($b, 'test');
        $a->setClosure($c);
        $this->assertEquals($a->getClosure(), $c);
    }

}


text:
// key: compiler.misc.invalid.default.interface
// key: compiler.misc.bad.class.file.header
// key: compiler.err.cant.access
// options: -processor CreateBadClassFile

/* The annotation processor will create an invalid classfile with version 51.0
 * and a non-abstract method in an interface. Loading the classfile will produce
 * the diagnostic.
 */
class InvalidDefaultInterface { }


text:
//package org.saiku.reporting.core;
//
//import org.pentaho.reporting.engine.classic.core.AttributeNames;
//import org.pentaho.reporting.engine.classic.core.ReportElement;
//import org.pentaho.reporting.engine.classic.core.function.AbstractElementFormatFunction;
//import org.pentaho.reporting.engine.classic.core.function.StructureFunction;
//import org.pentaho.reporting.engine.classic.core.states.LayoutProcess;
//import org.pentaho.reporting.engine.classic.core.style.ElementStyleKeys;
//import org.pentaho.reporting.engine.classic.core.style.TextStyleKeys;
//import org.pentaho.reporting.libraries.base.util.StringUtils;
//import org.saiku.reporting.core.model.ElementFormat;
//import org.saiku.reporting.core.model.FieldDefinition;
//
//public class OverrideFormattingFunction extends AbstractElementFormatFunction implements StructureFunction {
//	/**
//	 *
//	 */
//	private static final long serialVersionUID = 1L;
//
//	public int getProcessingPriority()
//	{
//		// executed after the metadata has been applied, but before the style-expressions get applied.
//		return 6000;
//	}
//
//
//	/**
//	 * Evaluates all defined style-expressions of the given element.
//	 *
//	 * @param e the element that should be updated.
//	 * @return true, if attributes or style were changed, false if no change was made.
//	 */
//	protected boolean evaluateElement(final ReportElement e)
//	{
//		if (e == null)
//		{
//			throw new NullPointerException();
//		}
//
//		boolean retval = false;
//		final Object maybeFormatData = e.getAttribute(AttributeNames.Wizard.NAMESPACE, "CachedWizardFormatData");
//		if (maybeFormatData instanceof ElementFormat)
//		{
//			final ElementFormat formatDefinition = (ElementFormat) maybeFormatData;
//			if (formatDefinition.getBackgroundColor() != null)
//			{
//				e.getStyle().setStyleProperty(ElementStyleKeys.BACKGROUND_COLOR, formatDefinition.getBackgroundColor());
//				retval = true;
//			}
//			if (formatDefinition.getFontColor() != null)
//			{
//				e.getStyle().setStyleProperty(ElementStyleKeys.PAINT, formatDefinition.getFontColor());
//				retval = true;
//			}
//			if (formatDefinition.getFontBold() != null)
//			{
//				e.getStyle().setStyleProperty(TextStyleKeys.BOLD, formatDefinition.getFontBold());
//				retval = true;
//			}
//			if (formatDefinition.getFontItalic() != null)
//			{
//				e.getStyle().setStyleProperty(TextStyleKeys.ITALIC, formatDefinition.getFontItalic());
//				retval = true;
//			}
//			if (formatDefinition.getFontName() != null)
//			{
//				e.getStyle().setStyleProperty(TextStyleKeys.FONT, formatDefinition.getFontName());
//				retval = true;
//			}
//			if (formatDefinition.getFontUnderline() != null)
//			{
//				e.getStyle().setStyleProperty(TextStyleKeys.UNDERLINED, formatDefinition.getFontUnderline());
//				retval = true;
//			}
//			if (formatDefinition.getFontItalic() != null)
//			{
//				e.getStyle().setStyleProperty(TextStyleKeys.ITALIC, formatDefinition.getFontItalic());
//				retval = true;
//			}
//			if (formatDefinition.getFontSize() != null)
//			{
//				e.getStyle().setStyleProperty(TextStyleKeys.FONTSIZE, formatDefinition.getFontSize());
//				retval = true;
//			}
//			if (formatDefinition.getFontStrikethrough() != null)
//			{
//				e.getStyle().setStyleProperty(TextStyleKeys.STRIKETHROUGH, formatDefinition.getFontStrikethrough());
//				retval = true;
//			}
//			if (formatDefinition.getHorizontalAlignment() != null)
//			{
//				e.getStyle().setStyleProperty(ElementStyleKeys.ALIGNMENT, formatDefinition.getHorizontalAlignment());
//				retval = true;
//			}
//			if (formatDefinition.getVerticalAlignment() != null)
//			{
//				e.getStyle().setStyleProperty(ElementStyleKeys.VALIGNMENT, formatDefinition.getVerticalAlignment());
//				retval = true;
//			}
//		}
//
//		final Object maybeFieldData = e.getAttribute(AttributeNames.Wizard.NAMESPACE, "CachedWizardFieldData");
//		if (maybeFieldData instanceof FieldDefinition)
//		{
//			final FieldDefinition fieldDefinition = (FieldDefinition) maybeFieldData;
//
//			if (fieldDefinition.getDataFormat() != null)
//			{
//				e.setAttribute(AttributeNames.Core.NAMESPACE, AttributeNames.Core.FORMAT_STRING,
//						fieldDefinition.getDataFormat());
//				retval = true;
//			}
//			if (fieldDefinition.getNullString() != null)
//			{
//				e.setAttribute(AttributeNames.Core.NAMESPACE, AttributeNames.Core.NULL_VALUE, fieldDefinition.getNullString());
//				retval = true;
//			}
//
//			if ("label".equals(e.getElementType().getMetaData().getName()) &&
//					!StringUtils.isEmpty(fieldDefinition.getName()))
//			{
//				e.setAttribute(AttributeNames.Core.NAMESPACE, AttributeNames.Core.VALUE, fieldDefinition.getName());
//			}
//
//		}
//
//		return retval;
//	}
//
//	/**
//	 * Returns the dependency level for the expression (controls evaluation order for expressions and functions).
//	 *
//	 * @return the level.
//	 */
//	public int getDependencyLevel()
//	{
//		return LayoutProcess.LEVEL_PAGINATE;
//	}
//}


text:
package org.mass.framework.core.repository;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mass.framework.core.entity.Player;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * Created by Allen on 2015-11-17.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
public class CrudRepositoryTest {

    @Autowired
    public PlayerRepository playerRepository;

    @Test
    public void testGet() {
        Player player = playerRepository.get(1L);
        System.out.println();
    }

    @Test
    public void testAdd() {
        Player player = new Player();
        player.setName("dream");
        playerRepository.add(player);
    }

}


text:
Majordodo is a replicated service to build complex multi-tenant computing grids.
You can view it as a distributed threadpool where tasks are submitted by users and a network of brokers schedules execution on a large set of machines, caring about failures, recovery and priority-based resources assignment.

Tasks are implemented in Java and can be submitted and monitored using a simple HTTP REST JSON API.

Multi-tenancy

Majordodo manages resources for each tenant and guarantees resource access isolation and fair scheduling. Users' execution priorities are dynamic and can be modified at runtime for each and every task, even ones that have already been submitted to the scheduler.

Resiliency

Majordodo leverages Apache Zookeeper  and Apache Bookkeeper to build a fully replicated, shared-nothing, broker architecture without any single point of failure. Workers can be run on commodity-hardware, virtual machines or dynamically provisioned cloud resources which may fail at any time without service interruption.

Scalability

Majordodo is designed to manage tasks for thousands of hosts. It is simple to add and remove hosts and resources with dynamic reconfiguration and adaptive tasks scheduling.


text:
chef_version '>= 12.5' if respond_to?(:chef_version)
description 'Environment cookbook that configures a Linux server as a container host with consul and nomad'
issues_url '${ProductUrl}/issues' if respond_to?(:issues_url)
license 'Apache-2.0'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
name 'resource_container_host_linux'
maintainer '${CompanyName} (${CompanyUrl})'
maintainer_email '${EmailDocumentation}'
source_url '${ProductUrl}' if respond_to?(:source_url)
version '${VersionSemantic}'

supports 'ubuntu', '>= 16.04'

depends 'chef-apt-docker', '= 2.0.2'
depends 'consul', '= 3.0.0'
depends 'docker', '= 2.15.24'
depends 'firewall', '= 2.6.2'
depends 'nomad', '= 0.13.0'
depends 'systemd', '= 2.1.3'


text:
namespace extensions {
class ScriptContext;

class UtilsNativeHandler : public ObjectBackedNativeHandler {
 public:
  explicit UtilsNativeHandler(ScriptContext* context);
  ~UtilsNativeHandler() override;

 private:
  // |args| consists of one argument: an arbitrary value. Returns a deep copy of
  // that value. The copy will have no references to nested values of the
  // argument.
  void DeepCopy(const v8::FunctionCallbackInfo<v8::Value>& args);

  DISALLOW_COPY_AND_ASSIGN(UtilsNativeHandler);
};

}  // namespace extensions

#endif  // EXTENSIONS_RENDERER_UTILS_NATIVE_HANDLER_H_


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gbif.registry.persistence.mapper;

import org.gbif.api.model.registry.Comment;

import java.util.List;
import java.util.UUID;

import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

@Repository
public interface CommentableMapper {

  int addComment(@Param("targetEntityKey") UUID entityKey, @Param("commentKey") int commentKey);

  int deleteComment(@Param("targetEntityKey") UUID entityKey, @Param("commentKey") int commentKey);

  List<Comment> listComments(@Param("targetEntityKey") UUID identifierKey);
}


text:
#include "DrvD3D9Pch.h"
#include "D3D9StateCache.h"

namespace Demi
{
    DiD3D9StateCache::DiD3D9StateCache(LPDIRECT3DDEVICE9 device)
        :mDevice(device),
        mVertexShader(nullptr),
        mPixelShader(nullptr),
        mVertDecl(nullptr),
        mIndexBuffer(nullptr)
    {
        DirtyAll();
    }

    DiD3D9StateCache::~DiD3D9StateCache()
    {

    }

    void DiD3D9StateCache::DirtyAll()
    {
        mRenderStates.ClearCache();

        for (int i = 0; i < D3D9_TEXTURE_COUNT; ++i)
        {
            mSamplerStates[i].ClearCache();
            mTextureStates[i].ClearCache();
        }

        mTextures.ClearCache();
        mStreams.ClearCache();
        mStreamFreqs.ClearCache();

        mVertexShader = nullptr;
        mPixelShader = nullptr;
        mVertDecl = nullptr;
        mIndexBuffer = nullptr;
    }

    HRESULT DiD3D9StateCache::SetRenderState(D3DRENDERSTATETYPE rs, DWORD val)
    {
        if (mRenderStates.SetCache((int)rs, val))
            return mDevice->SetRenderState(rs, val);
        return S_OK;
    }

    HRESULT DiD3D9StateCache::SetSamplerState(DWORD dwStage, D3DSAMPLERSTATETYPE d3dSamplerState, DWORD dwValue)
    {
        DI_ASSERT(dwStage < D3D9_MAX_SAMPLERS);
        if (mSamplerStates[dwStage].SetCache((int)d3dSamplerState, dwValue))
            return mDevice->SetSamplerState(dwStage, d3dSamplerState, dwValue);
        return S_OK;
    }

    HRESULT DiD3D9StateCache::SetTextureStageState(DWORD dwStage, D3DTEXTURESTAGESTATETYPE d3dTextureStageState, DWORD dwValue)
    {
        DI_ASSERT(dwStage < D3D9_MAX_SAMPLERS);
        if (mTextureStates[dwStage].SetCache((int)d3dTextureStageState, dwValue))
            return mDevice->SetTextureStageState(dwStage, d3dTextureStageState, dwValue);
        return S_OK;
    }

    HRESULT DiD3D9StateCache::SetTexture(DWORD stage, IDirect3DBaseTexture9* tex)
    {
        if (mTextures.SetCache(int(stage), tex))
            return mDevice->SetTexture(stage, tex);
        return S_OK;
    }

    HRESULT DiD3D9StateCache::SetVertexShader(IDirect3DVertexShader9* shader)
    {
        if (mVertexShader != shader)
        {
            mVertexShader = shader;
            return mDevice->SetVertexShader(shader);
        }
        return S_OK;
    }

    HRESULT DiD3D9StateCache::SetPixelShader(IDirect3DPixelShader9* shader)
    {
        if (mPixelShader != shader)
        {
            mPixelShader = shader;
            return mDevice->SetPixelShader(shader);
        }
        return S_OK;
    }

    HRESULT DiD3D9StateCache::SetVertexDeclaration(LPDIRECT3DVERTEXDECLARATION9 pVertDecl)
    {
        if (pVertDecl != mVertDecl)
        {
            HRESULT hr = mDevice->SetVertexDeclaration(pVertDecl);
            mVertDecl = pVertDecl;
            return hr;
        }
        return S_OK;
    }

    HRESULT DiD3D9StateCache::SetStreamSource(uint32 StreamNumber,
        IDirect3DVertexBuffer9* pStreamData, uint32 OffsetInBytes, uint32 Stride)
    {
        DI_ASSERT(StreamNumber < D3D9_VERTEXSTREAM_COUNT);
        if (mStreams.SetCache((int)StreamNumber, pStreamData))
        {
            HRESULT hr = mDevice->SetStreamSource(StreamNumber, pStreamData, OffsetInBytes, Stride);
            return hr;
        }
        return S_OK;
    }

    HRESULT DiD3D9StateCache::SetIndices(IDirect3DIndexBuffer9* pIndexData)
    {
        if (mIndexBuffer != pIndexData)
        {
            HRESULT hr = mDevice->SetIndices(pIndexData);
            mIndexBuffer = pIndexData;
            return hr;
        }
        return S_OK;
    }

    HRESULT DiD3D9StateCache::SetStreamSourceFreq(DWORD index, DWORD freq)
    {
        if (mStreamFreqs.SetCache((int)index, freq))
            return mDevice->SetStreamSourceFreq(index, freq);
        return S_OK;
    }
}


text:
// Filename: pstrtod.h
// Created by:  drose (13Jun09)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University.  All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license.  You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////

#ifndef PSTRTOD_H
#define PSTRTOD_H

#include "dtoolbase.h"

#ifdef __cplusplus
extern "C" {
#endif

EXPCL_DTOOL double
pstrtod(const char *nptr, char **endptr);

EXPCL_DTOOL double
patof(const char *str);

#ifdef __cplusplus
};  /* end of extern "C" */
#endif

#endif


text:
package org.springframework.aop.framework.adapter;

import java.io.Serializable;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import org.springframework.aop.MethodBeforeAdvice;

/**
 * Interceptor to wrap a MethodBeforeAdvice. In future we may also offer a more
 * efficient alternative solution in cases where there is no interception advice
 * and therefore no need to create a MethodInvocation object.
 *
 *
Used internally by the AOP framework: application developers should not need
 * to use this class directly.
 *
 *
You can use this class to wrap Spring MethodBeforeAdvice implementations
 * for use in other AOP frameworks supporting the AOP Alliance
 * interfaces.
 *
 * @author Rod Johnson
 */
public final class MethodBeforeAdviceInterceptor implements MethodInterceptor, Serializable {

	private MethodBeforeAdvice advice;

	public MethodBeforeAdviceInterceptor(MethodBeforeAdvice advice) {
		this.advice = advice;
	}

	/**
	 * @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
	 */
	public Object invoke(MethodInvocation mi) throws Throwable {
		advice.before(mi.getMethod(), mi.getArguments(), mi.getThis() );
		return mi.proceed();
	}

}


text:
namespace OJS.Services.Common
{
    public interface IService
    {
    }
}


text:
<?php

namespace Bigstock\OAuth2API;

class Client
{

    protected static $PRODUCTION_URL = 'https://api.bigstockphoto.com/2/oauth2';
    protected static $DEVELOPMENT_URL = 'https://testapi.bigstockphoto.com/2/oauth2';

    protected static $TOKEN_ENDPOINT = 'token';

    protected $client;
    protected $secret;

    protected $token;

    protected $in_production_mode;

    /**
     * construct method, useful only for setting whether or not you are hitting production endpoints
     *
     * @param  $in_production_mode  whether or not the client should hit production servers
     */
    public function __construct($in_production_mode = true)
    {
        $this->in_production_mode = $in_production_mode;
    }

    /**
     * primary kick-off method of setting up a communication route
     * takes the client and secret and saves it locally
     *
     * @param  $client  string  the client (partner) id
     * @param  $secret  string  the secret key tied to the client account
     */
    public function setClientCredentials($client, $secret)
    {
        $this->client = $client;
        $this->secret = $secret;
    }

    /**
     * secondary method of setting up a communication route
     * accepts a token that has been granted by token endpoint
     *
     * @param  $token  string  token handed off by api to make secure calls
     */
    public function setToken($token)
    {
        $this->token = $token;
    }

    /**
     * method that handles all requests
     * there will need to be at least one authentication method defined before calling this
     *
     * @param   $endpoint          string   the endpoint for service you want to hit
     * @param   $parameters        array    key -> value set of parameters relevant to the call
     * @return                     json     expanded json class from the request
     */
    public function request($endpoint, $parameters = array())
    {
        $is_token_request = ($endpoint == self::$TOKEN_ENDPOINT);

        if (empty($this->token) && !$is_token_request) {
            $this->token = $this->fetchToken();
        }

        $this->checkRequiredAuthentication($is_token_request);

        $handle = curl_init();
        curl_setopt($handle, CURLOPT_URL, $this->fetchURL($endpoint, $parameters));
        curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($handle, CURLOPT_POST, true);

        if ($is_token_request) {
            curl_setopt($handle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
            curl_setopt($handle, CURLOPT_USERPWD, "{$this->client}:{$this->secret}");

            $post_fields = array(
                'grant_type' => 'client_credentials',
            );
        } else {
            $post_fields = array(
                'access_token' => $this->token,
            );
        }

        curl_setopt($handle, CURLOPT_POSTFIELDS, http_build_query($post_fields));

        $response = curl_exec($handle);
        curl_close($handle);

        if ($response === false) {
            throw new \Exception('Request failed with error ' . curl_error($handle));
        }

        return json_decode($response);
    }

    /**
     * helper method to check for basic required authentication before making a request
     *
     * @param  $is_token_request  boolean  whether or not this request is for a token
     */
    protected function checkRequiredAuthentication($is_token_request)
    {
        if ($is_token_request) {
            if (empty($this->client) || empty($this->secret)) {
                throw new \Exception('You must define the client and secret before requesting a token!');
            }
        } else {
            if (empty($this->token)) {
                throw new \Exception('You must have a valid token before making a request!');
            }
        }
    }

    /**
     * helper method to request an access token
     * encapsulates request call and response parsing for the token endpoint
     *
     * @return  string  access token from Bigstock OAuth2
     */
    protected function fetchToken()
    {
        $response = $this->request(self::$TOKEN_ENDPOINT);

        if ($response === null) {
            throw new \Exception('Invalid response from the API. Cannot fetch token.');
        } else if (isset($response->error)) {
            throw new \Exception("There was an error creating a token: {$response->error_description}");
        } else if (!isset($response->access_token)) {
            throw new \Exception('Unexpected response from the API. Cannot parse token.');
        }

        return $response->access_token;
    }

    /**
     * helper method to construct the full api url
     * switch for production v development environment, plus builder for query params
     *
     * @param   $endpoint    string  api endpoint
     * @param   $parameters  array   array of parameters for endpoint
     * @return               string  url endpoint for curl request
     */
    protected function fetchURL($endpoint, $parameters)
    {
        $url = '';
        $url .= ($this->in_production_mode) ? self::$PRODUCTION_URL : self::$DEVELOPMENT_URL;
        $url .= '/';
        $url .= $endpoint;

        if (count($parameters) > 0) {
            $url .= '?';
            $url .= http_build_query($parameters);
        }

        return $url;
    }

}


text:
package com.spotify.helios.common;

import java.io.File;

public class LoggingConfig {

  private final int verbosity;
  private final boolean syslog;
  private final File configFile;
  private final boolean noLogSetup;

  public LoggingConfig(final int verbosity, final boolean syslog, final File configFile,
                       final boolean noLogSetup) {
    this.verbosity = verbosity;
    this.syslog = syslog;
    this.configFile = configFile;
    this.noLogSetup = noLogSetup;
  }

  public int getVerbosity() {
    return verbosity;
  }

  public boolean isSyslog() {
    return syslog;
  }

  public File getConfigFile() {
    return configFile;
  }

  public boolean getNoLogSetup() {
    return noLogSetup;
  }
}


text:
#include <mongoc/mongoc.h>
#include <mongoc/mongoc-util-private.h>

#include "mongoc/mongoc-client-private.h"

#include "TestSuite.h"
#include "json-test.h"
#include "test-libmongoc.h"
#include "mock_server/mock-server.h"
#include "mock_server/future-functions.h"

#undef MONGOC_LOG_DOMAIN
#define MONGOC_LOG_DOMAIN "client-test-max-staleness"

static int64_t
get_max_staleness (const mongoc_client_t *client)
{
   const mongoc_read_prefs_t *prefs;

   prefs = mongoc_client_get_read_prefs (client);

   return mongoc_read_prefs_get_max_staleness_seconds (prefs);
}

/* the next few tests are from max-staleness-tests.rst */
static void
test_mongoc_client_max_staleness (void)
{
   mongoc_client_t *client;

   client = test_framework_client_new (NULL, NULL);
   ASSERT_CMPINT64 (get_max_staleness (client), ==, (int64_t) -1);
   mongoc_client_destroy (client);

   client = test_framework_client_new (
      "mongodb://a/?" MONGOC_URI_READPREFERENCE "=secondary", NULL);
   ASSERT_CMPINT64 (get_max_staleness (client), ==, (int64_t) -1);
   mongoc_client_destroy (client);

   /* -1 is the default, means "no max staleness" */
   client = test_framework_client_new (
      "mongodb://a/?" MONGOC_URI_MAXSTALENESSSECONDS "=-1", NULL);
   ASSERT_CMPINT64 (get_max_staleness (client), ==, (int64_t) -1);
   mongoc_client_destroy (client);

   client = test_framework_client_new (
      "mongodb://a/?" MONGOC_URI_READPREFERENCE
      "=primary&" MONGOC_URI_MAXSTALENESSSECONDS "=-1",
      NULL);

   ASSERT_CMPINT64 (get_max_staleness (client), ==, (int64_t) -1);
   mongoc_client_destroy (client);

   /* no " MONGOC_URI_MAXSTALENESSSECONDS " with primary mode */
   capture_logs (true);
   ASSERT (!test_framework_client_new (
      "mongodb://a/?" MONGOC_URI_MAXSTALENESSSECONDS "=120", NULL));
   ASSERT_CAPTURED_LOG (MONGOC_URI_MAXSTALENESSSECONDS "=120",
                        MONGOC_LOG_LEVEL_WARNING,
                        "Invalid readPreferences");

   capture_logs (true);
   ASSERT (!test_framework_client_new (
      "mongodb://a/?" MONGOC_URI_READPREFERENCE
      "=primary&" MONGOC_URI_MAXSTALENESSSECONDS "=120",
      NULL));
   ASSERT_CAPTURED_LOG (MONGOC_URI_MAXSTALENESSSECONDS "=120",
                        MONGOC_LOG_LEVEL_WARNING,
                        "Invalid readPreferences");
   capture_logs (false);

   /* zero is prohibited */
   capture_logs (true);
   client = test_framework_client_new (
      "mongodb://a/?" MONGOC_URI_READPREFERENCE
      "=nearest&" MONGOC_URI_MAXSTALENESSSECONDS "=0",
      NULL);

   ASSERT_CAPTURED_LOG (
      MONGOC_URI_MAXSTALENESSSECONDS "=0",
      MONGOC_LOG_LEVEL_WARNING,
      "Unsupported value for \"" MONGOC_URI_MAXSTALENESSSECONDS "\": \"0\"");
   capture_logs (false);

   ASSERT_CMPINT64 (get_max_staleness (client), ==, (int64_t) -1);
   mongoc_client_destroy (client);

   client =
      test_framework_client_new ("mongodb://a/?" MONGOC_URI_MAXSTALENESSSECONDS
                                 "=120&" MONGOC_URI_READPREFERENCE "=secondary",
                                 NULL);

   ASSERT_CMPINT64 (get_max_staleness (client), ==, (int64_t) 120);
   mongoc_client_destroy (client);

   /* float is ignored */
   capture_logs (true);
   ASSERT (!test_framework_client_new (
      "mongodb://a/?" MONGOC_URI_READPREFERENCE
      "=secondary&" MONGOC_URI_MAXSTALENESSSECONDS "=10.5",
      NULL));

   ASSERT_CAPTURED_LOG (MONGOC_URI_MAXSTALENESSSECONDS "=10.5",
                        MONGOC_LOG_LEVEL_WARNING,
                        "Invalid " MONGOC_URI_MAXSTALENESSSECONDS);
   capture_logs (false);

   /* 1 is allowed, it'll be rejected once we begin server selection */
   client = test_framework_client_new (
      "mongodb://a/?" MONGOC_URI_READPREFERENCE
      "=secondary&" MONGOC_URI_MAXSTALENESSSECONDS "=1",
      NULL);

   ASSERT_EQUAL_DOUBLE (get_max_staleness (client), 1);
   mongoc_client_destroy (client);
}

static void
test_mongos_max_staleness_read_pref (void)
{
   mock_server_t *server;
   mongoc_collection_t *collection;
   mongoc_client_t *client;
   mongoc_read_prefs_t *prefs;
   future_t *future;
   request_t *request;
   bson_error_t error;

   server = mock_mongos_new (WIRE_VERSION_MIN);
   mock_server_run (server);
   mock_server_auto_endsessions (server);
   client =
      test_framework_client_new_from_uri (mock_server_get_uri (server), NULL);
   collection = mongoc_client_get_collection (client, "db", "collection");

   /* count command with mode "secondary", no MONGOC_URI_MAXSTALENESSSECONDS. */
   prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY);
   mongoc_collection_set_read_prefs (collection, prefs);
   future = future_collection_count (
      collection, MONGOC_QUERY_NONE, NULL, 0, 0, NULL, &error);
   request = mock_server_receives_msg (
      server,
      MONGOC_MSG_NONE,
      tmp_bson ("{'$db': 'db',"
                " '$readPreference': {"
                "   'mode': 'secondary',"
                "   'maxStalenessSeconds': {'$exists': false}}}"));

   mock_server_replies_simple (request, "{'ok': 1, 'n': 1}");
   ASSERT_OR_PRINT (1 == future_get_int64_t (future), error);

   request_destroy (request);
   future_destroy (future);

   /* count command with mode "secondary". MONGOC_URI_MAXSTALENESSSECONDS=1 is
    * allowed by client, although in real life mongos will reject it */
   mongoc_read_prefs_set_max_staleness_seconds (prefs, 1);
   mongoc_collection_set_read_prefs (collection, prefs);

   mongoc_collection_set_read_prefs (collection, prefs);
   future = future_collection_count (
      collection, MONGOC_QUERY_NONE, NULL, 0, 0, NULL, &error);
   request = mock_server_receives_msg (
      server,
      MONGOC_MSG_NONE,
      tmp_bson ("{'$db': 'db',"
                " '$readPreference': {"
                "   'mode': 'secondary',"
                "   'maxStalenessSeconds': {'$numberLong': '1'}}}"));

   mock_server_replies_simple (request, "{'ok': 1, 'n': 1}");
   ASSERT_OR_PRINT (1 == future_get_int64_t (future), error);

   request_destroy (request);
   future_destroy (future);

   /* For all read preference modes that are not 'primary', drivers MUST set
    * readPreference. */
   mongoc_read_prefs_set_mode (prefs, MONGOC_READ_SECONDARY_PREFERRED);
   mongoc_read_prefs_set_max_staleness_seconds (prefs, MONGOC_NO_MAX_STALENESS);
   mongoc_collection_set_read_prefs (collection, prefs);

   future = future_collection_count (
      collection, MONGOC_QUERY_NONE, NULL, 0, 0, NULL, &error);
   request = mock_server_receives_msg (
      server,
      MONGOC_MSG_NONE,
      tmp_bson (
         "{'$db': 'db', '$readPreference': {'mode': 'secondaryPreferred'}}"));

   mock_server_replies_simple (request, "{'ok': 1, 'n': 1}");
   ASSERT_OR_PRINT (1 == future_get_int64_t (future), error);

   request_destroy (request);
   future_destroy (future);

   /* CDRIVER-3633: with readPreference mode secondaryPreferred and
    * maxStalenessSeconds set, readPreference MUST be sent. */
   mongoc_read_prefs_set_max_staleness_seconds (prefs, 1);
   mongoc_collection_set_read_prefs (collection, prefs);

   future = future_collection_count (
      collection, MONGOC_QUERY_NONE, NULL, 0, 0, NULL, &error);
   request = mock_server_receives_msg (
      server,
      MONGOC_MSG_NONE,
      tmp_bson ("{'$db': 'db',"
                " '$readPreference': {"
                "   'mode': 'secondaryPreferred',"
                "   'maxStalenessSeconds': {'$numberLong': '1'}}}"));

   mock_server_replies_simple (request, "{'ok': 1, 'n': 1}");
   ASSERT_OR_PRINT (1 == future_get_int64_t (future), error);

   request_destroy (request);
   future_destroy (future);

   mongoc_read_prefs_destroy (prefs);
   mongoc_collection_destroy (collection);
   mongoc_client_destroy (client);
   mock_server_destroy (server);
}

static void
_test_last_write_date (bool pooled)
{
   mongoc_uri_t *uri;
   mongoc_client_pool_t *pool = NULL;
   mongoc_client_t *client;
   mongoc_collection_t *collection;
   bson_error_t error;
   bool r;
   mongoc_server_description_t *s0, *s1;
   int64_t delta;

   uri = test_framework_get_uri ();
   mongoc_uri_set_option_as_int32 (uri, "heartbeatFrequencyMS", 500);

   if (pooled) {
      pool = test_framework_client_pool_new_from_uri (uri, NULL);
      test_framework_set_pool_ssl_opts (pool);
      client = mongoc_client_pool_pop (pool);
   } else {
      client = test_framework_client_new_from_uri (uri, NULL);
      test_framework_set_ssl_opts (client);
   }
   mongoc_uri_destroy (uri);

   collection = get_test_collection (client, "test_last_write_date");
   r = mongoc_collection_insert_one (
      collection, tmp_bson ("{}"), NULL, NULL, &error);
   ASSERT_OR_PRINT (r, error);

   _mongoc_usleep (1000 * 1000);
   s0 = mongoc_topology_select (
      client->topology, MONGOC_SS_WRITE, NULL, NULL, &error);
   ASSERT_OR_PRINT (s0, error);

   _mongoc_usleep (1000 * 1000);
   r = mongoc_collection_insert_one (
      collection, tmp_bson ("{}"), NULL, NULL, &error);
   ASSERT_OR_PRINT (r, error);

   _mongoc_usleep (1000 * 1000);
   s1 = mongoc_topology_select (
      client->topology, MONGOC_SS_WRITE, NULL, NULL, &error);
   ASSERT_OR_PRINT (s1, error);
   ASSERT_CMPINT64 (s1->last_write_date_ms, !=, (int64_t) -1);

   /* lastWriteDate increased by roughly one second - be lenient, just check
    * it increased by less than 10 seconds */
   delta = s1->last_write_date_ms - s0->last_write_date_ms;
   ASSERT_CMPINT64 (delta, >, (int64_t) 0);
   ASSERT_CMPINT64 (delta, <, (int64_t) 10 * 1000);

   mongoc_server_description_destroy (s0);
   mongoc_server_description_destroy (s1);
   mongoc_collection_destroy (collection);

   if (pooled) {
      mongoc_client_pool_push (pool, client);
      mongoc_client_pool_destroy (pool);
   } else {
      mongoc_client_destroy (client);
   }
}

static void
test_last_write_date (void *ctx)
{
   _test_last_write_date (false);
}

static void
test_last_write_date_pooled (void *ctx)
{
   _test_last_write_date (true);
}

/* run only if wire version is older than 5 */
static void
_test_last_write_date_absent (bool pooled)
{
   mongoc_client_pool_t *pool = NULL;
   mongoc_client_t *client;
   bson_error_t error;
   mongoc_server_description_t *sd;

   if (pooled) {
      pool = test_framework_new_default_client_pool ();
      client = mongoc_client_pool_pop (pool);
   } else {
      client = test_framework_new_default_client ();
   }

   sd = mongoc_topology_select (
      client->topology, MONGOC_SS_READ, NULL, NULL, &error);
   ASSERT_OR_PRINT (sd, error);

   /* lastWriteDate absent */
   ASSERT_CMPINT64 (sd->last_write_date_ms, ==, (int64_t) -1);

   mongoc_server_description_destroy (sd);

   if (pooled) {
      mongoc_client_pool_push (pool, client);
      mongoc_client_pool_destroy (pool);
   } else {
      mongoc_client_destroy (client);
   }
}

static void
test_last_write_date_absent (void *ctx)
{
   _test_last_write_date_absent (false);
}

static void
test_last_write_date_absent_pooled (void *ctx)
{
   _test_last_write_date_absent (true);
}

static void
test_all_spec_tests (TestSuite *suite)
{
   install_json_test_suite (
      suite, JSON_DIR, "max_staleness", &test_server_selection_logic_cb);
}

void
test_client_max_staleness_install (TestSuite *suite)
{
   test_all_spec_tests (suite);
   TestSuite_Add (
      suite, "/Client/max_staleness", test_mongoc_client_max_staleness);
   TestSuite_AddMockServerTest (suite,
                                "/Client/max_staleness/mongos",
                                test_mongos_max_staleness_read_pref);
   TestSuite_AddFull (suite,
                      "/Client/last_write_date",
                      test_last_write_date,
                      NULL,
                      NULL,
                      test_framework_skip_if_not_replset,
                      test_framework_skip_if_slow);
   TestSuite_AddFull (suite,
                      "/Client/last_write_date/pooled",
                      test_last_write_date_pooled,
                      NULL,
                      NULL,
                      test_framework_skip_if_not_replset,
                      test_framework_skip_if_slow);
   TestSuite_AddFull (suite,
                      "/Client/last_write_date_absent",
                      test_last_write_date_absent,
                      NULL,
                      NULL,
                      test_framework_skip_if_replset);
   TestSuite_AddFull (suite,
                      "/Client/last_write_date_absent/pooled",
                      test_last_write_date_absent_pooled,
                      NULL,
                      NULL,
                      test_framework_skip_if_replset);
}


text:
"use strict";

import socket from "../socket";
import {switchToChannel, navigate} from "../router";
import store from "../store";

socket.on("quit", function (data) {
	// If we're in a channel, and it's on the network that is being removed,
	// then open another channel window
	const isCurrentNetworkBeingRemoved =
		store.state.activeChannel && store.state.activeChannel.network.uuid === data.network;

	store.commit("removeNetwork", data.network);

	if (!isCurrentNetworkBeingRemoved) {
		return;
	}

	if (store.state.networks.length > 0) {
		switchToChannel(store.state.networks[0].channels[0]);
	} else {
		navigate("Connect");
	}
});


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/Users/gmdearaujo/AndroidStudioProjects/PlannerAI/ParseStarterProject/build/intermediates/exploded-aar/com.android.support/appcompat-v7/23.0.1/res/values-w360dp/values-w360dp.xml -->
    <eat-comment/>
    <integer name="abc_max_action_buttons">3</integer>
</resources>


text:
layout: post
title: A Wiki? Yeah!
date: '2011-11-01T11:45:00-04:00'
tags:
- Wiki
- School
- Notetaking
tumblr_url: http://blog.mroberts.me/post/12198614917/a-wiki-yeah
menu: blog
---
A Wiki? Yeah!

> [http://wiki.mroberts.me/](wiki.mroberts.me)

Full disclosure: I totally stole this idea from [Wesley](http://blog.tahnok.me/), but it has helped me study for Psychology so far so I am going to run with it. We spend so much time writing these notes things, why shouldn't we do something with them?

If someone in my classes finds these, it might be useful to them, maybe no one will but having to type them out and format them forces me to re-read them and that's studying. #BrainHack

Also, I have decided to add in as much supplemental material as I can, pictures / links to articles / Wikipedia, to make the notes as complete as possible.

> In my PSYC*2390 class, my prof mentioned how the depth cue of occlusion was one of the first used by artists, dating back to Egyptian art. In that section of the notes, I added a link to an Egyptian painting that illustrates that.

Hopefully I will keep this up, but it may stagnate when I get super busy, and as for my classes from previous semesters… If I ever get super bored, I might put them up, but it won't have the studying incentive, so it might be later rather than sooner.

Tech Specs: I'm using [DokuWiki](http://www.dokuwiki.org/), which is a fairly simple wiki platform designed with PHP and uses files as storage not a DB (for easy backups - just copy the wiki folder), has revision control, has a fair amount of plugins to increase functionality and allows for ACL enough to satisfy me (keep them griefers away [Minecraft reference]). It also features a simplified syntax similar to [MediaWiki](http://www.mediawiki.org/), which I prefer to WYSIWYG.

I debated keeping it publicly editable in case someone wanted to add additional information to my notes, but I realized that they would stop being my notes in that case, and I want to be in control of them. That being said - if someone wants to join, send me an email and I will give you an account. If someone other than me joins, I will add some type of talk page feature (using the aforementioned plugins) so we can discuss before we edit each other's pages.


text:
require 'sinatra/base'
require 'json'

require_relative '../bag_of_words/bag_of_words_controller'
require_relative '../crawler/crawling_controller'
require_relative '../news/news_controller'
require_relative '../authentication/authentication_controller'

# Main endpoint of the application
#
# author: Luis Carlos Mateos
#
# description:
#   it defines the dossier endpoints that are available from the client applications
class DossierEndpoint < Sinatra::Base

  def initialize(*args)
    super(args)
    @crawling_controller = CrawlingController.new
    @news_controller = NewsController.new
    @bow_controller = BagOfWordsController.new
    @authentication_controller = AuthenticationController.new
  end

  # Gives the order to submit a background job and to start the crawling process over the newspapers
  #
  # @return [Boolean] response: status The crawl process has started or not
  get '/search' do
    content_type :json
    status = @crawling_controller.crawl_newspapers()
    {response: status}.to_json
  end

  # Queries the crawler for its status
  #
  # @return [String] response: status where status is ACTIVE or INACTIVE depending on the status of the crawler
  get '/status' do
    content_type :json
    status = @crawling_controller.crawl_active()
    {response: status}.to_json
  end

  # Queries for the news and if a query params were given filters them.
  #
  # @param [Optional<Hash>] fromts: <from_date>, tots: <to_date> where dates format is YYYY-MM-DD
  # @return [Array] news: <news>
  get '/news' do
    content_type :json
    news = @news_controller.fetch_news(params)
    {news: news}.to_json
  end

  # Retrieves the bag of words adding a word
  #
  # @return [Array] words: <words>
  get "/words" do
    content_type :json
    words = @bow_controller.fetch_words()
    {words: words}.to_json
  end

  # Updates the bag of words adding a word requires to send a form with www-url-form-encoded
  # @param [String] word: <word> word to be deleted
  # @return [Boolean] response: <succeeed> The word was added or not
  put "/words" do
    content_type :json
    success = @bow_controller.add_word(params[:word])
    {response: success}.to_json
  end

  # Updates the bag of words deleting a word
  #
  # @return [Boolean] response: <success> The delete was sucessful or failed
  delete "/words" do
    content_type :json
    success = @bow_controller.delete_word(params[:word])
    {response: success}.to_json
  end

  # Creates a session in the system for a user
  #
  # @return [String] response: <session_id> the session_id that should be sent in every internal request.
  post '/session' do
    begin
      content_type :json
      session_id = @authentication_controller.create_session(params)
      {session: session_id}.to_json
    rescue AuthenticationFailedError
      halt 401, headers, {code: 401, message: 'Unauthorized'}.to_json
    end
  end

  # Logs out a user from the system by reseting his session
  #
  # @return [String] response: <session_id> empty session id string
  delete '/session' do
    content_type :json
    session_id = @authentication_controller.delete_session(params)
    {session: session_id}.to_json
  end

  # Heartbeat that will provide with information about whether the core is working or not
  #
  #
  get "/ping" do
    "PONG"
  end

  before '/words' do
    begin
      @authentication_controller.validate_session({
        user: env['HTTP_AUTH_USER'],
        session_id: env['HTTP_SESSION_ID']
      })
    rescue AuthenticationFailedError => e
      halt 403, headers, {code: 403, message: 'Unauthorized'}.to_json
    end
  end

end


text:
require 'formula'

class Ffmpeg < Formula
  homepage 'http://ffmpeg.org/'
  url 'http://ffmpeg.org/releases/ffmpeg-2.2.2.tar.bz2'
  sha1 '8a4f282ccb5efbec31a9747d12c8d7b07c481f2e'

  head 'git://git.videolan.org/ffmpeg.git'

  bottle do
    sha1 "3d92cc6e39cb4a931ba0ef6086a3facccc2a4fb6" => :mavericks
    sha1 "abdf840749997229d507bb21096b4950430b2664" => :mountain_lion
    sha1 "65b6fee763e85df649addbe2232e0dec810c7365" => :lion
  end

  option "without-x264", "Disable H.264 encoder"
  option "without-lame", "Disable MP3 encoder"
  option "without-xvid", "Disable Xvid MPEG-4 video encoder"

  option "with-rtmpdump", "Enable RTMP protocol"
  option "with-libvo-aacenc", "Enable VisualOn AAC encoder"
  option "with-libass", "Enable ASS/SSA subtitle format"
  option "with-openjpeg", 'Enable JPEG 2000 image format'
  option 'with-openssl', 'Enable SSL support'
  option 'with-schroedinger', 'Enable Dirac video format'
  option 'with-ffplay', 'Enable FFplay media player'
  option 'with-tools', 'Enable additional FFmpeg tools'
  option 'with-fdk-aac', 'Enable the Fraunhofer FDK AAC library'
  option 'with-libvidstab', 'Enable vid.stab support for video stabilization'
  option 'with-x265', "Enable x265 encoder"

  depends_on 'pkg-config' => :build

  # manpages won't be built without texi2html
  depends_on 'texi2html' => :build if MacOS.version >= :mountain_lion
  depends_on 'yasm' => :build

  depends_on 'x264' => :recommended
  depends_on 'faac' => :recommended
  depends_on 'lame' => :recommended
  depends_on 'xvid' => :recommended

  depends_on :freetype => :optional
  depends_on 'theora' => :optional
  depends_on 'libvorbis' => :optional
  depends_on 'libvpx' => :optional
  depends_on 'rtmpdump' => :optional
  depends_on 'opencore-amr' => :optional
  depends_on 'libvo-aacenc' => :optional
  depends_on 'libass' => :optional
  depends_on 'openjpeg' => :optional
  depends_on 'sdl' if build.with? "ffplay"
  depends_on 'speex' => :optional
  depends_on 'schroedinger' => :optional
  depends_on 'fdk-aac' => :optional
  depends_on 'opus' => :optional
  depends_on 'frei0r' => :optional
  depends_on 'libcaca' => :optional
  depends_on 'libbluray' => :optional
  depends_on 'libquvi' => :optional
  depends_on 'libvidstab' => :optional
  depends_on 'x265' => :optional

  def install
    args = ["--prefix=#{prefix}",
            "--enable-shared",
            "--enable-pthreads",
            "--enable-gpl",
            "--enable-version3",
            "--enable-nonfree",
            "--enable-hardcoded-tables",
            "--enable-avresample",
            "--enable-vda",
            "--cc=#{ENV.cc}",
            "--host-cflags=#{ENV.cflags}",
            "--host-ldflags=#{ENV.ldflags}"
           ]

    args << "--enable-libx264" if build.with? 'x264'
    args << "--enable-libfaac" if build.with? 'faac'
    args << "--enable-libmp3lame" if build.with? 'lame'
    args << "--enable-libxvid" if build.with? 'xvid'

    args << "--enable-libfreetype" if build.with? 'freetype'
    args << "--enable-libtheora" if build.with? 'theora'
    args << "--enable-libvorbis" if build.with? 'libvorbis'
    args << "--enable-libvpx" if build.with? 'libvpx'
    args << "--enable-librtmp" if build.with? 'rtmpdump'
    args << "--enable-libopencore-amrnb" << "--enable-libopencore-amrwb" if build.with? 'opencore-amr'
    args << "--enable-libvo-aacenc" if build.with? 'libvo-aacenc'
    args << "--enable-libass" if build.with? 'libass'
    args << "--enable-ffplay" if build.with? "ffplay"
    args << "--enable-libspeex" if build.with? 'speex'
    args << '--enable-libschroedinger' if build.with? 'schroedinger'
    args << "--enable-libfdk-aac" if build.with? 'fdk-aac'
    args << "--enable-openssl" if build.with? 'openssl'
    args << "--enable-libopus" if build.with? 'opus'
    args << "--enable-frei0r" if build.with? 'frei0r'
    args << "--enable-libcaca" if build.with? 'libcaca'
    args << "--enable-libquvi" if build.with? 'libquvi'
    args << "--enable-libvidstab" if build.with? 'libvidstab'
    args << "--enable-libx265" if build.with? 'x265'

    if build.with? 'openjpeg'
      args << '--enable-libopenjpeg'
      args << '--extra-cflags=' + %x[pkg-config --cflags libopenjpeg].chomp
    end

    # For 32-bit compilation under gcc 4.2, see:
    # http://trac.macports.org/ticket/20938#comment:22
    ENV.append_to_cflags "-mdynamic-no-pic" if Hardware.is_32_bit? && Hardware::CPU.intel? && ENV.compiler == :clang

    ENV["GIT_DIR"] = cached_download/".git" if build.head?

    system "./configure", *args

    if MacOS.prefer_64_bit?
      inreplace 'config.mak' do |s|
        shflags = s.get_make_var 'SHFLAGS'
        if shflags.gsub!(' -Wl,-read_only_relocs,suppress', '')
          s.change_make_var! 'SHFLAGS', shflags
        end
      end
    end

    system "make install"

    if build.with? "tools"
      system "make alltools"
      bin.install Dir['tools/*'].select {|f| File.executable? f}
    end
  end

end


text:
jQuery.fn.showLoading = function(options) {
		var $this = jQuery(this);
		var indicatorID;
		var settings = {
			'addClass': '',
			'beforeShow': '',
			'afterShow': '',
			'hPos': 'center',
			'vPos': 'center',
			'indicatorZIndex' : 5001,
			'overlayZIndex': 5000,
			'parent': '',
			'marginTop': 0,
			'marginLeft': 0,
			'message' : null,
			'overlayWidth': null,
			'overlayHeight': null
			};

		jQuery.extend(settings, options);

		if($this.length)	{
			var $loadingDiv = jQuery('

');
			var $overlayDiv = jQuery('

');

			//
			// Set up ID and classes
			//
			if (settings.indicatorID) {
				indicatorID = settings.indicatorID;
				}
			else {
				indicatorID = $this.attr('id');
				}

			$loadingDiv.attr('id', 'loading-indicator-' + indicatorID );
			$loadingDiv.addClass('loading-indicator');

			if (settings.addClass){
				$loadingDiv.addClass(settings.addClass);
				}
			if(settings.message)	{
				$loadingDiv.addClass('ui-widget ui-widget-content ui-corner-all stdPadding alignCenter').html($("
").addClass('ui-loading-message').text(settings.message));
				}

			$loadingDiv.prepend("

"); //add gfx before txt.

			//
			// Create the overlay
			//
			$overlayDiv.css({
				'display':'none'
				}).addClass('ui-widget-overlay');

			// Append to parent. add a position-relative for continued absolute position support.
			$this.append($overlayDiv);

			//
			// Set overlay classes
			//
			$overlayDiv.attr('id', 'loading-indicator-' + indicatorID + '-overlay');

			$overlayDiv.addClass('loading-indicator-overlay');

			if ( settings.addClass ){
				$overlayDiv.addClass(settings.addClass + '-overlay');
			}

			//
			// Set overlay position
			//

			var overlay_width;
			var overlay_height;

			var border_top_width = $this.css('border-top-width');
			var border_left_width = $this.css('border-left-width');

			//
			// IE will return values like 'medium' as the default border,
			// but we need a number
			//
			border_top_width = isNaN(parseInt(border_top_width)) ? 0 : border_top_width;
			border_left_width = isNaN(parseInt(border_left_width)) ? 0 : border_left_width;
			var overlay_left_pos = $this.offset().left + parseInt(border_left_width);
			var overlay_top_pos = $this.offset().top + parseInt(border_top_width);

			if ( settings.overlayWidth !== null ) {
				overlay_width = settings.overlayWidth;
			}
			else {
				overlay_width = parseInt($this.width()) + parseInt($this.css('padding-right')) + parseInt($this.css('padding-left'));
			}

			if ( settings.overlayHeight !== null ) {
				overlay_height = settings.overlayWidth;
			}
			else {
				overlay_height = parseInt($this.height()) + parseInt($this.css('padding-top')) + parseInt($this.css('padding-bottom'));
			}

	//static is default and doesn't do much. relative with no left/right, etc does about the same thing.
	//this allows for the absolute positioned overlay div to NOT have a fixed height/width and use left:0, right:0, etc and stay within the parent element.
	//This 'should' still work fine with non static elements.
			if($this.css('position') == 'static')	{$this.css('position','relative')}

			$overlayDiv.css({'position':'absolute','left':0,'right':0,'top':0,'bottom':0}); /* fill entire parent */
			$overlayDiv.css('z-index', settings.overlayZIndex);

			//
			// Set any custom overlay CSS
			//
				if ( settings.overlayCSS ) {
					$overlayDiv.css ( settings.overlayCSS );
				}

			//
			// We have to append the element to the body first
			// or .width() won't work in Webkit-based browsers (e.g. Chrome, Safari)
			//
			$loadingDiv.css('display', 'none');
			$this.append($loadingDiv);

			$loadingDiv.css('position', 'absolute');
			$loadingDiv.css('z-index', settings.indicatorZIndex);

			//
			// Set top margin
			//

			var indicatorLeft = overlay_left_pos;

			if ( settings.marginLeft ) {
				indicatorLeft += parseInt(settings.marginLeft);
				}

			//
			// set horizontal position
			//
//	app.u.dump(" -> settings:"); app.u.dump(settings);
//app.u.dump("$overlayDiv.outerWidth(): "+$overlayDiv.outerWidth());
//app.u.dump("$loadingDiv.outerWidth(): "+$loadingDiv.outerWidth());
//app.u.dump("indicatorLeft: "+indicatorLeft);
//app.u.dump("jt left: "+(parseInt(($overlayDiv.outerWidth() - $loadingDiv.outerWidth()) / 2)))

			if ( settings.hPos.toString().toLowerCase() == 'center' ) {
//				$loadingDiv.css('left', (indicatorLeft + (($overlayDiv.outerWidth() - parseInt($loadingDiv.outerWidth())) / 2)).toString()  + 'px');
				$loadingDiv.css('left', (parseInt(($overlayDiv.outerWidth() - $loadingDiv.outerWidth()) / 2)).toString()  + 'px');
				}
			else if ( settings.hPos.toString().toLowerCase() == 'left' ) {
				$loadingDiv.css('left',0);
				}
			else if ( settings.hPos.toString().toLowerCase() == 'right' ) {
				$loadingDiv.css('right',0);
				}
			else {
				$loadingDiv.css('left', 0);
				}

			//
			// set vertical position
			//
			if ( settings.vPos.toString().toLowerCase() == 'center' ) {
				$loadingDiv.css('top', ((($overlayDiv.outerHeight() - parseInt($loadingDiv.outerHeight())) / 2)).toString()  + 'px');
				}
			else if ( settings.vPos.toString().toLowerCase() == 'top' ) {
				$loadingDiv.css('top', 0);
				}
			else if ( settings.vPos.toString().toLowerCase() == 'bottom' ) {
				$loadingDiv.css('bottom', 0);
				}
			else {
				$loadingDiv.css('top',0);
				}

			//
			// Set any custom css for loading indicator
			//
				if ( settings.css ) {
					$loadingDiv.css ( settings.css );
				}

			//
			// Set up callback options
			//
			var callback_options =
				{
					'overlay': $overlayDiv,
					'indicator': $loadingDiv,
					'element': this
				};

			//
			// beforeShow callback
			//
			if ( typeof(settings.beforeShow) == 'function' ) {
				settings.beforeShow( callback_options );
			}

			//
			// Show the overlay
			//
			$overlayDiv.show();

			//
			// Show the loading indicator
			//
			$loadingDiv.show();

			//
			// afterShow callback
			//
			if ( typeof(settings.afterShow) == 'function' ) {
				settings.afterShow( callback_options );
			}
		}
		else	{} //$this was not defined.
		return this;
    	 };

	jQuery.fn.hideLoading = function(options) {
		var indicatorID;
		var settings = {};
		jQuery.extend(settings, options);

		if ( settings.indicatorID ) {
			indicatorID = settings.indicatorID;
			}
		else {
			indicatorID = $(this).attr('id');
			}
// ** 201318 -> better method for selector
		$(app.u.jqSelector('#','loading-indicator-'+indicatorID),$(this)).remove();
		$(app.u.jqSelector('#','loading-indicator-'+indicatorID+'-overlay'),$(this)).remove();
//		$(this).find('#loading-indicator-' + indicatorID ).remove();
//		$(this).find('#loading-indicator-' + indicatorID + '-overlay' ).remove();

		return this;
     	};


text: Admin bunitão


text:
using JetBrains.Annotations;
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace Vulnerator.Model.Entity
{
    [Table("UniqueFindings")]
    public class UniqueFinding : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        [NotMapped]
        public bool IsChecked { get; set; }

        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public long UniqueFinding_ID { get; set; }

        [StringLength(50)]
        public string InstanceIdentifier { get; set; }

        [StringLength(2147483647)]
        public string ToolGeneratedOutput { get; set; }

        [StringLength(2147483647)]
        public string Comments { get; set; }

        [StringLength(2147483647)]
        public string FindingDetails { get; set; }

        public DateTime FirstDiscovered { get; set; }

        public DateTime LastObserved { get; set; }

        [Required]
        [StringLength(5)]
        public string DeltaAnalysisIsRequired { get; set; }

        public long FindingType_ID { get; set; }

        public virtual FindingType FindingType { get; set; }

        public long FindingSourceFile_ID { get; set; }

        public virtual UniqueFindingSourceFile UniqueFindingSourceFile { get; set; }

        // [CanBeNull]
        // [ForeignKey("MitigationOrCondition")]
        // public long? MitigationOrCondition_ID { get; set; }

        // [CanBeNull]
        // public virtual MitigationOrCondition MitigationOrCondition { get; set; }

        [Required]
        [StringLength(25)]
        public string Status { get; set; }

        public long Vulnerability_ID { get; set; }

        public virtual Vulnerability Vulnerability { get; set; }

        public long? Hardware_ID { get; set; }

        public virtual Hardware Hardware { get; set; }

        public long? Software_ID { get; set; }

        public virtual Software Software { get; set; }

        [StringLength(25)]
        public string SeverityOverride { get; set; }

        [StringLength(2000)]
        public string SeverityOverrideJustification { get; set; }

        [StringLength(100)]
        public string TechnologyArea { get; set; }

        [StringLength(500)]
        public string WebDB_Site { get; set; }

        [StringLength(100)]
        public string WebDB_Instance { get; set; }

        [StringLength(25)]
        public string Classification { get; set; }

        [StringLength(5)]
        public string CVSS_EnvironmentalScore { get; set; }

        [StringLength(25)]
        public string CVSS_EnvironmentalVector { get; set; }

    }
}


text:
package io.apiman.test.integration.ui.support.selenide.pages.plans;

import io.apiman.test.integration.ui.support.selenide.PageLocation;
import io.apiman.test.integration.ui.support.selenide.components.CreateChildEntityForm;
import io.apiman.test.integration.ui.support.selenide.layouts.AbstractPage;
import io.apiman.test.integration.ui.support.selenide.pages.plans.detail.PlanDetailPage;

/**
 * @author ldimaggi
 */
@PageLocation("/api-manager/new-plan")
public class CreatePlanPage extends AbstractPage<CreatePlanPage> implements
    CreateChildEntityForm<CreatePlanPage> {

    /**
     * Click the create button
     * @return PlanDetailPage page object
     */
    public PlanDetailPage create() {
        return create(PlanDetailPage.class);
    }
}


text:
- fast, but not vectorial
- must receive **only one** value, not a vector
- if returns a value which can be assigned
- always leave a space after `if`

```r
    a <- if (one_logical_condition) value_when_TRUE else value_when_FALSE
```

- nested `if`s require curly brackets

```r
if (one_logical_condition) {
    # do something when condition is TRUE
} else {
    # do something else when condition is FALSE
}
```

### `ifelse` from base R

- vectorized version
- faster than `if` when dealing with a vector
    + https://stackoverflow.com/questions/34005423/is-if-faster-than-ifelse
- treat it as a function

### `dplyr::if_else`

- as `if_else` but can deal with NAs and validates data types and vector lengths

## Multi if statements

### Nested `if`s

- allow for different conditions

```r
if (one_logical_condition) {
    # do something when first condition is TRUE
} else if (second_logical_condition) {
    # do something else when second condition is FALSE (and first is FALSE)
} else {
    # do something when both conditions are FALSE
}
```

### `switch` from base R

- think of it as multi-case `if` based on only one
- one expression that evaluates to one number or one string
- good practice to have a catch-all case (first unnamed argument)

### `purrr::when`

- think of it as vectorized `if`, with multiple conditions
- uses formulas which must evaluate to a single value
- good practice to have a catch-all case

### `dplyr::case_when`

- think of it as multi-case `if_else`
- uses formulas which must evaluate to a vector(!)
- good practice to have a catch-all case

## Data Frames

### Row names

Avoid row names in data frames

- Many functions in tidyverse remove them
- Not compatible with database tables
- [other issues](http://www.perfectlyrandom.org/2015/06/16/never-trust-the-row-names-of-a-dataframe-in-R/)

## Functions

### Arguments

- use `match.arg()` to validate function arguments


text:
/*
 * slurm-mon
 */

var express = require('express.io'), app = express(), path = require('path')
app.http().io();
app.set('port', process.env.PORT || 3000);
app.use(express.static(path.join(__dirname, 'public')));

app.io.on('connection', function(socket){
  console.log('User ' + socket.id + ' connected');
  socket.on('disconnect', function(){
    console.log('User ' + socket.id + ' disconnected');
  });
});

//Setup the ready route, and emit talk event.
app.io.route('ready', function(req) {
    req.io.emit('talk', {
        message: 'io event from an io route on the server'
    })
})

app.get('/', function(req, res) {
	res.sendfile(__dirname + '/index.html');
});
app.listen(app.get('port'), function() {
	console.log('HTTP server listening on port ' + app.get('port'));
});


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">
    <parent>
        <artifactId>hello-java-parent</artifactId>
        <groupId>shuaicj.hello.java</groupId>
        <version>1.0.0</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>hello-actuator</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>


text:
'use strict';
module.exports = StyledSelect
const isEmpty = require('lodash.isempty')

StyledSelect.$inject = []
function StyledSelect() {
    return {
        restrict: 'A'
        ,link: function(scope, elm, attr){

            elm.wrap('

')
            elm.after('

')

            scope.$watch(attr.ngModel, function(v){
                var currentOption;
                if (isEmpty(v)) {
                    currentOption = elm[0].options[0].text
                } else {
                    currentOption = elm[0].options[elm[0].selectedIndex].text
                }
                elm.next().text(currentOption)
            })
        }
    }
};


text:
ActiveRecord::Schema.verbose = false
ActiveRecord::Base.time_zone_aware_attributes = true if ActiveRecord::Base.respond_to?(:time_zone_aware_attributes)
ActiveRecord::Base.default_timezone = :utc
#just a random zone, unlikely to be local, and not utc
Time.zone = 'Moscow' if Time.respond_to?(:zone)

module MigrationSetup
  def setup
    DbTypeMigration.up
    CreateStringIds.up
    CreateEntries.up
    CreateUsers.up
    CreateAutoIds.up
    CreateValidatesUniquenessOf.up

    @connection = ActiveRecord::Base.connection
  end

  def teardown
    DbTypeMigration.down
    CreateStringIds.down
    CreateEntries.down
    CreateUsers.down
    CreateAutoIds.down
    CreateValidatesUniquenessOf.down
    ActiveRecord::Base.clear_active_connections!
  end
end

module FixtureSetup
  include MigrationSetup
  def setup
    super
    @title = "First post!"
    @content = "Hello from JRuby on Rails!"
    @new_title = "First post updated title"
    @rating = 205.76
    @user = User.create :login=>"something"
    @entry = Entry.create :title => @title, :content => @content, :rating => @rating, :user=>@user
    DbType.create
  end
end

module SimpleTestMethods
  include FixtureSetup

  def test_entries_created
    assert ActiveRecord::Base.connection.tables.find{|t| t =~ /^entries$/i}, "entries not created"
  end

  def test_users_created
    assert ActiveRecord::Base.connection.tables.find{|t| t =~ /^users$/i}, "users not created"
  end

  def test_entries_empty
    Entry.delete_all
    assert_equal 0, Entry.count
  end

  def test_find_with_string_slug
    new_entry = Entry.create(:title => "Blah")
    entry = Entry.find(new_entry.to_param)
    assert_equal new_entry.id, entry.id
  end

  def test_insert_returns_id
    unless ActiveRecord::Base.connection.adapter_name =~ /oracle/i
      value = ActiveRecord::Base.connection.insert("INSERT INTO entries (title, content, rating) VALUES('insert_title', 'some content', 1)")
      assert !value.nil?
      entry = Entry.find_by_title('insert_title')
      assert_equal entry.id, value
    end
  end

  def test_create_new_entry
    Entry.delete_all

    post = Entry.new
    post.title = @title
    post.content = @content
    post.rating = @rating
    post.save

    assert_equal 1, Entry.count
  end

  def test_create_partial_new_entry
    new_entry = Entry.create(:title => "Blah")
    new_entry2 = Entry.create(:title => "Bloh")
  end

  def test_find_and_update_entry
    post = Entry.find(:first)
    assert_equal @title, post.title
    assert_equal @content, post.content
    assert_equal @rating, post.rating

    post.title = @new_title
    post.save

    post = Entry.find(:first)
    assert_equal @new_title, post.title
  end

  def test_destroy_entry
    prev_count = Entry.count
    post = Entry.find(:first)
    post.destroy

    assert_equal prev_count - 1, Entry.count
  end

  if Entry.respond_to?(:limit)
    def test_limit
      Entry.limit(10).to_a
    end

    def test_count_with_limit
      assert_equal Entry.count, Entry.limit(10).count
    end
  end

  if Time.respond_to?(:zone)
    def test_save_time_with_utc
      current_zone = Time.zone
      default_zone = ActiveRecord::Base.default_timezone
      ActiveRecord::Base.default_timezone = Time.zone = :utc
      now = Time.now
      my_time = Time.local now.year, now.month, now.day, now.hour, now.min, now.sec
      m = DbType.create! :sample_datetime => my_time
      m.reload
      assert_equal my_time, m.sample_datetime
    rescue
      Time.zone = current_zone
      ActiveRecord::Base.default_timezone = default_zone
    end

    def test_save_time
      t = Time.now
      #precision will only be expected to the second.
      time = Time.local(t.year, t.month, t.day, t.hour, t.min, t.sec)
      e = DbType.find(:first)
      e.sample_datetime = time
      e.save!
      e = DbType.find(:first)
      assert_equal time.in_time_zone, e.sample_datetime
    end

    def test_save_date_time
      t = Time.now
      #precision will only be expected to the second.
      time = Time.local(t.year, t.month, t.day, t.hour, t.min, t.sec)
      datetime = time.to_datetime
      e = DbType.find(:first)
      e.sample_datetime = datetime
      e.save!
      e = DbType.find(:first)
      assert_equal time, e.sample_datetime.localtime
    end

    def test_save_time_with_zone
      t = Time.now
      #precision will only be expected to the second.
      original_time = Time.local(t.year, t.month, t.day, t.hour, t.min, t.sec)
      time = original_time.in_time_zone
      e = DbType.find(:first)
      e.sample_datetime = time
      e.save!
      e = DbType.find(:first)
      assert_equal time, e.sample_datetime
    end
  end

  def test_save_float
    e = DbType.find(:first)
    e.sample_float = 12.0
    e.save!

    e = DbType.find(:first)
    assert_equal(12.0, e.sample_float)
  end

  def test_save_date
    date = Date.new(2007)
    e = DbType.find(:first)
    e.sample_date = date
    e.save!
    e = DbType.find(:first)
    if DbType.columns_hash["sample_date"].type == :datetime
      # Oracle doesn't distinguish btw date/datetime
      assert_equal date, e.sample_date.to_date
    else
      assert_equal date, e.sample_date
    end
  end

  def test_boolean
    # An unset boolean should default to nil
    e = DbType.find(:first)
    assert_equal(nil, e.sample_boolean)

    e.sample_boolean = true
    e.save!

    e = DbType.find(:first)
    assert_equal(true, e.sample_boolean)
  end

  def test_integer
    # An unset boolean should default to nil
    e = DbType.find(:first)
    assert_equal(nil, e.sample_integer)

    e.sample_integer = 10
    e.save!

    e = DbType.find(:first)
    assert_equal(10, e.sample_integer)
  end

  def test_text
    # An unset boolean should default to nil
    e = DbType.find(:first)

    # Oracle adapter initializes all CLOB fields with empty_clob() function,
    # so they all have a initial value of an empty string ''
    assert_equal(nil, e.sample_text) unless ActiveRecord::Base.connection.adapter_name =~ /oracle/i

    e.sample_text = "ooop"
    e.save!

    e = DbType.find(:first)
    assert_equal("ooop", e.sample_text)
  end

  def test_string
    e = DbType.find(:first)

    # An empty string is treated as a null value in Oracle: http://www.techonthenet.com/oracle/questions/empty_null.php
    assert_equal('', e.sample_string) unless ActiveRecord::Base.connection.adapter_name =~ /oracle/i
    e.sample_string = "ooop"
    e.save!

    e = DbType.find(:first)
    assert_equal("ooop", e.sample_string)
  end

  def test_save_binary
    #string is 60_000 bytes
    binary_string = "\000ABCDEFGHIJKLMNOPQRSTUVWXYZ'\001\003"*1#2_000
    e = DbType.find(:first)
    e.sample_binary = binary_string
    e.save!
    e = DbType.find(:first)
    assert_equal binary_string, e.sample_binary
  end

  def test_indexes
    # Only test indexes if we have implemented it for the particular adapter
    if @connection.respond_to?(:indexes)
      indexes = @connection.indexes(:entries)
      assert_equal(0, indexes.size)

      index_name = "entries_index"
      @connection.add_index(:entries, :updated_on, :name => index_name)

      indexes = @connection.indexes(:entries)
      assert_equal(1, indexes.size)
      assert_equal "entries", indexes.first.table.to_s
      assert_equal index_name, indexes.first.name
      assert !indexes.first.unique
      assert_equal ["updated_on"], indexes.first.columns
    end
  end

  def test_dumping_schema
    require 'active_record/schema_dumper'
    @connection.add_index :entries, :title
    StringIO.open do |io|
      ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, io)
      assert_match(/add_index "entries",/, io.string)
    end
    @connection.remove_index :entries, :title

  end

  def test_nil_values
    test = AutoId.create('value' => '')
    assert_nil AutoId.find(test.id).value
  end

  # These should make no difference, but might due to the wacky regexp SQL rewriting we do.
  def test_save_value_containing_sql
    e = DbType.first
    e.save

    e.sample_string = e.sample_text = "\n\nselect from nothing where id = 'foo'"
    e.save
  end

  def test_invalid
    e = Entry.new(:title => @title, :content => @content, :rating => ' ')
    assert e.valid?
  end

  def test_reconnect
    assert_equal 1, Entry.count
    @connection.reconnect!
    assert_equal 1, Entry.count
  end

  if jruby?
    def test_connection_valid
      assert_raises(ActiveRecord::JDBCError) do
        @connection.raw_connection.with_connection_retry_guard do |c|
          begin
            stmt = c.createStatement
            stmt.execute "bogus sql"
          ensure
            stmt.close rescue nil
          end
        end
      end
    end

    class Animal < ActiveRecord::Base; end

    # ENEBO: Is this really ar-jdbc-specific or a bug in our adapter?
    def test_fetching_columns_for_nonexistent_table_should_raise
      assert_raises(ActiveRecord::JDBCError) do
        Animal.columns
      end
    end
  end

  def test_disconnect
    assert_equal 1, Entry.count
    ActiveRecord::Base.clear_active_connections!
    ActiveRecord::Base.connection_pool.disconnect! if ActiveRecord::Base.respond_to?(:connection_pool)
    assert !ActiveRecord::Base.connected?
    assert_equal 1, Entry.count
    assert ActiveRecord::Base.connected?
  end

  def test_add_not_null_column_to_table
    AddNotNullColumnToTable.up
    AddNotNullColumnToTable.down
  end

  def test_add_null_column_with_default
    Entry.connection.add_column :entries, :color, :string, :null => false, :default => "blue"
    created_columns = Entry.connection.columns('entries')

    color = created_columns.detect { |c| c.name == 'color' }
    assert !color.null
  end

  def test_add_null_column_with_no_default
    # You must specify a default value with most databases
    if ActiveRecord::Base.connection.adapter_name =~ /mysql/i
      Entry.connection.add_column :entries, :color, :string, :null => false
      created_columns = Entry.connection.columns('entries')

      color = created_columns.detect { |c| c.name == 'color' }
      assert !color.null
    end
  end

  def test_add_null_column_with_nil_default
    # You must specify a default value with most databases
    if ActiveRecord::Base.connection.adapter_name =~ /mysql/i
      Entry.connection.add_column :entries, :color, :string, :null => false, :default => nil
      created_columns = Entry.connection.columns('entries')

      color = created_columns.detect { |c| c.name == 'color' }
      assert !color.null
    end
  end

  def test_validates_uniqueness_of_strings_case_sensitive
    name_lower = ValidatesUniquenessOfString.new(:cs_string => "name", :ci_string => '1')
    name_lower.save!

    name_upper = ValidatesUniquenessOfString.new(:cs_string => "NAME", :ci_string => '2')
    assert_nothing_raised do
      name_upper.save!
    end

    name_lower_collision = ValidatesUniquenessOfString.new(:cs_string => "name", :ci_string => '3')
    assert_raise ActiveRecord::RecordInvalid do
      name_lower_collision.save!
    end

    name_upper_collision = ValidatesUniquenessOfString.new(:cs_string => "NAME", :ci_string => '4')
    assert_raise ActiveRecord::RecordInvalid do
      name_upper_collision.save!
    end
  end

  def test_validates_uniqueness_of_strings_case_insensitive
    name_lower = ValidatesUniquenessOfString.new(:cs_string => '1', :ci_string => "name")
    name_lower.save!

    name_upper = ValidatesUniquenessOfString.new(:cs_string => '2', :ci_string => "NAME")
    assert_raise ActiveRecord::RecordInvalid do
      name_upper.save!
    end

    name_lower_collision = ValidatesUniquenessOfString.new(:cs_string => '3', :ci_string => "name")
    assert_raise ActiveRecord::RecordInvalid do
      name_lower_collision.save!
    end

    alternate_name_upper = ValidatesUniquenessOfString.new(:cs_string => '4', :ci_string => "ALTERNATE_NAME")
    assert_nothing_raised do
      alternate_name_upper.save!
    end

    alternate_name_upper_collision = ValidatesUniquenessOfString.new(:cs_string => '5', :ci_string => "ALTERNATE_NAME")
    assert_raise ActiveRecord::RecordInvalid do
      alternate_name_upper_collision.save!
    end

    alternate_name_lower = ValidatesUniquenessOfString.new(:cs_string => '6', :ci_string => "alternate_name")
    assert_raise ActiveRecord::RecordInvalid do
      alternate_name_lower.save!
    end
  end

  class ChangeEntriesTable < ActiveRecord::Migration
    def self.up
      change_table :entries do |t|
        t.string :author
      end if respond_to?(:change_table)
    end
    def self.down
      change_table :entries do |t|
        t.remove :author
      end if respond_to?(:change_table)
    end
  end
  def test_change_table
    ChangeEntriesTable.up
    ChangeEntriesTable.down
  end

  def test_string_id
    f = StringId.new
    f.id = "some_string"
    f.save
    f = StringId.first #reload is essential
    assert_equal "some_string", f.id
  end
end

module MultibyteTestMethods
  include MigrationSetup

  if defined?(JRUBY_VERSION)
    def setup
      super
      config = ActiveRecord::Base.connection.config
      @jdbc_driver = ActiveRecord::ConnectionAdapters::JdbcDriver.new(config[:driver])
      @java_con = @jdbc_driver.connection(config[:url], config[:username], config[:password])
      @java_con.setAutoCommit(true)
    end

    def teardown
      @java_con.close
      @jdbc_driver = nil
      super
    end

    def test_select_multibyte_string
      @java_con.createStatement().execute("insert into entries (id, title, content) values (1, 'テスト', '本文')")
      entry = Entry.find(:first)
      assert_equal "テスト", entry.title
      assert_equal "本文", entry.content
      assert_equal entry, Entry.find_by_title("テスト")
    end

    def test_update_multibyte_string
      Entry.create!(:title => "テスト", :content => "本文")
      rs = @java_con.createStatement().executeQuery("select title, content from entries")
      assert rs.next
      assert_equal "テスト", rs.getString(1)
      assert_equal "本文", rs.getString(2)
    end
  end

  def test_multibyte_aliasing
    str = "テスト"
    quoted_alias = Entry.connection.quote_column_name(str)
    sql = "SELECT title AS #{quoted_alias} from entries"
    records = Entry.connection.select_all(sql)
    records.each do |rec|
      rec.keys.each do |key|
        assert_equal str, key
      end
    end
  end

  def test_chinese_word
    chinese_word = '中文'
    new_entry = Entry.create(:title => chinese_word)
    new_entry.reload
    assert_equal chinese_word, new_entry.title
  end
end

module NonUTF8EncodingMethods
  def setup
    @connection = ActiveRecord::Base.remove_connection
    latin2_connection = @connection.dup
    latin2_connection[:encoding] = 'latin2'
    latin2_connection.delete(:url) # pre-gen url gets stashed; remove to re-gen
    ActiveRecord::Base.establish_connection latin2_connection
    CreateEntries.up
  end

  def teardown
    CreateEntries.down
    ActiveRecord::Base.establish_connection @connection
  end

  def test_nonutf8_encoding_in_entry
    prague_district = 'hradčany'
    new_entry = Entry.create :title => prague_district
    new_entry.reload
    assert_equal prague_district, new_entry.title
  end
end

module ActiveRecord3TestMethods
  def self.included(base)
    base.send :include, Tests if ActiveRecord::VERSION::MAJOR == 3
  end

  module Tests
    def test_where
      entries = Entry.where(:title => @entry.title)
      assert_equal @entry, entries.first
    end
  end
end


text:
This external user sync CloudBolt Plugin will update (creating when needed) group membership and permissions based on the user's AD security group membership.

This script is written for an older version of CloudBolt. It will not work on version 7.2
and above.

The script takes as action inputs the security group names, and creates 3 groups (Silver, Bronze, and Gold) to put the users into.

This Plugin can be useful for the case where you want some users in AD to have access to all groups in CB, but some users to only be a requester on certain groups.

Security groups should exist within AD for requesters that end in "-Gold", "-Bronze", and "-Silver", plus one group each for viewers, approvers, resource admins, and group admins.

See the [CloudBolt docs](http://docs.cloudbolt.io/) for more information on User Permission Synchronization with AD.


text:
/**
 * Created at 4:23:48 PM Jul 17, 2010
 */
package org.jbox2d.testbed.framework;

import java.awt.BorderLayout;
import java.awt.Component;

import javax.swing.JFrame;
import javax.swing.JScrollPane;

import org.jbox2d.testbed.framework.j2d.TestbedSidePanel;

/**
 * The testbed frame. Contains all stuff. Make sure you call {@link #setVisible(boolean)} and
 * {@link #setDefaultCloseOperation(int)}.
 *
 * @author Daniel Murphy
 */
@SuppressWarnings("serial")
public class TestbedFrame extends JFrame {

  private TestbedSidePanel side;
  private TestbedModel model;
  private TestbedController controller;

  public TestbedFrame(final TestbedModel argModel, final TestbedPanel argPanel) {
    super("SIMPLE GUI");
    setLayout(new BorderLayout());

    model = argModel;
    model.setDebugDraw(argPanel.getDebugDraw());
    controller = new TestbedController(model, argPanel);

    add((Component) argPanel, "Center");
    pack();

    controller.playTest(0);
    controller.start();
  }
}


text:
<?php
/**
 * User: zach
 * Date: 6/7/13
 * Time: 2:51 PM
 */

namespace Elasticsearch\Tests\Endpoints\Indices;

use Elasticsearch\Endpoints\Indices\Refresh;
use Mockery as m;

/**
 * Class RefreshTest
 * @package Elasticsearch\Tests\Endpoints\Indices
 * @author  Zachary Tong <zachary.tong@elasticsearch.com>
 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache2
 * @link    http://elasticsearch.org
 */
class RefreshTest extends \PHPUnit_Framework_TestCase
{
    public function tearDown() {
        m::close();
    }

    public function testValidRefreshWithNoIndex()
    {
        $mockTransport = m::mock('\Elasticsearch\Transport')
                         ->shouldReceive('performRequest')->once()
                         ->with(
                                 'POST',
                                 '/_refresh',
                                 array(),
                                 null
                             )
                         ->getMock();

        $action = new Refresh($mockTransport);
        $action->performRequest();

    }

    public function testValidRefreshWithIndex()
    {

        $mockTransport = m::mock('\Elasticsearch\Transport')
                         ->shouldReceive('performRequest')->once()
                         ->with(
                                 'POST',
                                 '/testIndex/_refresh',
                                 array(),
                                 null
                             )
                         ->getMock();

        $action = new Refresh($mockTransport);
        $action->setIndex('testIndex')
        ->performRequest();

    }

}


text:
import * as Preact from '../../../../src/preact';
import {VideoIframe} from '../video-iframe';
import {mount} from 'enzyme';

function dispatchMessage(window, opt_event) {
  const event = window.document.createEvent('Event');
  event.initEvent('message', /* bubbles */ true, /* cancelable */ true);
  window.dispatchEvent(Object.assign(event, opt_event));
}

describes.realWin('VideoIframe Preact component', {}, (env) => {
  let window;
  let document;

  beforeEach(() => {
    window = env.win;
    document = window.document;
  });

  it('calls `onIframeLoad` once loaded', async () => {
    const onIframeLoad = env.sandbox.spy();
    const onCanPlay = env.sandbox.spy();
    const makeMethodMessage = env.sandbox.spy();
    const videoIframe = mount(
      <VideoIframe
        src="about:blank"
        makeMethodMessage={makeMethodMessage}
        onIframeLoad={onIframeLoad}
        onCanPlay={onCanPlay}
      />,
      {attachTo: document.body}
    );

    await videoIframe.find('iframe').invoke('onCanPlay')();

    expect(onCanPlay).to.be.calledOnce;
    expect(onIframeLoad).to.be.calledOnce;
  });

  it('unmutes per lack of `muted` prop', async () => {
    const makeMethodMessage = env.sandbox.spy();
    const videoIframe = mount(
      <VideoIframe src="about:blank" makeMethodMessage={makeMethodMessage} />,
      {attachTo: document.body}
    );

    await videoIframe.find('iframe').invoke('onCanPlay')();

    expect(makeMethodMessage.withArgs('unmute')).to.have.been.calledOnce;
  });

  it('mutes per `muted` prop', async () => {
    const makeMethodMessage = env.sandbox.spy();
    const videoIframe = mount(
      <VideoIframe
        src="about:blank"
        makeMethodMessage={makeMethodMessage}
        muted
      />,
      {attachTo: document.body}
    );

    await videoIframe.find('iframe').invoke('onCanPlay')();

    expect(makeMethodMessage.withArgs('mute')).to.have.been.calledOnce;
  });

  it('hides controls per lack of `controls` prop', async () => {
    const makeMethodMessage = env.sandbox.spy();
    const videoIframe = mount(
      <VideoIframe src="about:blank" makeMethodMessage={makeMethodMessage} />,
      {attachTo: document.body}
    );

    await videoIframe.find('iframe').invoke('onCanPlay')();

    expect(makeMethodMessage.withArgs('hideControls')).to.have.been.calledOnce;
  });

  it('shows controls per `controls` prop', async () => {
    const makeMethodMessage = env.sandbox.spy();
    const videoIframe = mount(
      <VideoIframe
        src="about:blank"
        makeMethodMessage={makeMethodMessage}
        controls
      />,
      {attachTo: document.body}
    );

    await videoIframe.find('iframe').invoke('onCanPlay')();

    expect(makeMethodMessage.withArgs('showControls')).to.have.been.calledOnce;
  });

  it('passes messages to onMessage', async () => {
    const onMessage = env.sandbox.spy();
    const videoIframe = mount(
      <VideoIframe src="about:blank" onMessage={onMessage} controls />,
      {attachTo: document.body}
    );

    const iframe = videoIframe.getDOMNode();

    const data = {foo: 'bar'};
    dispatchMessage(window, {source: iframe.contentWindow, data});

    expect(
      onMessage.withArgs(
        env.sandbox.match({
          currentTarget: iframe,
          target: iframe,
          data,
        })
      )
    ).to.have.been.calledOnce;
  });

  it("ignores messages if source doesn't match iframe", async () => {
    const onMessage = env.sandbox.spy();
    mount(<VideoIframe src="about:blank" onMessage={onMessage} controls />, {
      attachTo: document.body,
    });
    dispatchMessage(window, {source: null, data: 'whatever'});
    expect(onMessage).to.not.have.been.called;
  });

  it('stops listening to messages on unmount', async () => {
    const onMessage = env.sandbox.spy();
    const videoIframe = mount(
      <VideoIframe src="about:blank" onMessage={onMessage} />,
      {attachTo: document.body}
    );
    const iframe = videoIframe.getDOMNode();
    videoIframe.unmount();
    dispatchMessage(window, {source: iframe.contentWindow, data: 'whatever'});
    expect(onMessage).to.not.have.been.called;
  });

  it('unlistens only when unmounted', async () => {
    const addEventListener = env.sandbox.stub(window, 'addEventListener');
    const removeEventListener = env.sandbox.stub(window, 'removeEventListener');

    const videoIframe = mount(
      <VideoIframe src="about:blank" onMessage={() => {}} />,
      {attachTo: document.body}
    );

    expect(addEventListener.withArgs('message')).to.have.been.calledOnce;
    expect(removeEventListener.withArgs('message')).to.not.have.been.called;

    videoIframe.setProps({
      onMessage: () => {
        // An unstable onMessage prop should not cause unlisten
      },
    });
    videoIframe.update();
    expect(removeEventListener.withArgs('message')).to.not.have.been.called;

    videoIframe.unmount();
    expect(removeEventListener.withArgs('message')).to.have.been.calledOnce;
  });

  describe('uses makeMethodMessage to posts imperative handle methods', () => {
    ['play', 'pause'].forEach((method) => {
      it(`with \`${method}\``, async () => {
        let videoIframeRef;

        const makeMethodMessage = (method) => ({makeMethodMessageFor: method});

        const makeMethodMessageSpy = env.sandbox.spy(makeMethodMessage);

        const videoIframe = mount(
          <VideoIframe
            ref={(ref) => (videoIframeRef = ref)}
            src="about:blank"
            makeMethodMessage={makeMethodMessageSpy}
          />,
          {attachTo: document.body}
        );

        const postMessage = env.sandbox.stub(
          videoIframe.getDOMNode().contentWindow,
          'postMessage'
        );

        videoIframeRef[method]();
        await videoIframe.find('iframe').invoke('onCanPlay')();

        expect(makeMethodMessageSpy.withArgs(method)).to.have.been.calledOnce;
        expect(
          postMessage.withArgs(
            env.sandbox.match(makeMethodMessage(method)),
            '*'
          )
        ).to.have.been.calledOnce;
      });
    });
  });
});


text:
import { Constants as StudentConstants } from '../actions/attendance';
import { ATTENDANCE_STATES as AttendanceStates } from './student';
import attendanceReducer from './attendance';

describe('attendance reducer', () => {
  let state;
  let action;
  let date;
  let attendance;

  beforeEach(() => {
    state = undefined;
    action = { original: { body: {} }, body: {} };
    action.original.date = new Date('2016-01-01');
    date = action.original.date;
    attendance = [
      { lms_student_id: '1', status: AttendanceStates.ABSENT, date },
      { lms_student_id: '2', status: AttendanceStates.ABSENT, date },
      { lms_student_id: '3', status: AttendanceStates.ABSENT, date },
      { lms_student_id: '4', status: AttendanceStates.ABSENT, date },
      { lms_student_id: '5', status: AttendanceStates.ABSENT, date },
      { lms_student_id: '6', status: AttendanceStates.ABSENT, date },
      { lms_student_id: '7', status: AttendanceStates.ABSENT, date },
      { lms_student_id: '8', status: AttendanceStates.ABSENT, date },
    ];
  });

  it('should return the initial state', () => {
    state = attendanceReducer(state, action);
    expect(state.attendances).toBeDefined();
  });

  it('should handle GET_STUDENT_ATTENDANCE_DONE', () => {
    action.type = StudentConstants.GET_STUDENT_ATTENDANCE_DONE;
    action.payload = attendance;
    state = attendanceReducer(state, action);
    expect(Object.keys(state.attendances[date]).length).toEqual(8);
    expect(state.attendances[date]['1']).toEqual(AttendanceStates.ABSENT);
    expect(state.attendances[date]['2']).toEqual(AttendanceStates.ABSENT);
    expect(state.attendances[date]['3']).toEqual(AttendanceStates.ABSENT);
    expect(state.attendances[date]['4']).toEqual(AttendanceStates.ABSENT);
    expect(state.attendances[date]['5']).toEqual(AttendanceStates.ABSENT);
    expect(state.attendances[date]['6']).toEqual(AttendanceStates.ABSENT);
    expect(state.attendances[date]['7']).toEqual(AttendanceStates.ABSENT);
    expect(state.attendances[date]['8']).toEqual(AttendanceStates.ABSENT);
  });

  it('should handle UPDATE_STATUS to mark present', () => {
    action.type = StudentConstants.GET_STUDENT_ATTENDANCE_DONE;
    action.payload = attendance;
    state = attendanceReducer(state, action);
    action.body = {
      date: new Date('2016-01-01'),
      students: [{ lms_student_id: '1' }],
      status: AttendanceStates.PRESENT,
    };
    action.type = StudentConstants.UPDATE_STATUS;
    state = attendanceReducer(state, action);
    expect(state.attendances[date]['1']).toEqual(AttendanceStates.PROCESSING);
    expect(state.attendances[date]['2']).toEqual(AttendanceStates.ABSENT);
    expect(state.attendances[date]['3']).toEqual(AttendanceStates.ABSENT);
    expect(state.attendances[date]['4']).toEqual(AttendanceStates.ABSENT);
    expect(state.attendances[date]['5']).toEqual(AttendanceStates.ABSENT);
    expect(state.attendances[date]['6']).toEqual(AttendanceStates.ABSENT);
    expect(state.attendances[date]['7']).toEqual(AttendanceStates.ABSENT);
    expect(state.attendances[date]['8']).toEqual(AttendanceStates.ABSENT);
  });

  it('should handle UPDATE_STATUS to remove attendance', () => {
    action.type = StudentConstants.GET_STUDENT_ATTENDANCE_DONE;
    action.payload = attendance;
    state = attendanceReducer(state, action);
    action.body = {
      date: new Date('2016-01-01'),
      students: [{ lms_student_id: '1' }],
      status: '',
    };
    action.type = StudentConstants.UPDATE_STATUS;
    state = attendanceReducer(state, action);
    expect(state.attendances[date]['1']).toEqual('');
    expect(state.attendances[date]['2']).toEqual(AttendanceStates.ABSENT);
    expect(state.attendances[date]['3']).toEqual(AttendanceStates.ABSENT);
    expect(state.attendances[date]['4']).toEqual(AttendanceStates.ABSENT);
    expect(state.attendances[date]['5']).toEqual(AttendanceStates.ABSENT);
    expect(state.attendances[date]['6']).toEqual(AttendanceStates.ABSENT);
    expect(state.attendances[date]['7']).toEqual(AttendanceStates.ABSENT);
    expect(state.attendances[date]['8']).toEqual(AttendanceStates.ABSENT);
  });

  it('should handle UPDATE_STATUS_DONE with error', () => {
    action.error = 'IMANERROR';
    action.type = StudentConstants.UPDATE_STATUS_DONE;
    state = attendanceReducer(state, action);
    expect(state.attendances).toBeDefined();
    expect(action.error).toEqual('IMANERROR');
  });

  it('should handle UPDATE_STATUS_DONE without error', () => {
    action.type = StudentConstants.GET_STUDENT_ATTENDANCE_DONE;
    action.payload = attendance;
    state = attendanceReducer(state, action);
    action.original = {
      body: {
        date: new Date('2016-01-01'),
      },
    };
    action.payload = [{ lms_student_id: '1', status: 'PRESENT' }];
    action.type = StudentConstants.UPDATE_STATUS_DONE;
    state = attendanceReducer(state, action);
    expect(state.attendances[date]['1']).toEqual('PRESENT');
    expect(state.attendances[date]['2']).toEqual(AttendanceStates.ABSENT);
    expect(state.attendances[date]['3']).toEqual(AttendanceStates.ABSENT);
    expect(state.attendances[date]['4']).toEqual(AttendanceStates.ABSENT);
    expect(state.attendances[date]['5']).toEqual(AttendanceStates.ABSENT);
    expect(state.attendances[date]['6']).toEqual(AttendanceStates.ABSENT);
    expect(state.attendances[date]['7']).toEqual(AttendanceStates.ABSENT);
    expect(state.attendances[date]['8']).toEqual(AttendanceStates.ABSENT);
  });
});