text:
package us.kbase.test.auth2.lib.user;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;

import static us.kbase.test.auth2.TestCommon.set;

import java.time.Instant;
import java.util.Collections;

import org.junit.Test;

import com.google.common.base.Optional;

import us.kbase.auth2.lib.DisplayName;
import us.kbase.auth2.lib.EmailAddress;
import us.kbase.auth2.lib.UserDisabledState;
import us.kbase.auth2.lib.UserName;
import us.kbase.auth2.lib.identity.RemoteIdentityDetails;
import us.kbase.auth2.lib.identity.RemoteIdentityID;
import us.kbase.auth2.lib.identity.RemoteIdentity;
import us.kbase.auth2.lib.user.NewUser;
import us.kbase.test.auth2.TestCommon;

public class NewUserTest {

	/* note that this does not replicate the tests from authuser to test the general builder */

	private static final RemoteIdentity REMOTE = new RemoteIdentity(
			new RemoteIdentityID("prov42", "bar42"),
			new RemoteIdentityDetails("user42", "full42", "email42"));

	@Test
	public void build() throws Exception {
		final Instant now = Instant.now();
		final NewUser u = NewUser.getBuilder(
				new UserName("foo"), new DisplayName("bar"), now, REMOTE)
				.withEmailAddress(new EmailAddress("f@g.com")).build();

		assertThat("incorrect disable admin", u.getAdminThatToggledEnabledState(),
				is(Optional.absent()));
		assertThat("incorrect created", u.getCreated(), is(now));
		assertThat("incorrect custom roles", u.getCustomRoles(), is(Collections.emptySet()));
		assertThat("incorrect disabled state", u.getDisabledState(), is(new UserDisabledState()));
		assertThat("incorrect display name", u.getDisplayName(), is(new DisplayName("bar")));
		assertThat("incorrect email", u.getEmail(), is(new EmailAddress("f@g.com")));
		assertThat("incorrect enable toggle date", u.getEnableToggleDate(), is(Optional.absent()));
		assertThat("incorrect grantable roles", u.getGrantableRoles(),
				is(Collections.emptySet()));
		assertThat("incorrect identities", u.getIdentities(), is(set(REMOTE)));
		assertThat("incorrect identity", u.getIdentity(), is(REMOTE));
		assertThat("incorrect policy IDs", u.getPolicyIDs(), is(Collections.emptyMap()));
		assertThat("incorrect last login", u.getLastLogin(), is(Optional.absent()));
		assertThat("incorrect disabled reason", u.getReasonForDisabled(), is(Optional.absent()));
		assertThat("incorrect roles", u.getRoles(), is(Collections.emptySet()));
		assertThat("incorrect user name", u.getUserName(), is(new UserName("foo")));
		assertThat("incorrect is disabled", u.isDisabled(), is(false));
		assertThat("incorrect is local", u.isLocal(), is(false));
		assertThat("incorrect is root", u.isRoot(), is(false));
	}

	@Test
	public void buildFail() throws Exception {
		failBuild(UserName.ROOT, REMOTE,
				new IllegalArgumentException("Standard users cannot be root"));
		failBuild(new UserName("foo"), null, new NullPointerException("remoteIdentity"));
	}

	private void failBuild(
			final UserName userName,
			final RemoteIdentity remoteIdentity,
			final Exception e)
			throws Exception {
		try {
			NewUser.getBuilder(userName, new DisplayName("bar"), Instant.now(), remoteIdentity);
			fail("expected exception");
		} catch (Exception got) {
			TestCommon.assertExceptionCorrect(got, e);
		}
	}
}


text:
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Xml;
using fyiReporting.RDL;
using Xwt;

namespace LibRdlCrossPlatformViewer
{

    public class ReportViewer : VBox
    {
        private Report _report;
        private Pages pages;
        public NeedPassword DataSourceReferencePassword = null;
        private Xwt.ScrollView scrollView;
        private Xwt.VBox vboxPages;
        private Xwt.HBox vboxToolMenu;
        private Xwt.VBox vboxContents;

        private Backend _defaultBackend = Backend.XwtWinforms;
        public Backend DefaultBackend
        {
            get { return _defaultBackend; }
            set { _defaultBackend = value; }
        }

        private string connstr_param_name = "connection_string";
        public string ConnectionStringParameterName
        {
            get { return connstr_param_name; }
            set { connstr_param_name = value; }
        }

        private string conntype_param_name = "connection_type";
        public string ConnectionTypeParameterName
        {
            get { return conntype_param_name; }
            set { conntype_param_name = value; }
        }

        private bool displayButtonMenuToolbar = false;
        public bool DisplayMenuToolBar
        {
            get { return displayButtonMenuToolbar; }
            set
            {
                vboxToolMenu.Visible = value;
                displayButtonMenuToolbar = value;
            }
        }

        public ListDictionary Parameters { get; private set; }

        bool show_errors;
        public bool ShowErrors
        {
            get
            {
                return show_errors;
            }
            set
            {
                show_errors = value;
            }
        }

        bool show_params;
        public bool ShowParameters
        {
            get
            {
                return show_params;
            }
            set
            {
                show_params = value;

            }
        }

        public Uri SourceFile { get; private set; }

        private string _SourceRdl;
        public string SourceRdl
        {
            get
            {
                return _SourceRdl;
            }
            set
            {
                _SourceRdl = value;
                Rebuild();
            }
        }

        public fyiReporting.RDL.Report Report
        {
            get
            {
                return this._report;
            }
        }

        public ReportViewer()
        {
            // Setup layout boxes
            vboxContents = new Xwt.VBox();
            vboxToolMenu = new Xwt.HBox();

            // Setup tool button menu
            Xwt.Button buttonExport = new Xwt.Button("Export");
            buttonExport.Clicked += delegate (object sender, EventArgs e)
            {
                SaveAs();
            };
            vboxToolMenu.PackStart(buttonExport);

            Xwt.Button buttonPrint = new Xwt.Button("Print");
            vboxToolMenu.PackStart(buttonPrint);

            // Add vboxContent widgets
            vboxPages = new Xwt.VBox();
            vboxContents.PackStart(vboxToolMenu);
            vboxContents.PackStart(vboxPages);

            // Setup Controls Contents
            scrollView = new Xwt.ScrollView();
            scrollView.Content = vboxContents;
            scrollView.VerticalScrollPolicy = ScrollPolicy.Automatic;
            scrollView.BorderVisible = true;
            this.PackStart(scrollView, true, true);

            Parameters = new ListDictionary();

            ShowErrors = false;
        }

        public void LoadReport(Uri filename, string parameters, string connectionString)
        {

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(filename.AbsolutePath);

            foreach (XmlNode node in xmlDoc.GetElementsByTagName("ConnectString"))
            {
                node.InnerText = connectionString;
            }

            xmlDoc.Save(filename.AbsolutePath);

            LoadReport(filename, parameters);
        }

        /// <summary>
        /// Loads the report.
        /// </summary>
        /// <param name='filename'>
        /// Filename.
        /// </param>
        public void LoadReport(Uri filename)
        {
            LoadReport(filename, "");
        }

        /// <summary>
        /// Loads the report.
        /// </summary>
        /// <param name='filename'>
        /// Filename.
        /// </param>
        /// <param name='parameters'>
        /// Example: parameter1=someValue&parameter2=anotherValue
        /// </param>
        public void LoadReport(Uri sourcefile, string parameters)
        {
            SourceFile = sourcefile;

            // Any parameters?  e.g.  file1.rdl?orderid=5
            if (parameters.Trim() != "")
            {
                this.Parameters = this.GetParmeters(parameters);
            }
            else
            {
                this.Parameters = null;
            }

            // Obtain the source
            SourceRdl = System.IO.File.ReadAllText(sourcefile.AbsolutePath);
            // GetSource is omitted: all it does is read the file.
            // Compile the report

            Rebuild();
        }

        public void Rebuild()
        {
            _report = this.GetReport(SourceRdl);
            _report.RunGetData(Parameters);
            pages = _report.BuildPages();

            List<ReportArea> tempList = new List<ReportArea>();
            foreach (ReportArea w in this.vboxPages.Children)
            {
                tempList.Add(w);
            }
            foreach (ReportArea w in tempList)
            {
                vboxPages.Remove(w);
            }

            for (int pageCount = 0; pageCount < pages.Count; pageCount++)
            {
                ReportArea area = new ReportArea(this.DefaultBackend);
                area.SetReport(_report, pages[pageCount]);

                vboxPages.PackStart(area, true, true);
            }

            this.Show();

            if (_report.ErrorMaxSeverity > 0)
            {
                // TODO: add error messages back
                //SetErrorMessages(report.ErrorItems);
            }

        }

        private System.Collections.Specialized.ListDictionary GetParmeters(string parms)
        {
            System.Collections.Specialized.ListDictionary ld = new System.Collections.Specialized.ListDictionary();
            if (parms == null)
            {
                return ld; // dictionary will be empty in this case
            }

            // parms are separated by &

            char[] breakChars = new char[] { '&' };
            string[] ps = parms.Split(breakChars);

            foreach (string p in ps)
            {
                int iEq = p.IndexOf("=");
                if (iEq > 0)
                {
                    string name = p.Substring(0, iEq);
                    string val = p.Substring(iEq + 1);
                    ld.Add(name, val);
                }
            }
            return ld;
        }

        private Report GetReport(string reportSource)
        {
            // Now parse the file

            RDLParser rdlp;
            Report r;

            rdlp = new RDLParser(reportSource);
            // RDLParser takes RDL XML and Parse compiles the report

            r = rdlp.Parse();
            if (r.ErrorMaxSeverity > 0)
            {

                foreach (string emsg in r.ErrorItems)
                {
                    Console.WriteLine(emsg);
                }

                int severity = r.ErrorMaxSeverity;
                r.ErrorReset();
                if (severity > 4)
                {
                    r = null; // don't return when severe errors
                }
            }

            return r;
        }

        public void SaveAs(string FileName, fyiReporting.RDL.OutputPresentationType type)
        {
            fyiReporting.RDL.OneFileStreamGen sg = null;

            try
            {
                // Must use the RunGetData before each export or there is no data.
                _report.RunGetData(this.Parameters);

                sg = new fyiReporting.RDL.OneFileStreamGen(FileName, true);
                _report.RunRender(sg, type);
            }
            catch (Exception ex)
            {
                MessageDialog.ShowError(ex.Message);
            }
            finally
            {
                if (sg != null)
                {
                    sg.CloseMainStream();
                }
            }
            return;
        }

