text:
package org.wso2.carbon.identity.application.common.model.test;

import org.testng.annotations.Test;
import org.wso2.carbon.identity.application.common.model.Property;
import org.wso2.carbon.identity.application.common.model.ProvisioningConnectorConfig;

import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotEquals;

/**
 * Testing the ProvisioningConnectorConfig class
 */
public class ProvisioningConnectorConfigTest {

    @Test
    public void shouldGenerateDifferentHashCodesForDifferentNames() {
        ProvisioningConnectorConfig config1 = new ProvisioningConnectorConfig();
        config1.setName("Name1");
        config1.setProvisioningProperties(new Property[0]);

        ProvisioningConnectorConfig config2 = new ProvisioningConnectorConfig();
        config2.setName("Name2");
        config2.setProvisioningProperties(new Property[0]);

        assertNotEquals(config1.hashCode(), config2.hashCode());
    }

    @Test
    public void shouldReturnFalseByEqualsForDifferentNames() {
        ProvisioningConnectorConfig config1 = new ProvisioningConnectorConfig();
        config1.setName("Name1");
        config1.setProvisioningProperties(new Property[0]);

        ProvisioningConnectorConfig config2 = new ProvisioningConnectorConfig();
        config2.setName("Name2");
        config2.setProvisioningProperties(new Property[0]);

        assertFalse(config1.equals(config2));
    }
}


text:
import React from "react";
import { Field } from "formik";
import { ReadOnlyField } from "../ClusterConfiguration/ReadOnlyField";

export function ClusterSSHPort(props: { disabled: boolean; readOnlyValue?: any; }) {
  if (props.readOnlyValue !== undefined) {
    return (
      <ReadOnlyField label="SSH Port" value={props.readOnlyValue} />
    );
  }

  return (

      SSH Port

        <Field
          className="input"
          type="number"
          name="sshPort"
          disabled={props.disabled}
          minimum={0}
          maximum={65535}
          data-testid="sshPort" />

        SSH port for all machines that are used for load generation.

  );
}

redpajama_set_name: RedPajamaGithub


text:
// -*- mode: C++ -*-
//
// Copyright (c) 2007, 2008, 2010, 2011 The University of Utah
// All rights reserved.
//
// This file is part of `csmith', a random generator of C programs.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//   * Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistributions in binary form must reproduce the above copyright
//     notice, this list of conditions and the following disclaimer in the
//     documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#ifndef EXPRESSION_VARIABLE_H
#define EXPRESSION_VARIABLE_H

///////////////////////////////////////////////////////////////////////////////

#include <ostream>
#include <vector>
#include "Expression.h"
using namespace std;

class CGContext;
class Variable;

/*
 *
 */
class ExpressionVariable : public Expression
{
public:
	// Factory method.
	static ExpressionVariable *make_random(CGContext &cg_context, const Type* type, const CVQualifiers* qfer=0, bool as_param=false, bool as_return=false);

	explicit ExpressionVariable(const Variable &v);

	ExpressionVariable(const Variable &v, const Type* t);

	virtual ~ExpressionVariable(void);

	virtual Expression* clone() const;

	virtual CVQualifiers get_qualifiers(void) const;

	virtual void get_eval_to_subexps(vector<const Expression*>& subs) const {subs.push_back(this);}

	int get_indirect_level(void) const;

	const Variable* get_var(void) const {return &var;};
	//
	virtual std::vector<const ExpressionVariable*> get_dereferenced_ptrs(void) const;
	virtual void get_referenced_ptrs(std::vector<const Variable*>& ptrs) const;

	virtual unsigned int get_complexity(void) const { return 1;}

	virtual bool visit_facts(vector<const Fact*>& inputs, CGContext& cg_context) const;

	virtual const Type &get_type(void) const;

	virtual bool compatible(const Expression *exp) const;

	virtual bool compatible(const Variable *v) const;

	virtual bool use_var(const Variable* v) const { return v == &var;}

	virtual void Output(std::ostream &) const;

	virtual void OutputInterval(std::ostream &) const;

private:
	explicit ExpressionVariable(const ExpressionVariable &expr);

	const Variable &var;

	const Type* type;

	// unimplementable
	ExpressionVariable &operator=(const ExpressionVariable &ev);
};

///////////////////////////////////////////////////////////////////////////////

#endif // EXPRESSION_VARIABLE_H

// Local Variables:
// c-basic-offset: 4
// tab-width: 4
// End:

// End of file.


text:
package de.codesourcery.jasm16.ide;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.List;

import de.codesourcery.jasm16.compiler.ICompilationUnit;
import de.codesourcery.jasm16.compiler.io.IResource;
import de.codesourcery.jasm16.ide.exceptions.ProjectAlreadyExistsException;
import de.codesourcery.jasm16.ide.exceptions.ProjectNotFoundException;
import de.codesourcery.jasm16.utils.IOrdered;

/**
 * A workspace.
 *
 *
A workspace instance manages a set of {@link IAssemblyProject} instances and
 * allows {@link IWorkspaceListener}s to receive change notifications for these projects.

 * @author tobias.gierke@code-sourcery.de
 */
public interface IWorkspace extends IResourceListener
{
	public File getBaseDirectory(); // ok

	// project management
    public boolean doesProjectExist(String name); // ok

    public IAssemblyProject getProjectByName(String name); // ok

    public IAssemblyProject importProject(File baseDirectory) throws IOException,ProjectAlreadyExistsException;

    public IAssemblyProject createNewProject(String name) throws IOException,ProjectAlreadyExistsException;

    public IAssemblyProject getProjectForResource(IResource resource) throws ProjectNotFoundException;

    public List<IAssemblyProject> getAllProjects(); // ok

    public void openProject(IAssemblyProject project);

    public void closeProject(IAssemblyProject project);

    public void deleteProject(IAssemblyProject project,boolean deletePhysically) throws IOException;

    public void refreshProjects(Collection<IAssemblyProject> projects) throws IOException;

    public IBuildManager getBuildManager();

    /**
     * Delete a file.
     *
     *
If the file is actually the project's base directory, this method
     * behaves like invoking {@link #deleteProject(IAssemblyProject, boolean)}
     * with deletePhysically set to true.

     *
     * @param project
     * @param fileToDelete
     * @throws IOException
     */
    public void deleteFile(IAssemblyProject project,File fileToDelete) throws IOException;

    public void saveProjectConfiguration(IAssemblyProject project) throws IOException;

    // workspace listeners
    /**
     * Adds a workspace listener.
     *
     *
Listeners may implement {@link IOrdered} to control invocation order.

     *
     * @param listener
     */
    public void addWorkspaceListener(IWorkspaceListener listener);

    public void removeWorkspaceListener(IWorkspaceListener listener);

    /**
     * Adds a resource listener.
     *
     *
Listeners may implement {@link IOrdered} to control invocation order.

     *
     * @param listener
     */
    public void addResourceListener(IResourceListener listener);

    public void removeResourceListener(IResourceListener listener);

    // state management
    public void open() throws IOException; // ok

    public void close() throws IOException; // ok

    public void reloadWorkspace() throws IOException; // ok

	public void buildStarted(IAssemblyProject assemblyProject);

	public void compilationFinished(IAssemblyProject project, ICompilationUnit unit);

	public void buildFinished(IAssemblyProject assemblyProject, boolean buildSuccessful);
}


text:
from .. import abc
from .. import util
from . import util as builtin_util

frozen_machinery, source_machinery = util.import_importlib('importlib.machinery')

import sys
import types
import unittest

class LoaderTests(abc.LoaderTests):

    """Test load_module() for built-in modules."""

    def setUp(self):
        self.verification = {'__name__': 'errno', '__package__': '',
                             '__loader__': self.machinery.BuiltinImporter}

    def verify(self, module):
        """Verify that the module matches against what it should have."""
        self.assertIsInstance(module, types.ModuleType)
        for attr, value in self.verification.items():
            self.assertEqual(getattr(module, attr), value)
        self.assertIn(module.__name__, sys.modules)

    def load_module(self, name):
        return self.machinery.BuiltinImporter.load_module(name)

    def test_module(self):
        # Common case.
        with util.uncache(builtin_util.NAME):
            module = self.load_module(builtin_util.NAME)
            self.verify(module)

    # Built-in modules cannot be a package.
    test_package = test_lacking_parent = None

    # No way to force an import failure.
    test_state_after_failure = None

    def test_module_reuse(self):
        # Test that the same module is used in a reload.
        with util.uncache(builtin_util.NAME):
            module1 = self.load_module(builtin_util.NAME)
            module2 = self.load_module(builtin_util.NAME)
            self.assertIs(module1, module2)

    def test_unloadable(self):
        name = 'dssdsdfff'
        assert name not in sys.builtin_module_names
        with self.assertRaises(ImportError) as cm:
            self.load_module(name)
        self.assertEqual(cm.exception.name, name)

    def test_already_imported(self):
        # Using the name of a module already imported but not a built-in should
        # still fail.
        module_name = 'builtin_reload_test'
        assert module_name not in sys.builtin_module_names
        with util.uncache(module_name):
            module = types.ModuleType(module_name)
            sys.modules[module_name] = module
        with self.assertRaises(ImportError) as cm:
            self.load_module(module_name)
        self.assertEqual(cm.exception.name, module_name)

Frozen_LoaderTests, Source_LoaderTests = util.test_both(LoaderTests,
        machinery=[frozen_machinery, source_machinery])

class InspectLoaderTests:

    """Tests for InspectLoader methods for BuiltinImporter."""

    def test_get_code(self):
        # There is no code object.
        result = self.machinery.BuiltinImporter.get_code(builtin_util.NAME)
        self.assertIsNone(result)

    def test_get_source(self):
        # There is no source.
        result = self.machinery.BuiltinImporter.get_source(builtin_util.NAME)
        self.assertIsNone(result)

    def test_is_package(self):
        # Cannot be a package.
        result = self.machinery.BuiltinImporter.is_package(builtin_util.NAME)
        self.assertTrue(not result)

    def test_not_builtin(self):
        # Modules not built-in should raise ImportError.
        for meth_name in ('get_code', 'get_source', 'is_package'):
            method = getattr(self.machinery.BuiltinImporter, meth_name)
        with self.assertRaises(ImportError) as cm:
            method(builtin_util.BAD_NAME)
        self.assertRaises(builtin_util.BAD_NAME)

Frozen_InspectLoaderTests, Source_InspectLoaderTests = util.test_both(
        InspectLoaderTests,
        machinery=[frozen_machinery, source_machinery])

if __name__ == '__main__':
    unittest.main()


text:
using System.Collections.Generic;
using Xunit;
using static System.Linq.Tests.SkipTakeData;

namespace System.Linq.Tests
{
    public class SkipLastTests : EnumerableBasedTests
    {
        [Theory, MemberData(nameof(QueryableData), MemberType = typeof(SkipTakeData))]
        public void SkipLast(IQueryable<int> source, int count)
        {
            IQueryable<int> expected = source.Reverse().Skip(count).Reverse();
            IQueryable<int> actual = source.SkipLast(count);

            Assert.Equal(expected, actual);
        }

        [Fact]
        public void SkipLastThrowsOnNull()
        {
            AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<DateTime>)null).SkipLast(3));
        }
    }
}


