text:
<?php

namespace ZF\OAuth2\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * AuthorizationCode
 */
class AuthorizationCode
{
    /**
     * @var string
     */
    private $authorizationCode;

    /**
     * @var string
     */
    private $redirectUri;

    /**
     * @var \DateTime
     */
    private $expires;

    /**
     * @var string
     */
    private $idToken;

    /**
     * @var integer
     */
    private $id;

    /**
     * @var \ZF\OAuth2\Entity\Client
     */
    private $client;

    /**
     * @var \Doctrine\Common\Collections\Collection
     */
    private $scope;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->scope = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Set authorizationCode
     *
     * @param string $authorizationCode
     * @return AuthorizationCode
     */
    public function setAuthorizationCode($authorizationCode)
    {
        $this->authorizationCode = $authorizationCode;

        return $this;
    }

    /**
     * Get authorizationCode
     *
     * @return string
     */
    public function getAuthorizationCode()
    {
        return $this->authorizationCode;
    }

    /**
     * Set redirectUri
     *
     * @param string $redirectUri
     * @return AuthorizationCode
     */
    public function setRedirectUri($redirectUri)
    {
        $this->redirectUri = $redirectUri;

        return $this;
    }

    /**
     * Get redirectUri
     *
     * @return string
     */
    public function getRedirectUri()
    {
        return $this->redirectUri;
    }

    /**
     * Set expires
     *
     * @param \DateTime $expires
     * @return AuthorizationCode
     */
    public function setExpires($expires)
    {
        $this->expires = $expires;

        return $this;
    }

    /**
     * Get expires
     *
     * @return \DateTime
     */
    public function getExpires()
    {
        return $this->expires;
    }

    /**
     * Set idToken
     *
     * @param string $idToken
     * @return AuthorizationCode
     */
    public function setIdToken($idToken)
    {
        $this->idToken = $idToken;

        return $this;
    }

    /**
     * Get idToken
     *
     * @return string
     */
    public function getIdToken()
    {
        return $this->idToken;
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set client
     *
     * @param \ZF\OAuth2\Entity\Client $client
     * @return AuthorizationCode
     */
    public function setClient(\ZF\OAuth2\Entity\Client $client)
    {
        $this->client = $client;

        return $this;
    }

    /**
     * Get client
     *
     * @return \ZF\OAuth2\Entity\Client
     */
    public function getClient()
    {
        return $this->client;
    }

    /**
     * Add scope
     *
     * @param \ZF\OAuth2\Entity\Scope $scope
     * @return AuthorizationCode
     */
    public function addScope(\ZF\OAuth2\Entity\Scope $scope)
    {
        $this->scope[] = $scope;

        return $this;
    }

    /**
     * Remove scope
     *
     * @param \ZF\OAuth2\Entity\Scope $scope
     */
    public function removeScope(\ZF\OAuth2\Entity\Scope $scope)
    {
        $this->scope->removeElement($scope);
    }

    /**
     * Get scope
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getScope()
    {
        return $this->scope;
    }
}


text:
<?php

/**
 * Adminhtml grid widget massaction item additional action default
 *
 * @category   Mage
 * @package    Mage_Adminhtml
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Adminhtml_Block_Widget_Grid_Massaction_Item_Additional_Default extends Mage_Adminhtml_Block_Widget_Form implements Mage_Adminhtml_Block_Widget_Grid_Massaction_Item_Additional_Interface
{

    public function createFromConfiguration(array $configuration)
    {
        $form = new Varien_Data_Form();

        foreach ($configuration as $itemId=>$item) {
            $item['class'] = isset($item['class']) ? $item['class'] . ' absolute-advice' : 'absolute-advice';
            $form->addField($itemId, $item['type'], $item);
        }
        $this->setForm($form);
        return $this;
    }

}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/home/silver/桌面/CameraManager-master/lib/src/main/res/values-large/dimens.xml -->
    <eat-comment/>
    <dimen name="crop__bar_height">64dp</dimen>
</resources>


text:
 <div
   ng-repeat="(colRenderIndex, col) in colContainer.renderedColumns track by col.uid"
   ui-grid-one-bind-id-grid="rowRenderIndex + '-' + col.uid + '-cell'"
   class="ui-grid-cell"
   ng-class="{ 'ui-grid-row-header-cell': col.isRowHeader }"
   role="{{col.isRowHeader ? 'rowheader' : 'gridcell'}}"
   ui-grid-cell></div>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
 Copyright 2013 The Android Open Source Project

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->
<resources>
    <string name="app_name">Flashlight</string>
    <string name="intro_message">
        <![CDATA[

            Wearable activity that uses your wearable screen as a flashlight. There is also
            a party-mode option, if you want to make things interesting.

        ]]>
    </string>
</resources>


text:
package com.tinkerpop.gremlin.server.handler;

import com.tinkerpop.gremlin.driver.MessageSerializer;
import com.tinkerpop.gremlin.driver.message.RequestMessage;
import com.tinkerpop.gremlin.driver.ser.SerializationException;
import com.tinkerpop.gremlin.driver.ser.Serializers;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;

/**
 * @author Stephen Mallette (http://stephen.genoprime.com)
 */
public class NioGremlinBinaryRequestDecoder extends ByteToMessageDecoder {
    private static final Logger logger = LoggerFactory.getLogger(WsGremlinBinaryRequestDecoder.class);

    private static final Charset UTF8 = Charset.forName("UTF-8");
    private final Map<String, MessageSerializer> serializers;

    public NioGremlinBinaryRequestDecoder(final Map<String, MessageSerializer> serializers) {
        this.serializers = serializers;
    }

    @Override
    protected void decode(final ChannelHandlerContext channelHandlerContext, final ByteBuf byteBuf, final List<Object> objects) throws Exception {
        if (byteBuf.readableBytes() < 1) {
            return;
        }

        final byte lenOfContentType = byteBuf.readByte();
        if (byteBuf.readableBytes() < lenOfContentType) {
            byteBuf.resetReaderIndex();
            return;
        }

        final ByteBuf contentTypeBytes = channelHandlerContext.alloc().buffer(lenOfContentType);
        try {
            byteBuf.readBytes(contentTypeBytes);
            final String contentType = contentTypeBytes.toString(UTF8);
            final MessageSerializer serializer = select(contentType, Serializers.DEFAULT_REQUEST_SERIALIZER);

            channelHandlerContext.channel().attr(StateKey.SERIALIZER).set(serializer);
            channelHandlerContext.channel().attr(StateKey.USE_BINARY).set(true);
            try {
                objects.add(serializer.deserializeRequest(byteBuf.discardReadBytes()));
            } catch (SerializationException se) {
                objects.add(RequestMessage.INVALID);
            }
        } finally {
            contentTypeBytes.release();
        }
    }

    public MessageSerializer select(final String mimeType, final MessageSerializer defaultSerializer) {
        if (logger.isWarnEnabled() && !serializers.containsKey(mimeType))
            logger.warn("Gremlin Server is not configured with a serializer for the requested mime type [{}] - using {} by default",
                    mimeType, defaultSerializer.getClass().getName());

        return serializers.getOrDefault(mimeType, defaultSerializer);
    }
}


text:
<?php

/* FdrAdminBundle:TypePrestation:new.html.twig */
class __TwigTemplate_8a0cbaf6ceaae7e2e7d99d468259077be68c8d1c33b6481660bfb50a3b615c6b extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        // line 1
        try {
            $this->parent = $this->env->loadTemplate("::base.html.twig");
        } catch (Twig_Error_Loader $e) {
            $e->setTemplateFile($this->getTemplateName());
            $e->setTemplateLine(1);

            throw $e;
        }

        $this->blocks = array(
            'title' => array($this, 'block_title'),
            'body' => array($this, 'block_body'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "::base.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 2
    public function block_title($context, array $blocks = array())
    {
        echo "TypePrestation|New";
    }

    // line 3
    public function block_body($context, array $blocks = array())
    {
        // line 4
        echo "

 Modification d'un TypePrestation

";
        // line 8
        echo         $this->env->getExtension('form')->renderer->renderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'form_start');
        echo "

";
        // line 10
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'errors');
        echo "

<fieldset>
<legend>Formulaire d'ajout</legend>

";
        // line 21
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "libelle", array()), 'label', array("label" => " Libelle "));
        echo "

";
        // line 22
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "libelle", array()), 'widget');
        echo "";
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "libelle", array()), 'errors');
        echo "

</fieldset>

";
        // line 30
        echo         $this->env->getExtension('form')->renderer->renderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'form_end');
        echo "
";
    }

    public function getTemplateName()
    {
        return "FdrAdminBundle:TypePrestation:new.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  88 => 30,  75 => 22,  71 => 21,  57 => 10,  52 => 8,  46 => 4,  43 => 3,  37 => 2,  11 => 1,);
    }
}


text:
.antispam-div {
    display: none;
}

.recaptcha-contact {
    width: 50%;
    margin: 0;
}

.recaptcha-contact .button {
    float: right;
    margin: 5px;
}

.recaptcha-contact .alert {
    border: 1px solid #ccc;
    background-color: #fafafa;
    padding: 10px;
}

.recaptcha-contact .alert.success {
    border-color: #558042;
    background-color: #F4FBF1;
}

.recaptcha-contact .alert.error,
.recaptcha-contact .alert.fail {
    border-color: #B67272;
    background-color: #FBF1F1;
}