        public void SaveAs()
        {

            SaveFileDialog dlg = new SaveFileDialog("Select a file");
            dlg.Multiselect = false;
            dlg.Filters.Add(new FileDialogFilter("PDF files", "*.pdf"));
            dlg.Filters.Add(new FileDialogFilter("XML files", "*.xml"));
            dlg.Filters.Add(new FileDialogFilter("HTML files", "*.html"));
            dlg.Filters.Add(new FileDialogFilter("CSV files", "*.csv"));
            dlg.Filters.Add(new FileDialogFilter("RTF files", "*.rtf"));
            dlg.Filters.Add(new FileDialogFilter("TIF files", "*.tif"));
            dlg.Filters.Add(new FileDialogFilter("Excel 2007 (Table Only)", "*.xlsx"));
            dlg.Filters.Add(new FileDialogFilter("Excel 2007", "*.xlsx"));
            dlg.Filters.Add(new FileDialogFilter("MHT files", "*.mht"));

            Uri file = this.SourceFile;

            if (file != null)
            {
                dlg.InitialFileName = "*.pdf";
            }
            else
            {
                dlg.InitialFileName = "*.pdf";
            }

            if (dlg.Run() == false)
            {
                return;
            }

            // save the report in a rendered format
            string ext = null;
            int i = dlg.FileName.LastIndexOf('.');
            if (i < 1)
            {
                ext = "";
            }
            else
            {
                ext = dlg.FileName.Substring(i + 1).ToLower();
            }

            fyiReporting.RDL.OutputPresentationType type = fyiReporting.RDL.OutputPresentationType.Internal;
            switch (ext)
            {
                case "pdf":
                    type = fyiReporting.RDL.OutputPresentationType.PDF;
                    break;
                case "xml":
                    type = fyiReporting.RDL.OutputPresentationType.XML;
                    break;
                case "html":
                case "htm":
                    type = fyiReporting.RDL.OutputPresentationType.HTML;
                    break;
                case "csv":
                    type = fyiReporting.RDL.OutputPresentationType.CSV;
                    break;
                case "rtf":
                    type = fyiReporting.RDL.OutputPresentationType.RTF;
                    break;
                case "mht":
                case "mhtml":
                    type = fyiReporting.RDL.OutputPresentationType.MHTML;
                    break;
                case "xlsx":
                    type = dlg.ActiveFilter.Name.Contains("Table") ? OutputPresentationType.ExcelTableOnly : OutputPresentationType.Excel2007;
                    break;
                case "tif":
                    type = fyiReporting.RDL.OutputPresentationType.TIF;
                    break;
                case "tiff":
                    type = fyiReporting.RDL.OutputPresentationType.TIF;
                    break;
                default:
                    MessageDialog.ShowMessage(String.Format("{0} is not a valid file type.  File extension must be PDF, XML, HTML, CSV, MHT, RTF, TIF, XLSX.", dlg.FileName));
                    break;
            }

            SaveAs(dlg.FileName, type);

        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace SpeckCatalog\Service;

interface FormServiceAwareInterface
{
    /**
     * Get formService.
     *
     * @return formService.
     */
    public function getFormService();

    /**
     * Set formService.
     *
     * @param formService the value to set.
     */
    public function setFormService($formService);
}


text:
"""Basic unittests for the server resource control operations."""
from __future__ import absolute_import

from functools import partial

from six.moves import http_client
from django.test import Client, TransactionTestCase

from rotest.core.models import SignatureData

from tests.api.utils import request

class TestGetOrCreateSignature(TransactionTestCase):
    """Assert operations of get or create signature request."""
    fixtures = ['resource_ut.json']

    def setUp(self):
        """Setup test environment."""
        self.client = Client()
        self.requester = partial(request, client=self.client,
                                 path="signatures/get_or_create")

    def test_new_signature(self):
        """Validate creating and then using a new signature."""
        response, content = self.requester(json_data={
            "error": "new error traceback"
        })

        self.assertEqual(response.status_code, http_client.OK)
        self.assertTrue(content.is_new)
        self.assertEqual(content.link, "")

        response, content = self.requester(json_data={
            "error": "new error traceback"
        })

        self.assertEqual(response.status_code, http_client.OK)
        self.assertFalse(content.is_new)

    def test_precise_match(self):
        """Validate match with a simple string match."""
        link = "Some link"
        SignatureData.objects.create(pk=1, link=link,
                                     pattern="some traceback")

        response, content = self.requester(json_data={
            "error": "some traceback"
        })

        self.assertEqual(response.status_code, http_client.OK)
        self.assertFalse(content.is_new)
        self.assertEqual(content.id, 1)
        self.assertEqual(content.link, link)

    def test_pattern_match(self):
        """Validate match with a regular expression pattern."""
        link = "Some link"
        error = "error.level over 9000.0"
        pattern = SignatureData.create_pattern(error)
        self.assertNotEqual(error, pattern)

        SignatureData.objects.create(pk=2, link=link, pattern=pattern)

        response, content = self.requester(json_data={
            "error": error
        })

        self.assertEqual(response.status_code, http_client.OK)
        self.assertFalse(content.is_new)
        self.assertEqual(content.id, 2)
        self.assertEqual(content.link, link)


text:
/*
 * $Id$
 */

/*

 Copyright (c) 2000-2014 Board of Trustees of Leland Stanford Jr. University,
 all rights reserved.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
 IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

 Except as contained in this notice, the name of Stanford University shall not
 be used in advertising or otherwise to promote the sale, use or other dealings
 in this Software without prior written authorization from Stanford University.

 */

package org.lockss.plugin.clockss.tangram;

import org.apache.commons.collections.map.MultiValueMap;
import org.lockss.util.*;
import org.lockss.extractor.*;
import org.lockss.extractor.XmlDomMetadataExtractor.NodeValue;
import org.lockss.extractor.XmlDomMetadataExtractor.XPathValue;
import java.util.*;
import org.lockss.plugin.clockss.SourceXmlSchemaHelper;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *  A helper class that defines a schema for XML metadata extraction for
 *  Tangram source files
 *
 */
public class TangramSourceXmlSchemaHelper
implements SourceXmlSchemaHelper {
  static Logger log = Logger.getLogger(TangramSourceXmlSchemaHelper.class);
  static StringBuilder urlName = new StringBuilder();

  private static final String AUTHOR_SPLIT_CH = ",";
  private static final String TITLE_SEPARATOR = ":";
  /*
   *  Tangram specific node evaluators to extract the information we want
   */
  /*
   * Book Title, Subtitle -
   *  <Titolo>Book Title</Titolo>
   *  <Sottotitolo>SubTitle</Sottotitolo>
   *  if both: Title:SubTitle
   *  or, either Title, or :SubTitle
   */

  static private final NodeValue TANGRAM_BOOK_TITLE_VALUE = new NodeValue() {
    @Override
    public String getValue(Node node) {

      log.debug3("getValue of Tangram BOOK TITLE");
      String title = null;
      String subtitle = null;
      String nodeName = null;
      Node parent = node.getParentNode();
      NodeList childNodes = parent.getChildNodes();
      for (int m = 0; m < childNodes.getLength(); m++) {
        Node child = childNodes.item(m);
        if (Tangram_book_title.equals(child.getNodeName()) ){
          title = child.getTextContent();
        } else if (Tangram_book_subtitle.equals(child.getNodeName())) {
          subtitle = child.getTextContent();
        }
        if ((title != null) && (subtitle != null)) {
          break;
        }
      }

      StringBuilder titleVal = new StringBuilder();
      if (title != null) {
        titleVal.append(title);
      }
      // if empty title, but subtitle exists => " :Subtitle"
      // not a great title, but valuable to know...
      if (subtitle != null) {
        titleVal.append(TITLE_SEPARATOR + subtitle);
      }
      if (titleVal.length() != 0)  {
        log.debug3("book title: " + titleVal.toString());
        return titleVal.toString();
      } else {
        log.debug3("no value in this book title");
        return null;
      }

    }
  };

  /*
   * Metadata example
   * /node
   *  /Elenco_autori_curatori_principali [principal author]
   *  /Elenco_autori_curatori_principali_INV [principal author, inverted]
   *  /Titolo [title]
   *  /Sottotitolo [subtitle]
   *  /Categoria [category]
   *  /Formato [format]
   *  /Numero_pagine [# pages]
   *  /ISBN
   *  /PDF
   *  /Prezzo_di_copertina [price]
   *  /Data_pubblicazione [pub date]
   *  /Collana [Series]
   *  /URL_Libro   [book URL]
   */

  /*
   *  Tangram specific XPATH key definitions that we care about
   */

  /* Under an item node, the interesting bits live at these relative locations */

  private static final String Tangram_book_title = "Titolo";
  private static final String Tangram_book_subtitle = "Sottotitolo";
  private static final String Tangram_isbn = "ISBN";
  private static final String Tangram_art_pubdate = "Data_pubblicazione";
  /* access.url (relative) */
  private static final String Tangram_book_url = "PDF";
  /* author(s), single or multiple in one tag */
  private static final String Tangram_author =  "Elenco_autori_curatori_principali";
  /*
   *  The following 3 variables are needed to use the XPathXmlMetadataParser
   */

  /* 1.  MAP associating xpath & value type definition or evaluator */
  static private final Map<String,XPathValue>
  Tangram_articleMap = new HashMap<String,XPathValue>();
  static {
    // article specific stuff
    Tangram_articleMap.put(Tangram_art_pubdate, XmlDomMetadataExtractor.TEXT_VALUE);
    Tangram_articleMap.put(Tangram_author, XmlDomMetadataExtractor.TEXT_VALUE);
    Tangram_articleMap.put(Tangram_book_title, TANGRAM_BOOK_TITLE_VALUE);
    Tangram_articleMap.put(Tangram_isbn, XmlDomMetadataExtractor.TEXT_VALUE);
    Tangram_articleMap.put(Tangram_book_url, XmlDomMetadataExtractor.TEXT_VALUE);
  }

  /* 2. All the metadata is neatly under the <node> for each book
   */
  static private final String Tangram_topNode = "/catalogo/xml/node";

  /* 3. in Tangram, there some global information we gather */
  static private final Map<String,XPathValue>
  Tangram_globalMap = null; //new HashMap<String,XPathValue>();

  /*
   * The emitter will need a map to know how to cook ONIX raw values
   */
  protected static final MultiValueMap cookMap = new MultiValueMap();
  static {
    cookMap.put(Tangram_isbn, MetadataField.FIELD_ISBN);
    cookMap.put(Tangram_book_title, MetadataField.FIELD_PUBLICATION_TITLE);
    cookMap.put(Tangram_author,
        new MetadataField(MetadataField.FIELD_AUTHOR, MetadataField.splitAt(AUTHOR_SPLIT_CH)));
    cookMap.put(Tangram_art_pubdate, MetadataField.FIELD_DATE);
  }

  @Override
  public Map<String, XPathValue> getGlobalMetaMap() {
    return null; //Tangram_globalMap;
  }

  /**
   * return Tangram article paths representing metadata of interest
   */
  @Override
  public Map<String, XPathValue> getArticleMetaMap() {
    return Tangram_articleMap;
  }

  /**
   * Return the article node path
   */
  @Override
  public String getArticleNode() {
    return Tangram_topNode;
  }

  /**
   * Return a map to translate raw values to cooked values
   */
  @Override
  public MultiValueMap getCookMap() {
    return cookMap;
  }

  /* (non-Javadoc)
   * @see org.lockss.plugin.clockss.SourceXmlMetadataExtractorFactory.SourceXmlMetadataExtractorHelper#getDeDuplicationXPathKey()
   */
  @Override
  public String getDeDuplicationXPathKey() {
    return null;
  }

  /* (non-Javadoc)
   * @see org.lockss.plugin.clockss.SourceXmlMetadataExtractorFactory.SourceXmlMetadataExtractorHelper#getConsolidationXPathKey()
   */
  @Override
  public String getConsolidationXPathKey() {
    return null;
  }

  /* (non-Javadoc)
   * @see org.lockss.plugin.clockss.SourceXmlMetadataExtractorFactory.SourceXmlMetadataExtractorHelper#getFilenameXPathKey()
   */
  @Override
  public String getFilenameXPathKey() {

    return Tangram_book_url;
  }

}


text:
require "heroku_autoscaler/setter"
require "heroku_autoscaler/mailer"

module HerokuAutoscaler
  class Alerter
    include Setter

    ALERT_FREQUENCY       = 60 # sec
    EXEC_FREQUENCY        = 15 # sec
    FAILED_UPSCALES_ALERT = 4 # Min count of failed upscales to send an alert
    EVENTS                = %w(failed-upscale)

    attr_accessor :alert_frequency, :exec_frequency, :failed_upscales_alert

    def initialize(cache, options)
      @cache   = cache
      @options = options
      writers_setting(options)
    end

    def restart_event_counters
      EVENTS.each { |event| cache.set(event, 0) }
    end

    # If it tries to scale up, but the number of MAX_DYNOS restricts it
    def failed_upscale_alert(dynos, metrics, freq_upscale, upscale_queue_time)
      failed_upscales = failed_tries("failed-upscale", freq_upscale)
      return if !mailer || failed_upscales < failed_upscales_alert

      proc = proc { mailer.request_queueing_alert(dynos, metrics, failed_upscales * freq_upscale, upscale_queue_time) }
      send_alert("failed-upscale", proc)
    end

    private

    attr_reader :cache

    def mailer
      @mailer ||= begin
        return unless @options[:send_email]

        mailer = Mailer.new(@options[:email_config])
        mailer.config!
        mailer
      end
    end

    def failed_tries(failed_event, freq_upscale)
      failed_event_times = cache.fetch_number(failed_event)
      failed_event_times += exec_frequency.to_f / freq_upscale.to_f
      cache.set(failed_event, failed_event_times)
      failed_event_times
    end

    def send_alert(alert_name, proc)
      last_alert_sent = cache.fetch("alert-sent:#{alert_name}")
      return unless !last_alert_sent || Time.now - last_alert_sent >= alert_frequency

      proc.call
      cache.set_now("alert-sent:#{alert_name}")
    end
  end
end


text:
#ifndef HALIDE_SUBSTITUTE_H
#define HALIDE_SUBSTITUTE_H

/** \file
 *
 * Defines methods for substituting out variables in expressions and
 * statements. */

#include <map>

#include "IR.h"

namespace Halide {
namespace Internal {

/** Substitute variables with the given name with the replacement
 * expression within expr. This is a dangerous thing to do if variable
 * names have not been uniquified. While it won't traverse inside let
 * statements with the same name as the first argument, moving a piece
 * of syntax around can change its meaning, because it can cross lets
 * that redefine variable names that it includes references to. */
EXPORT Expr substitute(const std::string &name, const Expr &replacement, const Expr &expr);

/** Substitute variables with the given name with the replacement
 * expression within stmt. */
EXPORT Stmt substitute(const std::string &name, const Expr &replacement, const Stmt &stmt);

/** Substitute variables with names in the map. */
// @{
EXPORT Expr substitute(const std::map<std::string, Expr> &replacements, const Expr &expr);
EXPORT Stmt substitute(const std::map<std::string, Expr> &replacements, const Stmt &stmt);
// @}

/** Substitute expressions for other expressions. */
// @{
EXPORT Expr substitute(const Expr &find, const Expr &replacement, const Expr &expr);
EXPORT Stmt substitute(const Expr &find, const Expr &replacement, const Stmt &stmt);
// @}

/** Substitutions where the IR may be a general graph (and not just a
 * DAG). */
// @{
Expr graph_substitute(const std::string &name, const Expr &replacement, const Expr &expr);
Stmt graph_substitute(const std::string &name, const Expr &replacement, const Stmt &stmt);
Expr graph_substitute(const Expr &find, const Expr &replacement, const Expr &expr);
Stmt graph_substitute(const Expr &find, const Expr &replacement, const Stmt &stmt);
// @}

/** Substitute in all let Exprs in a piece of IR. Doesn't substitute
 * in let stmts, as this may change the meaning of the IR (e.g. by
 * moving a load after a store). Produces graphs of IR, so don't use
 * non-graph-aware visitors or mutators on it until you've CSE'd the
 * result. */
// @{
Expr substitute_in_all_lets(const Expr &expr);
Stmt substitute_in_all_lets(const Stmt &stmt);
// @}

}
}

#endif


text:
#ifndef _VUFORIA_VUMARKTARGET_H_
#define _VUFORIA_VUMARKTARGET_H_

// Include files
#include <Vuforia/Trackable.h>
#include <Vuforia/ObjectTarget.h>
#include <Vuforia/VuMarkTemplate.h>
#include <Vuforia/InstanceId.h>
#include <Vuforia/Image.h>

namespace Vuforia
{

/// A target for tracking VuMark instances.
/**
 * A VuMarkTarget is an instance of a VuMarkTemplate with a specific instance ID,
 * which can be tracked. The actual visual appearance of the instance can also
 * be retrieved.
 *
 * Note that some ObjectTarget functionalities such as setting the target size or
 * starting / stopping extended tracking cannot be used with individual
 * VuMarkTargets. You need to access these functionalities via the respective
 * VuMarkTemplate to change these properties for the entire set.
 */
class VUFORIA_API VuMarkTarget : public ObjectTarget
{
public:

    /// Returns the Trackable class' type
    static Type getClassType();

    /// Returns the VuMark template this VuMark instance was instantiated from
    virtual const VuMarkTemplate& getTemplate() const = 0;

    /// Returns the instance ID of this particular VuMark instance
    virtual const InstanceId& getInstanceId() const = 0;

    /// Returns a generated image of the VuMark being tracked
    virtual const Image& getInstanceImage() const = 0;
};

} // namespace Vuforia

#endif //_VUFORIA_VUMARKTARGET_H_


text:
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/switch_camera_pressed" android:state_enabled="true" android:state_pressed="true"/>
    <item android:drawable="@drawable/switch_camera_pressed" android:state_checked="true" android:state_enabled="true"/>
    <item android:drawable="@drawable/switch_camera"/>
</selector>


text:
<!DOCTYPE html>

<title>Profile</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">

<title>Books On The Go - Profile</title>

<link href="css/bootstrap.min.css" rel="stylesheet">

<link href="css/landing-page.css" rel="stylesheet">

<link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Lato:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css">

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                  Toggle navigation

              </button>
              Home

                      Buy/Sell

                       Community Forum

                      Profile

                      About Us

Axel Sim (Baruch College)

Department:

Programming

Register Date:
 06/23/2013

Date of Birth:
01/24/1988

Gender:
Female

Address:
New York, NY

Email:
axel.sim@baruchmail.cuny.edu

Phone:
555-456-7890(Mobile)

<input type="submit" value="Previous Orders" />

<input type="submit" value="Edit Profile" />


text:
describe("Higher order functions", () => {
  var funcs = require('../src/higher-order-functions');

  it("iterative map produces squares", () => expect(funcs.imperativeMap()).toEqual([0, 1, 4, 9]));
  it("functional map produces squares", () => expect(funcs.functionalMap()).toEqual([0, 1, 4, 9]));
  it("imperativefilter gets even numbers", () => expect(funcs.imperativeFilter()).toEqual([0, 2, 4, 6, 8]));
  it("functional filter gets even numbers", () => expect(funcs.functionalFilter()).toEqual([0, 2, 4, 6, 8]));
  it("imperative reduce adds numbers", () => expect(funcs.imperativeReduce()).toEqual(10));
  it("functional reduce adds numbers", () => expect(funcs.functionalReduce()).toEqual(10));
});


text:
The [main project page](http://kanbanik.github.io/kanbanik/)

Kanbanik is a free and open source kanban board which can be used for personal kanban as well as for managing of small teams.

Features:
* Support for complex flows (vertical/horizontal sub-states)
* Rich (WYSIWYG) task editing
* Drag and drop task moving
* Drag and drop workflow editing
* Complete JSON based [API](https://github.com/kanbanik/kanbanik/wiki/API)
* Editable class of service distinguished by colour
* Possibility to assigne a user to a task
* Support for simple authorization
* Works on touchscreen (mobile) devices


text:
THIS_MAKEFILE_PATH:=$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST))
THIS_DIR:=$(shell cd $(dir $(THIS_MAKEFILE_PATH));pwd)

ROOT := index.js
include $(shell node -e "require('n8-make')")

NODE_MODULES = $(THIS_DIR)/node_modules
BIN := $(NODE_MODULES)/.bin

# applications
NODE ?= node
NPM ?= $(NODE) $(shell which npm)
WEBPACK ?= $(NODE) $(BIN)/webpack
MOCHA ?= $(NODE) $(BIN)/mocha
CHOKI ?= $(BIN)/chokidar
SERVE = $(BIN)/serve

# create standalone bundle for testing purpose
standalone: build build/wpcom-xhr-request.js

build/wpcom-xhr-request.js:
	@$(WEBPACK) -p --config ./examples/webpack.config.js

install: node_modules

node_modules: package.json
	@NODE_ENV= $(NPM) install
	@touch node_modules

watch: watch/index.js

watch/index.js:
	$(CHOKI) $(ROOT) -c 'make'

test:
	@$(MOCHA) \
		--timeout 120s \
		--slow 3s \
		--grep "$(FILTER)" \
		--bail \
		--reporter spec \
		--compilers js:babel-register \
		test/

test-watch:
	@$(MOCHA) \
		--timeout 120s \
		--slow 3s \
		--grep "$(FILTER)" \
		--bail \
		--watch \
		--reporter spec \
		--compilers js:babel-register \
		test/

examples: standalone
	$(SERVE) -p 3002

.PHONY: standalone install watch test


text:
require File.dirname(__FILE__) + '/../integration_helper'

describe 'a PDF with a radio field' do
  let(:input_pdf) { File.join(File.dirname(__FILE__), "pdf") }

  context 'with nothing filled in' do
    let(:template) {
      PDFRavager::Template.new
    }
    let(:expected) { File.join(File.dirname(__FILE__), "empty.png") }

    it 'matches empty.png when rendered' do
      pix_diff, _ = compare_pdf_to_png(ravage_to_temp_file(template, input_pdf), expected)
      expect(pix_diff).to eq(0)
    end
  end

  context 'with "Yes" filled in' do
    let(:template) {
      PDFRavager::Template.new do |t|
        t.fill 'RadioButtonList', 'Yes'
      end
    }
    let(:expected) { File.join(File.dirname(__FILE__), "yes.png") }

    it 'matches yes.png when rendered' do
      pix_diff, _ = compare_pdf_to_png(ravage_to_temp_file(template, input_pdf), expected)
      expect(pix_diff).to eq(0)
    end
  end

  context 'with "No" filled in' do
    let(:template) {
      PDFRavager::Template.new do |t|
        t.fill 'RadioButtonList', 'No'
      end
    }
    let(:expected) { File.join(File.dirname(__FILE__), "no.png") }

    it 'matches no.png when rendered' do
      pix_diff, _ = compare_pdf_to_png(ravage_to_temp_file(template, input_pdf), expected)
      expect(pix_diff).to eq(0)
    end
  end
end


text:
namespace file_based_test_driver {

const char AlternationSet::kEmptyAlternationName[] = "<empty>";
const char AlternationSetWithModes::kEmptyAlternationName[] = "EMPTY";

absl::Status AlternationSet::Record(const std::string& alternation_name,
                                    const RunTestCaseResult& test_case_result) {
  FILE_BASED_TEST_DRIVER_RET_CHECK(!finished_);
  alternation_map_[test_case_result.test_outputs()].push_back(
      alternation_names_.size());
  alternation_names_.push_back(alternation_name.empty() ? kEmptyAlternationName
                                                        : alternation_name);
  return absl::OkStatus();
}

absl::Status AlternationSet::Finish(RunTestCaseResult* test_case_result) {
  FILE_BASED_TEST_DRIVER_RET_CHECK(!finished_);
  finished_ = true;
  std::vector<std::string>* test_outputs =
      test_case_result->mutable_test_outputs();
  FILE_BASED_TEST_DRIVER_RET_CHECK(test_outputs->empty());

  // If all of the results are the same, leave output as is. Otherwise,
  // process output into the form:
  //   {{{<semicolon separated list of alternation groups}}}
  //   <results for these groups>
  //   ----
  //   {{{<next groups>}}}
  //   <results for these groups>
  //   ...
  //
  // We'll group all alternations with equal outputs together,
  // ordering alternations by their original generation order.
  if (alternation_map_.size() <= 1) {
    if (!alternation_map_.empty()) {
      *test_outputs = alternation_map_.begin()->first;
    }
  } else {
    // Map the sorted vector of input indices with the same output
    // to that output value.
    // This will also sort the map by the first element of each vector.
    std::map<std::vector<int>, std::vector<std::string>> transposed_results_map;

    // Transpose alternation_map_ so it maps from a vector of indices (sorted)
    // to their common test output.
    // The vector of indices is already sorted, by construction.
    for (const auto& it : alternation_map_) {
      transposed_results_map[it.second] = it.first;
    }

    for (const auto& it : transposed_results_map) {
      const std::vector<int>& alternation_index_list = it.first;
      const std::vector<std::string>& group_output = it.second;

      std::vector<std::string> match_groups;
      match_groups.reserve(alternation_index_list.size());
      for (int idx : alternation_index_list) {
        match_groups.push_back(alternation_names_[idx]);
      }

      if (match_groups.size() > 1) {
        match_groups.insert(match_groups.begin(), "ALTERNATION GROUPS:");
        const std::string groups_list = absl::StrJoin(match_groups, "\n    ");
        test_outputs->push_back(groups_list);
      } else {
        test_outputs->push_back(
            absl::StrCat("ALTERNATION GROUP: ", match_groups[0]));
      }
      test_outputs->insert(test_outputs->end(), group_output.begin(),
                           group_output.end());
    }
  }

  test_outputs->insert(test_outputs->begin(), test_case_result->parts()[0]);
  alternation_map_.clear();

  return absl::OkStatus();
}

absl::Status AlternationSetWithModes::Record(
    const std::string& alternation_name,
    const RunTestCaseWithModesResult& test_case_result) {
  FILE_BASED_TEST_DRIVER_RET_CHECK(!finished_);
  static LazyRE2 re = {"[\\n\\{\\}\\<\\>]"};
  FILE_BASED_TEST_DRIVER_RET_CHECK(!RE2::PartialMatch(alternation_name, *re))
      << "Alternation \"" << alternation_name << "\" contains names that can't "
      << "be stored in a result_type: " << re->pattern();
  alternations_.emplace_back(
      alternation_name.empty() ? kEmptyAlternationName : alternation_name,
      test_case_result.test_case_outputs());
  return absl::OkStatus();
}

absl::Status AlternationSetWithModes::Finish(
    RunTestCaseWithModesResult* test_case_result) {
  FILE_BASED_TEST_DRIVER_RET_CHECK(!finished_);
  finished_ = true;

  TestCaseOutputs* test_case_outputs =
      test_case_result->mutable_test_case_outputs();

  TestCaseMode::UnorderedSet all_modes;
  FILE_BASED_TEST_DRIVER_RETURN_IF_ERROR(CollectModes(test_case_outputs, &all_modes));

  for (const TestCaseMode& mode : all_modes) {
    FILE_BASED_TEST_DRIVER_RETURN_IF_ERROR(BuildSingleMode(mode, test_case_outputs));
  }

  return absl::OkStatus();
}

absl::Status AlternationSetWithModes::CollectModes(
    TestCaseOutputs* test_case_outputs, TestCaseMode::UnorderedSet* all_modes) {
  bool set_possible_modes = true;
  for (const NameAndAlternationOutput& alternation : alternations_) {
    if (set_possible_modes) {
      FILE_BASED_TEST_DRIVER_RETURN_IF_ERROR(test_case_outputs->SetPossibleModes(
          alternation.outputs.possible_modes()));
      set_possible_modes = false;
    } else {
      FILE_BASED_TEST_DRIVER_RET_CHECK(test_case_outputs->possible_modes() ==
                alternation.outputs.possible_modes())
          << "Different possible modes for differerent alternations are not "
          << "allowed: {"
          << absl::StrJoin(test_case_outputs->possible_modes(), ",",
                           TestCaseMode::JoinFormatter())
          << "} vs {"
          << absl::StrJoin(alternation.outputs.possible_modes(), ",",
                           TestCaseMode::JoinFormatter())
          << "}";
    }
    for (const auto& mode_to_results : alternation.outputs.outputs_) {
      const TestCaseMode& mode = mode_to_results.first;
      all_modes->insert(mode);
    }
  }

  return absl::OkStatus();
}

absl::Status AlternationSetWithModes::BuildSingleMode(
    const TestCaseMode& mode, TestCaseOutputs* test_case_outputs) {
  ResultTypeToOutputMap result_type_to_output_map;

  FILE_BASED_TEST_DRIVER_RETURN_IF_ERROR(CollectAlternations(mode, &result_type_to_output_map));

  for (const auto& pair : result_type_to_output_map) {
    const std::string& result_type = pair.first;
    const OutputToAlternationNameMap& output_map = pair.second;
    bool added;
    FILE_BASED_TEST_DRIVER_RETURN_IF_ERROR(MaybeAddSingleOutput(mode, result_type, output_map,
                                         test_case_outputs, &added));
    if (!added) {
      FILE_BASED_TEST_DRIVER_RETURN_IF_ERROR(CombineAlternations(mode, result_type, output_map,
                                          test_case_outputs));
    }
  }

  return absl::OkStatus();
}

absl::Status AlternationSetWithModes::CollectAlternations(
    const TestCaseMode& mode,
    ResultTypeToOutputMap* result_type_to_output_map) {
  for (const NameAndAlternationOutput& alternation : alternations_) {
    auto it = alternation.outputs.outputs_.find(mode);
    FILE_BASED_TEST_DRIVER_RET_CHECK(it != alternation.outputs.outputs_.end());
    const TestCaseOutputs::ModeResults& mode_results = it->second;

    for (const auto& pair : mode_results) {
      const std::string& result_type = pair.first;
      const std::string& output = pair.second;
      (*result_type_to_output_map)[result_type][output].push_back(
          alternation.name);
    }
  }
  return absl::OkStatus();
}

absl::Status AlternationSetWithModes::MaybeAddSingleOutput(
    const TestCaseMode& mode, const std::string& result_type,
    const OutputToAlternationNameMap& output_map,
    TestCaseOutputs* test_case_outputs, bool* added) {
  *added = false;
  if (output_map.size() != 1) {
    return absl::OkStatus();
  }

  const std::pair<std::string, std::vector<std::string>>& output_and_idx_list =
      *output_map.begin();
  if (output_and_idx_list.second.size() != alternations_.size()) {
    return absl::OkStatus();
  }

  FILE_BASED_TEST_DRIVER_RETURN_IF_ERROR(test_case_outputs->RecordOutput(mode, result_type,
                                                  output_and_idx_list.first));
  *added = true;

  return absl::OkStatus();
}

absl::Status AlternationSetWithModes::CombineAlternations(
    const TestCaseMode& mode, const std::string& result_type,
    const OutputToAlternationNameMap& output_map,
    TestCaseOutputs* test_case_outputs) {
  for (const auto& output_and_names : output_map) {
    const std::string& output = output_and_names.first;
    const std::vector<std::string>& alternation_names = output_and_names.second;

    const std::string annotated_result_type = absl::StrCat(
        result_type, "{", absl::StrJoin(alternation_names, "}{"), "}");

    FILE_BASED_TEST_DRIVER_RETURN_IF_ERROR(
        test_case_outputs->RecordOutput(mode, annotated_result_type, output));
  }
  return absl::OkStatus();
}

}  // namespace file_based_test_driver


text:
#pragma once

#include <cassert>
#include "file.h"
#include "page.h"
#include "types.h"

namespace badgerdb {

/**
 * @brief Iterator for iterating over the pages in a file.
 *
 * This class provides a forward-only iterator for iterating over all of the
 * pages in a file.
 */
class FileIterator {
 public:
  /**
   * Constructs an empty iterator.
   */
  FileIterator()
      : file_(NULL),
        current_page_number_(Page::INVALID_NUMBER) {
  }

  /**
   * Constructors an iterator over the pages in a file, starting at the first
   * page.
   *
   * @param file  File to iterate over.
   */
  FileIterator(PageFile* file)
      : file_(file) {
    assert(file_ != NULL);
    const FileHeader& header = file_->readHeader();
    current_page_number_ = header.first_used_page;
  }

  /**
   * Constructs an iterator over the pages in a file, starting at the given
   * page number.
   *
   * @param file        File to iterate over.
   * @param page_number Number of page to start iterator at.
   */
  FileIterator(PageFile* file, PageId page_number)
      : file_(file),
        current_page_number_(page_number) {
  }

  /**
   * Advances the iterator to the next page in the file.
   */
	inline FileIterator& operator++() {
    assert(file_ != NULL);
    const PageHeader& header = file_->readPageHeader(current_page_number_);
    current_page_number_ = header.next_page_number;

		return *this;
	}

	//postfix
	inline FileIterator operator++(int)
	{
		FileIterator tmp = *this;   // copy ourselves

    assert(file_ != NULL);
    const PageHeader& header = file_->readPageHeader(current_page_number_);
    current_page_number_ = header.next_page_number;

		return tmp;
	}

  /**
   * Returns true if this iterator is equal to the given iterator.
   *
   * @param rhs   Iterator to compare against.
   * @return    True if other iterator is equal to this one.
   */
	inline bool operator==(const FileIterator& rhs) const {
    return file_->filename() == rhs.file_->filename() &&
        current_page_number_ == rhs.current_page_number_;
  }

	inline bool operator!=(const FileIterator& rhs) const {
    return (file_->filename() != rhs.file_->filename()) ||
        (current_page_number_ != rhs.current_page_number_);
  }

  /**
   * Dereferences the iterator, returning a copy of the current page in the
   * file.
   *
   * @return  Page in file.
   */
	inline Page operator*() const
  { return file_->readPage(current_page_number_); }

 private:
  /**
   * File we're iterating over.
   */
  PageFile* file_;

  /**
   * Number of page in file iterator is currently pointing to.
   */
  PageId current_page_number_;
};

}


text:
from __future__ import absolute_import
from .development import *


text:
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;

// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108

namespace System.Security.Cryptography
{
  public partial class PasswordDeriveBytes : DeriveBytes
  {
    #region Methods and constructors
    public byte[] CryptDeriveKey(string algname, string alghashname, int keySize, byte[] rgbIV)
    {
      return default(byte[]);
    }

    protected override void Dispose(bool disposing)
    {
    }

    public override byte[] GetBytes(int cb)
    {
      return default(byte[]);
    }

    public PasswordDeriveBytes(byte[] password, byte[] salt, string hashName, int iterations, CspParameters cspParams)
    {
    }

    public PasswordDeriveBytes(string strPassword, byte[] rgbSalt, string strHashName, int iterations, CspParameters cspParams)
    {
      Contract.Ensures(0 <= strHashName.Length);
    }

    public PasswordDeriveBytes(string strPassword, byte[] rgbSalt, string strHashName, int iterations)
    {
      Contract.Ensures(false);
    }

    public PasswordDeriveBytes(byte[] password, byte[] salt)
    {
      Contract.Ensures(false);
    }

    public PasswordDeriveBytes(string strPassword, byte[] rgbSalt)
    {
      Contract.Ensures(false);
    }

    public PasswordDeriveBytes(byte[] password, byte[] salt, string hashName, int iterations)
    {
      Contract.Ensures(false);
    }

    public PasswordDeriveBytes(byte[] password, byte[] salt, CspParameters cspParams)
    {
    }

    public PasswordDeriveBytes(string strPassword, byte[] rgbSalt, CspParameters cspParams)
    {
    }

    public override void Reset()
    {
    }
    #endregion

    #region Properties and indexers
    public string HashName
    {
      get
      {
        return default(string);
      }
      set
      {
      }
    }

    public int IterationCount
    {
      get
      {
        return default(int);
      }
      set
      {
      }
    }

    public byte[] Salt
    {
      get
      {
        return default(byte[]);
      }
      set
      {
      }
    }
    #endregion
  }
}


text:
cross platform virtual memory utilities library.

## small example
```cpp
// address can be unsinged integer or pointer
const auto region = vmu::query(address);
if(region && region.protection().accessible()) {
    const auto new_flags = vmu::access::read_write_exec;
    vmu::protection_guard guard(address, new_flags);
    // do something
} // protection will be restored on scope exit
```

***

# quick reference
## `basic_region<Address>`
Provides information about a memory region. Can be obtained using `query` or `query_region`.

| function      | return type                      | explanation                   |
| ------------- |--------------------------------- | ----------------------------- |
| begin         | Address                          | beginning of region           |
| end           | Address                          | one past the end of region    |
| size          | uint big enough to store Address | size of region                |
| protection    | protection_t                     | the protection of page        |
| guarded       | bool                             | whether the region is guarded |
| shared        | bool                             | whether the region is shared  |
| operator bool | bool                             | whether the region is used    |

## `protection_t`
Wrapper class around protection flags.

| function   | return type         |
| ---------- |-------------------- |
| accessible | bool                |
| readable   | bool                |
| writable   | bool                |
| executable | bool                |
| native     | native_protection_t |
| to_flags   | access              |

## `access` enumeration
- read
- write
- exec
- read_write
- read_exec
- write_exec
- read_write_exec

## region query functions
Arguments in `[]` are not required - overloaded functions are present.
### `basic_region<RegionAddress> query([native_handle_t], Address, [std::error_code&])`
Returns information about a region that the given address is in.
### `std::vector<basic_region<RegionAddress>> query_range([native_handle_t], Address, Address, [std::error_code&])`
Returns information about regions that the given range of addresses are in.

The default for RegionAddress is `std::uintptr_t` or if the first function argument is of type
`native_handle_t` - `std::uint64_t`.

## region protection
### `protection_guard`
RAII based memory region protection and query class that protects a region of memory and
restores it upon destruction.

If adopt_protection_t tag type is given constructor performs no
actions and destructor sets the given protection instead.

In critical code it is recommended to manually call `restore` or define `VMU_HANDLE_PG_DESTRUCTOR_FAILURE`
macro that will handle errors in destructor, because by default on error memory regions is left unrestored.

constructor overloads:
- `protection_guard(Address, protection_t)`
- `protection_guard(Address, Address, protection_t)`
- `protection_guard(Range, protection_t)`
- `protection_guard(Address, protection_t, adopt_protection_t)`
- `protection_guard(Address, Address, protection_t, adopt_protection_t)`
- `protection_guard(Range, protection_t, adopt_protection_t)`

| function                    | explanation                                                             |
| --------------------------- | ----------------------------------------------------------------------- |
| restore([std::error_code&]) | restores protection to its original state                               |
| release                     | "releases" protection so it does not get restored on object destruction |

### `void protect(Address, protection_t, [std::error_code&])`
Changes protection of a single page that the address is in.
### `void protect(Address, Address, protection_t, [std::error_code&])`
Changes protections of pages that range of addresses are in.

## Address types
In library addresses are 32bit or 64bit unsigned integers or pointers. Conversions are applied
automatically. By default every address that can cause an overflow / underflow is checked and an
std::overflow_error is thrown if the target address type cannot represent the source address type.

An example of this would be if you called `vmu::query<std::uint32_t>(std::numeric_limits<std::uint32_t>::max() * 2)`
it's pretty obvious that this regions end will definetly overflow the requested 32 bit integer.


text:
#ifndef _NETIPX_IPX_VAR_H_
#define _NETIPX_IPX_VAR_H_

/*
 * IPX Kernel Structures and Variables
 */
struct	ipxstat {
	u_long	ipxs_total;		/* total packets received */
	u_long	ipxs_badsum;		/* checksum bad */
	u_long	ipxs_tooshort;		/* packet too short */
	u_long	ipxs_toosmall;		/* not enough data */
	u_long	ipxs_forward;		/* packets forwarded */
	u_long	ipxs_cantforward;	/* packets rcvd for unreachable dest */
	u_long	ipxs_delivered;		/* datagrams delivered to upper level*/
	u_long	ipxs_localout;		/* total ipx packets generated here */
	u_long	ipxs_odropped;		/* lost packets due to nobufs, etc. */
	u_long	ipxs_noroute;		/* packets discarded due to no route */
	u_long	ipxs_mtutoosmall;	/* the interface mtu is too small */
};

#ifdef _KERNEL

#ifdef SYSCTL_DECL
SYSCTL_DECL(_net_ipx);
SYSCTL_DECL(_net_ipx_ipx);
#endif

extern int ipxcksum;
extern long ipx_pexseq;
extern struct ipxstat ipxstat;
extern struct ipxpcb ipxrawpcb;
extern struct pr_usrreqs ipx_usrreqs;
extern struct pr_usrreqs ripx_usrreqs;
extern struct sockaddr_ipx ipx_netmask;
extern struct sockaddr_ipx ipx_hostmask;

extern union ipx_net ipx_zeronet;
extern union ipx_host ipx_zerohost;
extern union ipx_net ipx_broadnet;
extern union ipx_host ipx_broadhost;

struct ifnet;
struct ipx_addr;
struct mbuf;
struct thread;
struct route;
struct sockaddr;
struct socket;
struct sockopt;

void	ipx_abort(struct ipxpcb *ipxp);
u_short	ipx_cksum(struct mbuf *m, int len);
int	ipx_control(struct socket *so, u_long cmd, caddr_t data,
			 struct ifnet *ifp, struct thread *td);
void	ipx_ctlinput(int cmd, struct sockaddr *arg_as_sa, void *dummy);
int	ipx_ctloutput(struct socket *so, struct sockopt *sopt);
void	ipx_drop(struct ipxpcb *ipxp, int errno);
void	ipx_init(void);
void	ipx_input(struct mbuf *m, struct ipxpcb *ipxp);
void	ipxintr(void);
int	ipx_outputfl(struct mbuf *m0, struct route *ro, int flags);
int	ipx_output_type20(struct mbuf *);
int	ipx_peeraddr(struct socket *so, struct sockaddr **nam);
void	ipx_printhost(struct ipx_addr *addr);
int	ipx_sockaddr(struct socket *so, struct sockaddr **nam);
void	ipx_watch_output(struct mbuf *m, struct ifnet *ifp);

#endif /* _KERNEL */

#endif /* !_NETIPX_IPX_VAR_H_ */


text:
#include "third_party/blink/renderer/core/layout/svg/svg_resources_cache.h"

#include <memory>
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/layout/svg/layout_svg_resource_container.h"
#include "third_party/blink/renderer/core/layout/svg/layout_svg_resource_paint_server.h"
#include "third_party/blink/renderer/core/layout/svg/svg_resources.h"
#include "third_party/blink/renderer/core/layout/svg/svg_resources_cycle_solver.h"
#include "third_party/blink/renderer/core/svg/svg_document_extensions.h"

namespace blink {

SVGResourcesCache::SVGResourcesCache() = default;

SVGResourcesCache::~SVGResourcesCache() = default;

SVGResources* SVGResourcesCache::AddResourcesFromLayoutObject(
    LayoutObject& object,
    const ComputedStyle& style) {
  DCHECK(!cache_.Contains(&object));

  // Build a list of all resources associated with the passed LayoutObject.
  std::unique_ptr<SVGResources> new_resources =
      SVGResources::BuildResources(object, style);
  if (!new_resources)
    return nullptr;

  // Put object in cache.
  SVGResources* resources =
      cache_.Set(&object, std::move(new_resources)).stored_value->value.get();

  // Run cycle-detection _afterwards_, so self-references can be caught as well.
  HashSet<LayoutSVGResourceContainer*> resource_set;
  resources->BuildSetOfResources(resource_set);

  SVGResourcesCycleSolver solver;
  for (auto* resource_container : resource_set) {
    if (resource_container->FindCycle(solver))
      resources->ClearReferencesTo(resource_container);
  }
  return resources;
}

bool SVGResourcesCache::RemoveResourcesFromLayoutObject(LayoutObject& object) {
  std::unique_ptr<SVGResources> resources = cache_.Take(&object);
  return !!resources;
}

SVGResourcesCache::ResourceUpdateInfo
SVGResourcesCache::UpdateResourcesFromLayoutObject(
    LayoutObject& object,
    const ComputedStyle& new_style) {
  std::unique_ptr<SVGResources> old_resources = cache_.Take(&object);
  SVGResources* new_resources = AddResourcesFromLayoutObject(object, new_style);
  return {
      old_resources || new_resources,
      SVGResources::DifferenceNeedsLayout(old_resources.get(), new_resources)};
}

static inline SVGResourcesCache& ResourcesCache(Document& document) {
  return document.AccessSVGExtensions().ResourcesCache();
}

SVGResources* SVGResourcesCache::CachedResourcesForLayoutObject(
    const LayoutObject& layout_object) {
  return ResourcesCache(layout_object.GetDocument()).cache_.at(&layout_object);
}

void SVGResourcesCache::ClientLayoutChanged(LayoutObject& object) {
  SVGResources* resources = CachedResourcesForLayoutObject(object);
  if (!resources)
    return;
  // Invalidate the resources if either the LayoutObject itself changed,
  // or we have filter resources, which could depend on the layout of children.
  if (!object.SelfNeedsLayout() && !resources->Filter())
    return;
  SVGElementResourceClient* client = SVGResources::GetClient(object);
  InvalidationModeMask invalidation_flags =
      resources->RemoveClientFromCacheAffectingObjectBounds(*client);
  if (LayoutSVGResourcePaintServer* fill = resources->Fill()) {
    fill->RemoveClientFromCache(*client);
    invalidation_flags |= SVGResourceClient::kPaintInvalidation;
  }
  if (LayoutSVGResourcePaintServer* stroke = resources->Stroke()) {
    stroke->RemoveClientFromCache(*client);
    invalidation_flags |= SVGResourceClient::kPaintInvalidation;
  }
  if (invalidation_flags) {
    LayoutSVGResourceContainer::MarkClientForInvalidation(object,
                                                          invalidation_flags);
  }
}

static inline bool LayoutObjectCanHaveResources(
    const LayoutObject& layout_object) {
  return layout_object.GetNode() && layout_object.GetNode()->IsSVGElement() &&
         !layout_object.IsSVGInlineText();
}

static inline bool IsLayoutObjectOfResourceContainer(
    const LayoutObject& layout_object) {
  const LayoutObject* current = &layout_object;
  while (current) {
    if (current->IsSVGResourceContainer())
      return true;
    current = current->Parent();
  }
  return false;
}

void SVGResourcesCache::ClientStyleChanged(LayoutObject& layout_object,
                                           StyleDifference diff,
                                           const ComputedStyle& new_style) {
  DCHECK(layout_object.GetNode());
  DCHECK(layout_object.GetNode()->IsSVGElement());

  if (!diff.HasDifference() || !layout_object.Parent())
    return;

  // LayoutObjects for SVGFE*Element should not be calling this function.
  DCHECK(!layout_object.IsSVGFilterPrimitive());

  // Dynamic changes of CSS properties like 'clip-path' may require us to
  // recompute the associated resources for a LayoutObject.
  // TODO(fs): Avoid passing in a useless StyleDifference, but instead compare
  // oldStyle/newStyle to see which resources changed to be able to selectively
  // rebuild individual resources, instead of all of them.
  bool needs_layout = false;
  if (LayoutObjectCanHaveResources(layout_object)) {
    SVGResourcesCache& cache = ResourcesCache(layout_object.GetDocument());
    auto update_info =
        cache.UpdateResourcesFromLayoutObject(layout_object, new_style);
    if (update_info) {
      layout_object.SetNeedsPaintPropertyUpdate();
      // Since the visual rect has the bounds of the clip-path, mask and filter
      // baked in, and the visual rect is updated during layout, we need to
      // trigger layout if the style change could somehow have affected the
      // bounds that form the visual rect.
      needs_layout = update_info.needs_layout;
    }
  }

  // If this layoutObject is the child of ResourceContainer and it require
  // repainting that changes of CSS properties such as 'visibility',
  // request repainting.
  needs_layout |= diff.NeedsPaintInvalidation() &&
                  IsLayoutObjectOfResourceContainer(layout_object);

  LayoutSVGResourceContainer::MarkForLayoutAndParentResourceInvalidation(
      layout_object, needs_layout);
}

void SVGResourcesCache::ResourceReferenceChanged(LayoutObject& layout_object) {
  DCHECK(layout_object.IsSVG());
  DCHECK(layout_object.GetNode());
  DCHECK(layout_object.GetNode()->IsSVGElement());

  if (!layout_object.Parent())
    return;

  // Only LayoutObjects that can actually have resources should be pending and
  // hence be able to call this method.
  DCHECK(LayoutObjectCanHaveResources(layout_object));

  SVGResourcesCache& cache = ResourcesCache(layout_object.GetDocument());
  if (cache.UpdateResourcesFromLayoutObject(layout_object,
                                            layout_object.StyleRef())) {
    layout_object.SetNeedsPaintPropertyUpdate();
  }

  LayoutSVGResourceContainer::MarkForLayoutAndParentResourceInvalidation(
      layout_object, true);
}

void SVGResourcesCache::ClientWasAddedToTree(LayoutObject& layout_object) {
  if (!layout_object.GetNode())
    return;
  LayoutSVGResourceContainer::MarkForLayoutAndParentResourceInvalidation(
      layout_object, false);

  if (!LayoutObjectCanHaveResources(layout_object))
    return;
  SVGResourcesCache& cache = ResourcesCache(layout_object.GetDocument());
  if (cache.AddResourcesFromLayoutObject(layout_object,
                                         layout_object.StyleRef()))
    layout_object.SetNeedsPaintPropertyUpdate();
}

void SVGResourcesCache::ClientWillBeRemovedFromTree(
    LayoutObject& layout_object) {
  if (!layout_object.GetNode())
    return;
  LayoutSVGResourceContainer::MarkForLayoutAndParentResourceInvalidation(
      layout_object, false);

  if (!LayoutObjectCanHaveResources(layout_object))
    return;
  SVGResourcesCache& cache = ResourcesCache(layout_object.GetDocument());
  if (cache.RemoveResourcesFromLayoutObject(layout_object))
    layout_object.SetNeedsPaintPropertyUpdate();
}

void SVGResourcesCache::ClientDestroyed(LayoutObject& layout_object) {
  SVGResourcesCache& cache = ResourcesCache(layout_object.GetDocument());
  cache.RemoveResourcesFromLayoutObject(layout_object);
}

SVGResourcesCache::TemporaryStyleScope::TemporaryStyleScope(
    LayoutObject& layout_object,
    const ComputedStyle& style,
    const ComputedStyle& temporary_style)
    : layout_object_(layout_object),
      original_style_(style),
      temporary_style_(temporary_style),
      styles_are_equal_(style == temporary_style) {
  if (styles_are_equal_)
    return;
  DCHECK(LayoutObjectCanHaveResources(layout_object_));
  auto& element = To<SVGElement>(*layout_object_.GetNode());
  SVGResources::UpdatePaints(element, nullptr, temporary_style_);
  SwitchTo(temporary_style);
}

SVGResourcesCache::TemporaryStyleScope::~TemporaryStyleScope() {
  if (styles_are_equal_)
    return;
  auto& element = To<SVGElement>(*layout_object_.GetNode());
  SVGResources::ClearPaints(element, &temporary_style_);
  SwitchTo(original_style_);
}

void SVGResourcesCache::TemporaryStyleScope::SwitchTo(
    const ComputedStyle& style) {
  DCHECK(!styles_are_equal_);
  SVGResourcesCache& cache = ResourcesCache(layout_object_.GetDocument());
  cache.UpdateResourcesFromLayoutObject(layout_object_, style);
}

}  // namespace blink


text:
package io.quarkus.it.hibernate.reactive.mysql;

import static org.hamcrest.Matchers.is;

import org.junit.jupiter.api.Test;

import io.quarkus.test.junit.QuarkusTest;
import io.restassured.RestAssured;

/**
 * Test various JPA operations running in Quarkus when the session is injected without Uni or CompletionStage.
 */
@QuarkusTest
public class HibernateReactiveMySQLAlternativeTest {

    @Test
    public void reactiveFindMutiny() {
        RestAssured.when()
                .get("/alternative-tests/reactiveFindMutiny")
                .then()
                .body(is("{\"id\":5,\"name\":\"Aloi\"}"));
    }

    @Test
    public void reactivePersist() {
        RestAssured.when()
                .get("/alternative-tests/reactivePersist")
                .then()
                .body(is("Tulip"));
    }

    @Test
    public void reactiveRemoveTransientEntity() {
        RestAssured.when()
                .get("/alternative-tests/reactiveRemoveTransientEntity")
                .then()
                .body(is("OK"));
    }

    @Test
    public void reactiveRemoveManagedEntity() {
        RestAssured.when()
                .get("/alternative-tests/reactiveRemoveManagedEntity")
                .then()
                .body(is("OK"));
    }

    @Test
    public void reactiveUpdate() {
        RestAssured.when()
                .get("/alternative-tests/reactiveUpdate")
                .then()
                .body(is("Tina"));
    }
}


text:
class Dockerfile():
    def __init__(self, version, base, packages, java, misc=''):
        self.version = version
        self.base = base
        self.packages = packages
        self.java = java
        self.misc = misc

    def get_image_name(self):
        return 'aosp-docker-{version}'.format(version=self.version)

    def build_dockerfile(self):
        misc = ''
        if self.misc != '':
            misc = "RUN {cmd}".format(cmd=self.misc)
        d = ("FROM {base}\n"
             "MAINTAINER Mathias Garbe <mathias.garbe@inovex.de>\n"
             "RUN touch /env.bash && echo 'source /env.bash' > /rc.bash && echo 'cd $PWD' >> /rc.bash && echo \"trap \\\"declare -p | sed -e '/declare -[a-z]*r/d' > /env.bash && declare -f >> /env.bash\\\" EXIT\" >> /rc.bash\n"
             "RUN chmod 777 /env.bash && chmod 777 /rc.bash\n"
             "RUN apt-get update\n"
             "RUN {java}\n"
             "RUN echo \"dash dash/sh boolean false\" | debconf-set-selections && dpkg-reconfigure -p critical dash\n"
             "RUN apt-get install -y bash-completion vim wget {packages}\n"
             "ADD https://commondatastorage.googleapis.com/git-repo-downloads/repo /usr/local/bin/\n"
             "RUN chmod 755 /usr/local/bin/*\n"
             "{misc}\n"
             "VOLUME [\"/tmp/ccache\", \"/aosp\"]\n"
             "ENV USE_CCACHE 1\n"
             "ENV CCACHE_DIR /tmp/ccache\n"
             "RUN apt-get clean && rm -rf /var/tmp/*\n").format(base=self.base, java=self.java, packages=self.packages, misc=misc)
        return d

    @staticmethod
    def build_versions():
        java6_lucid = 'apt-get install -y python-software-properties && add-apt-repository ppa:sun-java-community-team/sun-java6 && apt-get update && echo sun-java6-jdk shared/accepted-sun-dlj-v1-1 select true | /usr/bin/debconf-set-selections && apt-get install -y sun-java6-jdk'
        java6_precise = 'echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" >> /etc/apt/sources.list.d/webupd8.list && apt-key adv --keyserver keyserver.ubuntu.com --recv-keys EEA14886 &&  echo oracle-java6-installer shared/accepted-oracle-license-v1-1 select true | debconf-set-selections && apt-get update && apt-get -y install oracle-java6-installer oracle-java6-set-default'
        java6_trusty = 'echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu trusty main" >> /etc/apt/sources.list.d/webupd8.list && apt-key adv --keyserver keyserver.ubuntu.com --recv-keys EEA14886 &&  echo oracle-java6-installer shared/accepted-oracle-license-v1-1 select true | debconf-set-selections && apt-get update && apt-get -y install oracle-java6-installer oracle-java6-set-default'
        java7 = 'apt-get install -y openjdk-7-jdk'

        misc_git = 'apt-get install -y python-software-properties && add-apt-repository ppa:git-core/ppa && apt-get update && apt-get install -y git'

        v = {}
        v['4.0'] = Dockerfile('4.0', 'ubuntu:10.04', 'bash-completion uboot-mkimage gnupg flex bison gperf build-essential zip curl zlib1g-dev libc6-dev lib32ncurses5-dev ia32-libs x11proto-core-dev libx11-dev lib32readline5-dev lib32z-dev libgl1-mesa-dev g++-multilib mingw32 tofrodos python-markdown libxml2-utils xsltproc', java6_lucid, misc_git)
        v['4.1'] = Dockerfile('4.1', 'ubuntu:12.04', 'bash-completion uboot-mkimage bc bison bsdmainutils build-essential curl flex g++-multilib gcc-multilib git gnupg gperf lib32ncurses5-dev lib32readline-gplv2-dev lib32z1-dev libesd0-dev libncurses5-dev libsdl1.2-dev libwxgtk2.8-dev libxml2-utils lzop pngcrush schedtool xsltproc zip zlib1g-dev', java6_precise)
        v['4.2'] = v['4.1']
        v['4.3'] = v['4.2']
        v['4.4'] = Dockerfile('4.4', 'ubuntu:14.04', 'bash-completion u-boot-tools bc bison bsdmainutils build-essential curl flex g++-multilib gcc-multilib git gnupg gperf lib32ncurses5-dev lib32readline-gplv2-dev lib32z1-dev libesd0-dev libncurses5-dev libsdl1.2-dev libwxgtk2.8-dev libxml2-utils lzop pngcrush schedtool xsltproc zip zlib1g-dev', java6_trusty)
        v['5.0'] = Dockerfile('5.0', 'ubuntu:14.04', 'bash-completion u-boot-tools bc bison bsdmainutils build-essential curl flex g++-multilib gcc-multilib git gnupg gperf lib32ncurses5-dev lib32readline-gplv2-dev lib32z1-dev libesd0-dev libncurses5-dev libsdl1.2-dev libwxgtk2.8-dev libxml2-utils lzop pngcrush schedtool xsltproc zip zlib1g-dev', java7)
        return v


text:
#ifndef DEVICEINFO_QUERY_H
#define DEVICEINFO_QUERY_H

#include "core/os/device/device.pb.h"

namespace query {

bool createContext(void* platform_data);
const char* contextError();
void destroyContext();

// The functions below require a context to be created.

int numABIs();
void abi(int idx, device::ABI* abi);

const char* hardwareName();

const char* cpuName();
const char* cpuVendor();
device::Architecture cpuArchitecture();
int cpuNumCores();

const char* gpuName();
const char* gpuVendor();

const char* instanceSerial();
const char* instanceName();

void glDriver(device::OpenGLDriver*);

device::OSKind osKind();
const char* osName();
const char* osBuild();
int osMajor();
int osMinor();
int osPoint();

}  // namespace query

#endif  // DEVICEINFO_QUERY_H


text:
<?php
namespace DeployNetBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class SerialType extends AbstractType
{

    private $fieldName = 'serialNumberIn';

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('id', 'hidden')
            ->add($this->fieldName, 'text')
            ->add('save', 'submit', ['label' => 'Save']);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => 'DeployNetBundle\Entity\WorkOrderLine'
        ]);
    }

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