text:
<!doctype html>

    <meta charset="utf-8">
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1, minimal-ui">
    <title>Jon | Front-End Developer</title>

    <link href='http://fonts.googleapis.com/css?family=Quicksand' rel='stylesheet' type='text/css'>

    <link rel="stylesheet" href="../bower_components/components-font-awesome/css/font-awesome.css"/>

    <link rel="stylesheet" href="../bower_components/bootstrap/dist/css/bootstrap.css" />

    <link rel="stylesheet" href="styles/main.css">

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

          </button>
          JM

Work

Contact

About

HELLO

My name is:

Jon

Recent Work

MTG-Central

This is an app that lets you create a Haves and Wants list of your Magic The Gathering Cards, so that you can trade with people threw facebook

Beer Me

A random Beer generator which you can tweet out

Todo-MVC

This is a todo list writen in jQuery

Title

Info about the app HERE

About Me

I am a Front-End developer making the web a better place one line of code at a time!

      <form action="">

          <input type="text" required>

          Name

          <input type="text" required>

          Email

      </form>


text:
<?php

namespace Addons\Donation\Controller;

use Addons\Donation\Controller\BaseController;

class DonationController extends BaseController{
    var $model;
    function _initialize() {
        $this->model = $this->getModel ( 'Donation' );
        parent::_initialize ();
    }
    public function lists() {
        $this->assign('normal_tips','首页展示链接:'.addons_url('Donation://Wap/index',array('publicid'=>$public_id)).'   $public_id)).'">复制链接');
        $this->assign('normal_tips1','入驻链接:'.addons_url('Donation://Wap/add',array('publicid'=>$public_id)).'   $public_id)).'">复制链接');
        $cateArr=M('DonationCategory')->getFields('id,name');
        $list_data = $this->_get_model_list ( $this->model );
        foreach ($list_data['list_data']as&$data){
            $data ['cateid'] = $cateArr [$data ['cateid']];
        }
        $this->assign ( $list_data );
        $this->display ();
    }
}


text:
.class Lcom/android/systemui/statusbar/phone/KeyguardAffordanceHelper$2;
.super Ljava/lang/Object;
.source "KeyguardAffordanceHelper.java"

# interfaces
.implements Ljava/lang/Runnable;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/systemui/statusbar/phone/KeyguardAffordanceHelper;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/systemui/statusbar/phone/KeyguardAffordanceHelper;

# direct methods
.method constructor <init>(Lcom/android/systemui/statusbar/phone/KeyguardAffordanceHelper;)V
    .locals 0

    iput-object p1, p0, Lcom/android/systemui/statusbar/phone/KeyguardAffordanceHelper$2;->this$0:Lcom/android/systemui/statusbar/phone/KeyguardAffordanceHelper;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public run()V
    .locals 1

    iget-object v0, p0, Lcom/android/systemui/statusbar/phone/KeyguardAffordanceHelper$2;->this$0:Lcom/android/systemui/statusbar/phone/KeyguardAffordanceHelper;

    iget-object v0, v0, Lcom/android/systemui/statusbar/phone/KeyguardAffordanceHelper;->mCallback:Lcom/android/systemui/statusbar/phone/KeyguardAffordanceHelper$Callback;

    invoke-interface {v0}, Lcom/android/systemui/statusbar/phone/KeyguardAffordanceHelper$Callback;->onAnimationToSideEnded()V

    return-void
.end method


text:
<?php

declare(strict_types=1);

namespace WoohooLabs\Yin\JsonApi\Exception;

use WoohooLabs\Yin\JsonApi\Schema\Error\Error;
use WoohooLabs\Yin\JsonApi\Schema\Error\ErrorSource;

class ClientGeneratedIdNotSupported extends AbstractJsonApiException
{
    /**
     * @var string
     */
    protected $clientGeneratedId;

    public function __construct(string $clientGeneratedId)
    {
        parent::__construct(
            "Client generated ID " . ($clientGeneratedId !== "" ? "'$clientGeneratedId' " : "") .
            "is not supported!",
            403
        );
        $this->clientGeneratedId = $clientGeneratedId;
    }

    protected function getErrors(): array
    {
        return [
            Error::create()
                ->setStatus("403")
                ->setCode("CLIENT_GENERATED_ID_NOT_SUPPORTED")
                ->setTitle("Client generated ID is not supported")
                ->setDetail($this->getMessage())
                ->setSource(ErrorSource::fromPointer("/data/id")),
        ];
    }

    public function getClientGeneratedId(): string
    {
        return $this->clientGeneratedId;
    }
}


text:
<!DOCTYPE html>

		<title>three.js webgl - materials - cube reflection [Escher]</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

Three.js cube mapping demo

Original artwork by M. C. Escher

Texture by Mark VandeWettering


text:
module FractalFlame.Palette.Types.Palette where

import FractalFlame.Types.Base
import FractalFlame.Color.Types.Color

type Palette = Coord -> Color -- should return Color with alpha channel 1.0


text:
<?php

namespace Tea;

class Parentheses extends BaseExpression
{
	const KIND = 'parentheses';

	public $expression;

	public function __construct(BaseExpression $expression)
	{
		$this->expression = $expression;
	}
}


text:
namespace TestCases.HSSF.Record
{
    using System;
    using NPOI.HSSF.Record;
    using NPOI.SS.Formula;
    using System.IO;
    using System.Collections;

    using NUnit.Framework;
    using NPOI.SS.Formula.PTG;
    using NPOI.HSSF.UserModel;
    using NPOI.SS.UserModel;

    /**
     * Tests the serialization and deserialization of the FormulaRecord
     * class works correctly.
     *
     * @author Andrew C. Oliver
     */
    [TestFixture]
    public class TestFormulaRecord
    {
        [Test]
        public void TestCreateFormulaRecord()
        {
            FormulaRecord record = new FormulaRecord();
            record.Column=((short)0);
            //record.SetRow((short)1);
            record.Row=(1);
            record.XFIndex=((short)4);

            Assert.AreEqual(record.Column, (short)0);
            //Assert.AreEqual(record.Row,(short)1);
            Assert.AreEqual((short)record.Row, (short)1);
            Assert.AreEqual(record.XFIndex, (short)4);
        }

        /**
         * Make sure a NAN value is1 preserved
         * This formula record is1 a representation of =1/0 at row 0, column 0
         */
        [Test]
        public void TestCheckNanPreserve()
        {
            byte[] formulaByte = {
            0, 0, 0, 0,
            0x0F, 0x00,

			// 8 bytes cached number is a 'special value' in this case
			0x02, // special cached value type 'error'
			0x00,
            FormulaError.DIV0.Code,
            0x00,
            0x00,
            0x00,
            (byte)0xFF,
            (byte)0xFF,

            0x00,
            0x00,
            0x00,
            0x00,

            (byte)0xE0, //18
			(byte)0xFC,
			// Ptgs
			0x07, 0x00, // encoded length
			0x1E, 0x01, 0x00, // IntPtg(1)
			0x1E, 0x00, 0x00, // IntPtg(0)
			0x06, // DividePtg

		};

            FormulaRecord record = new FormulaRecord(TestcaseRecordInputStream.Create(FormulaRecord.sid,  formulaByte));
            Assert.AreEqual(0, record.Row, "Row");
            Assert.AreEqual(0, record.Column, "Column");
            Assert.AreEqual(record.CachedResultType,NPOI.SS.UserModel.CellType.Error);

            byte[] output = record.Serialize();
            Assert.AreEqual(33, output.Length, "Output size"); //includes sid+recordlength

            for (int i = 5; i < 13; i++)
            {
                Assert.AreEqual(formulaByte[i], output[i + 4], "FormulaByte NaN doesn't match");
            }
        }

        /**
         * Tests to see if the shared formula cells properly reSerialize the expPtg
         *
         */
        [Test]
        public void TestExpFormula()
        {
            byte[] formulaByte = new byte[27];

            formulaByte[4] = (byte)0x0F;
            formulaByte[14] = (byte)0x08;
            formulaByte[18] = (byte)0xE0;
            formulaByte[19] = (byte)0xFD;
            formulaByte[20] = (byte)0x05;
            formulaByte[22] = (byte)0x01;
            FormulaRecord record = new FormulaRecord(TestcaseRecordInputStream.Create(FormulaRecord.sid, formulaByte));
            Assert.AreEqual(0, record.Row, "Row");
            Assert.AreEqual(0, record.Column, "Column");
            byte[] output = record.Serialize();
            Assert.AreEqual(31, output.Length, "Output size"); //includes sid+recordlength
            Assert.AreEqual(1, output[26], "OffSet 22");
        }
        [Test]
        public void TestWithConcat()
        {
            // =CHOOSE(2,A2,A3,A4)
            byte[] data = {
				6, 0, 68, 0,
				1, 0, 1, 0, 15, 0, 0, 0, 0, 0, 0, 0, 57,
				64, 0, 0, 12, 0, 12, unchecked((byte)-4), 46, 0,
				30, 2, 0,	// Int - 2
				25, 4, 3, 0, // Attr
					8, 0, 17, 0, 26, 0, // jumpTable
					35, 0, // chooseOffSet
				36, 1, 0, 0, unchecked((byte)-64), // Ref - A2
				25, 8, 21, 0, // Attr
				36, 2, 0, 0, unchecked((byte)-64), // Ref - A3
				25,	8, 12, 0, // Attr
				36, 3, 0, 0, unchecked((byte)-64), // Ref - A4
				25, 8, 3, 0,  // Attr
				66, 4, 100, 0 // CHOOSE
		    };
            RecordInputStream inp = new RecordInputStream(new MemoryStream(data));
            inp.NextRecord();

            FormulaRecord fr = new FormulaRecord(inp);

            Ptg[] ptgs = fr.ParsedExpression;
            Assert.AreEqual(9, ptgs.Length);
            Assert.AreEqual(typeof(IntPtg), ptgs[0].GetType());
            Assert.AreEqual(typeof(AttrPtg), ptgs[1].GetType());
            Assert.AreEqual(typeof(RefPtg), ptgs[2].GetType());
            Assert.AreEqual(typeof(AttrPtg), ptgs[3].GetType());
            Assert.AreEqual(typeof(RefPtg), ptgs[4].GetType());
            Assert.AreEqual(typeof(AttrPtg), ptgs[5].GetType());
            Assert.AreEqual(typeof(RefPtg), ptgs[6].GetType());
            Assert.AreEqual(typeof(AttrPtg), ptgs[7].GetType());
            Assert.AreEqual(typeof(FuncVarPtg), ptgs[8].GetType());

            FuncVarPtg choose = (FuncVarPtg)ptgs[8];
            Assert.AreEqual("CHOOSE", choose.Name);
        }
        [Test]
        public void TestReSerialize()
        {
            FormulaRecord formulaRecord = new FormulaRecord();
            formulaRecord.Row = (/*setter*/1);
            formulaRecord.Column = (/*setter*/(short)1);
            formulaRecord.ParsedExpression = (/*setter*/new Ptg[] { new RefPtg("B$5"), });
            formulaRecord.Value = (/*setter*/3.3);
            byte[] ser = formulaRecord.Serialize();
            Assert.AreEqual(31, ser.Length);

            RecordInputStream in1 = TestcaseRecordInputStream.Create(ser);
            FormulaRecord fr2 = new FormulaRecord(in1);
            Assert.AreEqual(3.3, fr2.Value, 0.0);
            Ptg[] ptgs = fr2.ParsedExpression;
            Assert.AreEqual(1, ptgs.Length);
            RefPtg rp = (RefPtg)ptgs[0];
            Assert.AreEqual("B$5", rp.ToFormulaString());
        }

        /**
         * Bug noticed while fixing 46479.  Operands of conditional operator ( ? : ) were swapped
         * inside {@link FormulaRecord}
         */
        [Test]
        public void TestCachedValue_bug46479()
        {
            FormulaRecord fr0 = new FormulaRecord();
            FormulaRecord fr1 = new FormulaRecord();
            // Test some other cached value types
            fr0.Value = (/*setter*/3.5);
            Assert.AreEqual(3.5, fr0.Value, 0.0);
            fr0.SetCachedResultErrorCode (FormulaError.REF.Code);
            Assert.AreEqual(FormulaError.REF.Code, fr0.CachedErrorValue);

            fr0.SetCachedResultBoolean(false);
            fr1.SetCachedResultBoolean(true);
            if (fr0.CachedBooleanValue == true && fr1.CachedBooleanValue == false)
            {
                throw new AssertionException("Identified bug 46479c");
            }
            Assert.AreEqual(false, fr0.CachedBooleanValue);
            Assert.AreEqual(true, fr1.CachedBooleanValue);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using Assimp.Unmanaged;

namespace Assimp
{
    /// <summary>
    /// Represents a completely imported model or scene. Everything that was imported from the given file can be
    /// accessed from here. Once the scene is loaded from unmanaged memory, it resides solely in managed memory
    /// and Assimp's read only copy is released.
    /// </summary>
    public sealed class Scene : IMarshalable<Scene, AiScene>
    {
        private SceneFlags m_flags;
        private Node m_rootNode;
        private List<Mesh> m_meshes;
        private List<Light> m_lights;
        private List<Camera> m_cameras;
        private List<EmbeddedTexture> m_textures;
        private List<Animation> m_animations;
        private List<Material> m_materials;

        /// <summary>
        /// Gets or sets the state of the imported scene. By default no flags are set, but
        /// issues can arise if the flag is set to incomplete.
        /// </summary>
        public SceneFlags SceneFlags
        {
            get
            {
                return m_flags;
            }
            set
            {
                m_flags = value;
            }
        }

        /// <summary>
        /// Gets or sets the root node of the scene graph. There will always be at least the root node
        /// if the import was successful and no special flags have been set. Presence of further nodes
        /// depends on the format and content of the imported file.
        /// </summary>
        public Node RootNode
        {
            get
            {
                return m_rootNode;
            }
            set
            {
                m_rootNode = value;
            }
        }

        /// <summary>
        /// Gets if the scene contains meshes. Unless if no special scene flags are set
        /// this should always be true.
        /// </summary>
        public bool HasMeshes
        {
            get
            {
                return m_meshes.Count > 0;
            }
        }

        /// <summary>
        /// Gets the number of meshes in the scene.
        /// </summary>
        public int MeshCount
        {
            get
            {
                return m_meshes.Count;
            }
        }

        /// <summary>
        /// Gets the meshes contained in the scene, if any.
        /// </summary>
        public List<Mesh> Meshes
        {
            get
            {
                return m_meshes;
            }
        }

        /// <summary>
        /// Gets if the scene contains any lights.
        /// </summary>
        public bool HasLights
        {
            get
            {
                return m_lights.Count > 0;
            }
        }

        /// <summary>
        /// Gets the number of lights in the scene.
        /// </summary>
        public int LightCount
        {
            get
            {
                return m_lights.Count;
            }
        }

        /// <summary>
        /// Gets the lights in the scene, if any.
        /// </summary>
        public List<Light> Lights
        {
            get
            {
                return m_lights;
            }
        }

        /// <summary>
        /// Gets if the scene contains any cameras.
        /// </summary>
        public bool HasCameras
        {
            get
            {
                return m_cameras.Count > 0;
            }
        }

        /// <summary>
        /// Gets the number of cameras in the scene.
        /// </summary>
        public int CameraCount
        {
            get
            {
                return m_cameras.Count;
            }
        }
        /// <summary>
        /// Gets the cameras in the scene, if any.
        /// </summary>
        public List<Camera> Cameras
        {
            get
            {
                return m_cameras;
            }
        }

        /// <summary>
        /// Gets if the scene contains embedded textures.
        /// </summary>
        public bool HasTextures
        {
            get
            {
                return m_textures.Count > 0;
            }
        }

        /// <summary>
        /// Gets the number of embedded textures in the scene.
        /// </summary>
        public int TextureCount
        {
            get
            {
                return m_textures.Count;
            }
        }

        /// <summary>
        /// Gets the embedded textures in the scene, if any.
        /// </summary>
        public List<EmbeddedTexture> Textures
        {
            get
            {
                return m_textures;
            }
        }

        /// <summary>
        /// Gets if the scene contains any animations.
        /// </summary>
        public bool HasAnimations
        {
            get
            {
                return m_animations.Count > 0;
            }
        }

        /// <summary>
        /// Gets the number of animations in the scene.
        /// </summary>
        public int AnimationCount
        {
            get
            {
                return m_animations.Count;
            }
        }

        /// <summary>
        /// Gets the animations in the scene, if any.
        /// </summary>
        public List<Animation> Animations
        {
            get
            {
                return m_animations;
            }
        }

        /// <summary>
        /// Gets if the scene contains any materials. There should always be at least the
        /// default Assimp material if no materials were loaded.
        /// </summary>
        public bool HasMaterials
        {
            get
            {
                return m_materials.Count > 0;
            }
        }

        /// <summary>
        /// Gets the number of materials in the scene. There should always be at least the
        /// default Assimp material if no materials were loaded.
        /// </summary>
        public int MaterialCount
        {
            get
            {
                return m_materials.Count;
            }
        }

        /// <summary>
        /// Gets the materials in the scene.
        /// </summary>
        public List<Material> Materials
        {
            get
            {
                return m_materials;
            }
        }

        /// <summary>
        /// Constructs a new instance of the <see cref="Scene"/> class.
        /// </summary>
        public Scene()
        {
            m_flags = SceneFlags.None;
            m_rootNode = null;
            m_meshes = new List<Mesh>();
            m_lights = new List<Light>();
            m_cameras = new List<Camera>();
            m_textures = new List<EmbeddedTexture>();
            m_animations = new List<Animation>();
            m_materials = new List<Material>();
        }

        /// <summary>
        /// Clears the scene of all components.
        /// </summary>
        public void Clear()
        {
            m_rootNode = null;
            m_meshes.Clear();
            m_lights.Clear();
            m_cameras.Clear();
            m_textures.Clear();
            m_animations.Clear();
            m_materials.Clear();
        }

        /// <summary>
        /// Marshals a managed scene to unmanaged memory. The unmanaged memory must be freed with a call to
        /// <see cref="FreeUnmanagedScene"/>, the memory is owned by AssimpNet and cannot be freed by the native library.
        /// </summary>
        /// <param name="scene">Scene data</param>
        /// <returns>Unmanaged scene or NULL if the scene is null.</returns>
        public static IntPtr ToUnmanagedScene(Scene scene)
        {
            if(scene == null)
                return IntPtr.Zero;

            return MemoryHelper.ToNativePointer<Scene, AiScene>(scene);
        }

        /// <summary>
        /// Marshals an unmanaged scene to managed memory. This does not free the unmanaged memory.
        /// </summary>
        /// <param name="scenePtr">The unmanaged scene data</param>
        /// <returns>The managed scene, or null if the pointer is NULL</returns>
        public static Scene FromUnmanagedScene(IntPtr scenePtr)
        {
            if(scenePtr == IntPtr.Zero)
                return null;

            return MemoryHelper.FromNativePointer<Scene, AiScene>(scenePtr);
        }

        /// <summary>
        /// Frees unmanaged memory allocated -ONLY- in <see cref="ToUnmanagedScene"/>. To free an unmanaged scene allocated by the unmanaged Assimp library,
        /// call the appropiate <see cref="AssimpLibrary.ReleaseImport"/> function.
        /// </summary>
        /// <param name="scenePtr">Pointer to unmanaged scene data.</param>
        public static void FreeUnmanagedScene(IntPtr scenePtr)
        {
            if(scenePtr == IntPtr.Zero)
                return;

            FreeNative(scenePtr, true);
        }

        #region IMarshalable Implementation

        /// <summary>
        /// Gets if the native value type is blittable (that is, does not require marshaling by the runtime, e.g. has MarshalAs attributes).
        /// </summary>
        bool IMarshalable<Scene, AiScene>.IsNativeBlittable
        {
            get { return true; }
        }

        /// <summary>
        /// Writes the managed data to the native value.
        /// </summary>
        /// <param name="thisPtr">Optional pointer to the memory that will hold the native value.</param>
        /// <param name="nativeValue">Output native value</param>
        void IMarshalable<Scene, AiScene>.ToNative(IntPtr thisPtr, out AiScene nativeValue)
        {
            nativeValue.Flags = m_flags;
            nativeValue.Materials = IntPtr.Zero;
            nativeValue.RootNode = IntPtr.Zero;
            nativeValue.Meshes = IntPtr.Zero;
            nativeValue.Lights = IntPtr.Zero;
            nativeValue.Cameras = IntPtr.Zero;
            nativeValue.Textures = IntPtr.Zero;
            nativeValue.Animations = IntPtr.Zero;
            nativeValue.PrivateData = IntPtr.Zero;

            nativeValue.NumMaterials = (uint) MaterialCount;
            nativeValue.NumMeshes = (uint) MeshCount;
            nativeValue.NumLights = (uint) LightCount;
            nativeValue.NumCameras = (uint) CameraCount;
            nativeValue.NumTextures = (uint) TextureCount;
            nativeValue.NumAnimations = (uint) AnimationCount;

            //Write materials
            if(nativeValue.NumMaterials > 0)
                nativeValue.Materials = MemoryHelper.ToNativeArray<Material, AiMaterial>(m_materials.ToArray(), true);

            //Write scenegraph
            if(m_rootNode != null)
                nativeValue.RootNode = MemoryHelper.ToNativePointer<Node, AiNode>(m_rootNode);

            //Write meshes
            if(nativeValue.NumMeshes > 0)
                nativeValue.Meshes = MemoryHelper.ToNativeArray<Mesh, AiMesh>(m_meshes.ToArray(), true);

            //Write lights
            if(nativeValue.NumLights > 0)
                nativeValue.Lights = MemoryHelper.ToNativeArray<Light, AiLight>(m_lights.ToArray(), true);

            //Write cameras
            if(nativeValue.NumCameras > 0)
                nativeValue.Cameras = MemoryHelper.ToNativeArray<Camera, AiCamera>(m_cameras.ToArray(), true);

            //Write textures
            if(nativeValue.NumTextures > 0)
                nativeValue.Textures = MemoryHelper.ToNativeArray<EmbeddedTexture, AiTexture>(m_textures.ToArray(), true);

            //Write animations
            if(nativeValue.NumAnimations > 0)
                nativeValue.Animations = MemoryHelper.ToNativeArray<Animation, AiAnimation>(m_animations.ToArray(), true);
        }

        /// <summary>
        /// Reads the unmanaged data from the native value.
        /// </summary>
        /// <param name="nativeValue">Input native value</param>
        void IMarshalable<Scene, AiScene>.FromNative(ref AiScene nativeValue)
        {
            Clear();

            m_flags = nativeValue.Flags;

            //Read materials
            if(nativeValue.NumMaterials > 0 && nativeValue.Materials != IntPtr.Zero)
                m_materials.AddRange(MemoryHelper.FromNativeArray<Material, AiMaterial>(nativeValue.Materials, (int) nativeValue.NumMaterials, true));

            //Read scenegraph
            if(nativeValue.RootNode != IntPtr.Zero)
                m_rootNode = MemoryHelper.FromNativePointer<Node, AiNode>(nativeValue.RootNode);

            //Read meshes
            if(nativeValue.NumMeshes > 0 && nativeValue.Meshes != IntPtr.Zero)
                m_meshes.AddRange(MemoryHelper.FromNativeArray<Mesh, AiMesh>(nativeValue.Meshes, (int) nativeValue.NumMeshes, true));

            //Read lights
            if(nativeValue.NumLights > 0 && nativeValue.Lights != IntPtr.Zero)
                m_lights.AddRange(MemoryHelper.FromNativeArray<Light, AiLight>(nativeValue.Lights, (int) nativeValue.NumLights, true));

            //Read cameras
            if(nativeValue.NumCameras > 0 && nativeValue.Cameras != IntPtr.Zero)
                m_cameras.AddRange(MemoryHelper.FromNativeArray<Camera, AiCamera>(nativeValue.Cameras, (int) nativeValue.NumCameras, true));

            //Read textures
            if(nativeValue.NumTextures > 0 && nativeValue.Textures != IntPtr.Zero)
                m_textures.AddRange(MemoryHelper.FromNativeArray<EmbeddedTexture, AiTexture>(nativeValue.Textures, (int) nativeValue.NumTextures, true));

            //Read animations
            if(nativeValue.NumAnimations > 0 && nativeValue.Animations != IntPtr.Zero)
                m_animations.AddRange(MemoryHelper.FromNativeArray<Animation, AiAnimation>(nativeValue.Animations, (int) nativeValue.NumAnimations, true));
        }

        /// <summary>
        /// Frees unmanaged memory created by <see cref="IMarshalable{Scene, AiScene}.ToNative"/>.
        /// </summary>
        /// <param name="nativeValue">Native value to free</param>
        /// <param name="freeNative">True if the unmanaged memory should be freed, false otherwise.</param>
        public static void FreeNative(IntPtr nativeValue, bool freeNative)
        {
            if(nativeValue == IntPtr.Zero)
                return;

            AiScene aiScene = MemoryHelper.Read<AiScene>(nativeValue);

            if(aiScene.NumMaterials > 0 && aiScene.Materials != IntPtr.Zero)
                MemoryHelper.FreeNativeArray<AiMaterial>(aiScene.Materials, (int) aiScene.NumMaterials, Material.FreeNative, true);

            if(aiScene.RootNode != IntPtr.Zero)
                Node.FreeNative(aiScene.RootNode, true);

            if(aiScene.NumMeshes > 0 && aiScene.Meshes != IntPtr.Zero)
                MemoryHelper.FreeNativeArray<AiMesh>(aiScene.Meshes, (int) aiScene.NumMeshes, Mesh.FreeNative, true);

            if(aiScene.NumLights > 0 && aiScene.Lights != IntPtr.Zero)
                MemoryHelper.FreeNativeArray<AiLight>(aiScene.Lights, (int) aiScene.NumLights, Light.FreeNative, true);

            if(aiScene.NumCameras > 0 && aiScene.Cameras != IntPtr.Zero)
                MemoryHelper.FreeNativeArray<AiCamera>(aiScene.Cameras, (int) aiScene.NumCameras, Camera.FreeNative, true);

            if(aiScene.NumTextures > 0 && aiScene.Textures != IntPtr.Zero)
                MemoryHelper.FreeNativeArray<AiTexture>(aiScene.Textures, (int) aiScene.NumTextures, EmbeddedTexture.FreeNative, true);

            if(aiScene.NumAnimations > 0 && aiScene.Animations != IntPtr.Zero)
                MemoryHelper.FreeNativeArray<AiAnimation>(aiScene.Animations, (int) aiScene.NumAnimations, Animation.FreeNative, true);

            if(freeNative)
                MemoryHelper.FreeMemory(nativeValue);
        }

        #endregion
    }
}


text:
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';

export default class extends Route {
  @service('device/layout') device;

  redirect() {
    if (!this.device.isMobile) {
      this.transitionTo('docs.overview');
    }
  }
}


text:
require 'test_helper'
ActiveValidators.activate(:nino)

describe "NINO validations" do
  describe "for UK" do
    describe "for invalid" do
      it "rejects empty nino" do
        subject = build_nino_record({:nino => ''})
        subject.valid?.must_equal false
      end

      it "rejects nino, which has invalid first letter" do
        invalid_first_letter = %w[d f i q u v]
        invalid_first_letter.each do |letter|
          invalid_nino = letter + 'B123456C'
          subject = build_nino_record({:nino => invalid_nino})
          subject.valid?.must_equal false
        end
      end

      it "rejects nino, which has invalid second letter" do
        invalid_second_letter = %w[d f i q u v o]
        invalid_second_letter.each do |letter|
          invalid_nino = 'a' + letter + '123456C'
          subject = build_nino_record({:nino => invalid_nino})
          subject.valid?.must_equal false
        end
      end

      it "rejects too long nino" do
        subject = build_nino_record({:nino => 'AB123456C100200'})
        subject.valid?.must_equal false
      end

      it "rejects nino with invalid prefix" do
        subject = build_nino_record({:nino => '#$123456C'})
        subject.valid?.must_equal false
      end

      it "rejects nino with invalid chars in number section" do
        subject = build_nino_record({:nino => 'AB@2%4#6C'})
        subject.valid?.must_equal false
      end

      it "rejects wrong suffixes" do
        invalid_suffix = %w[E F G H] # and etc
        invalid_suffix.each do |suffix|
          invalid_nino = 'AB123456' + suffix
          subject = build_nino_record({:nino => invalid_nino})
          subject.valid?.must_equal false
        end
      end

      it "rejects non allocated prefixes" do
        non_allocated_prefixes = %w[bg, gb, nk, kn, tn, nt, zz]
        non_allocated_prefixes.each do |suffix|
          invalid_nino = suffix + '123456C'
          subject = build_nino_record({:nino => invalid_nino})
          subject.valid?.must_equal false
        end
      end

      it "rejects administrative numbers" do
        administrative_numbers = %w[oo, cr, fy, mw, nc, pp, py, pz]
        administrative_numbers.each do |suffix|
          invalid_nino = suffix + '123456C'
          subject = build_nino_record({:nino => invalid_nino})
          subject.valid?.must_equal false
        end
      end

      it "rejects temporary numbers" do
        subject = build_nino_record({:nino => '63T12345'})
        subject.valid?.must_equal false
      end
    end

    describe "for valid" do
      it "acepts correct nino" do
        subject = build_nino_record({:nino => 'AB123456C'})
        subject.valid?.must_equal true
      end

      it "acepts nino, divided by spaces" do
        subject = build_nino_record({:nino => 'AB 12 34 56 C'})
        subject.valid?.must_equal true
      end

      it "acepts downcase nino" do
        subject = build_nino_record({:nino => 'ab 12 34 56 c'})
        subject.valid?.must_equal true
      end

      it "acepts correct suffixes" do
        valid_suffix = %w[A B C D]
        valid_suffix.each do |suffix|
          valid_nino = 'AB123456' + suffix
          subject = build_nino_record({:nino => valid_nino})
          subject.valid?.must_equal true
        end
      end
    end
  end

  def build_nino_record(attrs = {})
    TestRecord.reset_callbacks(:validate)
    TestRecord.validates :nino, :nino => true
    TestRecord.new attrs
  end
end


text:
using namespace seqan;

// ============================================================================
// Enums, Tags, Classes, Typedefs.
// ============================================================================

// ----------------------------------------------------------------------------
// Class WeightedMatch
// ----------------------------------------------------------------------------

// Represents a read match to a contig with an error.
//
// WeightedMatch(c, p, d) represents a match of a read at position p in contig c with distance d.

class WeightedMatch
{
public:
    size_t contigId;
    bool isForward;
    size_t pos;
    int distance;
    // Optional begin position, used in wit builder to smooth matches.
    // Is not written out or used in the less than operator.
    size_t beginPos;

    WeightedMatch() {}

    WeightedMatch(size_t _contigId, bool _isForward, size_t _pos, int _distance, size_t _beginPos) :
        contigId(_contigId), isForward(_isForward), pos(_pos), distance(_distance), beginPos(_beginPos)
    {}

    // Order lexicographically by (contigId, pos, -distance).
    bool operator<(WeightedMatch const & other) const
    {
        if (contigId < other.contigId) return true;

        if (contigId == other.contigId && isForward > other.isForward) return true;

        if (contigId == other.contigId && isForward == other.isForward &&
            pos < other.pos) return true;

        if (contigId == other.contigId && isForward == other.isForward &&
            pos == other.pos && distance > other.distance) return true;

        return false;
    }

    bool operator==(WeightedMatch const & other) const
    {
        if (contigId != other.contigId) return false;

        if (isForward != other.isForward) return false;

        if (pos != other.pos) return false;

        if (distance != other.distance) return false;

        if (beginPos != other.beginPos) return false;

        return true;
    }

};

typedef String<WeightedMatch> TWeightedMatches;

// ----------------------------------------------------------------------------
// Helper Class WeightedMatchBeginPosNeqOrContigIdNeq
// ----------------------------------------------------------------------------

struct WeightedMatchBeginPosNeqOrContigIdNeq :
    std::binary_function<WeightedMatch, WeightedMatch, bool>
{
    bool operator()(WeightedMatch const & arg1, WeightedMatch const & arg2)
    {
        return arg1.beginPos != arg2.beginPos || arg1.contigId != arg2.contigId || arg1.isForward != arg2.isForward;
    }

};

// ============================================================================
// Metafunctions
// ============================================================================

// ============================================================================
// Functions
// ============================================================================

// ----------------------------------------------------------------------------
// Function operator<<()                                        [WeightedMatch]
// ----------------------------------------------------------------------------

// Stream output for WeightedMatch objects, for debugging.
template <typename TStream>
TStream & operator<<(TStream & out, WeightedMatch const & m)
{
    out << "(" << m.contigId << ", " << (m.isForward ? "F, " : "R, ")
    << m.pos << ", " << m.distance << ", " << m.beginPos << ")";
    return out;
}

// ----------------------------------------------------------------------------
// Function fillGaps()
// ----------------------------------------------------------------------------

// Fills gaps in the given error curve.  If there are two adjacent entries in the string that have the same start
// position but not adjacent end positions then we add an entry for each end position in between.

// errorCurve must be sorted by (contigId, endPosition).

void fillGaps(String<WeightedMatch> & errorCurve)
{
    typedef Iterator<String<WeightedMatch>, Standard>::Type TIterator;

    // Guard against not enough items in string.
    if (length(errorCurve) < 2)
        return;

    // The insertion buffer.
    String<WeightedMatch> buffer;
    for (TIterator it = begin(errorCurve, Standard()); (it + 1) != end(errorCurve, Standard()); ++it)
    {
        if (value(it).contigId != value(it + 1).contigId)
            continue;  // Skip if contigId is not equal.
        if (value(it).isForward != value(it + 1).isForward)
            continue;  // Skip if direction is not equal.
        if (value(it).pos + 1 == value(it + 1).pos)
            continue;  // Skip if the end positions are contiguous.
        if (value(it).beginPos != value(it + 1).beginPos)
            continue;  // Skip if the begin positions are not equal.
        // If the code reaches this position then we have a gap and fill it.
        int gapScore = _min(value(it).distance, value(it + 1).distance);
        for (size_t i = value(it).pos + 1; i < value(it + 1).pos; ++i)
            appendValue(buffer, WeightedMatch(value(it).contigId, value(it).isForward, i, gapScore, value(it).beginPos));
    }

    // Append buffer and sort inserted items to the right position.
    append(errorCurve, buffer);
    std::sort(begin(errorCurve), end(errorCurve));
}

// ----------------------------------------------------------------------------
// Function smoothErrorCurve()
// ----------------------------------------------------------------------------

// Smoothing of error curves, for the application of match equivalence.
//
// The algorithm works as follows.  For each contiguous interval of tuples with the same start position, do the
// following.  From the left to the right and from the right to the left to the first absolute maximum in each
// direction, make the curve monotonously increasing.  Between the rightmost and the leftmost maximum, set the values to
// the maximal value.

void smoothErrorCurve(String<WeightedMatch> & errorCurve)
{
    if (length(errorCurve) == 0u)
        return;

    // TODO(holtgrew): Standard should be the standard iterator, yes?
    typedef Iterator<String<WeightedMatch>, Standard>::Type TIterator;
    typedef Position<String<WeightedMatch> >::Type TPosition;

    // For all intervals with the same beginPosition.
    WeightedMatchBeginPosNeqOrContigIdNeq pred;
    TIterator itBegin = begin(errorCurve, Standard());
    TIterator itEnd = std::adjacent_find(itBegin, end(errorCurve, Standard()), pred);
    do
    {
//         std::cerr << "begin is " << (itBegin - begin(errorCurve, Standard())) << std::endl;
//         std::cerr << "end is " << (itEnd - begin(errorCurve, Standard())) << std::endl;
        if (itEnd != end(errorCurve, Standard()))
            itEnd += 1;
        SEQAN_ASSERT_NEQ(itBegin, itEnd);

        if (itBegin != itEnd)
        {
            // Find maximal score value.
            int maxScore = value(itBegin).distance;
            for (TIterator it = itBegin; it != itEnd; ++it)
                maxScore = _max(maxScore, value(it).distance);

//             std::cerr << "--- BEFORE itBegin..itEnd" << std::endl;
//             for (TIterator it = itBegin; it != itEnd; ++it) {
//                 std::cerr << value(it) << std::endl;
//             }
//             std::cerr << "---" << std::endl;

//             std::cerr << "maxScore is " << maxScore << std::endl;

            // Search leftmost and rightmost maximum.
            TIterator itLeftmost = 0, itRightmost = 0;
            for (TIterator it = itBegin; it != itEnd; ++it)
            {
                if (value(it).distance != maxScore)
                    continue;
                if (itLeftmost == 0)
                    itLeftmost = it;
                itRightmost = it;
            }

//             std::cerr << "leftmost is " << (itLeftmost - begin(errorCurve, Standard())) << " (" << value(itLeftmost).distance << ")" << std::endl;
//             std::cerr << "rightmost is " << (itRightmost - begin(errorCurve, Standard())) << " (" << value(itRightmost).distance << ")" << std::endl;

            // Level between leftmost and rightmost maxima.
            for (TIterator it = itLeftmost; it != itRightmost + 1; ++it)
                value(it).distance = maxScore;

            // Make monotonously decreasing from begin to leftmost.
            int currentMax = value(itBegin).distance;
            for (TIterator it = itBegin; it != itLeftmost; ++it)
            {
                currentMax = _max(currentMax, value(it).distance);
//                 std::cerr << "value(" << (it - begin(errorCurve, Standard())) << ") = " << currentMax << std::endl;
                value(it).distance = currentMax;
            }

            // Make monotonously decreasing from end to rightmost.
            TPosition offset = itBegin - begin(errorCurve, Standard());
            TPosition rightmostPos = offset + itRightmost - itBegin;
            TPosition intervalLength = itEnd - itBegin;
            typedef ModifiedString<Infix<String<WeightedMatch> >::Type, ModReverse> TModifiedString;
            TModifiedString rRightInterval(infix(errorCurve, rightmostPos, offset + intervalLength));
            typedef Iterator<TModifiedString, Standard>::Type TModifiedStringIterator;
            currentMax = front(rRightInterval).distance;
            for (TModifiedStringIterator it = begin(rRightInterval, Standard()); it != end(rRightInterval, Standard()); ++it)
            {
                currentMax = _max(currentMax, value(it).distance);
//                 std::cerr << "value(" << value(it) << ") = " << currentMax << std::endl;
                value(host(it)).distance = currentMax;
            }
        }

//         std::cerr << "--- AFTER itBegin..itEnd" << std::endl;
//         for (TIterator it = itBegin; it != itEnd; ++it) {
//             std::cerr << value(it) << std::endl;
//         }
//         std::cerr << "---" << std::endl;

        // Proceed.
        itBegin = itEnd;
        itEnd = std::adjacent_find(itBegin, end(errorCurve, Standard()), pred);
    }
    while (itBegin != end(errorCurve));
}

#endif  // SEQAN_APPS_RABEMA_CURVE_SMOOTHING_H_


text:
{#-
  This file was automatically generated - do not edit
-#}

  {% include "overrides/partials/parallax/hero.html" %}
  {% include "overrides/partials/parallax/expect.html" %}
  {% include "overrides/partials/parallax/spotlight.html" %}
  {% include "overrides/partials/parallax/trust.html" %}
  {% include "overrides/partials/parallax/users.html" %}
  {% include "overrides/partials/parallax/connect.html" %}

    {% include "partials/footer.html" %}


text:
PIXI.HypnoticRipplesFilter = function(width, height, texture)
{
	PIXI.AbstractFilter.call( this );

	this.passes = [this];

	var d = new Date();

	var dates = [
		d.getFullYear(), // the year (four digits)
		d.getMonth(),	   // the month (from 0-11)
		d.getDate(),     // the day of the month (from 1-31)
		d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds()
	];

	this.uniforms = {
		iResolution: { type: '3f', value: { x: width, y: height, z: 0 }},
		iGlobalTime: { type: '1f', value: 1 },
		iDate: { type: '4fv', value: dates },
		iChannel0: { type: 'sampler2D', value: texture }
	};

	//	Shader by Cha (https://www.shadertoy.com/view/ldX3zr)
	this.fragmentSrc = [
		"precision mediump float;",
		"uniform vec3      iResolution;",
		"uniform float     iGlobalTime;",
		"uniform float     iChannelTime[4];",
		"uniform vec4      iMouse;",
		"uniform vec4      iDate;",
		"uniform vec3      iChannelResolution[4];",
		"uniform sampler2D iChannel0;",
		"// add any extra uniforms here",

		"vec2 center = vec2(0.5,0.5);",
		"float speed = 0.035;",
		"float invAr = iResolution.y / iResolution.x;",

		"void main(void)",
		"{",
			"vec2 uv = gl_FragCoord.xy / iResolution.xy;",

			"vec3 col = vec4(uv,0.5+0.5*sin(iGlobalTime),1.0).xyz;",

			"vec3 texcol;",

			"float x = (center.x-uv.x);",
			"float y = (center.y-uv.y) *invAr;",

			"//float r = -sqrt(x*x + y*y); //uncoment this line to symmetric ripples",
			"float r = -(x*x + y*y);",
			"float z = 1.0 + 0.5*sin((r+iGlobalTime*speed)/0.013);",

			"texcol.x = z;",
			"texcol.y = z;",
			"texcol.z = z;",

			"gl_FragColor = vec4(col*texcol,1.0);",
			"//gl_FragColor = vec4(texcol,1.0);",
		"}"];

}

PIXI.HypnoticRipplesFilter.prototype = Object.create( PIXI.AbstractFilter.prototype );
PIXI.HypnoticRipplesFilter.prototype.constructor = PIXI.HypnoticRipplesFilter;

Object.defineProperty(PIXI.HypnoticRipplesFilter.prototype, 'iGlobalTime', {
    get: function() {
        return this.uniforms.iGlobalTime.value;
    },
    set: function(value) {
    	this.uniforms.iGlobalTime.value = value;
    }
});

var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render });

function preload() {

    // game.load.image('texture', 'wip/64x64.png');
    game.load.image('texture', 'wip/tex16.png');

}

var filter;
var sprite;

function create() {

	sprite = game.add.sprite(0, 0, 'texture');
	sprite.width = 800;
	sprite.height = 600;

	filter = new PIXI.HypnoticRipplesFilter(sprite.width, sprite.height, sprite.texture);

	sprite.filters = [filter];

}

function update() {

	filter.iGlobalTime = game.time.totalElapsedSeconds();

}

function render() {
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>JSDoc: Source: jquery-imageSlider.navigation.js</title>

    <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
    <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">

Source: jquery-imageSlider.navigation.js

(function(window, $){
  'use strict';
  /**
  * imageSliderNavigation Plugin - image slide sub module for navigation.
  *
  * @class imageSliderNavigation
  * @membarOf jQuery.fn
  */
  $.fn.imageSliderNavigation = function navigation(){
    var len = $(this).find('.slide').find('li').length;
    var $a = '';
    for(var i = 1; i <= len ;i++){
      $a = $a + '<a href="#page=' + i +'" data-index="' + i + '" class="'+ (i === 1 ? 'active' : '') +'"><span class="bland">' + i + '</span></a>';
    }
    $(this).find('.slide-nav').html($a);
  };

})(window, jQuery);

Index

Classes

imageSlider

imageSliderNavigation

imageSliderRotate

jQuery

fn

    Documentation generated by JSDoc 3.2.2 on Tue Oct 21 2014 13:38:07 GMT+0900 (KST)


text:
class SettingsValult;
class LocaleObject;

class SettingsController : public QObject
{
    Q_OBJECT
public:
    explicit SettingsController(QObject *parent = 0);
    ~SettingsController();

    Q_INVOKABLE QList<QObject *> getInputDeviceList();
    Q_INVOKABLE void setInputDevice(const int);
    Q_INVOKABLE int getInputDevice() const;

    Q_INVOKABLE QList<QObject *> getOutputDeviceList();
    Q_INVOKABLE void setOutputDevice(const int);
    Q_INVOKABLE int getOutputDevice() const;

    Q_INVOKABLE QList<QObject *> getUiLanguageList();
    Q_INVOKABLE void setUiLanguage(const QString);
    Q_INVOKABLE int getUiLanguage() const;

    Q_INVOKABLE QList<QObject *> getSttLanguageList();
    Q_INVOKABLE void setSttLanguage(const QString);
    Q_INVOKABLE int getSttLanguage() const;

    Q_INVOKABLE QStringList getTtsVoiceList();
    Q_INVOKABLE void setTtsVoice(const QString);
    Q_INVOKABLE int getTtsVoice() const;

    Q_INVOKABLE void loadSettings();
    Q_INVOKABLE void saveSettings();

signals:

public slots:

private:
    void initAudio();

    SettingsValult * settingsValult;

    QList<LocaleObject *> availableUiLanguages;
    QList<LocaleObject *> availableSttLanguages;
    QList<QString> availableTtsVoice;
    QHash<QString, LocaleObject *> availableLanguages;
};

#endif // SETTINGSCONTROLLER_H


text:
cask :v1 => 'alfred' do
  version '2.7_385'
  sha256 'a097fd1c8a49ddb62ad7b45243b34dccd6e663426ea0cef3c0e5f92529a83904'

  url "https://cachefly.alfredapp.com/Alfred_#{version}.zip"
  name 'Alfred'
  homepage 'http://www.alfredapp.com/'
  license :commercial

  app 'Alfred 2.app'
  app 'Alfred 2.app/Contents/Preferences/Alfred Preferences.app'

  postflight do
    suppress_move_to_applications :key => 'suppressMoveToApplications'
  end
end


text:
#include <modules/qtwidgets/lineeditqt.h>

#include <warn/push>
#include <warn/ignore/all>
#include <QKeyEvent>
#include <warn/pop>

namespace inviwo {

LineEditQt::LineEditQt(QWidget *parent) : QLineEdit(parent) {
    connect(this, &QLineEdit::returnPressed, [this]() {
        // loose focus when return is pressed
        this->clearFocus();
    });
    // do nothing when editing is finished (either return pressed or focus lost)
}

void LineEditQt::keyPressEvent(QKeyEvent *e) {
    // check whether pressed key is escape, if yes then trigger undo
    if (e->key() == Qt::Key_Escape) {
        emit editingCanceled();
        // loose focus
        this->clearFocus();
        e->accept();
        return;
    }
    QLineEdit::keyPressEvent(e);
}

}  // namespace inviwo


text:
require 'sorcery/providers/base'

module Sorcery
  module Providers
    # This class adds support for OAuth with vk.com.
    #
    #   config.mailru.key = <key>
    #   config.mailru.secret = <secret>
    #   ...
    #
    class Mailru < Base
      include Protocols::Oauth2

      attr_accessor :auth_path, :token_path, :user_info_url, :scope, :response_type

      def initialize
        super

        @scope          = nil
        @site           = 'https://connect.mail.ru/'
        @user_info_url  = 'http://www.appsmail.ru/platform/api'
        @auth_path      = '/oauth/authorize'
        @token_path     = '/oauth/token'
        @grant_type     = 'authorization_code'
      end

      def get_user_hash(access_token)
        user_hash = auth_hash(access_token)

        params = {
          app_id: key,
          method: 'users.getInfo',
          secure: 1,
          session_key: access_token.token,
          uids: access_token.params['x_mailru_vid']
        }

        request_params = params.merge(
          sig: sign_params(params),
        )

        response = access_token.get(user_info_url, params: request_params)

        if user_hash[:user_info] = JSON.parse(response.body)
          user_hash[:user_info] = user_hash[:user_info].first
          user_hash[:user_info]['full_name'] = [user_hash[:user_info]['first_name'], user_hash[:user_info]['last_name']].join(' ')
          user_hash[:uid] = user_hash[:user_info]['uid']
        end
        user_hash
      end

      # calculates and returns the url to which the user should be redirected,
      # to get authenticated at the external provider's site.
      def login_url(params, session)
        self.authorize_url({ authorize_url: auth_path,  })
      end

      def process_callback(params, session)
        args = {}.tap do |a|
          a[:code] = params[:code] if params[:code]
        end

        get_access_token(args, token_url: token_path, token_method: :post)
      end

      private

      def sign_params(params)
        code = params.map { |k,v| "#{k}=#{v}" }.join
        Digest::MD5.hexdigest(code + secret)
      end
    end
  end
end


text:
[![Gem Version](https://badge.fury.io/rb/oanda_api.svg)](https://rubygems.org/gems/oanda_api)
[![Code Climate](https://codeclimate.com/github/nukeproof/oanda_api/badges/gpa.svg)](https://codeclimate.com/github/nukeproof/oanda_api)
[![Test Coverage](https://codeclimate.com/github/nukeproof/oanda_api/badges/coverage.svg)](https://codeclimate.com/github/nukeproof/oanda_api)

Access Oanda FX accounts, get market data, trade, build trading strategies using Ruby.
## Synopsis
OandaAPI is a simple Ruby wrapper for the [Oanda REST API](http://developer.oanda.com/rest-live/introduction/).

This style of API wrapper is typically called a [fluent](http://en.wikipedia.org/wiki/Fluent_interface) interface. The wrapper translates native Ruby objects to and from JSON representations that the API understands.

For example,

```ruby
client = OandaAPI::Client::TokenClient.new(:practice, "practice_account_token")
account = client.account(12345).get
```

returns an `OandaAPI::Resource::Account`, with method accessors for all of the [Account](http://developer.oanda.com/rest-live/accounts/) attributes defined by the Oanda API.

## Features

A simple native Ruby reflection of the underlying REST API using Ruby idioms where appropriate.

Enable [Oanda's Best Practices](http://developer.oanda.com/rest-live/best-practices/) recommendations for accessing the API including:

- Secure connections over SSL with always verified certificates
- Persistent connections
- Response compression
- Request rate limiting

Some Examples
-------------

### Getting price quotes
```ruby
require 'oanda_api'

client = OandaAPI::Client::TokenClient.new(:practice, ENV.fetch("OANDA_PRACTICE_TOKEN"))

prices = client.prices(instruments: %w(EUR_USD USD_JPY)).get

prices.each do |p|
  p.instrument       # => "EUR_USD"
  p.ask              # => 1.13781
  p.bid              # => 1.13759
  p.time             # => 2015-01-27 21:01:13 UTC
end
```

### Getting candle information
```ruby
require 'oanda_api'

client = OandaAPI::Client::TokenClient.new(:practice, ENV.fetch("OANDA_PRACTICE_TOKEN"))

candles = client.candles( instrument: "EUR_USD",
                         granularity: "M1",
                       candle_format: "midpoint",
                               start: (Time.now - 3600).utc.to_datetime.rfc3339)
                .get

candles.size         # => 57
candles.granularity  # => "M1"
candles.instrument   # => "EUR_USD"

candles.each do |c|
  c.complete?        # => true
  c.open_mid         # => 1.137155
  c.close_mid        # => 1.137185
  c.high_mid         # => 1.13729
  c.low_mid          # => 1.137155
  c.time             # => 2015-01-27 20:26:00 UTC
  c.volume           # => 25
end
```

### Creating a market order
```ruby
require 'oanda_api'

client = OandaAPI::Client::TokenClient.new(:practice, ENV.fetch("OANDA_PRACTICE_TOKEN"))

order = client.account(12345)
              .order(instrument: "USD_JPY",
                           type: "market",
                           side: "buy",
                          units: 10_000)
              .create

order.price            # => 114.887
order.time             # => 2014-12-20 21:25:57 UTC
order.trade_opened.id  # => 175491416
```

### Closing a position
```ruby
require 'oanda_api'

client = OandaAPI::Client::TokenClient.new(:practice, ENV.fetch("OANDA_PRACTICE_TOKEN"))

account = client.account(12345)             # => OandaAPI::NamespaceProxy
position = account.position("USD_JPY").get  # => OandaAPI::Resource::Position

position.ave_price  # => 114.898
position.side       # => "buy"
position.units      # => 30_000

# Close out the 30_000 long position
closed_position = account.position("USD_JPY").close  # => OandaAPI::Resource::Position

closed_position.price        # => 114.858
closed_position.total_units  # => 30_000
closed_position.ids          # => [175490804, 175491421, 175491416]

transaction = account.transaction(175490804).get    # => OandaAPI::Resource::Transaction
transaction.instrument  # => "USD_JPY"
transaction.time        # => 2014-12-19 03:29:48 UTC
transaction.type        # => "MARKET_ORDER_CREATE"
```

### Getting Economic Calendar Information

```ruby
require 'oanda_api'

# If you want to use sugar like: 1.day, 1.hour, 1.week, etc.
require 'active_support/core_ext/numeric/time'

client = OandaAPI::Client::TokenClient.new(:practice, ENV.fetch("OANDA_PRACTICE_TOKEN"))

client.calendar(period: 1.day).get.each do |event|
  event.class     # => OandaAPI::Resource::CalendarEvent
  event.title     # => "Industrial Production"
  event.currency  # => "EUR"
  event.region    # => "europe"
  event.forecast  # => "-0.3"
  event.previous  # => "-0.3"
  event.actual    # => "3.3"
  event.impact    # => "2"
  event.unit      # => "% m/m"
  event.timestamp # => 1457420400
  event.time      # => 2016-03-08 07:00:00 UTC
end
```

##Streaming
OandaAPI also supports the [Oanda realtime streaming API](http://developer.oanda.com/rest-live/streaming/).

For example to stream live prices,

```ruby
client = OandaAPI::Streaming::Client.new(:practice, ENV.fetch("OANDA_PRACTICE_TOKEN"))
prices = client.prices(account_id: 1234, instruments: %w[AUD_CAD AUD_CHF])
prices.stream do |price|
  # Note: The code in this block should handle the price
  #       as efficiently as possible, otherwise the connection could timeout.
  #       For example, you could publish the tick on a queue to be handled
  #       by some other thread or process.
  price  # => OandaAPI::Resource::Price
end
```

Documentation
-------------

Please see the [Oanda Developer Wiki](http://developer.oanda.com/rest-live/introduction/)
for detailed documentation and API usage notes.

| Ruby                       |  Oanda REST API      |
|:---------------------------|:---------------------|
| client.accounts.get        | GET /v1/accounts     |
| client.account(123).get    | GET /v1/accounts/123 |
| client.instruments(account_id: 123).get     | GET /v1/instruments?accountId=123  |
| client.prices(instruments: ["EUR_USD","USD_JPY"]).get | GET /v1/prices/?instruments=EUR_USD%2CUSD_JPY |
| client.account(123).orders.get | GET /v1/accounts/123/orders |
| client.account(123).order(123).get | GET /v1/accounts/123/orders/123 |
| client.account(123).order( *options* ).create | POST /v1/accounts/123/orders |
| client.account(123).order(id:123, *options* ).update | PATCH /v1/accounts/123/orders/123 |
| client.account(123).order(123).close | DELETE /v1/accounts/123/orders/123 |
| client.account(123).positions.get | GET /v1/accounts/123/positions |
| client.account(123).position("EUR_USD").get | GET /v1/accounts/123/positions/EUR_USD |
| client.account(123).position("EUR_USD").close | DELETE /v1/accounts/123/positions/EUR_USD |
| client.account(123).trades.get | GET /v1/accounts/123/trades |
| client.account(123).trade(123).get | GET /v1/accounts/123/trades/123 |
| client.account(123).trade(id:123, *options* ).update | PATCH /v1/accounts/123/trades/123 |
| client.account(123).trade(123).close | DELETE /v1/accounts/123/trades/123 |
| client.account(123).transactions.get | GET /v1/accounts/123/transactions |
| client.account(123).transaction(123).get | GET /v1/accounts/123/transactions/123 |
| client.account(123).alltransactions.get | GET /v1/accounts/123/alltransactions |
| client.calendar(instrument: "AUD_USD", period: 86400).get | GET /labs/v1/calendar?instrument=AUD_USD&period=86400|
| client.spreads(instrument: "AUD_USD", period: 86400).get | GET /labs/v1/spreads?instrument=AUD_USD&period=86400|

Installation
------------

Add this line to your application's Gemfile:

    gem 'oanda_api'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install oanda_api

Inside of your Ruby program, require oanda_api with:

    require 'oanda_api'

Configuration
-------------

Add a configuration block to your application to specify client settings such
as whether or not to use compression, request rate limiting, or other options.
See the RubyDoc [documentation](http://www.rubydoc.info/gems/oanda_api) for OandaAPI for more configuration settings.

```ruby
OandaAPI.configure do |config|
  config.use_compression = true
  config.use_request_throttling = true
  config.max_requests_per_second = 10
	config.max_new_connections_per_second = 1
end
```

Supported Platforms
-------------------

OandaAPI works with Ruby 2.0 and higher.

Tested on:

* MRI 2.1, 2.2, 2.3
* JRuby 9.0.0, 9.0.5
* Rubinius 2.4, 2.5

Contributing
------------

If you'd like to contribute code or modify this gem, you can run the test suite with:

```ruby
gem install oanda_api --dev
bundle exec rspec # or just 'rspec' may work
```
When you're ready to code:

1. Fork this repository on github.
2. Make your changes.
3. Add tests where applicable and run the existing tests with `rspec` to make sure they all pass.
4. Add new documentation where appropriate using [YARD](http://yardoc.org/) formatting.
5. Create a new pull request and submit it to me.

License
-------

Copyright (c) 2014 Dean Missikowski. Distributed under the MIT License. See
[LICENSE](LICENSE) for further details.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
<Type Name="ResourceNotFoundEventArgs" FullName="Urho.Resources.ResourceNotFoundEventArgs">
  <TypeSignature Language="C#" Value="public struct ResourceNotFoundEventArgs" />
  <TypeSignature Language="ILAsm" Value=".class public sequential ansi sealed beforefieldinit ResourceNotFoundEventArgs extends System.ValueType" />
  <AssemblyInfo>
    <AssemblyName>Urho</AssemblyName>
    <AssemblyVersion>1.0.0.0</AssemblyVersion>
  </AssemblyInfo>
  <Base>
    <BaseTypeName>System.ValueType</BaseTypeName>
  </Base>
  <Interfaces />
  <Docs>
    Event arguments for the ResourceCache's ResourceNotFound event
    <remarks>To be added.</remarks>
  </Docs>
  <Members>
    <Member MemberName="ResourceName">
      <MemberSignature Language="C#" Value="public string ResourceName { get; }" />
      <MemberSignature Language="ILAsm" Value=".property instance string ResourceName" />
      <MemberType>Property</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.String</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <value>To be added.</value>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
  </Members>
</Type>


text:
var lti;
(function() {
  $.digits = function(number){
    return number.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
  }
  var $results = $("#results");
  var $message = $("#message");
  var $result = $("#result").detach().removeAttr('id');
  $(".result").live('click', function(event) {
    if($(event.target).hasClass('preview')) { return; }
    event.preventDefault();
    var videoUrl = $(this).attr('rel');
    var entry = $(this).data('entry');
    if($(event.target).hasClass('embed')) {
      lti.resourceSelected({
        embed_type: 'iframe',
        url: "http://www.schooltube.com/embed/" + entry.vkey,
        width: 500,
        height: 375,
        title: entry.title
      });
    } else {
      lti.resourceSelected({
        embed_type: 'link',
        url: entry.short_url,
        text: entry.title
      });
    }
  });
  $("#search").submit(function(event) {
    event.preventDefault();
    event.stopPropagation();
    $results.empty().hide();
    $message.show().text("Loading...");
    var query = encodeURIComponent($("#query").val());
    var url = "/schooltube_search?q=" + query;
    $.ajax({
      url: url,
      success: function(data) {
        console.log(data);
        if(!data.objects || data.objects.length == 0) {
          $results.empty().hide();
          $message.show().text("No Results Found");
          return;
        }
        for(var idx = 0; idx < data.objects.length && data.objects[idx]; idx++) {
          var entry = data.objects[idx];
          var $entry = $result.clone(true);
          $entry.data('entry', entry);
          var duration = entry.duration;
          var seconds = duration % 60;
          var minutes = (duration - seconds) / 60;
          duration = (minutes || "0") + ":" + (seconds < 10 ? ("0" + seconds) : seconds);
          $entry.find(".title").text("(" + duration + ") " + entry.title);
          $entry.find(".img").attr('src', entry.thumbnail_url);
          $entry.find(".views").text($.digits(entry.view_count) + " view" + (entry.view_count == 1 ? "" : "s"));
          $entry.find(".description").text(entry.description);
          $entry.find(".embed_holder").toggle(entry.allow_embed);
          $entry.find(".preview").attr('href', entry.short_url);
          $entry.attr('rel', entry.short_url);
          $results.append($entry.show());
        }
        $results.show();
        $message.hide();
      },
      dataType: 'json'
    });
  }).submit();
})();


text:
<?php

namespace Zend\Mvc\Service;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class DiStrictAbstractServiceFactoryFactory implements FactoryInterface
{
    /**
     * Class responsible for instantiating a DiStrictAbstractServiceFactory
     *
     * @param  ServiceLocatorInterface $serviceLocator
     * @return DiStrictAbstractServiceFactory
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $diAbstractFactory = new DiStrictAbstractServiceFactory(
            $serviceLocator->get('Di'),
            DiStrictAbstractServiceFactory::USE_SL_BEFORE_DI
        );
        $config = $serviceLocator->get('Config');

        if (isset($config['di']['allowed_controllers'])) {
            $diAbstractFactory->setAllowedServiceNames($config['di']['allowed_controllers']);
        }

        return $diAbstractFactory;
    }
}


text:
#include "third_party/blink/renderer/core/layout/svg/layout_svg_foreign_object.h"

#include "third_party/blink/renderer/core/layout/hit_test_result.h"
#include "third_party/blink/renderer/core/layout/svg/svg_layout_support.h"
#include "third_party/blink/renderer/core/layout/svg/svg_resources_cache.h"
#include "third_party/blink/renderer/core/layout/svg/transformed_hit_test_location.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/paint/svg_foreign_object_painter.h"
#include "third_party/blink/renderer/core/svg/svg_foreign_object_element.h"

namespace blink {

LayoutSVGForeignObject::LayoutSVGForeignObject(SVGForeignObjectElement* node)
    : LayoutSVGBlock(node), needs_transform_update_(true) {}

LayoutSVGForeignObject::~LayoutSVGForeignObject() = default;

bool LayoutSVGForeignObject::IsChildAllowed(LayoutObject* child,
                                            const ComputedStyle& style) const {
  // Disallow arbitary SVG content. Only allow proper <svg xmlns="svgNS">
  // subdocuments.
  return !child->IsSVGChild();
}

void LayoutSVGForeignObject::Paint(const PaintInfo& paint_info) const {
  SVGForeignObjectPainter(*this).Paint(paint_info);
}

LayoutUnit LayoutSVGForeignObject::ElementX() const {
  return LayoutUnit(
      roundf(SVGLengthContext(GetElement())
                 .ValueForLength(StyleRef().SvgStyle().X(), StyleRef(),
                                 SVGLengthMode::kWidth)));
}

LayoutUnit LayoutSVGForeignObject::ElementY() const {
  return LayoutUnit(
      roundf(SVGLengthContext(GetElement())
                 .ValueForLength(StyleRef().SvgStyle().Y(), StyleRef(),
                                 SVGLengthMode::kHeight)));
}

LayoutUnit LayoutSVGForeignObject::ElementWidth() const {
  return LayoutUnit(SVGLengthContext(GetElement())
                        .ValueForLength(StyleRef().Width(), StyleRef(),
                                        SVGLengthMode::kWidth));
}

LayoutUnit LayoutSVGForeignObject::ElementHeight() const {
  return LayoutUnit(SVGLengthContext(GetElement())
                        .ValueForLength(StyleRef().Height(), StyleRef(),
                                        SVGLengthMode::kHeight));
}

void LayoutSVGForeignObject::UpdateLogicalWidth() {
  SetLogicalWidth(StyleRef().IsHorizontalWritingMode() ? ElementWidth()
                                                       : ElementHeight());
}

void LayoutSVGForeignObject::ComputeLogicalHeight(
    LayoutUnit,
    LayoutUnit logical_top,
    LogicalExtentComputedValues& computed_values) const {
  computed_values.extent_ =
      StyleRef().IsHorizontalWritingMode() ? ElementHeight() : ElementWidth();
  computed_values.position_ = logical_top;
}

void LayoutSVGForeignObject::UpdateLayout() {
  DCHECK(NeedsLayout());

  auto* foreign = To<SVGForeignObjectElement>(GetElement());

  bool update_cached_boundaries_in_parents = false;
  if (needs_transform_update_) {
    local_transform_ =
        foreign->CalculateTransform(SVGElement::kIncludeMotionTransform);
    needs_transform_update_ = false;
    update_cached_boundaries_in_parents = true;
  }

  LayoutRect old_viewport = FrameRect();

  // Set box origin to the foreignObject x/y translation, so positioned objects
  // in XHTML content get correct positions. A regular LayoutBoxModelObject
  // would pull this information from ComputedStyle - in SVG those properties
  // are ignored for non <svg> elements, so we mimic what happens when
  // specifying them through CSS.
  SetX(ElementX());
  SetY(ElementY());

  bool layout_changed = EverHadLayout() && SelfNeedsLayout();
  LayoutBlock::UpdateLayout();
  DCHECK(!NeedsLayout());

  // If our bounds changed, notify the parents.
  if (!update_cached_boundaries_in_parents)
    update_cached_boundaries_in_parents = old_viewport != FrameRect();
  if (update_cached_boundaries_in_parents)
    LayoutSVGBlock::SetNeedsBoundariesUpdate();

  // Invalidate all resources of this client if our layout changed.
  if (layout_changed)
    SVGResourcesCache::ClientLayoutChanged(*this);
}

bool LayoutSVGForeignObject::NodeAtPointFromSVG(
    HitTestResult& result,
    const HitTestLocation& hit_test_location,
    const PhysicalOffset& accumulated_offset,
    HitTestAction) {
  DCHECK_EQ(accumulated_offset, PhysicalOffset());
  TransformedHitTestLocation local_location(hit_test_location,
                                            LocalSVGTransform());
  if (!local_location)
    return false;

  // |local_location| already includes the offset of the <foreignObject>
  // element, but PaintLayer::HitTestLayer assumes it has not been.
  HitTestLocation local_without_offset(*local_location, -PhysicalLocation());
  HitTestResult layer_result(result.GetHitTestRequest(), local_without_offset);
  layer_result.SetInertNode(result.InertNode());
  bool retval = Layer()->HitTest(local_without_offset, layer_result,
                                 PhysicalRect(PhysicalRect::InfiniteIntRect()));

  // Preserve the "point in inner node frame" from the original request,
  // since |layer_result| is a hit test rooted at the <foreignObject> element,
  // not the frame, due to the constructor above using
  // |point_in_foreign_object| as its "point in inner node frame".
  // TODO(chrishtr): refactor the PaintLayer and HitTestResults code around
  // this, to better support hit tests that don't start at frame boundaries.
  PhysicalOffset original_point_in_inner_node_frame =
      result.PointInInnerNodeFrame();
  if (result.GetHitTestRequest().ListBased())
    result.Append(layer_result);
  else
    result = layer_result;
  result.SetPointInInnerNodeFrame(original_point_in_inner_node_frame);
  return retval;
}

bool LayoutSVGForeignObject::NodeAtPoint(
    HitTestResult& result,
    const HitTestLocation& hit_test_location,
    const PhysicalOffset& accumulated_offset,
    HitTestAction hit_test_action) {
  // Skip LayoutSVGBlock's override.
  return LayoutBlockFlow::NodeAtPoint(result, hit_test_location,
                                      accumulated_offset, hit_test_action);
}

PaintLayerType LayoutSVGForeignObject::LayerTypeRequired() const {
  // Skip LayoutSVGBlock's override.
  return LayoutBlockFlow::LayerTypeRequired();
}

void LayoutSVGForeignObject::StyleDidChange(StyleDifference diff,
                                            const ComputedStyle* old_style) {
  LayoutSVGBlock::StyleDidChange(diff, old_style);

  if (old_style && (SVGLayoutSupport::IsOverflowHidden(*old_style) !=
                    SVGLayoutSupport::IsOverflowHidden(StyleRef()))) {
    // See NeedsOverflowClip() in PaintPropertyTreeBuilder for the reason.
    SetNeedsPaintPropertyUpdate();

    if (Layer())
      Layer()->SetNeedsCompositingInputsUpdate();
  }
}

}  // namespace blink


text:
package com.querydsl.sql;

import java.sql.Connection;
import java.sql.SQLException;

import javax.inject.Provider;
import javax.sql.DataSource;

import com.querydsl.core.Tuple;
import com.querydsl.core.types.Expression;
import com.querydsl.core.types.dsl.Expressions;

/**
 * Factory class for query and DML clause creation
 *
 * @author tiwe
 *
 */
public class SQLQueryFactory extends AbstractSQLQueryFactory<SQLQuery<?>> {

    static class DataSourceProvider implements Provider<Connection> {

        private final DataSource ds;

        public DataSourceProvider(DataSource ds) {
            this.ds = ds;
        }

        @Override
        public Connection get() {
            try {
                return ds.getConnection();
            } catch (SQLException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }

    }

    public SQLQueryFactory(SQLTemplates templates, Provider<Connection> connection) {
        this(new Configuration(templates), connection);
    }

    public SQLQueryFactory(Configuration configuration, Provider<Connection> connection) {
        super(configuration, connection);
    }

    public SQLQueryFactory(Configuration configuration, DataSource dataSource) {
        super(configuration, new DataSourceProvider(dataSource));
    }

    @Override
    public SQLQuery<?> query() {
        return new SQLQuery<Void>(connection.get(), configuration);
    }

    /**
     * Create a new SQLQuery instance with the given projection
     *
     * @param expr projection
     * @param <T>
     * @return select(expr)
     */
    public <T> SQLQuery<T> select(Expression<T> expr) {
        return query().select(expr);
    }

    /**
     * Create a new SQLQuery instance with the given projection
     *
     * @param exprs projection
     * @return select(exprs)
     */
    public SQLQuery<Tuple> select(Expression<?>... exprs) {
        return query().select(exprs);
    }

    /**
     * Create a new SQLQuery instance with the given projection
     *
     * @param expr distinct projection
     * @param <T>
     * @return select(distinct expr)
     */
    public <T> SQLQuery<T> selectDistinct(Expression<T> expr) {
        return query().select(expr).distinct();
    }

    /**
     * Create a new SQLQuery instance with the given projection
     *
     * @param exprs distinct projection
     * @return select(distinct exprs)
     */
    public SQLQuery<Tuple> selectDistinct(Expression<?>... exprs) {
        return query().select(exprs).distinct();
    }

    /**
     * Create a new SQLQuery instance with zero as the projection
     *
     * @return select(0)
     */
    public SQLQuery<Integer> selectZero() {
        return select(Expressions.ZERO);
    }

    /**
     * Create a new SQLQuery instance with one as the projection
     *
     * @return select(1)
     */
    public SQLQuery<Integer> selectOne() {
        return select(Expressions.ONE);
    }

    /**
     * Create a new detached SQLQuery instance with the given projection and source
     *
     * @param expr query source and projection
     * @param <T>
     * @return select(expr).from(expr)
     */
    public <T> SQLQuery<T> selectFrom(RelationalPath<T> expr) {
        return select(expr).from(expr);
    }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="HandheldFriendly" content="True">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <meta name="description" content="Suppose we have two datasets, have \(n1\), \(n2\) data separately, and we know mean and variance of each, \(\mu_1\) ,\(\sigma_1^2\), \(\mu_2\) , \(\sigma_2^2\) ">
<meta property="og:type" content="article">
<meta property="og:title" content="How to Calculate Combined Variance">
<meta property="og:url" content="http://yoursite.com/2014/09/25/how-to-calculate-combined-variance/index.html">
<meta property="og:site_name" content="yanguango">
<meta property="og:description" content="Suppose we have two datasets, have \(n1\), \(n2\) data separately, and we know mean and variance of each, \(\mu_1\) ,\(\sigma_1^2\), \(\mu_2\) , \(\sigma_2^2\) , then we combined the two datasets to s">
<meta property="og:locale" content="en">
<meta property="og:updated_time" content="2017-11-20T18:59:15.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="How to Calculate Combined Variance">
<meta name="twitter:description" content="Suppose we have two datasets, have \(n1\), \(n2\) data separately, and we know mean and variance of each, \(\mu_1\) ,\(\sigma_1^2\), \(\mu_2\) , \(\sigma_2^2\) , then we combined the two datasets to s">

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

            <link rel="icon" type="image/png" href="/images/favicon-192x192.png" sizes="192x192">

            <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon.png">

    <title>How to Calculate Combined Variance</title>

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

Home

About

Writing

Projects

      Previous post
      Next post
      Back to top
      Share post

<a class="icon" href="http://www.tumblr.com/share/link?url=http://yoursite.com/2014/09/25/how-to-calculate-combined-variance/&name=How to Calculate Combined Variance&description=<p>Suppose we have two datasets, have \(n1\), \(n2\) data separately, and we know mean and variance of each, \(\mu_1\) ,\(\sigma_1^2\), \(\mu_2\) , \(\sigma_2^2\) , then we combined the two datasets to single one, what's the variance of the combined dataset?</p>
<p>I find a solution in Internet, here is the formula.<br>">

        How to Calculate Combined Variance

        yanguango

        <time datetime="2014-09-26T00:02:00.000Z" itemprop="datePublished">2014-09-25</time>

Suppose we have two datasets, have \(n1\), \(n2\) data separately, and we know mean and variance of each, \(\mu_1\) ,\(\sigma_1^2\), \(\mu_2\) , \(\sigma_2^2\) , then we combined the two datasets to single one, what's the variance of the combined dataset?

I find a solution in Internet, here is the formula.

Now, I will prove it. Consider
\[
Var[x] = E[x^2] - (E[x])^2
\]

Therefore

\[
\sigma^2 = \frac{n1E[x_1^2]+n2E[x_2^2]}{n1+n2} - (E[x])^2 \
= \frac{n1E[x_1^2]+n2E[x_2^2]}{n1+n2} - \mu^2 \
\frac{n1(\sigma_1^2 + \mu_1^2)+n2(\sigma_2^2 + \mu_2^2)}{n1+n2} - \mu^2
\]

The we expand the first formula

The interesting point is

So I think the formula from Internet is correct.

            Please enable JavaScript to view the comments powered by Disqus.

Home

About

Writing

Projects

<a class="icon" href="http://www.tumblr.com/share/link?url=http://yoursite.com/2014/09/25/how-to-calculate-combined-variance/&name=How to Calculate Combined Variance&description=<p>Suppose we have two datasets, have \(n1\), \(n2\) data separately, and we know mean and variance of each, \(\mu_1\) ,\(\sigma_1^2\), \(\mu_2\) , \(\sigma_2^2\) , then we combined the two datasets to single one, what's the variance of the combined dataset?</p>
<p>I find a solution in Internet, here is the formula.<br>">

 TOC

 Share

 Top

 Menu

    Copyright © 2017 Guang Yang

Home

About

Writing

Projects

<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="/lib/meslo-LG/styles.css">
<link rel="stylesheet" href="/lib/justified-gallery/justifiedGallery.min.css">


text:
layout: page
title: Supervisores OTP
category: advanced
order: 6
lang: pt
---

Supervisores são processos especializados com um propósito: monitorar outros processos. Estes supervisores nos possibilitam a criação de aplicações tolerantes a falhas automaticamente reiniciando processos filhos quando eles falham.

{% include toc.html %}

## Configuração

A magia de Supervisores está na função `Supervisor.start_link/2`. Além de iniciar nosso supervisor e filhos, nos permite definir a estratégia que nosso supervisor irá usar para gerenciar os processos filhos.

Filhos são definidos usando uma lista e a função `worker/3` que nós importamos de `Supervisor.Spec`. A função `worker/3` pega um módulo, argumentos e um conjunto de opções. Por baixo dos panos, `worker/3` chama `start_link/3` com nossos argumentos durante a inicialização.

Usando o SimpleQueue da lição [OTP Concurrency](../../advanced/otp-concurrency) vamos começar:

```elixir
import Supervisor.Spec

children = [
  worker(SimpleQueue, [], [name: SimpleQueue])
]

{:ok, pid} = Supervisor.start_link(children, strategy: :one_for_one)
```

Se o nosso processo fosse falhar ou ser encerrado, nosso Supervisor iria automaticamente reiniciar este processo como se nada tivesse acontecido.

### Estratégias

Atualmente, existem quatro estratégias diferentes de reinicialização disponíveis aos supervisores:

+ `:one_for_one` - Apenas reinicia os processos filhos que falharem.

+ `:one_for_all` - Reinicia todos os processos filhos no evento da falha.

+ `:rest_for_one` - Reinicia o processo que falhou e qualquer processo que começou depois deste.

+ `:simple_one_for_one` - O melhor para processos filhos dinamicamente adicionados. É requerido que o Supervisor.Spec tenha apenas um filho, mas este filho pode ser gerado múltiplas vezes. Esta estratégia se destina a ser usada quando precisamos dinamicamente iniciar ou parar filhos supervisionados.

### Nesting

Além de processos de trabalho também podemos supervisionar surpevisores para criar uma árvore de supervisores. A única diferença para nós é trocar `supervisor/3` por `worker/3`.

```elixir
import Supervisor.Spec

children = [
  supervisor(ExampleApp.ConnectionSupervisor, [[name: ExampleApp.ConnectionSupervisor]]),
  worker(SimpleQueue, [[], [name: SimpleQueue]])
]

{:ok, pid} = Supervisor.start_link(children, strategy: :one_for_one)
```

## Supervisor de tarefas

Tarefas têm o seu próprio Supervisor especializado, o `Task.Supervisor`. Projetado para tarefas criadas dinamicamente. O supervisor usa `:simple_one_for_one` por debaixo dos panos.

### Instalação

Incluir o `Task.Supervisor` não é diferente de outros supervisores:

```elixir
import Supervisor.Spec

children = [
  supervisor(Task.Supervisor, [[name: ExampleApp.TaskSupervisor]]),
]

{:ok, pid} = Supervisor.start_link(children, strategy: :one_for_one)
```

### Tarefas Supervisionadas

Com o supervisor inicializado, podemos usar a função `start_child/2` para criar uma tarefa supervisionada:

```elixir
{:ok, pid} = Task.Supervisor.start_child(ExampleApp.TaskSupervisor, fn -> background_work end)
```

Se a nossa tarefa quebrar prematuramente, ela irá ser reiniciada para nós. Isto pode ser particularmente útil quando se trabalha com conexões de entrada ou processamento em background.


text:
package me.chanjar.weixin.mp.bean.membercard;

import lombok.Data;

/**
 * @author yqx
 * @date 2018/9/19
 */
@Data
public class ActivatePluginParamResult {

  private int errcode;

  private String errmsg;

  private String url;

}