text:
angular.module('basic_framework').factory('LogicLayer', ['RepositoryLayer', '$q', function (RepositoryLayer, $q) {
    //$q - A service that helps you run functions asynchronously,
    // and use their return values (or exceptions) when they are done processing.

    //Assign the scope of LogicLayer factory to a variable LogicLayer
    var LogicLayer = this;

    LogicLayer.entries = {};

    LogicLayer.getAllEntries = function() {

        //A promise represents the eventual result of an asynchronous operation.
        // It is a placeholder into which the successful result value or reason for failure will materialize.

        //The purpose of the deferred object is to expose the associated Promise instance as well as APIs that
        // can be used for signaling the successful or unsuccessful completion, as well as the status of the task.
        var deferred = $q.defer();

        //Make $http call using endpoint specified in repositoryLayer
        RepositoryLayer.getEntries().then(function(response){
            //Success callBack - handle the response

            //Log the response object to the console
            console.log(response);

            //Assign the response data to new object to get rid of unnecessary data
            LogicLayer.entries = response.data;

            //Resolve the derived promise with LogicLayer.entries
            deferred.resolve(LogicLayer.entries);
        }).catch(function(error){
            //error callBack
            //.catch(errorCallBack) is shorthand for promise.then(null, errorCallBack)

            //Reject the promise with the reason
            deferred.reject(error);
        });

        return deferred.promise;
    };

    LogicLayer.addEntry = function(entry) {

        //Instantiate deferred object using $q.defer()
        var deferred = $q.defer();

        //Make $http call using endpoint specified in repositoryLayer
        RepositoryLayer.postEntry(entry).then(function(response){
            //success
            console.log("Successfully posted person");

            //Logging the response will log the http response from the API which in this case returns the data 'Posted'
            //console.log(response);

            //Resolve the promise with the response
            deferred.resolve(response);
        }).catch(function(error){

            //Reject the promise with the reason/error
            deferred.reject(error);
        });

        return deferred.promise;
    };

    LogicLayer.delete = function(entry) {

        var deferred = $q.defer();

        //Make $http call using endpoint specified in repositoryLayer
        RepositoryLayer.deleteEntry(entry).then(function(response){
            //success callback

            //Log the response to the console which will contain the data 'Deleted' sent from API
            console.log(response);
            console.log("Successfully deleted person");

            //Resolve using response
            deferred.resolve(response);
        }).catch(function(error){
            console.log(error);

            //Reject with error/reason
            deferred.reject(error);
        });

        return deferred.promise;
    };

    //Return the scope through the reference variable LogicLayer
    return LogicLayer;

}]);


text:
using System;
using UnityEngine;
using System.Collections;

public class PlayerUIController : MonoBehaviour
{
    private PowerUpCollector _powerUpCollector;
    private GameObject _lastObject;
    private Texture _powerUpIcon;
    private CarRankTracker _rankTracker;
    private GUIStyle _ScoreStyle = new GUIStyle();

    void Start ()
	{
	    _powerUpCollector = GetComponent<PowerUpCollector>();
        _rankTracker = GetComponent<CarRankTracker>();

        _ScoreStyle.normal.textColor = Color.red;
        _ScoreStyle.fontSize = 32;
        _ScoreStyle.alignment = TextAnchor.UpperCenter;
	}

	void Update ()
	{
	    if (_powerUpCollector.CurrentItem == null)
	        _powerUpIcon = null;

	    if (_lastObject == _powerUpCollector.CurrentItem) return;

	    _lastObject = _powerUpCollector.CurrentItem;

	    if (_lastObject == null)
	    {
	        _powerUpIcon = null;
	        return;

	    }

	    var info = _lastObject.GetComponent<PowerUpInfo>();

        _powerUpIcon = info.Icon.texture;
    }

    void OnGUI()
    {
        if (_powerUpIcon != null)
        {
            GUI.DrawTexture(new Rect(0,0, 64,64), _powerUpIcon, ScaleMode.ScaleToFit, true, 1f);
        }

        var speed = Math.Floor(rigidbody2D.velocity.magnitude*3600/1000);
        var scoreString = string.Format("Speed: {0} Rank: {1}/10 Lap: {2}/3", speed, _rankTracker.Rank, _rankTracker.Lap);

        GUI.Label(new Rect(0, 0, Screen.width, Screen.height), scoreString, _ScoreStyle);
    }
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 * Config
 * -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 */

const _baseEndpointUrl = {
  production: 'https://jsonplaceholder.typicode.com',
  development: 'https://jsonplaceholder.typicode.com',
};
const baseEndpointUrl = _baseEndpointUrl[process.env.NODE_ENV];

const cookieAuthStatusName = 'rardpg_auth_status';

export {
  baseEndpointUrl,
  cookieAuthStatusName
};


text:
<!DOCTYPE html>

	<meta charset="utf-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1">
	<title>
		Elementos finitos con aplicaciones - Introducción
	</title>
	<link rel="stylesheet" href="./css/uvm2013rwd.css" media="screen" />
	<link rel="stylesheet" href="./css/uvm2013print.css" media="print" />
	<link rel="stylesheet" href="./css/html_templates/template10rwd.css" type="text/css" media="screen" />
	<link rel="shortcut icon" href="./images/icono.ico" />
	<base href="index.html" />

GitHub

CV

FAQ

Página personal

Inicio

scipy-lecture-notes-ES

Teoria-FEM-Python

Introducción a la programación

Métodos numéricos I

Métodos numéricos II

Ingeniería sanitaria

Hormigón armado

Mecánica de rocas - Introducción

Dinámica estructural - Introducción

Dinámica de fluidos computacional - Introducción

Elementos finitos con aplicaciones - Introducción

Publicaciones

Contacto

Elementos finitos con aplicaciones - Introducción

Soluciones analíticas aproximadas

Método de residuos ponderados

Método de mínimos cuadrados

Ejemplo 1

Método de Bubnov-Galerkin

Ejemplo 1 Ecuación diferencial ordinaria

Ejemplo 2 Barra con carga distribuida y carga puntual

Ejemplo 3 Viga con carga distribuida y carga puntual

Método de Petrov-Galerkin

Ejemplo 1

Funciones base estándar

Método de Bubnov-Galerkin usando formulación en desplazamientos

Barra con carga distribuida y carga puntual

Ejemplo 1 Solución aproximada generalizada

Ejemplo 2 Solución aproximada lineal

Ejemplo 3 Solución aproximada cuadrática

Viga con carga distribuida y carga puntual

Ejemplo 4 Solución aproximada generalizada

Ejemplo 5 Solución aproximada cúbica

Ejemplo 6 Solución aproximada de quinto orden