    public function setFieldName($fieldName)
    {
        $this->fieldName = $fieldName;
    }
}


text:
const nxPreset = require('@nrwl/jest/preset');

module.exports = {
  ...nxPreset, ...{
    coverageReporters: ['text-summary', 'json', 'lcov']
  }
};


text:
require 'spec_helper'

module Drape
  describe Finders do
    protect_class ProductDecorator
    before { ProductDecorator.decorates_finders }

    describe '.find' do
      it 'proxies to the model class' do
        Product.should_receive(:find).with(1)
        ProductDecorator.find(1)
      end

      it 'decorates the result' do
        found = Product.new
        Product.stub(:find).and_return(found)
        decorator = ProductDecorator.find(1)
        expect(decorator).to be_a ProductDecorator
        expect(decorator.object).to be found
      end

      it 'passes context to the decorator' do
        Product.stub(:find)
        context = { some: 'context' }
        decorator = ProductDecorator.find(1, context: context)

        expect(decorator.context).to be context
      end
    end

    describe '.find_by_(x)' do
      it 'proxies to the model class' do
        Product.should_receive(:find_by_name).with('apples')
        ProductDecorator.find_by_name('apples')
      end

      it 'decorates the result' do
        found = Product.new
        Product.stub(:find_by_name).and_return(found)
        decorator = ProductDecorator.find_by_name('apples')
        expect(decorator).to be_a ProductDecorator
        expect(decorator.object).to be found
      end

      it 'proxies complex ProductDecorators' do
        Product.should_receive(:find_by_name_and_size).with('apples', 'large')
        ProductDecorator.find_by_name_and_size('apples', 'large')
      end

      it 'proxies find_last_by_(x) ProductDecorators' do
        Product.should_receive(:find_last_by_name_and_size).with('apples', 'large')
        ProductDecorator.find_last_by_name_and_size('apples', 'large')
      end

      it 'proxies find_or_initialize_by_(x) ProductDecorators' do
        Product.should_receive(:find_or_initialize_by_name_and_size).with('apples', 'large')
        ProductDecorator.find_or_initialize_by_name_and_size('apples', 'large')
      end

      it 'proxies find_or_create_by_(x) ProductDecorators' do
        Product.should_receive(:find_or_create_by_name_and_size).with('apples', 'large')
        ProductDecorator.find_or_create_by_name_and_size('apples', 'large')
      end

      it 'passes context to the decorator' do
        Product.stub(:find_by_name_and_size)
        context = { some: 'context' }
        decorator = ProductDecorator.find_by_name_and_size('apples', 'large', context: context)

        expect(decorator.context).to be context
      end
    end

    describe '.find_all_by_' do
      it 'proxies to the model class' do
        Product.should_receive(:find_all_by_name_and_size).with('apples', 'large').and_return([])
        ProductDecorator.find_all_by_name_and_size('apples', 'large')
      end

      it 'decorates the result' do
        found = [Product.new, Product.new]
        Product.stub(:find_all_by_name).and_return(found)
        decorator = ProductDecorator.find_all_by_name('apples')

        expect(decorator).to be_a Drape::CollectionDecorator
        expect(decorator.decorator_class).to be ProductDecorator
        expect(decorator).to eq found
      end

      it 'passes context to the decorator' do
        Product.stub(:find_all_by_name)
        context = { some: 'context' }
        decorator = ProductDecorator.find_all_by_name('apples', context: context)

        expect(decorator.context).to be context
      end
    end

    describe '.all' do
      it 'returns a decorated collection' do
        found = [Product.new, Product.new]
        Product.stub all: found
        decorator = ProductDecorator.all

        expect(decorator).to be_a Drape::CollectionDecorator
        expect(decorator.decorator_class).to be ProductDecorator
        expect(decorator).to eq found
      end

      it 'passes context to the decorator' do
        Product.stub(:all)
        context = { some: 'context' }
        decorator = ProductDecorator.all(context: context)

        expect(decorator.context).to be context
      end
    end

    describe '.first' do
      it 'proxies to the model class' do
        Product.should_receive(:first)
        ProductDecorator.first
      end

      it 'decorates the result' do
        first = Product.new
        Product.stub(:first).and_return(first)
        decorator = ProductDecorator.first
        expect(decorator).to be_a ProductDecorator
        expect(decorator.object).to be first
      end

      it 'passes context to the decorator' do
        Product.stub(:first)
        context = { some: 'context' }
        decorator = ProductDecorator.first(context: context)

        expect(decorator.context).to be context
      end
    end

    describe '.last' do
      it 'proxies to the model class' do
        Product.should_receive(:last)
        ProductDecorator.last
      end

      it 'decorates the result' do
        last = Product.new
        Product.stub(:last).and_return(last)
        decorator = ProductDecorator.last
        expect(decorator).to be_a ProductDecorator
        expect(decorator.object).to be last
      end

      it 'passes context to the decorator' do
        Product.stub(:last)
        context = { some: 'context' }
        decorator = ProductDecorator.last(context: context)

        expect(decorator.context).to be context
      end
    end
  end
