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

goog.provide('goog.ui.editor.EquationEditorDialog');

goog.require('goog.editor.Command');
goog.require('goog.ui.Dialog');
goog.require('goog.ui.editor.AbstractDialog');
goog.require('goog.ui.editor.EquationEditorOkEvent');
goog.require('goog.ui.equation.TexEditor');

/**
 * Equation editor dialog (based on goog.ui.editor.AbstractDialog).
 * @param {Object} context The context that this dialog runs in.
 * @param {goog.dom.DomHelper} domHelper DomHelper to be used to create the
 *     dialog's dom structure.
 * @param {string} equation Initial equation.
 * @param {string} helpUrl URL pointing to help documentation.
 * @constructor
 * @extends {goog.ui.editor.AbstractDialog}
 */
goog.ui.editor.EquationEditorDialog = function(context, domHelper,
    equation, helpUrl) {
  goog.ui.editor.AbstractDialog.call(this, domHelper);
  this.equationEditor_ =
      new goog.ui.equation.TexEditor(context, helpUrl, domHelper);
  this.equationEditor_.render();
  this.equationEditor_.setEquation(equation);
  this.equationEditor_.addEventListener(goog.editor.Command.EQUATION,
      this.onChange_, false, this);
};
goog.inherits(goog.ui.editor.EquationEditorDialog,
    goog.ui.editor.AbstractDialog);

/**
 * The equation editor actual UI.
 * @type {goog.ui.equation.TexEditor}
 * @private
 */
goog.ui.editor.EquationEditorDialog.prototype.equationEditor_;

/**
 * The dialog's OK button element.
 * @type {Element?}
 * @private
 */
goog.ui.editor.EquationEditorDialog.prototype.okButton_;

/** @override */
goog.ui.editor.EquationEditorDialog.prototype.createDialogControl =
    function() {
  var builder = new goog.ui.editor.AbstractDialog.Builder(this);

  /**
   * @desc The title of the equation editor dialog.
   */
  var MSG_EE_DIALOG_TITLE = goog.getMsg('Equation Editor');

  /**
   * @desc Button label for the equation editor dialog for adding
   * a new equation.
   */
  var MSG_EE_BUTTON_SAVE_NEW = goog.getMsg('Insert equation');

  /**
   * @desc Button label for the equation editor dialog for saving
   * a modified equation.
   */
  var MSG_EE_BUTTON_SAVE_MODIFY = goog.getMsg('Save changes');

  var okButtonText = this.equationEditor_.getEquation() ?
      MSG_EE_BUTTON_SAVE_MODIFY : MSG_EE_BUTTON_SAVE_NEW;

  builder.setTitle(MSG_EE_DIALOG_TITLE)
    .setContent(this.equationEditor_.getElement())
    .addOkButton(okButtonText)
    .addCancelButton();

  return builder.build();
};

/**
 * @override
 */
goog.ui.editor.EquationEditorDialog.prototype.createOkEvent = function(e) {
  if (this.equationEditor_.isValid()) {
    // Equation is not valid, don't close the dialog.
    return null;
  }
  var equationHtml = this.equationEditor_.getHtml();
  return new goog.ui.editor.EquationEditorOkEvent(equationHtml);
};

/**
 * Handles CHANGE event fired when user changes equation.
 * @param {goog.ui.equation.ChangeEvent} e The event object.
 * @private
 */
goog.ui.editor.EquationEditorDialog.prototype.onChange_ = function(e) {
  if (!this.okButton_) {
    this.okButton_ = this.getButtonElement(
        goog.ui.Dialog.DefaultButtonKeys.OK);
  }
  this.okButton_.disabled = !e.isValid;
};


text:
package com.opengamma.livedata.server;

import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;

import org.fudgemsg.FudgeMsg;
import org.fudgemsg.MutableFudgeMsg;
import org.testng.annotations.Test;

import com.opengamma.id.ExternalId;
import com.opengamma.util.fudgemsg.OpenGammaFudgeContext;
import com.opengamma.util.test.TestGroup;

/**
 * A full unit test for {@link RedisLastKnownValueStoreProvider} and
 * also {@link RedisLastKnownValueStore}.
 */
@Test(groups = TestGroup.INTEGRATION)
public class RedisLastKnownValueStoreProviderTest {
  // TODO kirk 2012-07-18 -- This needs to be moved to external properties.
  private static final String REDIS_SERVER = "redis-lx-1";

  static String generatePrefix(String testName) {
    StringBuilder sb = new StringBuilder();
    sb.append(System.getProperty("user.name"));
    sb.append("-");
    sb.append(testName);
    sb.append("-");
    sb.append(System.currentTimeMillis());
    sb.append("-");
    return sb.toString();
  }

  // TODO kirk 2012-07-18 -- This needs to be restricted to times where there's a Redis
  // server available for testing.
  @Test
  public void testBasicFunctionality() {
    RedisLastKnownValueStoreProvider provider = new RedisLastKnownValueStoreProvider();
    provider.setServer(REDIS_SERVER);
    provider.setGlobalPrefix(generatePrefix("testBasicFunctionality"));
    provider.setWriteThrough(true);

    MutableFudgeMsg msg = OpenGammaFudgeContext.getInstance().newMessage();

    LastKnownValueStore store = provider.newInstance(ExternalId.of("Test", "testBasicFunctionality"), "no-norm");
    FudgeMsg currFields = store.getFields();
    assertTrue(currFields.isEmpty());

    msg.add("bid", 1.0d);
    msg.add("ask", 2.0d);

    store.updateFields(msg);

    currFields = store.getFields();
    assertEquals(1.0d, currFields.getDouble("bid"), 0.0005d);
    assertEquals(2.0d, currFields.getDouble("ask"), 0.0005d);

    // Reset the store.
    store = provider.newInstance(ExternalId.of("Test", "testBasicFunctionality"), "no-norm");
    currFields = store.getFields();
    assertEquals(1.0d, currFields.getDouble("bid"), 0.0005d);
    assertEquals(2.0d, currFields.getDouble("ask"), 0.0005d);

    // Write through another value and confirm it works.
    msg = OpenGammaFudgeContext.getInstance().newMessage();
    msg.add("bid", 5.0d);
    store.updateFields(msg);

    store = provider.newInstance(ExternalId.of("Test", "testBasicFunctionality"), "no-norm");
    currFields = store.getFields();
    assertEquals(5.0d, currFields.getDouble("bid"), 0.0005d);
    assertEquals(2.0d, currFields.getDouble("ask"), 0.0005d);

    // Reset the store. This time don't write through.
    provider.setWriteThrough(false);
    store = provider.newInstance(ExternalId.of("Test", "testBasicFunctionality"), "no-norm");
    currFields = store.getFields();
    assertEquals(5.0d, currFields.getDouble("bid"), 0.0005d);
    assertEquals(2.0d, currFields.getDouble("ask"), 0.0005d);

    msg = OpenGammaFudgeContext.getInstance().newMessage();
    msg.add("bid", 3.0d);
    msg.add("ask", 4.0d);
    store.updateFields(msg);
    currFields = store.getFields();
    assertEquals(3.0d, currFields.getDouble("bid"), 0.0005d);
    assertEquals(4.0d, currFields.getDouble("ask"), 0.0005d);

    // Reset the store.
    store = provider.newInstance(ExternalId.of("Test", "testBasicFunctionality"), "no-norm");
    currFields = store.getFields();
    assertEquals(5.0d, currFields.getDouble("bid"), 0.0005d);
    assertEquals(2.0d, currFields.getDouble("ask"), 0.0005d);
  }

}

redpajama_set_name: RedPajamaGithub


text:
package com.a21vianet.wallet.vport.common;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.widget.Toast;

import com.littlesparkle.growler.core.ui.activity.BaseActivity;
import com.littlesparkle.growler.core.ui.listener.PermissionRequestCallBack;
import com.littlesparkle.growler.core.ui.toast.ToastFactory;

import java.util.List;

/**
 * Created by wang.rongqiang on 2017/7/5.
 */

public class ActivityStartUtility {
    public static void startScanActivity(final Activity activity, final Intent intent, final int code) {
        String[] permissions = {Manifest.permission.CAMERA};
        BaseActivity.requestRuntimePermission(permissions, new PermissionRequestCallBack() {
            @Override
            public void onGranted() {
                activity.startActivityForResult(intent, code);
            }

            @Override
            public void onDenied(List<String> deniedPermission) {
                ToastFactory.getInstance(activity).makeTextShow("没有使用相机的权限,请在权限管理中开启", Toast.LENGTH_LONG);
            }
        });

    }
}


text:
package org.broadinstitute.hellbender.cmdline;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * This collection is for arguments that require special treatment by the arguments parser itself.
 * It should not grow beyond a very short list.
 */
public final class SpecialArgumentsCollection implements ArgumentCollectionDefinition {
    public static final String HELP_FULLNAME = "help";
    public static final String VERSION_FULLNAME = "version";
    public static final String ARGUMENTS_FILE_FULLNAME = "arguments_file";
    private static final long serialVersionUID = 1L;

    @Argument(shortName = "h", fullName = HELP_FULLNAME, doc= "display the help message", special = true)
    public boolean HELP = false;

    @Argument(fullName = VERSION_FULLNAME, doc="display the version number for this tool", special = true)
    public boolean VERSION = false;

    @Argument(fullName = ARGUMENTS_FILE_FULLNAME, doc="read one or more arguments files and add them to the command line", optional = true, special = true)
    public List<File> ARGUMENTS_FILE = new ArrayList<>();

}


text:
angular
  .module('Mobidul')
  .controller('CloneMobidulDialogController', CloneMobidulDialogController);

CloneMobidulDialogController.$inject = [
  '$log', '$scope', '$mdDialog', '$translate',
  'MobidulService', 'CreatorService',
  'UtilityService'
];