.recaptcha-contact .alert p {
    margin: 0;
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <link href="dist/app.css" rel="stylesheet">
    <title>Armagetron Advanced Authority Generator</title>

Extract Global IDs

Paste the teams list into the text field. Global IDs will be found and extracted from the text.

Verify & Edit

Click a name to edit it.

Publish

About

Created by dlh@forums.

Source code

Forums thread


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Grevillea 22(no. 104): 97 (1893)

#### Original name
Ascobolus barbatus Massee & Crossl., 1893

### Remarks
null


text:
<?php

namespace houdunwang\lang\build;

use houdunwang\arr\Arr;
use houdunwang\config\Config;

class Base
{
    //语句包
    private $language;

    public function __construct()
    {
        $this->language = include(Config::get('lang.lang'));
    }

    /**
     * 语言包文件
     *
     * @param $file
     */
    public function file($file)
    {
        $this->language = include $file;
    }

    //获取语言
    public function get($lang)
    {
        return Arr::get($this->language, $lang);
    }

    //设置单个语言
    public function set($name, $value)
    {
        $this->language = Arr::set($this->language, $name, $value);

        return true;
    }
}


text:
import Example from './CarouselExample';
// eslint-disable-next-line import/extensions
import CarouselExample from '!!raw-loader!./CarouselExample';

Example.args = {
  dark: false,
  slide: true,
  fade: false,
};

Example.parameters = {
  docs: {
    source: {
      code: CarouselExample,
      language: 'jsx',
      type: 'auto',
    },
  },
};

export default Example;


text:
% Copyright 2004 by Till Tantau <tantau@users.sourceforge.net>.
%
% In principle, this file can be redistributed and/or modified under
% the terms of the GNU Public License, version 2.
%
% However, this file is supposed to be a template to be modified
% for your own needs. For this reason, if you use this file as a
% template and not specifically distribute it as part of a another
% package/program, I grant the extra permission to freely copy and
% modify this file as you see fit and even to delete this copyright
% notice.

\documentclass{beamer}
% Replace the \documentclass declaration above
% with the following two lines to typeset your
% lecture notes as a handout:
%\documentclass{article}
%\usepackage{beamerarticle}

\usepackage{graphicx}
\usepackage[utf8]{inputenc}

\graphicspath{ {img/} }

% There are many different themes available for Beamer. A comprehensive
% list with examples is given here:
% http://deic.uab.es/~iblanes/beamer_gallery/index_by_theme.html
% You can uncomment the themes below if you would like to use a different
% one:
%\usetheme{AnnArbor}
%\usetheme{Antibes}
%\usetheme{Bergen}
%\usetheme{Berkeley}
%\usetheme{Berlin}
%\usetheme{Boadilla}
%\usetheme{boxes}
%\usetheme{CambridgeUS}
%\usetheme{Copenhagen}
%\usetheme{Darmstadt}
%\usetheme{default}
%\usetheme{Frankfurt}
%\usetheme{Goettingen}
%\usetheme{Hannover}
%\usetheme{Ilmenau}
%\usetheme{JuanLesPins}
%\usetheme{Luebeck}
%\usetheme{Madrid}
%\usetheme{Malmoe}
%\usetheme{Marburg}
%\usetheme{Montpellier}
%\usetheme{PaloAlto}
%\usetheme{Pittsburgh}
%\usetheme{Rochester}
%\usetheme{Singapore}
%\usetheme{Szeged}
\usetheme{Warsaw}

\title{Programming with NodeJS}

% A subtitle is optional and this may be deleted
\subtitle{Lesson 2: Callbacks, buffers, streams, APIs and Express}

%\author{F.~Author\inst{1} \and S.~Another\inst{2}}
% - Give the names in the same order as the appear in the paper.
% - Use the \inst{?} command only if the authors have different
%   affiliation.

%\institute[Universities of Somewhere and Elsewhere] % (optional, but mostly needed)
%{
%  \inst{1}%
%  Department of Computer Science\\
%  University of Somewhere
%  \and
%  \inst{2}%
%  Department of Theoretical Philosophy\\
%  University of Elsewhere}
% - Use the \inst command only if there are several affiliations.
% - Keep it simple, no one is interested in your street address.

\date{Febuary 14th, 2017}
% - Either use conference name or its abbreviation.
% - Not really informative to the audience, more for people (including
%   yourself) who are reading the slides online

\subject{NodeJS Lessons}
% This is only inserted into the PDF information catalog. Can be left
% out.

% If you have a file called "university-logo-filename.xxx", where xxx
% is a graphic format that can be processed by latex or pdflatex,
% resp., then you can add a logo as follows:

% \pgfdeclareimage[height=0.5cm]{university-logo}{university-logo-filename}
% \logo{\pgfuseimage{university-logo}}

% Delete this, if you do not want the table of contents to pop up at
% the beginning of each subsection:
%\AtBeginSubsection[]
%{
%  \begin{frame}<beamer>{Outline}
%    \tableofcontents[currentsection,currentsubsection]
%  \end{frame}
%}

% Let's get started
\begin{document}

\begin{frame}
  \titlepage
\end{frame}

%\begin{frame}{Outline}
%  \tableofcontents
%  % You might wish to add the option [pausesections]
%\end{frame}

% Section and subsections will appear in the presentation overview
% and table of contents.
\section{Introduction}

\begin{frame}{Summary of last week}
  Last week we:
  \pause
  \begin{itemize}
  \item We have installed NodeJS and NPM\pause
  \item We have learnt about JS syntax\pause
  \item We have learnt about NodeJS and what it's useful for\pause
  \item We have made a very simple http server
  \end{itemize}
\end{frame}

\section{Callbacks and the Event Loop}

\begin{frame}{Callbacks? Huh?}

NodeJS is a language developed around the idea of everything being asynchronous. \\
\pause
Asynchronous programming is programming where an operation is executed after the previous one has been terminated.\\
\pause
How does asynchronous programming differ from normal programming?\\
\pause
Consider this example:

\end{frame}

\begin{frame}{Asynchronous programming example}
Say you really want to have a chat with your mate Paul about the weather. You have two ways to get in touch with him.
You can either: \pause
\begin{itemize}
  \item Phone him\pause
  \item Send him a letter
\end{itemize}

\end{frame}

\begin{frame}

Both have distinct advantages and disadvantages.\\
\pause
If you phone him and ask him what the weather is like, you have to sit there and wait for him to look outside and reply.\\
\pause
This is considered synchronous. You have a guarantee that he will reply as soon as possible, but you have to wait the entire time he's looking outside.\\
\pause
Alternatively, if you send him a letter asking what the weather is like, you can do other things while you wait for the postman to come with his response. However, you have no idea how long until you will recieve that response is.\\
\pause
This is considered asynchronous.

\end{frame}

\begin{frame}

NodeJS is asynchronous.\\ \pause
The reason for this is just the same as with Paul and the weather. \pause If instead of talking to just Paul, you want to talk to 100s of people about the weather they are all experiencing, an asynchronous approach will allow you to keep conversations open with all of these people at the same time.\\

\end{frame}

\begin{frame}{Seperating IO bound and CPU bound tasks}

Note, this asynchronous feature is really strong for some purposes and really weak for others.\\
There are two types of functionality we will want in our program. They are:
\pause
\begin{itemize}
  \item CPU bound \pause - stuff which the CPU has to do e.g. sorting an array, adding numbers together \pause
  \item I/O bound \pause - stuff which the CPU tells something else to do, where it then gives it back to the CPU at another time e.g. opening a file (your hard drive takes time to retrieve the file), downloading something from the web (your network card takes time to download)
\end{itemize}

\pause

This distinction is important for NodeJS as it defines which bits NodeJS can do seemingly concurrently and which it won't be able to do well.

\end{frame}

\begin{frame}{NodeJS and concurrency}

Specifically, NodeJS is a single threaded program which uses an event loop to manage pseudo-concurrency. \\
\pause
What this means is that, if NodeJS is doing a CPU bound task, the entire program has to stop and wait for the CPU task to be completed before \textbf{anything} can happen.\\
\pause
If however NodeJS is executing an IO bound task, it can say "ok you do that IO, and once you've done the IO task, tell me and i'll execute this bit of code".\\
\pause
The "bit of code" is called a callback function and is a function which you give to an IO bound function, which is executed once the IO bound function is done.

\end{frame}

\begin{frame}{Callbacks}

\begin{figure}[h]
\includegraphics[width=0.8\textwidth]{fscode}
\end{figure}

\end{frame}

\begin{frame}{Callbacks}

\begin{figure}[h]
\includegraphics[width=0.8\textwidth]{fscode2}
\end{figure}

\end{frame}

\begin{frame}{Buffers}

Buffers are a class in NodeJS which allows us to deal with big chunks of bytes.\\
\pause
Useful for times where you're getting a chunk of bytes in from somewhere e.g. downloading a file or opening a file from your file system

\end{frame}

\begin{frame}{Buffers}

You can make a new buffer with \textit{var myBuffer = new Buffer(BUFFER SIZE);}.\\
\pause
You can write to a buffer via \textit{myBuffer.write(CONTENT);}.\\
\pause
Most usefully, you can convert a buffer to a string with \textit{myBuffer.toString()}.

\end{frame}

\begin{frame}{The Express framework}

The Express framework is an HTTP server framework for NodeJS with a bunch of really powerful features, making it much stronger than the framework we used last week, 'http'.

\end{frame}

\begin{frame}{Hello world in Express}

\begin{figure}[h]
\includegraphics[width=0.8\textwidth]{express}
\end{figure}

\end{frame}

\begin{frame}{Hello world in Express}

\begin{figure}[h]
\includegraphics[width=0.8\textwidth]{express2}
\end{figure}

\end{frame}

\begin{frame}{Hello world in Express}

\begin{figure}[h]
\includegraphics[width=0.8\textwidth]{express3}
\end{figure}

\end{frame}

\begin{frame}{Hello world in Express}

\begin{figure}[h]
\includegraphics[width=0.8\textwidth]{express4}
\end{figure}

\end{frame}

\begin{frame}{Middleware}

One of the strong points of Express is it's middleware capabilities.\pause Middleware is code which is executed inbetween when you get the request and when you deal with it.\pause Some examples of middleware include adding authentication to every request, so only people who are logged in can go to certain places in the site.

\end{frame}

\begin{frame}{Endpoints}

An endpoint is a \textit{destination}. When you go to 127.0.0.1:3000 you are going to the root endpoint \textit{/}.\pause \\
If instead you go to 127.0.0.1:3000/hello/world, you are going to the endpoint \textit{/hello/world}.

\end{frame}

\begin{frame}{Templates}

Templates are pretty much HTML++.\\ \pause
They are pre-rendered on the server side and can be passed in values.

\end{frame}

\begin{frame}{EJS}

EJS is a templating language developed to be very strong when paired with javascript (like NodeJS). It mixes normal HTML with embedded javascript which is compiled before it is sent to the client. It looks a little like this:

\begin{figure}[h]
\includegraphics[width=0.6\textwidth]{ejs}
\end{figure}

\end{frame}

\begin{frame}{Putting it all together}

\end{frame}

\section{Summary}

\begin{frame}{That's all for tonight!}
  To summarise:
  \begin{itemize}
  \item We have learnt about callbacks and the NodeJS event loop
  \item We have learnt about buffers
  \item We have learnt about the Express framework
  \item We have made a complex server using Express
  \end{itemize}
\end{frame}

\begin{frame}{For next week}
Source code plus lecture slides will be available online soon after the lesson.\\
If you are new to HackSocNotts, please join us on \textit{http://hacksocnotts.slack.com}.\\
If you have any questions, feel free to ask now or over slack.\\
\end{frame}

\end{document}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context-4.0.xsd
                           http://www.springframework.org/schema/util
                           http://www.springframework.org/schema/util/spring-util-4.0.xsd"
>

    <context:component-scan base-package="com.sulaco.fuse" />

    <bean class="com.sulaco.fuse.codec.JsonWireCodec" />

    <!-- test properties -->
    <bean id="properties" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="targetObject" value="#{@systemProperties}" />
        <property name="targetMethod" value="putAll" />
        <property name="arguments">
            <util:properties>
                <prop key="contentDir">./</prop>
            </util:properties>
        </property>
    </bean>

</beans>


text:
require 'action_controller'
require 'application_helper'

module Refinery
  module Admin
    module BaseController

      extend ActiveSupport::Concern

      included do
        layout :layout?

        before_filter :authenticate_refinery_user!, :restrict_plugins, :restrict_controller
        after_filter :store_location?, :except => [:new, :create, :edit, :update, :destroy, :update_positions] # for redirect_back_or_default

        helper_method :searching?, :group_by_date
      end

      module InstanceMethods
        def admin?
          true # we're in the admin base controller, so always true.
        end

        def searching?
          params[:search].present?
        end

        def error_404(exception=nil)
          # fallback to the default 404.html page.
          render :file => Rails.root.join("public", "404.html").cleanpath.to_s,
                 :layout => false,
                 :status => 404
        end

      protected

        def group_by_date(records)
          new_records = []

          records.each do |record|
            key = record.created_at.strftime("%Y-%m-%d")
            record_group = new_records.collect{|records| records.last if records.first == key }.flatten.compact << record
            (new_records.delete_if {|i| i.first == key}) << [key, record_group]
          end

          new_records
        end

        def restrict_plugins
          current_length = (plugins = current_refinery_user.authorized_plugins).length

          # Superusers get granted access if they don't already have access.
          if current_refinery_user.has_role?(:superuser)
            if (plugins = plugins | ::Refinery::Plugins.registered.names).length > current_length
              current_refinery_user.plugins = plugins
            end
          end

          ::Refinery::Plugins.set_active(plugins)
        end

        def restrict_controller
          # if ::Refinery::Plugins.active.reject { |plugin| params[:controller] !~ Regexp.new(plugin.menu_match)}.empty?
          #   warn "'#{current_refinery_user.username}' tried to access '#{params[:controller]}' but was rejected."
          #   error_404
          # end
        end

        # Override method from application_controller. Not needed in this controller.
        def find_pages_for_menu; end

      private
        def layout?
          "refinery/admin#{"_dialog" if from_dialog?}"
        end

        # Check whether it makes sense to return the user to the last page they
        # were at instead of the default e.g. refinery_admin_pages_path
        # right now we just want to snap back to index actions and definitely not to dialogues.
        def store_location?
          store_location unless action_name !~ /index/ or request.xhr? or from_dialog?
        end

        # Override authorized? so that only users with the Refinery role can admin the website.
        def authorized?
          refinery_user?
        end
      end

    end
  end
end


text:
package com.markmao.pulltorefresh.lib.chat;

/**
 * @author greg
 * @since 6/21/13
 */
public class Chat {

    private String message;
    private String author;

    // Required default constructor for Firebase object mapping
    @SuppressWarnings("unused")
    private Chat() {
    }

    Chat(String message, String author) {
        this.message = message;
        this.author = author;
    }

    public String getMessage() {
        return message;
    }

    public String getAuthor() {
        return author;
    }
}


text:
package org.gradoop.flink.model.impl.operators.matching.transactional.function;

import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.configuration.Configuration;
import org.gradoop.common.model.impl.id.GradoopId;
import org.gradoop.common.model.impl.pojo.Edge;
import org.gradoop.common.model.impl.pojo.Vertex;
import org.gradoop.flink.model.impl.operators.matching.common.matching.ElementMatcher;
import org.gradoop.flink.model.impl.operators.matching.common.query.QueryHandler;
import org.gradoop.flink.model.impl.operators.matching.common.tuples.IdWithCandidates;
import org.gradoop.flink.model.impl.operators.matching.common.tuples.TripleWithCandidates;
import org.gradoop.flink.model.impl.operators.matching.transactional.tuples.GraphWithCandidates;
import org.gradoop.flink.model.impl.layouts.transactional.tuples.GraphTransaction;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import static org.gradoop.common.util.GradoopConstants.DEFAULT_EDGE_LABEL;
import static org.gradoop.common.util.GradoopConstants.DEFAULT_VERTEX_LABEL;

/**
 * Matches the elements of GraphTransactions against a query string. Returns
 * GraphsWithCandidates, which can be input for HasEmbeddings or FindEmbeddings.
 */
public class GraphTransactionMatcher
  extends RichMapFunction<GraphTransaction, GraphWithCandidates> {

  /**
   * serial version uid
   */
  private static final long serialVersionUID = 42L;
  /**
   * Query handler
   */
  private transient QueryHandler handler;
  /**
   * Query string
   */
  private String query;

  /**
   * Constructor
   * @param query query string
   */
  public GraphTransactionMatcher(String query) {
    this.query = query;
  }

  @Override
  public void open(Configuration parameters) throws Exception {
    handler = new QueryHandler(this.query);
  }

  @Override
  public GraphWithCandidates map(GraphTransaction graphTransaction) {

    GraphWithCandidates graph = new GraphWithCandidates(
      graphTransaction.getGraphHead().getId());

    Set<Vertex> vertices = graphTransaction.getVertices();
    List<IdWithCandidates<GradoopId>> vertexCandidates
      = new ArrayList<>(vertices.size());

    for (Vertex vertex : vertices) {
      IdWithCandidates<GradoopId> candidates = new IdWithCandidates<>();
      candidates.setId(vertex.getId());
      candidates.setCandidates(
        getCandidates(handler.getVertexCount(), ElementMatcher.getMatches(
            vertex,
            handler.getVertices(),
            DEFAULT_VERTEX_LABEL
          )
        )
      );
      vertexCandidates.add(candidates);
    }

    Set<Edge> edges = graphTransaction.getEdges();
    List<TripleWithCandidates<GradoopId>> edgeCandidates =
    new ArrayList<>(edges.size());

    for (Edge edge : edges) {
      TripleWithCandidates<GradoopId> candidates = new TripleWithCandidates<>();
      candidates.setEdgeId(edge.getId());
      candidates.setSourceId(edge.getSourceId());
      candidates.setTargetId(edge.getTargetId());
      candidates.setCandidates(
        getCandidates(handler.getEdgeCount(), ElementMatcher.getMatches(
            edge,
            handler.getEdges(),
            DEFAULT_EDGE_LABEL
          )
        )
      );
      edgeCandidates.add(candidates);
    }

    graph.setVertexCandidates(vertexCandidates);
    graph.setEdgeCandidates(edgeCandidates);
    return graph;
  }

  /**
   * Returns a bit vector representing the matches for the given entity.
   *
   * @param candidateCount  size of the bit vector
   * @param matches         matches for the given entity
   * @return bit vector representing matches
   */
  private boolean[] getCandidates(int candidateCount, List<Long> matches) {
    boolean[] candidates = new boolean[candidateCount];

    for (Long candidate : matches) {
      candidates[candidate.intValue()] = true;
    }
    return candidates;
  }
}


text:
package com.pushtorefresh.storio.sample.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.annotation.NonNull;

import com.pushtorefresh.storio.sample.db.tables.TweetsTable;
import com.pushtorefresh.storio.sample.db.tables.UsersTable;

public class DbOpenHelper extends SQLiteOpenHelper {

    public DbOpenHelper(@NonNull Context context) {
        super(context, "sample_db", null, 1);
    }

    @Override
    public void onCreate(@NonNull SQLiteDatabase db) {
        db.execSQL(TweetsTable.getCreateTableQuery());
        db.execSQL(UsersTable.getCreateTableQuery());
    }

    @Override
    public void onUpgrade(@NonNull SQLiteDatabase db, int oldVersion, int newVersion) {
        // no impl
    }
}


text:
/**
 * Uses the new array typed in javascript to binary base64 encode/decode
 * at the moment just decodes a binary base64 encoded
 * into either an ArrayBuffer (decodeArrayBuffer)
 * or into an Uint8Array (decode)
 *
 * References:
 * https://developer.mozilla.org/en/JavaScript_typed_arrays/ArrayBuffer
 * https://developer.mozilla.org/en/JavaScript_typed_arrays/Uint8Array
 */

var Base64Binary = {
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

	/* will return a  Uint8Array type */
	decodeArrayBuffer: function(input) {
		var bytes = (input.length/4) * 3;
		var ab = new ArrayBuffer(bytes);
		this.decode(input, ab);

		return ab;
	},

	removePaddingChars: function(input){
		var lkey = this._keyStr.indexOf(input.charAt(input.length - 1));
		if(lkey == 64){
			return input.substring(0,input.length - 1);
		}
		return input;
	},

	decode: function (input, arrayBuffer) {
		//get last chars to see if are valid
		input = this.removePaddingChars(input);
		input = this.removePaddingChars(input);

		var bytes = parseInt((input.length / 4) * 3, 10);

		var uarray;
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
		var j = 0;

		if (arrayBuffer)
			uarray = new Uint8Array(arrayBuffer);
		else
			uarray = new Uint8Array(bytes);

		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

		for (i=0; i<bytes; i+=3) {
			//get the 3 octects in 4 ascii chars
			enc1 = this._keyStr.indexOf(input.charAt(j++));
			enc2 = this._keyStr.indexOf(input.charAt(j++));
			enc3 = this._keyStr.indexOf(input.charAt(j++));
			enc4 = this._keyStr.indexOf(input.charAt(j++));

			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;

			uarray[i] = chr1;
			if (enc3 != 64) uarray[i+1] = chr2;
			if (enc4 != 64) uarray[i+2] = chr3;
		}

		return uarray;
	}
}


text:
package com.google.engedu.anagrams;

import android.support.annotation.VisibleForTesting;
import android.text.TextUtils;

import org.w3c.dom.Text;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Random;

public class AnagramDictionary {

    private static final int MIN_NUM_ANAGRAMS = 5;
    private static final int DEFAULT_WORD_LENGTH = 3;
    private static final int MAX_WORD_LENGTH = 7;
    private Random random = new Random();

    private HashMap<String, ArrayList<String>> lettersToWord = new HashMap<>();

    public AnagramDictionary(InputStream wordListStream) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(wordListStream));
        String line;
        while((line = in.readLine()) != null) {
            String word = line.trim();
            //
            //  Your code here
            //
        }
    }

    public boolean isGoodWord(String word, String base) {
        //
        // Your code here
        //
        return true;
    }

    public ArrayList<String> getAnagrams(String targetWord) {
        ArrayList<String> result = new ArrayList<String>();
        //
        // Your code here
        //
        return result;
    }

    @VisibleForTesting
    static boolean isAnagram(String first, String second) {
        //
        // Your code here
        //
        return true;
    }

    @VisibleForTesting
    static String sortLetters(String input) {
        char[] chars = input.toCharArray();
        //
        // Your code here
        //
        return "";
    }

    public ArrayList<String> getAnagramsWithOneMoreLetter(String word) {
        ArrayList<String> result = new ArrayList<String>();
        //
        // Your code here
        //
        return result;
    }

    public String pickGoodStarterWord() {
        //
        // Your code here
        //
        return "stop";
    }
}


text:
package edu.clemson.resolve.jetbrains.psi;

import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;

public interface ResMathFunctionAppList extends ResCompositeElement {

  @NotNull
  List<ResMathExp> getMathExpList();

  @NotNull
  PsiElement getLparen();

  @Nullable
  PsiElement getRparen();

}


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

import com.facebook.presto.hive.HdfsEnvironment;
import com.facebook.presto.hive.HiveClientConfig;
import com.facebook.presto.hive.HiveColumnHandle;
import com.facebook.presto.hive.HivePageSourceFactory;
import com.facebook.presto.hive.parquet.memory.AggregatedMemoryContext;
import com.facebook.presto.hive.parquet.predicate.ParquetPredicate;
import com.facebook.presto.hive.parquet.reader.ParquetMetadataReader;
import com.facebook.presto.hive.parquet.reader.ParquetReader;
import com.facebook.presto.spi.ConnectorPageSource;
import com.facebook.presto.spi.ConnectorSession;
import com.facebook.presto.spi.PrestoException;
import com.facebook.presto.spi.predicate.TupleDomain;
import com.facebook.presto.spi.type.TypeManager;
import com.google.common.collect.ImmutableSet;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.joda.time.DateTimeZone;
import parquet.column.ColumnDescriptor;
import parquet.hadoop.metadata.BlockMetaData;
import parquet.hadoop.metadata.FileMetaData;
import parquet.hadoop.metadata.ParquetMetadata;
import parquet.schema.MessageType;

import javax.inject.Inject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;

import static com.facebook.presto.hive.HiveColumnHandle.ColumnType.REGULAR;
import static com.facebook.presto.hive.HiveErrorCode.HIVE_CANNOT_OPEN_SPLIT;
import static com.facebook.presto.hive.HiveErrorCode.HIVE_MISSING_DATA;
import static com.facebook.presto.hive.HiveSessionProperties.isParquetOptimizedReaderEnabled;
import static com.facebook.presto.hive.HiveSessionProperties.isParquetPredicatePushdownEnabled;
import static com.facebook.presto.hive.HiveUtil.getDeserializerClassName;
import static com.facebook.presto.hive.parquet.HdfsParquetDataSource.buildHdfsParquetDataSource;
import static com.facebook.presto.hive.parquet.ParquetTypeUtils.getParquetType;
import static com.facebook.presto.hive.parquet.predicate.ParquetPredicateUtils.buildParquetPredicate;
import static com.facebook.presto.hive.parquet.predicate.ParquetPredicateUtils.getParquetTupleDomain;
import static com.facebook.presto.hive.parquet.predicate.ParquetPredicateUtils.predicateMatches;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toList;

public class ParquetPageSourceFactory
        implements HivePageSourceFactory
{
    private static final Set<String> PARQUET_SERDE_CLASS_NAMES = ImmutableSet.<String>builder()
            .add("org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe")
            .add("parquet.hive.serde.ParquetHiveSerDe")
            .build();

    private final TypeManager typeManager;
    private final boolean useParquetColumnNames;
    private final HdfsEnvironment hdfsEnvironment;

    @Inject
    public ParquetPageSourceFactory(TypeManager typeManager, HiveClientConfig config, HdfsEnvironment hdfsEnvironment)
    {
        this(typeManager, requireNonNull(config, "hiveClientConfig is null").isUseParquetColumnNames(), hdfsEnvironment);
    }

    public ParquetPageSourceFactory(TypeManager typeManager, boolean useParquetColumnNames, HdfsEnvironment hdfsEnvironment)
    {
        this.typeManager = requireNonNull(typeManager, "typeManager is null");
        this.useParquetColumnNames = useParquetColumnNames;
        this.hdfsEnvironment = requireNonNull(hdfsEnvironment, "hdfsEnvironment is null");
    }

    @Override
    public Optional<? extends ConnectorPageSource> createPageSource(
            Configuration configuration,
            ConnectorSession session,
            Path path,
            long start,
            long length,
            long fileSize,
            Properties schema,
            List<HiveColumnHandle> columns,
            TupleDomain<HiveColumnHandle> effectivePredicate,
            DateTimeZone hiveStorageTimeZone)
    {
        if (!isParquetOptimizedReaderEnabled(session)) {
            return Optional.empty();
        }

        if (!PARQUET_SERDE_CLASS_NAMES.contains(getDeserializerClassName(schema))) {
            return Optional.empty();
        }

        return Optional.of(createParquetPageSource(
                hdfsEnvironment,
                session.getUser(),
                configuration,
                path,
                start,
                length,
                fileSize,
                schema,
                columns,
                useParquetColumnNames,
                typeManager,
                isParquetPredicatePushdownEnabled(session),
                effectivePredicate));
    }

    public static ParquetPageSource createParquetPageSource(
            HdfsEnvironment hdfsEnvironment,
            String user,
            Configuration configuration,
            Path path,
            long start,
            long length,
            long fileSize,
            Properties schema,
            List<HiveColumnHandle> columns,
            boolean useParquetColumnNames,
            TypeManager typeManager,
            boolean predicatePushdownEnabled,
            TupleDomain<HiveColumnHandle> effectivePredicate)
    {
        AggregatedMemoryContext systemMemoryContext = new AggregatedMemoryContext();

        ParquetDataSource dataSource = null;
        try {
            FileSystem fileSystem = hdfsEnvironment.getFileSystem(user, path, configuration);
            dataSource = buildHdfsParquetDataSource(fileSystem, path, start, length, fileSize);
            ParquetMetadata parquetMetadata = ParquetMetadataReader.readFooter(fileSystem, path, fileSize);
            FileMetaData fileMetaData = parquetMetadata.getFileMetaData();
            MessageType fileSchema = fileMetaData.getSchema();

            List<parquet.schema.Type> fields = columns.stream()
                    .filter(column -> column.getColumnType() == REGULAR)
                    .map(column -> getParquetType(column, fileSchema, useParquetColumnNames))
                    .filter(Objects::nonNull)
                    .collect(toList());

            MessageType requestedSchema = new MessageType(fileSchema.getName(), fields);

            List<BlockMetaData> blocks = new ArrayList<>();
            for (BlockMetaData block : parquetMetadata.getBlocks()) {
                long firstDataPage = block.getColumns().get(0).getFirstDataPageOffset();
                if (firstDataPage >= start && firstDataPage < start + length) {
                    blocks.add(block);
                }
            }

            if (predicatePushdownEnabled) {
                TupleDomain<ColumnDescriptor> parquetTupleDomain = getParquetTupleDomain(fileSchema, requestedSchema, effectivePredicate);
                ParquetPredicate parquetPredicate = buildParquetPredicate(requestedSchema, parquetTupleDomain, fileMetaData.getSchema());
                final ParquetDataSource finalDataSource = dataSource;
                blocks = blocks.stream()
                        .filter(block -> predicateMatches(parquetPredicate, block, finalDataSource, fileSchema, requestedSchema, parquetTupleDomain))
                        .collect(toList());
            }

            ParquetReader parquetReader = new ParquetReader(
                    fileSchema,
                    requestedSchema,
                    blocks,
                    dataSource,
                    typeManager,
                    systemMemoryContext);

            return new ParquetPageSource(
                    parquetReader,
                    dataSource,
                    fileSchema,
                    requestedSchema,
                    schema,
                    columns,
                    effectivePredicate,
                    typeManager,
                    useParquetColumnNames,
                    systemMemoryContext);
        }
        catch (Exception e) {
            try {
                if (dataSource != null) {
                    dataSource.close();
                }
            }
            catch (IOException ignored) {
            }
            if (e instanceof PrestoException) {
                throw (PrestoException) e;
            }
            String message = format("Error opening Hive split %s (offset=%s, length=%s): %s", path, start, length, e.getMessage());
            if (e.getClass().getSimpleName().equals("BlockMissingException")) {
                throw new PrestoException(HIVE_MISSING_DATA, message, e);
            }
            throw new PrestoException(HIVE_CANNOT_OPEN_SPLIT, message, e);
        }
    }
}


text:
#import <Foundation/Foundation.h>
#import "AdVideoManagerDelegate.h"
#import "AdViewConfig.h"
#import "AdViewCommonDef.h"

@class AdVideoManager;
@class AdViewConfig;
@class AdViewAdNetworkConfig;

@interface AdVideoAdNetworkAdapter : NSObject {
	id<AdVideoManagerDelegate> __weak adVideoDelegate;
	AdVideoManager __weak *adVideoManager;
	AdViewConfig *adVideoConfig;
	AdViewAdNetworkConfig *networkConfig;
	UIViewController *adVideoController;

    AdVideoLoadType loadType;
}

/**
 * Subclasses must implement +networkType to return an AdVideoAdNetworkType enum.
 */
+ (AdVideoAdNetworkType)networkType;

/**
 * Subclasses must add itself to the AdViewAdNetworkRegistry. One way
 * to do so is to implement the +load function and register there.
 */
//+ (void)load;

/**
 * Default initializer. Subclasses do not need to override this method unless
 * they need to perform additional initialization. In which case, this
 * method must be called via the super keyword.
 */
- (id)initWithAdVideoDelegate:(id<AdVideoManagerDelegate>)delegate
                      manager:(AdVideoManager *)manager
                       config:(AdViewConfig *)config
                networkConfig:(AdViewAdNetworkConfig *)netConf;

/**
 * Ask the adapter to load an adinstl. This must be implemented by subclasses.
 */
- (BOOL)loadAdVideo:(UIViewController*)controller;

/**
 * Ask the adapter to show an adinstl. This must be implemented by subclasses.
 */
- (BOOL)showAdVideo:(UIViewController*)controller;

/**
 * When called, the adapter must remove itself as a delegate or notification
 * observer from the underlying ad network SDK. Subclasses must implement this
 * method, even if the underlying SDK doesn't have a way of removing delegate
 * (in which case, you should contact the ad network). Note that this method
 * will be called in dealloc at AdVideoAdNetworkAdapter, before adVideoController
 * is released. Care must be taken if you also keep a reference of your ad view
 * in a separate instance variable, as you may have released that variable
 * before this gets called in AdVideoAdNetworkAdapter's dealloc. Use
 * adVideoController, defined in this class, instead of your own instance variable.
 * This function should also be idempotent, i.e. get called multiple times and
 * not crash.
 */
- (void)stopBeingDelegate;

/**
 * Subclasses return YES to ask AdVideoManager to send metric requests to the
 * AdVideo server for ad impressions. Default is YES.
 */
- (BOOL)shouldSendExMetric;

/**
 * Tell the adapter that the interface orientation changed or is about to change
 */
- (void)rotateToOrientation:(UIInterfaceOrientation)orientation;

/**
 * Some ad transition types may cause issues with particular ad networks. The
 * adapter should know whether the given animation type is OK. Defaults to
 * YES.
 */
- (BOOL)isBannerAnimationOK:(AWBannerAnimationType)animType;

@property (nonatomic,weak) id<AdVideoManagerDelegate> adVideoDelegate;
@property (nonatomic,weak) AdVideoManager *adVideoManager;
@property (nonatomic,retain) AdViewConfig *adVideoConfig;
@property (nonatomic,retain) AdViewAdNetworkConfig *networkConfig;
@property (nonatomic,retain) UIViewController *adVideoController;

@property (nonatomic,assign) BOOL bWaitAd;
@property (nonatomic,assign) AdVideoLoadType loadType;

#pragma mark util method.
- (BOOL) isTestMode;

- (BOOL) isOpenGps;

@end


text:
module Fayde.Markup {
    import XamlMarkup = nullstone.markup.xaml.XamlMarkup;

    export function Resolve (uri: string);
    export function Resolve (uri: Uri);
    export function Resolve (uri: any): nullstone.async.IAsyncRequest<XamlMarkup> {
        return nullstone.async.create((resolve, reject) => {
            XamlMarkup.create(uri)
                .loadAsync()
                .then(xm => {
                    var co = collector.create();
                    return nullstone.async.many([
                        xm.resolve(Fayde.TypeManager, co.collect),
                        co.resolve()
                    ]).then(() => resolve(xm), reject);
                }, reject);
        });
    }

    module collector {
        export interface ICollector {
            collect(ownerUri: string, ownerName: string, propName: string, val: any);
            resolve(): nullstone.async.IAsyncRequest<any>;
        }

        export function create (): ICollector {
            var rduris: string[] = [];
            return {
                collect (ownerUri: string, ownerName: string, propName: string, val: any) {
                    if (ownerUri === Fayde.XMLNS && ownerName === "ResourceDictionary" && propName === "Source")
                        rduris.push(val);
                },
                resolve (): nullstone.async.IAsyncRequest<any> {
                    return nullstone.async.many(rduris.map(Resolve));
                }
            };
        }
    }
}


text:
from __future__ import unicode_literals

from indico.core.celery.controllers import RHCeleryTasks
from indico.web.flask.wrappers import IndicoBlueprint

_bp = IndicoBlueprint('celery', __name__, url_prefix='/admin/tasks', template_folder='templates',
                      virtual_template_folder='celery')

_bp.add_url_rule('/', 'index', RHCeleryTasks)


text:
Javascript Club
---------------

We are going to make a javascript version of the classic
stone takeaway game. We start with a pile that has a random
number of stones in it.  We can remove any number up to a given
amount. For example, we might be able to remove 1, 2, 3, 4, or
5 of the stones at any turn.

The player who takes the last stone (or stones) wins.


text:
package br.com.crescer.aula3.util;

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

/**
 * @author Carlos H. Nonnemacher
 */
public class ConnectionFactory {

    private static final String URL = "jdbc:oracle:thin:@localhost:1521:xe";
    private static final String USER = "CWI";
    private static final String PASS = "CWI";

    public static Connection newConnection() throws SQLException {
        return DriverManager.getConnection(URL, USER, PASS);
    }

}


text:
package net.catchpole.io;

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

import net.catchpole.lang.Disposable;

import java.io.*;

public class MemoryInputOutputStream implements InputOutputStream, Disposable, Externalizable {
    private ByteArrayOutputStream baos;
    private byte[] bytes;
    private Integer initialBuffer;

    public MemoryInputOutputStream() {
    }

    public MemoryInputOutputStream(int initialBuffer) {
        this.initialBuffer = initialBuffer;
    }

    public InputStream getInputStream() throws IOException {
        if (bytes == null) {
            bytes = baos != null ? baos.toByteArray() : new byte[0];
        }
        return new ByteArrayInputStream(bytes);
    }

    public OutputStream getOutputStream() throws IOException {
        bytes = null;
        baos = (initialBuffer == null ? new ByteArrayOutputStream() : new ByteArrayOutputStream(initialBuffer));
        return baos;
    }

    public byte[] getBytes() {
        return baos.toByteArray();
    }

    public void dispose() {
        baos = null;
        bytes = null;
    }

    public String toString() {
        return this.getClass().getSimpleName() + ' ' + (bytes != null ? bytes.length : 0);
    }

    public void writeExternal(ObjectOutput out) throws IOException {
        if (baos != null) {
            byte[] data = baos.toByteArray();
            out.writeInt(data.length);
            out.write(data);
        } else if (bytes != null) {
            out.writeInt(bytes.length);
            out.write(bytes);
        }
        out.writeInt(0);
    }

    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        bytes = new byte[in.readInt()];
        in.readFully(bytes);
    }
}


