text:
angular.module('security.login.form', ['services.localizedMessages'])

// The LoginFormController provides the behaviour behind a reusable form to allow users to authenticate.
// This controller and its template (login/form.tpl.html) are used in a modal dialog box by the security service.
.controller('LoginFormController', ['$scope', 'security', 'localizedMessages', function($scope, security, localizedMessages) {
    // The model for this form
    $scope.user = {};

    // Any error message from failing to login
    $scope.authError = null;

    // The reason that we are being asked to login - for instance because we tried to access something to which we are not authorized
    // We could do something diffent for each reason here but to keep it simple...
    $scope.authReason = null;
    if ( security.getLoginReason() ) {
        $scope.authReason = ( security.isAuthenticated() ) ?
            localizedMessages.get('login.reason.notAuthorized') :
            localizedMessages.get('login.reason.notAuthenticated');
    }

    // Attempt to authenticate the user specified in the form's model
    $scope.login = function() {
        // Clear any previous security errors
        $scope.authError = null;

        // Try to login
        security.login($scope.user.email, $scope.user.password).then(function(loggedIn) {
            if ( !loggedIn ) {
                // If we get here then the login failed due to bad credentials
                $scope.authError = localizedMessages.get('login.error.invalidCredentials');
            }
        }, function(x) {
            // If we get here then there was a problem with the login request to the server
            $scope.authError = localizedMessages.get('login.error.serverError', { exception: x });
        });
    };

    $scope.clearForm = function() {
        $scope.user = {};
    };

    $scope.cancelLogin = function() {
        security.cancelLogin();
    };
}]);

redpajama_set_name: RedPajamaGithub


text:
/* (c) 2014 LinkedIn Corp. All rights reserved.
 *
 * 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.
 */

package gobblin.converter;

import java.util.Iterator;

import com.google.common.collect.ImmutableSet;

/**
 * A type of {@link java.lang.Iterable}s corresponding to empty {@link java.util.Collection}s.
 *
 * @author ynli
 *
 * @param <T> record type
 */
public class EmptyIterable<T> implements Iterable<T> {

  @Override
  public Iterator<T> iterator() {
    return ImmutableSet.<T>of().iterator();
  }
}


text:
$(document).ready(function(){
    $('.modal-trigger').leanModal();

$('.dropdown-button').dropdown();

function myfunc(){
	console.log('hello');
}
});

// //AJAX part of upvote
// var upvotebtn = document.querySelector('#upvotebtn');

// upvotebtn.addEventListener('click',function(){
// 	console.log('clicked');
// 	var xhttp = new XMLHttpRequest();
// 	xhttp.onreadystatechange  = function(){
// 		console.log('changed');
// 	};
// 	xhttp.open('GET','{{url_for('auth.upvote')}}',true);
// 	xhttp.send();
// });


text:
"""Compare gradients computed with adjoint vs analytical solution."""
import sys

sys.path = sys.path[1:]  # A hack so that we always import the installed library.

import pytest
import torch
import torchsde
from torchsde.settings import LEVY_AREA_APPROXIMATIONS, METHODS, NOISE_TYPES, SDE_TYPES

from . import utils
from . import problems

torch.manual_seed(1147481649)
torch.set_default_dtype(torch.float64)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
dtype = torch.get_default_dtype()

def _methods():
    yield SDE_TYPES.ito, METHODS.milstein, None
    yield SDE_TYPES.ito, METHODS.srk, None
    yield SDE_TYPES.stratonovich, METHODS.midpoint, None
    yield SDE_TYPES.stratonovich, METHODS.reversible_heun, None

@pytest.mark.parametrize("sde_cls", [problems.ExDiagonal, problems.ExScalar, problems.ExAdditive,
                                     problems.NeuralGeneral])
@pytest.mark.parametrize("sde_type, method, options", _methods())
@pytest.mark.parametrize('adaptive', (False,))
def test_against_numerical(sde_cls, sde_type, method, options, adaptive):
    # Skipping below, since method not supported for corresponding noise types.
    if sde_cls.noise_type == NOISE_TYPES.general and method in (METHODS.milstein, METHODS.srk):
        return

    d = 3
    m = {
        NOISE_TYPES.scalar: 1,
        NOISE_TYPES.diagonal: d,
        NOISE_TYPES.general: 2,
        NOISE_TYPES.additive: 2
    }[sde_cls.noise_type]
    batch_size = 4
    t0, t1 = ts = torch.tensor([0.0, 0.5], device=device)
    dt = 1e-3
    y0 = torch.full((batch_size, d), 0.1, device=device)
    sde = sde_cls(d=d, m=m, sde_type=sde_type).to(device)

    if method == METHODS.srk:
        levy_area_approximation = LEVY_AREA_APPROXIMATIONS.space_time
    else:
        levy_area_approximation = LEVY_AREA_APPROXIMATIONS.none
    bm = torchsde.BrownianInterval(
        t0=t0, t1=t1, size=(batch_size, m), dtype=dtype, device=device,
        levy_area_approximation=levy_area_approximation
    )

    if method == METHODS.reversible_heun:
        tol = 1e-6
        adjoint_method = METHODS.adjoint_reversible_heun
        adjoint_options = options
    else:
        tol = 1e-2
        adjoint_method = None
        adjoint_options = None

    def func(inputs, modules):
        y0, sde = inputs[0], modules[0]
        ys = torchsde.sdeint_adjoint(sde, y0, ts, dt=dt, method=method, adjoint_method=adjoint_method,
                                     adaptive=adaptive, bm=bm, options=options, adjoint_options=adjoint_options)
        return (ys[-1] ** 2).sum(dim=1).mean(dim=0)

    # `grad_inputs=True` also works, but we really only care about grad wrt params and want fast tests.
    utils.gradcheck(func, y0, sde, eps=1e-6, rtol=tol, atol=tol, grad_params=True)

def _methods_dt_tol():
    for sde_type, method, options in _methods():
        if method == METHODS.reversible_heun:
            yield sde_type, method, options, 2**-3, 1e-3, 1e-4
            yield sde_type, method, options, 1e-3, 1e-3, 1e-4
        else:
            yield sde_type, method, options, 1e-3, 1e-2, 1e-2

@pytest.mark.parametrize("sde_cls", [problems.NeuralDiagonal, problems.NeuralScalar, problems.NeuralAdditive,
                                     problems.NeuralGeneral])
@pytest.mark.parametrize("sde_type, method, options, dt, rtol, atol", _methods_dt_tol())
@pytest.mark.parametrize("len_ts", [2, 9])
def test_against_sdeint(sde_cls, sde_type, method, options, dt, rtol, atol, len_ts):
    # Skipping below, since method not supported for corresponding noise types.
    if sde_cls.noise_type == NOISE_TYPES.general and method in (METHODS.milstein, METHODS.srk):
        return

    d = 3
    m = {
        NOISE_TYPES.scalar: 1,
        NOISE_TYPES.diagonal: d,
        NOISE_TYPES.general: 2,
        NOISE_TYPES.additive: 2
    }[sde_cls.noise_type]
    batch_size = 4
    ts = torch.linspace(0.0, 1.0, len_ts, device=device, dtype=torch.float64)
    t0 = ts[0]
    t1 = ts[-1]
    y0 = torch.full((batch_size, d), 0.1, device=device, dtype=torch.float64, requires_grad=True)
    sde = sde_cls(d=d, m=m, sde_type=sde_type).to(device, torch.float64)

    if method == METHODS.srk:
        levy_area_approximation = LEVY_AREA_APPROXIMATIONS.space_time
    else:
        levy_area_approximation = LEVY_AREA_APPROXIMATIONS.none
    bm = torchsde.BrownianInterval(
        t0=t0, t1=t1, size=(batch_size, m), dtype=torch.float64, device=device,
        levy_area_approximation=levy_area_approximation
    )

    if method == METHODS.reversible_heun:
        adjoint_method = METHODS.adjoint_reversible_heun
        adjoint_options = options
    else:
        adjoint_method = None
        adjoint_options = None

    ys_true = torchsde.sdeint(sde, y0, ts, dt=dt, method=method, bm=bm, options=options)
    grad = torch.randn_like(ys_true)
    ys_true.backward(grad)

    true_grad = torch.cat([y0.grad.view(-1)] + [param.grad.view(-1) for param in sde.parameters()])
    y0.grad.zero_()
    for param in sde.parameters():
        param.grad.zero_()

    ys_test = torchsde.sdeint_adjoint(sde, y0, ts, dt=dt, method=method, bm=bm, adjoint_method=adjoint_method,
                                      options=options, adjoint_options=adjoint_options)
    ys_test.backward(grad)
    test_grad = torch.cat([y0.grad.view(-1)] + [param.grad.view(-1) for param in sde.parameters()])

    torch.testing.assert_allclose(ys_true, ys_test)
    torch.testing.assert_allclose(true_grad, test_grad, rtol=rtol, atol=atol)

@pytest.mark.parametrize("problem", [problems.BasicSDE1, problems.BasicSDE2, problems.BasicSDE3, problems.BasicSDE4])
@pytest.mark.parametrize("method", ["milstein", "srk"])
@pytest.mark.parametrize('adaptive', (False, True))
def test_basic(problem, method, adaptive):
    d = 10
    batch_size = 128
    ts = torch.tensor([0.0, 0.5], device=device)
    dt = 1e-3
    y0 = torch.zeros(batch_size, d).to(device).fill_(0.1)

    problem = problem(d).to(device)

    num_before = _count_differentiable_params(problem)

    problem.zero_grad()
    _, yt = torchsde.sdeint_adjoint(problem, y0, ts, method=method, dt=dt, adaptive=adaptive)
    loss = yt.sum(dim=1).mean(dim=0)
    loss.backward()

    num_after = _count_differentiable_params(problem)
    assert num_before == num_after

def _count_differentiable_params(module):
    return len([p for p in module.parameters() if p.requires_grad])


text:
/**
 * @author mr.doob / http://mrdoob.com/
 */

THREE.Scene = function () {

	THREE.Object3D.call( this );

	this.fog = null;
	this.overrideMaterial = null;

	this.matrixAutoUpdate = false;

	this.__objects = [];
	this.__lights = [];

	this.__objectsAdded = [];
	this.__objectsRemoved = [];

};

THREE.Scene.prototype = new THREE.Object3D();
THREE.Scene.prototype.constructor = THREE.Scene;

THREE.Scene.prototype.__addObject = function ( object ) {

	if ( object instanceof THREE.Light ) {

		if ( this.__lights.indexOf( object ) === - 1 ) {

			this.__lights.push( object );

		}

	} else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {

		if ( this.__objects.indexOf( object ) === - 1 ) {

			this.__objects.push( object );
			this.__objectsAdded.push( object );

			// check if previously removed

			var i = this.__objectsRemoved.indexOf( object );

			if ( i !== -1 ) {

				this.__objectsRemoved.splice( i, 1 );

			}

		}

	}

	for ( var c = 0; c < object.children.length; c ++ ) {

		this.__addObject( object.children[ c ] );

	}

};

THREE.Scene.prototype.__removeObject = function ( object ) {

	if ( object instanceof THREE.Light ) {

		var i = this.__lights.indexOf( object );

		if ( i !== -1 ) {

			this.__lights.splice( i, 1 );

		}

	} else if ( !( object instanceof THREE.Camera ) ) {

		var i = this.__objects.indexOf( object );

		if( i !== -1 ) {

			this.__objects.splice( i, 1 );
			this.__objectsRemoved.push( object );

			// check if previously added

			var ai = this.__objectsAdded.indexOf( object );

			if ( ai !== -1 ) {

				this.__objectsAdded.splice( ai, 1 );

			}

		}

	}

	for ( var c = 0; c < object.children.length; c ++ ) {

		this.__removeObject( object.children[ c ] );

	}

};


