text:
require 'spec_helper'

describe Wukong::Local::StdioDriver do
  before { EM.stub(:stop) }

  let(:driver) { Wukong::Local::StdioDriver.new(:bogus_event_machine_inserted_arg, :identity, {}) }

  it "attaches itself as an EventMachine handler for $stdin, providing the given label and settings" do
    EM.should_receive(:attach).with($stdin, Wukong::Local::StdioDriver, :foo, {})
    Wukong::Local::StdioDriver.start(:foo, {})
  end

  describe "setting up a dataflow" do
    context "#post_init hook from EventMachine" do
      after { driver.post_init }

      it "sets signal traps for INT and TERM" do
        Signal.should_receive(:trap).with('INT').at_least(:once)
        Signal.should_receive(:trap).with('TERM').at_least(:once)
      end

      it "calls the #setup_dataflow method" do
        driver.should_receive(:setup_dataflow).at_least(:once)
      end

      it "syncs $stdout" do
        $stdout.should_receive(:sync).at_least(:once)
      end

    end
  end

  describe "driving a dataflow" do
    context "#receive_line hook from EventMachine" do
      let(:line) { "hello" }

      after  { driver.receive_line(line) }
      it "passes the line to the #send_through_dataflow method" do
        driver.should_receive(:send_through_dataflow).with(line)
      end

      context "upon an error within the dataflow" do
        let(:message) { "whoops" }

        before do
          driver.should_receive(:send_through_dataflow).with(line) do
            raise Wukong::Error.new(message)
          end
          driver.log.stub(:error)
        end

        it "logs an error message" do
          driver.log.should_receive(:error).with(kind_of(String))
        end
      end
    end
  end

  describe "shutting down a dataflow" do
    context "#unbind hook from EventMachine" do
      after { driver.unbind }

      it "calls the #finalize_and_stop_dataflow method" do
        driver.should_receive(:finalize_and_stop_dataflow)
      end

      it "stops the EventMachine reactor" do
        EM.should_receive(:stop)
      end

    end
  end
end


text:
/*
 * @fileOverview
 * @author: Mike Grabowski (@grabbou)
 */

'use strict';

var Blueprint = require('../../lib/models/blueprint');
var File = require('../../lib/models/file');
var Promise = require('bluebird');
var camelCase = require('camel-case');
var path = require('path');
var fs = require('fs');

module.exports = {

  // This blueprint only ensures actions file exists, so skip by default
  skipExistingFiles: true,

  // Additional optional argument
  args: [{
    type: String,
    name: 'action',
    property: 'blueprintAction'
  }],

  description: 'Generates new action',

  afterInstall: function(options) {

    // No action specified, skip adding it
    if (!options.blueprintAction) return;

    var blueprintAction = camelCase(options.blueprintAction);
    var actionPath = path.join(options.rootFolder, options.blueprintName, 'actions.js');
    var file = File.load(actionPath);

    if (!file.hasVariableInScope('dispatch')) {
      return Promise.reject('You must import dispatch method from a dispatcher');
    }

    var setToString = file.getMethodByInvocation('setToString');

    if (!setToString) {
      return Promise.reject('Couldn\'t find `setToString` method. Make sure it exists');
    }

    if (!file.getFunctionDeclaration(blueprintAction)) {
      var functionDeclaration = [
        '',
        'export function ' + blueprintAction + '() {',
        '  dispatch(' + blueprintAction + ');',
        '}'
      ];
      file.prependCode(setToString, functionDeclaration.join('\n'));
    }

    var definedStrings = file.getObjectExpression(setToString);

    if (!definedStrings.hasProperty(blueprintAction)) {
      definedStrings.addProperty(blueprintAction, true);
    }

    return new Promise
      .fromNode(function(callback) {
        fs.writeFile(actionPath, file.print(), callback);
      })
      .then(function() {
        return Blueprint.load('store-action').install(options);
      });
  }
};

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Threading;
using Nancy.Hosting.Self;
using System.Linq;

namespace NancyDemo
{
	class Program
	{
		static void Main(string[] args)
		{
			var uri = "http://localhost:8888";
			var host = new NancyHost(new Uri(uri));
			Console.WriteLine ("Starting on port 8888");
			host.Start();  // start hosting
			Console.WriteLine ("started!");
				Thread.Sleep(Timeout.Infinite);
			Console.WriteLine ("Shutting down...");
			host.Stop();  // stop hosting
			Console.WriteLine ("done");
		}
	}
}


text:
/**
* LibroDetailController
* Controlador de la ficha del libro
* $scope - ámbito
* $http -
* $routeParams - parámetros de la ruta
*/
function LibroDetailController($scope, $http, $routeParams) {
  $scope.id = $routeParams.libroId;

  $http.get('data/libro'+$scope.id+'.json').success(function(data) {
	  $scope.libro = data[0];
  });

}


text:
//////////////////////////////////////////////////////////////////////////
// Copyright 2001-2015 Aspose Pty Ltd. All Rights Reserved.
//
// This file is part of Aspose.Email. The source code in this file
// is only intended as a supplement to the documentation, and is provided
// "as is", without warranty of any kind, either expressed or implied.
//////////////////////////////////////////////////////////////////////////

using System.IO;
using System;
using Aspose.Email;
using Aspose.Email.Outlook.Pst;

namespace CSharp.Outlook
{
    class NewPSTAddSubfolders
    {
        public static void Run()
        {
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_Outlook();
            string dst = dataDir + "PersonalStorage.pst";

            if (File.Exists(dst))
                File.Delete(dst);

            // Create new PST
            PersonalStorage pst = PersonalStorage.Create(dst, FileFormatVersion.Unicode);

            // Add new folder "Inbox"
            pst.RootFolder.AddSubFolder("Inbox");

            Console.WriteLine(Environment.NewLine + "PST saved successfully at " + dst);
        }
    }
}


text:
package accrue.cryptoerase.ast;

import polyglot.ast.JLDel_c;
import polyglot.ast.Node;
import polyglot.types.SemanticException;
import polyglot.visit.TypeChecker;

public class CEAssignDel extends JLDel_c {

	@Override
	public Node typeCheck(TypeChecker tc) throws SemanticException {
		return CEExt_c.ext(node()).typeCheck(tc);
	}

}


text:
{% load static %}
<!DOCTYPE html>

    <title>{{ user_name }} - DistribSystem</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="{% static 'userroles/css/bootstrap.min.css' %}" rel="stylesheet" type="text/css">
    <link rel="stylesheet" type="text/css" href="{% static 'userroles/css/style.css' %}">

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-targer="#topNavBar">

          </button>
          Добро пожаловать, {{ user_name }} {{ user_surname }}!

              Мой профиль

          <form class="navbar-form navbar-right" action="{% url 'userroles:logout' %}">
            <button class="btn btn-primary" type="submit">Выйти</button>
          </form>

            {% if is_student %}
              {% include "accounts/parts/menus/student_menu.html" %}
            {% endif %}

            {% if is_professor %}
              {% include "accounts/parts/menus/professor_menu.html" %}
            {% endif %}

            {% if is_cooperator %}
              {% include "accounts/parts/menus/cooperator_menu.html" %}
            {% endif %}

            {% if is_sci_director %}
              {% include "accounts/parts/menus/sci_dir_menu.html" %}
            {% endif %}

Домашняя

          {% block content %}
          {% endblock %}

DistribSystem Team (c) 2017


text:
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static

urlpatterns = patterns(
    '',
    url(r'^', include('frontend.urls')),

    url(r'^', include('iconpacks.urls')),
    url(r'^', include('iconcollections.urls')),
    url(r'^', include('revisions.urls')),
    url(r'^', include('labels.urls')),

    url(r'^', include('fontbuilder.urls')),

    url(r'^convert/', include('convert.urls')),
    url(r'^accounts/', include('accounts.urls')),
)

if settings.DEBUG:
    urlpatterns += static(
        settings.STATIC_URL,
        document_root=settings.STATIC_ROOT
    )


text:
<?php
declare(strict_types=1);

namespace Genkgo\Xsl;

use DOMDocument;
use Genkgo\Xsl\Callback\FunctionCollection;
use Genkgo\Xsl\Util\TransformerCollection;

final class TransformationContext
{
    /**
     * @var DOMDocument
     */
    private $document;

    /**
     * @var array|null
     */
    private $phpFunctions;

    /**
     * @var TransformerCollection
     */
    private $transformers;

    /**
     * @var FunctionCollection
     */
    private $functions;

    /**
     * @param DOMDocument $document
     * @param TransformerCollection $transformers
     * @param FunctionCollection $functions
     * @param array|null $phpFunctions
     */
    public function __construct(
        DOMDocument $document,
        TransformerCollection $transformers,
        FunctionCollection $functions,
        array $phpFunctions = null
    ) {
        $this->document = $document;
        $this->transformers = $transformers;
        $this->functions = $functions;
        $this->phpFunctions = $phpFunctions;
    }

    /**
     * @return DOMDocument
     */
    public function getDocument()
    {
        return $this->document;
    }

    /**
     * @return array|null
     */
    public function getPhpFunctions()
    {
        return $this->phpFunctions;
    }

    /**
     * @return FunctionCollection
     */
    public function getFunctions()
    {
        return $this->functions;
    }

    /**
     * @return TransformerCollection|TransformerInterface[]
     */
    public function getTransformers()
    {
        return $this->transformers;
    }
}


text:
package se.sawano.java.security.otp.google.keyuri;

import static org.apache.commons.lang3.Validate.notNull;

/**
 * An encoder that performs URI encoding, aka percent-encoding. See also RFC
 * 3986.
 */
public class UriEncoder {

    /**
     * Unreserved characters as per RFC 3986. [A-Za-z0-9] are already excluded by the PercentEscaper.
     */
    private static final String UNRESERVED_CHARACTERS = "-._~";

    /**
     * Encodes the given string.
     *
     * @param value
     *         the string to encode
     *
     * @return the URI encoded string
     */
    public static String encode(final String value) {
        notNull(value);

        return new PercentEscaper(UNRESERVED_CHARACTERS, false).escape(value);
    }
}


text:
''' A collection of classes and functions for dealing with content.
'''

from json import dumps

class Content:
    ''' A class that represents a piece of content in the foldr network.
    '''

    def __init__(self, id, date, title, link, content, tags):
        self.id = str(id)
        self.date = str(date)
        self.title = title
        self.link = link
        self.content = content
        self.tags = list(tags)

    def to_json_dict(self):
        ''' Convert the content to its JSON dict representation.
        '''

        return {
            'id': self.id,
            'date': self.date,
            'title': self.title,
            'link': self.link,
            'content': self.content,
            'tags': self.tags
        }

    def to_json_string(self):
        ''' Convert the content to its JSON string representation.
        '''

        return dumps(self.to_json_dict())


text:
title: Digimon Rumble Arena - Colaboración
permalink: /digimon-rumble-arena-colaboracion/
header:
  overlay_image: /img/headers/pages/DigimonRumbleArenaHeader.jpg