text:
> Material Design colors

## Installation

```shell
$ npm install @cyclic/atom-color
```

## License

MIT © [Cyclic Materials](http://github.com/CyclicMaterials)


text:
import os

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(os.path.dirname(__file__), 'tests.db'),
    }
}

INSTALLED_APPS = (
    'django.contrib.sites',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'avocado',
    'tests',
)

ROOT_URLCONF = 'tests.urls'

SOUTH_TESTS_MIGRATE = False

SECRET_KEY = 'abc123'


text:
<meta http-equiv=Content-Type content="text/html; charset=windows-1252">
<meta name=Generator content="Microsoft Word 15 (filtered)">

Sunday,
April 05, 2015

To my family

                With
the only exception, and that is your Mother, you are the dearest and greatest
people I have in life.  My heart is full of love for each of you.  I don't know
if I have the ability to express my feelings of love, concerns and desires that
I have for each of you.  I tremble with concern as to whether I can relay in
words these feelings in such a way that none of you will take offence at what I
desire to express to each member of my family from my oldest daughter, Sandra
Lee to my youngest  great-grandson Luke.

                I
remember that as a teenager, a Sunday school teacher, had each in his class
write our GOALS we wanted to achieve in this life.  I am not sure if I had ever
done this before but as I thought about my goals to accomplish, I wrote three
Main goals I wanted to accomplish.  1st I wanted to serve a
mission.  2nd I wanted to marry a beautiful girl in the Temple.  3rd
I wanted to raise a family that would be honorable people and righteous
servants to our Lord.