text:
"""Check for uneffecient query to get number of objects using len"""
from django.shortcuts import render
from django.http import HttpResponseForbidden

from .models import Product, Category

def product_list_view(request):
    if request.is_authenticated():
        ctx = {'products': Product.objects.all(),
               'categories_count': len(Category.objects.all())}
        return render(request, 'product_list.html', context=ctx)
    else:
        return HttpResponseForbidden()


text:
/**
 * \file ir_import_prototypes.cpp
 * Import function prototypes from one IR tree into another.
 *
 * \author Ian Romanick
 */
#include "ir.h"
#include "glsl_symbol_table.h"

namespace {

/**
 * Visitor used to import function prototypes
 *
 * Normally the \c clone method of either \c ir_function or
 * \c ir_function_signature could be used.  However, we don't want a complete
 * clone of the \c ir_function_signature.  We want everything \b except the
 * body of the function.
 */
class import_prototype_visitor : public ir_hierarchical_visitor {
public:
   /**
    */
   import_prototype_visitor(exec_list *list, glsl_symbol_table *symbols,
			    void *mem_ctx)
   {
      this->mem_ctx = mem_ctx;
      this->list = list;
      this->symbols = symbols;
      this->function = NULL;
   }

   virtual ir_visitor_status visit_enter(ir_function *ir)
   {
      assert(this->function == NULL);

      this->function = this->symbols->get_function(ir->name);
      if (!this->function) {
	 this->function = new(this->mem_ctx) ir_function(ir->name);

	 list->push_tail(this->function);

	 /* Add the new function to the symbol table.
	  */
	 this->symbols->add_function(this->function);
      }
      return visit_continue;
   }

   virtual ir_visitor_status visit_leave(ir_function *ir)
   {
      (void) ir;
      assert(this->function != NULL);

      this->function = NULL;
      return visit_continue;
   }

   ir_visitor_status visit_enter(ir_function_signature *ir)
   {
      assert(this->function != NULL);

      ir_function_signature *copy = ir->clone_prototype(mem_ctx, NULL);

      this->function->add_signature(copy);

      /* Do not process child nodes of the ir_function_signature.  There can
       * never be any nodes inside the ir_function_signature that we care
       * about.  Instead continue with the next sibling.
       */
      return visit_continue_with_parent;
   }

private:
   exec_list *list;
   ir_function *function;
   glsl_symbol_table *symbols;
   void *mem_ctx;
};

} /* anonymous namespace */

/**
 * Import function prototypes from one IR tree into another
 *
 * \param source   Source instruction stream containing functions whose
 *                 prototypes are to be imported
 * \param dest     Destination instruction stream where new \c ir_function and
 *                 \c ir_function_signature nodes will be stored
 * \param symbols  Symbol table where new functions will be stored
 * \param mem_ctx  ralloc memory context used for new allocations
 */
void
import_prototypes(const exec_list *source, exec_list *dest,
		  glsl_symbol_table *symbols, void *mem_ctx)
{
   import_prototype_visitor v(dest, symbols, mem_ctx);

   /* Making source be const is just extra documentation.
    */
   v.run(const_cast<exec_list *>(source));
}


text:
namespace media {
class VideoCapturerSource;
}  // namespace media

namespace content {

// Representation of a video stream coming from a camera, owned by Blink as
// WebMediaStreamSource. Objects of this class are created and live on main
// Render thread. Objects can be constructed either by indicating a |device| to
// look for, or by plugging in a |source| constructed elsewhere.
class CONTENT_EXPORT MediaStreamVideoCapturerSource
    : public MediaStreamVideoSource {
 public:
  MediaStreamVideoCapturerSource(
      const SourceStoppedCallback& stop_callback,
      std::unique_ptr<media::VideoCapturerSource> source);
  MediaStreamVideoCapturerSource(const SourceStoppedCallback& stop_callback,
                                 const StreamDeviceInfo& device_info);
  ~MediaStreamVideoCapturerSource() override;

  // Implements MediaStreamVideoSource.
  void RequestRefreshFrame() override;

 private:
  friend class CanvasCaptureHandlerTest;
  friend class MediaStreamVideoCapturerSourceTest;

  // Implements MediaStreamVideoSource.
  void GetCurrentSupportedFormats(
      int max_requested_width,
      int max_requested_height,
      double max_requested_frame_rate,
      const VideoCaptureDeviceFormatsCB& callback) override;
  void StartSourceImpl(
      const media::VideoCaptureFormat& format,
      const blink::WebMediaConstraints& constraints,
      const VideoCaptureDeliverFrameCB& frame_callback) override;
  void StopSourceImpl() override;

  // Method to bind as RunningCallback in VideoCapturerSource::StartCapture().
  void OnStarted(bool result);

  const char* GetPowerLineFrequencyForTesting() const;

  // The source that provides video frames.
  const std::unique_ptr<media::VideoCapturerSource> source_;

  DISALLOW_COPY_AND_ASSIGN(MediaStreamVideoCapturerSource);
};

}  // namespace content

#endif  // CONTENT_RENDERER_MEDIA_MEDIA_STREAM_VIDEO_CAPTURER_SOURCE_H_


text: Developing phonetic algorithms to correct Russian spelling


text:
import './chunk-2452e3d3.js';
import './helpers.js';
import './chunk-8ed29c41.js';
import { I as Icon } from './chunk-d92f0cd9.js';
export { I as BIcon } from './chunk-d92f0cd9.js';
import { r as registerComponent, u as use } from './chunk-cca88db8.js';

var Plugin = {
  install: function install(Vue) {
    registerComponent(Vue, Icon);
  }
};
use(Plugin);

export default Plugin;


text:
/**
 * Only implements needed gestures for mobile.
 */

import * as eventUtil from './event';
import { ZRRawTouchEvent, ZRPinchEvent, Dictionary } from './types';
import Displayable from '../graphic/Displayable';

interface TrackItem {
    points: number[][]
    touches: Touch[]
    target: Displayable,
    event: ZRRawTouchEvent
}

export class GestureMgr {

    private _track: TrackItem[] = []

    constructor() {}

    recognize(event: ZRRawTouchEvent, target: Displayable, root: HTMLElement) {
        this._doTrack(event, target, root);
        return this._recognize(event);
    }

    clear() {
        this._track.length = 0;
        return this;
    }

    _doTrack(event: ZRRawTouchEvent, target: Displayable, root: HTMLElement) {
        const touches = event.touches;

        if (!touches) {
            return;
        }

        const trackItem: TrackItem = {
            points: [],
            touches: [],
            target: target,
            event: event
        };

        for (let i = 0, len = touches.length; i < len; i++) {
            const touch = touches[i];
            const pos = eventUtil.clientToLocal(root, touch, {});
            trackItem.points.push([pos.zrX, pos.zrY]);
            trackItem.touches.push(touch);
        }

        this._track.push(trackItem);
    }

    _recognize(event: ZRRawTouchEvent) {
        for (let eventName in recognizers) {
            if (recognizers.hasOwnProperty(eventName)) {
                const gestureInfo = recognizers[eventName](this._track, event);
                if (gestureInfo) {
                    return gestureInfo;
                }
            }
        }
    }
}

function dist(pointPair: number[][]): number {
    const dx = pointPair[1][0] - pointPair[0][0];
    const dy = pointPair[1][1] - pointPair[0][1];

    return Math.sqrt(dx * dx + dy * dy);
}

function center(pointPair: number[][]): number[] {
    return [
        (pointPair[0][0] + pointPair[1][0]) / 2,
        (pointPair[0][1] + pointPair[1][1]) / 2
    ];
}

type Recognizer = (tracks: TrackItem[], event: ZRRawTouchEvent) => {
    type: string
    target: Displayable
    event: ZRRawTouchEvent
}

const recognizers: Dictionary<Recognizer> = {

    pinch: function (tracks: TrackItem[], event: ZRRawTouchEvent) {
        const trackLen = tracks.length;

        if (!trackLen) {
            return;
        }

        const pinchEnd = (tracks[trackLen - 1] || {}).points;
        const pinchPre = (tracks[trackLen - 2] || {}).points || pinchEnd;

        if (pinchPre
            && pinchPre.length > 1
            && pinchEnd
            && pinchEnd.length > 1
        ) {
            let pinchScale = dist(pinchEnd) / dist(pinchPre);
            !isFinite(pinchScale) && (pinchScale = 1);

            (event as ZRPinchEvent).pinchScale = pinchScale;

            const pinchCenter = center(pinchEnd);
            (event as ZRPinchEvent).pinchX = pinchCenter[0];
            (event as ZRPinchEvent).pinchY = pinchCenter[1];

            return {
                type: 'pinch',
                target: tracks[0].target,
                event: event
            };
        }
    }

    // Only pinch currently.
};


text:
class AddEditionStringToManifestation < ActiveRecord::Migration
  def self.up
    add_column :manifestations, :edition_string, :string
  end

  def self.down
    remove_column :manifestations, :edition_string
  end
end


text:
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using EnergenieLibv2.Interfaces;
using EnergenieLibv2.Extensions;
using static EnergenieLibv2.Encryption;
using static EnergenieLibv2.Helper.CheckHostName;
using static EnergenieLibv2.Helper.RunAsyncHelper;
using static EnergenieLibv2.Helper.TcpSocketHelper;

namespace EnergenieLibv2
{

    public class Energenie : IEnergenie
    {
        private const byte IsOn = 0x41;
        private const byte IsOff = 0x82;

        private const byte SwitchOn = 0x01;
        private const byte SwitchOff = 0x02;
        private const byte NoSwitching = 0x04;

        private byte[] Handshake = { 0x11 };

        private byte[] buffer = new byte[1024];

        #region Constructor
        public Energenie()
        {

        }
        #endregion

        public async Task<bool> GetSocketStateAsync(string key, int socket, string host, int port = 5000, int retries = 3, int timeout = 3)
        {
            ExitOnInvalidSocketNumber(socket);
            ExitOnInvalidKey(key);

            keyAsBytes = key;

            return await RunAsyncWithRetries<bool>(async delegate
            {
                using (var tcpSocket = await GetTcpSocket(host, port, timeout))
                {
                    var challenge = await tcpSocket.SendReceiveAsync(Handshake, timeout);
                    var solution = CalcSolution(challenge);
                    var encryptedStatus = await tcpSocket.SendReceiveAsync(solution, timeout);

                    tcpSocket.Close();

                    return DecryptState(encryptedStatus, challenge, socket) == IsOn;
                }
            }, retries);
        }

        public async Task<bool> SetSocketStateAsync(string key, int socket, bool state, string host, int port = 5000, int retries = 3, int timeout = 3)
        {
            ExitOnInvalidSocketNumber(socket);
            ExitOnInvalidKey(key);

            keyAsBytes = key;

            byte[] newState = { NoSwitching, NoSwitching, NoSwitching, NoSwitching };
            newState[socket - 1] = ConvertFromBoolToEnergenieState(state);

            keyAsBytes = key;

            return await RunAsyncWithRetries<bool>(async delegate
            {
                using (var tcpSocket = await GetTcpSocket(host, port, timeout))
                {
                    var challenge = await tcpSocket.SendReceiveAsync(Handshake, timeout);
                    var solution = CalcSolution(challenge);
                    await tcpSocket.SendReceiveAsync(solution, timeout);

                    var controlMsg = EncryptActionMsg(challenge, newState);
                    var sendControlMsg = await tcpSocket.SendReceiveAsync(controlMsg, timeout);
                    tcpSocket.Close();
                    return true;
                }
            }, retries);
        }

        private void ExitOnInvalidSocketNumber(int socket)
        {
            if ((socket > 0) && (socket <= 4)) return;
                else throw new ArgumentOutOfRangeException("Socket number must be 1, 2, 3 or 4. Current socket is {0}", socket.ToString());
        }