end


text:
@implementation DJSignupViewController
{
    __weak IBOutlet UITextField *mUserName;
    __weak IBOutlet UITextField *mPassword;
    __weak IBOutlet UITextField *mConfirmPassword;
    IBOutlet UIScrollView       *mScrollView;
    __weak UITextField          *mActiveField;

}

#pragma mark - view

- (void)viewDidLoad
{
    [super viewDidLoad];

    [mUserName setDelegate:self];
    [mPassword setDelegate:self];
    [mConfirmPassword setDelegate:self];

    //keyboard control
    [self registerForKeyboardNotification];
    UITapGestureRecognizer *backgroundTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backgroundTapped:)];
    [mScrollView addGestureRecognizer:backgroundTapGesture];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];

    if ([self isViewLoaded])
    {
        mUserName = nil;
        mPassword = nil;
        mConfirmPassword = nil;
        mScrollView = nil;
        mActiveField = nil;
    }
}

#pragma mark - action

- (IBAction)registerButtonTapped:(id)sender
{
    if ([[mUserName text] length] != 0 && [[mUserName text] length] <= 10
        && [[mPassword text] length] != 0 && [[mPassword text] length] >= 8
        && [[mPassword text] isEqualToString:[mConfirmPassword text]])
    {
        [self signUp];
    }
    else if ([[mUserName text] length] == 0 || [[mPassword text] length] == 0)
    {
        [[[UIAlertView alloc] initWithTitle:@"Missing information"
                                    message:@"Make sure you fill all of the information"
                                   delegate:nil
                          cancelButtonTitle:@"OK"
                          otherButtonTitles:nil, nil] show];
    }
    else
    {
        [[[UIAlertView alloc] initWithTitle:@"Not match password"
                                    message:@"Check your password"
                                   delegate:nil
                          cancelButtonTitle:@"OK"
                          otherButtonTitles:nil, nil] show];
    }
}