text:
/* SampleCIView.h - simple OpenGL based CoreImage view */

// This code was stolen from /Developer/Examples/Quartz/Core Image/FunHouse/SampleCIView.m
// and modified to scale the CIImage within the frame rect (preserving aspect ratio,
// and painting unused areas black)

#import <Cocoa/Cocoa.h>

#import <QuartzCore/CoreImage.h>

@interface SampleCIView: NSOpenGLView
{
    CIContext *_context;
    CIImage   *_image;
    NSRect     _lastBounds;
	//CGRect     _cleanRect;
	CGSize     _displaySize;

	//CIImage *greenLines, *redLines;

	BOOL mirrored, goodScan;
	BOOL newHighResiSight;
	CGRect highResPortionOfImage;

	NSRecursiveLock         *lock;
	CIFilter *mirroredFilter, *redLinesFilter, *greenLinesFilter;
}

- (void)setImage:(CIImage *)image;
//- (void)setImage:(CIImage *)image dirtyRect:(CGRect)r;
//- (void)setCleanRect:(CGRect)cleanRect;
- (void)setDisplaySize:(CGSize)displaySize;

- (CIImage *)image;

// Called when the view bounds have changed
- (void)viewBoundsDidChange:(NSRect)bounds;

- (void)setGoodScan:(BOOL)aBool;
- (void)setMirrored:(BOOL)aBool;
- (void)setHighResiSight:(BOOL)aBool;