function CloneMobidulDialogController (
  $log, $scope, $mdDialog, $translate,
  MobidulService, CreatorService,
  UtilityService
) {
  /// CloneMobidulDialogController
  var cloneMobidulDialog = this;

  // constants
  // NOTE: TODO: Code duplication w/ CreatorController
  cloneMobidulDialog._codeHelperGenerating = $translate.instant('CREATING');
  cloneMobidulDialog._codeHelperGenerated  = $translate.instant('AUTOMATICALLY_CREATED');
  cloneMobidulDialog._codeHelperManual     = $translate.instant('MANUALLY_CREATED');

  // vars
  cloneMobidulDialog.canNotSave = false;

  cloneMobidulDialog.mobidul = {
    name: MobidulService.Mobidul.mobidulName,
    code: MobidulService.Mobidul.mobidulCode,
    link: 'www.mobilot.at',

    originalCode: MobidulService.Mobidul.mobidulCode,
    generateCode: false,

    codeHelper: {
      show: false,
      text: '',
    }
  };

  // functions
  cloneMobidulDialog.close        = close;
  cloneMobidulDialog.changeName   = changeName;
  cloneMobidulDialog.changeCode   = changeCode;
  cloneMobidulDialog.cloneMobidul = cloneMobidul;

  /// constructor

  _init();

  /// private functions

  function _init () {
    $log.debug('CloneMobidulDialogController init');
  }

  // NOTE: TODO: Code duplication w/ CreatorController
  function _isOriginalCode (mobidulCode) {
    return mobidulCode === cloneMobidulDialog.mobidul.originalCode;
  }

  // NOTE: TODO: Code duplication w/ CreatorController
  function _refreshCodeHelper (mobidulCode, codeHelperText) {
    var isOriginalCode = _isOriginalCode(mobidulCode);

    if (isOriginalCode) {
      cloneMobidulDialog.mobidul.codeHelper.text = '';
    } else {
      cloneMobidulDialog.mobidul.codeHelper.text = codeHelperText;
    }

    cloneMobidulDialog.mobidul.codeHelper.show = ! isOriginalCode;
  }

  // NOTE: TODO: Code duplication w/ CreatorController
  function _resetCodeHelper () {
    cloneMobidulDialog.mobidul.codeHelper.show = false;
    cloneMobidulDialog.mobidul.codeHelper.text = '';
  }

  // NOTE: TODO: Code duplication w/ CreatorController
  function _restoreOriginalStationCode () {
    cloneMobidulDialog.mobidul.code = cloneMobidulDialog.mobidul.originalCode;

    _resetCodeHelper();
  }

  /// public functions

  function close () {
    $mdDialog.hide();
  }

  function changeName () {
    var mobidulName = cloneMobidulDialog.mobidul.name.trim();
    var mobidulCode = UtilityService.getCodeFromName(mobidulName);

    if (mobidulCode) {
      cloneMobidulDialog.mobidul.codeHelper.text =
        cloneMobidulDialog._codeHelperGenerating;
    }

    if ( ! _isOriginalCode(mobidulCode) ) {
      CreatorService.existsMobidul(mobidulCode)
      .success(function (response, status, headers, config) {
        //$log.debug('existsMobidul success response: ');
        //$log.debug(response);

        // TODO: add exists from the responseobject
        //$log.debug('response.exists: ' + response.exists);

        cloneMobidulDialog.canNotSave = response.exists;
        mobidulCode = response.mobidulCode;

        if (mobidulCode) {
          cloneMobidulDialog.mobidul.code = mobidulCode;

          _refreshCodeHelper(
            mobidulCode,
            cloneMobidulDialog._codeHelperGenerated
          );
        } else {
          cloneMobidulDialog.mobidul.code = '';

          _resetCodeHelper();
        }
      });
    } else {
      _restoreOriginalStationCode();
    }
  }

  function changeCode () {
    $log.debug('CloneMobidulDialog changeCode:')
  }

  function cloneMobidul () {
    var params = {
      oldCode:  MobidulService.Mobidul.mobidulCode,
      name:     cloneMobidulDialog.mobidul.name,
      code:     cloneMobidulDialog.mobidul.code
    };

    MobidulService.cloneMobidul(params)
    .then(function (response, status, headers, config, statusText) {
      if (response.data.success) {
        var successDialog = $mdDialog.alert()
        .parent( angular.element(document.body) )
        .clickOutsideToClose(true)
        .title($translate.instant('SAY_TITLE'))
        .textContent($translate.instant('CLONE_INFO_SUCCESS'))
        .ariaLabel($translate.instant('SAY_TITLE'))
        .ok($translate.instant('CLOSE'));

        $mdDialog.show(successDialog);

        cloneMobidulDialog.close();
      } else {
        $log.info($response.data.msg);
      }
    });
  }

  // ...
}


text:
package io.pravega.client.batch.impl;

import com.google.common.annotations.Beta;
import io.pravega.client.batch.SegmentIterator;
import io.pravega.client.segment.impl.EventSegmentReader;
import io.pravega.client.segment.impl.NoSuchSegmentException;
import io.pravega.client.segment.impl.Segment;
import io.pravega.client.segment.impl.SegmentInputStreamFactory;
import io.pravega.client.segment.impl.SegmentTruncatedException;
import io.pravega.client.stream.Serializer;
import io.pravega.client.stream.TruncatedDataException;

import java.nio.ByteBuffer;
import java.util.NoSuchElementException;
import java.util.concurrent.TimeoutException;

import io.pravega.common.util.Retry;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

@Beta
@Slf4j
public class SegmentIteratorImpl<T> implements SegmentIterator<T> {

    private final Segment segment;
    private final Serializer<T> deserializer;
    @Getter
    private final long startingOffset;
    private final long endingOffset;
    private final EventSegmentReader input;
    private final Retry.RetryWithBackoff backoffSchedule = Retry.withExpBackoff(1, 10, 9, 30000);

    public SegmentIteratorImpl(SegmentInputStreamFactory factory, Segment segment,
            Serializer<T> deserializer, long startingOffset, long endingOffset) {
        this.segment = segment;
        this.deserializer = deserializer;
        this.startingOffset = startingOffset;
        this.endingOffset = endingOffset;
        input = factory.createEventReaderForSegment(segment, startingOffset, endingOffset);
    }

    @Override
    public boolean hasNext() {
        return input.getOffset() < endingOffset;
    }

    @Override
    public T next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }

        // retry in-case of an empty ByteBuffer
        ByteBuffer read =
                backoffSchedule.retryWhen(t -> t instanceof TimeoutException)
                               .run(() -> {
                                   try {
                                       ByteBuffer buffer = input.read();
                                       if (buffer == null) {
                                           log.warn("Empty buffer while reading from Segment {} at offset {}",
                                                   input.getSegmentId(), input.getOffset());
                                           throw new TimeoutException(input.toString());
                                       }
                                       return buffer;
                                   } catch (NoSuchSegmentException | SegmentTruncatedException e) {
                                       throw new TruncatedDataException("Segment " + segment + " has been truncated.");
                                   }
                               });

        return deserializer.deserialize(read);
    }

    @Override
    public long getOffset() {
        return input.getOffset();
    }

    @Override
    public void close() {
        input.close();
    }

}


text:
package org.uct.cs.simplify.model;

import org.uct.cs.simplify.ply.header.PLYElement;
import org.uct.cs.simplify.ply.reader.PLYReader;
import org.uct.cs.simplify.util.ReliableBufferedInputStream;

import java.io.FileInputStream;
import java.io.IOException;

public class SimpleVertexReader extends StreamingVertexReader implements AutoCloseable
{
    protected final PLYReader reader;
    protected final PLYElement vertexElement;
    protected final VertexAttrMap vam;
    protected final long start;
    protected final int blockSize;
    protected final byte[] blockBuffer;
    protected final long count;
    protected final long itercount;
    protected final ReliableBufferedInputStream istream;
    protected final long nth;
    protected final long skip;
    protected final long skipBytes;
    protected long index;

    public SimpleVertexReader(PLYReader reader) throws IOException
    {
        this(reader, 1);
    }

    public SimpleVertexReader(PLYReader reader, long nth) throws IOException
    {
        if (nth < 1) throw new IllegalArgumentException("nth must be at least 1");

        this.nth = nth;
        this.skip = nth - 1;
        this.reader = reader;
        this.vertexElement = reader.getHeader().getElement("vertex");
        this.count = this.vertexElement.getCount();
        this.itercount = (nth == 1) ? this.count : (long) Math.ceil(this.count / (double) this.nth);

        this.vam = new VertexAttrMap(this.vertexElement);

        this.start = reader.getElementDimension("vertex").getOffset();

        this.istream = new ReliableBufferedInputStream(new FileInputStream(reader.getFile()));
        this.istream.skip(this.start);
        this.blockSize = this.vertexElement.getItemSize();
        this.blockBuffer = new byte[ this.blockSize ];
        this.skipBytes = this.skip * this.blockSize;
    }

    @Override
    public boolean hasNext()
    {
        return this.index < this.count;
    }

    @Override
    public Vertex next() throws IOException
    {
        Vertex v = new Vertex(0, 0, 0);
        next(v);
        return v;
    }

    @Override
    public void next(Vertex v) throws IOException
    {
        this.istream.read(this.blockBuffer, 0, this.blockSize);
        v.read(blockBuffer, vam);
        this.index += nth;
        this.istream.skip(this.skipBytes);
    }

    public long getSampling()
    {
        return this.itercount;
    }

    @Override
    public long getCount()
    {
        return this.count;
    }

    @Override
    public void close() throws IOException
    {
        this.istream.close();
    }

    @Override
    public VertexAttrMap getVam()
    {
        return this.vam;
    }

}


text:
{-|
Module      : IRTS.JavaScript.Specialize
Description : The JavaScript specializer.
Copyright   :
License     : BSD3
Maintainer  : The Idris Community.
-}