comments: false
---
Proyecto de retraducción y doblaje de Digimon Rumble Arena para PlayStation One, dirigido por
**[Estudios G3S](http://www.estudiosg3s.com/){:target="_blank"}**.

Esta traducción está basada en la versión NTSC-U del juego (Hay intención de publicar un parche
para la versión europea) y respeta todos los términos de la saga original, además de incluir las
canciones originales de la serie. Actualmente el doblaje está acabado e insertado, pero la
traducción es parcial por problemas de romhacking.

Su primera versión se publicó el 30 de marzo de 2018.

**EQUIPO DE TRADUCCIÓN DE DIGIMON RUMBLE ARENA**
**Equipo técnico**

**Organización** – Jesús Valle
**Idea y material** – Traducciones DarkchaosTraducción – Ilducci, Carls López, Skads7
**Programación e inserción** – Ilducci, Jesús Valle, Carls López
**Traducción de gráficos** – Skads7, Carls López, Ilducci
**Asistencia Técnica** – Ilducci

**Equipo de doblaje**

**Dirección de doblaje** – Jesús Valle
**Iván Durán** – BEELZEMON/SERAPHIMON
**Chemichi Von Alexandros** – MATT/VEEMON/GUILMON/BLACKWARGREYMON
**Maka Evans** – CALUMON
**Isaac Martín** – DAVIS
**Jesús Valle** – AGUMON/KEN/DIGIMON EMPERADOR/MEGAGARGOMON
**Javi G. Díaz** – GABUMON
**Paul Dubber** – GALLANTMON/IMPMON/METALGARURUMON
**Nicole Rodríguez** – GATOMON/COMENTARISTA
**Emilio Fernández** – HENRY
**Oni Belfi** – IMPERIALDRAMON/OMNIMON/WARGREYMON
**Andrea Serrano** – KARI
**Sara Troyano** – MAGNADRAMON/TK
**Carol Rodríguez** – PATAMON
**Pablo Chico** – REAPERMON
**Noelia De Luis** – RENAMON/SAKUYAMON/RIKA/TAKATO
**Mike Wazowski** – STINGMON
**Andromeda Studio Dubs** – TAI/TERRIERMON
**Víctor González** – WORMMON

Podéis saber más **[pulsando en este enlace](http://www.estudiosg3s.com/digimon-rumble-arena-lanzamiento/){:target="_blank"}**.

Mi trabajo consistió en ayudar en la traducción de textos y gráficos, así como en enseñar a G3S
cómo se inyectan sonidos en esta consola.

{% include video id="fcvRKrjaivk" provider="youtube" %}


text:
iDevJS

编辑话题

        <post-editor class="block-card" [post]="post" *ngIf="post" (submitPost)="onSubmitPost($event)"></post-editor>


text:
package org.esupportail.cas.adaptors.esupotp.web.flow;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.trusted.web.flow.AbstractMultifactorTrustedDeviceWebflowConfigurer;
import org.apereo.cas.trusted.web.flow.MultifactorAuthenticationTrustBean;
import org.apereo.cas.web.flow.CasWebflowConstants;
import org.apereo.cas.web.flow.configurer.CasMultifactorWebflowCustomizer;
import org.apereo.cas.web.support.WebUtils;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.webflow.definition.registry.FlowDefinitionRegistry;
import org.springframework.webflow.engine.Flow;
import org.springframework.webflow.engine.builder.support.FlowBuilderServices;

import lombok.val;

public class EsupOtpMultifactorTrustWebflowConfigurer extends AbstractMultifactorTrustedDeviceWebflowConfigurer {

	private Boolean isDeviceRegistrationRequired = false;

    private final FlowDefinitionRegistry flowDefinitionRegistry;

    public EsupOtpMultifactorTrustWebflowConfigurer(final FlowBuilderServices flowBuilderServices,
                                                      final FlowDefinitionRegistry loginFlowDefinitionRegistry,
                                                      final boolean isDeviceRegistrationRequired,
                                                      final FlowDefinitionRegistry flowDefinitionRegistry,
                                                      final ConfigurableApplicationContext applicationContext,
                                                      final CasConfigurationProperties casProperties,
                                                      final List<CasMultifactorWebflowCustomizer> mfaFlowCustomizers) {
        super(flowBuilderServices, loginFlowDefinitionRegistry, applicationContext, casProperties, Optional.of(flowDefinitionRegistry), mfaFlowCustomizers);
        this.flowDefinitionRegistry = flowDefinitionRegistry;
        this.isDeviceRegistrationRequired = isDeviceRegistrationRequired;
    }

    @Override
    protected void doInitialize() {
        if(!isDeviceRegistrationRequired) {
            // Hack : override register trusted device flow AbstractMultifactorTrustedDeviceWebflowConfigurer.registerMultifactorTrustedAuthentication
            // -> with this, we auto register device (without form) if isDeviceRegistrationRequired=false
            val flowId = Arrays.stream(flowDefinitionRegistry.getFlowDefinitionIds()).findFirst().get();
            val flow = (Flow) flowDefinitionRegistry.getFlowDefinition(flowId);
            val registerAction = createActionState(flow, CasWebflowConstants.STATE_ID_PREPARE_REGISTER_TRUSTED_DEVICE, "mfaSetTrustAction");
            createStateDefaultTransition(registerAction, CasWebflowConstants.STATE_ID_SUCCESS);
            flow.getStartActionList().add(requestContext -> {
	        	val deviceBean = WebUtils.getMultifactorAuthenticationTrustRecord(requestContext, MultifactorAuthenticationTrustBean.class);
	            val deviceRecord = deviceBean.get();
	            deviceRecord.setDeviceName("auto-device-registration");
	            return null;
	        });
        }
        registerMultifactorTrustedAuthentication();
    }

}


text:
"""Main Controller"""
import logging, string, os
from datetime import datetime
from collections import defaultdict

import pkg_resources
from tg import expose, flash, redirect, session, config, response, request, config
from tg.decorators import with_trailing_slash, without_trailing_slash
from tg.flash import TGFlash
from pylons import c, g, cache

import ew
import ming

import allura
from allura.app import SitemapEntry
from allura.lib.base import WsgiDispatchController
from allura.lib import helpers as h
from allura.lib import plugin
from allura.controllers.error import ErrorController
from allura import model as M
from allura.lib.widgets import project_list as plw
from .auth import AuthController
from .search import SearchController, ProjectBrowseController
from .static import NewForgeController
from .site_admin import SiteAdminController
from .project import NeighborhoodController, HostNeighborhoodController
from .rest import RestController

__all__ = ['RootController']

log = logging.getLogger(__name__)

TGFlash.static_template = '''$('#messages').notify('%(message)s', {status: '%(status)s'});'''

class W:
    project_summary = plw.ProjectSummary()

class RootController(WsgiDispatchController):
    """
    The root controller for the allura application.

    All the other controllers and WSGI applications should be mounted on this
    controller. For example::

        panel = ControlPanelController()
        another_app = AnotherWSGIApplication()

    Keep in mind that WSGI applications shouldn't be mounted directly: They
    must be wrapped around with :class:`tg.controllers.WSGIAppController`.

    """

    auth = AuthController()
    error = ErrorController()
    nf = NewForgeController()
    nf.admin = SiteAdminController()
    search = SearchController()
    rest = RestController()

    def __init__(self):
        n_url_prefix = '/%s/' % request.path.split('/')[1]
        n = M.Neighborhood.query.get(url_prefix=n_url_prefix)
        if n and not n.url_prefix.startswith('//'):
            n.bind_controller(self)
        self.browse = ProjectBrowseController()
        self.allura_sitemap = SitemapIndexController()
        super(RootController, self).__init__()

    def _setup_request(self):
        c.project = c.app = None
        c.memoize_cache = {}
        c.user = plugin.AuthenticationProvider.get(request).authenticate_request()
        assert c.user is not None, 'c.user should always be at least User.anonymous()'

    def _cleanup_request(self):
        pass

    @expose('jinja:allura:templates/project_list.html')
    @with_trailing_slash
    def index(self, **kw):
        """Handle the front-page."""
        c.project_summary = W.project_summary
        projects = M.Project.query.find(
            dict(is_root=True,
                 is_nbhd_project=False,
                 deleted=False)).sort('shortname').all()
        neighborhoods = M.Neighborhood.query.find().sort('name')
        psort = [ (n, [ p for p in projects if p.neighborhood_id==n._id ])
                  for n in neighborhoods ]
        categories = M.ProjectCategory.query.find({'parent_id':None}).sort('name').all()
        c.custom_sidebar_menu = [
            SitemapEntry(cat.label, '/browse/'+cat.name) for cat in categories
        ]
        return dict(projects=psort,title="All Projects",text=None)

class SitemapIndexController(object):
    projects_per_page = 1000

    @expose('jinja:allura:templates/sitemap_index.xml')
    def index(self, **kw):
        base_url = config.get('base_url', 'sourceforge.net')
        num_projects = M.Project.query.find().count()
        now = datetime.utcnow().date()
        return dict(
            now=now,
            sitemaps = [
                '%s/sitemap/%d' % (base_url, offset)
                for offset in range(0, num_projects, self.projects_per_page) ])

    @expose()
    def _lookup(self, offset, *remainder):
        return SitemapController(int(offset), self.projects_per_page), remainder

class SitemapController(object):

    def __init__(self, offset, limit):
        self.offset, self.limit = offset, limit

    @expose('jinja:allura:templates/sitemap.xml')
    def index(self, **kw):
        now = datetime.utcnow().date()
        base_url = config.get('base_url', 'sourceforge.net')
        locs = []
        for p in M.Project.query.find().skip(self.offset).limit(self.limit):
            c.project = p
            locs += [  base_url + s.url
                       for s in p.sitemap() ]
        return dict(
            now=now,
            locs=locs)


text:
module Location
	class V2 < Grape::API
	format :json

		helpers NCU::OAuth::Helpers

		helpers do
			def request
				@request ||= ::Rack::Request.new(env)
			end
			def error! message, error_code
				V2.logger.error "{:path=>#{request.path}, :params=>#{request.params.to_hash}, :method=>#{request.request_method}, :message=>#{message}, :status=>#{error_code}}"
				super message, error_code
			end
			def find_token scope
				this_token = token scope
				error! this_token[:error_message], this_token[:error_code] if this_token.has_key? :error_message
				this_token
			end
			def check_api_token
				error! 'api_token is missing', 400 unless headers.key?('X-Ncu-Api-Token')
				RestClient.get Settings::OAUTH_API_TOKEN_URL + headers['X-Ncu-Api-Token'] + '?ip=' + env['REMOTE_ADDR'], {x_ncu_api_token: Settings::NCU_API_TOKEN} do |response, request, result, &block|
					if response.code == 200
						res = JSON.parse response.body
						return
					end
					error! 'invalid_token', 401
				end
			end
		end

		rescue_from RuntimeError do |e|
			V2.logger.error e
			error! 'server_error', 500
		end

		before do
			unless request.path.start_with? '/location/v2/doc'
				case request.request_method
				when 'GET'
					#scope = NCU::OAuth::API_TOKEN
					check_api_token
				else
					scope = NCU::OAuth::PERSONNEL_INFO_READ
					@this_token = find_token scope
				end
			end
			header 'Content-Type', 'application/json;charset=UTF-8'
		end

		desc 'Returns places.' do
			success Location::Entities::Places
			headers "X-NCU-API-TOKEN":{
				description: 'your API token',
				required: true
			}
		end
		params do
			optional :limit, type: Integer, default: 5, desc: 'Maximum number of places returned on one result page. (Default: 5)'
			optional :page, type: Integer, default: 1, desc: 'Which result page to return. (Default: 1)'
			optional :startLat, type:Float, values: -90.0..+90.0, default: nil, desc: ''
			optional :startLng, type:Float, values: -180.0..+180.0, default: nil, desc: ''
			optional :endLat, type:Float, values: -90.0..+90.0, default: nil, desc: ''
			optional :endLng, type:Float, values: -180.0..+180.0, default: nil, desc: ''
			optional :chineseName, type: String, default: nil, desc: ''
			optional :englishName, type: String, default: nil, desc: ''
			optional :type, type: String, default: nil, desc: ''
			optional :tag, type: String, default: nil, desc: ''
		end
		get :places do
			if !params[:tag].nil?
				tags = DB::Tag.where(:name => params[:tag])
				place_ids = Array.new
				for tag in tags
					place_ids.push(tag.place_id)
				end
				places = DB::Place.where(:id => place_ids)
			else
				places = DB::Place.all
			end
			places = places.where("lat >= ?", params[:startLat]) unless params[:startLat].nil?
			places = places.where("lng >= ?", params[:startLng]) unless params[:startLng].nil?
			places = places.where("lat <= ?", params[:endLat]) unless params[:endLat].nil?
			places = places.where("lng <= ?", params[:endLng]) unless params[:endLng].nil?
			places = places.where(:cname => params[:chineseName]) unless params[:chineseName].nil?
			places = places.where(:ename => params[:englishName]) unless params[:englishName].nil?
			places = places.where(:catagory => params[:type]) unless params[:catagory].nil?

			places = places.where(:exsist => true)
			places = places.page(params[:page]).per(params[:limit])
			for place in places
				place.tags = DB::Tag.where(:place_id => place.id)
			end

			reps = Location::Entities::Place.represent places
			{places:reps, count:reps.size, page:params[:page]}
		end

		resource :faculties do
			desc 'Find faculty\'s information by his/her Chinese name.' do
				success Location::Entities::Faculties
				headers "X-NCU-API-TOKEN":{
					description: 'your API token',
					required: true
				}
			end
			params do
				requires :cname, type: String, desc:'faculty\'s Chinese name'
			end
			get '/' do
				db_faculties = DB::Faculty.where(:cname => params[:cname])
				reps = Location::Entities::Faculty.represent db_faculties
			end
		end

		resource :units do
			desc 'Find administrative and research units.' do
				success Location::Entities::Units
				headers "X-NCU-API-TOKEN":{
					description: 'your API token',
					required: true
				}
			end
			params do
				optional :fname, type: String, desc:'unit\'s full Chinese name'
				optional :building_cname, type: String, desc:'place\'s full Chinese name'
				mutually_exclusive :fname, :building_cname
			end
			get '/' do
				if !params[:fname].nil?
					db_units = DB::Unit.where(:full_name => params[:fname])
				else
					db_units = DB::Unit.where(:cname => params[:building_cname])
				end
				reps = Location::Entities::Unit.represent db_units
			end
		end

		resource :myFile do
			desc 'upload a file' do
				headers 'Authorization': {
					description: 'Bearer token.',
					required: true
				}
			end
			params do
				requires :file, type: Rack::Multipart::UploadedFile, desc:'desc'
			end
			post '/upload' do
				if params[:file].nil?
					{"result":"file null"}
				else
					image = params[:file]
					#FileUtils.cp File.absolute_path(image.filename), Settings::FILE_STORAGE_PATH
					FileUtils.cp image.tempfile.path, Settings::FILE_STORAGE_PATH + "/" + image.filename
					FileUtils.chmod 0744, Settings::FILE_STORAGE_PATH + "/" + image.filename
					{"filename": Settings::FILE_STORAGE_PATH + "/" + image.filename, "size":image.size}
					#{"filename": File.absolute_path(image.filename), "size":image.size}
					#{"filename": image.tempfile.path, "size":image.size}
				end
			end

			desc 'download a file' do
				headers "X-NCU-API-TOKEN":{
					description: 'your API token',
					required: true
				}
			end
			params do
				requires :filename, type: String, desc:'filename'
			end
			content_type :png, "image/png"
			get '/download' do
				#content_type "application/octet-stream"
				content_type 'image/png'
				#header['Content-Disposition'] = "attachment; filename=files01.png"
				#env['api.format'] = :binary
				#File.binread(File.absolute_path(filename))

				File.binread(Settings::FILE_STORAGE_PATH + "/" + params[:filename])
				#File.binread('/home/u102502005/grapeProjects/Location-Service/files01.png')

				#File.open('/home/u102502005/grapeProjects/Location-Service/files01.png').read
				#file '/home/u102502005/grapeProjects/Location-Service/files01.png'
			end

=begin
			desc 'Upload an image.'
			params do
				optional :image_file, type: File, default: nil, desc: 'Picture of this place, location service would automatically store uploaded picture and generate an URL for the picture, picture URL would be sent in response.'
			end
			post 'avatar' do
				{
					filename: params[:image_file][:filename],
					size: params[:image_file][:tempfile].size
				}
			end

			desc 'Upload and download a file of any format.'
			params do
				optional :file, type: File, default: nil, desc: 'Picture of this place, location service would automatically store uploaded picture and generate an URL for the picture, picture URL would be sent in response.'
			end
			post 'download' do
				filename = params[:file][:filename]
				content_type MIME::Types.type_for(filename)[0].to_s
				env['api.format'] = :binary
				header 'Content-Disposition', "attachment; filename*=UTF-8''#{URI.escape(filename)}"
				params[:file][:tempfile].read
			end
=end
		end

		resource :place do
			desc 'Creates a place.' do
				success Location::Entities::Place
				headers 'Authorization': {
					description: 'Bearer token.',
					required: true
				}
			end
			params do
				requires :chineseName, type: String, desc: 'Chinese name of this place.'
				optional :englishName, type: String, default: '', desc: 'English name of this place.'
				requires :latitude, type: Float, values: -90.0..+90.0, desc: 'latitude of this place.'
				requires :longitude, type: Float, values: -180.0..+180.0, desc: 'longitude of this place.'
				optional :description, type: String, default: '', desc: 'Description of this place.'
				optional :tags, type: Array[JSON], default: '', desc: 'Tags to be added to this place.'
				optional :picture, type: File, default: nil, desc: 'Picture of this place, location service would automatically store uploaded picture and generate an URL for the picture, picture URL would be sent in response.'
				optional :pictureURL, type: String, default: '', desc: 'URL of picture of this place, If the request parameter "picture" is set, this request parameter would be ignored.'
			end
			post do
				db_place = DB::Place.new
				db_place.cname = params[:chineseName]
				db_place.ename = params[:englishName]
				db_place.picture_name = params[:pictureURL]
				db_place.catagory = "WIKI"
				db_place.description = params[:description]
				db_place.portal_id = @this_token['user']
				db_place.exsist = true
				db_place.lat = params[:latitude]
				db_place.lng = params[:longitude]
				db_place.save
				reps = Location::Entities::Place.represent db_place
			end

			desc 'Returns a place.' do
				success Location::Entities::Place
				headers 'X-NCU-API-TOKEN': {
					description: 'Bearer token.',
					required: true
				}
			end
			params do
			end
			get ':id', requirements: { id: /[0-9]*/ } do
				db_place = DB::Place.where(:id => params[:id]).first
				if  db_place == nil || db_place.exsist == false
					error! 'place not found', 404
				end
				db_place.tags = DB::Tag.where(:place_id => params[:id])
				reps = Location::Entities::Place.represent db_place
			end

			desc 'Deletes a place.' do
				success Location::Entities::Place
				headers 'Authorization': {
					description: 'Bearer token.',
					required: true
				}
			end
			params do
			end
			delete ':id', requirements: { id: /[0-9]*/ } do
				db_place = DB::Place.where(:id => params[:id]).first
				db_place.exsist = false
				db_place.save
				db_place.tags = DB::Tag.where(:place_id => params[:id])
				db_place.portal_id = @this_token['user']
				reps = Location::Entities::Place.represent db_place
			end

			desc 'Updates a place.' do
				success Location::Entities::Place
				headers 'Authorization': {
					description: 'Bearer token.',
					required: true
				}
			end
			params do
				optional :chineseName, type: String, default: '', desc: 'Chinese name of this place.'
				optional :englishName, type: String, default: '', desc: 'English name of this place.'
				optional :latitude, type: Float, values: -90.0..+90.0, default: 0, desc: 'latitude of this place.'
				optional :longitude, type: Float, values: -180.0..+180.0, default: 0, desc: 'longitude of this place.'
				optional :description, type: String, default: '', desc: 'Description of this place.'
				optional :picture, type: File, default: nil, desc: 'Picture of this place, location service would automatically store uploaded picture and generate an URL for the picture, picture URL would be sent in response.'
				optional :pictureURL, type: String, default: '', desc: 'URL of picture of this place, If the request parameter "picture" is set, this request parameter would be ignored.'
			end
			put ':id', requirements: { id: /[0-9]*/ } do
				db_place = DB::Place.where(:id => params[:id]).first

				if db_place != nil && db_place.exsist == true
					unless params[:chineseName].nil?
						db_place.cname = params[:chineseName]
					end

					unless params[:englishName].nil?
						db_place.ename = params[:englishName]
					end

					unless params[:pictureURL].nil?
						db_place.picture_name = params[:pictureURL]
					end

					unless params[:description].nil?
						db_place.description = params[:description]
					end

					db_place.portal_id = @this_token['user']

					unless params[:latitude].nil?
						db_place.lat = params[:latitude]
					end

					unless params[:longitude].nil?
						db_place.lng = params[:longitude]
					end

					db_place.save
					db_place.tags = DB::Tag.where(:place_id => params[:id])
					reps = Location::Entities::Place.represent db_place

				else
					error! 'place not found', 404
				end

			end

			desc 'Creates a tag.' do
				success Location::Entities::Place
				headers 'Authorization': {
					description: 'Bearer token.',
					required: true
				}
			end
			params do
				requires :name, type: String, desc: 'Name of this tag.'
			end
			post ':id/tag', requirements: { id: /[0-9]*/ } do
				db_place = DB::Place.where(:id => params[:id]).where(:exsist => true).first
				if db_place == nil
					error! 'place does not exsist', 404
				end

				unless DB::Tag.where(:place_id => params[:id]).where(:exsist => true).where(:name => params[:name]).count > 0
					db_tag = DB::Tag.new
					db_tag.place_id = params[:id]
					db_tag.name = params[:name]
					db_place.portal_id = @this_token['user']
					db_tag.exsist = true
					db_tag.save
				end
				db_place.tags = DB::Tag.where(:place_id => params[:id]).where(:exsist => true)
				reps = Location::Entities::Place.represent db_place
			end

			desc 'Deletes a tag.' do
				success Location::Entities::Place
				headers 'Authorization': {
					description: 'Bearer token.',
					required: true
				}
			end
			params do
				requires :name, type: String, desc: 'Name of the tag to be deleted.'
			end
			delete ':id/tag', requirements: { id: /[0-9]*/ } do
				db_place = DB::Place.where(:id => params[:id]).where(:exsist => true).first
				if db_place == nil
					error! 'place does not exsist', 404
				end

				db_tag = DB::Tag.where(:place_id => params[:id]).where(:exsist => true).where(:name => params[:name]).first
				if db_tag != nil
					db_tag.exsist = false
					db_tag.portal_id = @this_token['user']
					db_tag.save
				end

				db_place.tags = DB::Tag.where(:place_id => db_place.id).where(:exsist => true)
				reps = Location::Entities::Place.represent db_place
			end
		end

		add_swagger_documentation api_version: 'v2',
                                hide_documentation_path: true,
                                hide_format: true,
                                mount_path: '/doc',
                                base_path: "#{Settings::API_URL}/location/v2"

	end
end


text:
readonly PROGNAME=$(basename $0)
readonly PROGDIR="$( cd "$(dirname "$0")" ; pwd -P )"
readonly ARGS="$@"

# pull in utils
source "${PROGDIR}/utils.sh"

# Make sure we have all the right stuff
prerequisites() {
  # we want to be root to install / uninstall
  if [ "$EUID" -ne 0 ]; then
    error "Please run as root"
    exit 1
  fi
}

# Uninstall Terraform
uninstall_terraform() {
  echo ""
  echo "Remove any residual artitfacts from previous installs..."
  rm -rf $DOWNLOADED_FILE

  echo ""
  echo "Removing Terraform executables (incl. plugins)"
  cd "$INSTALL_DIR" || exit 1
  rm -rf terraform*
}

main() {
  # Be unforgiving about errors
  set -euo pipefail
  readonly SELF="$(absolute_path $0)"
  prerequisites
  uninstall_terraform
}

[[ "$0" == "$BASH_SOURCE" ]] && main


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.</groupId>
    <artifactId>feeder</artifactId>
    <version>1.1.0-SNAPSHOT</version>
    <packaging>pom</packaging>

    <name>feeder</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <modules>
        <module>feeder-parent</module>
        <module>feeder-conf</module>
        <module>feeder-core</module>
        <module>feeder-assembly</module>
    </modules>
</project>


text:
var bkjs = require('backendjs');
var db = bkjs.db;
var api = bkjs.api;
var app = bkjs.app;
var core = bkjs.core;
var lib = bkjs.lib;
var logger = bkjs.logger;

db.describeTables({
    // New table
    test: {
        id: { primary: 1 },
        name: {},
        mtime: { type: "now" },
    },
    // Extend users table
    bk_user: {
        test0: { pub: 1 },
    },
});

// Create API endpoints and routes
app.configureWeb = function(options, callback)
{
    db.setProcessRow("post", 'test', this.processTestRow);

    // Add new record
    api.app.all(/^\/test\/add/, function(req, res) {
        db.add('test', { id: req.query.id, name: req.query.name }, function(err, rows) {
            api.sendReply(res, err);
        });
    });
    // Update record
    api.app.all(/^\/test\/update/, function(req, res) {
        if (!req.query.id || !req.query.name) return api.sendRepy(res, { status: 400, message: "id and name required" });

        db.update('test', req.query, function(err, rows) {
            api.sendReply(res, err);
        });
    });
    // Retrieve record by id
    api.app.all(/^\/test\/([0-9]+)/, function(req, res) {
        var options = api.getOptions(req);
        db.get('test', { id: req.params[0] }, options, function(err, rows) {
            api.sendJSON(req, err, rows);
        });
    });
    callback()
};

// A job method that can be called directly from the crontab or via shell
app.processTestJob = function(options, callback)
{
    db.select("test", {}, function(err, rows) {
        if (err) return callback(err);
        console.log("Test contains: ", rows.length, "records")
        callback()
    });
}

// Modify every row returned to the client, we can add/del properties
app.processTestRow = function(req, row, options)
{
    row.url = '/test/list';
    return row;
}

api.registerPostProcess('', /^\/account\/([a-z\/]+)$/, function(req, res, rows) {
    var self = this;
    switch (req.params[0]) {
    case 'add':
       // Perform our own additional work for new accounts, req.account contains new account record
       db.add('test', { id: req.account.id });
       break;
    case 'del':
       db.del('test', { id: req.account.id });
       break;
    }
});

// Redirect on unauthorized access to the files
api.registerPreProcess('', /^\/test\/list$/, function(req, status, callback) {
    if (status.status != 200) {
        status.status = 302;
        status.url = '/public/index.html';
    }
    callback(status);
});

bkjs.server.start();


text:
namespace blink {
#if defined(ENABLE_PEPPER_CDMS)
class WebLocalFrame;
#endif
class WebSecurityOrigin;
}

namespace media {

class CdmContext;
class CdmFactory;
class CdmSessionAdapter;
class WebContentDecryptionModuleSessionImpl;

class MEDIA_EXPORT WebContentDecryptionModuleImpl
    : public blink::WebContentDecryptionModule {
 public:
  static void Create(CdmFactory* cdm_factory,
                     const blink::WebSecurityOrigin& security_origin,
                     const base::string16& key_system,
                     blink::WebContentDecryptionModuleResult result);

  virtual ~WebContentDecryptionModuleImpl();

  // blink::WebContentDecryptionModule implementation.
  virtual blink::WebContentDecryptionModuleSession* createSession();

  virtual void setServerCertificate(
      const uint8* server_certificate,
      size_t server_certificate_length,
      blink::WebContentDecryptionModuleResult result);

  // Returns the CdmContext associated with this CDM, which must not be nullptr.
  // TODO(jrummell): Figure out lifetimes, as WMPI may still use the decryptor
  // after WebContentDecryptionModule is freed. http://crbug.com/330324
  CdmContext* GetCdmContext();

 private:
  // Takes reference to |adapter|.
  WebContentDecryptionModuleImpl(scoped_refptr<CdmSessionAdapter> adapter);

  scoped_refptr<CdmSessionAdapter> adapter_;

  DISALLOW_COPY_AND_ASSIGN(WebContentDecryptionModuleImpl);
};

// Allow typecasting from blink type as this is the only implementation.
inline WebContentDecryptionModuleImpl* ToWebContentDecryptionModuleImpl(
    blink::WebContentDecryptionModule* cdm) {
  return static_cast<WebContentDecryptionModuleImpl*>(cdm);
}

}  // namespace media

#endif  // MEDIA_BLINK_WEBCONTENTDECRYPTIONMODULE_IMPL_H_


text:
/*****************************************************************************/
/*  ERRNO.H  v15.12.3                                                        */
/*                                                                           */
/* Copyright (c) 1995-2016 Texas Instruments Incorporated                    */
/* http://www.ti.com/                                                        */
/*                                                                           */
/*  Redistribution and  use in source  and binary forms, with  or without    */
/*  modification,  are permitted provided  that the  following conditions    */
/*  are met:                                                                 */
/*                                                                           */
/*     Redistributions  of source  code must  retain the  above copyright    */
/*     notice, this list of conditions and the following disclaimer.         */
/*                                                                           */
/*     Redistributions in binary form  must reproduce the above copyright    */
/*     notice, this  list of conditions  and the following  disclaimer in    */
/*     the  documentation  and/or   other  materials  provided  with  the    */
/*     distribution.                                                         */
/*                                                                           */
/*     Neither the  name of Texas Instruments Incorporated  nor the names    */
/*     of its  contributors may  be used to  endorse or  promote products    */
/*     derived  from   this  software  without   specific  prior  written    */
/*     permission.                                                           */
/*                                                                           */
/*  THIS SOFTWARE  IS PROVIDED BY THE COPYRIGHT  HOLDERS AND CONTRIBUTORS    */
/*  "AS IS"  AND ANY  EXPRESS OR IMPLIED  WARRANTIES, INCLUDING,  BUT NOT    */
/*  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR    */
/*  A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT    */
/*  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,    */
/*  SPECIAL,  EXEMPLARY,  OR CONSEQUENTIAL  DAMAGES  (INCLUDING, BUT  NOT    */
/*  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,    */
/*  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY    */
/*  THEORY OF  LIABILITY, WHETHER IN CONTRACT, STRICT  LIABILITY, OR TORT    */
/*  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE    */
/*  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.     */
/*                                                                           */
/*****************************************************************************/

#ifndef _ERRNO
#define _ERRNO

#if defined(__TMS320C28XX_CLA__)
#error "Header file <errno.h> not supported by CLA compiler"
#endif

#pragma diag_push
#pragma CHECK_MISRA("-6.3") /* standard types required for standard headers */
#pragma CHECK_MISRA("-19.1") /* #includes required for implementation */
#pragma CHECK_MISRA("-20.1") /* standard headers must define standard names */
#pragma CHECK_MISRA("-20.2") /* standard headers must define standard names */

#ifdef __cplusplus
//----------------------------------------------------------------------------
// <cerrno> IS RECOMMENDED OVER <errno.h>.  <errno.h> IS PROVIDED FOR
// COMPATIBILITY WITH C AND THIS USAGE IS DEPRECATED IN C++
//----------------------------------------------------------------------------
extern "C" namespace std
{
#endif /* __cplusplus */

#include <linkage.h>
#include <_tls.h>

    #define EDOM   1
    #define ERANGE 2
    #define ENOENT 3
    #define EFPOS  5
    #define EILSEQ 6

    extern _DATA_ACCESS int errno;
    #pragma diag_push
    /* errno is not allowed under MISRA, anyway */
    #pragma CHECK_MISRA("-5.6") /* duplicated name in another scope (errno) */
    #pragma CHECK_MISRA("-19.4") /* macro expands to parenthesized */
    #ifdef __cplusplus
      #define errno ::std::errno
    #else
      #define errno errno
    #endif
    #pragma diag_pop

#ifdef __cplusplus
} /* extern "C" namespace std */
#endif /* __cplusplus */

#pragma diag_pop

#endif  /* _ERRNO */

#pragma diag_push

/* using declarations must occur outside header guard to support including both
   C and C++-wrapped version of header; see _CPP_STYLE_HEADER check */
/* this code is for C++ mode only and thus also not relevant for MISRA */
#pragma CHECK_MISRA("-19.15")

#if defined(__cplusplus) && !defined(_CPP_STYLE_HEADER)

#endif /* _CPP_STYLE_HEADER */

#pragma diag_pop


text:
require 'spec_helper'

describe Todo do
  let(:issue) { create(:issue) }

  describe 'relationships' do
    it { is_expected.to belong_to(:author).class_name("User") }
    it { is_expected.to belong_to(:note) }
    it { is_expected.to belong_to(:project) }
    it { is_expected.to belong_to(:group) }
    it { is_expected.to belong_to(:target).touch(true) }
    it { is_expected.to belong_to(:user) }
  end

  describe 'respond to' do
    it { is_expected.to respond_to(:author_name) }
    it { is_expected.to respond_to(:author_email) }
  end

  describe 'validations' do
    it { is_expected.to validate_presence_of(:action) }
    it { is_expected.to validate_presence_of(:target_type) }
    it { is_expected.to validate_presence_of(:user) }
    it { is_expected.to validate_presence_of(:author) }

    context 'for commits' do
      subject { described_class.new(target_type: 'Commit') }

      it { is_expected.to validate_presence_of(:commit_id) }
      it { is_expected.not_to validate_presence_of(:target_id) }
    end

    context 'for issuables' do
      subject { described_class.new(target: issue) }

      it { is_expected.to validate_presence_of(:target_id) }
      it { is_expected.not_to validate_presence_of(:commit_id) }
    end
  end

  describe '#body' do
    before do
      subject.target = build(:issue, title: 'Bugfix')
    end

    it 'returns target title when note is blank' do
      subject.note = nil

      expect(subject.body).to eq 'Bugfix'
    end

    it 'returns note when note is present' do
      subject.note = build(:note, note: 'quick fix')

      expect(subject.body).to eq 'quick fix'
    end
  end

  describe '#done' do
    it 'changes state to done' do
      todo = create(:todo, state: :pending)
      expect { todo.done }.to change(todo, :state).from('pending').to('done')
    end

    it 'does not raise error when is already done' do
      todo = create(:todo, state: :done)
      expect { todo.done }.not_to raise_error
    end
  end

  describe '#for_commit?' do
    it 'returns true when target is a commit' do
      subject.target_type = 'Commit'
      expect(subject.for_commit?).to eq true
    end

    it 'returns false when target is an issuable' do
      subject.target_type = 'Issue'
      expect(subject.for_commit?).to eq false
    end
  end

  describe '#target' do
    context 'for commits' do
      let(:project) { create(:project, :repository) }
      let(:commit) { project.commit }

      it 'returns an instance of Commit when exists' do
        subject.project = project
        subject.target_type = 'Commit'
        subject.commit_id = commit.id

        expect(subject.target).to be_a(Commit)
        expect(subject.target).to eq commit
      end

      it 'returns nil when does not exists' do
        subject.project = project
        subject.target_type = 'Commit'
        subject.commit_id = 'xxxx'

        expect(subject.target).to be_nil
      end
    end

    it 'returns the issuable for issuables' do
      subject.target_id = issue.id
      subject.target_type = issue.class.name
      expect(subject.target).to eq issue
    end
  end

  describe '#target_reference' do
    it 'returns commit full reference with short id' do
      project = create(:project, :repository)
      commit = project.commit

      subject.project = project
      subject.target_type = 'Commit'
      subject.commit_id = commit.id

      expect(subject.target_reference).to eq commit.reference_link_text(full: true)
    end

    it 'returns full reference for issuables' do
      subject.target = issue
      expect(subject.target_reference).to eq issue.to_reference(full: true)
    end
  end

  describe '#self_added?' do
    let(:user_1) { build(:user) }

    before do
      subject.user = user_1
    end

    it 'is true when the user is the author' do
      subject.author = user_1

      expect(subject).to be_self_added
    end

    it 'is false when the user is not the author' do
      subject.author = build(:user)

      expect(subject).not_to be_self_added
    end
  end

  describe '#self_assigned?' do
    let(:user_1) { build(:user) }

    before do
      subject.user = user_1
      subject.author = user_1
      subject.action = Todo::ASSIGNED
    end

    it 'is true when todo is ASSIGNED and self_added' do
      expect(subject).to be_self_assigned
    end

    it 'is false when the todo is not ASSIGNED' do
      subject.action = Todo::MENTIONED

      expect(subject).not_to be_self_assigned
    end

    it 'is false when todo is not self_added' do
      subject.author = build(:user)

      expect(subject).not_to be_self_assigned
    end
  end

  describe '.for_action' do
    it 'returns the todos for a given action' do
      create(:todo, action: Todo::MENTIONED)

      todo = create(:todo, action: Todo::ASSIGNED)

      expect(described_class.for_action(Todo::ASSIGNED)).to eq([todo])
    end
  end

  describe '.for_author' do
    it 'returns the todos for a given author' do
      user1 = create(:user)
      user2 = create(:user)
      todo = create(:todo, author: user1)

      create(:todo, author: user2)

      expect(described_class.for_author(user1)).to eq([todo])
    end
  end

  describe '.for_project' do
    it 'returns the todos for a given project' do
      project1 = create(:project)
      project2 = create(:project)
      todo = create(:todo, project: project1)

      create(:todo, project: project2)

      expect(described_class.for_project(project1)).to eq([todo])
    end
  end

  describe '.for_group' do
    it 'returns the todos for a given group' do
      group1 = create(:group)
      group2 = create(:group)
      todo = create(:todo, group: group1)

      create(:todo, group: group2)

      expect(described_class.for_group(group1)).to eq([todo])
    end
  end

  describe '.for_type' do
    it 'returns the todos for a given target type' do
      todo = create(:todo, target: create(:issue))

      create(:todo, target: create(:merge_request))

      expect(described_class.for_type(Issue.name)).to eq([todo])
    end
  end

  describe '.for_target' do
    it 'returns the todos for a given target' do
      todo = create(:todo, target: create(:issue))

      create(:todo, target: create(:merge_request))

      expect(described_class.for_type(Issue.name).for_target(todo.target))
        .to contain_exactly(todo)
    end
  end

  describe '.for_commit' do
    it 'returns the todos for a commit ID' do
      todo = create(:todo, commit_id: '123')

      create(:todo, commit_id: '456')

      expect(described_class.for_commit('123')).to eq([todo])
    end
  end

  describe '.for_group_and_descendants' do
    it 'returns the todos for a group and its descendants' do
      parent_group = create(:group)
      child_group = create(:group, parent: parent_group)

      todo1 = create(:todo, group: parent_group)
      todo2 = create(:todo, group: child_group)
      todos = described_class.for_group_and_descendants(parent_group)

      expect(todos).to include(todo1)

      # Nested groups only work on PostgreSQL, so on MySQL todo2 won't be
      # present.
      expect(todos).to include(todo2) if Gitlab::Database.postgresql?
    end
  end

  describe '.any_for_target?' do
    it 'returns true if there are todos for a given target' do
      todo = create(:todo)

      expect(described_class.any_for_target?(todo.target)).to eq(true)
    end

    it 'returns false if there are no todos for a given target' do
      issue = create(:issue)

      expect(described_class.any_for_target?(issue)).to eq(false)
    end
  end

  describe '.update_state' do
    it 'updates the state of todos' do
      todo = create(:todo, :pending)
      ids = described_class.update_state(:done)

      todo.reload

      expect(ids).to eq([todo.id])
      expect(todo.state).to eq('done')
    end

    it 'does not update todos that already have the given state' do
      create(:todo, :pending)

      expect(described_class.update_state(:pending)).to be_empty
    end
  end
end


text:
namespace cc {

// A Layer that renders a solid color. The color is specified by using
// SetBackgroundColor() on the base class.
class CC_EXPORT SolidColorLayer : public Layer {
 public:
  static scoped_refptr<SolidColorLayer> Create();

  SolidColorLayer(const SolidColorLayer&) = delete;
  SolidColorLayer& operator=(const SolidColorLayer&) = delete;

  std::unique_ptr<LayerImpl> CreateLayerImpl(
      LayerTreeImpl* tree_impl) const override;

  void SetBackgroundColor(SkColor4f color) override;

 protected:
  SolidColorLayer();

 private:
  ~SolidColorLayer() override;
};

}  // namespace cc
#endif  // CC_LAYERS_SOLID_COLOR_LAYER_H_


text:
<?php

namespace CodeZero\Mailer;

abstract class MailComposer
{
    /**
     * Mail
     *
     * @var Mail
     */
    private $mail;

    /**
     * Create a new mail instance.
     *
     * @param Mail $mail
     */
    public function __construct(Mail $mail)
    {
        $this->mail = $mail;
    }

    /**
     * Compose an e-mail.
     *
     * @param string $toEmail
     * @param string $toName
     * @param string $subject
     * @param string $view
     * @param array $data
     * @param callable $options
     *
     * @return \CodeZero\Mailer\Mail
     */
    protected function getMail($toEmail, $toName, $subject, $view, array $data = array(), $options = null)
    {
        return $this->mail->compose($toEmail, $toName, $subject, $view, $data, $options);
    }
}


text:
package org.citygml4j.core.model.dynamizer;

import org.citygml4j.core.model.core.AbstractFeature;
import org.xmlobjects.gml.model.geometry.Envelope;
import org.xmlobjects.gml.model.temporal.TimePosition;
import org.xmlobjects.gml.util.EnvelopeOptions;

public abstract class AbstractTimeseries extends AbstractFeature {
    private TimePosition firstTimestamp;
    private TimePosition lastTimestamp;

    public TimePosition getFirstTimestamp() {
        return firstTimestamp;
    }

    public void setFirstTimestamp(TimePosition firstTimestamp) {
        this.firstTimestamp = asChild(firstTimestamp);
    }

    public TimePosition getLastTimestamp() {
        return lastTimestamp;
    }

    public void setLastTimestamp(TimePosition lastTimestamp) {
        this.lastTimestamp = asChild(lastTimestamp);
    }

    @Override
    protected void updateEnvelope(Envelope envelope, EnvelopeOptions options) {
    }
}


text:
See the [JSON Web Algorithms (JWA)](https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-36) spec for more
information regarding algorithms in JWT.


text:
export * from './article-resolver';
export * from './articles-resolver';


text:
#include "Edb.h"

EFI_DEBUG_STATUS
DebuggerGo (
  IN     CHAR16                    *CommandArg,
  IN     EFI_DEBUGGER_PRIVATE_DATA *DebuggerPrivate,
  IN     EFI_EXCEPTION_TYPE        ExceptionType,
  IN OUT EFI_SYSTEM_CONTEXT        SystemContext
  )
/*++

Routine Description:

  DebuggerCommand - Go

Arguments:

  CommandArg      - The argument for this command
  DebuggerPrivate - EBC Debugger private data structure
  InterruptType   - Interrupt type.
  SystemContext   - EBC system context.

Returns:

  EFI_DEBUG_BREAK    - formal return value
  EFI_DEBUG_CONTINUE - something wrong

--*/
{
  UINTN        Address;
  CHAR16       *CommandStr;
  EFI_STATUS   Status;

  //
  // Check argument
  //
  if (CommandArg != NULL) {
    if (EfiStriCmp (CommandArg, L"til") == 0) {
      CommandStr = StrGetNextTokenLine (L" ");
      if (CommandStr != NULL) {
        //
        // Enable GoTil break now
        // set BreakAddress, and set feature flag.
        //
        Status = Symboltoi (CommandStr, &Address);
        if (EFI_ERROR (Status)) {
          if (Status == EFI_NOT_FOUND) {
            Address = Xtoi(CommandStr);
          } else {
            //
            // Something wrong, let Symboltoi print error info.
            //
            EDBPrint (L"Command Argument error!\n");
            return EFI_DEBUG_CONTINUE;
          }
        }
        DebuggerPrivate->GoTilContext.BreakAddress = Address;
        DebuggerPrivate->FeatureFlags |= EFI_DEBUG_FLAG_EBC_GT;
      } else {
        EDBPrint (L"Command Argument error!\n");
        return EFI_DEBUG_CONTINUE;
      }
    } else {
      EDBPrint (L"Command Argument error!\n");
      return EFI_DEBUG_CONTINUE;
    }
  }

  //
  // Done
  //
  return EFI_DEBUG_BREAK;
}


text:
/*
Title: CSS coding standards
Sort: 2
*/

## Introduction

CSS (**C**ascading **S**tyle**S**heets) is used to control the presentation of
web pages. CSS obeys the principle of "separation of concerns" - HTML is used to
mark up content and CSS is used to control its presentation.

CSS may be included inline using the `style` attribute, inside a `<style>` node,
or separately in an external linked stylesheet. On projects we will normally
usr the external linked stylesheet method. To control more dynamic
elements, we will also use JavaScript to modify their styling, using jQuery's
`addClass()` and `removeClass()` methods, and also `css()` where applicable.

## Specifics

### Formatting

The policies outlined in _File formats and encodings_ MUST be applied to CSS for
all projects for Communisis Digital.

CSS SHALL be written in the more verbose multi-line format; prefer this:

    element {
        prop1 : val1;
        prop2 : val2;
        prop3 : val3;
    }

Rather than this:

    element { prop1 : val1; prop2 : val2; prop3 : val3; }

The latter is harder to read and harder to edit, and also less appropriate for
version control.

Property/value key pairs SHOULD be separated by a space, a colon, and another
space (this is uncommon in CSS, but aids readability and mirrors common
conventions in other languages for creating objects and hashes).

Where there is only one property/value pair for a selector, _the semicolon MUST
still be used_. Even though the semicolon, as per CSS's grammar, is optional in
this case, include it anyway - if a second property/value pair is added a later
date, there is the no requirement to check whether a semicolon needs to be added
on the previous line since there will always be one there. (These problems can
be very hard to spot later - often the CSS rendering engine will silently ignore
one or both properties.) As an example, do this:

    body {
        background : red;
    }

Rather than this:

    body {
        background : red
    }

### Property order

Having a standardised convention for ordering CSS properties has no performance
benefits, but it does make projects easier for developers to work on and
maintain. We recommend ordering properties around their type of functionality
(rather than alphabetically, by length, or any other more abstruse method). We
therefore SHALL use the following order:

1. Display and flow.
2. Positioning.
3. Dimensions (width before height).
4. Margins, padding, borders.
5. Typography.
6. Colours and backgrounds.
7. Miscellaneous.
8. CSS3 (prefixed) properties. *

(* See _CSS3 and vendor prefixes_ for a full discussion on this point.)

A (contrived) example follows:

    .panel {
    /* display and flow */
        display : block;
        position : relative;
        float : left;
        z-index : 10;

    /* dimensions */
        width : 500px;
        height : 200px;

    /* margins, padding, borders */
        margin : 10px 20px;
        padding : 1em;
        border : 1px solid red;

    /* typography */
        font-size : 1.5em;
        font-weight : bold;

    /* colours and backgrounds */
        color : red;
        background-image : ... ;
        background-color : blue;
        background-position : 10px 20px;
        background-repeat : no-repeat;

    /* miscellaneous */
        opacity : 0.8;
        cursor : pointer;

    /* CSS3 property with vendor-prefixes last */
        -webkit-border-radius : 12px;
        -moz-border-radius : 12px;
        -ms-border-radius : 12px;
        -o-border-radius : 12px;
        border-radius : 12px;
    }

(Comments have been added here only for clarity. In real code, there would be no
comments and the property types would stand by themselves.)

### Naming conventions

Please see below under _SMACSS_.

### Spritesheets

Spritesheets (sometimes referred to as "CSS Sprites" or simply "sprites") are
separate images combined into one image file, with individual image elements
aligned appropriately in a grid. The general reason for this methodology is to
reduce the number of distinct HTTP requests (and also to decrease the download
size, in many cases).

Spritesheets SHOULD be used for:

* Sets of grouped icons (eg. social media sharing icons).

* Buttons where there are multiple states (eg. default, over, and active).

They MUST be avoided when a repeating background is required or where they will
lead to increased complexity; on the latter point,
[a sprite sheet like Amazon's][amazon-sprite] will almost certainly massively
increase development and maintenance time.

The original, layered version of each spritesheet MUST be kept in the folder
defined for non-web assets in the project repository. Each spritesheet MUST
be described in the associated project documentation. The description MUST
define:

* The filename of the spritesheet.
* The logic behind the grouping of each spritesheet (eg. "Additional product
  information icons").
* Whether the sprite should be used horizontally or vertically.
* The order of the states used for each image (eg. "off, over, active").

[amazon-sprite]: http://g-ecx.images-amazon.com/images/G/01/gno/images/orangeBlue/navPackedSprites-US-15._V202471683_.png

### Units

For fonts, we SHALL use `em`. This is a relative, scalable unit and well-suited
for pages which may be viewed in varying contexts.

In-page modules SHOULD, where possible, be fluid and not have fixed widths.
Their _container elements_, however, will have fixed widths. By "container
element", we broadly mean an element which contains no content directly by
itself, but instead "wraps around" other content; examples would include the
container around the entire page, the header or footer portions of the page, or
the structure which contains the principal navigation. In the SMACSS model (see
below), these would generally each be controlled by a _Layout_ rule.

In general, this approach will help cater for a
responsive design, should one be implemented in a future release.

## SMACSS

[SMACSS][smacss] (**S**calable and **M**odular **A**rchitecture for CSS) is a
methodology which is intended to help developers working on larger projects. We
SHOULD loosely follow the principles defined in the core SMACSS chapters (ie.
3-9).

Key concepts:

* Division of rules into five categories:

    * **Base**

        Defaults for a site - eg. `html` and `body` having no padding or margin.

    * **Layout**

        Styles which divide the page into sections (putting modules into place).

    * **Module**

        Reusable components of the page (sidebars, footers, product listings,
        etc.).

    * **State**

        Styles which can be applied to a module and describe its state, eg.
        open, closed, hidden, expanded.

    * **Theme**

        Styles which may be used to apply a theme to module (optional).

* Naming conventions:

    * For layouts, use `l-` as a prefix.

    * For states, use `is-` as a prefix, eg. `is-hidden`

* Specificity and selectors:

    * Avoid making unnecessary assumptions and being too specific with
      ID and element selectors - using classes can often provide a more
      generic solution.

* "Sub-classing" - supposing you have a generic element with a class of `panel`,
  you may wish to use this element in different contexts (for instance in a the
  main content area and also in a sidebar); in these contexts it may have
  slightly different properties, eg. its width.  To avoid specificity
  complexities, SMACSS proposes "sub-classing" the `panel` class by creating a
  second class with the particulars of the context applied to it:

        .panel {
            width : 100px;
        }
            .panel.panel-sidebar {
                width : 80px;
            }

The convention is to give the element the same name followed by a hyphen and
then the context; in the markup, we would then have:

[smacss]: http://smacss.com/

## CSS3 and vendor prefixes

[CSS3] is not, in its entirety, a formal recommendation from the W3C yet, but
browser vendors have, nonetheless, begun implementing some of its functionality.
To indicate that this functionality is experimental or has not been formalised,
browser vendors have taken to prefixing the properties with certain strings;
these are known as "vendor prefixes".

The vendor prefixes in current and common use are:

* `-webkit-`: Chrome, Safari, most mobile browsers.
* `-moz-`: Firefox and browsers using the Gecko engine.
* `-ms-`: recent versions of Internet Explorer.
* `-o-`: Opera.

An example of handling these vendor prefixes follows:

    .element {
        -webkit-transition: all 4s ease;
        -moz-transition: all 4s ease;
        -ms-transition: all 4s ease;
        -o-transition: all 4s ease;
        transition: all 4s ease;
    }

The unprefixed version SHALL be placed last as per this article:
<http://css-tricks.com/ordering-css3-properties/>

[CSS3]: http://www.w3.org/TR/#tr_CSS

## Browser feature detection

As with JavaScript, we SHOULD be targeting features rather than browsers.
Modernizr's "feature" classes, which it adds to the `html` node, will be used
for feature detection.

Where it is absolutely necessary, we MAY use
[HTML5 Boilerplate's IE HTML tags][bp-ie-tags] to provide CSS workarounds
for particular Internet Explorer issues.

[bp-ie-tags]: http://html5boilerplate.com/docs/The-markup/#ie-html-tag-classes

## Media types

Styles relating to distinct media types (chiefly `print` as opposed to the
default `screen`) MUST be kept in the same stylesheet.
["5 years later: print CSS still sucks"][print-css-sucks] explains why. Where
necessary, minimal print-based styles can be invoked using `@media` queries:

    body {
        background : green;
    }

    @media print {
        body {
            background : white;
        }
    }

[print-css-sucks]: http://www.phpied.com/5-years-later-print-css-still-sucks/

## Build process

CSS MUST be stripped of comments and unnecessary whitespace during the build
process - it MUST be minified to its most succinct and optimal form. During
development, CSS MUST be appropriately indented and commented.

All non-CDN CSS files MUST be concatenated into a single 'master' CSS file. See
_Build process_ for more information.


text:
extern World * world;

TextRenderer::TextRenderer() {
    this->physics = world->physics;
    Object3dProperties props;
    props.has_physics = false;
    for (int i = 0; i < 127; i++) {
        this->letters.push_back(new Letter(static_cast<char> (i)));
    }
    std::cout << this->letters.size();

}

void TextRenderer::addString(std::string * string){
    for(char& c : *string) {
        std::cout << c << std::endl;
    }

}

void TextRenderer::draw(glm::mat4 * mvp){
    for(Letter * letter : this->letters) {
        letter->scene.draw(mvp);
    }
}

void TextRenderer::label(SpatialObjectExpanded object,std::string name){

    GLfloat width = 0.0;

    Object3dProperties props;
    props.position = RELATIVE;
    props.dimension.width = 0;
    props.dimension.height = 0.01;
    props.color = glm::vec3(0,0,111);
//    this->name = name;

    for(char& c : name) {
       width += this->letters[static_cast<int> (c)]->width;
    }
    std::cout << width << std::endl;
//    this->spatial_construct = std::make_shared<Object3d>(&props);
}


text:
"""Tests for install_python_dev_dependencies.py."""

from __future__ import annotations

import builtins
import contextlib
import io
import os
import subprocess
import sys

from core.tests import test_utils
from scripts import install_python_dev_dependencies

from typing import Dict, Generator, List

class InstallPythonDevDependenciesTests(test_utils.GenericTestBase):

    @contextlib.contextmanager
    def sys_real_prefix_context(
        self, new_value: str,
    ) -> Generator[None, None, None]:
        """Create a context manager to temporarily set sys.real_prefix.

        Args:
            new_value: str. The new value of sys.real_prefix to set.

        Yields:
            None. Yields nothing, but upon yielding sys.real_prefix will be set.
        """
        had_attribute = hasattr(sys, 'real_prefix')
        if had_attribute:
            original = getattr(sys, 'real_prefix')
        setattr(sys, 'real_prefix', new_value)
        try:
            yield
        finally:
            if had_attribute:
                setattr(sys, 'real_prefix', original)
            else:
                delattr(sys, 'real_prefix')

    def test_check_python_env_is_suitable_passes_when_in_venv(self) -> None:
        prefix_swap = self.swap(
            sys, 'prefix', '/home/user/.pyenv/versions/3.7.10')
        base_prefix_swap = self.swap(
            sys, 'base_prefix', '/home/user/.pyenv/versions/oppia')
        real_prefix_manager = self.sys_real_prefix_context('')
        environ_swap = self.swap(os, 'environ', {})
        with prefix_swap, base_prefix_swap, real_prefix_manager, environ_swap:
            install_python_dev_dependencies.check_python_env_is_suitable()

    def test_check_python_env_is_suitable_passes_when_in_venv_real_prefix(
        self
    ) -> None:
        prefix_swap = self.swap(
            sys, 'prefix', '/home/user/.pyenv/versions/3.7.10')
        base_prefix_swap = self.swap(
            sys, 'base_prefix', '/home/user/.pyenv/versions/3.7.10')
        real_prefix_manager = self.sys_real_prefix_context(
            '/home/user/.pyenv/versions/oppia')
        environ_swap = self.swap(os, 'environ', {})
        with prefix_swap, base_prefix_swap, real_prefix_manager, environ_swap:
            install_python_dev_dependencies.check_python_env_is_suitable()

    def test_check_python_env_is_suitable_fails_when_out_of_venv(self) -> None:
        prefix_swap = self.swap(
            sys, 'prefix', '/home/user/.pyenv/versions/3.7.10')
        base_prefix_swap = self.swap(
            sys, 'base_prefix', '/home/user/.pyenv/versions/3.7.10')
        real_prefix_manager = self.sys_real_prefix_context('')
        environ_swap = self.swap(os, 'environ', {})
        expected_error = (
            'Oppia must be developed within a virtual environment.')
        with self.assertRaisesRegex(
            AssertionError, expected_error
        ):
            with prefix_swap, base_prefix_swap, real_prefix_manager:
                with environ_swap:
                    (
                        install_python_dev_dependencies
                        .check_python_env_is_suitable()
                    )

    def test_check_python_env_is_suitable_passes_when_on_ci(self) -> None:
        prefix_swap = self.swap(
            sys, 'prefix', '/home/user/.pyenv/versions/3.7.10')
        base_prefix_swap = self.swap(
            sys, 'base_prefix', '/home/user/.pyenv/versions/3.7.10')
        real_prefix_manager = self.sys_real_prefix_context('')
        environ_swap = self.swap(os, 'environ', {'GITHUB_ACTION': '1'})
        with prefix_swap, base_prefix_swap, real_prefix_manager, environ_swap:
            install_python_dev_dependencies.check_python_env_is_suitable()

    def test_install_installation_tools(self) -> None:
        expected_tools = {
            'pip': '22.1.1',
            'pip-tools': '6.6.2',
            'setuptools': '58.5.3',
        }
        installed_tools: Dict[str, str] = {}

        def mock_run(
            args: List[str], check: bool, encoding: str,
        ) -> None:
            package, version = args[-1].split('==')
            self.assertNotIn(package, installed_tools)
            installed_tools[package] = version
            self.assertEqual(
                args,
                [
                    sys.executable, '-m', 'pip', 'install',
                    f'{package}=={version}',
                ],
            )
            self.assertTrue(check)
            self.assertEqual(encoding, 'utf-8')

        run_swap = self.swap(subprocess, 'run', mock_run)

        with run_swap:
            install_python_dev_dependencies.install_installation_tools()

        self.assertEqual(installed_tools, expected_tools)

    def test_install_dev_dependencies(self) -> None:

        def mock_run(*_args: str, **_kwargs: str) -> None:  # pylint: disable=unused-argument
            pass

        run_swap = self.swap_with_checks(
            subprocess, 'run', mock_run, expected_args=[
                (['pip-sync', 'requirements_dev.txt'],),
            ],
            expected_kwargs=[
                {'check': True, 'encoding': 'utf-8'},
            ]
        )

        with run_swap:
            install_python_dev_dependencies.install_dev_dependencies()

    def test_compile_pip_requirements_no_change(self) -> None:

        def mock_run(*_args: str, **_kwargs: str) -> None:  # pylint: disable=unused-argument
            pass

        def mock_open(*_args: str, **_kwargs: str) -> io.StringIO:
            return io.StringIO('mock file contents')

        run_swap = self.swap_with_checks(
            subprocess, 'run', mock_run, expected_args=[
                ([
                    'pip-compile', '--no-emit-index-url', 'requirements_dev.in',
                    '--output-file', 'requirements_dev.txt',
                ],),
            ],
            expected_kwargs=[
                {'check': True, 'encoding': 'utf-8'},
            ]
        )
        open_swap = self.swap_with_checks(
            builtins, 'open', mock_open, expected_args=[
                ('requirements_dev.txt', 'r'),
                ('requirements_dev.txt', 'r'),
            ],
            expected_kwargs=[
                {'encoding': 'utf-8'},
                {'encoding': 'utf-8'},
            ],
        )

        with run_swap, open_swap:
            change = (
                install_python_dev_dependencies.compile_pip_requirements(
                    'requirements_dev.in', 'requirements_dev.txt'))
        self.assertFalse(change)

    def test_compile_pip_requirements_change(self) -> None:

        def mock_run(*_args: str, **_kwargs: str) -> None:  # pylint: disable=unused-argument
            pass

        counter = []

        def mock_open(*_args: str, **_kwargs: str) -> io.StringIO:
            counter.append(1)
            return io.StringIO(f'mock file contents {len(counter)}')

        run_swap = self.swap_with_checks(
            subprocess, 'run', mock_run, expected_args=[
                ([
                    'pip-compile', '--no-emit-index-url', 'requirements_dev.in',
                    '--output-file', 'requirements_dev.txt',
                ],),
            ],
            expected_kwargs=[
                {'check': True, 'encoding': 'utf-8'},
            ]
        )
        open_swap = self.swap_with_checks(
            builtins, 'open', mock_open, expected_args=[
                ('requirements_dev.txt', 'r'),
                ('requirements_dev.txt', 'r'),
            ],
            expected_kwargs=[
                {'encoding': 'utf-8'},
                {'encoding': 'utf-8'},
            ],
        )

        with run_swap, open_swap:
            change = (
                install_python_dev_dependencies.compile_pip_requirements(
                    'requirements_dev.in', 'requirements_dev.txt'))
        self.assertTrue(change)

    def test_main_passes_with_no_assert_and_no_change(self) -> None:
        def mock_func() -> None:
            pass

        def mock_compile(*_args: str) -> bool:
            return False

        assert_swap = self.swap_with_checks(
            install_python_dev_dependencies, 'check_python_env_is_suitable',
            mock_func)
        install_tools_swap = self.swap_with_checks(
            install_python_dev_dependencies,
            'install_installation_tools', mock_func)
        compile_swap = self.swap_with_checks(
            install_python_dev_dependencies,
            'compile_pip_requirements', mock_compile)
        install_dependencies_swap = self.swap_with_checks(
            install_python_dev_dependencies,
            'install_dev_dependencies', mock_func)

        with assert_swap, install_tools_swap, compile_swap:
            with install_dependencies_swap:
                install_python_dev_dependencies.main([])

    def test_main_passes_with_assert_and_no_change(self) -> None:
        def mock_func() -> None:
            pass

        def mock_compile(*_args: str) -> bool:
            return False

        assert_swap = self.swap_with_checks(
            install_python_dev_dependencies, 'check_python_env_is_suitable',
            mock_func)
        install_tools_swap = self.swap_with_checks(
            install_python_dev_dependencies,
            'install_installation_tools', mock_func)
        compile_swap = self.swap_with_checks(
            install_python_dev_dependencies,
            'compile_pip_requirements', mock_compile)
        install_dependencies_swap = self.swap_with_checks(
            install_python_dev_dependencies,
            'install_dev_dependencies', mock_func)

        with assert_swap, install_tools_swap, compile_swap:
            with install_dependencies_swap:
                install_python_dev_dependencies.main(
                    ['--assert_compiled'])

    def test_main_passes_with_no_assert_and_change(self) -> None:
        def mock_func() -> None:
            pass

        def mock_compile(*_args: str) -> bool:
            return True

        assert_swap = self.swap_with_checks(
            install_python_dev_dependencies, 'check_python_env_is_suitable',
            mock_func)
        install_tools_swap = self.swap_with_checks(
            install_python_dev_dependencies,
            'install_installation_tools', mock_func)
        compile_swap = self.swap_with_checks(
            install_python_dev_dependencies,
            'compile_pip_requirements', mock_compile)
        install_dependencies_swap = self.swap_with_checks(
            install_python_dev_dependencies,
            'install_dev_dependencies', mock_func)

        with assert_swap, install_tools_swap, compile_swap:
            with install_dependencies_swap:
                install_python_dev_dependencies.main([])

    def test_main_fails_with_assert_and_change(self) -> None:
        def mock_func() -> None:
            pass

        def mock_compile(*_args: str) -> bool:
            return True

        assert_swap = self.swap_with_checks(
            install_python_dev_dependencies, 'check_python_env_is_suitable',
            mock_func)
        install_tools_swap = self.swap_with_checks(
            install_python_dev_dependencies,
            'install_installation_tools', mock_func)
        compile_swap = self.swap_with_checks(
            install_python_dev_dependencies,
            'compile_pip_requirements', mock_compile)
        install_dependencies_swap = self.swap_with_checks(
            install_python_dev_dependencies,
            'install_dev_dependencies', mock_func)

        error_regex = (
            'The Python development requirements file '
            'requirements_dev.txt was changed')

        with assert_swap, install_tools_swap, compile_swap:
            with install_dependencies_swap:
                with self.assertRaisesRegex(
                        RuntimeError, error_regex):
                    install_python_dev_dependencies.main(
                        ['--assert_compiled'])


text:
<?php

require_once 'autoload.php';

/**
 * To-Do lists Plugin
 *
 * @author Andrzej Kupczyk
 */
class ToDoListsPlugin extends MantisPlugin
{
    const VERSION = '1.1.0';

    /**
     * @var TasksRepository
     */
    protected $repository;

    public function register()
    {
        $this->name = plugin_lang_get('name');
        $this->description = plugin_lang_get('description');
        $this->page = 'config_page';

        $this->version = self::VERSION;
        $this->requires = [
            'MantisCore' => '1.2.0',
        ];

        $this->author = 'Andrzej Kupczyk';
        $this->contact = 'kontakt@andrzejkupczyk.pl';
        $this->url = 'http://andrzejkupczyk.pl';
    }

    public function init()
    {
        $this->repository = new ToDoLists\TasksRepository;
    }

    public function config()
    {
        return [
            'manage_threshold' => DEVELOPER,
            'view_threshold' => REPORTER,
        ];
    }

    public function hooks()
    {
        return [
            'EVENT_LAYOUT_RESOURCES' => 'resources',
            'EVENT_VIEW_BUG_DETAILS' => 'display',
        ];
    }

    public function schema()
    {
        return [
            ['CreateTableSQL', [
                plugin_table('tasks'),
                'id I UNSIGNED PRIMARY NOTNULL AUTOINCREMENT,
                bug_id I UNSIGNED NOTNULL DEFAULT \'0\',
                description C(120) NOTNULL DEFAULT \'\',
                finished L DEFAULT 0',
                ['mysql' => 'ENGINE=MyISAM DEFAULT CHARSET=utf8', 'pgsql' => 'WITHOUT OIDS'],
            ]],
            ['CreateIndexSQL', [
                'idx_tasks_bug_id',
                plugin_table('tasks'),
                'bug_id',
            ]],
        ];
    }

    /**
     * @param string  $event
     * @param integer $bugId
     */
    public function display($event, $bugId)
    {
        $tasks = $this->repository->findByBug($bugId);
        include_once 'pages/partials/todolist.php';
    }

    /**
     * @param  string   $event
     * @return string
     */
    public function resources($event)
    {
        return '<link rel="stylesheet" type="text/css" href="' . plugin_file('todolists.css') . '" />' .
            '<script type="text/javascript" src="' . plugin_file('vue-min.js') . '"></script>' .
            '<script type="text/javascript" src="' . plugin_file('vue-resource-min.js') . '"></script>';
    }
}


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

    <title>PHP + Symfony Tips - Pasando Parametros a un Listener de Formulario</title>
    <meta name="description" content="" />

    <meta name="HandheldFriendly" content="True" />
    <meta name="MobileOptimized" content="320" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="stylesheet" type="text/css" href="/assets/css/normalize.css" />
    <link rel="stylesheet" type="text/css" href="/assets/css/screen.css" />
    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Noto+Serif:400,700,400italic|Open+Sans:700,400" />

    <link rel="stylesheet" type="text/css" href="/assets/css/syntax.css">

    <link rel="stylesheet" type="text/css" href="/assets/css/main.css" />

                PHP + Symfony Tips

            <time datetime="2015-08-24">24 Aug 2015</time>

            on

Pasando Parametros a un Listener de Formulario

La idea de este post es demostrar como podemos pasar opciones a un campo de formulario que se crea por medio de un escucha de eventos de formularios, para así dar a conocer el potencial que ofrece el componente de formularios, el despachador de eventos y el OptionsResolver.

Vamos a crear un ejemplo donde tenemos un formulario que muestra un listado de alumnos de una sección seleccionada, donde además solo mostraremos los alumnos con un promedio superior al indicado como parametro al formulario.

Como se puede apreciar, el listado de alumnos depende de la sección que se haya seleccionado, por lo que dicho campo se creará utilizando un listener de formularios. Además, este listener deberá conocer cual es el promedio mínimo que los usuarios deberán poseer para aparecer en el listado.

Este es el código del listener:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

<?php

namespace AppBundle\Form\Listener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;

class AddAlumnosFieldSubscriber implements EventSubscriberInterface
{
	private $promedioMinimo;

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

    public static function getSubscribedEvents()
    {
        return array(
            FormEvents::PRE_SET_DATA => 'onPreSetData',
            FormEvents::PRE_SUBMIT => 'onPreSubmit',
        );
    }

    public function onPreSetData(FormEvent $event)
    {
		$this->addField($event->getForm(), null);
    }

    public function onPreSubmit(FormEvent $event)
    {
        $data = $event->getData();
        $form = $event->getForm();

        $seccion = isset($data['seccion']) ? $data['seccion'] : null;

        $this->addField($event->getForm(), $seccion);
    }

    protected function addField($form, $seccion)
    {
    	$form->add('alumnos', 'entity', [
        	'class' => 'EntidadAlumnos',
            'property' => 'nombreYPromedio',
            'query_builder' => function($alumnosRepository) use($seccion) {
            	return $alumnosRepository->obtenerQueryPorSeccionYPromedioMinimo(
                	$seccion, $this->promedioMinimo
                    //el uso de $this en un Closure es a partir de php 5.4
                );
            }
        ]);
    }
}

Como se puede ver, nuestro listener recibe el promedio mínimo en su constructor, y con el, añade el campo de alunmos al formulario aplicando los filtros necesarios en la consulta a la base de datos.

Ahora el formulario que agrega el campo de la sección y de alumnos:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

<?php

namespace AppBundle\Form\Type;

use AppBundle\Form\Listener\AddAlumnosFieldSubscriber;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

/**
 * @author Manuel Aguirre <programador.manuel@gmail.com>
 */
class PromediosType extends AbstractType
{

    public function getName()
    {
        return 'promedio_alumnos';
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('seccion', 'entity', [
         	// Configuración del campo...
        ]);

        $builder->addEventSubscriber(new AddAlumnosFieldSubscriber(
        	$options['promedio_minimo'] // Obtenemos este valor como una opción del form.
        ));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults([
        	// Opciones por defecto del formulario
        ]);

        $resolver->setRequired(['promedio_minimo']);

        $resolver->setAllowedTypes([
        	// Solo aceptamos valores flotantes para esta opción.
        	'promedio_minimo' => 'float',
        ]);
    }
}

Haciendo uso del componente OptionsResolver disponible en los formularios, creamos una opción llamada promedio_minimo y luego hacemos llegar el valor definido en dicha opción al AddAlumnosFieldSubscriber en su creación.

Por último le hacemos llegar la opción en el controlador al momento de crear el formulario:

1
2
3
4
5
6
7
8
9
10
11
12
13
14

<?php
/... Algún Controlador ...
/**
 * @Route("/una-ruta", name="nombre_ruta")
 */
public function nombreAction(Request $request)
{
    $form = $this->createForm(new AlumnosType(), null, [
    	'promedio_minimo' => 10
    ]);
    $form->handleRequest($request);

    //...
}

Como ven el componente de formularios es muy flexible y nos permite crear formularios con alto grado de complejidad gracias a los escuchas de eventos y a el componente OptionsResolver, mediante el cual definimos nuestras propias opciones para los formularios.

 Manuel Aguirre <programador.manuel@gmail.com>

                        Desarrollador Web, (PHP, HTML, css, javascript).

                        Intento usar Symfony2 y/o sus componentes en mis proyectos.

                        Apasionado por el aprendizaje y loco por la Programación :-)

Comparte

                    Twitter

                    Facebook

                    Google+

                Please enable JavaScript to view the comments powered by Disqus.
                comments powered by Disqus


text:
<?php

namespace Waldo\OpenIdConnect\ProviderBundle\Tests\Handler;

use Waldo\OpenIdConnect\ProviderBundle\Handler\AuthenticationSuccessHandler;
use Symfony\Component\HttpFoundation\Request;

/**
 * AuthenticationSuccessHandlerTest
 *
 * @author valérian Girard <valerian.girard@educagri.fr>
 */
class AuthenticationSuccessHandlerTest extends \PHPUnit_Framework_TestCase
{

    private $httpUtils;
    private $securityContext;
    private $token;

    public function testHasClientId()
    {
        $logoutSuccessHandler = $this->getAuthenticationSuccessHandler();

        $request = new Request();
        $request->query->set('client_id', 'my_client_id');

        $this->httpUtils->expects($this->once())
                ->method("createRedirectResponse")
                ->with($this->callback(function($o) {
                            return $o instanceof \Symfony\Component\HttpFoundation\Request &&
                                    $o->attributes->get("clientId") === 'my_client_id';
                        }), $this->equalTo("oicp_authentication_scope"))
                ->will($this->returnValue("ok"));

        $res = $logoutSuccessHandler->onAuthenticationSuccess($request, $this->token);

        $this->assertEquals("ok", $res);
    }

    public function testHasSession()
    {
        $logoutSuccessHandler = $this->getAuthenticationSuccessHandler();

        $request = new Request();
        $session = $this->getMock("Symfony\Component\HttpFoundation\Session\Session");
        $session->expects($this->once())
                ->method("has")
                ->with($this->equalTo("_security.securitytest.target_path"))
                ->will($this->returnValue(true));
        $session->expects($this->once())
                ->method("get")
                ->with($this->equalTo("_security.securitytest.target_path"))
                ->will($this->returnValue("session_value"));

        $request->setSession($session);

        $this->token->expects($this->once())
                ->method("getProviderKey")
                ->will($this->returnValue("securitytest"));

        $this->httpUtils->expects($this->once())
                ->method("createRedirectResponse")
                ->with($this->callback(function($o) {
                            return $o instanceof \Symfony\Component\HttpFoundation\Request;
                        }), $this->equalTo("session_value"))
                ->will($this->returnValue("ok"));

        $res = $logoutSuccessHandler->onAuthenticationSuccess($request, $this->token);

        $this->assertEquals("ok", $res);
    }

    public function testIsAdmin()
    {
        $logoutSuccessHandler = $this->getAuthenticationSuccessHandler();

        $this->securityContext->expects($this->once())
                ->method("isGranted")
                ->with($this->equalTo("ROLE_ADMIN"))
                ->will($this->returnValue(true));

        $request = new Request();
        $session = $this->getMock("Symfony\Component\HttpFoundation\Session\Session");
        $session->expects($this->once())
                ->method("has")
                ->with($this->equalTo("_security.securitytest.target_path"))
                ->will($this->returnValue(false));
        $request->setSession($session);

        $this->token->expects($this->once())
                ->method("getProviderKey")
                ->will($this->returnValue("securitytest"));

        $this->httpUtils->expects($this->once())
                ->method("createRedirectResponse")
                ->with($this->callback(function($o) {
                            return $o instanceof \Symfony\Component\HttpFoundation\Request;
                        }), $this->equalTo("oicp_admin_index"))
                ->will($this->returnValue("ok"));

        $res = $logoutSuccessHandler->onAuthenticationSuccess($request, $this->token);

        $this->assertEquals("ok", $res);
    }

    public function testIsSimpleUser()
    {
        $logoutSuccessHandler = $this->getAuthenticationSuccessHandler();

        $this->securityContext->expects($this->once())
                ->method("isGranted")
                ->with($this->equalTo("ROLE_ADMIN"))
                ->will($this->returnValue(false));

        $request = new Request();
        $session = $this->getMock("Symfony\Component\HttpFoundation\Session\Session");
        $session->expects($this->once())
                ->method("has")
                ->with($this->equalTo("_security.securitytest.target_path"))
                ->will($this->returnValue(false));
        $request->setSession($session);

        $this->token->expects($this->once())
                ->method("getProviderKey")
                ->will($this->returnValue("securitytest"));

        $this->httpUtils->expects($this->once())
                ->method("createRedirectResponse")
                ->with($this->callback(function($o) {
                            return $o instanceof \Symfony\Component\HttpFoundation\Request;
                        }), $this->equalTo("oicp_account_index"))
                ->will($this->returnValue("ok"));

        $res = $logoutSuccessHandler->onAuthenticationSuccess($request, $this->token);

        $this->assertEquals("ok", $res);
    }

    private function getAuthenticationSuccessHandler()
    {
        $this->securityContext = $this->getMock("Symfony\Component\Security\Core\SecurityContextInterface");
        $this->httpUtils = $this->getMock("Symfony\Component\Security\Http\HttpUtils");
        $this->token = $this->getMockBuilder("Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken")
                ->disableOriginalConstructor()
                ->getMock();

        return new AuthenticationSuccessHandler($this->securityContext, $this->httpUtils);
    }

}


text:
"""Build a project using PEP 517 hooks.
"""
import argparse
import logging
import os
import contextlib
from pip._vendor import pytoml
import shutil
import errno
import tempfile

from .envbuild import BuildEnvironment
from .wrappers import Pep517HookCaller

log = logging.getLogger(__name__)

@contextlib.contextmanager
def tempdir():
    td = tempfile.mkdtemp()
    try:
        yield td
    finally:
        shutil.rmtree(td)

def _do_build(hooks, env, dist, dest):
    get_requires_name = 'get_requires_for_build_{dist}'.format(**locals())
    get_requires = getattr(hooks, get_requires_name)
    reqs = get_requires({})
    log.info('Got build requires: %s', reqs)

    env.pip_install(reqs)
    log.info('Installed dynamic build dependencies')

    with tempdir() as td:
        log.info('Trying to build %s in %s', dist, td)
        build_name = 'build_{dist}'.format(**locals())
        build = getattr(hooks, build_name)
        filename = build(td, {})
        source = os.path.join(td, filename)
        shutil.move(source, os.path.join(dest, os.path.basename(filename)))

def mkdir_p(*args, **kwargs):
    """Like `mkdir`, but does not raise an exception if the
    directory already exists.
    """
    try:
        return os.mkdir(*args, **kwargs)
    except OSError as exc:
        if exc.errno != errno.EEXIST:
            raise

def build(source_dir, dist, dest=None):
    pyproject = os.path.join(source_dir, 'pyproject.toml')
    dest = os.path.join(source_dir, dest or 'dist')
    mkdir_p(dest)

    with open(pyproject) as f:
        pyproject_data = pytoml.load(f)
    # Ensure the mandatory data can be loaded
    buildsys = pyproject_data['build-system']
    requires = buildsys['requires']
    backend = buildsys['build-backend']

    hooks = Pep517HookCaller(source_dir, backend)

    with BuildEnvironment() as env:
        env.pip_install(requires)
        _do_build(hooks, env, dist, dest)

parser = argparse.ArgumentParser()
parser.add_argument(
    'source_dir',
    help="A directory containing pyproject.toml",
)
parser.add_argument(
    '--binary', '-b',
    action='store_true',
    default=False,
)
parser.add_argument(
    '--source', '-s',
    action='store_true',
    default=False,
)
parser.add_argument(
    '--out-dir', '-o',
    help="Destination in which to save the builds relative to source dir",
)

def main(args):
    # determine which dists to build
    dists = list(filter(None, (
        'sdist' if args.source or not args.binary else None,
        'wheel' if args.binary or not args.source else None,
    )))

    for dist in dists:
        build(args.source_dir, dist, args.out_dir)

if __name__ == '__main__':
    main(parser.parse_args())