        private void ExitOnInvalidKey(string key)
        {
            if (key.Length != 8) throw new ArgumentOutOfRangeException("Key must be 8 characters. Current key has {0} characters", key.Length.ToString());
        }

        private byte ConvertFromBoolToEnergenieState(bool state)
        {
            switch (state)
            {
                case true: return SwitchOn;
                case false: return SwitchOff;
                default: return NoSwitching;
            }
        }
    }
}


text:
'use strict';

adsApp.factory('authentication', [
    'localStorageService',
    function (localStorageService) {

        var key = 'user';

        function saveUserData(data) {
            localStorageService.set(key, data);
        }

        function getUserData() {
            return localStorageService.get(key);
        }

        function removeUser() {
            localStorage.removeItem('ls.user');
        }

        function getHeaders() {
            var headers = {};
            var userData = getUserData();

            if (userData) {
                headers.Authorization = 'Bearer ' + userData.access_token;
            }

            return headers;
        }

        function isAdmin() {
            return getUserData().isAdmin;
        }

        function isLoggedIn() {
            return !!getUserData();
        }

        return {
            saveUser: saveUserData,
            getUserData: getUserData,
            removeUser: removeUser,
            getHeaders: getHeaders,
            isAdmin: isAdmin,
            isLoggedIn: isLoggedIn
        }
    }]);


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This is a port of ManifestParser.h from WebKit/WebCore/loader/appcache.

#ifndef CONTENT_BROWSER_APPCACHE_APPCACHE_MANIFEST_PARSER_H_
#define CONTENT_BROWSER_APPCACHE_APPCACHE_MANIFEST_PARSER_H_

#include <string>
#include <vector>

#include "base/containers/hash_tables.h"
#include "content/common/appcache_interfaces.h"
#include "content/common/content_export.h"

class GURL;

namespace content {

struct CONTENT_EXPORT AppCacheManifest {
  AppCacheManifest();
  ~AppCacheManifest();

  base::hash_set<std::string> explicit_urls;
  AppCacheNamespaceVector intercept_namespaces;
  AppCacheNamespaceVector fallback_namespaces;
  AppCacheNamespaceVector online_whitelist_namespaces;
  bool online_whitelist_all;
  bool did_ignore_intercept_namespaces;
};

enum ParseMode {
  PARSE_MANIFEST_PER_STANDARD,
  PARSE_MANIFEST_ALLOWING_INTERCEPTS
};

CONTENT_EXPORT bool ParseManifest(
    const GURL& manifest_url,
    const char* data,
    int length,
    ParseMode parse_mode,
    AppCacheManifest& manifest);

}  // namespace content

#endif  // CONTENT_BROWSER_APPCACHE_APPCACHE_MANIFEST_PARSER_H_


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Nova Hedwigia, Beih. 111: 81 (1996)

#### Original name
Marasmius oncospermatis Corner

### Remarks
null


text:
@interface ChooseModeViewController () {
    void(^coldNetCheckCompletion)(BOOL);
}
@property(weak, nonatomic) IBOutlet UIView *vColdContainer;
@property(weak, nonatomic) IBOutlet UIView *vHotContainer;
@property(weak, nonatomic) IBOutlet UIView *vColdIcon;
@property(weak, nonatomic) IBOutlet UIView *vHotIcon;
@property(weak, nonatomic) IBOutlet UIView *vColdCheck;
@property(weak, nonatomic) IBOutlet UIView *vHotWait;
@property(weak, nonatomic) IBOutlet UIView *vHotProgress;
@property(weak, nonatomic) IBOutlet UIView *vHotRetry;
@property(weak, nonatomic) IBOutlet UIButton *btnSwitchToCold;
@property(weak, nonatomic) IBOutlet UIButton *btnRetry;
@property(weak, nonatomic) IBOutlet UIButton *btnHot;
@property(weak, nonatomic) IBOutlet UIButton *btnCold;
@property(weak, nonatomic) IBOutlet ColdModeCheckConnectionView *vColdNetCheck;

@end

@interface ChooseModeViewController (States)
- (void)showColdCheckWithCompletion:(void (^)())completion;

- (void)showColdCheck;

- (void)showColdIconWithCompletion:(void (^)())completion;

- (void)showColdIcon;

- (void)showHotWaitWithCompletion:(void (^)())completion;

- (void)showHotWait;

- (void)showHotIconWithCompletion:(void (^)())completion;

- (void)showHotIcon;
@end

@interface ChooseModeViewController (ConfigureView)
- (void)configureView;
@end

@interface ChooseModeViewController (DowloadSpvDelegate) <DowloadSpvDelegate>
@end

@interface ChooseModeViewController (AfterChoose)
- (void)toHotView;

- (void)toColdView;
@end

@implementation ChooseModeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configureView];
    [[BlockUtil instance] syncSpvBlock];
    if (![[BTSettings instance] needChooseMode]) {
        if ([[BTSettings instance] getAppMode] == HOT && ![[BlockUtil instance] syncSpvFinish]) {
            [BlockUtil instance].delegate = self;
            [[BlockUtil instance] syncSpvBlock];
            self.vHotProgress.hidden = NO;
            self.vHotRetry.hidden = YES;
            [self showHotWait];

        }
        if ([[BTSettings instance] getAppMode] == COLD) {
            [self showColdCheckWithCompletion:^{
                [self.vColdNetCheck beginCheck:coldNetCheckCompletion];
            }];
        }
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)coldCheckWithoutAnimationAgain {
    [self.vColdNetCheck beginCheck:coldNetCheckCompletion];
}

- (IBAction)coldButtonPressed:(id)sender {
    if (![BTSettings instance].needChooseMode) {
        return;
    }
    [[[DialogAlert alloc] initWithAttributedMessage:[self getAttributedWarningMessage:NSLocalizedString(@"choose_mode_cold_confirm", nil)] confirm:^{
        [[BTSettings instance] setAppMode:COLD];
        [[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalNever];
        [self showColdCheckWithCompletion:^{
            [self.vColdNetCheck beginCheck:coldNetCheckCompletion];
        }];
    }                                        cancel:nil] showInWindow:self.view.window];
}

- (IBAction)hotButtonPressed:(id)sender {
    if (![BTSettings instance].needChooseMode) {
        return;
    }
    [[[DialogAlert alloc] initWithAttributedMessage:[self getAttributedWarningMessage:NSLocalizedString(@"choose_mode_warm_confirm", nil)] confirm:^{
        [[BTSettings instance] setAppMode:HOT];
        [[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
        [[BitherTime instance] start];
        self.vHotProgress.hidden = NO;
        self.vHotRetry.hidden = YES;
        if (![[BlockUtil instance] syncSpvFinish]) {
            [self showHotWaitWithCompletion:^{
                self.vHotProgress.hidden = NO;
                self.vHotRetry.hidden = YES;
                if (![[BlockUtil instance] syncSpvFinish]) {
                    [BlockUtil instance].delegate = self;
                    [[BlockUtil instance] syncSpvBlock];
                } else {
                    [self showHotIconWithCompletion:^{
                        [self toHotView];
                    }];
                }
            }];
        } else {
            [self showHotWaitWithCompletion:^{
                self.vHotProgress.hidden = NO;
                self.vHotRetry.hidden = YES;
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t) (1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self showHotIconWithCompletion:^{
                        [self toHotView];
                    }];
                });
            }];
        }
    }                                        cancel:nil] showInWindow:self.view.window];
}

- (IBAction)hotRetryPressed:(id)sender {
    [BlockUtil instance].delegate = self;
    [[BlockUtil instance] syncSpvBlock];
    self.vHotRetry.hidden = YES;
    self.vHotProgress.hidden = NO;
}

- (IBAction)switchToColdPressed:(id)sender {
    [[[DialogAlert alloc] initWithAttributedMessage:[self getAttributedWarningMessage:NSLocalizedString(@"launch_sequence_switch_to_cold_warn", nil)] confirm:^{
        [[BTSettings instance] setAppMode:COLD];
        [[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalNever];
        [self showColdCheckWithCompletion:^{
            [self.vColdNetCheck beginCheck:coldNetCheckCompletion];
        }];
    }                                        cancel:nil] showInWindow:self.view.window];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (NSAttributedString *)getAttributedWarningMessage:(NSString *)str {
    NSUInteger firstLineBreak = [str rangeOfString:@"\n"].location;
    if ([str characterAtIndex:firstLineBreak + 1] == '\n') {
        str = [[str substringToIndex:firstLineBreak + 1] stringByAppendingString:[str substringFromIndex:firstLineBreak + 2]];
    }
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:str];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.paragraphSpacing = 5;
    [attr addAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:kDialogAlertLabelFontSize], NSForegroundColorAttributeName : [UIColor whiteColor], NSParagraphStyleAttributeName : paragraphStyle} range:NSMakeRange(0, str.length)];
    [attr addAttributes:@{NSFontAttributeName : [UIFont boldSystemFontOfSize:kDialogAlertLabelFontSize * 1.2], NSForegroundColorAttributeName : [UIColor redColor]} range:NSMakeRange(0, firstLineBreak)];
    return attr;
}

@end

@implementation ChooseModeViewController (States)

- (void)showColdCheckWithCompletion:(void (^)())completion {
    [self.view bringSubviewToFront:self.vHotContainer];
    self.vColdCheck.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    self.vColdIcon.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin;
    [UIView animateWithDuration:kChooseModeStateTransactionDuration animations:^{
        [self showColdCheck];
    }                completion:^(BOOL finished) {
        if (completion) {
            completion();
        }
    }];
}

- (void)showColdCheck {
    self.vColdCheck.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    self.vColdIcon.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin;
    [self showCold];
}

- (void)showColdIconWithCompletion:(void (^)())completion {
    [self.view bringSubviewToFront:self.vHotContainer];
    self.vColdCheck.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    self.vColdIcon.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin;
    [UIView animateWithDuration:kChooseModeStateTransactionDuration animations:^{
        [self showColdIcon];
    }                completion:^(BOOL finished) {
        if (completion) {
            completion();
        }
    }];
}

- (void)showColdIcon {
    self.vColdCheck.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    self.vColdIcon.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin;
    [self showCold];
    [self setView:self.vColdIcon height:CGRectGetHeight(self.vColdIcon.frame) y:(CGRectGetHeight(self.view.frame) - CGRectGetHeight(self.vColdIcon.frame)) / 2];
    [self setView:self.vColdCheck height:0 y:CGRectGetHeight(self.view.frame)];
}

- (void)showHotWaitWithCompletion:(void (^)())completion {
    [self.view bringSubviewToFront:self.vColdContainer];
    self.vHotIcon.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    self.vHotWait.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    [UIView animateWithDuration:kChooseModeStateTransactionDuration animations:^{
        [self showHotWait];
    }                completion:^(BOOL finished) {
        if (completion) {
            completion();
        }
    }];
}

- (void)showHotWait {
    self.vHotIcon.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    self.vHotWait.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    [self showHot];
}

- (void)showHotIconWithCompletion:(void (^)())completion {
    [self.view bringSubviewToFront:self.vColdContainer];
    self.vHotIcon.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
    self.vHotWait.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin;
    [UIView animateWithDuration:kChooseModeStateTransactionDuration animations:^{
        [self showHotIcon];
    }                completion:^(BOOL finished) {
        if (completion) {
            completion();
        }
    }];
}

- (void)showHotIcon {
    self.vHotIcon.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
    self.vHotWait.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin;
    [self showHot];
    [self setView:self.vHotIcon height:CGRectGetHeight(self.vHotIcon.frame) y:(CGRectGetHeight(self.view.frame) - CGRectGetHeight(self.vHotIcon.frame)) / 2];
    [self setView:self.vHotWait height:0 y:0];
}