{-# LANGUAGE OverloadedStrings, PatternGuards #-}

module IRTS.JavaScript.Specialize
  ( SCtor
  , STest
  , SProj
  , specialCased
  , specialCall
  , qualifyN
  ) where

import Data.Char
import Data.List
import qualified Data.Map.Strict as Map
import Data.Text (Text)
import qualified Data.Text as T
import Idris.Core.TT
import IRTS.JavaScript.AST

split :: Char -> String -> [String]
split c "" = [""]
split c (x:xs)
  | c == x = "" : split c xs
  | otherwise =
    let ~(h:t) = split c xs
    in ((x : h) : t)

qualify :: String -> Name -> Name
qualify "" n = n
qualify ns n = sNS n (reverse $ split '.' ns)

qualifyN :: String -> String -> Name
qualifyN ns n = qualify ns $ sUN n

-- special-cased constructors
type SCtor = [JsExpr] -> JsExpr

type STest = JsExpr -> JsExpr

type SProj = JsExpr -> Int -> JsExpr

constructorOptimizeDB :: Map.Map Name (SCtor, STest, SProj)
constructorOptimizeDB =
  Map.fromList
    [ item "Prelude.Bool" "True" (const $ JsBool True) trueTest cantProj
    , item "Prelude.Bool" "False" (const $ JsBool False) falseTest cantProj
    , item "Prelude.Interfaces" "LT" (const $ JsInt (0-1)) ltTest cantProj
    , item "Prelude.Interfaces" "EQ" (const $ JsInt 0) eqTest cantProj
    , item "Prelude.Interfaces" "GT" (const $ JsInt 1) gtTest cantProj
    -- , item "Prelude.List" "::" cons fillList uncons
    -- , item "Prelude.List" "Nil" nil emptyList cantProj
    -- , item "Prelude.Maybe" "Just" (\[x] -> x) notNoneTest justProj
    -- , item "Prelude.Maybe" "Nothing" (const $ JsUndefined) noneTest cantProj
    ]
    -- constructors
  where
    nil = const $ JsArray []
    cons [h, t] = JsMethod (JsArray [h]) "concat" [t]
    -- tests
    --trueTest e = JsUniOp (T.pack "!") $ JsUniOp (T.pack "!") e
    trueTest = id
    falseTest e = JsUniOp (T.pack "!") e
    emptyList e = JsBinOp "===" (JsProp e "length") (JsInt 0)
    fillList e = JsBinOp ">" (JsProp e "length") (JsInt 0)
    ltTest e = JsBinOp "<" e (JsInt 0)
    eqTest e = JsBinOp "===" e (JsInt 0)
    gtTest e = JsBinOp ">" e (JsInt 0)
    noneTest e = JsBinOp "===" e JsUndefined
    notNoneTest e = JsBinOp "!==" e JsUndefined
    -- projections
    justProj x n = x
    uncons x 1 = JsArrayProj (JsInt 0) x
    uncons x 2 = JsMethod x "slice" [JsInt 1]
    cantProj x j = error $ "This type should be projected"
    item :: String
         -> String
         -> SCtor
         -> STest
         -> SProj
         -> (Name, (SCtor, STest, SProj))
    item ns n ctor test match = (qualifyN ns n, (ctor, test, match))

specialCased :: Name -> Maybe (SCtor, STest, SProj)
specialCased n = Map.lookup n constructorOptimizeDB

-- special functions
type SSig = (Int, [JsExpr] -> JsExpr)

callSpecializeDB :: Map.Map Name (SSig)
callSpecializeDB =
  Map.fromList
    [ qb "Eq" "Int" "==" "==="
    , qb "Ord" "Int" "<" "<"
    , qb "Ord" "Int" ">" ">"
    , qb "Ord" "Int" "<=" "<="
    , qb "Ord" "Int" ">=" ">="
    , qb "Eq" "Double" "==" "==="
    , qb "Ord" "Double" "<" "<"
    , qb "Ord" "Double" ">" ">"
    , qb "Ord" "Double" "<=" "<="
    , qb "Ord" "Double" ">=" ">="
    ]
  where
    qb intf ty op jsop =
      ( qualify "Prelude.Interfaces" $
        SN $
        WhereN
          0
          (qualify "Prelude.Interfaces" $
           SN $ ImplementationN (qualifyN "Prelude.Interfaces" intf) [ty])
          (SN $ MethodN $ UN op)
      , (2, \[x, y] -> JsBinOp jsop x y))

specialCall :: Name -> Maybe SSig
specialCall n = Map.lookup n callSpecializeDB


text:
/* $OpenBSD: md32_common.h,v 1.22 2016/11/04 13:56:04 miod Exp $ */
/* ====================================================================
 * Copyright (c) 1999-2007 The OpenSSL Project.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. 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.
 *
 * 3. All advertising materials mentioning features or use of this
 *    software must display the following acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
 *
 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
 *    endorse or promote products derived from this software without
 *    prior written permission. For written permission, please contact
 *    licensing@OpenSSL.org.
 *
 * 5. Products derived from this software may not be called "OpenSSL"
 *    nor may "OpenSSL" appear in their names without prior written
 *    permission of the OpenSSL Project.
 *
 * 6. Redistributions of any form whatsoever must retain the following
 *    acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
 *
 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
 * EXPRESSED 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 OpenSSL PROJECT OR
 * ITS 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.
 * ====================================================================
 *
 */

/*
 * This is a generic 32 bit "collector" for message digest algorithms.
 * Whenever needed it collects input character stream into chunks of
 * 32 bit values and invokes a block function that performs actual hash
 * calculations.
 *
 * Porting guide.
 *
 * Obligatory macros:
 *
 * DATA_ORDER_IS_BIG_ENDIAN or DATA_ORDER_IS_LITTLE_ENDIAN
 *	this macro defines byte order of input stream.
 * HASH_CBLOCK
 *	size of a unit chunk HASH_BLOCK operates on.
 * HASH_LONG
 *	has to be at least 32 bit wide.
 * HASH_CTX
 *	context structure that at least contains following
 *	members:
 *		typedef struct {
 *			...
 *			HASH_LONG	Nl,Nh;
 *			either {
 *			HASH_LONG	data[HASH_LBLOCK];
 *			unsigned char	data[HASH_CBLOCK];
 *			};
 *			unsigned int	num;
 *			...
 *			} HASH_CTX;
 *	data[] vector is expected to be zeroed upon first call to
 *	HASH_UPDATE.
 * HASH_UPDATE
 *	name of "Update" function, implemented here.
 * HASH_TRANSFORM
 *	name of "Transform" function, implemented here.
 * HASH_FINAL
 *	name of "Final" function, implemented here.
 * HASH_BLOCK_DATA_ORDER
 *	name of "block" function capable of treating *unaligned* input
 *	message in original (data) byte order, implemented externally.
 * HASH_MAKE_STRING
 *	macro convering context variables to an ASCII hash string.
 *
 * MD5 example:
 *
 *	#define DATA_ORDER_IS_LITTLE_ENDIAN
 *
 *	#define HASH_LONG		MD5_LONG
 *	#define HASH_CTX		MD5_CTX
 *	#define HASH_CBLOCK		MD5_CBLOCK
 *	#define HASH_UPDATE		MD5_Update
 *	#define HASH_TRANSFORM		MD5_Transform
 *	#define HASH_FINAL		MD5_Final
 *	#define HASH_BLOCK_DATA_ORDER	md5_block_data_order
 *
 *					<appro@fy.chalmers.se>
 */

#include <stdint.h>

#include <openssl/opensslconf.h>

#if !defined(DATA_ORDER_IS_BIG_ENDIAN) && !defined(DATA_ORDER_IS_LITTLE_ENDIAN)
#error "DATA_ORDER must be defined!"
#endif

#ifndef HASH_CBLOCK
#error "HASH_CBLOCK must be defined!"
#endif
#ifndef HASH_LONG
#error "HASH_LONG must be defined!"
#endif
#ifndef HASH_CTX
#error "HASH_CTX must be defined!"
#endif

#ifndef HASH_UPDATE
#error "HASH_UPDATE must be defined!"
#endif
#ifndef HASH_TRANSFORM
#error "HASH_TRANSFORM must be defined!"
#endif
#if !defined(HASH_FINAL) && !defined(HASH_NO_FINAL)
#error "HASH_FINAL or HASH_NO_FINAL must be defined!"
#endif

#ifndef HASH_BLOCK_DATA_ORDER
#error "HASH_BLOCK_DATA_ORDER must be defined!"
#endif

/*
 * This common idiom is recognized by the compiler and turned into a
 * CPU-specific intrinsic as appropriate.
 * e.g. GCC optimizes to roll on amd64 at -O0
 */
static inline uint32_t ROTATE(uint32_t a, uint32_t n)
{
	return (a<<n)|(a>>(32-n));
}

#if defined(DATA_ORDER_IS_BIG_ENDIAN)

#if defined(__GNUC__) && __GNUC__>=2 && !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM)
# if (defined(__i386) || defined(__i386__) || \
      defined(__x86_64) || defined(__x86_64__))
    /*
     * This gives ~30-40% performance improvement in SHA-256 compiled
     * with gcc [on P4]. Well, first macro to be frank. We can pull
     * this trick on x86* platforms only, because these CPUs can fetch
     * unaligned data without raising an exception.
     */
#  define HOST_c2l(c,l)	({ unsigned int r=*((const unsigned int *)(c));	\
				   asm ("bswapl %0":"=r"(r):"0"(r));	\
				   (c)+=4; (l)=r;			})
#  define HOST_l2c(l,c)	({ unsigned int r=(l);			\
				   asm ("bswapl %0":"=r"(r):"0"(r));	\
				   *((unsigned int *)(c))=r; (c)+=4;	})
# endif
#endif

#ifndef HOST_c2l
#define HOST_c2l(c,l) do {l =(((unsigned long)(*((c)++)))<<24);	\
			  l|=(((unsigned long)(*((c)++)))<<16);	\
			  l|=(((unsigned long)(*((c)++)))<< 8);	\
			  l|=(((unsigned long)(*((c)++)))    );	\
		      } while (0)
#endif
#ifndef HOST_l2c
#define HOST_l2c(l,c) do {*((c)++)=(unsigned char)(((l)>>24)&0xff);	\
			  *((c)++)=(unsigned char)(((l)>>16)&0xff);	\
			  *((c)++)=(unsigned char)(((l)>> 8)&0xff);	\
			  *((c)++)=(unsigned char)(((l)    )&0xff);	\
		      } while (0)
#endif

#elif defined(DATA_ORDER_IS_LITTLE_ENDIAN)

#if defined(__i386) || defined(__i386__) || defined(__x86_64) || defined(__x86_64__)
#  define HOST_c2l(c,l)	((l)=*((const unsigned int *)(c)), (c)+=4)
#  define HOST_l2c(l,c)	(*((unsigned int *)(c))=(l), (c)+=4)
#endif

#ifndef HOST_c2l
#define HOST_c2l(c,l) do {l =(((unsigned long)(*((c)++)))    );	\
			  l|=(((unsigned long)(*((c)++)))<< 8);	\
			  l|=(((unsigned long)(*((c)++)))<<16);	\
			  l|=(((unsigned long)(*((c)++)))<<24);	\
		      } while (0)
#endif
#ifndef HOST_l2c
#define HOST_l2c(l,c) do {*((c)++)=(unsigned char)(((l)    )&0xff);	\
			  *((c)++)=(unsigned char)(((l)>> 8)&0xff);	\
			  *((c)++)=(unsigned char)(((l)>>16)&0xff);	\
			  *((c)++)=(unsigned char)(((l)>>24)&0xff);	\
		      } while (0)
#endif

#endif

/*
 * Time for some action:-)
 */

int
HASH_UPDATE(HASH_CTX *c, const void *data_, size_t len)
{
	const unsigned char *data = data_;
	unsigned char *p;
	HASH_LONG l;
	size_t n;

	if (len == 0)
		return 1;

	l = (c->Nl + (((HASH_LONG)len) << 3))&0xffffffffUL;
	/* 95-05-24 eay Fixed a bug with the overflow handling, thanks to
	 * Wei Dai <weidai@eskimo.com> for pointing it out. */
	if (l < c->Nl) /* overflow */
		c->Nh++;
	c->Nh+=(HASH_LONG)(len>>29);	/* might cause compiler warning on 16-bit */
	c->Nl = l;

	n = c->num;
	if (n != 0) {
		p = (unsigned char *)c->data;

		if (len >= HASH_CBLOCK || len + n >= HASH_CBLOCK) {
			memcpy (p + n, data, HASH_CBLOCK - n);
			HASH_BLOCK_DATA_ORDER (c, p, 1);
			n = HASH_CBLOCK - n;
			data += n;
			len -= n;
			c->num = 0;
			memset (p,0,HASH_CBLOCK);	/* keep it zeroed */
		} else {
			memcpy (p + n, data, len);
			c->num += (unsigned int)len;
			return 1;
		}
	}

	n = len/HASH_CBLOCK;
	if (n > 0) {
		HASH_BLOCK_DATA_ORDER (c, data, n);
		n    *= HASH_CBLOCK;
		data += n;
		len -= n;
	}

	if (len != 0) {
		p = (unsigned char *)c->data;
		c->num = (unsigned int)len;
		memcpy (p, data, len);
	}
	return 1;
}

void HASH_TRANSFORM (HASH_CTX *c, const unsigned char *data)
{
	HASH_BLOCK_DATA_ORDER (c, data, 1);
}