- (IBAction)backgroundTapped:(id)sender
{
    //keyboard hide
    [[self view] endEditing:YES];
}

#pragma mark - text field delegate

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    mActiveField = textField;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    mActiveField = nil;

    //password length check
    if ([textField tag] == 1 && [[textField text] length] < 8)
    {
        [[[UIAlertView alloc] initWithTitle:@"Check password length"
                                    message:@"Password must be 8 or more characters"
                                   delegate:self
                          cancelButtonTitle:@"OK"
                          otherButtonTitles:nil, nil] show];
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    //user name length check
    if([textField tag] == 0 && [[[textField text] stringByAppendingString:string] length] > 10)
    {
        [[[UIAlertView alloc] initWithTitle:@"Check user name length"
                                    message:@"User name must be 10 characters or less"
                                   delegate:self
                          cancelButtonTitle:@"OK"
                          otherButtonTitles:nil, nil] show];
        return NO;
    }
    //when password is too long
    else if([textField tag] == 1 && [[[textField text] stringByAppendingString:string] length] > 40)
    {
        [[[UIAlertView alloc] initWithTitle:@"Password is too long"
                                    message:@"You can determine other password which is easy to remember"
                                   delegate:self
                          cancelButtonTitle:@"OK"
                          otherButtonTitles:nil, nil] show];

        return NO;
    }

    return YES;
}