   	<address>

© 2015

   	</address>


text:
package org.apache.olingo.odata2.api.processor.part;

import java.io.InputStream;

import org.apache.olingo.odata2.api.exception.ODataException;
import org.apache.olingo.odata2.api.processor.ODataProcessor;
import org.apache.olingo.odata2.api.processor.ODataResponse;
import org.apache.olingo.odata2.api.uri.info.DeleteUriInfo;
import org.apache.olingo.odata2.api.uri.info.GetMediaResourceUriInfo;
import org.apache.olingo.odata2.api.uri.info.PutMergePatchUriInfo;

/**
 * Execute an OData entity media request
 *
 */
public interface EntityMediaProcessor extends ODataProcessor {

  /**
   * Reads the media resource of an entity.
   * @param uriInfo information about the request URI
   * @param contentType the content type of the response
   * @return an {@link ODataResponse} object
   * @throws ODataException
   */
  ODataResponse readEntityMedia(GetMediaResourceUriInfo uriInfo, String contentType) throws ODataException;

  /**
   * Updates the media resource of an entity.
   * @param uriInfo information about the request URI
   * @param content the content of the request
   * @param requestContentType the content type of the request body
   * @param contentType the content type of the response
   * @return an {@link ODataResponse} object
   * @throws ODataException
   */
  ODataResponse updateEntityMedia(PutMergePatchUriInfo uriInfo, InputStream content, String requestContentType,
      String contentType) throws ODataException;

  /**
   * Deletes the media resource of an entity.
   * @param uriInfo information about the request URI
   * @param contentType the content type of the response
   * @return an {@link ODataResponse} object
   * @throws ODataException
   */
  ODataResponse deleteEntityMedia(DeleteUriInfo uriInfo, String contentType) throws ODataException;
}


text:
TESTS = auto check diagnostic failing known skip todo writer yaml
GOPATH ?= $(CURDIR)/gopath

.PHONY: $(TESTS)

all: $(foreach t,$(TESTS),test/$(t)/test)
	prove -v -e '' test/*/test

clean:
	rm -f test/*/test

test/%/test: test/%/*.go tap.go yaml_json.go yaml_yaml.go
	go build -o $@ -tags yaml ./test/$*

$(TESTS): %: test/%/test
	prove -v -e '' test/$@/test


text:
package org.jruby.test;

import junit.framework.TestCase;

import org.jruby.Ruby;
import org.jruby.RubyObject;
import org.jruby.runtime.builtin.IRubyObject;

public class TestRubyObject extends TestCase {
    private Ruby runtime;
    private IRubyObject rubyObject;

    public TestRubyObject(String name) {
        super(name);
    }

    public void setUp() {
        runtime = Ruby.newInstance();
        rubyObject = new RubyObject(runtime, runtime.getObject());
    }

    public void testNil() {
        assertTrue(!rubyObject.isNil());
    }

    public void testTrue() {
        assertTrue(rubyObject.isTrue());
    }

    public void testEquals() {
        assertTrue(rubyObject.equals(rubyObject));
    }

    public void testClone() {
        assertTrue(rubyObject.rbClone().getType() == rubyObject.getType());
    }

    public void testDup() {
        assertTrue(rubyObject.dup().getType() == rubyObject.getType());
    }

    public void testType() {
        assertEquals("Object", rubyObject.getType().name().toString());
    }

    public void testFreeze() {
        assertTrue(!rubyObject.isFrozen());
        rubyObject.setFrozen(true);
        assertTrue(rubyObject.isFrozen());
    }

    public void testTaint() {
        assertTrue(!rubyObject.isTaint());
        rubyObject.setTaint(true);
        assertTrue(rubyObject.isTaint());
    }

    public void test_to_s() {
        assertTrue(rubyObject.toString().startsWith("#<Object:0x"));
    }

    public void test_kind_of() {
        assertTrue(runtime.getObject().isInstance(rubyObject));
        // assertTrue(rubyObject.kind_of(ruby.getClasses().getStringClass()).isFalse());
    }
}


text:
<?php

namespace Illuminate\Queue;

use Closure;
use Symfony\Component\Process\PhpExecutableFinder;
use Symfony\Component\Process\Process;

class Listener
{
    /**
     * The command working path.
     *
     * @var string
     */
    protected $commandPath;

    /**
     * The environment the workers should run under.
     *
     * @var string
     */
    protected $environment;

    /**
     * The amount of seconds to wait before polling the queue.
     *
     * @var int
     */
    protected $sleep = 3;

    /**
     * The amount of times to try a job before logging it failed.
     *
     * @var int
     */
    protected $maxTries = 0;

    /**
     * The output handler callback.
     *
     * @var \Closure|null
     */
    protected $outputHandler;

    /**
     * Create a new queue listener.
     *
     * @param  string  $commandPath
     * @return void
     */
    public function __construct($commandPath)
    {
        $this->commandPath = $commandPath;
    }

    /**
     * Get the PHP binary.
     *
     * @return string
     */
    protected function phpBinary()
    {
        return (new PhpExecutableFinder)->find(false);
    }

    /**
     * Get the Artisan binary.
     *
     * @return string
     */
    protected function artisanBinary()
    {
        return defined('ARTISAN_BINARY') ? ARTISAN_BINARY : 'artisan';
    }

    /**
     * Listen to the given queue connection.
     *
     * @param  string  $connection
     * @param  string  $queue
     * @param  \Illuminate\Queue\ListenerOptions  $options
     * @return void
     */
    public function listen($connection, $queue, ListenerOptions $options)
    {
        $process = $this->makeProcess($connection, $queue, $options);

        while (true) {
            $this->runProcess($process, $options->memory);
        }
    }