#ifndef HASH_NO_FINAL
int HASH_FINAL (unsigned char *md, HASH_CTX *c)
{
	unsigned char *p = (unsigned char *)c->data;
	size_t n = c->num;

	p[n] = 0x80; /* there is always room for one */
	n++;

	if (n > (HASH_CBLOCK - 8)) {
		memset (p + n, 0, HASH_CBLOCK - n);
		n = 0;
		HASH_BLOCK_DATA_ORDER (c, p, 1);
	}
	memset (p + n, 0, HASH_CBLOCK - 8 - n);

	p += HASH_CBLOCK - 8;
#if   defined(DATA_ORDER_IS_BIG_ENDIAN)
	HOST_l2c(c->Nh, p);
	HOST_l2c(c->Nl, p);
#elif defined(DATA_ORDER_IS_LITTLE_ENDIAN)
	HOST_l2c(c->Nl, p);
	HOST_l2c(c->Nh, p);
#endif
	p -= HASH_CBLOCK;
	HASH_BLOCK_DATA_ORDER (c, p, 1);
	c->num = 0;
	memset (p, 0, HASH_CBLOCK);

#ifndef HASH_MAKE_STRING
#error "HASH_MAKE_STRING must be defined!"
#else
	HASH_MAKE_STRING(c, md);
#endif

	return 1;
}
#endif

#ifndef MD32_REG_T
#if defined(__alpha) || defined(__sparcv9) || defined(__mips)
#define MD32_REG_T long
/*
 * This comment was originaly written for MD5, which is why it
 * discusses A-D. But it basically applies to all 32-bit digests,
 * which is why it was moved to common header file.
 *
 * In case you wonder why A-D are declared as long and not
 * as MD5_LONG. Doing so results in slight performance
 * boost on LP64 architectures. The catch is we don't
 * really care if 32 MSBs of a 64-bit register get polluted
 * with eventual overflows as we *save* only 32 LSBs in
 * *either* case. Now declaring 'em long excuses the compiler
 * from keeping 32 MSBs zeroed resulting in 13% performance
 * improvement under SPARC Solaris7/64 and 5% under AlphaLinux.
 * Well, to be honest it should say that this *prevents*
 * performance degradation.
 *				<appro@fy.chalmers.se>
 */
#else
/*
 * Above is not absolute and there are LP64 compilers that
 * generate better code if MD32_REG_T is defined int. The above
 * pre-processor condition reflects the circumstances under which
 * the conclusion was made and is subject to further extension.
 *				<appro@fy.chalmers.se>
 */
#define MD32_REG_T int
#endif
#endif


text:
var Montage = require("montage").Montage,
    Component = require("montage/ui/component").Component;

exports.Double = Component.specialize( {

    hasTemplate: {
        value: false
    },

    _value: {
        value: null
    },

    value: {
        get: function() {
            return this._value;
        },
        set: function(value) {
            if (this._value !== value) {
                this._value = value;
                this.needsDraw = true;
            }
        }
    },

    _secondValue: {
        value: null
    },

    secondValue: {
        get: function() {
            return this._secondValue;
        },
        set: function(value) {
            if (this._secondValue !== value) {
                this._secondValue = value;
                this.needsDraw = true;
            }
        }
    },

    /**
        The Montage converted used to convert or format values displayed by this Text instance.
        @type {Property}
        @default null
    */
    converter: {
        value: null
    },

    /**
        The default string value assigned to the Text instance.
        @type {Property}
        @default {string} ""
    */
    defaultValue: {
        value: ""
    },

    _valueNode: {
        value: null
    },

    _secondValueNode: {
        value: null
    },

    _RANGE: {
        value: document.createRange()
    },

    enterDocument: {
        value: function(firstTime) {
            if (firstTime) {
                var range = this._RANGE;
                range.selectNodeContents(this.element);
                range.deleteContents();
                this._valueNode = document.createTextNode("");
                range.insertNode(this._valueNode);
                this._secondValueNode = document.createTextNode("");
                range.insertNode(this._secondValueNode);
            }
        }
    },

    draw: {
        value: function() {
            // get correct value
            var value = this._value,
                displayValue = (value || 0 === value ) ? value : this.defaultValue;
            var secondValue = this._secondValue,
                secondDisplayValue = (secondValue || 0 === secondValue ) ? secondValue : this.defaultValue;

            if (this.converter) {
                displayValue = this.converter.convert(displayValue);
                secondDisplayValue = this.converter.convert(secondDisplayValue);
            }

            //push to DOM
            this._valueNode.data = displayValue;
            this._secondValueNode.data = secondDisplayValue;
        }
    }

});


text:
package com.neustar.ultraservice.schema.v01;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for DnssecKeyRecordList complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="DnssecKeyRecordList">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="DnssecKey" type="{http://schema.ultraservice.neustar.com/v01/}DnssecKey" maxOccurs="unbounded"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "DnssecKeyRecordList", propOrder = {
    "dnssecKey"
})
public class DnssecKeyRecordList {

    @XmlElement(name = "DnssecKey", required = true)
    protected List<DnssecKey> dnssecKey;

    /**
     * Gets the value of the dnssecKey property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the dnssecKey property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getDnssecKey().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link DnssecKey }
     *
     *
     */
    public List<DnssecKey> getDnssecKey() {
        if (dnssecKey == null) {
            dnssecKey = new ArrayList<DnssecKey>();
        }
        return this.dnssecKey;
    }

}


text:
<!DOCTYPE html>

    <title>Paul Laurence Dunbar | Lit2Go ETC</title>
    <link rel="stylesheet" href="http://etc.usf.edu/lit2go/css/screenless.css" type="text/css" media="screen" title="no title" charset="utf-8">
    <link rel="stylesheet" href="http://etc.usf.edu/lit2go/css/printless.css" type="text/css" media="print" title="no title" charset="utf-8">

          Lit2Go

<form action="http://etc.usf.edu/lit2go/search/"><input type="text" name="q" placeholder="Search" value=""></form>

Authors

Books

Genres

Collections

Readability

      Paul Laurence Dunbar

	Paul Laurence Dunbar was a seminal American poet of the late 19th and early 20th centuries. Dunbar gained national recognition for his 1896 book of poetry, Lyrics of a Lowly Life.

          Nationality: American

          Birth Date: 27 June 1872

          Death Date: 9 Feb 1906

          ✎ Cite This

  Share
  |

      Available Works

        The Heart of Happy Hollow (1904)

	The Heart of Happy Hollow is a short story collection by Paul Laurence Dunbar that focuses on the experiences of African-Americans after the conclusion of the Civil War.

        Humour and Dialect (1913)

	This is a collection of poetry by African American author Paul Laurence Dunbar. Dunbar's work frequently features a conversational tone, innovative rhetorical structure, and a colorful use of both dialect and mainstream English. Dunbar was among the first nationally successful African American writers.

        Lyrics of Love and Laughter (1913)

	This is a collection of poetry by African American author Paul Laurence Dunbar. Dunbar's work frequently features a conversational tone, innovative rhetorical structure, and a colorful use of both dialect and mainstream English. Dunbar was among the first nationally successful African American writers.

        Lyrics of Love and Sorrow (1913)

	This is a collection of poetry by African American author Paul Laurence Dunbar. Dunbar's work frequently features a conversational tone, innovative rhetorical structure, and a colorful use of both dialect and mainstream English. Dunbar was among the first nationally successful African American writers.

        Lyrics of Lowly Life (1913)

	This is a collection of poetry by African American author Paul Laurence Dunbar. Dunbar's work frequently features a conversational tone, innovative rhetorical structure, and a colorful use of both dialect and mainstream English. Dunbar was among the first nationally successful African American writers.

        Lyrics of Sunshine and Shadow (1913)

	This is a collection of poetry by African American author Paul Laurence Dunbar. Dunbar's work frequently features a conversational tone, innovative rhetorical structure, and a colorful use of both dialect and mainstream English. Dunbar was among the first nationally successful African American writers.

        Lyrics of the Hearthside (1913)

	This is a collection of poetry by African American author Paul Laurence Dunbar. Dunbar's work frequently features a conversational tone, innovative rhetorical structure, and a colorful use of both dialect and mainstream English. Dunbar was among the first nationally successful African American writers.

        Miscellaneous Poems (1913)

	This is a collection of poetry by African American author Paul Laurence Dunbar. Dunbar's work frequently features a conversational tone, innovative rhetorical structure, and a colorful use of both dialect and mainstream English. Dunbar was among the first nationally successful African American writers.

        APA

        MLA

        Chicago

        FCIT. (2016, February 15). Paul Laurence Dunbar author page. Retrieved February 15, 2016, from http://etc.usf.edu/lit2go/authors/172/paul-laurence-dunbar/

        FCIT. "Paul Laurence Dunbar author page." Lit2Go ETC. Web. 15 February 2016. <http://etc.usf.edu/lit2go/authors/172/paul-laurence-dunbar/>.

        FCIT, "Paul Laurence Dunbar author page." Accessed February 15, 2016. http://etc.usf.edu/lit2go/authors/172/paul-laurence-dunbar/.

            This collection of children's literature is a part of the Educational Technology Clearinghouse and is funded by various grants.

            Copyright © 2006—2016 by the Florida Center for Instructional Technology, College of Education, University of South Florida.

License

Credits

FAQ

Giving


text:
<?php

namespace AppBundle\Controller;

use AppBundle\Entity\Alumno;
use AppBundle\Entity\AvisoSancion;
use AppBundle\Entity\ObservacionSancion;
use AppBundle\Entity\Sancion;
use AppBundle\Form\Type\NuevaObservacionType;
use AppBundle\Form\Type\NuevaSancionType;
use AppBundle\Form\Type\RangoFechasInformeType;
use AppBundle\Form\Type\SancionType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * @Route("/sancion")
 */

class SancionController extends BaseController
{
    /**
     * @Route("/nueva/{alumno}", name="parte_sancionar",methods={"GET", "POST"})
     * @Security("has_role('ROLE_REVISOR')")
     */
    public function sancionarAction(Alumno $alumno, Request $peticion)
    {
        $sancion = new Sancion();
        $usuario = $this->getUser();

        $sancion->setFechaSancion(new \DateTime())
            ->setUsuario($usuario)
            ->setRegistradoEnSeneca(false);

        $em = $this->getDoctrine()->getManager();

        $partes = $em->getRepository('AppBundle:Parte')->findAllSancionablesPorAlumno($alumno);

        $formulario = $this->createForm(new NuevaSancionType(), $sancion, array(
            'alumno' => $alumno
        ));

        $formulario->handleRequest($peticion);

        if ($formulario->isSubmitted() && $formulario->isValid()) {

            $em = $this->getDoctrine()->getManager();

            foreach($sancion->getPartes() as $parte) {
                $parte->setSancion($sancion);
            }
            $em->persist($sancion);
            $em->flush();

            $this->notificarSancion($alumno->getGrupo()->getTutores(), $sancion);
            $this->notificarSancion($em->getRepository('AppBundle:Usuario')->getUsuariosDeSancion($sancion), $sancion);

            $this->addFlash('success', 'Se ha registrado la sanción');

            // redireccionar a la portada
            return new RedirectResponse(
                $this->generateUrl('parte_pendiente')
            );
        }

        return $this->render('AppBundle:Parte:sancionar.html.twig',
            array(
                'alumno' => $alumno,
                'partes' => $partes,
                'sanciones' => $em->getRepository('AppBundle:Sancion')->findAllPorAlumno($alumno),
                'formulario' => $formulario->createView(),
                'usuario' => $usuario
            ));
    }