- (void)showCold {
    [self setView:self.vColdContainer height:CGRectGetHeight(self.view.frame) y:0];
    [self setView:self.vHotContainer height:CGRectGetHeight(self.vHotContainer.frame) y:CGRectGetHeight(self.view.frame)];
}

- (void)showHot {
    [self setView:self.vHotContainer height:CGRectGetHeight(self.view.frame) y:0];
    [self setView:self.vColdContainer height:CGRectGetHeight(self.vColdContainer.frame) y:0 - CGRectGetHeight(self.vColdContainer.frame)];
}

- (void)setView:(UIView *)view height:(CGFloat)height y:(CGFloat)y {
    CGRect frame = view.frame;
    frame.size.height = height;
    frame.origin.y = y;
    view.frame = frame;
}
@end

@implementation ChooseModeViewController (DowloadSpvDelegate)

- (void)success {
    [BlockUtil instance].delegate = nil;
    self.vHotRetry.hidden = YES;
    self.vHotProgress.hidden = NO;
    [self showHotIconWithCompletion:^{
        [self toHotView];
    }];
    [[PeerUtil instance] startPeer];

}

- (void)error {
    self.vHotRetry.hidden = NO;
    self.vHotProgress.hidden = YES;
}

@end

@implementation ChooseModeViewController (AfterChoose)

- (void)toHotView {
    [self toViewWithIdentifier:@"BitherHot" zoomView:self.btnHot];
}

- (void)toColdView {
    [self toViewWithIdentifier:@"BitherCold" zoomView:self.btnCold];
}

- (void)toViewWithIdentifier:(NSString *)identifier zoomView:(UIView *)zoom {
    IOS7ContainerViewController *container = [[IOS7ContainerViewController alloc] init];
    container.controller = [self.storyboard instantiateViewControllerWithIdentifier:identifier];
    [[UIApplication sharedApplication].keyWindow insertSubview:container.view atIndex:0];
    [UIView animateWithDuration:kChooseModeStateTransactionDuration animations:^{
        zoom.transform = CGAffineTransformMakeScale(2, 2);
        self.view.alpha = 0;
    }                completion:^(BOOL finished) {
        [container.view removeFromSuperview];
        [UIApplication sharedApplication].keyWindow.rootViewController = container;
    }];
}

@end

@implementation ChooseModeViewController (ConfigureView)

- (void)configureView {
    [self.view setBackgroundColor:[UIColor parseColor:kChooseModeGradientCenterColor]];
    CGRect frame = self.vColdCheck.frame;
    frame.size.width = self.view.frame.size.width;
    frame.origin.y = self.vColdContainer.frame.size.height;
    self.vColdCheck.frame = frame;

    frame = self.vHotWait.frame;
    frame.size.width = self.view.frame.size.width;
    frame.origin.y = 0;
    self.vHotWait.frame = frame;

    self.vHotIcon.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    self.vHotWait.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin;
    self.vColdCheck.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    self.vColdIcon.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin;
    self.vColdNetCheck.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height / 2);
    self.vHotProgress.hidden = YES;
    CGFloat width = [self.btnSwitchToCold sizeThatFits:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX)].width + 20;
    self.btnSwitchToCold.frame = CGRectMake(self.btnSwitchToCold.frame.origin.x - (width - self.btnSwitchToCold.frame.size.width) / 2, self.btnSwitchToCold.frame.origin.y, width, self.btnSwitchToCold.frame.size.height);
    [self gradientViewWithStart:[UIColor parseColor:kChooseModeGradientColdColor] end:[UIColor parseColor:kChooseModeGradientCenterColor] view:self.vColdContainer];
    [self gradientViewWithStart:[UIColor parseColor:kChooseModeGradientCenterColor] end:[UIColor parseColor:kChooseModeGradientHotColor] view:self.vHotContainer];
    __weak ChooseModeViewController *c = self;
    coldNetCheckCompletion = ^(BOOL passed) {
        if (passed) {
            [c showColdIconWithCompletion:^{
                [c toColdView];
            }];
        } else {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t) (0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [c coldCheckWithoutAnimationAgain];
            });
        }
    };
}

- (void)gradientViewWithStart:(UIColor *)start end:(UIColor *)end view:(UIView *)view {
    UIImage *image = [UIColor gradientFromColor:start toColor:end withHeight:self.view.frame.size.height];
    UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, view.frame.size.width, view.frame.size.height)];
    iv.image = image;
    iv.contentMode = UIViewContentModeScaleToFill;
    iv.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    [view insertSubview:iv atIndex:0];
}
@end


text:
<?xml version="1.0" ?>
<phpsemver
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/sourcerer-mike/phpsemver/3.2.0/etc/phpsemver.xsd"
        title="My own versioning">
    <RuleSet name="first">
        <Trigger>
            <Classes>
                <IsRemoved/>
            </Classes>
            <Functions>
                <IsRemoved/>
            </Functions>
        </Trigger>
    </RuleSet>
    <RuleSet name="second">
        <Trigger>
            <Classes>
                <IsAdded/>
            </Classes>
            <Functions>
                <IsAdded/>
            </Functions>
        </Trigger>
    </RuleSet>
    <RuleSet name="last">
    </RuleSet>
    <Filter>
        <Blacklist>
            <Pattern>^pattern-test/blacklist/.*</Pattern>
        </Blacklist>
        <Whitelist>
            <Pattern>^pattern-test/whitelist/.*</Pattern>
        </Whitelist>
    </Filter>
</phpsemver>


text:
{% extends "base.html" %}

{% block content %}

{{ APP_NAME }}

        <form class="form-inline" role="form">

                <input style="width:100%" type="input" name="query" class="form-control" placeholder="Search Text Here" />

            <button type="submit" class="btn btn-default">SEARCH</button>
        </form>

{% endblock %}

{% block bottom_scripts %}

{% endblock %}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<addon  id="plugin.video.avalon.netflix" name="Netflix" version="0.4.01" provider-name="avalonprojects.net">
  <requires>
    <import addon="xbmc.python" version="2.1.0"/>
    <import addon="script.module.simplejson" version="2.0.10" />
  </requires>
  <extension point="xbmc.python.pluginsource" library="default.py">
    <provides>video</provides>
  </extension>
  <extension point="xbmc.python.script" library="../resources/scripts/UpdateGenreTitles.py" />
  <extension point="xbmc.python.script" library="../resources/scripts/UpdateMyList.py" />

  <extension point="xbmc.addon.metadata">
    <platform>windx</platform>
    <minversion>1</minversion>
    <summary lang="en">Unnofficial Netflix plugin for XBMC</summary>
    <description lang="en">Unnofficial Netflix plugin for XBMC.</description>
  </extension>
</addon>


text:
package org.pocketcampus.plugin.events.android.req;

import org.pocketcampus.platform.android.io.Request;
import org.pocketcampus.plugin.events.android.EventsController;
import org.pocketcampus.plugin.events.android.EventsModel;
import org.pocketcampus.plugin.events.android.iface.IEventsView;
import org.pocketcampus.plugin.events.shared.EventPoolReply;
import org.pocketcampus.plugin.events.shared.EventPoolRequest;
import org.pocketcampus.plugin.events.shared.EventsService.Iface;

/**
 * GetEventPoolChildrenRequest
 *
 * This class sends an HttpRequest using Thrift to the PocketCampus server
 * in order to get the list of EventPools.
 *
 * @author Amer <amer.chamseddine@epfl.ch>
 *
 */
public class GetEventPoolRequest extends Request<EventsController, Iface, EventPoolRequest, EventPoolReply> {

	private IEventsView caller;

	public GetEventPoolRequest(IEventsView caller) {
		this.caller = caller;
	}

	@Override
	protected EventPoolReply runInBackground(Iface client, EventPoolRequest param) throws Exception {
		return client.getEventPool(param);
	}

	@Override
	protected void onResult(EventsController controller, EventPoolReply result) {
		if(result.getStatus() == 200) {
			if(result.isSetCategs())
				EventsController.updateEventCategs(result.getCategs());
			if(result.isSetTags())
				EventsController.updateEventTags(result.getTags());

			((EventsModel) controller.getModel()).addEventItems(result.getChildrenItems());
			((EventsModel) controller.getModel()).addEventPool(result.getEventPool());

			keepInCache();
		} else {
			caller.mementoServersDown();
		}
	}

	@Override
	protected void onError(EventsController controller, Exception e) {
		if(foundInCache())
			caller.networkErrorCacheExists();
		else
			caller.networkErrorHappened();
		e.printStackTrace();
	}

}


text:
from ironic.drivers import ipmi
from ironic.drivers.modules.intel_ipmi import management

class IntelIPMIHardware(ipmi.IPMIHardware):
    """Intel IPMI hardware type.

    Uses ``ipmitool`` to implement power and management.
    Provides serial console implementations via ``shellinabox`` or ``socat``.
    Supports Intel SST-PP feature.
    """
    @property
    def supported_management_interfaces(self):
        """List of supported management interfaces."""
        return [management.IntelIPMIManagement]


text:
/// <reference types="Cypress" />

context('Spies, Stubs, and Clock', () => {
  it('cy.spy() - wrap a method in a spy', () => {
    // https://on.cypress.io/spy
    cy.visit('https://example.cypress.io/commands/spies-stubs-clocks')

    const obj = {
      foo () {},
    }

    const spy = cy.spy(obj, 'foo').as('anyArgs')

    obj.foo()

    expect(spy).to.be.called
  })

  it('cy.spy() retries until assertions pass', () => {
    cy.visit('https://example.cypress.io/commands/spies-stubs-clocks')

    const obj = {
      /**
       * Prints the argument passed
       * @param x {any}
      */
      foo (x) {
        console.log('obj.foo called with', x)
      },
    }

    cy.spy(obj, 'foo').as('foo')

    setTimeout(() => {
      obj.foo('first')
    }, 500)

    setTimeout(() => {
      obj.foo('second')
    }, 2500)

    cy.get('@foo').should('have.been.calledTwice')
  })

  it('cy.stub() - create a stub and/or replace a function with stub', () => {
    // https://on.cypress.io/stub
    cy.visit('https://example.cypress.io/commands/spies-stubs-clocks')

    const obj = {
      /**
       * prints both arguments to the console
       * @param a {string}
       * @param b {string}
      */
      foo (a, b) {
        console.log('a', a, 'b', b)
      },
    }

    const stub = cy.stub(obj, 'foo').as('foo')

    obj.foo('foo', 'bar')

    expect(stub).to.be.called
  })

  it('cy.clock() - control time in the browser', () => {
    // https://on.cypress.io/clock

    // create the date in UTC so its always the same
    // no matter what local timezone the browser is running in
    const now = new Date(Date.UTC(2017, 2, 14)).getTime()

    cy.clock(now)
    cy.visit('https://example.cypress.io/commands/spies-stubs-clocks')
    cy.get('#clock-div').click()
      .should('have.text', '1489449600')
  })

  it('cy.tick() - move time in the browser', () => {
    // https://on.cypress.io/tick

    // create the date in UTC so its always the same
    // no matter what local timezone the browser is running in
    const now = new Date(Date.UTC(2017, 2, 14)).getTime()

    cy.clock(now)
    cy.visit('https://example.cypress.io/commands/spies-stubs-clocks')
    cy.get('#tick-div').click()
      .should('have.text', '1489449600')
    cy.tick(10000) // 10 seconds passed
    cy.get('#tick-div').click()
      .should('have.text', '1489449610')
  })
})


text:
package Moose::Meta::Method::Overridden;
our $VERSION = '2.1404';

use strict;
use warnings;

use parent 'Moose::Meta::Method';

use Moose::Util 'throw_exception';

