text:
#include <QVBoxLayout>
#include <QtDeclarative>
#include "stkdialog.h"
#include "stkmenumodel.h"

StkDialog::StkDialog(SimImageProvider * imageProvider, const QString &iconUrl,
                     const QString &title, const QString &qmlViewUrl, QWidget *parent) :
    QDialog(parent,Qt::Window)
{
    mImageProvider = imageProvider;
    mIconUrl = iconUrl;
    mTitle = title;
    mQmlViewUrl = qmlViewUrl;
    mMinChars = mMaxChars = mSelection = -1;
    mLoopTone = mHideTyping = mNumeric = false;
    mShowBackButton = mShowEndButton = true;
}

void StkDialog::initView()
{
    // Create QML View as central widget
    mView = new QDeclarativeView;

    // Register image provider, deleted with the engine
    QDeclarativeEngine * engine = mView->engine();
    engine->addImageProvider(SIM_IMAGE_PROVIDER, mImageProvider);
    mView->setSource(QUrl(mQmlViewUrl));
    mView->setResizeMode(QDeclarativeView::SizeRootObjectToView);
    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(mView);
    setLayout(layout);

    // Find qml objects and connect signals
    QObject *object;
    QObject *root = this->mView->rootObject();

    // Main icon and title
    object = root->findChild<QObject*>("icon");
    if (object)
        object->setProperty("source", mIconUrl);
    object = root->findChild<QObject*>("title");
    if (object && !mTitle.isEmpty())
        object->setProperty("text", mTitle);

    // SIM Toolkit Menu
    QObject * menuView = root->findChild<QObject*>("menuView");
    if (menuView) {
        // set model "menuModel" for ListView "menuView"
        QDeclarativeContext *context = mView->rootContext();
        StkMenuModel * menuModel = new StkMenuModel();
        menuModel->setMenuItems(mMenuItems);
        context->setContextProperty("menuModel",menuModel);
        connect(root, SIGNAL(itemSelected(int)), this, SLOT(responseOkWithSelection(int)));
        if (mSelection != -1)
            menuView->setProperty("currentIndex", mSelection);
    }

    // Text edit / input
    QObject * editText = root->findChild<QObject*>("editText");
    if (editText) {
        editText->setProperty("text",mDefaultText);
        editText->setProperty("isNumeric",mNumeric);
        editText->setProperty("hideTyping",mHideTyping);
        editText->setProperty("minChars",mMinChars);
        editText->setProperty("maxChars",mMaxChars);
        connect(root, SIGNAL(textEntered(QString)), this, SLOT(responseOkWithText(QString)));
    }

    // Audio tone
    QObject * audioTone = root->findChild<QObject*>("audioTone");
    if (audioTone && !mToneSource.isEmpty()) {
        // Default StkPlaySound.qml audioTone loops: SoundEffect.Infinite
        if (!mLoopTone)
            audioTone->setProperty("loops", 1);
        audioTone->setProperty("source", "qrc:/audio/" + mToneSource + ".wav");
    }

    // Browser View
    QObject * browserView = root->findChild<QObject*>("browserView");
    if (browserView && !mUrl.isEmpty())
        browserView->setProperty("url", mUrl);

    // SIM Toolkit Panel
    QObject * panel = root->findChild<QObject*>("panel");
    if (panel) {
        // Default StkPanel.qml showEndButton: true
        if (mShowEndButton) {
            object = panel->findChild<QObject*>("endRect");
            if (object)
                connect(root, SIGNAL(endSession()), this, SLOT(responseEnd()));
        } else {
            panel->setProperty("showEndButton", false);
        }
        // Default StkPanel.qml showBackButton: true
        if (mShowBackButton) {
            object = panel->findChild<QObject*>("backRect");
            if (object)
                connect(root, SIGNAL(goBack()), this, SLOT(responseBack()));
        } else {
            panel->setProperty("showBackButton", false);
        }
    }

    // Yes button
    object = root->findChild<QObject*>("yesRect");
    if (object)
        connect(root, SIGNAL(accepted()), this, SLOT(responseYes()));

    // No button
    object = root->findChild<QObject*>("noRect");
    if (object)
        connect(root, SIGNAL(rejected()), this, SLOT(responseNo()));

    // Ok button
    object = root->findChild<QObject*>("okRect");
    if (object && !menuView && !editText)
        connect(root, SIGNAL(accepted()), this, SLOT(responseOk()));

    // default response: end session
    agentResponse = End;
}


text:
using System.Reflection;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("GitReview")]
[assembly: Guid("d696edeb-562e-4df2-acd5-9f20c1400086")]

redpajama_set_name: RedPajamaGithub


text:
// RUN: %clang_cc1 -fcxx-exceptions -fexceptions -fsyntax-only -verify %s
template<typename T, typename U>
struct X0 {
  void f(T x, U y) {
    (void)(x + y); // expected-error{{invalid operands}}
  }
};

struct X1 { };

template struct X0<int, float>;
template struct X0<int*, int>;
template struct X0<int X1::*, int>; // expected-note{{instantiation of}}

template<typename T>
struct X2 {
  void f(T);

  T g(T x, T y) {
    /* DeclStmt */;
    T *xp = &x, &yr = y; // expected-error{{pointer to a reference}}
    /* NullStmt */;
  }
};

template struct X2<int>;
template struct X2<int&>; // expected-note{{instantiation of}}

template<typename T>
struct X3 {
  void f(T) {
    Label:
    T x;
    goto Label;
  }
};

template struct X3<int>;

template <typename T> struct X4 {
  T f() const {
    return; // expected-error{{non-void function 'f' should return a value}}
  }

  T g() const {
    return 1; // expected-error{{void function 'g' should not return a value}}
  }
};

template struct X4<void>; // expected-note{{in instantiation of}}
template struct X4<int>; // expected-note{{in instantiation of}}

struct Incomplete; // expected-note 2{{forward declaration}}

template<typename T> struct X5 {
  T f() { } // expected-error{{incomplete result type}}
};
void test_X5(X5<Incomplete> x5); // okay!

template struct X5<Incomplete>; // expected-note{{instantiation}}

template<typename T, typename U, typename V> struct X6 {
  U f(T t, U u, V v) {
    // IfStmt
    if (t > 0)
      return u;
    else {
      if (t < 0)
        return v; // expected-error{{cannot initialize return object of type}}
    }

    if (T x = t) {
      t = x;
    }
    return v; // expected-error{{cannot initialize return object of type}}
  }
};

struct ConvertibleToInt {
  operator int() const;
};

template struct X6<ConvertibleToInt, float, char>;
template struct X6<bool, int, int*>; // expected-note{{instantiation}}

template <typename T> struct X7 {
  void f() {
    void *v = this;
  }
};

template struct X7<int>;

template<typename T> struct While0 {
  void f(T t) {
    while (t) {
    }

    while (T t2 = T()) ;
  }
};

template struct While0<float>;

template<typename T> struct Do0 {
  void f(T t) {
    do {
    } while (t); // expected-error{{not contextually}}
  }
};

struct NotConvertibleToBool { };
template struct Do0<ConvertibleToInt>;
template struct Do0<NotConvertibleToBool>; // expected-note{{instantiation}}

template<typename T> struct For0 {
  void f(T f, T l) {
    for (; f != l; ++f) {
      if (*f)
        continue;
      else if (*f == 17)
        break;
    }
  }
};

template struct For0<int*>;

template<typename T> struct Member0 {
  void f(T t) {
    t;
    t.f;
    t->f;

    T* tp;
    tp.f; // expected-error{{member reference base type 'T *' is not a structure or union}}
    tp->f;

    this->f;
    this.f; // expected-error{{member reference base type 'Member0<T> *' is not a structure or union}}
  }
};

template<typename T, typename U> struct Switch0 {
  U f(T value, U v0, U v1, U v2) {
    switch (value) {
    case 0: return v0;

    case 1: return v1;

    case 2: // fall through

    default:
      return  v2;
    }
  }
};

template struct Switch0<int, float>;

template<typename T, int I1, int I2> struct Switch1 {
  T f(T x, T y, T z) {
    switch (x) {
    case I1: return y; // expected-note{{previous}}
    case I2: return z; // expected-error{{duplicate}}
    default: return x;
    }
  }
};

template struct Switch1<int, 1, 2>;
template struct Switch1<int, 2, 2>; // expected-note{{instantiation}}

template<typename T> struct IndirectGoto0 {
  void f(T x) {
    // FIXME: crummy error message below
    goto *x; // expected-error{{incompatible}}

  prior:
    T prior_label;
    prior_label = &&prior; // expected-error{{assigning to 'int'}}

    T later_label;
    later_label = &&later; // expected-error{{assigning to 'int'}}

  later:
    (void)(1+1);
  }
};

template struct IndirectGoto0<void*>;
template struct IndirectGoto0<int>; // expected-note{{instantiation}}

template<typename T> struct TryCatch0 {
  void f() {
    try {
    } catch (T t) { // expected-error{{incomplete type}} \
                    // expected-error{{abstract class}}
    } catch (...) {
    }
  }
};

struct Abstract {
  virtual void foo() = 0; // expected-note{{pure virtual}}
};

template struct TryCatch0<int>; // okay
template struct TryCatch0<Incomplete*>; // expected-note{{instantiation}}
template struct TryCatch0<Abstract>; // expected-note{{instantiation}}

// PR4383
template<typename T> struct X;
template<typename T> struct Y : public X<T> {
  Y& x() { return *this; }
};

// Make sure our assertions don't get too uppity.
namespace test0 {
  template <class T> class A { void foo(T array[10]); };
  template class A<int>;
}

namespace PR7016 {
  template<typename T> void f() { T x = x; }
  template void f<int>();
}

namespace PR9880 {
  struct lua_State;
  struct no_tag { char a; };			// (A)
  struct yes_tag { long a; long b; };	// (A)

  template <typename T>
  struct HasIndexMetamethod {
    template <typename U>
    static no_tag check(...);
    template <typename U>
    static yes_tag check(char[sizeof(&U::luaIndex)]);
    enum { value = sizeof(check<T>(0)) == sizeof(yes_tag) };
  };

  class SomeClass {
  public:
    int luaIndex(lua_State* L);
  };

  int i = HasIndexMetamethod<SomeClass>::value;
}


text:
package org.orienteer.core.service;

import com.google.inject.AbstractModule;

import java.util.Random;

public class CustomTestModule extends AbstractModule {