    /**
     * Create a new Symfony process for the worker.
     *
     * @param  string  $connection
     * @param  string  $queue
     * @param  \Illuminate\Queue\ListenerOptions  $options
     * @return \Symfony\Component\Process\Process
     */
    public function makeProcess($connection, $queue, ListenerOptions $options)
    {
        $command = $this->createCommand(
            $connection,
            $queue,
            $options
        );

        // If the environment is set, we will append it to the command array so the
        // workers will run under the specified environment. Otherwise, they will
        // just run under the production environment which is not always right.
        if (isset($options->environment)) {
            $command = $this->addEnvironment($command, $options);
        }

        return new Process(
            $command,
            $this->commandPath,
            null,
            null,
            $options->timeout
        );
    }

    /**
     * Add the environment option to the given command.
     *
     * @param  array  $command
     * @param  \Illuminate\Queue\ListenerOptions  $options
     * @return array
     */
    protected function addEnvironment($command, ListenerOptions $options)
    {
        return array_merge($command, ["--env={$options->environment}"]);
    }

    /**
     * Create the command with the listener options.
     *
     * @param  string  $connection
     * @param  string  $queue
     * @param  \Illuminate\Queue\ListenerOptions  $options
     * @return array
     */
    protected function createCommand($connection, $queue, ListenerOptions $options)
    {
        return array_filter([
            $this->phpBinary(),
            $this->artisanBinary(),
            'queue:work',
            $connection,
            '--once',
            "--queue={$queue}",
            "--delay={$options->delay}",
            "--memory={$options->memory}",
            "--sleep={$options->sleep}",
            "--tries={$options->maxTries}",
        ], function ($value) {
            return ! is_null($value);
        });
    }

    /**
     * Run the given process.
     *
     * @param  \Symfony\Component\Process\Process  $process
     * @param  int  $memory
     * @return void
     */
    public function runProcess(Process $process, $memory)
    {
        $process->run(function ($type, $line) {
            $this->handleWorkerOutput($type, $line);
        });

        // Once we have run the job we'll go check if the memory limit has been exceeded
        // for the script. If it has, we will kill this script so the process manager
        // will restart this with a clean slate of memory automatically on exiting.
        if ($this->memoryExceeded($memory)) {
            $this->stop();
        }
    }

    /**
     * Handle output from the worker process.
     *
     * @param  int  $type
     * @param  string  $line
     * @return void
     */
    protected function handleWorkerOutput($type, $line)
    {
        if (isset($this->outputHandler)) {
            call_user_func($this->outputHandler, $type, $line);
        }
    }

    /**
     * Determine if the memory limit has been exceeded.
     *
     * @param  int  $memoryLimit
     * @return bool
     */
    public function memoryExceeded($memoryLimit)
    {
        return (memory_get_usage(true) / 1024 / 1024) >= $memoryLimit;
    }

    /**
     * Stop listening and bail out of the script.
     *
     * @return void
     */
    public function stop()
    {
        exit;
    }

    /**
     * Set the output handler callback.
     *
     * @param  \Closure  $outputHandler
     * @return void
     */
    public function setOutputHandler(Closure $outputHandler)
    {
        $this->outputHandler = $outputHandler;
    }
}


text:
define(['jquery',
        'models/visit', 'collections/visits',
        'views/assign', 'views/visits',
        'jquery.mobile',],
function($,
    Visit, Visits,
    AssignView, VisitsView
    ) {

    var controller = {
        visits: function() {
            var visits = new Visits(null)
            var self = this
            visits.fetch({
                success: function() {
                    self.changeView(new VisitsView({ collection: visits }))
                }
            })
        },

        assign: function(visit) {
            var vis = new Visit({ VISIT: visit })
            var self = this
            vis.fetch({
                success: function() {
                    self.changeView(new AssignView({ model: vis }))
                }
            })
        },

        changeView: function(view, transition) {
            app.views.outgoing = app.views.incoming
            app.views.incoming = view

            $('body').append(view.render().$el)
            $('body').pagecontainer("change", view.$el, { transition: "slide" })
            console.log('change view')

            setTimeout(function() {
                console.log('destroying', app.views.outgoing)
                if (app.views.outgoing) app.views.outgoing.destroy()
            }, 2*1000)
        },
    }

    app.addInitializer(function() {
        app.on('assign:visit', function(visit) {
            controller.assign(visit)
        })
    })

    app.addInitializer(function() {
        app.on('visits', function() {
            controller.visits()
            app.router.navigate('')
        })
    })

    return controller

})


text:
<?= $this->url->link('KB', 'app', 'index', array(), false, 'logo', t('Dashboard')).' '.$this->e($title) ?>
            <?php if (! empty($description)): ?>
                <span class="tooltip" title='<?= $this->e($this->text->markdown($description)) ?>'>

            <?php endif ?>

            <?php if (isset($board_selector) && ! empty($board_selector)): ?>

                <select id="board-selector"
                        class="chosen-select select-auto-redirect"
                        tabindex="-1"
                        data-notfound="<?= t('No results match:') ?>"
                        data-placeholder="<?= t('Display another project') ?>"
                        data-redirect-regex="PROJECT_ID"
                        data-redirect-url="<?= $this->url->href('board', 'show', array('project_id' => 'PROJECT_ID')) ?>">
                    <option value=""></option>
                    <?php foreach($board_selector as $board_id => $board_name): ?>
                        <option value="<?= $board_id ?>"><?= $this->e($board_name) ?></option>
                    <?php endforeach ?>
                </select>

            <?php endif ?>

                <?= $this->url->link(t('Logout'), 'auth', 'logout') ?>
                (<?= $this->user->getProfileLink() ?>)


text:
'use strict';

describe('GravatarUrlBuilderSrvc', function() {
    beforeEach(module("eventsApp"));

    var email = "x@y.com";
    it('should contain image url reference', inject(function(gravatarUrlBuilder) {
        expect(gravatarUrlBuilder.buildGravatarUrl(email)).toContain(".jpg");
    }));
});