    /**
     * @Route("/notificar", name="sancion_listado_notificar",methods={"GET", "POST"})
     * @Security("has_role('ROLE_REVISOR') or has_role('ROLE_TUTOR') ")
     */
    public function listadoNotificarAction(Request $request)
    {
        $usuario = $this->getUser();
        $em = $this->getDoctrine()->getManager();

        if (($request->getMethod() === 'POST') && (($request->request->get('noNotificada')) || ($request->request->get('notificada')))) {

            $id = $request->request->get(($request->request->get('notificada')) ? 'notificada' : 'noNotificada');

            $sanciones = $em->getRepository('AppBundle:Sancion')
                ->findAllNoNotificadosPorAlumno($id);

            foreach ($sanciones as $sancion) {
                $avisoSancion = new AvisoSancion();
                $avisoSancion
                    ->setSancion($sancion)
                    ->setUsuario($usuario)
                    ->setAnotacion($request->request->get('anotacion'))
                    ->setFecha(new \DateTime())
                    ->setTipo($em->getRepository('AppBundle:CategoriaAviso')->find($request->request->get('tipo')));

                if ($request->request->get('notificada')) {
                    $sancion->setFechaComunicado(new \DateTime());
                }

                $em->persist($avisoSancion);
            }
            $em->flush();
        }

        $alumnos = ($this->isGranted('ROLE_REVISOR'))
            ? $em->getRepository('AppBundle:Alumno')->findAllConSancionesAunNoNotificadas()
            : $em->getRepository('AppBundle:Alumno')->findAllConSancionesAunNoNotificadasPorTutoria($usuario);

        if (count($alumnos) == 0) {
            // redireccionar a la portada
            return new RedirectResponse(
                $this->generateUrl('portada')
            );
        }
        return $this->render('AppBundle:Sancion:notificar.html.twig',
            array(
                'usuario' => $usuario,
                'alumnos' => $alumnos,
                'tipos' => $em->getRepository('AppBundle:CategoriaAviso')->findAll()
            ));
    }

    /**
     * @Route("/listar", name="sancion_listar",methods={"GET"})
     * @Security("has_role('ROLE_REVISOR')")
     */
    public function listarAction()
    {
        $usuario = $this->getUser();
        $em = $this->getDoctrine()->getManager();

        $sanciones = $em->getRepository('AppBundle:Sancion')
            ->createQueryBuilder('s')
            ->orderBy('s.fechaSancion', 'DESC')
            ->getQuery()
            ->getResult();

        return $this->render('AppBundle:Sancion:listar.html.twig',
            array(
                'sanciones' => $sanciones,
                'usuario' => $usuario
            ));
    }

    /**
     * @Route("/detalle/{sancion}", name="sancion_detalle",methods={"GET", "POST"})
     * @Security("has_role('ROLE_REVISOR')")
     */
    public function detalleAction(Sancion $sancion, Request $request)
    {
        $usuario = $this->getUser();
        $em = $this->getDoctrine()->getManager();

        $formularioSancion = $this->createForm(new SancionType(), $sancion, array(
            'admin' => true,
            'bloqueado' => false
        ));

        $formularioSancion->get('sinSancion')->setData($sancion->getMotivosNoAplicacion() !== null);

        $observacion = new ObservacionSancion();
        $observacion
            ->setSancion($sancion)
            ->setFecha(new \DateTime())
            ->setUsuario($usuario);

        $formularioObservacion = $this->createForm(new NuevaObservacionType(), $observacion, array(
            'admin' => $this->isGranted('ROLE_ADMIN')
        ));

        $formularioObservacion->handleRequest($request);

        if ($formularioObservacion->isSubmitted() && $formularioObservacion->isValid()) {
            $em->persist($observacion);
            $em->flush();
            $this->addFlash('success', 'Observación registrada correctamente');
        }

        $formularioSancion->handleRequest($request);

        if ($formularioSancion->isSubmitted() && $formularioSancion->isValid()) {

            $em->flush();

            $this->addFlash('success', 'Se han registrado correctamente los cambios en la sanción');

            return new RedirectResponse(
                $this->generateUrl('sancion_listar')
            );
        }

        return $this->render('AppBundle:Sancion:detalle.html.twig',
            array(
                'sancion' => $sancion,
                'formulario_sancion' => $formularioSancion->createView(),
                'formulario_observacion' => $formularioObservacion->createView(),
                'usuario' => $usuario
            ));
    }

    /**
     * @Route("/informe", name="sancion_informe",methods={"GET", "POST"})
     * @Security("has_role('ROLE_REVISOR')")
     */
    public function informeAction(Request $request)
    {
        $usuario = $this->getUser();
        $em = $this->getDoctrine()->getManager();

        $fechasPorDefecto = array('desde' => null, 'hasta' => null);

        $formFechas = $this->createForm(new RangoFechasInformeType(), $fechasPorDefecto)
            ->handleRequest($request);

        $fechas = ($formFechas->isValid()) ? $formFechas->getData() : array('desde' => null, 'hasta' => null);

        $alumnado = $em->getRepository('AppBundle:Alumno')->getSancionadosPorFecha($fechas);

        if ($formFechas->isValid() && $formFechas->get('generar')->isClicked()) {
            $plantilla = $this->container->getParameter('listado');
            $logos = $this->container->getParameter('logos');

            $pdf = $this->generarPdf('Informe de sanciones', $logos, $plantilla, -15);

            $html = $this->renderView('AppBundle:Sancion:imprimir_informe.html.twig',
                array(
                    'items' => $alumnado,
                    'fechas' => $fechas
                ));

            $pdf->writeHTML($html);

            $response = new Response($pdf->Output( 'Informe_de_sanciones_' . date('Y-m-d H-i-s') . '.pdf'));
            $response->headers->set('Content-Type', 'application/pdf');

            return $response;
        }

        return $this->render('AppBundle:Sancion:listar_informe.html.twig',
            array(
                'formulario_fechas' => $formFechas->createView(),
                'items' => $alumnado,
                'usuario' => $usuario
            ));
    }

     /**
     * @Route("/imprimir/{sancion}", name="sancion_detalle_pdf",methods={"GET"})
     * @Security("has_role('ROLE_REVISOR')")
     */
    public function detallePdfAction(Sancion $sancion)
    {
        $usuario = $this->getUser();
        $plantilla = $this->container->getParameter('sancion');
        $logos = $this->container->getParameter('logos');

        $pdf = $this->generarPdf('Sancion #' . $sancion->getId(), $logos, $plantilla, -15, 'S' . $sancion->getId());

        $html = $this->renderView('AppBundle:Sancion:imprimir.html.twig',
            array(
                'sancion' => $sancion,
                'usuario' => $usuario,
                'localidad' => $this->container->getParameter('localidad'),
                'director' => $this->container->getParameter('director')
            ));

        $pdf->writeHTML($html);

        $response = new Response($pdf->Output('sancion_' . $sancion->getId() . '.pdf'));
        $response->headers->set('Content-Type', 'application/pdf');

        return $response;
    }
}


text:
"""
Implementation of the `xsl:stylesheet` and `xsl:transform` elements.
"""

import sys
import operator
import itertools
import collections
from gettext import gettext as _

from amara.namespaces import XMLNS_NAMESPACE, XSL_NAMESPACE
from amara import tree, xpath
from amara.writers import outputparameters
from amara.xpath import XPathError, datatypes
from amara.xslt import XsltError, xsltcontext
from amara.xslt.tree import (xslt_element, content_model, attribute_types,
                             literal_element, variable_elements)

__all__ = ['match_tree', 'transform_element']

TEMPLATE_CONFLICT_LOCATION = _(
    'In stylesheet %s, line %s, column %s, pattern %r')

BUILTIN_TEMPLATE_WITH_PARAMS = _(
    'Built-in template invoked with parameters that will be ignored.')

_template_location = operator.attrgetter('baseUri', 'lineNumber',
                                         'columnNumber', '_match')

def _fixup_aliases(node, aliases):
    for child in node:
        if isinstance(child, literal_element.literal_element):
            child.fixup_aliases(aliases)
            _fixup_aliases(child, aliases)
        elif isinstance(child, xslt_element):
            _fixup_aliases(child, aliases)
    return

# The dispatch table is first keyed by mode, then keyed by node type. If an
# element type, it is further keyed by the name test.
class _type_dispatch_table(dict):
    def __missing__(self, type_key):
        if type_key == tree.element.xml_typecode:
            value = self[type_key] = collections.defaultdict(list)
        else:
            value = self[type_key] = []
        return value

class _key_dispatch_table(dict):

    __slots__ = ('_match_table', '_matches_attribute')

    _unpack_key = operator.attrgetter('_match', '_use', 'namespaces')
    _unpack_pattern = operator.attrgetter('node_test', 'axis_type', 'node_type')

    def __init__(self, keys):
        match_table = _type_dispatch_table()
        for key in keys:
            match, use, namespaces = self._unpack_key(key)
            for pattern in match:
                node_test, axis_type, node_type = self._unpack_pattern(pattern)
                info = (node_test, axis_type, namespaces, use)
                # Add the template rule to the dispatch table
                type_key = node_type.xml_typecode
                if type_key == tree.element.xml_typecode:
                    # Element types are further keyed by the name test.
                    name_key = node_test.name_key
                    if name_key:
                        prefix, local = name_key
                        # Unprefixed names are in the null-namespace
                        try:
                            namespace = prefix and namespaces[prefix]
                        except KeyError:
                            raise XPathError(XPathError.UNDEFINED_PREFIX,
                                            prefix=prefix)
                        else:
                            name_key = namespace, local
                    match_table[type_key][name_key].append(info)
                else:
                    # Every other node type gets lumped into a single list
                    # for that node type
                    match_table[type_key].append(info)
        # Now expanded the tables and convert to regular dictionaries to
        # prevent inadvertant growth when non-existant keys are used.
        # Add those patterns that don't have a distinct type:
        #   node(), id() and key() patterns
        any_patterns = match_table[tree.node.xml_typecode]
        match_table = self._match_table = dict(match_table)
        for type_key, patterns in match_table.iteritems():
            if type_key == tree.element.xml_typecode:
                # Add those that are wildcard tests ('*' and 'prefix:*')
                wildcard_names = patterns[None]
                name_table = match_table[type_key] = dict(patterns)
                for name_key, patterns in name_table.iteritems():
                    if name_key is not None:
                        patterns.extend(wildcard_names)
                    patterns.extend(any_patterns)
                    name_table[name_key] = tuple(patterns)
            else:
                patterns.extend(any_patterns)
                match_table[type_key] = tuple(patterns)
        self._matches_attribute = tree.attribute.xml_typecode in match_table

    def _match_nodes(self, context, nodes):
        initial_focus = context.node, context.position, context.size
        context.size = len(nodes)
        position = 1
        for node in nodes:
            context.node = context.current_node = node
            context.position = position
            position += 1
            # Get the possible matches for `node`
            type_key = node.xml_typecode
            type_table = self._match_table
            if type_key in type_table:
                if type_key == tree.element.xml_typecode:
                    element_table = type_table[type_key]
                    name_key = node.xml_name
                    if name_key in element_table:
                        matches = element_table[name_key]
                    else:
                        matches = element_table[None]
                else:
                    matches = type_table[type_key]
            else:
                matches = type_table[tree.node.xml_typecode]

            for pattern, axis_type, namespaces, use_expr in matches:
                context.namespaces = namespaces
                try:
                    m = pattern.match(context, node, axis_type)
                except XPathError, exc:
                    raise XsltError(exc.code)

                if m:
                    focus = context.node, context.position, context.size
                    context.node, context.position, context.size = node, 1, 1
                    value = use_expr.evaluate(context)
                    if isinstance(value, datatypes.nodeset):
                        for value in value:
                            yield datatypes.string(value), node
                    else:
                        yield datatypes.string(value), node
                    context.node, context.position, context.size = focus

            if isinstance(node, tree.element):
                for item in self._match_nodes(context, node.xml_children):
                    yield item
                if self._matches_attribute and node.xml_attributes:
                    attributes = tuple(node.xml_attributes.nodes())
                    for item in self._match_nodes(context, attributes):
                        yield item
            elif isinstance(node, tree.entity):
                for item in self._match_nodes(context, node.xml_children):
                    yield item
        context.node, context.position, context.size = initial_focus
        return

    def __missing__(self, key):
        assert isinstance(key, tree.entity), key
        values = collections.defaultdict(set)
        context = xsltcontext.xsltcontext(key, 1, 1)
        for value, node in self._match_nodes(context, [key]):
            values[value].add(node)
        # Now store the unique nodes as an XPath nodeset
        values = self[key] = dict(values)
        for value, nodes in values.iteritems():
            values[value] = datatypes.nodeset(nodes)
        return values