	public static interface ITestInterface {
		public String getKey();
	}

	public static class TestInterface implements ITestInterface {

		private String key = RANDOM_STRING;

		@Override
		public String getKey() {
			return key;
		}

	}

	public static final String RANDOM_STRING = "Random"+new Random().nextLong();
	@Override
	protected void configure() {
		bind(ITestInterface.class).to(TestInterface.class).asEagerSingleton();
	}

}


text:
Shelfed due to complications with exp tracking.

Path of Exile Map Tracking

Cartogram is a desktop application to track maps ran by both yourself and party members. It tracks maps ran, map drops, currency, uniques and divination cards. It uses clipboard data delivered by the Path of Exile client.

**Working Features**

- Logging maps you have ran (or ran in a party), including their quantity, quality, rarity, affixes and pack size.
- Logging the map drops attatched to a map ran (maps, currency, uniques and divination cards)
- Duration of a running map
- Logging map drops from Zana and Cartographers found
- Adding notes to each map (eg. Shav's dropped for some guy in this map / X died from Y in here)
- Customizable hotkeys for stoping maps/zana/cartos etc.
- Reporting to spreadsheet/Google docs to share your results.
- Overlay with basic information

**Planned Features**

- Basic reporting graphs/data
- Zana Dailies
- Fragment Farming
- Atziri Farming
- OPT-IN MySQL data collection to correlate mass user data

**Feature is ready but not supported in-game.**

I've messaged GGG a handful of times with a proposed solution but it is not implemented in game as of yet. I hope that on public release of this application that GGG will be incentivized to make this easy for benefit of the community.
- Experience gained per map (including a smaller percent of level eg. 0.64% of a level)

---

![Image](http://i.imgur.com/QD9BtpN.png)

Much to come.


text:
<?php

namespace Kunstmaan\FormBundle\AdminList;

use Kunstmaan\AdminBundle\Entity\AbstractEntity;
use Kunstmaan\AdminBundle\Helper\Security\Acl\AclHelper;
use Kunstmaan\AdminListBundle\AdminList\FilterType\ORM\BooleanFilterType;
use Kunstmaan\AdminListBundle\AdminList\FilterType\ORM\StringFilterType;
use Kunstmaan\AdminListBundle\AdminList\Configurator\AbstractDoctrineORMAdminListConfigurator;
use Kunstmaan\AdminBundle\Helper\Security\Acl\Permission\PermissionDefinition;

use Doctrine\ORM\QueryBuilder;
use Doctrine\ORM\EntityManager;

/**
 * Adminlist configuration to list all the form pages
 */
class FormPageAdminListConfigurator extends AbstractDoctrineORMAdminListConfigurator
{

    /**
     * @var string
     */
    protected $permission;

    /**
     * @param EntityManager $em         The entity manager
     * @param AclHelper     $aclHelper  The ACL helper
     * @param string        $permission The permission
     */
    public function __construct(EntityManager $em, AclHelper $aclHelper, $permission)
    {
        parent::__construct($em, $aclHelper);
        $this->setPermissionDefinition(
            new PermissionDefinition(array($permission), 'Kunstmaan\NodeBundle\Entity\Node', 'n')
        );
    }

    /**
     * Configure filters
     */
    public function buildFilters()
    {
        $builder = $this->getFilterBuilder();
        $builder->add('title', new StringFilterType("title"), "Title")
                ->add('online', new BooleanFilterType('online'), 'Online');
    }

    /**
     * Configure the visible columns
     */
    public function buildFields()
    {
        $this->addField("title", "Title", true)
             ->addField("lang", "Language", true)
             ->addField("url", "Form path", true);
    }

    /*
 * Add a view action.
 */
    public function buildItemActions()
    {
        $create_route = function ($item) {
            return array(
                'path'   => 'KunstmaanFormBundle_formsubmissions_list',
                'params' => array('nodeTranslationId' => $item->getId())
            );
        };
        $ia = new \Kunstmaan\AdminListBundle\AdminList\ItemAction\SimpleItemAction($create_route, "eye-open", "View");
        $this->addItemAction($ia);
    }

    /**
     * Return the url to edit the given $item
     *
     * @param mixed $item
     *
     * @return array
     */
    public function getEditUrlFor($item)
    {
        return array(
            'path'   => 'KunstmaanFormBundle_formsubmissions_list',
            'params' => array('nodeTranslationId' => $item->getId())
        );
    }

    /**
     * Return the url to list all the items
     *
     * @return array
     */
    public function getIndexUrl()
    {
        return array('path' => 'KunstmaanFormBundle_formsubmissions');
    }

    /**
     * Configure if it's possible to add new items
     *
     * @return bool
     */
    public function canAdd()
    {
        return false;
    }

    public function canEdit($item)
    {
        return false;
    }

    /**
     * Configure the types of items you can add
     *
     * @param array $params
     *
     * @return array
     */
    public function getAddUrlFor(array $params = array())
    {
        return "";
    }

    /**
     * Configure if it's possible to delete the given $item
     *
     * @param mixed $item
     *
     * @return bool
     */
    public function canDelete($item)
    {
        return false;
    }

    /**
     * Get the delete url for the given $item
     *
     * @param mixed $item
     *
     * @return array
     */
    public function getDeleteUrlFor($item)
    {
        return array();
    }

    /**
     * @return string
     */
    public function getBundleName()
    {
        return 'KunstmaanNodeBundle';
    }

    /**
     * @return string
     */
    public function getEntityName()
    {
        return 'NodeTranslation';
    }

    /**
     * Override controller path (because actions for different entities are defined in a single Settings controller).
     *
     * @return string
     */
    public function getControllerPath()
    {
        return 'KunstmaanFormBundle:FormSubmissions';
    }

    /**
     * @param QueryBuilder $queryBuilder The query builder
     */
    public function adaptQueryBuilder(QueryBuilder $queryBuilder)
    {
        parent::adaptQueryBuilder($queryBuilder);
        $queryBuilder->innerJoin('b.node', 'n', 'WITH', 'b.node = n.id')
            ->andWhere(
                'n.id IN (SELECT m.id FROM Kunstmaan\FormBundle\Entity\FormSubmission s join s.node m)'
            )
            ->addOrderBy('n.sequenceNumber', 'DESC');
    }

}


text:
require 'spec_helper'

describe Recap::Tasks::Env do
  let :config do
    Capistrano::Configuration.new
  end

  let :namespace do
    config.env
  end

  before do
    Recap::Tasks::Env.load_into(config)
  end

  describe 'Settings' do
    describe '#environment_file' do
      it 'defaults to /home/ + application_user + /.env' do
        config.set :application_user, 'marigold'
        config.environment_file.should eql('/home/marigold/.env')
      end
    end
  end

  describe 'Tasks' do
    before do
      config.set :environment_file, 'path/to/.env'
      namespace.stubs(:deployed_file_exists?).with(config.environment_file, '.').returns(true)
      namespace.stubs(:capture).with("cat #{config.environment_file}").returns('')
      namespace.stubs(:puts)
    end

    describe 'env' do
      it 'outputs the current environment if one exists' do
        namespace.stubs(:capture).with("cat #{config.environment_file}").returns("A=b\nX=Y")
        namespace.expects(:puts).with('The config variables are:')
        namespace.expects(:puts).with(responds_with(:to_s, Recap::Support::Environment.from_string("A=b\nX=Y").to_s))
        config.find_and_execute_task('env')
      end
    end

    describe 'env:set' do
      it 'merges the edited environment with the default one' do
        config.set_default_env 'A', 'b'
        namespace.expects(:put_as_app).with(Recap::Support::Environment.from_string("A=b\nX=Y").to_s, config.environment_file)
        namespace.stubs(:env_argv).returns(['X=Y'])
        config.find_and_execute_task('env:set')
      end

      it 'allows overriding of the default environment' do
        config.set_default_env 'A', 'b'
        namespace.expects(:put_as_app).with(Recap::Support::Environment.from_string('A=c').to_s, config.environment_file)
        namespace.stubs(:env_argv).returns(['A=c'])
        config.find_and_execute_task('env:set')
      end

      it 'can unset a variable by assigning an empty value to it' do
        namespace.stubs(:capture).with("cat #{config.environment_file}").returns("X=Y\nA=b")
        namespace.expects(:put_as_app).with(Recap::Support::Environment.from_string('X=Y').to_s, config.environment_file)
        namespace.stubs(:env_argv).returns(['A='])
        config.find_and_execute_task('env:set')
      end

      it 'uploads the new environment' do
        namespace.expects(:put_as_app).with(Recap::Support::Environment.from_string('X=Y').to_s, config.environment_file)
        namespace.stubs(:env_argv).returns(['X=Y'])
        config.find_and_execute_task('env:set')
      end

      it 'removes the environment if it is empty' do
        namespace.stubs(:capture).with("cat #{config.environment_file}").returns("X=Y")
        namespace.expects(:as_app).with("rm -f #{config.environment_file}", '~')
        namespace.stubs(:env_argv).returns(['X='])
        config.find_and_execute_task('env:set')
      end
    end

    describe 'env:reset' do
      it 'removes the environment file from the server' do
        namespace.stubs(:env_argv).returns([])
        namespace.expects(:as_app).with("rm -f #{config.environment_file}", '~').at_least_once
        config.find_and_execute_task('env:reset')
      end
    end

    describe 'env:edit' do
      it 'merges the edited environment with the default one' do
        config.set_default_env 'A', 'b'
        namespace.stubs(:edit_file).returns('X=Y')
        namespace.expects(:put_as_app).with(Recap::Support::Environment.from_string("A=b\nX=Y").to_s, config.environment_file)
        config.find_and_execute_task('env:edit')
      end

      it 'allows overriding of the default environment' do
        config.set_default_env 'A', 'b'
        namespace.stubs(:edit_file).returns('A=c')
        namespace.expects(:put_as_app).with(Recap::Support::Environment.from_string('A=c').to_s, config.environment_file)
        config.find_and_execute_task('env:edit')
      end

      it 'uploads the new environment' do
        namespace.stubs(:edit_file).returns('X=Y')
        namespace.expects(:put_as_app).with(Recap::Support::Environment.from_string('X=Y').to_s, config.environment_file)
        config.find_and_execute_task('env:edit')
      end

      it 'removes the environment if it is empty' do
        namespace.stubs(:edit_file).returns('')
        namespace.expects(:as_app).with("rm -f #{config.environment_file}", '~')
        config.find_and_execute_task('env:edit')
      end
    end
  end
end


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

<title>de.esoco.gwt.client.res Class Hierarchy (esoco-gwt 1.3.0 API)</title>
<meta name="date" content="2018-10-29">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package de.esoco.gwt.client.res

Package Hierarchies:

All Packages

Interface Hierarchy

com.google.gwt.resources.client.ClientBundle

de.esoco.gwt.client.res.EsocoGwtResources

com.google.gwt.resources.client.ResourcePrototype

com.google.gwt.resources.client.CssResourceBase

com.google.gwt.resources.client.CssResource

de.esoco.gwt.client.res.EsocoGwtCss

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is the Mozilla SVG project.
 *
 * The Initial Developer of the Original Code is IBM Corporation.
 * Portions created by the Initial Developer are Copyright (C) 2005
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either of the GNU General Public License Version 2 or later (the "GPL"),
 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

#ifndef __NS_SVGFILTERINSTANCE_H__
#define __NS_SVGFILTERINSTANCE_H__

#include "nsIDOMSVGLength.h"
#include "nsIDOMSVGFilters.h"
#include "nsRect.h"
#include "nsIContent.h"
#include "nsAutoPtr.h"
#include "nsSVGFilters.h"
#include "nsSVGNumber2.h"
#include "nsSVGNumberPair.h"

#include "gfxImageSurface.h"

class nsSVGElement;
class nsSVGFilterElement;
class nsSVGFilterPaintCallback;
struct gfxRect;

/**
 * This class performs all filter processing.
 *
 * We build a graph of the filter image data flow, essentially
 * converting the filter graph to SSA. This lets us easily propagate
 * analysis data (such as bounding-boxes) over the filter primitive graph.
 */
class NS_STACK_CLASS nsSVGFilterInstance
{
public:
  nsSVGFilterInstance(nsIFrame *aTargetFrame,
                      nsSVGFilterPaintCallback *aPaintCallback,
                      nsSVGFilterElement *aFilterElement,
                      const gfxRect &aTargetBBox,
                      const gfxRect& aFilterRect,
                      const nsIntSize& aFilterSpaceSize,
                      const gfxMatrix &aFilterSpaceToDeviceSpaceTransform,
                      const nsIntRect& aTargetBounds,
                      const nsIntRect& aDirtyOutputRect,
                      const nsIntRect& aDirtyInputRect,
                      PRUint16 aPrimitiveUnits) :
    mTargetFrame(aTargetFrame),
    mPaintCallback(aPaintCallback),
    mFilterElement(aFilterElement),
    mTargetBBox(aTargetBBox),
    mFilterSpaceToDeviceSpaceTransform(aFilterSpaceToDeviceSpaceTransform),
    mFilterRect(aFilterRect),
    mFilterSpaceSize(aFilterSpaceSize),
    mTargetBounds(aTargetBounds),
    mDirtyOutputRect(aDirtyOutputRect),
    mDirtyInputRect(aDirtyInputRect),
    mSurfaceRect(nsIntPoint(0, 0), aFilterSpaceSize),
    mPrimitiveUnits(aPrimitiveUnits) {
  }

  // The area covered by temporary images, in filter space
  void SetSurfaceRect(const nsIntRect& aRect) { mSurfaceRect = aRect; }

  gfxRect GetFilterRect() const { return mFilterRect; }

  const nsIntSize& GetFilterSpaceSize() { return mFilterSpaceSize; }
  PRUint32 GetFilterResX() const { return mFilterSpaceSize.width; }
  PRUint32 GetFilterResY() const { return mFilterSpaceSize.height; }

  const nsIntRect& GetSurfaceRect() const { return mSurfaceRect; }
  PRInt32 GetSurfaceWidth() const { return mSurfaceRect.width; }
  PRInt32 GetSurfaceHeight() const { return mSurfaceRect.height; }

  nsresult Render(gfxASurface** aOutput);
  nsresult ComputeOutputDirtyRect(nsIntRect* aDirty);
  nsresult ComputeSourceNeededRect(nsIntRect* aDirty);
  nsresult ComputeOutputBBox(nsIntRect* aBBox);

  float GetPrimitiveNumber(PRUint8 aCtxType, const nsSVGNumber2 *aNumber) const
  {
    return GetPrimitiveNumber(aCtxType, aNumber->GetAnimValue());
  }
  float GetPrimitiveNumber(PRUint8 aCtxType, const nsSVGNumberPair *aNumberPair,
                           nsSVGNumberPair::PairIndex aIndex) const
  {
    return GetPrimitiveNumber(aCtxType, aNumberPair->GetAnimValue(aIndex));
  }
  /**
   * Converts a point and a length in filter primitive units into filter space.
   * For object-bounding-box units, the object bounding box offset is applied
   * to the point.
   */
  void ConvertLocation(float aValues[3]) const;

  gfxMatrix GetUserSpaceToFilterSpaceTransform() const;
  gfxMatrix GetFilterSpaceToDeviceSpaceTransform() const {
    return mFilterSpaceToDeviceSpaceTransform;
  }
  gfxPoint FilterSpaceToUserSpace(const gfxPoint& aPt) const;

private:
  typedef nsSVGFE::Image Image;
  typedef nsSVGFE::ColorModel ColorModel;

  struct PrimitiveInfo {
    nsSVGFE*  mFE;
    // the bounding box of the result image produced by this primitive, in
    // filter space
    nsIntRect mResultBoundingBox;
    // the bounding box of the part of the result image that is actually
    // needed by other primitives or by the filter result, in filter space
    // (used for Render only)
    nsIntRect mResultNeededBox;
    // the bounding box of the part of the result image that could be
    // changed by changes to mDirtyInputRect in the source image(s)
    // (used for ComputeOutputDirtyRect only)
    nsIntRect mResultChangeBox;
    Image     mImage;
    PRInt32   mImageUsers;

    // Can't use nsAutoTArray here, because these Info objects
    // live in nsTArrays themselves and nsTArray moves the elements
    // around in memory, which breaks nsAutoTArray.
    nsTArray<PrimitiveInfo*> mInputs;

    PrimitiveInfo() : mFE(nsnull), mImageUsers(0) {}
  };

  class ImageAnalysisEntry : public nsStringHashKey {
  public:
    ImageAnalysisEntry(KeyTypePointer aStr) : nsStringHashKey(aStr) { }
    ImageAnalysisEntry(const ImageAnalysisEntry& toCopy) : nsStringHashKey(toCopy),
      mInfo(toCopy.mInfo) { }

    PrimitiveInfo* mInfo;
  };

  nsresult BuildSources();
  // Build graph of PrimitiveInfo nodes describing filter primitives
  nsresult BuildPrimitives();
  // Compute bounding boxes of the filter primitive outputs
  void ComputeResultBoundingBoxes();
  // Compute bounding boxes of what we actually *need* from the filter
  // primitive outputs
  void ComputeNeededBoxes();
  // Compute bounding boxes of what could have changed given some changes
  // to the source images.
  void ComputeResultChangeBoxes();
  nsIntRect ComputeUnionOfAllNeededBoxes();
  nsresult BuildSourceImages();

  // Allocates an image surface that covers mSurfaceRect (it uses
  // device offsets so that its origin is positioned at mSurfaceRect.TopLeft()
  // when using cairo to draw into the surface). The surface is cleared
  // to transparent black.
  already_AddRefed<gfxImageSurface> CreateImage();

  void ComputeFilterPrimitiveSubregion(PrimitiveInfo* aInfo);
  void EnsureColorModel(PrimitiveInfo* aPrimitive,
                        ColorModel aColorModel);

  /**
   * Scales a numeric filter primitive length in the X, Y or "XY" directions
   * into a length in filter space (no offset is applied).
   */
  float GetPrimitiveNumber(PRUint8 aCtxType, float aValue) const;

  gfxRect UserSpaceToFilterSpace(const gfxRect& aUserSpace) const;
  void ClipToFilterSpace(nsIntRect* aRect) const
  {
    nsIntRect filterSpace(nsIntPoint(0, 0), mFilterSpaceSize);
    aRect->IntersectRect(*aRect, filterSpace);
  }
  void ClipToGfxRect(nsIntRect* aRect, const gfxRect& aGfx) const;

  nsIFrame*               mTargetFrame;
  nsSVGFilterPaintCallback* mPaintCallback;
  nsSVGFilterElement*     mFilterElement;
  // Bounding box of the target element, in user space
  gfxRect                 mTargetBBox;
  gfxMatrix               mFilterSpaceToDeviceSpaceTransform;
  gfxRect                 mFilterRect;
  nsIntSize               mFilterSpaceSize;
  // Filter-space bounds of the target image (SourceAlpha/SourceGraphic)
  nsIntRect               mTargetBounds;
  nsIntRect               mDirtyOutputRect;
  nsIntRect               mDirtyInputRect;
  nsIntRect               mSurfaceRect;
  PRUint16                mPrimitiveUnits;

  PrimitiveInfo           mSourceColorAlpha;
  PrimitiveInfo           mSourceAlpha;
  nsTArray<PrimitiveInfo> mPrimitives;
};

#endif


text:
<readable><title>2097398349_ff178b3f1b</title><content>
A hiker waves to the camera as he standing in front of snowcapped mountains .
A man stands on the snow near the mountains .
A person poses in the snow .
A person stands in the snow at the top of a mountian , arms raised .
A skier in the mountains .
</content></readable>


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _constant = require('./common/constant');

var _utils = require('./common/utils');

var x = _interopRequireWildcard(_utils);

var _calendar_utils = require('./common/calendar_utils');

var c = _interopRequireWildcard(_calendar_utils);

var _tool = require('./common/tool');

var _bootstrap = require('./style/bootstrap');

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

var RawCalendar = _react2.default.createClass({
    displayName: 'RawCalendar',

    propTypes: {
        // key date determines current month
        mday: _react.PropTypes.object,

        // today
        today: _react.PropTypes.object,

        // callback for state changes after mouse hover & mouse leave & click on dates
        onUpdateState: _react.PropTypes.func,

        // callback for the change of selected date
        onChange: _react.PropTypes.func,

        // a tuple of dates, selection can only be made in the valid range
        validRange: _react.PropTypes.array,

        // a list of selected dates
        selectedDates: _react.PropTypes.array,

        // internal use only, a tuple of dates to show range
        selectedRange: _react.PropTypes.array,

        // customize selected date state change
        selectedReducer: _react.PropTypes.func,

        // calendar select mode, single or multiple. It will use the default select reducer if you don't customize it.
        selectMode: _react.PropTypes.number,

        // whether to show out-of-range dates
        showOutRange: _react.PropTypes.bool,

        // customize styles
        styles: _react.PropTypes.object
    },

    getInitialState: function getInitialState() {
        return {
            selectedDates: [],
            hoveredDate: {}
        };
    },

    componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
        var self = this,
            props_to_state = {
            selectedDates: function selectedDates(a, b) {
                return x.and.apply(null, x.zipWith(function (x, y) {
                    return c.compare_date(x, y) === 0;
                }, a || [], b || []));
            },
            hoveredDate: function hoveredDate(a, b) {
                return c.compare_date(a, b) === 0;
            }
        };

        this.setState((0, _tool.updated_props)(props_to_state, self.props, nextProps));
    },

    componentDidMount: function componentDidMount() {
        this.setState({
            selectedDates: this.props.selectedDates || [],
            hoveredDate: this.props.hoveredDate || {}
        });
    },

    render: function render() {
        var default_selected_reducer = function default_selected_reducer(prev, x) {
            switch (selectMode) {
                case _constant.CALENDAR_SELECT_MODE.SINGLE:
                    return [x];

                case _constant.CALENDAR_SELECT_MODE.MULTIPLE:
                    var index = prev.findIndex(function (d) {
                        return c.date_equal(d, x);
                    }),
                        copy = undefined;

                    return index == -1 ? [].concat(_toConsumableArray(prev), [x]) : (copy = [].concat(_toConsumableArray(prev)), copy.splice(index, 1), copy);

                default:
                    return prev;
            }
        };
        var self = this;
        var _self$props = self.props;
        var selectMode = _self$props.selectMode;
        var _self$props$mday = _self$props.mday;
        var mday = _self$props$mday === undefined ? c.from_system_date(new Date()) : _self$props$mday;
        var _self$props$today = _self$props.today;
        var today = _self$props$today === undefined ? c.from_system_date(new Date()) : _self$props$today;
        var _self$props$validRang = _self$props.validRange;
        var validRange = _self$props$validRang === undefined ? [] : _self$props$validRang;
        var _self$props$selectedR = _self$props.selectedRange;
        var selectedRange = _self$props$selectedR === undefined ? [] : _self$props$selectedR;
        var _self$props$onUpdateS = _self$props.onUpdateState;
        var onUpdateState = _self$props$onUpdateS === undefined ? x.noop : _self$props$onUpdateS;
        var _self$props$onChange = _self$props.onChange;
        var onChange = _self$props$onChange === undefined ? x.noop : _self$props$onChange;
        var _self$props$selectedR2 = _self$props.selectedReducer;
        var selectedReducer = _self$props$selectedR2 === undefined ? default_selected_reducer : _self$props$selectedR2;
        var _self$props$showOutRa = _self$props.showOutRange;
        var showOutRange = _self$props$showOutRa === undefined ? false : _self$props$showOutRa;
        var styles = _self$props.styles;
        var style = _self$props.style;
        var _self$state = self.state;
        var selectedDates = _self$state.selectedDates;
        var hoveredDate = _self$state.hoveredDate;
        var mark_selected = x.map(function (d) {
            var found = selectedDates.find(function (x) {
                return c.date_equal(d, x);
            });
            return (showOutRange || !d.out) && found ? _extends({}, d, { selected: true }) : d;
        });
        var mark_hovered = x.map(function (d) {
            return c.compare_date(hoveredDate, d) === 0 ? _extends({}, d, { hovered: true }) : d;
        });
        var mark_defaulted = x.map(function (d) {
            return (showOutRange || !d.out) && c.date_equal(today, d) ? _extends({}, d, { defaulted: true }) : d;
        });
        var mark_banned = x.map(function (d) {
            return c.date_in_range(d, validRange) ? d : _extends({}, d, { banned: true });
        });
        var mark_range = x.map(function (d) {
            return selectedRange.length !== 0 && (showOutRange || !d.out) && c.date_in_range(d, selectedRange) ? _extends({}, d, { ranged: true }) : d;
        });
        var mark_not_this_month = x.map(function (d) {
            return c.get_month(d) !== c.get_month(mday) ? _extends({}, d, { out: true }) : d;
        });
        var weeks = x.compose(x.group(7), mark_range, mark_selected, mark_hovered, mark_defaulted, mark_banned, mark_not_this_month, c.padding_month_dates)(mday);
        var weekday_title = ['Sun', 'Mon', 'Tue', 'Wed', 'Thur', 'Fri', 'Sat'];
        var notify_state_change = function notify_state_change() {
            onUpdateState(self.state);
        };
        var on_click_date = function on_click_date(date) {
            return function () {
                if (date.banned) return;

                var old_selected = self.state.selectedDates,
                    new_selected = (selectedReducer || default_selected_reducer)(old_selected, date);

                self.setState({
                    selectedDates: new_selected
                }, function () {
                    notify_state_change();

                    if (!c.date_list_equal(old_selected, new_selected)) {
                        onChange(new_selected, old_selected);
                    }
                });
            };
        };
        var on_hover_date = function on_hover_date(date) {
            return function () {
                self.setState({
                    hoveredDate: date
                }, notify_state_change);
            };
        };
        var on_leave_date = function on_leave_date(date) {
            return function () {
                if (c.compare_date(date, self.state.hoveredDate) === 0) {
                    self.setState({ hoveredDate: {} }, notify_state_change);
                }
            };
        };

        styles = Object.assign({}, _bootstrap.calendar_styles, styles || {});

        return _react2.default.createElement(
            'div',
            { style: Object.assign({}, styles.calendar, style) },
            _react2.default.createElement(
                'ul',
                { style: styles.weeks },
                _react2.default.createElement(
                    'li',
                    null,
                    _react2.default.createElement(
                        'ul',
                        { style: styles.week },
                        weekday_title.map(function (t) {
                            return _react2.default.createElement(
                                'li',
                                { key: t, style: (0, _bootstrap.get_style)(styles, ['day', 'weekday_title']) },
                                t
                            );
                        })
                    )
                ),
                weeks.map(function (week) {
                    return _react2.default.createElement(
                        'li',
                        { key: JSON.stringify(week) },
                        _react2.default.createElement(
                            'ul',
                            { style: styles.week },
                            week.map(function (d) {
                                var classes = ['day', d.defaulted ? 'default_day' : '', d.hovered ? 'hovered_day' : '', d.ranged ? 'ranged_day' : '', d.selected ? 'selected_day' : '', d.banned ? 'banned_day' : '', ['lt_month_day', '', 'gt_month_day'][1 + c.compare_month(d, mday)]];

                                return _react2.default.createElement(
                                    'li',
                                    {
                                        key: JSON.stringify(d),
                                        style: (0, _bootstrap.get_style)(styles, classes),
                                        onClick: on_click_date(d),
                                        onMouseEnter: on_hover_date(d),
                                        onMouseLeave: on_leave_date(d)
                                    },
                                    c.get_day(d)
                                );
                            })
                        )
                    );
                })
            )
        );
    }
});

exports.default = RawCalendar;


text:
 confirm("Hello! My name is conversation robot!");
var youAge= prompt("Just between us, what is your age?");
if(youAge>13){console.log("Oh! My maker is just 13 years old.");
}else{console.log("All right, yes, okay.");}
confirm("Right. i am about to ask you a difficult and pointless question!");
var protonNumber= prompt("What is the number of protons in the nucleus of an ununoctium atom?");
if(protonNumber===118){console.log("You got it right!! Amazing!!");
}else{console.log("As i expected... wrong! it is 118.");}

var name= prompt("what is your name?");
if (name===Patrick){console.log("Oh my goodness!!!");
}else{console.log("ah.");
console.log("all right. your name is...");
console.log(name);
console.log("your age is...");
console.log(youAge);
console.log("so... i cannot think of much to say now, goodbye!")


text:
require "spec_helper"

describe Influxer::Client do
  let(:conf) { Influxer.config }
  subject { Influxer.client }

  describe "#initialize" do
    it "sets config database value" do
      expect(subject.config.database).to eq conf.database
    end

    it "passes config params" do
      conf.username = "admin"
      conf.port = 2222
      expect(subject.config.username).to eq "admin"
      expect(subject.config.port).to eq 2222
    end
  end

  describe "cache", :query do
    let(:q) { "list series" }
    after { Rails.cache.clear }

    it "writes data to cache" do
      conf.cache = {}

      subject.query(q)
      expect(Rails.cache.exist?("influxer:listseries")).to be_truthy
    end

    it "should write data to cache with expiration" do
      conf.cache = {expires_in: 90}

      subject.query(q)
      expect(Rails.cache.exist?("influxer:listseries")).to be_truthy

      Timecop.travel(1.minute.from_now)
      expect(Rails.cache.exist?("influxer:listseries")).to be_truthy

      Timecop.travel(2.minutes.from_now)
      expect(Rails.cache.exist?("influxer:listseries")).to be_falsey
    end

    it "does not write data to cache if disabled" do
      conf.cache = {}
      conf.cache_enabled = false

      subject.query(q)
      expect(Rails.cache.exist?("influxer:listseries")).to be_falsey
    end

    it "does not write data to cache without cache config" do
      conf.cache = nil

      subject.query(q)
      expect(Rails.cache.exist?("influxer:listseries")).to be_falsey
    end
  end
end


text:
"""\
Neurospin functions and classes for nipy.

(c) Copyright CEA-INRIA-INSERM, 2003-2009.
Distributed under the terms of the BSD License.

http://www.lnao.fr

functions for fMRI

This module contains several objects and functions for fMRI processing.
"""

from nipy.testing import Tester

# No subpackage should be imported here to avoid run-time errors
# related to missing dependencies or binary incompatibilities

test = Tester().test
bench = Tester().bench


text:
struct _ENetPeer;

namespace bm {

class Enet;
class ClientHost;

// 'Peer' represents a remote transmission point which data packets
// may be sent or received from.
class Peer {
  friend class Event;
  friend class Host;

 public:
  // Queues a packet to be sent. 'data' is the allocated data for the packet.
  // 'length' is the length of the data. 'reliable' is the reliability flag.
  // 'channel_id' is the id of the channel the packet will be sent through.
  // The packet will be sent after calling 'ServerHost::Service()' or
  // 'ClientHost::Service()' methods.
  // Returns 'true' on success, returns 'false' on error.
  BM_NET_DECL bool Send(
    const char* data,
    size_t length,
    bool reliable = true,
    uint8_t channel_id = 0);

  // Returns the ip of the remote peer.
  // An empty string will be returned in case of an error.
  BM_NET_DECL std::string GetIp() const;

  // Returns the port of the remote peer.
  BM_NET_DECL uint16_t GetPort() const;

  // Request a disconnection from a peer.
  // An 'Event::TYPE_DISCONNECT' event will be generated by
  // 'ServerHost::Service()' or 'ClientHost::Service()' once
  // the disconnection is complete.
  BM_NET_DECL void Disconnect();

  // Force an immediate disconnection from a peer.
  // No 'Event::TYPE_DISCONNECT' event will be generated. The foreign peer
  // is not guarenteed to receive the disconnect notification, and is reset
  // immediately upon return from this function.
  BM_NET_DECL void DisconnectNow();

  // Request a disconnection from a peer, but only after all queued outgoing
  // packets are sent.
  // An 'Event::TYPE_DISCONNECT' event will be generated by
  // 'ServerHost::Service()' or 'ClientHost::Service()' once
  // the disconnection is complete.
  BM_NET_DECL void DisconnectLater();

  // Forcefully disconnects a peer. The foreign host represented by the peer
  // is not notified of the disconnection and will timeout on its connection
  // to the local host.
  BM_NET_DECL void Reset();

  // Sets the 'Peer''s internal data, that can be freely modified.
  // If you have two intances of 'Peer' associated with the same '_peer', both
  // of them will have the same internal data.
  BM_NET_DECL void SetData(void* data);

  // Returns the 'Peer's internal data.
  BM_NET_DECL void* GetData() const;

 private:
  // Creates a 'Peer' associated with the ENet peer 'peer'.
  explicit Peer(_ENetPeer* peer);

  _ENetPeer* _peer;

  DISALLOW_COPY_AND_ASSIGN(Peer);
};

}  // namespace bm

#endif  // NET_PEER_H_


text:
require "rack_request_blocker"

module RackRequestBlocker
  describe Middleware do
    before(:each) do
      RackRequestBlocker::Middleware.active_requests.update { 0 }
      RackRequestBlocker::Middleware.allow_requests
    end

    describe "#call" do
      let(:app) { double("Rack application") }

      before(:each) do
        allow(app).to receive(:call)
      end

      it "increments then decrements the active-request count" do
        request_count = double("atomic count")
        count = spy("count value")
        allow(request_count).to receive(:update).and_yield(count)

        middleware = described_class.new(app,
                                         active_requests: request_count)
        middleware.call({})

        expect(count).to have_received(:+).with(1)
        expect(count).to have_received(:-).with(1)
      end

      context "when requests are blocked" do
        before(:each) do
          RackRequestBlocker::Middleware.block_requests
        end

        it "returns a 503 response" do
          middleware = described_class.new(app)
          expect(middleware.call({})).to eq([503, {}, []])
        end

        it "does not send app#call" do
          expect(app).to_not receive(:call)
        end
      end

      context "when requests are not blocked" do
        before(:each) do
          RackRequestBlocker::Middleware.allow_requests
        end

        it "sends app#call" do
          middleware = described_class.new(app)
          expect(app).to receive(:call).with(foo: "bar")
          middleware.call({ foo: "bar" })
        end

        it "does not send app#call" do
          middleware = described_class.new(app)
          allow(app).to receive(:call).and_return([200, {}, %w[foo]])
          expect(middleware.call({})).to eq([200, {}, %w[foo]])
        end
      end
    end
  end
end


text:
//////////////////////////////////////////////////////////////////////////////
/**
 * Create a new instance of vectorFeature
 *
 * @class
 * @extends geo.vectorFeature
 * @extends geo.d3.object
 * @returns {geo.d3.vectorFeature}
 */
//////////////////////////////////////////////////////////////////////////////
geo.d3.vectorFeature = function (arg) {
  'use strict';
  if (!(this instanceof geo.d3.vectorFeature)) {
    return new geo.d3.vectorFeature(arg);
  }
  arg = arg || {};
  geo.vectorFeature.call(this, arg);
  geo.d3.object.call(this);

  ////////////////////////////////////////////////////////////////////////////
  /**
   * @private
   */
  ////////////////////////////////////////////////////////////////////////////
  var m_this = this,
      s_init = this._init,
      s_exit = this._exit,
      s_update = this._update,
      m_buildTime = geo.timestamp(),
      m_style = {},
      m_sticky;

  ////////////////////////////////////////////////////////////////////////////
  /**
   * Generate a unique ID for a marker definition
   * @private
   * @param {object} d Unused datum (for d3 compat)
   * @param {number} i The marker index
   */
  ////////////////////////////////////////////////////////////////////////////
  function markerID(d, i) {
    return m_this._d3id() + '_marker_' + i;
  }

  ////////////////////////////////////////////////////////////////////////////
  /**
   * Add marker styles for vector arrows.
   * @private
   * @param {object[]} data The vector data array
   * @param {function} stroke The stroke accessor
   * @param {function} opacity The opacity accessor
   */
  ////////////////////////////////////////////////////////////////////////////
  function updateMarkers(data, stroke, opacity) {

    var renderer = m_this.renderer();
    var sel = m_this.renderer()._definitions()
      .selectAll('marker.geo-vector')
        .data(data);
    sel.enter()
      .append('marker')
        .attr('id', markerID)
        .attr('class', 'geo-vector')
        .attr('viewBox', '0 0 10 10')
        .attr('refX', '1')
        .attr('refY', '5')
        .attr('markerWidth', '5')
        .attr('markerHeight', '5')
        .attr('orient', 'auto')
        .append('path')
          .attr('d', 'M 0 0 L 10 5 L 0 10 z');

    sel.exit().remove();

    sel.style('stroke', renderer._convertColor(stroke))
      .style('fill', renderer._convertColor(stroke))
      .style('opacity', opacity);
  }

  ////////////////////////////////////////////////////////////////////////////
  /**
   * Initialize
   * @protected
   */
  ////////////////////////////////////////////////////////////////////////////
  this._init = function (arg) {
    s_init.call(m_this, arg);
    m_sticky = m_this.layer().sticky();
    return m_this;
  };

  ////////////////////////////////////////////////////////////////////////////
  /**
   * Build
   * @protected
   */
  ////////////////////////////////////////////////////////////////////////////
  this._build = function () {
    var data = m_this.data(),
        s_style = m_this.style.get(),
        m_renderer = m_this.renderer(),
        orig_func = m_this.origin(),
        size_func = m_this.delta(),
        cache = [],
        scale = m_this.style('scale'),
        max = Number.NEGATIVE_INFINITY;

    // call super-method
    s_update.call(m_this);

    // default to empty data array
    if (!data) { data = []; }

    // cache the georeferencing
    cache = data.map(function (d, i) {
      var origin = m_renderer.worldToDisplay(orig_func(d, i)),
          delta = size_func(d, i);
      max = Math.max(max, delta.x * delta.x + delta.y * delta.y);
      return {
        x1: origin.x,
        y1: origin.y,
        dx: delta.x,
        dy: -delta.y
      };
    });

    max = Math.sqrt(max);
    if (!scale) {
      scale = 75 / max;
    }

    function getScale() {
      return scale / m_renderer.scaleFactor();
    }

    // fill in d3 renderer style object defaults
    m_style.id = m_this._d3id();
    m_style.data = data;
    m_style.append = 'line';
    m_style.attributes = {
      x1: function (d, i) {
        return cache[i].x1;
      },
      y1: function (d, i) {
        return cache[i].y1;
      },
      x2: function (d, i) {
        return cache[i].x1 + getScale() * cache[i].dx;
      },
      y2: function (d, i) {
        return cache[i].y1 + getScale() * cache[i].dy;
      },
      'marker-end': function (d, i) {
        return 'url(#' + markerID(d, i) + ')';
      }
    };
    m_style.style = {
      stroke: function () { return true; },
      strokeColor: s_style.strokeColor,
      strokeWidth: s_style.strokeWidth,
      strokeOpacity: s_style.strokeOpacity
    };
    m_style.classes = ['d3VectorFeature'];

    // Add markers to the defition list
    updateMarkers(data, s_style.strokeColor, s_style.strokeOpacity);

    // pass to renderer to draw
    m_this.renderer()._drawFeatures(m_style);

    // update time stamps
    m_buildTime.modified();
    m_this.updateTime().modified();
    return m_this;
  };

  ////////////////////////////////////////////////////////////////////////////
  /**
   * Update
   * @protected
   */
  ////////////////////////////////////////////////////////////////////////////
  this._update = function () {
    s_update.call(m_this);

    if (m_this.getMTime() >= m_buildTime.getMTime()) {
      m_this._build();
    } else {
      updateMarkers(
        m_style.data,
        m_style.style.strokeColor,
        m_style.style.strokeOpacity
      );
    }

    return m_this;
  };

  ////////////////////////////////////////////////////////////////////////////
  /**
   * Exit
   * @protected
   */
  ////////////////////////////////////////////////////////////////////////////
  this._exit = function () {
    s_exit.call(m_this);
    m_style = {};
    updateMarkers([], null, null);
  };

  this._init(arg);
  return this;
};

inherit(geo.d3.vectorFeature, geo.vectorFeature);

// Now register it
geo.registerFeature('d3', 'vector', geo.d3.vectorFeature);


text:
SpellCheckSelectorDialog::SpellCheckSelectorDialog(QWidget *parent, Qt::WindowFlags f) :
    QDialog(parent, f),
    ui(new Ui::SpellCheckSelectorDialog)
{
    ui->setupUi(this);
    Configuration *conf = Configuration::getInstance();
    const QStringList sl = conf->getAllAvailableSpellCheckDictNames();
    int index = -1;
    QLocale locale;
    for(int i=0; i<sl.length(); i++){
        QString dictName = sl.at(i);
        if(dictName=="en_GB"){
            ui->languageComboBox->addItem("English - United Kingdom", dictName);
        } else if(dictName=="en_US"){
            ui->languageComboBox->addItem("English - United States", dictName);
        } else {
            ui->languageComboBox->addItem(dictName, dictName);
        }
        if(dictName==locale.name())
            index = i;
    }
    if(index==-1 && sl.length()>=1){
        ui->languageComboBox->setCurrentIndex(0);
    }

    connect(ui->buttonBox, SIGNAL(rejected()),
            this, SLOT(close()));
    connect(ui->buttonBox, SIGNAL(accepted()),
            this, SLOT(acceptSlot()));
}

void SpellCheckSelectorDialog::acceptSlot()
{
    language = ui->languageComboBox->itemData(ui->languageComboBox->currentIndex()).toString();
    accept();;
}

QString SpellCheckSelectorDialog::getSpellCheckLanguageName()
{
    return language;
}

SpellCheckSelectorDialog::~SpellCheckSelectorDialog()
{
    delete ui;
}


text:
namespace AngleSharp.Css.Declarations
{
    using AngleSharp.Css.Dom;
    using System;
    using static ValueConverters;

    static class BreakBeforeDeclaration
    {
        public static String Name = PropertyNames.BreakBefore;

        public static IValueConverter Converter = BreakModeConverter;

        public static ICssValue InitialValue = InitialValues.BreakBeforeDecl;

        public static PropertyFlags Flags = PropertyFlags.None;
    }
}


text:
"""Models for django-nose test application.

Based on the Django tutorial:
https://docs.djangoproject.com/en/1.8/intro/tutorial01/
"""

from django.db import models

class Question(models.Model):
    """A poll question."""

    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        """Return string representation."""
        return self.question_text

class Choice(models.Model):
    """A poll answer."""

    question = models.ForeignKey(Question)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        """Return string representation."""
        return self.choice_text


text:
<?php

$data = '
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta name="description" content="TRYDHS - Test Your Code!" />
	<meta name="author" content="" />
	<meta name="keywords" content="" />

	<link href="%in/style/basic.css" type="text/css" rel="stylesheet" media="all" />
	<link id="menu_3" href="%in/bar/menu_3.css" type="text/css" rel="stylesheet" />
	<link href="%in/favicon.ico" rel="shortcut icon" />
	<script type="text/javascript" src="%in/jquery.js"></script>
	<script type="text/javascript" src="%in/jq-json.js"></script>
	<script type="text/javascript" src="%in/jq-corners.js"></script>
	<script type="text/javascript" src="%in/jq-shadow.js"></script>
';

$data = str_replace("%", $pfad_to_home, $data);
echo($data);

?>


text:
package org.killbill.billing.client.actor

import akka.actor.{Actor, ActorRef}
import akka.event.Logging
import spray.client.pipelining._
import spray.http.HttpHeader

import scala.util.{Failure, Success}

/**
  * Created by jgomez on 12/11/2015.
  */
object PluginActor {
  case class PluginGet(uri: String)
  case class PluginHead(uri: String)
  case class PluginPost(uri: String, body: String)
  case class PluginPut(uri: String, body: String)
  case class PluginDelete(uri: String)
  case class PluginOptions(uri: String)
}

case class PluginActor(killBillUrl: String, headers: List[HttpHeader]) extends Actor {

  import PluginActor._

  implicit val system = context.system
  val parent = context.parent
  import system.dispatcher
  val log = Logging(system, getClass)
  def sendAndReceive = sendReceive

  def receive = {
    case PluginGet(uri) =>
      pluginGet(sender, uri)
      context.stop(self)

    case PluginHead(uri) =>
      pluginHead(sender, uri)
      context.stop(self)

    case PluginPost(uri, body) =>
      pluginPost(sender, uri, body)
      context.stop(self)

    case PluginPut(uri, body) =>
      pluginPut(sender, uri, body)
      context.stop(self)

    case PluginDelete(uri) =>
      pluginDelete(sender, uri)
      context.stop(self)

    case PluginOptions(uri) =>
      pluginOptions(sender, uri)
      context.stop(self)
  }

  def pluginPut(originalSender: ActorRef, uri: String, body: String) = {
    log.info("Plugin Put...")

    val pipeline = sendAndReceive

    val responseFuture = pipeline {
      Put(killBillUrl+s"/plugins", body) ~> addHeaders(headers)
    }
    responseFuture.onComplete {
      case Success(response) => {
        if (!response.status.toString().contains("200")) {
          originalSender ! response.entity.asString
        }
        else {
          originalSender ! response.status.toString()
        }
      }
      case Failure(error) => {
        originalSender ! error.getMessage()
      }
    }
  }

  def pluginPost(originalSender: ActorRef, uri: String, body: String) = {
    log.info("Plugin Post...")

    val pipeline = sendAndReceive

    val responseFuture = pipeline {
      Post(killBillUrl+s"/plugins", body) ~> addHeaders(headers)
    }
    responseFuture.onComplete {
      case Success(response) => {
        if (!response.status.toString().contains("201")) {
          originalSender ! response.entity.asString
        }
        else {
          originalSender ! response.status.toString()
        }
      }
      case Failure(error) => {
        originalSender ! error.getMessage()
      }
    }
  }

  def pluginGet(originalSender: ActorRef, uri: String) = {
    log.info("Plugin GET...")
    pluginActions(originalSender, uri, "Get")
  }

  def pluginHead(originalSender: ActorRef, uri: String) = {
    log.info("Plugin HEAD...")
    pluginActions(originalSender, uri, "Head")
  }

  def pluginOptions(originalSender: ActorRef, uri: String) = {
    log.info("Plugin OPTIONS...")
    pluginActions(originalSender, uri, "Options")
  }

  def pluginDelete(originalSender: ActorRef, uri: String) = {
    log.info("Plugin DELETE...")
    pluginActions(originalSender, uri, "Delete")
  }

  def pluginActions(originalSender: ActorRef, uri: String, action: String) = {
    val pipeline = sendAndReceive

    val responseFuture = pipeline {
      action match {
        case "Get" => Get(killBillUrl+s"/plugins/$uri") ~> addHeaders(headers)
        case "Head" => Head(killBillUrl+s"/plugins/$uri") ~> addHeaders(headers)
        case "Options" => Options(killBillUrl+s"/plugins/$uri") ~> addHeaders(headers)
        case "Delete" => Delete(killBillUrl+s"/plugins/$uri") ~> addHeaders(headers)
      }
    }
    responseFuture.onComplete {
      case Success(response) =>
        originalSender ! response
      case Failure(error) =>
        originalSender ! error.getMessage
    }
  }
}


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.yolean.concurrent;

import org.junit.Test;

import java.util.Iterator;
import java.util.Map;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

/**
 * @author baldersheim
 * @since 5.2
 */
public class CopyOnWriteHashMapTest {

    @Test
    public void requireThatAccessorsWork() {
        Map<String, String> map = new CopyOnWriteHashMap<>();
        assertEquals(0, map.size());
        assertEquals(true, map.isEmpty());
        assertEquals(false, map.containsKey("fooKey"));
        assertEquals(false, map.containsValue("fooVal"));
        assertNull(map.get("fooKey"));
        assertNull(map.remove("fooKey"));
        assertEquals(0, map.keySet().size());
        assertEquals(0, map.entrySet().size());
        assertEquals(0, map.values().size());

        map.put("fooKey", "fooVal");
        assertEquals(1, map.size());
        assertEquals(false, map.isEmpty());
        assertEquals(true, map.containsKey("fooKey"));
        assertEquals(true, map.containsValue("fooVal"));
        assertEquals("fooVal", map.get("fooKey"));
        assertEquals(1, map.keySet().size());
        assertEquals(1, map.entrySet().size());
        assertEquals(1, map.values().size());

        map.put("barKey", "barVal");
        assertEquals(2, map.size());
        assertEquals(false, map.isEmpty());
        assertEquals(true, map.containsKey("fooKey"));
        assertEquals(true, map.containsKey("barKey"));
        assertEquals(true, map.containsValue("fooVal"));
        assertEquals(true, map.containsValue("barVal"));
        assertEquals("fooVal", map.get("fooKey"));
        assertEquals("barVal", map.get("barKey"));
        assertEquals(2, map.keySet().size());
        assertEquals(2, map.entrySet().size());
        assertEquals(2, map.values().size());

        assertEquals("fooVal", map.remove("fooKey"));
        assertEquals(1, map.size());
        assertEquals(false, map.isEmpty());
        assertEquals(false, map.containsKey("fooKey"));
        assertEquals(true, map.containsKey("barKey"));
        assertEquals(false, map.containsValue("fooVal"));
        assertEquals(true, map.containsValue("barVal"));
        assertNull(map.get("fooKey"));
        assertEquals("barVal", map.get("barKey"));
        assertEquals(1, map.keySet().size());
        assertEquals(1, map.entrySet().size());
        assertEquals(1, map.values().size());
    }

    @Test
    public void requireThatEntrySetDoesNotReflectConcurrentModifications() {
        Map<String, String> map = new CopyOnWriteHashMap<>();
        map.put("fooKey", "fooVal");

        Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
        assertEquals("fooVal", map.remove("fooKey"));

        assertTrue(it.hasNext());
        Map.Entry<String, String> entry = it.next();
        assertEquals("fooKey", entry.getKey());
        assertEquals("fooVal", entry.getValue());
    }

    @Test
    public void requireThatKeySetDoesNotReflectConcurrentModifications() {
        Map<String, String> map = new CopyOnWriteHashMap<>();
        map.put("fooKey", "fooVal");

        Iterator<String> it = map.keySet().iterator();
        assertEquals("fooVal", map.remove("fooKey"));

        assertTrue(it.hasNext());
        assertEquals("fooKey", it.next());
    }

    @Test
    public void requireThatValuesDoNotReflectConcurrentModifications() {
        Map<String, String> map = new CopyOnWriteHashMap<>();
        map.put("fooKey", "fooVal");

        Iterator<String> it = map.values().iterator();
        assertEquals("fooVal", map.remove("fooKey"));

        assertTrue(it.hasNext());
        assertEquals("fooVal", it.next());
    }
}


text:
proskate-frontol-discount
=========================


text:
const gcm = require('node-gcm');
const R = require('ramda');
const { DEFAULT_TTL, GCM_METHOD, GCM_MAX_TTL } = require('./constants');

const ttlFromExpiry = R.compose(
  R.min(GCM_MAX_TTL),
  (expiry) => expiry - Math.floor(Date.now() / 1000)
);

const extractTimeToLive = R.cond([
  [R.propIs(Number, 'expiry'), ({ expiry }) => ttlFromExpiry(expiry)],
  [R.propIs(Number, 'timeToLive'), R.prop('timeToLive')],
  [R.T, R.always(DEFAULT_TTL)],
]);

const pathIsString = R.pathSatisfies(R.is(String));

const containsValidRecipients = R.either(
  pathIsString(['recipients', 'to']),
  pathIsString(['recipients', 'condition'])
);

const propValueToSingletonArray = (propName) =>
  R.compose(R.of, R.prop(propName));

const getRecipientList = R.cond([
  [R.has('registrationTokens'), R.prop('registrationTokens')],
  [R.has('to'), propValueToSingletonArray('to')],
  [R.has('condition'), propValueToSingletonArray('condition')],
]);

const sendChunk = (GCMSender, recipients, message, retries) =>
  new Promise((resolve) => {
    const recipientList = getRecipientList(recipients);

    GCMSender.send(message, recipients, retries, (err, response) => {
      // Response: see https://developers.google.com/cloud-messaging/http-server-ref#table5
      if (err) {
        resolve({
          method: GCM_METHOD,
          success: 0,
          failure: recipientList.length,
          message: recipientList.map((value) => ({
            originalRegId: value,
            regId: value,
            error: err,
            errorMsg: err instanceof Error ? err.message : err,
          })),
        });
      } else if (response && response.results !== undefined) {
        let regIndex = 0;
        resolve({
          method: GCM_METHOD,
          multicastId: response.multicast_id,
          success: response.success,
          failure: response.failure,
          message: response.results.map((value) => {
            const regToken = recipientList[regIndex];
            regIndex += 1;
            return {
              messageId: value.message_id,
              originalRegId: regToken,
              regId: value.registration_id || regToken,
              error: value.error ? new Error(value.error) : null,
              errorMsg: value.error ? value.error.message || value.error : null,
            };
          }),
        });
      } else {
        resolve({
          method: GCM_METHOD,
          multicastId: response.multicast_id,
          success: response.success,
          failure: response.failure,
          message: recipientList.map((value) => ({
            originalRegId: value,
            regId: value,
            error: new Error('unknown'),
            errorMsg: 'unknown',
          })),
        });
      }
    });
  });

const sendGCM = (regIds, data, settings) => {
  const opts = { ...settings.gcm };
  const { id } = opts;
  delete opts.id;
  const GCMSender = new gcm.Sender(id, opts);
  const promises = [];
  const notification = {
    title: data.title, // Android, iOS (Watch)
    body: data.body, // Android, iOS
    icon: data.icon, // Android
    image: data.image, // Android
    picture: data.picture, // Android
    style: data.style, // Android
    sound: data.sound, // Android, iOS
    badge: data.badge, // iOS
    tag: data.tag, // Android
    color: data.color, // Android
    click_action: data.clickAction || data.category, // Android, iOS
    body_loc_key: data.locKey, // Android, iOS
    body_loc_args: data.locArgs, // Android, iOS
    title_loc_key: data.titleLocKey, // Android, iOS
    title_loc_args: data.titleLocArgs, // Android, iOS
    android_channel_id: data.android_channel_id, // Android
    notification_count: data.notificationCount || data.badge, // Android
  };

  let custom;
  if (typeof data.custom === 'string') {
    custom = {
      message: data.custom,
    };
  } else if (typeof data.custom === 'object') {
    custom = { ...data.custom };
  } else {
    custom = {
      data: data.custom,
    };
  }

  custom.title = custom.title || data.title;
  custom.message = custom.message || data.body;
  custom.sound = custom.sound || data.sound;
  custom.icon = custom.icon || data.icon;
  custom.msgcnt = custom.msgcnt || data.badge;
  if (opts.phonegap === true && data.contentAvailable) {
    custom['content-available'] = 1;
  }

  const message = new gcm.Message({
    // See https://developers.google.com/cloud-messaging/http-server-ref#table5
    collapseKey: data.collapseKey,
    priority: data.priority === 'normal' ? 'normal' : 'high',
    contentAvailable: data.silent ? true : data.contentAvailable || false,
    delayWhileIdle: data.delayWhileIdle || false,
    timeToLive: extractTimeToLive(data),
    restrictedPackageName: data.restrictedPackageName,
    dryRun: data.dryRun || false,
    data: opts.phonegap === true ? Object.assign(custom, notification) : custom, // See https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/PAYLOAD.md#android-behaviour
    notification:
      opts.phonegap === true || data.silent === true ? undefined : notification,
  });
  let chunk = 0;

  /* allow to override device tokens with custom `to` or `condition` field:
   * https://github.com/ToothlessGear/node-gcm#recipients */
  if (containsValidRecipients(data)) {
    promises.push(
      sendChunk(GCMSender, data.recipients, message, data.retries || 0)
    );
  } else {
    // Split tokens in 1.000 chunks, see https://developers.google.com/cloud-messaging/http-server-ref#table1
    do {
      const registrationTokens = regIds.slice(chunk * 1000, (chunk + 1) * 1000);
      promises.push(
        sendChunk(GCMSender, { registrationTokens }, message, data.retries || 0)
      );
      chunk += 1;
    } while (1000 * chunk < regIds.length);
  }

  return Promise.all(promises).then((results) => {
    const resumed = {
      method: GCM_METHOD,
      multicastId: [],
      success: 0,
      failure: 0,
      message: [],
    };

    results.forEach((result) => {
      if (result.multicastId) {
        resumed.multicastId.push(result.multicastId);
      }
      resumed.success += result.success;
      resumed.failure += result.failure;
      resumed.message.push(...result.message);
    });

    return resumed;
  });
};

module.exports = sendGCM;


text:
CustomParser::CustomParser(): Parser()
{

}

CustomParser::~CustomParser()
{

}

Savvy::ResultCode CustomParser::ParseToken(Savvy::uint32 a_Token, std::string& a_TokenName)
{
	return Savvy::SAVVY_OK;
}

void CustomParser::Reset()
{

}

Savvy::ResultCode CustomParser::Initialize(Savvy::Database* a_Database)
{
	return Savvy::Parser::Initialize(a_Database);
}


text:
package br.unicamp.cst.trafficUnjammer.experiments.entity;

import java.io.Serializable;
import java.util.ArrayList;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

/**
 * @author andre
 *
 */
@JsonIgnoreProperties(ignoreUnknown=true)
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class ControlledLanesIDs implements Serializable
{
	private static final long serialVersionUID = 7105295659607280687L;

	private ArrayList<String> controlledIncomingLanesIDs;

	private ArrayList<String> controlledOutgoingLanesIDs;

	private String phaseIncomingLanes;

	/**
	 * @return the controlledIncomingLanesIDs
	 */
	public synchronized ArrayList<String> getControlledIncomingLanesIDs()
	{
		return controlledIncomingLanesIDs;
	}

	/**
	 * @param controlledIncomingLanesIDs the controlledIncomingLanesIDs to set
	 */
	public synchronized void setControlledIncomingLanesIDs(ArrayList<String> controlledIncomingLanesIDs)
	{
		this.controlledIncomingLanesIDs = controlledIncomingLanesIDs;
	}

	/**
	 * @return the controlledOutgoingLanesIDs
	 */
	public synchronized ArrayList<String> getControlledOutgoingLanesIDs()
	{
		return controlledOutgoingLanesIDs;
	}

	/**
	 * @param controlledOutgoingLanesIDs the controlledOutgoingLanesIDs to set
	 */
	public synchronized void setControlledOutgoingLanesIDs(ArrayList<String> controlledOutgoingLanesIDs)
	{
		this.controlledOutgoingLanesIDs = controlledOutgoingLanesIDs;
	}

	/**
	 * @return the phaseIncomingLanes
	 */
	public synchronized String getPhaseIncomingLanes() {
		return phaseIncomingLanes;
	}

	/**
	 * @param phaseIncomingLanes the phaseIncomingLanes to set
	 */
	public synchronized void setPhaseIncomingLanes(String phaseIncomingLanes) {
		this.phaseIncomingLanes = phaseIncomingLanes;
	}
}


text:
require 'prometheus/client'
require 'prometheus/client/counter'
require 'examples/metric_example'
require 'prometheus/client/data_stores/direct_file_store'

describe Prometheus::Client::Counter do
  # Reset the data store
  before do
    Prometheus::Client.config.data_store = Prometheus::Client::DataStores::Synchronized.new
  end

  let(:expected_labels) { [] }

  let(:counter) do
    Prometheus::Client::Counter.new(:foo,
                                    docstring: 'foo description',
                                    labels: expected_labels)
  end

  it_behaves_like Prometheus::Client::Metric

  describe '#increment' do
    it 'increments the counter' do
      expect do
        counter.increment
      end.to change { counter.get }.by(1.0)
    end

    context "with a an expected label set" do
      let(:expected_labels) { [:test] }

      it 'increments the counter for a given label set' do
        expect do
          expect do
            counter.increment(labels: { test: 'label' })
          end.to change { counter.get(labels: { test: 'label' }) }.by(1.0)
        end.to_not change { counter.get(labels: { test: 'other' }) }
      end
    end

    it 'increments the counter by a given value' do
      expect do
        counter.increment(by: 5)
      end.to change { counter.get }.by(5.0)
    end

    it 'raises an ArgumentError on negative increments' do
      expect do
        counter.increment(by: -1)
      end.to raise_error ArgumentError
    end

    it 'returns the new counter value' do
      expect(counter.increment).to eql(1.0)
    end

    it 'is thread safe' do
      expect do
        Array.new(10) do
          Thread.new do
            10.times { counter.increment }
          end
        end.each(&:join)
      end.to change { counter.get }.by(100.0)
    end
  end
end


text:
LaTeX input:        mmd-mavrldoc-header
Title:              NANO266 General Lab Instructions
Author:             Shyue Ping Ong
Affiliation:        University of California, San Diego
Address:            9500 Gilman Drive, Mail Code 0448, La Jolla, CA 92093-0448
Web:                http://www.materialsvirtuallab.org
Base Header Level:  2
LaTeX Mode:         mavrldoc
LaTeX input:        mmd-mavrldoc-begin-doc
LaTeX footer:       mmd-mavrldoc-footer

# Introduction

Welcome to the lab sessions for NANO266. Before you begin, you should read this
carefully and follow all instructions to make sure that your computer /
computing resource is set up properly. Your instructors are on hand to help you
if you run into any problems.

# First Principles Modeling Codes

In the labs, we will be using two open-source first principles modeling codes:

1. NWchem (http://www.nwchem-sw.org) is a computational chemistry code that
   aims to be scalable both in their ability to treat large scientific
   computational chemistry problems efficiently.
2. QuantumEspresso (http://www.quantum-espresso.org/) is an integrated suite of
   computer codes for electronic-structure calculations and materials modeling
   at the nanoscale. It is based on density-functional theory, plane waves, and
   pseudopotentials.

Before you start any of the labs, make sure that you have the software
installed and in your path. You have four options:

## Option 1: Use XSEDE

![XSEDE user portal](XSEDEUserPortal.png)

We have secured an XSEDE allocation for this course. Please go the the XSEDE
portal (https://portal.xsede.org) and create an account as shown above.
After you have done so, email your username to one of the TAs to be added
to the allocation for this course. You can then login to the allocations
with

```bash
ssh <your_username>@comet.sdsc.edu
```

If you are on a Windows machine, you need to download a SSH client like
[PuTTY](http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html).
Once you are logged in, immediately run

```bash
module load qe nwchem python
export NWCHEM_BASIS_LIBRARY=/opt/nwchem/data/libraries/
```

to make sure that QuantumEspresso, NWChem and Python are loaded for you and
that the libraries are set properly. You can also add these two lines to
your `.bash_profile` so that it will always be loaded for you when you login.

## Option 2: Set up your own Mac

If you have your own Mac, you can use the executables already included in
this repo (see cloning the repo section). Run the following command to add
the bin directory to your path as follows (assuming you are on bash):

```bash
export PATH=$PATH:<path/to/repo>/bin/Mac
# The following is to set the NWChem basis sets used in lab1.
# Be careful that the ending slash is needed!
export NWCHEM_BASIS_LIBRARY = <path/to/repo>/resources/nwchem_basis/
```

## Option 3: Use a Virtual Machine

You can download VirtualBox (https://www.virtualbox.org/), and a
pre-configured Ubuntu virtual machine at this [link](https://s3.amazonaws.com/mavrl-web/nano266.ova).

Note that it is a hefty 3 Gb download, so you will want to download this on
a fast connection. After launching VirtualBox, do File->Import Appliance and
then select the downloaded `nano266.ova` file. You can then start the
virtual machine. You should be able to login to the virtual machine without
a password. If one is ever needed, it is simply "nano266fun". Start a
terminal by clicking on the icon on the left. By typing `ls`, you should see
that a nano266 directory is already cloned for you. Simply `cd nano266` and
you are ready to begin to do the labs.

## Option 4: Compile your own

You can download the source code for QuantumEspresso or NWChem and install
it yourself. *Attempt this only if you have a fairly good familiarity with
compiling things on Unix-based OSes, or are willing to spend the time to
figure it out!* If you foresee you will be working on such calculations
extensively in future, it is generally useful for you to learn how to do
this. Start with the QuantumEspresso code as it is more straightforward to
compile.

In general, it is not recommended that you run on a native Windows OS for these
labs. Most first principles codes are designed to run primarily on
supercomputing clusters that have Unix-based OSes. If you have a Windows
machine, you should try options 1 or 3 above.

# Cloning the repo

On wherever you are performing the calculations for the lab, you should clone
this repo by doing:

```
git clone https://github.com/materialsvirtuallab/nano266.git
```

Check that you have the repo cloned successfully by doing a `ls`. If you are
using XSEDE, make sure that you do the git clone in your home folder, i.e.,
the folder that you are in when you first log into XSEDE. This makes following
the rest of the instructions much easier.

This assumes you already have git installed, which comes by default in XSEDE
and Mac and can easily be installed in Unix-based OSes. To update your repo to
the latest version at any time, you can do:

```
git pull
```

from within the repo.

# Using a Unix-based terminal

If you have never used a Unix-based terminal, there is a bit of a slight
learning curve. But in general, you will be working with only four or five
commands:

```bash
cd <dirname>       # change directory to <dirname>
cp <file1> <file2> # copies <file1> to <file2>
mv <file1> <file2> # moves <file1> to <file2>
rm <file>          # remove <file>
```

You will also be doing some basic text editing in the terminal. For beginners,
the `nano` command line editor has the smallest learning curve. Other options
are `vi` and `emacs`.

Finally, you will need to get your results over to your local computer to do
analysis. The easiest way to do this is with:

```bash
scp <username>@trestles.sdsc.edu:~/nano266/location/of/file .
```

in your local Mac or Linux terminal. If you are on Windows, the equivalent is
[pscp](http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html).

# Programming in Python

A lot of the labs use Python as a scripting language for automating
calculations and analysis. You should ensure that you have Python 2.7.x
installed with numpy. If you have a Mac, this should be already the case. If
you use the virtual machine, it is also already set up.

If you don't know Python, get a quick primer from the official [Python
documentation](https://docs.python.org/2.7/). You do not really need to know
much more than the basics for the purposes of the labs. Learning how to use a
scripting language like Python can save you loads of time in automating
calculations.


text:
import Hat = require('../src/hat');

describe('hello', function():any {
    it('world', function():any {
        var hat:any = new Hat('World');
        var str:any = hat.go();
        expect(str).toEqual('World');
    });
});


text:
package Structural.Adapter.Switch;

import Structural.Adapter.Engine.VehicleEngine;

/**
 *
 * @author argshub
 */
public class BikeSwitch implements VehicleSwitch {
 private VehicleEngine engine;

    public BikeSwitch(VehicleEngine engine) {
        this.engine = engine;
    }

    @Override
    public void startEngine() {
        this.engine.startSpin();
    }

    @Override
    public void stopEngine() {
        this.engine.stopSpin();
    }
}


text:
ReactJsNewsTut
==============

A simple [tutorial for React JS News](https://reactjsnews.com/making-react-make-sense/).

This repo contains the example code from the tutorial series.


text:
package connectivity.utility;

import java.util.HashMap;

/**
 *
 * @author Leif Andreas Rudlang
 * @version 1.0
 * @date 22.01.2014
 */
public class ConfigReader {

	private static final String NOT_FOUND = "File not found: ";
	private static final String LINE_COMMENT = "//";
	private static final String LINE_SPACE = " ";

	private String location;
	private HashMap<String,String> values;
	private int size;
	private boolean hasConfig;
	private String line_separator;

	/**
	 *
	 */
	public ConfigReader(){
		clear();
	}

	/**
	 *
	 * @param configlocation
	 */
	public ConfigReader(String configlocation){

		clear();

		this.location = configlocation;
		hasConfig = read(location);
	}

	/**
	 * Clears the configuration reader
	 */
	public void clear(){

		location = "";
		line_separator = Utility.getLineSeparator("");
		values = new HashMap<String,String>();
		hasConfig = false;
		size = 0;
	}

	/**
	 *
	 * @param path
	 * @return
	 */
	public boolean read(String path){

		this.location = path;
		String config = Utility.readFile(location);

		if(config == null || config.isEmpty() || config.contains(NOT_FOUND)){
			return false;
		}

		line_separator = Utility.getLineSeparator(config);

		String[] lines = config.split(line_separator);
		String parameter = "";
		String name = "";

		if(lines.length <= 0){
			return false;
		}

		for(String line : lines){

			if(line == null || line.isEmpty()){
				continue;
			}

			String[] expl = line.split(LINE_SPACE);

			if(expl.length > 1){

				name = expl[0];
				parameter = expl[1];

				if(!valueExists(name) && !name.contains(LINE_COMMENT)){
					size++;
					values.put(name, parameter);
				}
			}

		}

		return true;
	}

	public void write(String path){

		Utility.writeFile(path, this.toString());
	}

	/**
	 *
	 * @param key
	 * @return
	 */
	public boolean valueExists(String key){

		return values.containsKey(key);
	}

	/**
	 *
	 * @param key
	 * @return
	 */
	public String getValue(String key){

		return values.get(key);
	}

	public void setValue(String key, String param){

		values.put(key, param);
	}

	/**
	 *
	 * @return
	 */
	public boolean hasConfiguration(){

		return hasConfig;
	}

	/**
	 *
	 * @return
	 */
	public int size(){

		return size;
	}

	/**
	 *
	 * @return
	 */
	public boolean isEmpty(){

		return values.isEmpty();
	}

	/**
	 *
	 * @return
	 */
	public String lastPath(){

		return location;
	}

	@Override
	public String toString(){

		StringBuilder str = new StringBuilder();

		for(String key : values.keySet()){

			str.append(key+" "+getValue(key)+line_separator);
		}

		return str.toString();
	}

}


text:
package vxlan

import (
	"strconv"

	"github.com/pkg/errors"

	"github.com/networkservicemesh/networkservicemesh/controlplane/api/connection"
	"github.com/networkservicemesh/networkservicemesh/controlplane/api/connection/mechanisms/common"
)

// Mechanism - a vxlan mechanism utility wrapper
type Mechanism interface {
	// SrcIP -  src ip
	SrcIP() (string, error)
	// DstIP - dst ip
	DstIP() (string, error)
	// VNI - vni
	VNI() (uint32, error)
}

type mechanism struct {
	*connection.Mechanism
}

// ToMechanism - convert unified mechanism to useful wrapper
func ToMechanism(m *connection.Mechanism) Mechanism {
	if m.Type == MECHANISM {
		return &mechanism{
			m,
		}
	}
	return nil
}

func (m *mechanism) SrcIP() (string, error) {
	return common.GetSrcIP(m.Mechanism)
}

func (m *mechanism) DstIP() (string, error) {
	return common.GetDstIP(m.Mechanism)
}

// VNI returns the VNI parameter of the Mechanism
func (m *mechanism) VNI() (uint32, error) {
	if m == nil {
		return 0, errors.New("mechanism cannot be nil")
	}

	if m.GetParameters() == nil {
		return 0, errors.Errorf("mechanism.Parameters cannot be nil: %v", m)
	}

	vxlanvni, ok := m.Parameters[VNI]
	if !ok {
		return 0, errors.Errorf("mechanism.Type %s requires mechanism.Parameters[%s]", m.GetType(), VNI)
	}

	vni, err := strconv.ParseUint(vxlanvni, 10, 24)

	if err != nil {
		return 0, errors.Wrapf(err, "mechanism.Parameters[%s] must be a valid 24-bit unsigned integer, instead was: %s: %v", VNI, vxlanvni, m)
	}

	return uint32(vni), nil
}