text:
/*
 *
 * TeamManagement actions
 *
 */

import {
  FETCH_EMPLOYEES,
  SET_MEMBER_TO_PREVIEW,
  SET_ADMIN,
  SET_CONFIRMATION_OPTIONS,
  TOGGLE_ADD_MEMBER_MODAL,
  DELETE_EMPLOYEE,
  ADD_EMPLOYEE,
} from './constants';

export function getEmployees(hotelId) {
  return {
    type: FETCH_EMPLOYEES,
    hotelId,
  };
}

export function setMemberToPreview(index) {
  return {
    type: SET_MEMBER_TO_PREVIEW,
    index,
  };
}

export function setAdmin(employeeId) {
  return {
    type: SET_ADMIN,
    employeeId,
  };
}

export function deleteEmployee(employeeId) {
  return {
    type: DELETE_EMPLOYEE,
    employeeId,
  };
}

export function setConfirmationOptions(options) {
  return {
    type: SET_CONFIRMATION_OPTIONS,
    options,
  };
}

export function toggleAddMemberModal(shouldDisplay) {
  return {
    type: TOGGLE_ADD_MEMBER_MODAL,
    shouldDisplay,
  };
}

export function addEmployee(details, hotelId, userId) {
  return {
    type: ADD_EMPLOYEE,
    details,
    hotelId,
    userId,
  };
}


text:
package com.danikula.videocache;

import java.io.ByteArrayInputStream;
import java.util.Arrays;

/**
 * Simple memory based {@link Cache} implementation.
 *
 * @author Alexey Danilov (danikula@gmail.com).
 */
public class ByteArrayCache implements Cache {

    private volatile byte[] data;
    private volatile boolean completed;

    public ByteArrayCache() {
        this(new byte[0]);
    }

    public ByteArrayCache(byte[] data) {
        this.data = Preconditions.checkNotNull(data);
    }

    @Override
    public int read(byte[] buffer, long offset, int length) throws ProxyCacheException {
        if (offset >= data.length) {
            return -1;
        }
        if (offset > Integer.MAX_VALUE) {
            throw new IllegalArgumentException("Too long offset for memory cache " + offset);
        }
        return new ByteArrayInputStream(data).read(buffer, (int) offset, length);
    }

    @Override
    public long available() throws ProxyCacheException {
        return data.length;
    }

    @Override
    public void append(byte[] newData, int length) throws ProxyCacheException {
        Preconditions.checkNotNull(data);
        Preconditions.checkArgument(length >= 0 && length <= newData.length);

        byte[] appendedData = Arrays.copyOf(data, data.length + length);
        System.arraycopy(newData, 0, appendedData, data.length, length);
        data = appendedData;
    }

    @Override
    public void close() throws ProxyCacheException {
    }

    @Override
    public void complete() {
        completed = true;
    }

    @Override
    public boolean isCompleted() {
        return completed;
    }
}


text:
<?php
/**
 * Piwik - Open source web analytics
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 * @category Piwik
 * @package Piwik
 */

/**
 * Class for sending mails, for more information see:
 *
 * @package Piwik
 * @see Zend_Mail, libs/Zend/Mail.php
 * @link http://framework.zend.com/manual/en/zend.mail.html
 */
class Piwik_Mail extends Zend_Mail
{
    /**
     * Default charset utf-8
     *
     * @param string $charset  charset, defaults to utf-8
     */
    public function __construct($charset = 'utf-8')
    {
        parent::__construct($charset);
        $this->initSmtpTransport();
    }

    /**
     * Sets the sender to use
     *
     * @param string $email
     * @param null|string $name
     * @return Zend_Mail
     */
    public function setFrom($email, $name = null)
    {
        $hostname = Piwik_Config::getInstance()->mail['defaultHostnameIfEmpty'];
        $piwikHost = Piwik_Url::getCurrentHost($hostname);

        // If known Piwik URL, use it instead of "localhost"
        $piwikUrl = Piwik::getPiwikUrl();
        $url = parse_url($piwikUrl);
        if (isset($url['host'])
            && $url['host'] != 'localhost'
            && $url['host'] != '127.0.0.1'
        ) {
            $piwikHost = $url['host'];
        }
        $email = str_replace('{DOMAIN}', $piwikHost, $email);
        return parent::setFrom($email, $name);
    }

    /**
     * @return void
     */
    private function initSmtpTransport()
    {
        $mailConfig = Piwik_Config::getInstance()->mail;
        if (empty($mailConfig['host'])
            || $mailConfig['transport'] != 'smtp'
        ) {
            return;
        }
        $smtpConfig = array();
        if (!empty($mailConfig['type']))
            $smtpConfig['auth'] = strtolower($mailConfig['type']);
        if (!empty($mailConfig['username']))
            $smtpConfig['username'] = $mailConfig['username'];
        if (!empty($mailConfig['password']))
            $smtpConfig['password'] = $mailConfig['password'];
        if (!empty($mailConfig['encryption']))
            $smtpConfig['ssl'] = $mailConfig['encryption'];

        $tr = new Zend_Mail_Transport_Smtp($mailConfig['host'], $smtpConfig);
        Piwik_Mail::setDefaultTransport($tr);
        ini_set("smtp_port", $mailConfig['port']);
    }
}


text:
@echo off

set CK_CUR_PATH=%~dp0
set CK_CUSTOM_AUTOTUNER_SCRIPT="%CK_CUR_PATH%\autotune_customized_universal1_plugin.bat"

ck autotune program:custom-autotuning-wrapper @autotune_customized_universal1.json --new --skip_collaborative --skip_pruning --scenario=experiment.tune.custom.dimensions


text:
Lazy Array
==========