#pragma mark - keyboard

- (void)registerForKeyboardNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardDidShow:)
                                                 name:UIKeyboardDidShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];

}

- (void)keyboardDidShow:(NSNotification *)notification
{
    NSDictionary *info = [notification userInfo];
    CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    UIEdgeInsets insets = UIEdgeInsetsMake(0, 0, keyboardSize.height, 0);
    [mScrollView setContentInset:insets];
    [mScrollView setScrollIndicatorInsets:insets];

    CGRect rect = [self view].frame;
    rect.size.height -= keyboardSize.height;

    CGPoint activeFieldEndPoint = CGPointMake([mActiveField frame].origin.x, [mActiveField frame].origin.y + [mActiveField frame].size.height);

    if (!CGRectContainsPoint(rect, activeFieldEndPoint))
    {
        CGPoint scrollPoint = CGPointMake(0, rect.size.height - [mActiveField frame].origin.y + 10);
        [mScrollView setContentOffset:scrollPoint animated:YES];
    }
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    UIEdgeInsets insets = UIEdgeInsetsZero;
    [mScrollView setContentInset:insets];
    [mScrollView setScrollIndicatorInsets:insets];
}

#pragma mark - private

- (void)signUp
{
    PFUser *user = [PFUser user];
    [user setUsername:[mUserName text]];
    [user setPassword:[mPassword text]];

    [user signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error)
     {
         if (succeeded)
         {
             [self performSegueWithIdentifier:@"signupCompleted" sender:self];
         }
         else if (error)
         {
             [[[UIAlertView alloc] initWithTitle:@"Fail to signup"
                                         message:@"Username already taken"
                                        delegate:nil
                               cancelButtonTitle:@"OK"
                               otherButtonTitles:nil, nil] show];

             return;

         }

     }];
}