sub new {
    my ( $class, %args ) = @_;

    # the package can be overridden by roles
    # it is really more like body's compilation stash
    # this is where we need to override the definition of super() so that the
    # body of the code can call the right overridden version
    my $super_package = $args{package} || $args{class}->name;

    my $name = $args{name};

    my $super = $args{class}->find_next_method_by_name($name);

    (defined $super)
        || throw_exception( CannotOverrideNoSuperMethod => class       => $class,
                                                           params      => \%args,
                                                           method_name => $name
                          );

    my $super_body = $super->body;

    my $method = $args{method};

    my $body = sub {
        local $Moose::SUPER_PACKAGE = $super_package;
        local @Moose::SUPER_ARGS = @_;
        local $Moose::SUPER_BODY = $super_body;
        return $method->(@_);
    };

    # FIXME do we need this make sure this works for next::method?
    # subname "${super_package}::${name}", $method;

    # FIXME store additional attrs
    $class->wrap(
        $body,
        package_name => $args{class}->name,
        name         => $name
    );
}

1;

# ABSTRACT: A Moose Method metaclass for overridden methods

__END__

=pod

=encoding UTF-8

=head1 NAME

Moose::Meta::Method::Overridden - A Moose Method metaclass for overridden methods

=head1 VERSION

version 2.1404

=head1 DESCRIPTION

This class implements method overriding logic for the L<Moose>
C<override> keyword.

The overriding subroutine's parent will be invoked explicitly using
the C<super> keyword from the parent class's method definition.

=head1 METHODS

=over 4

=item B<< Moose::Meta::Method::Overridden->new(%options) >>

This constructs a new object. It accepts the following options:

=over 8

=item * class

The metaclass object for the class in which the override is being
declared. This option is required.

=item * name

The name of the method which we are overriding. This method must exist
in one of the class's superclasses. This option is required.

=item * method

The subroutine reference which implements the overriding. This option
is required.

=back

=back

=head1 BUGS

See L<Moose/BUGS> for details on reporting bugs.

=head1 AUTHORS

=over 4

=item *

Stevan Little <stevan.little@iinteractive.com>

=item *

Dave Rolsky <autarch@urth.org>

=item *

Jesse Luehrs <doy@tozt.net>

=item *

Shawn M Moore <code@sartak.org>

=item *

יובל קוג'מן (Yuval Kogman) <nothingmuch@woobling.org>

=item *

Karen Etheridge <ether@cpan.org>

=item *

Florian Ragwitz <rafl@debian.org>

=item *

Hans Dieter Pearcey <hdp@weftsoar.net>

=item *

Chris Prather <chris@prather.org>

=item *

Matt S Trout <mst@shadowcat.co.uk>

=back

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2006 by Infinity Interactive, Inc..

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut


text:
System.register([], function (exports, module) {
	'use strict';
	return {
		execute: function () {

			Unknown.staticMember;
			Unknown.prototype.method;

		}
	};
});


text:
if (typeof require.ensure !== 'function') require.ensure = (d, c) => c(require)
import { injectAsyncReducer } from '../../store'

export default function createRoutes(store) {
  return {
    path: 'measurement',
    getComponents(location, cb) {
      require.ensure([
        './containers/MeasurementPage',
        './reducer',
      ], (require) => {
        const MeasurementPage = require('./containers/MeasurementPage').default
        const measurementReducer = require('./reducer').default
        injectAsyncReducer(store, 'measurements', measurementReducer)
        cb(null, MeasurementPage)
      })
    },
  }
}


text:
title: "Трансфузиология"
---

**В задачи службы заготовки компонентов крови современного стационара входит не только заготовка оптимального
количества трансфузионных сред, но и обеспечение безопасности доноров и реципиентов. Большую роль в оптимизации
процесса заготовки играет грамотная организация работы службы заготовки крови. В настоящий момент можно значимо
снизить процент посттрансфузионных осложнений с помощью современных средств информатизации.**

## Решаем

- Прослеживание информации о трансфузионной среде от донора к реципиенту;
- Обеспечивание информационного сопровождения и контроля, предотвращающие возможных ошибок персонала на пути от «от вены до вены»;
- Создание единого информационного пространства и, как следствие, эффективная организация планирования, распределение
и подбор компонентов крови, осуществление анализа результатов проведенных трансфузий и полученние осложнений, осуществление
научных работ подразделения и т.п.;
- Обеспечение высокой производительности работы сотрудников отделений трансфузиологии, сокращение объема «ручного» труда;
- Автоматическую загрузку результатов проведенных исследований из лабораторной информационной системы.

## Автоматизируем

- Ввод кодов отводов для доноров, которых отстранил терапевт или процедурный кабинет;
- Ведение баз данных абсолютных отводов;
- Подготовка списков лиц, осуществивших донацию;
- Подбор доноров по заданным параметрам, планирование донорского потока, подготовка списков доноров, автоматическая рассылка донорам приглашений, SMS-сообщений в качестве напоминаний;
- Подбор доноров редких групп;
- Составление отчетов;
- Ведение списков почетных доноров.

## Врачам-терапевтам

- Идентификация донора с помощью штрихкода с карточки или регистрационного номера;
- Просмотр данных предыдущих кроводач;
- Внесение решения о новой кроводаче в карту по завершению осмотра.

## Журнал операционной

- Поиск любой осуществленной кроводачи по номеру или дате;
- Выборка всех кроводач конкретного донора;
- Выдача дубликат справок;
- Формирование отчетов с подсчетом определенных типов кроводач либо за определенный срок (день, месяц и т.д.)

## Компоненты крови

В системе «Трансфузиология» доступна регистрация полученных компонентов крови. Последующая их передача в экспедицию,
карантин или на утилизацию производится на этапе паспортизации. Также здесь есть возможность составления отчета по
фракционированию.

### Этикетировка

- Формирование этикетки на готовые компоненты;
- Формирование и печать отчетов типа «Сводка браков за период»;
- Поиск любого компонента крови по номеру, дате или типу и проследить его историю: когда и от какого донора был заготовлен, апробирован, когда и кому выдан.

### Экспедиция

После успешного процесса формирования трансфузионной среды, она попадает в «Экспедицию», что соответствующим образом
отражается в системе «Трансфузиология». В системе осуществляется контроль поступления заявок из клинических отделений и
выдачи компонентов крови.

## Руководителю

В функции системы «Трансфузиология» входит также ведение полного инвентарного учета компонентов крови и ведение
карантинизации больших объемов компонентов крови.

Руководителю трансфузионного отделения система «Трансфузиология» позволяет на экспертном уровне проводить оценку
деятельности отделения и формировать отчеты по результатам работы подразделения.

## Еще вопросы?

Если остались вопросы, то можно отправить [заявку](mailto:sales@hitsl.ru) на проведение презентации Трансфузиология.

**Внедрение «Трансфузиология» - важный шаг на пути к обеспечению высокой безопасности и эффективности трансфузионной терапии.**


text:
ACCEPTED

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

#### Published in
Bull. trimest. Soc. mycol. Fr. 102(1): 100 (1986)

#### Original name
Camaroglobulus resinae Speer, 1986

### Remarks
null


text:
<?php

namespace Coff\OneWire\DataSource;

use Coff\DataSource\AsyncDataSource;
use Coff\DataSource\StatefulDataSourceInterface;
use Coff\DataSource\StatefulTrait;

abstract class W1DataSource extends AsyncDataSource implements StatefulDataSourceInterface
{
    use StatefulTrait;

    protected $id;

    public function getId() {
        return $this->id;
    }

    public function setValue($value) {
        $this->value = $value;

        return $this;
    }

    public function setStamp($timestamp) {
        $this->stamp = $timestamp;

        return $this;
    }

}