@end


text:
# This code will try to automatically detect known motor/power boards and configure the correctly tailored command for them*/

canTalkToATMEGAviaSPI(){
    avrdude -P /dev/spidev1.0 -c linuxspi -vv -p m2560 > /dev/null 2>&1
    if [ $? -ne 0 ]
    then
        return 1
    else
        return 0
    fi

}

export ROV_BOARD=custom

if canTalkToATMEGAviaSPI
then
    export ROV_BOARD=board25
else
    export ROV_BOARD=cape
fi

echo "$ROV_BOARD" > /var/run/rov_board

exit 0


text:
<?php
/**
 * DrupalPractice_Sniffs_General_OptionsTSniff
 *
 * PHP version 5
 *
 * @category PHP
 * @package  PHP_CodeSniffer
 * @link     http://pear.php.net/package/PHP_CodeSniffer
 */

/**
 * Checks that values in #otions form arrays are translated.
 *
 * @category PHP
 * @package  PHP_CodeSniffer
 * @link     http://pear.php.net/package/PHP_CodeSniffer
 */
class DrupalPractice_Sniffs_General_OptionsTSniff implements PHP_CodeSniffer_Sniff
{

    /**
     * Returns an array of tokens this test wants to listen for.
     *
     * @return array
     */
    public function register()
    {
        return array(T_CONSTANT_ENCAPSED_STRING);

    }//end register()

    /**
     * Processes this test, when one of its tokens is encountered.
     *
     * @param PHP_CodeSniffer_File $phpcsFile The current file being processed.
     * @param int                  $stackPtr  The position of the current token
     *                                        in the stack passed in $tokens.
     *
     * @return void
     */
    public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
    {
        // Look for the string "#options".
        $tokens = $phpcsFile->getTokens();
        if ($tokens[$stackPtr]['content'] !== '"#options"' && $tokens[$stackPtr]['content'] !== "'#options'") {
            return;
        }

        // Look for an opening array pattern that starts to define #options
        // values.
        $statementEnd = $phpcsFile->findNext(T_SEMICOLON, ($stackPtr + 1));
        $arrayString  = $phpcsFile->getTokensAsString(($stackPtr + 1), ($statementEnd - $stackPtr));
        // Cut out all the white space.
        $arrayString = preg_replace('/\s+/', '', $arrayString);

        if (strpos($arrayString, '=>array(') !== 0 && strpos($arrayString, ']=array(') !== 0) {
            return;
        }

        // We only search within the #options array.
        $arrayToken   = $phpcsFile->findNext(T_ARRAY, ($stackPtr + 1));
        $statementEnd = $tokens[$arrayToken]['parenthesis_closer'];

        // Go through the array by examining stuff after "=>".
        $arrow = $phpcsFile->findNext(T_DOUBLE_ARROW, ($stackPtr + 1), $statementEnd, false, null, true);
        while ($arrow !== false) {
            $arrayValue = $phpcsFile->findNext(T_WHITESPACE, ($arrow + 1), $statementEnd, true);
            // We are only interested in string literals that are not numbers
            // and more than 3 characters long.
            if ($tokens[$arrayValue]['code'] === T_CONSTANT_ENCAPSED_STRING
                && !is_numeric(substr($tokens[$arrayValue]['content'], 1, -1))
                && strlen($tokens[$arrayValue]['content']) > 5
            ) {
                // We need to make sure that the string is the one and only part
                // of the array value.
                $afterValue = $phpcsFile->findNext(T_WHITESPACE, ($arrayValue + 1), $statementEnd, true);
                if ($tokens[$afterValue]['code'] === T_COMMA || $tokens[$afterValue]['code'] === T_CLOSE_PARENTHESIS) {
                    $warning = '#options values usually have to run through t() for translation';
                    $phpcsFile->addWarning($warning, $arrayValue, 'TforValue');
                }
            }

            $arrow = $phpcsFile->findNext(T_DOUBLE_ARROW, ($arrow + 1), $statementEnd, false, null, true);
        }

    }//end process()

}//end class


text:
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';

import {
  fetchSithList,
  navigateUp,
  navigateDown
} from 'pods/sith/actions';
import IndexComponent from './component';

function mapStateToProps (state) {
  const {
    location,
    sith
  } = state;

  return {
    location,
    sith
  };
}

function mapDispatchToProps (dispatch) {
  return bindActionCreators({
    fetchSithList,
    navigateUp,
    navigateDown
  }, dispatch);
}