@end


text:
// <auto-generated>
// Copyright (c) Microsoft and contributors.  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.
//
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
//
// For documentation on code generator please visit
//   https://aka.ms/nrp-code-generation
// Please contact wanrpdev@microsoft.com if you need to make changes to this file.
// </auto-generated>

using Microsoft.Azure.Management.Network.Models;
using Microsoft.WindowsAzure.Commands.Common.Attributes;
using Newtonsoft.Json;

namespace Microsoft.Azure.Commands.Network.Models
{
    public partial class PSExpressRouteCircuitConnection : PSChildResource
    {
        [JsonProperty(Order = 1)]
        [Ps1Xml(Target = ViewControl.Table)]
        public string AddressPrefix { get; set; }
        [JsonProperty(Order = 1)]
        public string AuthorizationKey { get; set; }
        [JsonProperty(Order = 1)]
        [Ps1Xml(Target = ViewControl.Table)]
        public string CircuitConnectionStatus { get; set; }
        [JsonProperty(Order = 1)]
        [Ps1Xml(Target = ViewControl.Table)]
        public string ProvisioningState { get; set; }
        [JsonProperty(Order = 1)]
        public PSResourceId ExpressRouteCircuitPeering { get; set; }
        [JsonProperty(Order = 1)]
        public PSResourceId PeerExpressRouteCircuitPeering { get; set; }