class transform_element(xslt_element):
    content_model = content_model.seq(
        content_model.rep(content_model.qname(XSL_NAMESPACE, 'xsl:import')),
        content_model.top_level_elements,
        )
    attribute_types = {
        'id': attribute_types.id(),
        'extension-element-prefixes': attribute_types.prefixes(),
        'exclude-result-prefixes': attribute_types.prefixes(),
        'version': attribute_types.number(required=True),
        }

    space_rules = None
    decimal_formats = None
    namespace_aliases = None
    attribute_sets = None
    match_templates = None
    named_templates = None
    parameters = None
    variables = None
    global_variables = None
    initial_functions = None

    builtin_param_warning = True

    def setup(self, _param_element=variable_elements.param_element):
        """
        Called only once, at the first initialization
        """
        self.output_parameters = outputparameters.outputparameters()

        # Sort the top-level elements in decreasing import precedence to ease
        # processing later.
        precedence_key = operator.attrgetter('import_precedence')
        elements = sorted(self.children, key=precedence_key, reverse=True)

        # Merge the top-level stylesheet elements into their respective
        # lists.  Any element name not in the mapping is discarded.
        # Note, by sharing the same list no merging is required later.
        whitespace_elements, variable_elements = [], []
        top_level_elements = {
            'strip-space' : whitespace_elements,
            'preserve-space' : whitespace_elements,
            'output' : [],
            'key' : [],
            'decimal-format' : [],
            'namespace-alias' : [],
            'attribute-set': [],
            'variable' : variable_elements,
            'param' : variable_elements,
            'template' : [],
            }
        # Using `groupby` takes advantage of series of same-named elements
        # appearing adjacent to each other.
        key = operator.attrgetter('expanded_name')
        for (namespace, name), nodes in itertools.groupby(self.children, key):
            if namespace == XSL_NAMESPACE and name in top_level_elements:
                top_level_elements[name].extend(nodes)

        # - process the `xsl:preserve-space` and `xsl:strip-space` elements
        # RECOVERY: Multiple matching patterns use the last occurance
        space_rules = {}
        for element in whitespace_elements:
            strip = element._strip_whitespace
            for token in element._elements:
                namespace, name = token
                space_rules[token] = (namespace, name, strip)
        self.space_rules = space_rules.values()
        # sort in decreasing priority, where `*` is lowest, followed by
        # `prefix:*`, then all others.
        self.space_rules.sort(reverse=True)

        # - process the `xsl:output` elements
        # Sort in increasing import precedence, so the last one added
        # will have the highest import precedence
        elements = top_level_elements['output']
        getter = operator.attrgetter(
            '_method', '_version', '_encoding', '_omit_xml_declaration',
            '_standalone', '_doctype_system', '_doctype_public',
            '_cdata_section_elements', '_indent', '_media_type',
            '_byte_order_mark', '_canonical_form')
        for element in elements:
            (method, version, encoding, omit_xmldecl, standalone,
             doctype_system, doctype_public, cdata_elements, indent,
             media_type, byte_order_mark, canonical_form) = getter(element)
            if method is not None:
                self.output_parameters.method = method
            if version is not None:
                self.output_parameters.version = version
            if encoding is not None:
                self.output_parameters.encoding = encoding
            if omit_xmldecl is not None:
                self.output_parameters.omit_xml_declaration = omit_xmldecl
            if standalone is not None:
                self.output_parameters.standalone = standalone
            if doctype_system is not None:
                self.output_parameters.doctype_system = doctype_system
            if doctype_public is not None:
                self.output_parameters.doctype_public = doctype_public
            if cdata_elements:
                self.output_parameters.cdata_section_elements += cdata_elements
            if indent is not None:
                self.output_parameters.indent = indent
            if media_type is not None:
                self.output_parameters.media_type = media_type
            if byte_order_mark is not None:
                self.output_parameters.byte_order_mark = byte_order_mark
            if canonical_form is not None:
                self.output_parameters.canonical_form = canonical_form

        # - process the `xsl:key` elements
        # Group the keys by name
        elements = top_level_elements['key']
        name_key = operator.attrgetter('_name')
        elements.sort(key=name_key)
        keys = self._keys = {}
        for name, elements in itertools.groupby(elements, name_key):
            keys[name] = tuple(elements)

        # - process the `xsl:decimal-format` elements
        formats = self.decimal_formats = {}
        getter = operator.attrgetter(
            '_decimal_separator', '_grouping_separator', '_infinity',
            '_minus_sign', '_NaN', '_percent', '_per_mille', '_zero_digit',
            '_digit', '_pattern_separator')
        for element in top_level_elements['decimal-format']:
            name = element._name
            format = getter(element)
            # It is an error to declare a decimal-format more than once
            # (even with different import precedence) with different values.
            if name in formats and formats[name] != format:
                # Construct a useful name for the error message.
                if name:
                    namespace, name = name
                    if namespace:
                        name = element.namespaces[namespace] + ':' + name
                else:
                    name = '#default'
                raise XsltError(XsltError.DUPLICATE_DECIMAL_FORMAT, name)
            else:
              formats[name] = format
        # Add the default decimal format, if not declared.
        if None not in formats:
            formats[None] = ('.', ',', 'Infinity', '-', 'NaN', '%',
                             unichr(0x2030), '0', '#', ';')

        # - process the `xsl:namespace-alias` elements
        elements = top_level_elements['namespace-alias']
        elements.reverse()
        aliases = self.namespace_aliases = {}
        for precedence, group in itertools.groupby(elements, precedence_key):
            mapped = {}
            for element in group:
                namespace = element.namespaces[element._stylesheet_prefix]
                if namespace not in aliases:
                    mapped[namespace] = True
                    result_prefix = element._result_prefix
                    result_namespace = element.namespaces[result_prefix]
                    aliases[namespace] = (result_namespace, result_prefix)
                # It is an error for a namespace URI to be mapped to multiple
                # different namespace URIs (with the same import precedence).
                elif namespace in mapped:
                    raise XsltError(XsltError.DUPLICATE_NAMESPACE_ALIAS,
                                    element._stylesheet_prefix)
        if aliases:
            # apply namespace fixup for the literal elements
            _fixup_aliases(self, aliases)

        # - process the `xsl:attribute-set` elements
        sets = self.attribute_sets = {}
        for element in top_level_elements['attribute-set']:
            sets[element._name] = element

        # - process the `xsl:param` and `xsl:variable` elements
        index, self._variables = {}, variable_elements[:]
        variable_elements.reverse()
        for element in variable_elements:
            name = element._name
            if name not in index:
                # unique (or first) variable binding
                index[name] = 1
            else:
                # shadowed variable binding, remove from processing list
                self._variables.remove(element)
        self.parameters = frozenset(element._name for element in self._variables
                                    if isinstance(element, _param_element))

        # - process the `xsl:template` elements
        match_templates = collections.defaultdict(_type_dispatch_table)
        named_templates = self.named_templates = {}
        elements = top_level_elements['template']
        elements.reverse()
        getter = operator.attrgetter('node_test', 'axis_type', 'node_type')
        for position, element in enumerate(elements):
            match, name = element._match, element._name
            precedence = element.import_precedence
            if match:
                namespaces = element.namespaces
                template_priority = element._priority
                mode_table = match_templates[element._mode]
                for pattern in match:
                    node_test, axis_type, node_type = getter(pattern)
                    if template_priority is None:
                        priority = node_test.priority
                    else:
                        priority = template_priority
                    sort_key = (precedence, priority, position)
                    info = (sort_key, node_test, axis_type, element)
                    # Add the template rule to the dispatch table
                    type_key = node_type.xml_typecode
                    if type_key == tree.element.xml_typecode:
                        # Element types are further keyed by the name test.
                        name_key = node_test.name_key
                        if name_key:
                            prefix, local = name_key
                            # Unprefixed names are in the null-namespace
                            try:
                                namespace = prefix and namespaces[prefix]
                            except KeyError:
                                raise XPathError(XPathError.UNDEFINED_PREFIX,
                                                 prefix=prefix)
                            else:
                                name_key = namespace, local
                        mode_table[type_key][name_key].append(info)
                    else:
                        # Every other node type gets lumped into a single list
                        # for that node type
                        mode_table[type_key].append(info)
            if name:
                # XSLT 1.0, Section 6, Paragraph 3:
                # It is an error if a stylesheet contains more than one
                # template with the same name and same import precedence.
                if name not in named_templates:
                    named_templates[name] = element
                elif named_templates[name].import_precedence == precedence:
                    # Construct a useful name for the error message.
                    namespace, name = name
                    if namespace:
                        name = element.namespaces[namespace] + ':' + name
                    raise XsltError(XsltError.DUPLICATE_NAMED_TEMPLATE, name)
        # Now expanded the tables and convert to regular dictionaries to
        # prevent inadvertant growth when non-existant keys are used.
        match_templates = self.match_templates = dict(match_templates)
        for mode, type_table in match_templates.iteritems():
            # Add those patterns that don't have a distinct type:
            #   node(), id() and key() patterns
            any_patterns = type_table[tree.node.xml_typecode]
            type_table = match_templates[mode] = dict(type_table)
            for type_key, patterns in type_table.iteritems():
                if type_key == tree.element.xml_typecode:
                    # Add those that are wildcard tests ('*' and 'prefix:*')
                    wildcard_names = patterns[None]
                    name_table = type_table[type_key] = dict(patterns)
                    for name_key, patterns in name_table.iteritems():
                        if name_key is not None:
                            patterns.extend(wildcard_names)
                        patterns.extend(any_patterns)
                        patterns.sort(reverse=True)
                        name_table[name_key] = tuple(patterns)
                else:
                    patterns.extend(any_patterns)
                    patterns.sort(reverse=True)
                    type_table[type_key] = tuple(patterns)
        #self._dump_match_templates(match_templates)
        return

    def _dump_match_templates(self, match_templates=None):
        from pprint import pprint
        if match_templates is None:
            match_templates = self.match_templates
        print "=" * 50
        for mode, type_table in match_templates.iteritems():
            print "mode:", mode
            for node_type, patterns in type_table.iteritems():
                print "  node type:", node_type
                print "  patterns: ",
                pprint(patterns)
                #for patterninfo in self.match_templates[mode][nodetype]:
                #    pat, axistype, template = patterninfo
                #    print "    template matching pattern  %r  for axis type %s" % (pat, axistype)
                #    templates[template] = 1
                print '-'*30
        return

    ############################# Prime Routines #############################

    def prime(self, context):
        processed = context.variables
        elements, deferred = self._variables, []
        num_writers = len(context._writers)
        while 1:
            for element in elements:
                if element._name in processed:
                    continue
                try:
                    element.instantiate(context)
                except XPathError, error:
                    if error.code != XPathError.UNDEFINED_VARIABLE:
                        raise
                    # Remove any aborted and possibly unbalanced
                    # outut handlers on the stack.
                    del context._writers[num_writers:]
                    deferred.append(element)
            if not deferred:
                break
            elif deferred == elements:
                # Just pick the first one as being the "bad" variable.
                raise XsltError(XsltError.CIRCULAR_VARIABLE,
                                name=deferred[0]._name)
            # Re-order stored variable elements to simplify processing for
            # the next transformation.
            for element in deferred:
                self._variables.remove(element)
                self._variables.append(element)
            # Try again, but this time processing only the ones that
            # referenced, as of yet, undefined variables.
            elements, deferred = deferred, []

        for name, keys in self._keys.iteritems():
            context.keys[name] = _key_dispatch_table(keys)
        return

    def update_keys(self, context):
        """
        Update all the keys for all documents in the context
        Only used as an override for the default lazy key eval
        """
        node = context.node
        for doc in context.documents.itervalues():
            context.node = doc
            for key_name in self._keys:
                self.update_key(context, key_name)
        context.node = node
        return

    ############################# Exit Routines #############################

    def reset(self):
        """
        Called whenever the processor is reset, i.e. after each run
        Also called whenever multiple stylesheets are appended to
        a processor, because the new top-level elements from the
        new stylesheet need to be processed into the main one
        """
        self.reset1()
        self.reset2()
        return

    ############################ Runtime Routines ############################

    def apply_imports(self, context, precedence):
        node, mode = context.node, context.mode
        # Get the possible template rules for `node`
        type_key = node.xml_typecode
        if mode in self.match_templates:
            type_table = self.match_templates[mode]
            if type_key in type_table:
                if type_key == tree.element.xml_typecode:
                    element_table = type_table[type_key]
                    name = node.xml_name
                    if name in element_table:
                        template_rules = element_table[name]
                    else:
                        template_rules = element_table[None]
                else:
                    template_rules = type_table[type_key]
            else:
                template_rules = type_table[tree.node.xml_typecode]
        else:
            template_rules = ()

        first_template = locations = None
        for sort_key, pattern, axis_type, template in template_rules:
            # Filter out those patterns with a higher import precedence than
            # what was specified.
            if sort_key[0] < precedence:
                context.namespaces = template.namespaces
                try:
                    m = pattern.match(context, node, axis_type)
                except XpathError, exc:
                    raise XsltError(exc.code, node, locations)

                if m:
                    # Make sure the template starts with a clean slate
                    state = context.template, context.variables
                    context.template = template
                    context.variables = context.global_variables
                    try:
                        template.instantiate(context)
                    finally:
                        context.template, context.variables = state
                    break
        else:
            # Nothing matched, use builtin templates
            if isinstance(node, (tree.element, tree.entity)):
                self.apply_templates(context, node.xml_children, mode)
            elif isinstance(node, (tree.text, tree.attribute)):
                context.text(node.xml_value)
        return

    def apply_templates(self, context, nodes, mode=None, params=None):
        """
        Intended to be used by XSLT instruction implementations only.

        Implements the xsl:apply-templates instruction by attempting to
        let the stylesheet apply its own template for the given context.
        If the stylesheet does not have a matching template, the
        built-in templates are invoked.

        context is an XsltContext instance. params is a dictionary of
        parameters being passed in, defaulting to None.
        """
        initial_focus = context.node, context.position, context.size
        initial_state = context.template, context.mode

        if params is None:
            params = {}

        context.size, context.mode = len(nodes), mode
        # Note, it is quicker to increment the `position` variable than it
        # is to use enumeration: itertools.izip(nodes, itertools.count(1))
        position = 1
        for node in nodes:
            # Set the current node for this template application
            context.node = context.current_node = node
            context.position = position
            position += 1

            # Get the possible template rules for `node`
            type_key = node.xml_typecode
            if mode in self.match_templates:
                type_table = self.match_templates[mode]
                if type_key in type_table:
                    if type_key == tree.element.xml_typecode:
                        element_table = type_table[type_key]
                        name = node.xml_name
                        if name in element_table:
                            template_rules = element_table[name]
                        else:
                            template_rules = element_table[None]
                    else:
                        template_rules = type_table[type_key]
                else:
                    template_rules = type_table[tree.node.xml_typecode]
            else:
                template_rules = ()

            first_template = locations = None
            for sort_key, pattern, axis_type, template in template_rules:
                context.namespaces = template.namespaces
                if pattern.match(context, node, axis_type):
                    if 1: # recovery_method == Recovery.SILENT
                        # (default until recovery behaviour is selectable)
                        # Just use the first matching pattern since they are
                        # already sorted in descending order.
                        break
                    else: # recovery_method in (Recovery.WARNING, Recovery.NONE)
                        if not first_template:
                            first_template = template
                        else:
                            if not locations:
                                locations = [_template_location(first_template)]
                            locations.append(_template_location(template))
            else:
                # All template rules have been processed
                if locations:
                    # Multiple template rules have matched.  Report the
                    # template rule conflicts, sorted by position
                    locations.sort()
                    locations = '\n'.join(TEMPLATE_CONFLICT_LOCATION % location
                                          for location in locations)
                    exception = XsltError(XsltError.MULTIPLE_MATCH_TEMPLATES,
                                          node, locations)
                    if 1: # recovery_method == Recovery.WARNING
                        processor.warning(str(exception))
                    else:
                        raise exception
                if first_template:
                    template = first_template
                    context.namespaces = template.namespaces
                else:
                    template = None

            if template:
                context.template = template
                # Make sure the template starts with a clean slate
                variables = context.variables
                context.variables = context.global_variables
                try:
                    template.instantiate(context, params)
                finally:
                    context.variables = variables
            else:
                # Nothing matched, use builtin templates
                if params and self.builtin_param_warning:
                    context.processor.warning(BUILTIN_TEMPLATE_WITH_PARAMS)
                    self.builtin_param_warning = False
                if isinstance(node, (tree.element, tree.entity)):
                    self.apply_templates(context, node.xml_children, mode)
                elif isinstance(node, (tree.text, tree.attribute)):
                    context.text(node.xml_value)

        # Restore context
        context.node, context.position, context.size = initial_focus
        context.template, context.mode = initial_state
        return