function mergeProps (stateProps, dispatchProps) {
  return Object.assign({}, stateProps, {
    actions: {
      ...dispatchProps
    }
  });
}

export default connect(
  mapStateToProps,
  mapDispatchToProps,
  mergeProps
)(IndexComponent);


text: MessageFormat.locale.mr=function(n){return n===1?"one":"other"}


text:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Blink.SQL;
using Blink.Util;

namespace Blink
{
    public class BlinkDatabaseInitializer<TContext, TMigrationsConfiguration> : IDatabaseInitializer<TContext>
        where TContext : DbContext
        where TMigrationsConfiguration : DbMigrationsConfiguration<TContext>, new()
    {
        private readonly BlinkPreparationOptions context;

        public BlinkDatabaseInitializer(BlinkPreparationOptions context)
        {
            this.context = context;
        }

        private static string previouslyCalculatedHash = null;

        public void InitializeDatabase(TContext context)
        {
            Log("Initializing " + context.Database.Connection.Database);

            var mode = this.context.DBCreationMode;
            var dbExists = context.Database.Exists();
            if (!dbExists)
            {
                // we can't re-use the db if it doesn't yet exist, so for this run we're
                // switching to creating it;
                Log("Recreating the database because it does not yet exist.");
                mode = BlinkDBCreationMode.RecreateEveryTest;
            }

            Log("Reading SQL Server configuration and backup directory");
            var sqlServer = new SqlServerInfo(context);
            var backupDirectory = sqlServer.GetBackupDirectory();
            Log("Backup directory is " + backupDirectory);

            // identify this context in the cache;
            string hash;
            if (previouslyCalculatedHash == null)
            {
                Log("Calculating DB hash");

                hash = context.DbContextHash();

                if (this.context.SignatureGenerator != null)
                {
                    hash += "|" + this.context.SignatureGenerator();
                }

                hash = hash.WithoutPathCharacters();

                previouslyCalculatedHash = hash;
                Log("DB hash calculated");
            }
            else
            {
                Log("Hash has already been calculated this run!");
                hash = previouslyCalculatedHash;
            }

            var dbName = context.Database.Connection.Database;
            var safeDbName = dbName.WithoutPathCharacters();
            var backupFile = Path.Combine(backupDirectory, string.Format("BlinkDb_{0}_{1}.bak", safeDbName, hash));

            // is there a backup file for this context?
            bool backupExists = File.Exists(backupFile);
            Log("Using backup file '" + backupFile + " for the database, which " + (backupExists ? "exists." : "does not exist."));

            if (!backupExists)
            {
                // no backup for this version -- we'll need to
                // recreate - the DB will be out of date.
                Log("Recreating the database because there is no appropriate cache.");
                mode = BlinkDBCreationMode.RecreateEveryTest;
            }

            if (mode == BlinkDBCreationMode.UseDBIfItAlreadyExists)
            {
                // no need to do anything
                Log("The database already exists. Initialization is complete.");
                return;
            }

            if (dbExists)
            {
                // nuke the database
                ForceDropDatabase(context);
            }

            if (backupExists)
            {
                // restore from disk
                RestoreDb(context, backupFile);
            }
            else
            {
                // rebuild db from scratch and backup for later runs;
                BuildDb(context);
                BackupDb(context, backupFile);

                // because this is a new DB, the hash needs to be cleared
                previouslyCalculatedHash = null;
            }

            Log("The database already exists. Initialization is complete.");

        }

        private void Log(string message)
        {
            Logging.Log(message);
        }

        private void RestoreDb(TContext context, string backupFile)
        {
            Log("Restoring the database from '" + backupFile + "'.");
            context.ExecuteSqlAsMaster(SqlScripts.Restore, new
            {
                databaseName = context.Database.Connection.Database,
                backupPath = backupFile
            });
        }

        private void BackupDb(TContext context, string backupFile)
        {
            Log("Backing up the existing database.");
            context.ExecuteSqlAsMaster(SqlScripts.Backup, new
            {
                sourceDb = context.Database.Connection.Database,
                backupPath = backupFile
            });
        }

        private void BuildDb(TContext context)
        {
            Log("Creating the databsase and applying migrations.");
            var config = new TMigrationsConfiguration();
            config.TargetDatabase = new System.Data.Entity.Infrastructure.DbConnectionInfo(context.Database.Connection.ConnectionString, "System.Data.SqlClient");
            var migrator = new DbMigrator(config);
            migrator.Update();
        }

        private void ForceDropDatabase(TContext context)
        {
            if (context.Database.Exists())
            {
                Log("Dropping thr existing database.");

                // set the database to SINGLE_USER so it can be dropped
                context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, "ALTER DATABASE [" + context.Database.Connection.Database + "] SET SINGLE_USER WITH ROLLBACK IMMEDIATE");

                // drop the database
                context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, "USE master DROP DATABASE [" + context.Database.Connection.Database + "]");
            }
        }
    }
}


text:
package org.endeavourhealth.enterprise.core.database.models.data;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import java.io.Serializable;

@Embeddable
public class ReportResultOrganisationEntityKey implements Serializable {

	private long reportResultId;
	private long organisationId;

	@Basic
	@Column(name = "ReportResultId", nullable = false)
	public long getReportResultId() {
		return reportResultId;
	}

	public ReportResultOrganisationEntityKey setReportResultId(long reportResultId) {
		this.reportResultId = reportResultId;
		return this;
	}

	@Basic
	@Column(name = "OrganisationId", nullable = false)
	public long getOrganisationId() {
		return organisationId;
	}

	public ReportResultOrganisationEntityKey setOrganisationId(long organisationId) {
		this.organisationId = organisationId;
		return this;
	}

	@Override
	public boolean equals(Object o) {
		if (this == o) return true;
		if (o == null || getClass() != o.getClass()) return false;

		ReportResultOrganisationEntityKey that = (ReportResultOrganisationEntityKey) o;

		if (reportResultId != that.reportResultId) return false;
		if (organisationId != that.organisationId) return false;

		return true;
	}

	@Override
	public int hashCode() {
		int result = (int) (reportResultId ^ (reportResultId >>> 32));
		result = 31 * result + (int) (organisationId ^ (organisationId >>> 32));
		return result;
	}
}


text:
require_relative 'boot'
require 'rails/all'
Bundler.require(*Rails.groups)

module TimeGiver
  class Application < Rails::Application
    config.sass.preferred_syntax = :sass
    config.assets.precompile += %w(*.png *.jpg *.jpeg *.gif)
    config.i18n.available_locales = [:ja, :de, :nl, :en]
    config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
    config.i18n.default_locale = :en
  end
end


text:
package com.tle.web.controls.youtube.migration;

import com.tle.core.guice.Bind;
import com.tle.core.hibernate.impl.HibernateMigrationHelper;
import com.tle.core.migration.AbstractHibernateDataMigration;
import com.tle.core.migration.MigrationInfo;
import com.tle.core.migration.MigrationResult;
import com.tle.core.plugins.impl.PluginServiceImpl;
import com.tle.core.xml.service.XmlService;
import com.tle.web.sections.SectionUtils;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.apache.log4j.Logger;
import org.hibernate.ScrollableResults;
import org.hibernate.annotations.AccessType;
import org.hibernate.classic.Session;

/**
 * Solution for Redmine #7946. Older youtube attachments record only the playUrl, and not the
 * videoId as a discrete value. The youtube player now looks for the videoId saved in the
 * Attachments metadata, and composes a new URL on the fly, no longer restricted to the 'old-style'
 * playUrl value. Accordingly, for older youtube attachments which lack the videoId, it is necessary
 * to parse the playUrl value, extract and preserve the video Id substring as the videoId value.

 * Looking for URL values of the form
 * http://www.youtube.com/x/y/z/AA00BB11CC3?foo=whatever&bar=whateverelse, where we're indifferent
 * as to the path segments (x/y/z) if any between the server and the 11-character identifier, and
 * equally indifferent as to the param key-values pairs if any. What we're looking for is the
 * vidoeId string which is the last path segment before the key-value parameters. (In practice this
 * videoId appears to be always 11 characters long). We look for an explicit videoId key-value in
 * the attachments attribute Map, and having established the absence thereof, update the attachments
 * data map with an explicit vidoeId extracted from the full URL.

 * NB - some youtube URLs in the system lack a '?' dividing the URL path from the query key-value
 * parameters eg http://www.youtube.com/x/y/z/AA00BB11CC3&foo=woteva&bar=wotevaelse, hence we allow
 * our parse of the URL to accept this oddity.
 *
 * @author larry
 */
@SuppressWarnings("nls")
@Bind
@Singleton
public class UpdateOlderYoutubeAttachmentMigration extends AbstractHibernateDataMigration {
  private static final Logger LOGGER =
      Logger.getLogger(UpdateOlderYoutubeAttachmentMigration.class);
  private static final String keyPrefix =
      PluginServiceImpl.getMyPluginId(UpdateOlderYoutubeAttachmentMigration.class) + ".migration.";

  private static final String YOUTUBE_URL = "http://www.youtube.com";
  private static final String PLAY_URL_KEY = "playUrl";
  private static final String VIDEO_ID_KEY = "videoId";
  private static final String KEY_PATH = "$PATH$";

  @Inject private XmlService xmlService;

  @Override
  public MigrationInfo createMigrationInfo() {
    return new MigrationInfo(
        keyPrefix + "older.youtube.title", keyPrefix + "older.youtube.description");
  }

  @Override
  protected void executeDataMigration(
      HibernateMigrationHelper helper, MigrationResult result, Session session) throws Exception {
    // Query for attachments with a node with text value "playUrl", and
    // another node with text value beginning with the youtube URL
    String query =
        "From Attachment a "
            + " where a.data like '%<string>"
            + PLAY_URL_KEY
            + "</string>%'"
            + " and a.data like '%<string>"
            + YOUTUBE_URL
            + "%'";

    ScrollableResults scroll = session.createQuery(query).scroll();
    result.incrementStatus();
    int numProcessed = 0;
    while (scroll.next()) {
      FakeAttachment attachment = (FakeAttachment) scroll.get(0);

      Map<String, Object> dataMap =
          xmlService.deserialiseFromXml(getClass().getClassLoader(), attachment.data);
      boolean dataMapModified = checkForUpdate(dataMap);
      if (dataMapModified) {
        attachment.data = xmlService.serialiseToXml(dataMap);
        session.save(attachment);
        session.flush();
        session.clear();
        result.incrementStatus();
        numProcessed++;
      }
    }
    LOGGER.info(numProcessed + " youtube URLs updated with extracted videoIds");
  }

  /**
   * @see
   *     com.tle.core.migration.AbstractHibernateDataMigration#countDataMigrations(com.tle.core.hibernate.impl.HibernateMigrationHelper,
   *     org.hibernate.classic.Session)
   */
  @Override
  protected int countDataMigrations(HibernateMigrationHelper helper, Session session) {
    // Burdensome to evaluate
    return 1;
  }