        [JsonIgnore]
        public string ExpressRouteCircuitPeeringText
        {
            get { return JsonConvert.SerializeObject(ExpressRouteCircuitPeering, Formatting.Indented, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore }); }
        }

        [JsonIgnore]
        public string PeerExpressRouteCircuitPeeringText
        {
            get { return JsonConvert.SerializeObject(PeerExpressRouteCircuitPeering, Formatting.Indented, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore }); }
        }
    }
}


text:
<?php
/**
 * @group Trl_DateHelper
 */
class Kwc_Trl_DateHelper_Test extends Kwc_TestAbstract
{
    public function setUp()
    {
        parent::setUp('Kwc_Trl_DateHelper_Root');
    }

    public function testDe()
    {
        $c = $this->_root->getComponentById('root-master_date');
        $this->assertEquals('de', $c->getLanguage());
        $this->assertEquals('d.m.Y', $c->trlKwf('Y-m-d'));
        $this->assertEquals('09.06.1983', $c->render());

        $c = $this->_root->getComponentById('root-master_dateTime');
        $this->assertEquals('09.06.1983 15:30', $c->render());
    }

    public function testEn()
    {
        $c = $this->_root->getComponentById('root-en_date');
        $this->assertEquals('en', $c->getLanguage());
        $this->assertEquals('Y-m-d', $c->trlKwf('Y-m-d'));
        $this->assertEquals('1983-06-09', $c->render());

        $c = $this->_root->getComponentById('root-en_dateTime');
        $this->assertEquals('1983-06-09 15:30', $c->render());
    }
}


text:
Create a New League or
Join One of the Leagues Below

    <form role="form" (submit)="onCreateLeague($event, leagueName.value, createPassword.value)">

          League Name

          <input type="text" id="leagueName" #leagueName placeholder="League Name" autofocus>

          League Password

          <input type="password" id="createPassword" #createPassword placeholder="League Password">

      <button class="login-btn" type="submit">Create League</button>
    </form>

Silly Season Fantasy Leagues

		Players are warming up

						{{selectedLeague===league.league.id?'▲':'▼'}} {{league.league.league_name}}

{{league.teams}} {{league.teams > 1 ? "Teams" : "Team"}}, Created by {{league.owner.name}}

						<form *ngIf="joinButton" role="form" (submit)="onJoinLeague($event, league.league.id, leaguePassword.value)" class="float-right">
							<input type="password" id="leaguePassword" #leaguePassword placeholder="League Password">
							<button type="submit">Join League</button>
						</form>

										Team
										Manager
										Pts
										GWP
										In the Bank

											Team Value

									{{i+1}}
									{{team.team_name}}
									{{team.name}}
									{{team.totpoints}}
									{{team.gwpoints}}

										{{team.money | currency:'GBP':true:'4.0-0'}}

										{{team.teamvalue | currency:'GBP':true:'4.0-0'}}


text: About Us


text:
var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
import { QueryBuilder } from "./QueryBuilder";
import { SqlServerDriver } from "../driver/sqlserver/SqlServerDriver";
import { PostgresDriver } from "../driver/postgres/PostgresDriver";
import { AbstractSqliteDriver } from "../driver/sqlite-abstract/AbstractSqliteDriver";
/**
 * Allows to build complex sql queries in a fashion way and execute those queries.
 */
var InsertQueryBuilder = /** @class */ (function (_super) {
    __extends(InsertQueryBuilder, _super);
    function InsertQueryBuilder() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    // -------------------------------------------------------------------------
    // Public Implemented Methods
    // -------------------------------------------------------------------------
    /**
     * Gets generated sql query without parameters being replaced.
     */
    InsertQueryBuilder.prototype.getQuery = function () {
        var sql = this.createInsertExpression();
        return sql.trim();
    };
    /**
     * Optional returning/output clause.
     */
    InsertQueryBuilder.prototype.output = function (output) {
        return this.returning(output);
    };
    // -------------------------------------------------------------------------
    // Public Methods
    // -------------------------------------------------------------------------
    /**
     * Specifies INTO which entity's table insertion will be executed.
     */
    InsertQueryBuilder.prototype.into = function (entityTarget, columns) {
        var mainAlias = this.createFromAlias(entityTarget);
        this.expressionMap.setMainAlias(mainAlias);
        this.expressionMap.insertColumns = columns || [];
        return this;
    };
    /**
     * Values needs to be inserted into table.
     */
    InsertQueryBuilder.prototype.values = function (values) {
        this.expressionMap.valuesSet = values;
        return this;
    };
    /**
     * Optional returning/output clause.
     */
    InsertQueryBuilder.prototype.returning = function (returning) {
        if (this.connection.driver instanceof SqlServerDriver || this.connection.driver instanceof PostgresDriver) {
            this.expressionMap.returning = returning;
            return this;
        }
        else
            throw new Error("OUTPUT or RETURNING clause only supported by MS SQLServer or PostgreSQL");
    };
    /**
     * Adds additional ON CONFLICT statement supported in postgres.
     */
    InsertQueryBuilder.prototype.onConflict = function (statement) {
        this.expressionMap.onConflict = statement;
        return this;
    };
    // -------------------------------------------------------------------------
    // Protected Methods
    // -------------------------------------------------------------------------
    /**
     * Creates INSERT express used to perform insert query.
     */
    InsertQueryBuilder.prototype.createInsertExpression = function () {
        var _this = this;
        var valueSets = this.getValueSets();
        var values, columnNames;
        if (this.expressionMap.mainAlias.hasMetadata) {
            var columns_1 = this.expressionMap.mainAlias.metadata.columns.filter(function (column) {
                if (!_this.expressionMap.insertColumns.length)
                    return !column.isGenerated;
                return _this.expressionMap.insertColumns.indexOf(column.propertyPath);
            });
            // get a table name and all column database names
            columnNames = columns_1.map(function (column) { return _this.escape(column.databaseName); }).join(", ");
            // get values needs to be inserted
            values = valueSets.map(function (valueSet, insertionIndex) {
                var columnValues = columns_1.map(function (column) {
                    var paramName = "_inserted_" + insertionIndex + "_" + column.databaseName;
                    var value = _this.connection.driver.preparePersistentValue(column.getEntityValue(valueSet), column);
                    if (value instanceof Function) {
                        return value();
                    }
                    else if (value === undefined) {
                        if (_this.connection.driver instanceof AbstractSqliteDriver) {
                            return "NULL";
                        }
                        else {
                            return "DEFAULT";
                        }
                    }
                    else {
                        if (_this.connection.driver instanceof SqlServerDriver) {
                            _this.setParameter(paramName, _this.connection.driver.parametrizeValue(column, value));
                        }
                        else {
                            _this.setParameter(paramName, value);
                        }
                        return ":" + paramName;
                    }
                });
                return "(" + columnValues.join(",") + ")";
            }).join(", ");
        }
        else {
            // get a table name and all column database names
            columnNames = this.expressionMap.insertColumns.join(", ");
            // get values needs to be inserted
            values = valueSets.map(function (valueSet, insertionIndex) {
                var columnValues = Object.keys(valueSet).map(function (columnName) {
                    var paramName = "_inserted_" + insertionIndex + "_" + columnName;
                    var value = valueSet[columnName];
                    if (value instanceof Function) {
                        return value();
                    }
                    else if (value === undefined) {
                        if (_this.connection.driver instanceof AbstractSqliteDriver) {
                            return "NULL";
                        }
                        else {
                            return "DEFAULT";
                        }
                    }
                    else {
                        _this.setParameter(paramName, value);
                        return ":" + paramName;
                    }
                });
                return "(" + columnValues.join(",") + ")";
            }).join(", ");
        }
        // generate sql query
        if (this.expressionMap.returning !== "" && this.connection.driver instanceof PostgresDriver) {
            return "INSERT INTO " + this.getTableName(this.getMainTableName()) + (columnNames ? "(" + columnNames + ")" : "") + " VALUES " + values + (this.expressionMap.onConflict ? " ON CONFLICT " + this.expressionMap.onConflict : "") + " RETURNING " + this.expressionMap.returning;
        }
        else if (this.expressionMap.returning !== "" && this.connection.driver instanceof SqlServerDriver) {
            return "INSERT INTO " + this.getTableName(this.getMainTableName()) + "(" + columnNames + ") OUTPUT " + this.expressionMap.returning + " VALUES " + values;
        }
        else {
            return "INSERT INTO " + this.getTableName(this.getMainTableName()) + "(" + columnNames + ") VALUES " + values + (this.expressionMap.onConflict ? " ON CONFLICT " + this.expressionMap.onConflict : "");
        }
    };
    /**
     * Gets array of values need to be inserted into the target table.
     */
    InsertQueryBuilder.prototype.getValueSets = function () {
        if (this.expressionMap.valuesSet instanceof Array && this.expressionMap.valuesSet.length > 0)
            return this.expressionMap.valuesSet;
        if (this.expressionMap.valuesSet instanceof Object)
            return [this.expressionMap.valuesSet];
        throw new Error("Cannot perform insert query because values are not defined. Call \"qb.values(...)\" method to specify inserted values.");
    };
    return InsertQueryBuilder;
}(QueryBuilder));
export { InsertQueryBuilder };

//# sourceMappingURL=InsertQueryBuilder.js.map