text:
[![npm version](https://badge.fury.io/js/miio.svg)](https://badge.fury.io/js/miio)
[![Dependencies](https://david-dm.org/aholstenson/miio.svg)](https://david-dm.org/aholstenson/miio)

Control Mi Home devices that implement the miIO protocol, such as the
Mi Air Purifier, Mi Robot Vacuum and Mi Smart Socket. These devices are commonly
part of what Xiaomi calls the Mi Ecosystem which is branded as MiJia.

`miio` is [MIT-licensed](LICENSE.md) and requires at least Node 6.6.0. As
the API is promise-based Node 8 is recommended which provides support `async`
and `await` that greatly simplifies asynchronous handling.

**Note:** Since 0.15.0 this library has been rewritten to use [abstract-things](https://github.com/tinkerhub/abstract-things)
as its base. The API of devices will have changed, and some bugs are to be
expected. Testing and feedback on the new API is welcome, please open issues
as needed.

## Devices types

The intent of this library is to support all miIO-compatible devices and to
provide an easy to use API for them. The library maps specific device models to
generic device types with well defined capabilities to simplify interacting with
them.

Currently supported devices are:

* Air Purifiers (1, 2 and Pro)
* Mi Humidifier
* Mi Smart Socket Plug and Power Strips
* Mi Robot Vacuum (V1 and V2)
* Mi Smart Home Gateway (Aqara) and accessories - switches, sensors, etc
* Philips Light Bulb and Eyecare Lamp
* Yeelights (White Bulb, Color Bulb, Desk Lamp and Strip)

See [documentation for devices](docs/devices/README.md) for information about
the types, their API and supported device models. You can also check
[Missing devices](docs/missing-devices.md) if you want to know what you can do
to help this library with support for your device.

## Installation

To install into your project:

```
npm install miio
```

To install globally for access to the command line tool:

```
npm install -g miio
```

## Usage

```javascript
const miio = require('miio');
```

Resolve a handle to the device:

```javascript
// Resolve a device, resolving the token automatically or from storage
miio.device({ address: '192.168.100.8' })
  .then(device => console.log('Connected to', device))
  .catch(err => handleErrorHere);

// Resolve a device, specifying the token (see below for how to get the token)
miio.device({ address: '192.168.100.8', token: 'token-as-hex' })
  .then(device => console.log('Connected to', device))
  .catch(err => handleErrorHere);
```

Call methods to interact with the device:

```javascript
// Switch the power of the device
device.togglePower()
  .then(on => console.log('Power is now', on))
  .catch(err => handleErrorHere);

// Using async/await
await device.togglePower();
```

Listen to events such as property changes and actions:

```javascript
// Listen for power changes
device.on('power', power => console.log('Power changed to', power));

// The device is available for event handlers
const handler = ({ action }, device) => console.log('Action', action, 'performed on', device);
device1.on('action', handler);
device2.on('action', handler);
```

Capabilities and types are used to hint about what a device can do:

```javascript
if(device.matches('cap:temperature')) {
  console.log(await device.temperature());
}

if(device.matches('cap:switchable-power')) {
  device.setPower(false)
    .then(console.log)
    .catch(console.error);
}
```

If you are done with the device call `destroy` to stop all network traffic:

```javascript
device.destroy();
```

## Tokens and device management

A few miIO devices send back their token during a handshake and can be used
without figuring out the token. Most devices hide their token, such as
Yeelights and the Mi Robot Vacuum.

There is a command line tool named `miio` that helps with finding and storing
tokens. See [Device management](docs/management.md) for details
and common use cases.

## Discovering devices

Use `miio.devices()` to look for and connect to devices on the local network.
This method of discovery will tell you directly if a device reveals its token
and can be auto-connected to. If you do not want to automatically connect to
devices you can use `miio.browse()` instead.

Example using `miio.devices()`:

```javascript
const devices = miio.devices({
  cacheTime: 300 // 5 minutes. Default is 1800 seconds (30 minutes)
});

devices.on('available', device => {
  if(device.matches('placeholder')) {
    // This device is either missing a token or could not be connected to
  } else {
    // Do something useful with device
  }
});

devices.on('unavailable', device => {
  // Device is no longer available and is destroyed
});
```

`miio.devices()` supports these options:

* `cacheTime`, the maximum amount of seconds a device can be unreachable before it becomes unavailable. Default: `1800`
* `filter`, function used to filter what devices are connected to. Default: `reg => true`
* `skipSubDevices`, if sub devices on Aqara gateways should be skipped. Default: `false`
* `useTokenStorage`, if tokens should be fetched from storage (see device management). Default: `true`
* `tokens`, object with manual mapping between ids and tokens (advanced, use [Device management](docs/management.md) if possible)

See [Advanced API](docs/advanced-api.md) for details about `miio.browse()`.

## Device API

Check [documentation for devices](docs/devices/README.md) for details about
the API for supported devices. Detailed documentation of the core API is
available in the section [Using things in the abstract-things documentation](http://abstract-things.readthedocs.io/en/latest/using-things.html).

## Library versioning and API stability

This library uses [semantic versioning](http://semver.org/) with an exception
being that the API for devices is based on their type and capabilities and not
their model.

This means that a device can have methods removed if its type or capabilities
change, which can happen if a better implementation is made available for the
model. When working with the library implement checks against type and
capabilities for future compatibility within the same major version of `miio`.

Capabilities can be considered stable across major versions, if a device
supports `power` no minor or patch version will introduce `power-mega` and
replace `power`. If new functionality is needed the new capability will be
added along side the older one.

## Reporting issues

[Reporting issues](docs/reporting-issues.md) contains information that is
useful for making any issue you want to report easier to fix.

## Debugging

The library uses [debug](https://github.com/visionmedia/debug) with two
namespaces, `miio` is used for packet details and network discovery and devices
use the `thing:miio` namespace. These are controlled via the `DEBUG`
environment flag. The flag can be set while running the miio command or any
NodeJS script:

Show debug info about devices during discovery:

```
$ DEBUG=thing\* miio discover
```

To activate both namespaces set `DEBUG` to both:

```
$ DEBUG=miio\*,thing\* miio discover
```

## Protocol documentation

This library is based on the documentation provided by OpenMiHome. See https://github.com/OpenMiHome/mihome-binary-protocol for details. For details
about how to figure out the commands for new devices look at the
[documentation for protocol and commands](docs/protocol.md).


text:
import { Injectable } from '@angular/core'

import { PropertiesService } from './properties.service'
import { PokemonService } from '../services/pokemon.service'

import { Pokemon } from '../models/pokemon.model'
import { Species } from '../models/species.model'
import { Move } from '../models/move.model'
import { SortOrder } from '../models/sort-order.model'
import { SortType } from '../models/sort-type.model'
import { PokemonTableStat } from '../models/pokemon-table-stat.model'

@Injectable()
export class SortService {
	private _pokemonSortOrder: string = '';
	private _speciesSortOrder: string = '';

	constructor(
		private _properties: PropertiesService,
		private _pokemonService: PokemonService
	){}

	public get pokemonSortOrder(): string {
		return this._pokemonSortOrder;
	}

	public get speciesSortOrder(): string {
		return this._speciesSortOrder;
	}

	public get pokemonSortOrders(): string[] {
		let allSortOrders: string[] = Object.keys(this._properties.pokemonTableSortOrders);
		let pokemonSortOrders: string[] = [];

		for(let i: number = 0; i < allSortOrders.length; i++){
			let sortOrder: string = allSortOrders[i];
			if(!sortOrder.includes('species_')) pokemonSortOrders.push(sortOrder);
		}

		return pokemonSortOrders;
	}

	public get speciesSortOrders(): string[] {
		return Object.keys(this._properties.speciesSortOrders);
	}

	public sortPokemon(
		sortOrderName: string,
		reverseSortOrder: boolean
	) {
		if(this._properties.pokemonTableSortOrders.hasOwnProperty(sortOrderName)){
			let sortOrder = this._properties.pokemonTableSortOrders[sortOrderName].sort_types;

			//double clicking a heading should reverse the primary sort
			if(this._pokemonSortOrder === sortOrderName && reverseSortOrder){
				sortOrder[0].asc = !sortOrder[0].asc;
			}

			this._pokemonSortOrder = sortOrderName;

			this._pokemonService.pokemon.sort((a, b) => {
				for(let i: number = 0; i < sortOrder.length; i++){
					let sortType: SortType = sortOrder[i];

					//TODO: figure out a cleaner way of DPS sorting
					if(sortType.property === 'moves.fast.DPS'){
						let moveA: Move = null;
						let moveB: Move = null;

						for(let moveIdx: number = 0; moveIdx < a.moves.fast.length; moveIdx++){
							let move: Move = a.moves.fast[moveIdx];
							if(move.selected){
								moveA = move;
								break;
							}
						}

						for(let moveIdx: number = 0; moveIdx < b.moves.fast.length; moveIdx++){
							let move: Move = b.moves.fast[moveIdx];
							if(move.selected){
								moveB = move;
								break;
							}
						}

						if(moveA && moveB && moveA.DPS < moveB.DPS) return sortType.asc ? -1 : 1;
						if(moveA && moveB && moveA.DPS > moveB.DPS) return sortType.asc ? 1 : -1;
					} else if(sortType.property === 'moves.charged.DPS'){
						let moveA: Move = null;
						let moveB: Move = null;

						for(let moveIdx: number = 0; moveIdx < a.moves.charged.length; moveIdx++){
							let move: Move = a.moves.charged[moveIdx];
							if(move.selected){
								moveA = move;
								break;
							}
						}

						for(let moveIdx: number = 0; moveIdx < b.moves.charged.length; moveIdx++){
							let move: Move = b.moves.charged[moveIdx];
							if(move.selected){
								moveB = move;
								break;
							}
						}

						if(moveA && moveB && moveA.DPS < moveB.DPS) return sortType.asc ? -1 : 1;
						if(moveA && moveB && moveA.DPS > moveB.DPS) return sortType.asc ? 1 : -1;
					} else if(sortType.property === 'DPS') {
						let dpsA: number = 0;
						let dpsB: number = 0;

						for(let moveIdx: number = 0; moveIdx < a.moves.fast.length; moveIdx++){
							let move: Move = a.moves.fast[moveIdx];
							if(move.selected){
								dpsA += move.DPS;
								break;
							}
						}

						for(let moveIdx: number = 0; moveIdx < b.moves.fast.length; moveIdx++){
							let move: Move = b.moves.fast[moveIdx];
							if(move.selected){
								dpsB += move.DPS;
								break;
							}
						}

						for(let moveIdx: number = 0; moveIdx < a.moves.charged.length; moveIdx++){
							let move: Move = a.moves.charged[moveIdx];
							if(move.selected){
								dpsA += move.DPS;
								break;
							}
						}

						for(let moveIdx: number = 0; moveIdx < b.moves.charged.length; moveIdx++){
							let move: Move = b.moves.charged[moveIdx];
							if(move.selected){
								dpsB += move.DPS;
								break;
							}
						}

						if(dpsA < dpsB) return sortType.asc ? -1 : 1;
						if(dpsA > dpsB) return sortType.asc ? 1 : -1;
					} else if(sortType.property.includes('species_')){
						let propertySplit: string[] = sortType.property.split('_');
						let speciesProperty: string = propertySplit.length > 0 ? propertySplit[1] : '';

						let speciesA: Species = null;
						let speciesB: Species = null;

						for(let speciesIdx: number = 0; speciesIdx < this._pokemonService.species.length; speciesIdx++){
							let curSpecies = this._pokemonService.species[speciesIdx];

							if(a.pokedex_number === curSpecies.pokedex_number) speciesA = curSpecies;
							if(b.pokedex_number === curSpecies.pokedex_number) speciesB = curSpecies;

							if(speciesA !== null && speciesB !== null) break;
						}

						if(speciesA[speciesProperty] < speciesB[speciesProperty]) return sortType.asc ? -1 : 1;
						if(speciesA[speciesProperty] > speciesB[speciesProperty]) return sortType.asc ? 1 : -1;
					} else {
						if(a[sortType.property] < b[sortType.property]) return sortType.asc ? -1 : 1;
						if(a[sortType.property] > b[sortType.property]) return sortType.asc ? 1 : -1;
					}
				}
				return 0;
			});
		}
	}

	public sortSpecies(
		sortOrderName: string,
		reverseSortOrder: boolean
	) {
	  if(this._properties.speciesSortOrders.hasOwnProperty(sortOrderName)){
	    let sortOrder = this._properties.speciesSortOrders[sortOrderName].sort_types;

	    //double clicking a heading should reverse the primary sort
	    if(this._speciesSortOrder === sortOrderName && reverseSortOrder){
	      sortOrder[0].asc = !sortOrder[0].asc;
	    }

	    this._speciesSortOrder = sortOrderName;

	    this._pokemonService.species.sort((a, b) => {
	      for(let i: number = 0; i < sortOrder.length; i++){
	        let sortType: SortType = sortOrder[i];

	        if(a[sortType.property] < b[sortType.property]) return sortType.asc ? -1 : 1;
	        if(a[sortType.property] > b[sortType.property]) return sortType.asc ? 1 : -1;
	      }
	      return 0;
	    });
	  }
	}
}


text:
@media screen and (max-width:800px) {
	.tinynav {
		background:#e7402f;
	}
}
body.boxed div.body {
	border-top:5px solid #e7402f;
}
.testimonial-name, .service-box.black .circleicon i, .service-box.featured .circleicon i, .service-box:hover i, .footerlogo47, .primarycolor, a, a:hover {
	color:#e7402f;
}
.cameraContents .camera_caption span, .popular .vuzz-button.buttonprice, .popular .vuzz-button, .popular .vuzz-pricing-per, .popular .vuzz-pricing-cost, .captionicons, a.tagcloud:hover,.tagcloud a:hover, .service-box.featured , .service-box:hover, #skill i, article .day, .totop, .totop:hover, .primarybg {
	background:#e7402f;
}
.navbar .nav>li>a:focus,.navbar .nav>li>a:hover,.navbar .nav>.active>a,.navbar .nav>.active>a:hover,.navbar .nav>.active>a:focus {
	background-color:#e7402f;
}
.navbar .nav li.dropdown.open>.dropdown-toggle,.navbar .nav li.dropdown.active>.dropdown-toggle,.navbar .nav li.dropdown.open.active>.dropdown-toggle {
	background-color:#e7402f;
}
#search a {
	background:#e7402f url(../img/part-btn-search.png) no-repeat center center;
}
.dropdown-menu>li>a:hover,.dropdown-menu>li>a:focus,.dropdown-submenu:hover>a,.dropdown-submenu:focus>a {
	background-color:#e7402f;
}
.footerdark h1 {
	border-bottom:1px solid #e7402f;
}
.grey-box-icon:hover .fontawesome-icon.circle-white,.grey-box-icon.active .fontawesome-icon.circle-white {
	background-color:#e7402f;
}
a.prev,a.next {
	background:url(../img/carousel_arrows.png) no-repeat #e7402f;
}
a.next {
	background-position:-22px 0
}
.btn-primary {
	background-color:#e7402f;
}
.panel,.panel1 {
border-left:8px solid #e7402f;
}
#filter ul li .selected {
color: #e7402f !Important;
}
.vuzz-pricing-table>div.popular {
border-top:#e7402f 3px solid;
}
::selection {background:#e7402f;color:#fff;}


text:
using System;
using System.Runtime.InteropServices;
//using CFNetwork;

using CoreFoundation;
using Foundation;
using ObjCRuntime;

namespace SocketRocketBinding
{

	//	[Static]
	//	[Verify(ConstantsInterfaceAssociation)]
	//partial interface Constants
	//{
	//	// extern NSString *const SRWebSocketErrorDomain;
	//	[Field("SRWebSocketErrorDomain", "__Internal")]
	//	NSString SRWebSocketErrorDomain { get; }

	//	// extern NSString *const SRHTTPResponseErrorKey;
	//	[Field("SRHTTPResponseErrorKey", "__Internal")]
	//	NSString SRHTTPResponseErrorKey { get; }
	//}

	// @interface SRWebSocket : NSObject <NSStreamDelegate>
	[BaseType(typeof(NSObject))]
	interface SRWebSocket : INSStreamDelegate
	{
		[Wrap("WeakDelegate")]
		SRWebSocketDelegate Delegate { get; set; }

		// @property (nonatomic, weak) id<SRWebSocketDelegate> delegate;
		[NullAllowed, Export("delegate", ArgumentSemantic.Weak)]
		NSObject WeakDelegate { get; set; }

		// @property (readonly, nonatomic) SRReadyState readyState;
		[Export("readyState")]
		SRReadyState ReadyState { get; }

		// @property (readonly, retain, nonatomic) NSURL * url;
		[Export("url", ArgumentSemantic.Retain)]
		NSUrl Url { get; }

		// @property (readonly, nonatomic) CFHTTPMessageRef receivedHTTPHeaders;
		//[Export("receivedHTTPHeaders")]
		//[DllImport ("/System/Library/Frameworks/CFNetwork.framework/CFNetwork")]
		//unsafe CFHTTPMessageRef* ReceivedHTTPHeaders { get; }

		// @property (readwrite, nonatomic) NSArray * requestCookies;
		[Export("requestCookies", ArgumentSemantic.Assign)]
		//[Verify(StronglyTypedNSArray)]
		NSObject[] RequestCookies { get; set; }

		// @property (readonly, copy, nonatomic) NSString * protocol;
		[Export("protocol")]
		string Protocol { get; }

		// -(id)initWithURLRequest:(NSURLRequest *)request protocols:(NSArray *)protocols allowsUntrustedSSLCertificates:(BOOL)allowsUntrustedSSLCertificates;
		[Export("initWithURLRequest:protocols:allowsUntrustedSSLCertificates:")]
		//[Verify(StronglyTypedNSArray)]
		IntPtr Constructor(NSUrlRequest request, NSObject[] protocols, bool allowsUntrustedSSLCertificates);

		// -(id)initWithURLRequest:(NSURLRequest *)request protocols:(NSArray *)protocols;
		[Export("initWithURLRequest:protocols:")]
		//[Verify(StronglyTypedNSArray)]
		IntPtr Constructor(NSUrlRequest request, NSObject[] protocols);

		// -(id)initWithURLRequest:(NSURLRequest *)request;
		[Export("initWithURLRequest:")]
		IntPtr Constructor(NSUrlRequest request);

		// -(id)initWithURL:(NSURL *)url protocols:(NSArray *)protocols allowsUntrustedSSLCertificates:(BOOL)allowsUntrustedSSLCertificates;
		[Export("initWithURL:protocols:allowsUntrustedSSLCertificates:")]
		//[Verify(StronglyTypedNSArray)]
		IntPtr Constructor(NSUrl url, NSObject[] protocols, bool allowsUntrustedSSLCertificates);

		// -(id)initWithURL:(NSURL *)url protocols:(NSArray *)protocols;
		[Export("initWithURL:protocols:")]
		//[Verify(StronglyTypedNSArray)]
		IntPtr Constructor(NSUrl url, NSObject[] protocols);

		// -(id)initWithURL:(NSURL *)url;
		[Export("initWithURL:")]
		IntPtr Constructor(NSUrl url);

		// -(void)setDelegateOperationQueue:(NSOperationQueue *)queue;
		[Export("setDelegateOperationQueue:")]
		void SetDelegateOperationQueue(NSOperationQueue queue);

		// -(void)setDelegateDispatchQueue:(dispatch_queue_t)queue;
		[Export("setDelegateDispatchQueue:")]
		void SetDelegateDispatchQueue(DispatchQueue queue);

		// -(void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode;
		[Export("scheduleInRunLoop:forMode:")]
		void ScheduleInRunLoop(NSRunLoop aRunLoop, string mode);

		// -(void)unscheduleFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode;
		[Export("unscheduleFromRunLoop:forMode:")]
		void UnscheduleFromRunLoop(NSRunLoop aRunLoop, string mode);

		// -(void)open;
		[Export("open")]
		void Open();

		// -(void)close;
		[Export("close")]
		void Close();

		// -(void)closeWithCode:(NSInteger)code reason:(NSString *)reason;
		[Export("closeWithCode:reason:")]
		void CloseWithCode(nint code, string reason);

		// -(void)send:(id)data;
		[Export("send:")]
		void Send(NSObject data);

		// -(void)sendPing:(NSData *)data;
		[Export("sendPing:")]
		void SendPing(NSData data);
	}

	// @protocol SRWebSocketDelegate <NSObject>
	[BaseType(typeof(NSObject))]
	[Model, Protocol]
	interface SRWebSocketDelegate
	{
		// @required -(void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message;
		[Abstract]
		[Export("webSocket:didReceiveMessage:")]
		void WebSocket(SRWebSocket webSocket, NSObject message);

		// @optional -(void)webSocketDidOpen:(SRWebSocket *)webSocket;
		[Export("webSocketDidOpen:")]
		void WebSocketDidOpen(SRWebSocket webSocket);

		// @optional -(void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error;
		[Export("webSocket:didFailWithError:")]
		void WebSocket(SRWebSocket webSocket, NSError error);

		// @optional -(void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean;
		[Export("webSocket:didCloseWithCode:reason:wasClean:")]
		void WebSocket(SRWebSocket webSocket, nint code, string reason, bool wasClean);

		// @optional -(void)webSocket:(SRWebSocket *)webSocket didReceivePong:(NSData *)pongPayload;
		[Export("webSocket:didReceivePong:")]
		void WebSocket(SRWebSocket webSocket, NSData pongPayload);

		// @optional -(BOOL)webSocketShouldConvertTextFrameToString:(SRWebSocket *)webSocket;
		[Export("webSocketShouldConvertTextFrameToString:")]
		bool WebSocketShouldConvertTextFrameToString(SRWebSocket webSocket);
	}

	//public interface ISRWebSocketDelegate
	//{ }

	// @interface SRCertificateAdditions (NSURLRequest)
	//[Category]
	//[BaseType(typeof(NSUrlRequest))]
	//interface NSURLRequest_SRCertificateAdditions
	//{
	//	// @property (readonly, retain, nonatomic) NSArray * SR_SSLPinnedCertificates;
	//	[Export("SR_SSLPinnedCertificates", ArgumentSemantic.Retain)]
	//	//	[Verify(StronglyTypedNSArray)]
	//	NSObject[] SR_SSLPinnedCertificates { get; }
	//}

	//// @interface SRCertificateAdditions (NSMutableURLRequest)
	//[Category]
	//[BaseType(typeof(NSMutableUrlRequest))]
	//interface NSMutableURLRequest_SRCertificateAdditions
	//{
	//	// @property (retain, nonatomic) NSArray * SR_SSLPinnedCertificates;
	//	[Export("SR_SSLPinnedCertificates", ArgumentSemantic.Retain)]
	//	//[Verify(StronglyTypedNSArray)]
	//	NSObject[] SR_SSLPinnedCertificates { get; set; }
	//}

	// @interface SRWebSocket (NSRunLoop)
	[Category]
	[BaseType(typeof(NSRunLoop))]
	interface NSRunLoop_SRWebSocket
	{
		// +(NSRunLoop *)SR_networkRunLoop;
		[Static]
		[Export("SR_networkRunLoop")]
		//	[Verify(MethodToProperty)]
		NSRunLoop SR_networkRunLoop { get; }
	}

	//[Static]
	////	[Verify(ConstantsInterfaceAssociation)]
	//partial interface Constants
	//{
	//	// extern double SocketRocketVersionNumber;
	//	[Field("SocketRocketVersionNumber", "__Internal")]
	//	double SocketRocketVersionNumber { get; }

	//	// extern const unsigned char [] SocketRocketVersionString;
	//	//[Field("SocketRocketVersionString", "__Internal")]
	//	//IntPtr SocketRocketVersionString { get; }
	//}

}


text: <gcse:searchbox-only resultsURL="{% url 'gcse_results' object.gid %}"></gcse:searchbox-only>


text:
package statics;

public class MembrosEstaticosTestDrive extends MembrosEstaticos {
	public static void main(String[] args) {
		System.out.println("Criar objetos!\n");

		MembrosEstaticos me = new MembrosEstaticos();
		// MembrosEstaticos me2 = new MembrosEstaticos();

	}
}


text:
namespace Alembic {
namespace AbcMaterial {
namespace ALEMBIC_VERSION_NS {

ALEMBIC_ABC_DECLARE_SCHEMA_INFO( "AbcMaterial_Material_v1",
                                 "",
                                 ".material",
                                 MaterialSchemaInfo );

}

using namespace ALEMBIC_VERSION_NS;

}
}

#endif


text:
module CommaHeaven
  module Sqler
    class AssociationColumns < Columns
      attr_accessor :position, :association

      # @parent@ is the parameter for passing a reference to the
      # containing columns array
      def initialize(association, export, position, parent, index = nil, options = {})
        self.parent = parent
        self.position = position
        self.association = association
        self.index = index
        super(association.klass, export, options)
      end

      def foreign_key_for(an_association)
        an_association.respond_to?(:foreign_key) ? an_association.foreign_key : an_association.primary_key_name
      end

      def table_alias(method = :pluralize)
        t = association.name.to_s.send(method)

        return prefix + [((parent && parent.parent) ? parent.table_alias(method) : nil), t, index].compact.join('_')
      end

      def prefix
        return "_"
      end
    end
  end
end


text:
import { APP_ID, APP_KEY, REGION } from '../../test/configs';
import AV from 'leancloud-storage';

import './file-message-and-subclasses';
import './location-message';

AV.init({
  appId: APP_ID,
  appKey: APP_KEY,
  region: REGION,
});


text:
package in.nerd_is.dragtodismisslayout;

/**
 * @author Xuqiang ZHENG on 2017/4/8.
 */
public class MathUtils {
    private MathUtils() {
    }

    public static double log2(double x) {
        return Math.log(x) / Math.log(2);
    }
}


text:
require 'active_merchant'
require 'test/unit'
require 'mocha'
require 'yaml'

begin
  gem 'actionpack'
rescue LoadError
  raise StandardError, "The view tests need ActionPack"
end

require 'action_controller'
require 'action_controller/test_process'
require 'active_merchant/billing/integrations/action_view_helper'

ActiveMerchant::Billing::Base.mode = :test

$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'active_merchant/bancomer'

module ActiveMerchant
  module Assertions
    def assert_field(field, value)
      clean_backtrace do
        assert_equal value, @helper.fields[field]
      end
    end

    # Allows the testing of you to check for negative assertions:
    #
    #   # Instead of
    #   assert !something_that_is_false
    #
    #   # Do this
    #   assert_false something_that_should_be_false
    #
    # An optional +msg+ parameter is available to help you debug.
    def assert_false(boolean, message = nil)
      message = build_message message, '<?> is not false or nil.', boolean

      clean_backtrace do
        assert_block message do
          not boolean
        end
      end
    end

    # A handy little assertion to check for a successful response:
    #
    #   # Instead of
    #   assert_success response
    #
    #   # DRY that up with
    #   assert_success response
    #
    # A message will automatically show the inspection of the response
    # object if things go afoul.
    def assert_success(response)
      clean_backtrace do
        assert response.success?, "Response failed: #{response.inspect}"
      end
    end

    # The negative of +assert_success+
    def assert_failure(response)
      clean_backtrace do
        assert_false response.success?, "Response expected to fail: #{response.inspect}"
      end
    end

    def assert_valid(validateable)
      clean_backtrace do
        assert validateable.valid?, "Expected to be valid"
      end
    end

    def assert_not_valid(validateable)
      clean_backtrace do
        assert_false validateable.valid?, "Expected to not be valid"
      end
    end

    private
    def clean_backtrace(&block)
      yield
    rescue Test::Unit::AssertionFailedError => e
      path = File.expand_path(__FILE__)
      raise Test::Unit::AssertionFailedError, e.message, e.backtrace.reject { |line| File.expand_path(line) =~ /#{path}/ }
    end
  end
end

class Test::Unit::TestCase
  include ActiveMerchant::Billing
  include ActiveMerchant::Assertions
  include ActiveMerchant::Utils
end


text:
/* global angular */

'use strict';

var app = angular.module('dicomUI');

// Step 1: Register states
app.config(function($stateProvider, $urlRouterProvider) {

    // Default route
    $urlRouterProvider.otherwise("/upload");

    // Shorthands
    var uiAppUri = "components/ui-app/";

    var menuUri     = uiAppUri + "menu/views/menu.html";
    var loginUri    = uiAppUri + "login/views/login.html";
    var uploaderUri = uiAppUri + "uploader/views/uploader.html";

    // Now set up the states
    $stateProvider

        .state('login', {
            url         : "/login",
            templateUrl : loginUri,
            controller  : 'LoginController'
        })

        // All routes below this point need authentication
        // I'm not using a custom resolve method.
        // See "main.js" has a .run statement about states-authentication

        .state('upload', {

            url     : "/upload",

            views   : {

                '' : {
                    templateUrl : uploaderUri,
                    controller  : 'UploaderController'
                },

                'menu' : {
                    templateUrl : menuUri,
                    controller  : 'MenuController'
                }
            },

            data    : {
                auth    : false,
                roles   : []
            }
        });
});

// Step 2: Handle state change logic
app.run(['$rootScope', '$state',

    function($rootScope, $state){

        $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState) {

            // Should the user be logged in for this root?
            var loginRequired = toState.data !== undefined && toState.data.auth;

            if(loginRequired){
                $state.go('login');
                event.preventDefault();
                return;
            }

            // Check access rights
            // var accessRights = ...
            // logic to handles access rights
        });
    }
]);


text:
package com.astir_trotter.atcustom.ui.iconics.core.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.ColorInt;
import android.support.annotation.ColorRes;
import android.support.annotation.DimenRes;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.widget.ImageView;

import com.astir_trotter.atcustom.R;
import com.astir_trotter.atcustom.ui.iconics.core.IconicsDrawable;
import com.astir_trotter.atcustom.ui.iconics.core.typeface.IIcon;
import com.astir_trotter.atcustom.util.Convertor;

@SuppressLint("AppCompatCustomView")
public class IconicsImageView extends ImageView {

    private IconicsDrawable mIcon = null;
    @ColorInt
    private int mColor = 0;
    private int mSize = -1;
    private int mPadding = -1;
    @ColorInt
    private int mContourColor = 0;
    private int mContourWidth = -1;
    @ColorInt
    private int mBackgroundColor = 0;
    private int mCornerRadius = -1;

    public IconicsImageView(Context context) {
        this(context, null);
    }

    public IconicsImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public IconicsImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        if (!isInEditMode()) {
            // Attribute initialization
            final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.IconicsImageView, defStyle, 0);
            String icon = a.getString(R.styleable.IconicsImageView_iiv_icon);

            //set the color even if we had no image yet
            mColor = a.getColor(R.styleable.IconicsImageView_iiv_color, 0);
            mSize = a.getDimensionPixelSize(R.styleable.IconicsImageView_iiv_size, -1);
            mPadding = a.getDimensionPixelSize(R.styleable.IconicsImageView_iiv_padding, -1);
            mContourColor = a.getColor(R.styleable.IconicsImageView_iiv_contour_color, 0);
            mContourWidth = a.getDimensionPixelSize(R.styleable.IconicsImageView_iiv_contour_width, -1);
            mBackgroundColor = a.getColor(R.styleable.IconicsImageView_iiv_background_color, 0);
            mCornerRadius = a.getDimensionPixelSize(R.styleable.IconicsImageView_iiv_corner_radius, -1);

            //recycle the typedArray
            a.recycle();

            //set the scale type for this view
            setScaleType(ScaleType.CENTER_INSIDE);

            //if we have no icon return now
            if (icon == null) {
                return;
            }

            //get the drawable
            mIcon = new IconicsDrawable(context, icon);

            //set attributes
            setAttributes();

            //set our values for this view
            setImageDrawable(mIcon);
        }
    }

    public void setIcon(Character icon) {
        setIcon(icon, true);
    }

    public void setIcon(Character icon, boolean resetAttributes) {
        setIcon(new IconicsDrawable(getContext(), icon), resetAttributes);
    }

    public void setIcon(String icon) {
        setIcon(icon, true);
    }

    public void setIcon(String icon, boolean resetAttributes) {
        setIcon(new IconicsDrawable(getContext(), icon), resetAttributes);
    }

    public void setIcon(IIcon icon) {
        setIcon(icon, true);
    }

    public void setIcon(IIcon icon, boolean resetAttributes) {
        setIcon(new IconicsDrawable(getContext(), icon), resetAttributes);
    }

    public void setIcon(IconicsDrawable icon) {
        setIcon(icon, true);
    }

    public void setIcon(IconicsDrawable icon, boolean resetAttributes) {
        mIcon = icon;
        //reset the attributes defined via the layout
        if (resetAttributes) {
            setAttributes();
        }
        //set the imageDrawable
        setImageDrawable(mIcon);
    }

    public void setIconText(String iconText) {
        setIconText(iconText, true);
    }

    public void setIconText(String iconText, boolean resetAttributes) {
        setIcon(new IconicsDrawable(getContext()).iconText(iconText), resetAttributes);
    }

    private void setAttributes() {
        if (mColor != 0) {
            mIcon.color(mColor);
        }
        if (mSize != -1) {
            mIcon.sizePx(mSize);
        }
        if (mPadding != -1) {
            mIcon.paddingPx(mPadding);
        }
        if (mContourColor != 0) {
            mIcon.contourColor(mContourColor);
        }
        if (mContourWidth != -1) {
            mIcon.contourWidthPx(mContourWidth);
        }
        if (mBackgroundColor != 0) {
            mIcon.backgroundColor(mBackgroundColor);
        }
        if (mCornerRadius != -1) {
            mIcon.roundedCornersPx(mCornerRadius);
        }
    }

    public void setColor(@ColorInt int color) {
        if (getDrawable() instanceof IconicsDrawable) {
            ((IconicsDrawable) getDrawable()).color(color);
        }
        mColor = color;
    }

    public void setColorRes(@ColorRes int colorRes) {
        if (getDrawable() instanceof IconicsDrawable) {
            ((IconicsDrawable) getDrawable()).colorRes(colorRes);
        }
        mColor = ContextCompat.getColor(getContext(), colorRes);
    }

    public void setPaddingPx(int padding) {
        if (getDrawable() instanceof IconicsDrawable) {
            ((IconicsDrawable) getDrawable()).paddingPx(padding);
        }
        mPadding = padding;
    }

    public void setPaddingDp(int paddingDp) {
        if (getDrawable() instanceof IconicsDrawable) {
            ((IconicsDrawable) getDrawable()).paddingDp(paddingDp);
        }
        mPadding = (int) Convertor.dp2px(paddingDp);
    }

    public void setPaddingRes(@DimenRes int paddingRes) {
        if (getDrawable() instanceof IconicsDrawable) {
            ((IconicsDrawable) getDrawable()).paddingRes(paddingRes);
        }
        mPadding = getContext().getResources().getDimensionPixelSize(paddingRes);
    }

    public void setContourColor(@ColorInt int color) {
        if (getDrawable() instanceof IconicsDrawable) {
            ((IconicsDrawable) getDrawable()).contourColor(color);
        }
        mContourColor = color;
    }

    public void setContourColorRes(@ColorRes int colorRes) {
        if (getDrawable() instanceof IconicsDrawable) {
            ((IconicsDrawable) getDrawable()).contourColorRes(colorRes);
        }
        mContourColor = ContextCompat.getColor(getContext(), colorRes);
    }

    public void setContourWidthPx(int contourWidth) {
        if (getDrawable() instanceof IconicsDrawable) {
            ((IconicsDrawable) getDrawable()).contourWidthPx(contourWidth);
        }
        mContourWidth = contourWidth;
    }

    public void setContourWidthDp(int contourWidthDp) {
        if (getDrawable() instanceof IconicsDrawable) {
            ((IconicsDrawable) getDrawable()).contourWidthDp(contourWidthDp);
        }
        mContourWidth = (int) Convertor.dp2px(contourWidthDp);
    }

    public void setContourWidthRes(@DimenRes int contourWidthRes) {
        if (getDrawable() instanceof IconicsDrawable) {
            ((IconicsDrawable) getDrawable()).contourWidthRes(contourWidthRes);
        }
        mContourWidth = getContext().getResources().getDimensionPixelSize(contourWidthRes);
    }

    public void setBackgroundColor(@ColorInt int color) {
        if (getDrawable() instanceof IconicsDrawable) {
            ((IconicsDrawable) getDrawable()).backgroundColor(color);
        }
        mBackgroundColor = color;
    }

    public void setBackgroundColorRes(@ColorRes int colorRes) {
        if (getDrawable() instanceof IconicsDrawable) {
            ((IconicsDrawable) getDrawable()).backgroundColorRes(colorRes);
        }
        mBackgroundColor = ContextCompat.getColor(getContext(), colorRes);
    }

    public void setRoundedCornersPx(int cornerRadius) {
        if (getDrawable() instanceof IconicsDrawable) {
            ((IconicsDrawable) getDrawable()).roundedCornersDp(cornerRadius);
        }
        mCornerRadius = cornerRadius;
    }

    public void setRoundedCornersDp(int cornerRadiusDp) {
        if (getDrawable() instanceof IconicsDrawable) {
            ((IconicsDrawable) getDrawable()).roundedCornersDp(cornerRadiusDp);
        }
        mCornerRadius = (int) Convertor.dp2px(cornerRadiusDp);
    }

    public void setRoundedCornersRes(@DimenRes int cornerRadiusRes) {
        if (getDrawable() instanceof IconicsDrawable) {
            ((IconicsDrawable) getDrawable()).roundedCornersPx(cornerRadiusRes);
        }
        mCornerRadius = getContext().getResources().getDimensionPixelSize(cornerRadiusRes);
    }

    public IconicsDrawable getIcon() {
        if (getDrawable() instanceof IconicsDrawable) {
            return ((IconicsDrawable) getDrawable());
        }
        return mIcon;
    }
}


text:
use dotenv::dotenv;
use std::ops::Deref;

use std::env;
use diesel::pg::PgConnection;
use diesel::r2d2::{self, ConnectionManager};

use rocket::http::Status;
use rocket::request::{self, FromRequest};
use rocket::{Outcome, Request, State};

pub type Pool = r2d2::Pool<ConnectionManager<PgConnection>>;

pub fn init_pool() -> Pool {
    dotenv().ok();
    let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    let manager = ConnectionManager::<PgConnection>::new(database_url);
    r2d2::Pool::new(manager).expect("db pool");
}

pub struct Conn(pub r2d2::PooledConnection<ConnectionManager<PgConnection>>);

impl Deref for Conn {
    type Target = PgConnection;
    #[inline(always)]
    fn deref(&self) -> &Self::Target {
        &self.0
    }

}
impl <'a, 'r> FromRequest<'a, 'r> for Conn {
    type Error = ();
    fn from_request(request: &'a Request<'r>) -> request.:Outcome<Conn, ()> {
        let pool = request.guard::<State<Pool>>()?;
        match pool.get() {
            Ok(conn) => Outcome::Success(Conn(conn)),
            Err(_) => Outcome::Failure((Status::ServiceUnavailable, ())),
        }
    }
}