  public static boolean checkForUpdate(Map<String, Object> dataMap) {
    boolean wasModified = false;
    Object playUrlObj = dataMap.get(PLAY_URL_KEY);
    if (playUrlObj != null) {
      String playUrl = playUrlObj.toString();
      if (playUrl.startsWith(YOUTUBE_URL)) // we assume
      {
        int lastSlash = playUrl.lastIndexOf('/');
        // URL longer than just the server path
        if (lastSlash > 6 && lastSlash < playUrl.length()) {
          Object videoIdObj = dataMap.get(VIDEO_ID_KEY);
          if (videoIdObj == null) {
            Map<String, String[]> parsedUrlMap = SectionUtils.parseParamUrl(playUrl, true);
            String urlPath = parsedUrlMap.get(KEY_PATH)[0];
            String extractedVideoId = urlPath.substring(lastSlash + 1);
            dataMap.put(VIDEO_ID_KEY, extractedVideoId);
            wasModified = true;
          }
        }
      }
    }
    return wasModified;
  }

  /** @see com.tle.core.migration.AbstractHibernateDataMigration#getDomainClasses() */
  @Override
  protected Class<?>[] getDomainClasses() {
    return new Class[] {FakeAttachment.class};
  }

  @Entity(name = "Attachment")
  @AccessType("field")
  public static class FakeAttachment {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    long id;

    @Column(length = 8192)
    String data;
  }
}


text:
'use stritc'

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var InfocursoSchema = Schema({
	curso: String,
	fecini: String,
	fecfin: String,
	duracion: String,
	cargahor: String
});

module.exports = mongoose.model('Infocurso', InfocursoSchema);


text:
using System;
using NUnit.Framework;
using spectator.Sources.PerformanceCounters;

namespace spectator.Tests.Sources
{
    [TestFixture]
    public class PerformanceCounterAdapterTests
    {
        [Test]
        public void when_performance_counter_does_not_exist_then_an_exception_is_thrown()
        {
            Assert.Throws<InvalidOperationException>(() => new PerformanceCounterAdapter("does", "not", "exist"));
        }
    }
}


text:
function randomColor()
  return {
    math.random(0,255),
    math.random(0,255),
    math.random(0,255),
    255
  }
end

function love.load(arg)
  if arg[#arg] == "-debug" then require("mobdebug").start() end
  -- WARNING - this needs to be rough for Intel HD4400
  love.graphics.setPointStyle("rough")

  playerCount = 2
  currentPlayer = 1
  boardSizeX = 10 -- in tiles
  boardSizeY = 10
  boardOffsetX = 10 -- in pixels
  boardOffsetY = 10
  tileSizeX = math.floor((love.graphics.getWidth() - boardOffsetX) / boardSizeX) -- in pixels
  tileSizeY = math.floor((love.graphics.getHeight() - boardOffsetY) / boardSizeY)

  players = {}
  for i = 1,playerCount do
    local px = 5
    local py = 3 + i

    players[i] = {
      lines = { {x = px, y = py} },

      vx = 0,
      vy = 0,
      name = "player_" .. i,
      color = randomColor(),
    }
  end
end

function love.update(dt)

end

function love.keypressed(k)
   if k == 'escape' then
      love.event.quit()
   end
end

function advancePlayer()
  local function nextPlayer(p)
    p = p + 1
    if p > playerCount then
      return 1
    else
      return p
    end
  end

  currentPlayer = nextPlayer(currentPlayer)
end

function drawPlayers()
  local function setPlayerColor(player)
    love.graphics.setColor(player.color)
  end

  local function drawPlayerLines(player)
    if #player.lines < 2 then
      return
    end

    for i = 1, #player.lines - 1 do
      local p1 = getScreenCoordFromBoardCoord(player.lines[i])
      local p2 = getScreenCoordFromBoardCoord(player.lines[i+1])

      love.graphics.line(
        p1.x,
        p1.y,
        p2.x,
        p2.y
      )
    end
  end

  local function drawPlayerPoint(player)
    love.graphics.setPointSize(20)
    local p = player.lines[#player.lines]
    local pScreen = getScreenCoordFromBoardCoord(p)
    love.graphics.point(pScreen.x, pScreen.y)
  end

  for _,p in ipairs(players) do
    setPlayerColor(p)
    drawPlayerLines(p)
    drawPlayerPoint(p)
  end
end

function getBoardCoordFromScreenCoord(s)
  -- adding half makes it stick to tile edges (i.e. line crosses)
  return {
    x = math.floor((s.x - boardOffsetX ) / tileSizeX + 0.5) + 1,
    y = math.floor((s.y - boardOffsetY) / tileSizeY + 0.5) + 1
  }
end

function getScreenCoordFromBoardCoord(c)
  return {
    x = (c.x - 1) * tileSizeX + boardOffsetX,
    y = (c.y - 1) * tileSizeY + boardOffsetY
  }
end

function love.mousereleased(x, y, button)
  local c = getBoardCoordFromScreenCoord({ x = x, y = y })
  table.insert(players[currentPlayer].lines, c)
  advancePlayer()
end

function isValidMove(playerId, position)
end

function love.draw()
  --love.graphics.setColor(20,255,0,128)
  --love.graphics.print("Hello Ruda", 100, 100)

  --local x = love.mouse.getX()
  --local y = love.mouse.getY()

  -- drawing size of a tile in pixels

  love.graphics.setColor(128,128,128,255)
  love.graphics.setPointSize(2)
  -- offset simply adds left-top margin to the board
  for x = 1, boardSizeX do
    for y = 1, boardSizeY do
      local p = getScreenCoordFromBoardCoord({ x = x, y = y })

      love.graphics.point(p.x, p.y)
    end
  end

  drawPlayers()
end


text:
body {
  padding-top: 70px;
}

.navbar-custom {
  background-color: #0273d4;
  color: #ffffff;
  border-radius: 0;
}

.navbar-custom .navbar-nav>li>a {
  color: #ffffff;
}

.navbar-custom .navbar-nav>li>a:hover, .navbar-custom .navbar-nav>li>a:focus {
  background-color: #0143a3;
}

.navbar-custom .navbar-brand {
  color: #ffffff;
}

.navbar-custom .navbar-brand:hover, .navbar-custom .navbar-brand:focus {
  background-color: #0143a3;
}


text:
module StructuredWarnings
  # This module encapsulates the extensions to Object, that are introduced
  # by this library.
  module Kernel

    # :call-seq:
    #   warn(message = nil)
    #   warn(warning_class, message)
    #   warn(warning_instance)
    #
    # This method provides a +raise+-like interface. It extends the default
    # warn in ::Kernel to allow the use of structured warnings.
    #
    # Internally it uses the StructuredWarnings::warner to format a message
    # based on the given warning class, the message and a stack frame.
    # The return value is passed to super, which is likely the implementation
    # in ::Kernel. That way, it is less likely, that structured_warnings
    # interferes with other extensions.
    #
    # It the warner return nil or an empty string the underlying warn will not
    # be called. That way, warnings may be transferred to other devices without
    # the need to redefine ::Kernel#warn.
    #
    # Just like the original version, this method does not take command line
    # switches or verbosity levels into account. In order to deactivate all
    # warnings use Warning.disable.
    #
    #   warn "This is an old-style warning" # This will emit a StandardWarning
    #
    #   class Foo
    #     def bar
    #       warn DeprecationWarning, "Never use bar again, use beer"
    #     end
    #     def beer
    #       "Ahhh"
    #     end
    #   end
    #
    #   warn Warning.new("The least specific warning you can get")
    #
    def warn(*args)
      first = args.shift
      if first.is_a? Class and first <= Warning
        warning = first
        message = args.shift

      elsif first.is_a? Warning
        warning = first.class
        message = first.message

      else
        warning = StandardWarning
        message = first.to_s
      end

      # If args is not empty, user passed an incompatible set of arguments.
      # Maybe somebody else is overriding warn as well and knows, what to do.
      # Better do nothing in this case. See #5
      return super unless args.empty?

      if warning.active?
        output = StructuredWarnings.warner.format(warning, message, caller(1))
        super(output) unless output.nil? or output.to_s.empty?
      end
    end
  end
end


text:
NSString *const deviceDidReceiveIncoming = @"deviceDidReceiveIncoming";
NSString *const deviceDidStartListening = @"deviceDidStartListening";
NSString *const deviceDidStopListening = @"deviceDidStopListening";
NSString *const connectionDidFail = @"connectionDidFail";
NSString *const connectionDidStartConnecting = @"connectionDidStartConnecting";
NSString *const connectionDidConnect = @"connectionDidConnect";
NSString *const connectionDidDisconnect = @"connectionDidDisconnect";
NSString *const deviceReady = @"deviceReady";

@implementation RCTTwilio
{
  TCDevice* _phone;
  TCConnection* _connection;
  TCConnection* _pendingConnection;
}

RCT_EXPORT_MODULE();

@synthesize bridge = _bridge;

- (NSArray<NSString *> *)supportedEvents {
  return @[deviceDidReceiveIncoming, deviceDidStartListening, deviceDidStopListening, connectionDidFail, connectionDidStartConnecting, connectionDidConnect, connectionDidDisconnect, deviceReady];
}

RCT_EXPORT_METHOD(initWithTokenUrl:(NSString *) tokenUrl) {
  NSURL *url = [NSURL URLWithString: tokenUrl];
  NSError *error = nil;
  NSString *token = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
  if (token == nil) {
    NSLog(@"Error retrieving token: %@", [error localizedDescription]);
  } else {
    _phone = [[TCDevice alloc] initWithCapabilityToken:token delegate:self];
    [self sendEventWithName:deviceReady body:nil];
  }
}

RCT_EXPORT_METHOD(initWithToken:(NSString *) token) {
  _phone = [[TCDevice alloc] initWithCapabilityToken:token delegate:self];
  [self sendEventWithName:deviceReady body:nil];
}

RCT_EXPORT_METHOD(connect:(NSDictionary *) params) {
  _connection = [_phone connect:params delegate:self];
}

RCT_EXPORT_METHOD(disconnect) {
  [_connection disconnect];
}

RCT_EXPORT_METHOD(accept) {
  [_pendingConnection accept];
  _connection = _pendingConnection;
  _pendingConnection = nil;
}

RCT_EXPORT_METHOD(reject) {
  [_pendingConnection reject];
}

RCT_EXPORT_METHOD(ignore) {
  [_pendingConnection ignore];
}

RCT_EXPORT_METHOD(setMuted:(BOOL)isMuted) {
  if (_connection && _connection.state == TCConnectionStateConnected) {
    [_connection setMuted:isMuted];
  }
}

RCT_EXPORT_METHOD(sendDigits:(NSString *) digits) {
  if (_connection && _connection.state == TCConnectionStateConnected) {
    [_connection sendDigits:digits];
  }
}

#pragma mark - TCDeviceDelegate

-(void)device:(TCDevice *)device didReceiveIncomingConnection:(TCConnection *)connection {
  _pendingConnection = connection;
  [_pendingConnection setDelegate:self];
  [self sendEventWithName:deviceDidReceiveIncoming body:connection.parameters];
}

-(void)deviceDidStartListeningForIncomingConnections:(TCDevice*)device {
  [self sendEventWithName:deviceDidStartListening body:nil];
}

-(void)device:(TCDevice *)device didStopListeningForIncomingConnections:(NSError *)error {
  id body = nil;
  if (error != nil) {
    body = @{@"err": [error localizedDescription]};
  }
  [self sendEventWithName:deviceDidStopListening body:body];
}

#pragma mark - TCConnectionDelegate

-(void)connection:(TCConnection *)connection didFailWithError:(NSError *)error {
  [self sendEventWithName:connectionDidFail body:@{@"err": [error localizedDescription]}];
}

-(void)connectionDidStartConnecting:(TCConnection *)connection {
  [self sendEventWithName:connectionDidStartConnecting body:connection.parameters];
}

-(void)connectionDidConnect:(TCConnection *)connection {
  [self sendEventWithName:connectionDidConnect body:nil];
}

-(void)connectionDidDisconnect:(TCConnection *)connection {
  if (connection == _connection) {
    _connection = nil;
  }

  if (connection == _pendingConnection) {
    _pendingConnection = nil;
  }
  [self sendEventWithName:connectionDidDisconnect body:nil];
}

@end


text:
require 'spec_helper'

describe Site do
  context "adding sites" do
    it "cannot be created without a uri" do
      no_uri=Site.create(comment: "no Uri")
      expect(no_uri.error_on(:uri)).to include("can't be blank")
    end
    it "cannot be created without a comment" do
      no_comment=Site.create(uri: "cnn.com")
      expect(no_comment.error_on(:comment)).to include("can't be blank")
    end
    it "is created with policy=production by default" do
      policy_default=Site.create(uri: "cnn.com", comment: "CNN")
      expect(policy_default.policy).to eq("production")
    end
    it "requires policy to be one of test, development,or production" do
      fail=Site.create(uri: "cnn.com", comment: "CNN", policy: "fail")
      test=Site.create(uri: "cnn.com", comment: "CNN", policy: "test")
      expect(fail.errors_on(:policy)).to include("must be one of: production, development, test")
      expect(test).to have(0).errors_on(:policy)
    end
    it "ensures uris are unique within a policy" do
      cnn_test=Site.create(uri: "cnn.com", comment: "CNN", policy: "test")
      cnn_fail=Site.create(uri: "cnn.com", comment: "CNN", policy: "test")
      expect(cnn_fail.errors_on(:uri)).to include("can only be included once per policy")
    end
    it "allows sites to be duplicated in separate policies" do
      cnn_test=Site.create(uri: "cnn.com", comment: "CNN", policy: "test")
      cnn_prod=Site.create(uri: "cnn.com", comment: "CNN", policy: "production")
      expect(cnn_prod).to have(0).errors_on(:uri)
    end
  end

  context "validating uris" do
    it "fails for invalid uris" do
      invalid=Site.create(uri: "----@:", comment: "invalid uri")
      expect(invalid.errors_on(:uri)).to include("Invalid URI: ----@:")
    end
  end

  context "stripping uri components" do
    it "strips everything from uri except the hostname and path" do
      schemed=Site.create(uri: "http://www.wibble.com/foo", comment: "has a scheme")
      expect(schemed.uri).to eq('www.wibble.com/foo')
    end
    it "saves hostname/path unaltered" do
      pathed=Site.create(uri: "wibble.com/foo", comment: "has a path and no scheme")
      expect(pathed.uri).to eq('wibble.com/foo')

    end
    it "saves bare hostnames unaltered" do
      hname=Site.create(uri: "wibble.com", comment: "has no path and no scheme")
      expect(hname.uri).to eq('wibble.com')
    end
  end
  context "adding and removing categories" do
    describe "#add" do
      it "adds individual categories by name"
      it "adds multiple categories by name"
      it "adds individual Category objects"
      it "adds multiple Category objects"
      it "adds categories as mixed strings and objects"
      context "with validation failure" do
        it "rejects invalid categorization"
        it "rejects invalid category names"
        it "rejects missing categories"
      end
    end
    describe "#remove" do
      it "removes individual categories by name"
      it "removes multiple categories by name"
      it "removes individual Category objects"
      it "removes multiple Category objects"
      it "removes categories as mixed strings and objects"
      context "with invalid association" do
        it "succeeds for categorizations not already associated"
        it "rejects invalid category names"
        it "rejects missing categories"
      end
    end
  end

end


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using Microsoft.Common.Core.IO;
using Microsoft.Common.Core.Logging;
using Microsoft.Common.Core.Services;
using Microsoft.R.Host.Client.BrokerServices;
using System.Threading;
using System.Threading.Tasks;

namespace Microsoft.R.Host.Client {
    public class RemotingWebServer : IRemotingWebServer {
        private readonly IServiceContainer _services;
        private readonly IFileSystem _fs;
        private readonly IActionLog _log;

        private LocalStaticFileServer _localStaticFileServer;
        private object _localStaticFileServerLock = new object();

        private RemoteStaticFileServer _remoteStaticFileServer;
        private object _remoteStaticFileServerLock = new object();

        public RemotingWebServer(IServiceContainer services) {
            _services = services;
            _fs = _services.FileSystem();
            _log = _services.Log();
        }

        public Task<string> HandleRemoteWebUrlAsync(string remoteUrl, string baseAddress, string name, IConsole console, CancellationToken ct = default(CancellationToken)) =>
            WebServer.CreateWebServerAndHandleUrlAsync(remoteUrl, baseAddress, name, _log, console, ct);

        public Task<string> HandleLocalStaticFileUrlAsync(string url, IConsole console, CancellationToken ct = default(CancellationToken)) =>
           GetOrCreateLocalStaticFileServer(console).HandleUrlAsync(url, ct);

        public Task<string> HandleRemoteStaticFileUrlAsync(string url,  IRSessionProvider rSessionProvider, IConsole console, CancellationToken ct = default(CancellationToken)) =>
            GetOrCreateRemoteStaticFileServerAsync(rSessionProvider, console).HandleUrlAsync(url, ct);

        private LocalStaticFileServer GetOrCreateLocalStaticFileServer(IConsole console) {
            lock (_localStaticFileServerLock) {
                _localStaticFileServer = _localStaticFileServer ?? new LocalStaticFileServer(_fs, _log, console);
            }
            return _localStaticFileServer;
        }

        private RemoteStaticFileServer GetOrCreateRemoteStaticFileServerAsync(IRSessionProvider rSessionProvider, IConsole console) {
            lock (_remoteStaticFileServerLock) {
                _remoteStaticFileServer = _remoteStaticFileServer ?? new RemoteStaticFileServer(rSessionProvider, _fs, _log, console);
            }
            return _remoteStaticFileServer;
        }
    }
}


text:
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  before_action :authenticate_user!
  before_action :configure_permitted_parameters, if: :devise_controller?

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:username, :email, :password, :password_confirmation])
    devise_parameter_sanitizer.permit(:sign_in, keys: [:login, :password, :password_confirmation])
    devise_parameter_sanitizer.permit(:account_update, keys: [:username, :email, :password, :password_confirmation, :current_password])
  end