#def PrintStylesheetTree(node, stream=None, indentLevel=0, showImportIndex=0,
#                        lastUri=None):
#    """
#    Function to print the nodes in the stylesheet tree, to aid in debugging.
#    """
#    stream = stream or sys.stdout
#    if lastUri != node.xml_base:
#        stream.write(indentLevel * '  ')
#        stream.write('====%s====\n' % node.xml_base)
#        lastUri = node.xml_base
#    stream.write(indentLevel * '  ' + str(node))
#    if showImportIndex:
#        stream.write(' [' + str(node.import_precedence) + ']')
#    stream.write('\n')
#    stream.flush()
#    show_ii = isinstance(node, xslt_element) and \
#        node.expandedName in [(XSL_NAMESPACE, 'stylesheet'),
#                              (XSL_NAMESPACE, 'transform')]
#    for child in node.children:
#        PrintStylesheetTree(child, stream, indentLevel+1, show_ii, lastUri)
#    return


text:
layout: page-api
title: QUnit.test.each()
excerpt: Add tests using a data provider.
groups:
  - main
version_added: "2.16.0"
---

`QUnit.test.each( name, dataset, callback )`

`QUnit.test.only.each( name, dataset, callback )`

`QUnit.test.skip.each( name, dataset, callback )`

`QUnit.test.todo.each( name, dataset, callback )`

Add tests using a data provider.

| parameter | description |
|-----------|-------------|
| `name` (string) | Title of unit being tested |
| `dataset` (array or object) | Array or object of data values passed to each test case |
| `callback` (function) | Function that performs the test |

### Callback parameters

| parameter | description |
|-----------|-------------|
| `assert` (object) | A new instance object with the [assertion methods](../assert/index.md) |
| `data` (any) | Data value |

Use this method to add multiple tests that are similar, but with different data passed in.

`QUnit.test.each()` generates multiple calls to [`QUnit.test()`](./test.md) internally, and has all the same capabilities such support for async functions, returning a Promise, and the `assert` argument.

Each test case is passed one value of your dataset.

The [`only`](./test.only.md), [`skip`](./test.skip.md), and [`todo`](./test.todo.md) variants are also available, as `QUnit.test.only.each`, `QUnit.test.skip.each`, and `QUnit.test.todo.each` respectively.

## Examples

### Basic data provider

```js
function isEven (x) {
  return x % 2 === 0;
}

QUnit.test.each('isEven()', [2, 4, 6], (assert, data) => {
  assert.true(isEven(data), `${data} is even`);
});
```

### Array data provider

The original array is passed to your callback. [Array destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) can be used to unpack the data array, directly from the callback signature.

```js
function square (x) {
  return x * x;
}

QUnit.test.each('square()', [
  [2, 4],
  [3, 9]
], (assert, [value, expected]) => {
  assert.equal(square(value), expected, `${value} squared`);
});
```

### Object data provider

```js
QUnit.test.each('isEven()', {
  caseEven: [2, true],
  caseNotEven: [3, false]
}, (assert, [value, expected]) => {
  assert.strictEqual(isEven(value), expected);
});
```

### Async functions with `each()`

```js
function isEven (x) {
  return x % 2 === 0;
}

async function isAsyncEven (x) {
  return isEven(x);
}

QUnit.test.each('isAsyncEven()', [2, 4], async (assert, data) => {
  assert.true(await isAsyncEven(data), `${data} is even`);
});
```