[![Build Status](https://travis-ci.org/harp-orm/lazy-array.svg?branch=master)](https://travis-ci.org/harp-orm/lazy-array)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/harp-orm/lazy-array/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/harp-orm/lazy-array/?branch=master)
[![Code Coverage](https://scrutinizer-ci.com/g/harp-orm/lazy-array/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/harp-orm/lazy-array/?branch=master)
[![Latest Stable Version](https://poser.pugx.org/harp-orm/lazy-array/v/stable.png)](https://packagist.org/packages/harp-orm/lazy-array)

An array which contents can be loaded only when needed

Instalation
-----------

Install via composer

```
composer require harp-orm/lazy-array
```

Usage
-----
```
$arr = new LazyArray($loader);

// This is where the loader->load() method gets executed
echo $arr[2];
```

License
-------

Copyright (c) 2015, Clippings Ltd. Developed by Ivan Kerin

Under BSD-3-Clause license, read LICENSE file.


text:
import button from './button/button';

export const COMPONENTS = [
  button
];


text:
Middelman allows you to define [local data](http://middlemanapp.com/advanced/local-data/). DataModel allows you to define a model class which will be mapped with that data. This is useful:

* If you hate hashes in your view code and want to call methods
* Want to eventually move to another system that uses an ORM

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'middleman-data_model'
```

And then execute:

```bash
$ bundle
```

Or install it yourself as:

```bash
$ gem install middleman-data_model
```

## Usage

* Add the gem to your gemfile within your middleman project

```ruby
gem 'middleman-data_model'
```

* Add the following line to your **config.rb**

```ruby
activate :data_models
```

* Define a model class within your **data** directory which is a sub-class of `Middleman::DataModel::SimpleDataModel`.

Here I define an Event model which will automatically match itself to any data
stored in `data.events`.

```ruby
class Event < Middleman::DataModel::SimpleDataModel

end
```

* Use the model within your view:

```erb
<div class="events">
  <ul class="events-list">
    <%= Event.all.each do |event| %>
      <li class="vevent">
        <div class="img">
          <img src="<%= event.image_url" alt="<%= event.image_alt %>">
        </div>
        <div>
          <h3><a href="/"><%= event.title %></a></h3>
          <p class="location"><a href="/"><%= event.location %></a></p>
          <p class="details"><%= event.details %></p>
        </div>
      </li>
    <% end %>
  </ul>
</div>
```

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
package org.terasology.gestalt.di.injection.beans;

import javax.inject.Inject;

public class Counter2 implements ICounter {
    @Inject
    public Counter2() {

    }
    private int count = 0;

    @Override
    public void add() {
        count++;
    }

    @Override
    public int getCount() {
        return count;
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016-08-17
 * Time: 10:54
 */

namespace Addons\Model;

use Grace\Base\ModelInterface;

class Gate implements ModelInterface
{
    public function depend()
    {
        return[
          'Model::Token',
        ];
    }

    //凡是token必须的接口都要接受token检验后才能调用相应的方法
    public function verifyToken($token)
    {
        model('Token')->verifyToken($token);
    }

}


text:
// -----------------------------------------------------------------------
// <copyright file="LoadBalancingTransport.cs" company="Exit Games GmbH">
//   Photon Voice API Framework for Photon - Copyright (C) 2015 Exit Games GmbH
// </copyright>
// <summary>
//   Extends Photon Realtime API with media streaming functionality.
// </summary>
// <author>developer@photonengine.com</author>
// ----------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using ExitGames.Client.Photon;
using Photon.Realtime;

namespace Photon.Voice
{
    class VoiceEvent
    {
        /// <summary>
        /// Single event used for voice communications.
        /// </summary>
        /// Change if it conflicts with other event codes used in the same Photon room.
        public const byte Code = 202; // all photon voice events use single event code
        public const byte FrameCode = 203; // LoadBalancingTransport2 uses separate code for frame event serialized as byte[]
    }

    /// <summary>
    /// Extends LoadBalancingClient with media streaming functionality.
    /// </summary>
    /// <remarks>
    /// Use your normal LoadBalancing workflow to join a Voice room.
    /// All standard LoadBalancing features are available.
    /// Use <see cref="VoiceClient"/> to work with media streams.
    /// </remarks>
    public class LoadBalancingTransport : LoadBalancingClient, IVoiceTransport, ILogger, IDisposable
    {
        internal const int VOICE_CHANNEL = 0;

        /// <summary>The <see cref="VoiceClient"></see> implementation associated with this LoadBalancingTransport.</summary>
        public VoiceClient VoiceClient { get { return this.voiceClient; } }

        protected VoiceClient voiceClient;
        private PhotonTransportProtocol protocol;

        public void LogError(string fmt, params object[] args) { this.DebugReturn(DebugLevel.ERROR, string.Format(fmt, args)); }
        public void LogWarning(string fmt, params object[] args) { this.DebugReturn(DebugLevel.WARNING, string.Format(fmt, args)); }
        public void LogInfo(string fmt, params object[] args) { this.DebugReturn(DebugLevel.INFO, string.Format(fmt, args)); }
        public void LogDebug(string fmt, params object[] args) { this.DebugReturn(DebugLevel.ALL, string.Format(fmt, args)); }

        // send different media type to different channels for efficiency
        internal byte photonChannelForCodec(Codec c)
        {
            return (byte)(1 + Array.IndexOf(Enum.GetValues(typeof(Codec)), c));
        }

        public bool IsChannelJoined(int channelId) { return this.State == ClientState.Joined; }

        /// <summary>
        /// Initializes a new <see cref="LoadBalancingTransport"/>.
        /// </summary>
        /// <param name="logger">ILogger instance. If null, this instance LoadBalancingClient.DebugReturn implementation is used.<see cref="ConnectionProtocol"></see></param>
        /// <param name="connectionProtocol">Connection protocol (UDP or TCP). <see cref="ConnectionProtocol"></see></param>
        public LoadBalancingTransport(ILogger logger = null, ConnectionProtocol connectionProtocol = ConnectionProtocol.Udp) : base(connectionProtocol)
        {
            if (logger == null)
            {
                logger = this;
            }
            base.EventReceived += onEventActionVoiceClient;
            base.StateChanged += onStateChangeVoiceClient;
            this.voiceClient = new VoiceClient(this, logger);
            var voiceChannelsCount = Enum.GetValues(typeof(Codec)).Length + 1; // channel per stream type, channel 0 is for user events
            if (LoadBalancingPeer.ChannelCount < voiceChannelsCount)
            {
                this.LoadBalancingPeer.ChannelCount = (byte)voiceChannelsCount;
            }
            this.protocol = new PhotonTransportProtocol(voiceClient, logger);
        }

        /// <summary>
        /// This method dispatches all available incoming commands and then sends this client's outgoing commands.
        /// Call this method regularly (2 to 20 times a second).
        /// </summary>
        new public void Service()
        {
            base.Service();
            this.voiceClient.Service();
        }

        [Obsolete("Use LoadBalancingPeer::OpChangeGroups().")]
        public virtual bool ChangeAudioGroups(byte[] groupsToRemove, byte[] groupsToAdd)
        {
            return this.LoadBalancingPeer.OpChangeGroups(groupsToRemove, groupsToAdd);
        }

        [Obsolete("Use GlobalInterestGroup.")]
        public byte GlobalAudioGroup
        {
            get { return GlobalInterestGroup; }
            set { GlobalInterestGroup = value; }
        }
        /// <summary>
        /// Set global interest group for this client. This call sets InterestGroup for existing local voices and for created later to given value.
        /// Client set as listening to this group only until LoadBalancingPeer.OpChangeGroups() called. This method can be called any time.
        /// </summary>
        /// <see cref="LocalVoice.InterestGroup"/>
        /// <see cref="LoadBalancingPeer.OpChangeGroups(byte[], byte[])"/>
        public byte GlobalInterestGroup
        {
            get { return this.voiceClient.GlobalInterestGroup; }
            set
            {
                this.voiceClient.GlobalInterestGroup = value;
                if (this.State == ClientState.Joined)
                {
                    if (this.voiceClient.GlobalInterestGroup != 0)
                    {
                        this.LoadBalancingPeer.OpChangeGroups(new byte[0], new byte[] { this.voiceClient.GlobalInterestGroup });
                    }
                    else
                    {
                        this.LoadBalancingPeer.OpChangeGroups(new byte[0], null);
                    }
                }
            }
        }

        #region nonpublic

        public void SendVoicesInfo(IEnumerable<LocalVoice> voices, int channelId, int targetPlayerId)
        {
            foreach (var codecVoices in voices.GroupBy(v => v.Info.Codec))
            {
                object content = protocol.buildVoicesInfo(codecVoices, true);

                var sendOpt = new SendOptions()
                {
                    Reliability = true,
                    Channel = photonChannelForCodec(codecVoices.Key),
                };

                var opt = new RaiseEventOptions();
                if (targetPlayerId == -1)
                {
                    opt.TargetActors = new int[] { this.LocalPlayer.ActorNumber };
                }
                else if (targetPlayerId != 0)
                {
                    opt.TargetActors = new int[] { targetPlayerId };
                }

                this.OpRaiseEvent(VoiceEvent.Code, content, opt, sendOpt);
            }
        }

        public void SendVoiceRemove(LocalVoice voice, int channelId, int targetPlayerId)
        {
            object content = protocol.buildVoiceRemoveMessage(voice);
            var sendOpt = new SendOptions()
            {
                Reliability = true,
                Channel = photonChannelForCodec(voice.Info.Codec),
            };

            var opt = new RaiseEventOptions();

            if (targetPlayerId == -1)
            {
                opt.TargetActors = new int[] { this.LocalPlayer.ActorNumber };
            }
            else if (targetPlayerId != 0)
            {
                opt.TargetActors = new int[] { targetPlayerId };
            }
            if (voice.DebugEchoMode)
            {
                opt.Receivers = ReceiverGroup.All;
            }

            this.OpRaiseEvent(VoiceEvent.Code, content, opt, sendOpt);
        }

        public virtual void SendFrame(ArraySegment<byte> data, FrameFlags flags, byte evNumber, byte voiceId, int channelId, int targetPlayerId, bool reliable, LocalVoice localVoice)
        {
            object[] content = protocol.buildFrameMessage(voiceId, evNumber, data, flags);

            var sendOpt = new SendOptions()
            {
                Reliability = reliable,
                Channel = photonChannelForCodec(localVoice.Info.Codec),
                Encrypt = localVoice.Encrypt
            };

            var opt = new RaiseEventOptions();
            if (targetPlayerId == -1)
            {
                opt.TargetActors = new int[] { this.LocalPlayer.ActorNumber };
            }
            else if (targetPlayerId != 0)
            {
                opt.TargetActors = new int[] { targetPlayerId };
            }
            if (localVoice.DebugEchoMode)
            {
                opt.Receivers = ReceiverGroup.All;
            }
            opt.InterestGroup = localVoice.InterestGroup;

            this.OpRaiseEvent(VoiceEvent.Code, content, opt, sendOpt);
            while (this.LoadBalancingPeer.SendOutgoingCommands());
        }

        public string ChannelIdStr(int channelId) { return null; }
        public string PlayerIdStr(int playerId) { return null; }

        protected virtual void onEventActionVoiceClient(EventData ev)
        {
            // check for voice event first
            if (ev.Code == VoiceEvent.Code)
            {
                // Payloads are arrays. If first array element is 0 than next is event subcode. Otherwise, the event is data frame with voiceId in 1st element.
                protocol.onVoiceEvent(ev[(byte)ParameterCode.CustomEventContent], VOICE_CHANNEL, ev.Sender, ev.Sender == this.LocalPlayer.ActorNumber);
            }
            else
            {
                int playerId;
                switch (ev.Code)
                {
                    case (byte)EventCode.Join:
                        playerId = ev.Sender;
                        if (playerId == this.LocalPlayer.ActorNumber)
                        {
                        }
                        else
                        {
                            this.voiceClient.onPlayerJoin(VOICE_CHANNEL, playerId);
                        }
                        break;
                    case (byte)EventCode.Leave:
                        {
                            playerId = ev.Sender;
                            if (playerId == this.LocalPlayer.ActorNumber)
                            {
                                this.voiceClient.onLeaveAllChannels();
                            }
                            else
                            {
                                this.voiceClient.onPlayerLeave(VOICE_CHANNEL, playerId);
                            }
                        }
                        break;
                }
            }
        }

        void onStateChangeVoiceClient(ClientState fromState, ClientState state)
        {
            switch (fromState)
            {
                case ClientState.Joined:
                    this.voiceClient.onLeaveChannel(VOICE_CHANNEL);
                    break;
            }

            switch (state)
            {
                case ClientState.Joined:
                    this.voiceClient.onJoinChannel(VOICE_CHANNEL);
                    if (this.voiceClient.GlobalInterestGroup != 0)
                    {
                        this.LoadBalancingPeer.OpChangeGroups(new byte[0], new byte[] { this.voiceClient.GlobalInterestGroup });
                    }
                    break;
            }
        }

        #endregion

        /// <summary>
        /// Releases all resources used by the <see cref="LoadBalancingTransport"/> instance.
        /// </summary>
        public void Dispose()
        {
            this.voiceClient.Dispose();
        }
    }
}


text:
from multiprocessing import Pool
from datetime import datetime, timedelta
import urllib2, socket, time, os, commands
from urllib2 import HTTPError, URLError

numOfProcesses = 10  # be careful with this value on production systems
timeOutForQuery = 300  # in seconds

# monHost = 'aipanda100.cern.ch'
# monPort = '8001'

# monHost = 'localhost'
# monPort = '10001'

# monHost = 'bigpanda.cern.ch'
# monHost = 'aipanda022.cern.ch'
# monPort = '80'

if "PANDAMON_HOST" in os.environ:
    monHost = os.environ['PANDAMON_HOST']

if "PANDAMON_PORT" in os.environ:
    monPort = os.environ['PANDAMON_PORT']

monURL = 'http://%s:%s' % (monHost, monPort)

tests = [
    {'url': '/', 'isJSON': False},
    {'url': '/job?pandaid=2424153059&timestamp=1', 'isJSON': False},
    {'url': '/workingGroups/?timestamp=1', 'isJSON': False},
    {'url': '/jobs/?display_limit=100&limit=100&timestamp=1', 'isJSON': False},
    {'url': '/jobs/?jobtype=analysis&timestamp=1&display_limit=100&limit=100', 'isJSON': False},
    {'url' :'/tasks/?eventservice=1&display_limit=100&limit=100', 'isJSON': False},
    {'url': '/task/10593330/?timestamp=1', 'isJSON': False},
    {'url': '/task/10569749/?timestamp=1', 'isJSON': False},
    {'url': '/errors/?sortby=count&limit=100&timestamp=1', 'isJSON': False},
    {'url': '/errors/?computingsite=UKI-SCOTGRID-DURHAM_SL6&timestamp=1&produsername=gangarbt&jobstatus=failed|holding&piloterrorcode=1099&hours=12&display_limit=100&limit=100',
        'isJSON': False},
    {'url': '/user/simon%20head/?display_limit=100&timestamp=1&limit=100', 'isJSON': False},
    {'url': '/sites/?cloud=CA&timestamp=1', 'isJSON': False},
    {'url': '/workQueues/?timestamp=1', 'isJSON': False},
    {'url': '/incidents/?timestamp=1', 'isJSON': False},
    {'url': '/logger/?timestamp=1', 'isJSON': False},
    {'url': '/?mode=quicksearch&timestamp=1', 'isJSON': False},
    {'url': '/wns/ANALY_SFU/?timestamp=1', 'isJSON': False},
    {'url': '/jobs/?cloud=All&jobtype=analysis&hours=1&jobtype=analysis&display_limit=100&limit=100&timestamp=1',
     'isJSON': False},
    {'url': '/jobs/?display_limit=100&jobstatus=failed&transexitcode=6&display_limit=100&specialhandling=ddm:rucio&timestamp=1',
        'isJSON': False},
    {'url': '/job?pandaid=3205354738&timestamp=1', 'isJSON': False},
    {'url': '/tasks/?parent_tid=10568751&display_limit=100&timestamp=1', 'isJSON': False},
    {'url': '/runningdpdprodtasks/?timestamp=1', 'isJSON': False},
    {'url': '/jobs/?jobname=3cc1b8b7-094c-4de8-aca6-007344563ded_63147&taskid=None&sortby=attemptnr&timestamp=1',
     'isJSON': False},
    {'url': '/user/gangarbt/?display_limit=100&limit=100&timestamp=1', 'isJSON': False},
    {'url': '/jobs/?jeditaskid=10514057&eventservice=not2&display_limit=100&timestamp=1', 'isJSON': False},
    {'url': '/jobs/?jeditaskid=10514057&eventservice=not2&display_limit=100&jobstatus=failed&taskbuffererrorcode=114&display_limit=100&timestamp=1',
        'isJSON': False},
    {'url': '/incidents/?timestamp=1', 'isJSON': False},
    {'url': '/incidents/?type=queuecontrol&timestamp=1', 'isJSON': False},
    {'url': '/incidents/?site=ITEP_MCORE&timestamp=1', 'isJSON': False},
    {'url': '/jobs/?jobtype=test&display_limit=100&jobstatus=failed&exeerrorcode=65&display_limit=100&timestamp=1',
     'isJSON': False},
    {'url': '/incidents/?site=ITEP_MCORE&timestamp=1', 'isJSON': False},
    {'url': '/taskprofileplot/?jeditaskid=10557536&timestamp=1', 'isJSON': False},
    {'url': '/datasetList/?containername=data16_13TeV.00309375.physics_Main.merge.DAOD_HIGG2D1.f749_m1684_p2950&timestamp=1',
        'isJSON': False},
    {'url': '/fileInfo/?lfn=group.det-muon.10505609.EXT0._000009.HITS.pool.root&scope=group.det-muon&timestamp=1',
     'isJSON': False},
    {'url': '/eslogger/?timestamp=1', 'isJSON': False},
    {'url': '/jobs/?jobtype=groupproduction&display_limit=100&computingsite=AGLT2_LMEM&timestamp=1', 'isJSON': False}
]

extendedtests = [
    {'url': '/jobs/?jobparam=*14_13TeV*|14_15TeV&timestamp=1', 'isJSON': False},
    {'url': '/jobs/?jobparam=*14_13TeV*|14_15TeV&timestamp=1', 'isJSON': True},
    {'url': '/jobs/?jeditaskid=4862100&timestamp=1', 'isJSON': True},
    {'url': '/tasks/?taskname=mc12_8TeV.227851.MadGraphPythia_AUET2B_CTEQ6L1_pMSSM_QCD_381934528_METFilter.merge.e3470_a220_a263_a264_r4540_p1328&timestamp=1',
        'isJSON': True},
    {'url': '/task/?jeditaskid=1592496&timestamp=1', 'isJSON': True},
    {'url': '/dp/?timestamp=1', 'isJSON': False},
    {'url': '/status_summary/?timestamp=1', 'isJSON': False},
    {'url': '/dash/analysis/?timestamp=1', 'isJSON': False},
    {'url': '/runningmcprodtasks/?timestamp=1', 'isJSON': False},
    {'url': '/jobs/?cloud=&jobtype=analysis&hours=3&jobtype=analysis&mismatchedcloudsite=true&display_limit=100&atlasrelease=Atlas-17.7.3&timestamp=1',
        'isJSON': False},
    {'url': '/jobs/?cloud=&jobtype=analysis&hours=3&jobtype=analysis&mismatchedcloudsite=true&display_limit=100&atlasrelease=Atlas-17.7.3&atlasrelease=Atlas-17.7.3&atlasrelease=Atlas-17.7.3&timestamp=1',
        'isJSON': False},
    {'url': '/user/atlas-dpd-production/?display_limit=100&limit=100&timestamp=1', 'isJSON': False}
]

# tests = tests + extendedtests

def runTest(x):
    urlToTest = monURL + tests[x]['url']
    passed = False
    print "Testing %s...  %s" % (datetime.today().strftime("%Y-%m-%d %H:%M:%S %Z"), urlToTest)
    if (tests[x]['isJSON'] == False):
        headers = {'Accept': 'text/html'}
    else:
        headers = {'Accept': 'application/json'}
    req = urllib2.Request(urlToTest, headers=headers)
    starttime = time.time()
    testResult = {}
    testResult['url'] = urlToTest
    try:
        result = urllib2.urlopen(req, timeout=timeOutForQuery)
    except socket.timeout as e:
        testResult['status'] = -1
    except HTTPError as e:
        testResult['status'] = e.code
    except URLError as e:
        testResult['status'] = e.reason
    else:
        testResult['status'] = result.getcode()
    endtime = time.time()
    testResult['timeToPerform'] = endtime - starttime
    return testResult

if __name__ == '__main__':
    pool = Pool(processes=numOfProcesses)
    #    result = pool.apply_async(runTest, range(len(tests)))
    outputList = pool.map(runTest, range(len(tests)))
    print "\nTest result:"
    countErrors = 0;
    for outout in outputList:
        if (outout['status'] != 200):
            print outout['url'] + " failed with status " + str(outout['status'])
            countErrors += 1
    print 'All tests passed' if countErrors == 0 else ' -1 status means exceding time limit'
    print "\nTop 10 of the heaviest queries:"
    outputList = sorted(outputList, key=lambda x: -x['timeToPerform'], reverse=False)
    for outout in outputList[0:9]:
        print outout['url'] + ' : ' + str(int(outout['timeToPerform'])) + ' sec'


text:
'use strict';
var _ = require('lodash');
var valueFactory = require('../factory/value.js');
var Base = require('./Base');

var ArrayExpression = module.exports = Base.extend({
  initialize: function () {
    this.type = 'ArrayExpression';
  },

  /**
   * push a new value in the array
   * @param  {String} arg New value as a string
   * @return {this}
   */
  push: function (arg) {
    arg = valueFactory.create(arg);
    this.nodes.forEach(function (node) {
      node.elements.push(arg);
    });
    return this;
  },

  /**
   * unshift a new value in the array
   * @param  {String} arg New value as a string
   * @return {this}
   */
  unshift: function (arg) {
    arg = valueFactory.create(arg);
    this.nodes.forEach(function (node) {
      node.elements.unshift(arg);
    });
    return this;
  },

  /**
   * Return the value at given index (only target the first node occurence)
   * @param  {Number}  index
   * @return {Literal} Value reference as a literal type
   */
  at: function (index) {
    return valueFactory.wrap(this.nodes[0].elements[index]);
  },

  /**
   * Replace node with new value
   * @param {String} value
   * @return this
   */
  value: function (value) {
    var val = valueFactory.create(value);
    this.nodes.forEach(function (node) {
      delete node.type;
      delete node.elements;
      _.extend(node, val);
    });
    return valueFactory.wrap(this.nodes[0]);
  }

});


text:
require "sqlite3"

class Eventify::Database
  PATH = File.expand_path(File.join(ENV["HOME"], "/.eventify/events.sqlite3"))

  class << self
    def exists?(event)
      results = sqlite.execute "select 1 from event where id=? and provider=? and link=?", event.id, event.provider, event.link
      !results.empty?
    end

    def save(event)
      sqlite.execute "insert into event values(?, ?, ?, ?, ?)",
        event.id,
        event.provider,
        event.title,
        event.link,
        event.date.to_s
    end

    def events
      translated_events = []
      sqlite.execute("select * from event") do |event|
        translated_events << const_get(event["provider"]).new(
          id: event["id"],
          title: event["title"],
          link: event["link"],
          date: Time.parse(event["date"])
        )
      end

      translated_events
    end

    private

    def sqlite
      @sqlite ||= begin
                    FileUtils.mkdir_p File.dirname(PATH)
                    database = SQLite3::Database.new PATH
                    database.results_as_hash = true

                    database.execute "create table if not exists event(
                      id text,
                      provider text,
                      title text,
                      link text,
                      date text,
                      primary key (id, provider, link)
                    )"

                    database
                  end
    end
  end
end