end


text:
package br.com.softplan.jsversioning.process;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.maven.plugin.logging.Log;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class WebFilesProcessor {

    private Path webFilesDirectory;
    private Path webAppOutputDirectory;
    private Log log;

    public WebFilesProcessor(File webFilesDirectory, File webAppOutputDirectory, Log log) {
        this.webFilesDirectory = webFilesDirectory.toPath();
        this.webAppOutputDirectory = webAppOutputDirectory.toPath();
        this.log = log;
    }

    public void process() {
        this.log.debug("Start to walk the file tree of path on " + this.webFilesDirectory);
        try {
            Files.walkFileTree(this.webFilesDirectory, new WebFilesVisitor());
        } catch (Exception e) {
            throw new IllegalStateException("Error processing files: ", e);
        }
    }

    private class ScriptTagProcessor {

        private Pattern pattern = Pattern.compile("src=\"(.+\\.js)");
        private Map<String, String> jsVersionCache = new ConcurrentHashMap<>();

        public Optional<String> process(final Path filePath) throws IOException {

            String content = FileUtils.readFileToString(filePath.toFile(), Charset.defaultCharset());
            Matcher matcher = this.pattern.matcher(content);

            int changes = 0;
            while (matcher.find()) {
                changes++;
                String fileName = matcher.group(1);

                String version = this.jsVersionCache.get(fileName);
                if (StringUtils.isBlank(version)) {
                    version = new JsFile(fileName).getVersion();
                    this.jsVersionCache.put(fileName, version);
                }

                content = StringUtils.replace(content, String.format("\"%s\"", fileName), String.format("\"%s?n=%s\"", fileName, version));
            }

            if (changes > 0) {
                return Optional.ofNullable(content);
            }
            return Optional.empty();
        }

        private class JsFile {

            private String fileName;

            JsFile(String fileNamePath) {
                this.fileName = fileNamePath;
            }

            String getVersion() {
                Path jsFilePath = WebFilesProcessor.this.webFilesDirectory.resolve(fileName);
                return resolveFileChecksum(jsFilePath.toFile());
            }

            private String resolveFileChecksum(File file) {
                try {
                    String checksum = String.valueOf(FileUtils.checksumCRC32(file));
                    WebFilesProcessor.this.log.info("JS : " + file.toString() + ", CHECKSUM: " + checksum);
                    return checksum;
                } catch (IOException e) {
                    WebFilesProcessor.this.log.debug("Failed to generate checksum for file: " + file.getAbsolutePath(), e);
                    return getRandomVersion(fileName);
                }
            }

            private String getRandomVersion(String fileName) {
                String randomString = UUID.randomUUID().toString();
                WebFilesProcessor.this.log.info("JS NOT FOUND: " + fileName + ", VERSION: " + randomString);
                return randomString;
            }

        }
    }

    private class WebFileWriter {

        void write(Path filePath,
                   String content) {
            try {
                Path relativeFilePath = WebFilesProcessor.this.webFilesDirectory.relativize(filePath);
                Path destinationFilePath = WebFilesProcessor.this.webAppOutputDirectory.resolve(relativeFilePath);
                Files.createDirectories(destinationFilePath.getParent());
                Files.write(destinationFilePath, content.getBytes());
            } catch (Exception e) {
                throw new IllegalStateException("Couldn't write modified web file: ", e);
            }
        }

    }

    private class WebFilesVisitor extends SimpleFileVisitor<Path> {

        private ScriptTagProcessor scriptTagProcessor = new ScriptTagProcessor();
        private WebFileWriter webFileWriter = new WebFileWriter();

        @Override
        public FileVisitResult visitFile(Path filePath,
                                         BasicFileAttributes attrs) throws IOException {
            String contentType = Files.probeContentType(filePath);
            if (!contentType.contains("image")) {
                log.debug("Checking file: " + filePath);
                this.scriptTagProcessor.process(filePath)
                        .ifPresent(content -> this.webFileWriter.write(filePath, content));
            } else {
                log.debug("File is an image or video: " + filePath);
            }
            return FileVisitResult.CONTINUE;
        }

    }

}