Or in classic ES5 syntax, by returning a Promise from each callback:

```js
function isEven (x) {
  return x % 2 === 0;
}

function isAsyncEven (x) {
  return Promise.resolve(isEven(x));
}

QUnit.test.each('isAsyncEven()', [2, 4], function (assert, data) {
  return isAsyncEven(data).then(function (result) {
    assert.true(result, data + ' is even');
  });
});
```


text:
package com.itellity.comp.type.communication;

import com.itellity.comp.type.base.AbstractMappingHelper;
import com.itellity.sys.entity.Entity;
import com.itellity.comp.type.communication.InternetAddress;

/**
 * Mapping Helper for InternetAddresses
 *
 * @author Erik Schmiegelow
 * @author Goetz Perry
 * @version $Id: InternetAddressMH.java 22220 2011-09-05 14:59:58Z erik $
 */
public class InternetAddressMH extends AbstractMappingHelper {

    /**
     * parse an InternetAddress from the given values
     *
     * @param entity
     * @param internetAddress
     *
     * @return
     */
    public static InternetAddress parseValue(Entity entity, String internetAddress) {

        InternetAddress internet = null;

        if (isNullOrEmpty(internetAddress)) {

            internet = InternetAddress.UNDEFINED;
        } else {

            try {

                internet = new InternetAddress(internetAddress);
            } catch (Exception e) {
            	e.printStackTrace();
                internet = InternetAddress.UNDEFINED;
            }
        }

        return internet;
    }

    /**
     * DOCUMENT ME!
     *
     * @param internetAddress
     *
     * @return
     */
    public static String dispatchValue(InternetAddress internetAddress) {

        if ((internetAddress == null) || (internetAddress.isUndefined())) {

            return "";
        } else {

            return internetAddress.getInternetAddress();
        }
    }
}


text:
require 'spec_helper'

describe Identity do
  context "updating session manager" do
    let :realm do
      Realm.create!(:label => 'realm')
    end

    let :someone do
      Identity.create!(:realm => realm)
    end

    let :account1 do
      Account.create!(:identity => someone,
        :realm => realm,
        :uid => '1',
        :provider => 'twitter',
        :name => "account1")
    end

    let :account2 do
      Account.create!(:identity => someone,
        :realm => realm,
        :uid => '1',
        :provider => 'facebook',
        :name => 'account2')
    end

    it "can read throught a cache" do
      identity = someone
      result = Identity.cached_find_by_id(identity.id)
      result.should eq identity
      attributes = result.attributes
      attributes[:god] = true
      $memcached.set(result.cache_key, attributes.to_json)
      from_cache = Identity.cached_find_by_id(identity.id)
      from_cache.god?.should be_truthy
    end

    it "can read a collection through a cache" do
      identities = (1..20).map { Identity.create!(:realm => realm) }
      from_db = Identity.cached_find_all_by_id(identities[0..10].map(&:id))
      from_db.map(&:id).should eq from_db[0..10].map(&:id)
      # Spoof all cached identities as gods
      from_db.each do |identity|
        attributes = identity.attributes.merge({'god' => true})
        $memcached.set(identity.cache_key, attributes.to_json)
      end
      from_db_and_cache = Identity.cached_find_all_by_id(identities[0..20].map(&:id))
      # Check all gods
      from_db_and_cache[0..10].map(&:god).inject(true){|r, e| r && e}.should be_truthy
      # Check all muggles
      from_db_and_cache[11..19].map(&:god).inject(true){|r, e| r && !e}.should be_truthy
    end

    it "can retrieve a user from a session_key" do
      me = someone
      session = Session.create!(:identity => me)
      Identity.find_by_session_key(session.key).should eq me
      # Again from cache
      Identity.find_by_session_key(session.key).should eq me
    end

    it "automatically destroys all sessions when destroyed" do
      me = someone
      session = Session.create!(:identity => me)
      me.destroy
      Session.find_by_id(session.id).should be_nil
    end

    it "initializes the last_seen_on for new identitites" do
      Identity.find(someone.id).last_seen_on.should eq Time.now.to_date
    end

    it "can find identities not seen for a while" do
      (0..9).each do |age|
        # FIXME: We should store time zone in database to avoid UTC conversion
        Identity.create!(:realm => realm, :last_seen_on => (Time.now - age.days).utc)
      end
      Identity.not_seen_for_more_than_days(20).size.should eq 0
      Identity.not_seen_for_more_than_days(9).size.should eq 0
      Identity.not_seen_for_more_than_days(8).size.should eq 1
      Identity.not_seen_for_more_than_days(1).size.should eq 8
      Identity.not_seen_for_more_than_days(0).size.should eq 9
    end

    it "can find anonymous identities" do
      someone
      Identity.anonymous.all.first.should eq someone
      account1.identity = someone
      account1.save!
      someone.ensure_primary_account
      someone.save!
      Identity.anonymous.all.size.should eq 0
    end

    describe "#fingerprints" do
      let :identity do
        Identity.new(:realm => realm)
      end

      it 'is empty if no accounts' do
        identity.accounts.should == []
        identity.fingerprints.should == []
      end

      it 'collects fingerprints from all accounts (when adding accounts directly)' do
        identity.accounts << Account.new(:identity => identity, :uid => '123', :provider => 'facebook', :realm => realm)
        identity.accounts << Account.new(:identity => identity, :uid => '234', :provider => 'twitter', :realm => realm)
        identity.fingerprints.length.should >= identity.accounts.length
        identity.fingerprints.sort.should == identity.accounts.map { |a| a.fingerprints }.flatten.sort
      end

      it 'collects fingerprints from all accounts (when creating accounts independently)' do
        Account.create!(:identity => identity, :uid => '123', :provider => 'facebook', :realm => realm)
        Account.create!(:identity => identity, :uid => '234', :provider => 'twitter', :realm => realm)
        identity.reload
        identity.fingerprints.length.should >= identity.accounts.length
        identity.fingerprints.sort.should == identity.accounts.map { |a| a.fingerprints }.flatten.sort
      end

      it 'preserves fingerprint after account is deleted' do
        account = Account.create!(:identity => identity, :uid => '123', :provider => 'facebook', :realm => realm)
        identity.reload
        old_fingerprints = identity.fingerprints.dup
        account.destroy

        identity.reload
        identity.fingerprints.should == old_fingerprints
      end
    end

    describe "#search" do
      let :twitter_account do
        Account.create!(:identity => someone,
          :realm => realm,
          :uid => '1',
          :provider => 'twitter',
          :nickname => 'tildetwitt',
          :name => "Tilde Tjohei Nielsen Babar")
      end
      let :facebook_account do
        Account.create!(:identity => someone,
          :realm => realm,
          :uid => '1',
          :provider => 'facebook',
          :nickname => 'tildeface',
          :name => "Tilde Mehe Nielsen")
      end

      before(:each) do
        twitter_account
        facebook_account
      end

      it "finds users identity from accounts with fuzzy match" do
        result = Identity.find_by_query("Tilde Nielsen")
        result.length.should eq 1
        result.first.accounts.map(&:nickname).sort.should == ['tildeface', 'tildetwitt']
      end

      it "finds users identity from accounts with exact match" do
        result = Identity.find_by_query('"Tilde Nielsen"')
        result.length.should eq 0
        result = Identity.find_by_query('"Tilde Mehe Nielsen"')
        result.length.should eq 1
      end

    end

    describe "#root?" do
      let(:root) { Realm.create!(:label => 'root') }

      it "has root" do
        he = Identity.new(:realm => root, :god => true)
        he.should be_root
      end

      it "is not root if just a regular guy" do
        he = Identity.new(:realm => root, :god => false)
        he.should_not be_root
      end

      it "is not root if god in a different realm" do
        he = Identity.new(:realm => realm, :god => true)
        he.should_not be_root
      end

    end

  end
end


text:
/**
 * Provides dynamic kibana configuration
 *
 * Dynamic config component
 */

var replaceString = '#es_url#';
var kibana_config = [
    "define(['settings'],",
    "function (Settings) {",
    '  "use strict";',
    "  return new Settings({",
    '    elasticsearch: "'+replaceString+'",',
    "    default_route     : '/dashboard/file/default.json',",
    '    kibana_index: "kibana-int",',
    "    panel_names: [ 'histogram', 'map', 'goal', 'table', 'filtering', 'timepicker', 'text', 'hits', 'column', 'trends', 'bettermap', 'query', 'terms', 'stats', 'sparklines' ]",
    "  });",
    "});"
  ].join("\n");

 exports.getDynamicKibanaConfig = function getDynamicKibanaConfig(req, config) {
    return kibana_config.replace(replaceString, config.es_url);
 }


text:
![3.6 stars](../../images/ic_star_black_18dp_1x.png)![3.6 stars](../../images/ic_star_black_18dp_1x.png)![3.6 stars](../../images/ic_star_black_18dp_1x.png)![3.6 stars](../../images/ic_star_half_black_18dp_1x.png)![3.6 stars](../../images/ic_star_border_black_18dp_1x.png) 9

To use the Windcast skill, try saying...

* *Alexa open wind cast and get wind information for Seattle*

* *Alexa open wind cast and get wind for Boulder on Sunday*

* *Alexa open wind cast*

Windcast provides you 24-hour wind forecasts for over 400 of the most popular US cities and provides you current wind direction pointing to the direction the wind is coming from.

Windcast is designed and built in Seattle, Washington for sailors, by sailors.

Update June 28, 2016: Windcast now provides wind information for over 120 marina's in Washington state.

***

### Skill Details

* **Invocation Name:** wind cast
* **Category:** null
* **ID:** amzn1.echo-sdk-ams.app.dca717d0-f91d-4bb1-95cb-624d70eab112
* **ASIN:** B01GZ1UIC2
* **Author:** iPhingers
* **Release Date:** June 16, 2016 @ 07:45:36
* **In-App Purchasing:** No


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

import ghidra.app.plugin.core.datamgr.DataTypeManagerPlugin;
import ghidra.app.plugin.core.datamgr.editor.DataTypeEditorManager;
import ghidra.program.model.data.Category;

public class CreateUnionAction extends CreateDataTypeAction {

	public CreateUnionAction(DataTypeManagerPlugin plugin) {
		super(plugin, "Union");
	}

	@Override
	protected void createNewDataType(DataTypeEditorManager editorManager, Category category) {
		editorManager.createNewUnion(category, false);
	}

}


text:
module DealRedemptions
  module ApplicationHelper
    # Set page layout title
    def page_title(page_title)
      content_for(:title) { page_title }
    end
  end
end


text:
The script `create_dell_vlans` can be used to pre-populate the bridges
and vlan nics needed for the HaaS to operate, but right now we don't
have an automated way to delete them. You shouldn't need to do this to
use the HaaS, but if for some reason you want to delete the nics related
to a given vlan, you can do:

    brctl delif br-vlan${vlan_number} em3.${vlan_number}
    vconfig rem em3.${vlan_number}
    ifconfig br-vlan${vlan_number} down
    brctl delbr br-vlan${vlan_number}

We're using `em3` as an example; do a `brctl show` to find out what
the right nic actually is.