text:
<Styles>
<Style name="bouton" element="span">
<Attribute name="class" value="bouton" />
</Style>
<Style name="bloc_comfin" element="span">
<Attribute name="class" value="bloc_comfin" />
</Style>
<Style name="bloc_comfin_en" element="span">
<Attribute name="class" value="bloc_comfin_en" />
</Style>
<Style name="bloc_actufin" element="span">
<Attribute name="class" value="bloc_actufin" />
</Style>
<Style name="bloc_agenda" element="span">
<Attribute name="class" value="bloc_agenda" />
</Style>
<Style name="bloc_agenda_table" element="span">
<Attribute name="class" value="bloc_agenda_table" />
</Style>
<Style name="bloc_agenda_table_td1" element="span">
<Attribute name="class" value="bloc_agenda_table_td1" />
</Style>
<Style name="bloc_agenda_table_td2" element="span">
<Attribute name="class" value="bloc_agenda_table_td2" />
</Style>
<Style name="agenda_cc" element="span">
<Attribute name="class" value="agenda_cc" />
</Style>
<Style name="bloc_stages_en" element="span">
<Attribute name="class" value="bloc_stages_en" />
</Style>
<Style name="bloc_stages" element="span">
<Attribute name="class" value="bloc_stages" />
</Style>
<Style name="bloc_stages_table" element="span">
<Attribute name="class" value="bloc_stages_table" />
</Style>
<Style name="bloc_stages_table_td1" element="span">
<Attribute name="class" value="bloc_stages_table_td1" />
</Style>
<Style name="bloc_stages_table_td2" element="span">
<Attribute name="class" value="bloc_stages_table_td2" />
</Style>
<Style name="liens_bas" element="span">
<Attribute name="class" value="liens_bas" />
</Style>
<Style name="recherchesite" element="span">
<Attribute name="class" value="recherchesite" />
</Style>
<Style name="champtxt" element="span">
<Attribute name="class" value="champtxt" />
</Style>
<Style name="boutonok" element="span">
<Attribute name="class" value="boutonok" />
</Style>
<Style name="titre_01" element="span">
<Attribute name="class" value="titre_01" />
</Style>
<Style name="table_bleu" element="span">
<Attribute name="class" value="table_bleu" />
</Style>
<Style name="table_bleu_td2" element="span">
<Attribute name="class" value="table_bleu_td2" />
</Style>
<Style name="table_date" element="span">
<Attribute name="class" value="table_date" />
</Style>
<Style name="table_td_17" element="span">
<Attribute name="class" value="table_td_17" />
</Style>
<Style name="table_td_18" element="span">
<Attribute name="class" value="table_td_18" />
</Style>
<Style name="table_td_20" element="span">
<Attribute name="class" value="table_td_20" />
</Style>
<Style name="table_td_30" element="span">
<Attribute name="class" value="table_td_30" />
</Style>
<Style name="table_td_39" element="span">
<Attribute name="class" value="table_td_39" />
</Style>
<Style name="table_td_50" element="span">
<Attribute name="class" value="table_td_50" />
</Style>
<Style name="table_td_89" element="span">
<Attribute name="class" value="table_td_89" />
</Style>
<Style name="table_td_97" element="span">
<Attribute name="class" value="table_td_97" />
</Style>
<Style name="table_td_98" element="span">
<Attribute name="class" value="table_td_98" />
</Style>
<Style name="table_td_00" element="span">
<Attribute name="class" value="table_td_00" />
</Style>
<Style name="table_td_02" element="span">
<Attribute name="class" value="table_td_02" />
</Style>
<Style name="table_td_03" element="span">
<Attribute name="class" value="table_td_03" />
</Style>
<Style name="table_td_04" element="span">
<Attribute name="class" value="table_td_04" />
</Style>
<Style name="table_td_05" element="span">
<Attribute name="class" value="table_td_05" />
</Style>
<Style name="table_td_06" element="span">
<Attribute name="class" value="table_td_06" />
</Style>
<Style name="div_action_global" element="span">
<Attribute name="class" value="div_action_global" />
</Style>
<Style name="texte_action" element="span">
<Attribute name="class" value="texte_action" />
</Style>
<Style name="table_global_action" element="span">
<Attribute name="class" value="table_global_action" />
</Style>
<Style name="table_global_action_td1" element="span">
<Attribute name="class" value="table_global_action_td1" />
</Style>
<Style name="table_action" element="span">
<Attribute name="class" value="table_action" />
</Style>
<Style name="table2" element="span">
<Attribute name="class" value="table2" />
</Style>
<Style name="table2_td1" element="span">
<Attribute name="class" value="table2_td1" />
</Style>
<Style name="table2_td2" element="span">
<Attribute name="class" value="table2_td2" />
</Style>
<Style name="table2_td3" element="span">
<Attribute name="class" value="table2_td3" />
</Style>
<Style name="table_pdt" element="span">
<Attribute name="class" value="table_pdt" />
</Style>
<Style name="table_pdt_img" element="span">
<Attribute name="class" value="table_pdt_img" />
</Style>
<Style name="table_pdt_td1" element="span">
<Attribute name="class" value="table_pdt_td1" />
</Style>
<Style name="table_pdt_td2" element="span">
<Attribute name="class" value="table_pdt_td2" />
</Style>
<Style name="table_pdt_td3" element="span">
<Attribute name="class" value="table_pdt_td3" />
</Style>
<Style name="table_double_ATV" element="span">
<Attribute name="class" value="table_double_ATV" />
</Style>
<Style name="table_double_satellite" element="span">
<Attribute name="class" value="table_double_satellite" />
</Style>
<Style name="table_double_g" element="span">
<Attribute name="class" value="table_double_g" />
</Style>
<Style name="table_double_d" element="span">
<Attribute name="class" value="table_double_d" />
</Style>
<Style name="emploi" element="span">
<Attribute name="class" value="emploi" />
</Style>
<Style name="bloc_recherche" element="span">
<Attribute name="class" value="bloc_recherche" />
</Style>
<Style name="deroulant2" element="span">
<Attribute name="class" value="deroulant2" />
</Style>
<Style name="result" element="span">
<Attribute name="class" value="result" />
</Style>
<Style name="ligne1" element="span">
<Attribute name="class" value="ligne1" />
</Style>
<Style name="ligne2" element="span">
<Attribute name="class" value="ligne2" />
</Style>
<Style name="ligne3" element="span">
<Attribute name="class" value="ligne3" />
</Style>
<Style name="ligne4" element="span">
<Attribute name="class" value="ligne4" />
</Style>
<Style name="ligne5" element="span">
<Attribute name="class" value="ligne5" />
</Style>
<Style name="ligne6" element="span">
<Attribute name="class" value="ligne6" />
</Style>
<Style name="ligne7" element="span">
<Attribute name="class" value="ligne7" />
</Style>
<Style name="formulaire" element="span">
<Attribute name="class" value="formulaire" />
</Style>
<Style name="langue" element="span">
<Attribute name="class" value="langue" />
</Style>
<Style name="sites_latec" element="span">
<Attribute name="class" value="sites_latec" />
</Style>
<Style name="table_sites_general" element="span">
<Attribute name="class" value="table_sites_general" />
</Style>
<Style name="table_sites" element="span">
<Attribute name="class" value="table_sites" />
</Style>
<Style name="table_sites_td" element="span">
<Attribute name="class" value="table_sites_td" />
</Style>
<Style name="table_sites_td2" element="span">
<Attribute name="class" value="table_sites_td2" />
</Style>
<Style name="table_sites2" element="span">
<Attribute name="class" value="table_sites2" />
</Style>
<Style name="table_sites2_td" element="span">
<Attribute name="class" value="table_sites2_td" />
</Style>
<Style name="titres_sites2" element="span">
<Attribute name="class" value="titres_sites2" />
</Style>
<Style name="titres_sites" element="span">
<Attribute name="class" value="titres_sites" />
</Style>
<Style name="titres_sites3" element="span">
<Attribute name="class" value="titres_sites3" />
</Style>
<Style name="sites_contenu" element="span">
<Attribute name="class" value="sites_contenu" />
</Style>
<Style name="sites_contenu2" element="span">
<Attribute name="class" value="sites_contenu2" />
</Style>
<Style name="synthesefi" element="span">
<Attribute name="class" value="synthesefi" />
</Style>
<Style name="synthesefi_td1" element="span">
<Attribute name="class" value="synthesefi_td1" />
</Style>
<Style name="rapports_telechargement" element="span">
<Attribute name="class" value="rapports_telechargement" />
</Style>
<Style name="rapports_telechargement_en" element="span">
<Attribute name="class" value="rapports_telechargement_en" />
</Style>
<Style name="lettre" element="span">
<Attribute name="class" value="lettre" />
</Style>
<Style name="lettre_en" element="span">
<Attribute name="class" value="lettre_en" />
</Style>
<Style name="lettre_content" element="span">
<Attribute name="class" value="lettre_content" />
</Style>
<Style name="comptederesultat" element="span">
<Attribute name="class" value="comptederesultat" />
</Style>
<Style name="comptederesultaten" element="span">
<Attribute name="class" value="comptederesultaten" />
</Style>
<Style name="comptederesultat_table" element="span">
<Attribute name="class" value="comptederesultat_table" />
</Style>
<Style name="comptederesultat_table_td1" element="span">
<Attribute name="class" value="comptederesultat_table_td1" />
</Style>
<Style name="comptederesultat_table_td2" element="span">
<Attribute name="class" value="comptederesultat_table_td2" />
</Style>
<Style name="comptederesultat_td1" element="span">
<Attribute name="class" value="comptederesultat_td1" />
</Style>
<Style name="comptederesultat_td2" element="span">
<Attribute name="class" value="comptederesultat_td2" />
</Style>
<Style name="comptederesultat_td3" element="span">
<Attribute name="class" value="comptederesultat_td3" />
</Style>
<Style name="comptederesultat_td4" element="span">
<Attribute name="class" value="comptederesultat_td4" />
</Style>
<Style name="chiffredaffaires" element="span">
<Attribute name="class" value="chiffredaffaires" />
</Style>
<Style name="chiffredaffaires_en" element="span">
<Attribute name="class" value="chiffredaffaires_en" />
</Style>
<Style name="bilansimplifie" element="span">
<Attribute name="class" value="bilansimplifie" />
</Style>
<Style name="bilansimplifieen" element="span">
<Attribute name="class" value="bilansimplifieen" />
</Style>
<Style name="bilansimplifie_td" element="span">
<Attribute name="class" value="bilansimplifie_td" />
</Style>
<Style name="bilansimplifie_td1" element="span">
<Attribute name="class" value="bilansimplifie_td1" />
</Style>
<Style name="bilansimplifie_td2" element="span">
<Attribute name="class" value="bilansimplifie_td2" />
</Style>
<Style name="bilansimplifie_td3" element="span">
<Attribute name="class" value="bilansimplifie_td3" />
</Style>
<Style name="fond_ombre" element="span">
<Attribute name="class" value="fond_ombre" />
</Style>
<Style name="resultat_tr" element="span">
<Attribute name="class" value="resultat_tr" />
</Style>
<Style name="resultatnet" element="span">
<Attribute name="class" value="resultatnet" />
</Style>
<Style name="resultatoperationnel" element="span">
<Attribute name="class" value="resultatoperationnel" />
</Style>
<Style name="ventilationducaparactivite" element="span">
<Attribute name="class" value="ventilationducaparactivite" />
</Style>
<Style name="ventilationducaparclient" element="span">
<Attribute name="class" value="ventilationducaparclient" />
</Style>
<Style name="portefeuilledecommandes" element="span">
<Attribute name="class" value="portefeuilledecommandes" />
</Style>
<Style name="portefeuilleparclient" element="span">
<Attribute name="class" value="portefeuilleparclient" />
</Style>
<Style name="strategie" element="span">
<Attribute name="class" value="strategie" />
</Style>
<Style name="table_implantations_td1" element="span">
<Attribute name="class" value="table_implantations_td1" />
</Style>
<Style name="table_objectifs" element="span">
<Attribute name="class" value="table_objectifs" />
</Style>
<Style name="table_organigramme" element="span">
<Attribute name="class" value="table_organigramme" />
</Style>
<Style name="table_organigramme_organe" element="span">
<Attribute name="class" value="table_organigramme_organe" />
</Style>
<Style name="table_organigramme_organe2" element="span">
<Attribute name="class" value="table_organigramme_organe2" />
</Style>
<Style name="table_organigramme_organe2_td" element="span">
<Attribute name="class" value="table_organigramme_organe2_td" />
</Style>
<Style name="table_organigramme_organe2_td2" element="span">
<Attribute name="class" value="table_organigramme_organe2_td2" />
</Style>
<Style name="table_organigramme_organe_td1" element="span">
<Attribute name="class" value="table_organigramme_organe_td1" />
</Style>
<Style name="table_organigramme_td1" element="span">
<Attribute name="class" value="table_organigramme_td1" />
</Style>
<Style name="table_organigramme_td2" element="span">
<Attribute name="class" value="table_organigramme_td2" />
</Style>
<Style name="table_organigramme_td3" element="span">
<Attribute name="class" value="table_organigramme_td3" />
</Style>
<Style name="table_organigramme_petit" element="span">
<Attribute name="class" value="table_organigramme_petit" />
</Style>
<Style name="table_organigramme_petit_td" element="span">
<Attribute name="class" value="table_organigramme_petit_td" />
</Style>
<Style name="deroulant" element="span">
<Attribute name="class" value="deroulant" />
</Style>
<Style name="pop_up_general" element="span">
<Attribute name="class" value="pop_up_general" />
</Style>
<Style name="fermer" element="span">
<Attribute name="class" value="fermer" />
</Style>
<Style name="plandusite" element="span">
<Attribute name="class" value="plandusite" />
</Style>
<Style name="plandusite2" element="span">
<Attribute name="class" value="plandusite2" />
</Style>
<Style name="plandusite2_td1" element="span">
<Attribute name="class" value="plandusite2_td1" />
</Style>
<Style name="plandusite2_td2" element="span">
<Attribute name="class" value="plandusite2_td2" />
</Style>
<Style name="plandusite2_td3" element="span">
<Attribute name="class" value="plandusite2_td3" />
</Style>
<Style name="table_liens" element="span">
<Attribute name="class" value="table_liens" />
</Style>
<Style name="table_map" element="span">
<Attribute name="class" value="table_map" />
</Style>
<Style name="table_map_td1" element="span">
<Attribute name="class" value="table_map_td1" />
</Style>
<Style name="table_map_td2" element="span">
<Attribute name="class" value="table_map_td2" />
</Style>
<Style name="table_map_td3" element="span">
<Attribute name="class" value="table_map_td3" />
</Style>
<Style name="leveltrois" element="span">
<Attribute name="class" value="leveltrois" />
</Style>
<Style name="leveltroisencours" element="span">
<Attribute name="class" value="leveltroisencours" />
</Style>
<Style name="table_recherche" element="span">
<Attribute name="class" value="table_recherche" />
</Style>
<Style name="table_recherche_td1" element="span">
<Attribute name="class" value="table_recherche_td1" />
</Style>
<Style name="table_recherche_td2" element="span">
<Attribute name="class" value="table_recherche_td2" />
</Style>
<Style name="titre_recherche" element="span">
<Attribute name="class" value="titre_recherche" />
</Style>
<Style name="rubrique" element="span">
<Attribute name="class" value="rubrique" />
</Style>
<Style name="recherche_fermer" element="span">
<Attribute name="class" value="recherche_fermer" />
</Style>
<Style name="bt_fermer" element="span">
<Attribute name="class" value="bt_fermer" />
</Style>
<Style name="acces" element="span">
<Attribute name="class" value="acces" />
</Style>
<Style name="acces_texte" element="span">
<Attribute name="class" value="acces_texte" />
</Style>
</Styles>


text:
<?php

/*
 * Carousel Template for gallery
 */

$cnt = count($slides);  // Slides number
?>
<?php for ($i = 1; $i <= $cnt; $i++): ?>
<div class="modal" id="<?=$gallery->id.'_'.$slides[$i-1]->id;?>">

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

<?=$gallery->title;?><?php if($slides[$i-1]->title) echo ': '.$slides[$i-1]->title;?>

        <?=($i-1)
            ? HTML::anchor('#'.$gallery->id.'_'.$slides[$i-2]->id, '', array('data-toggle' => 'modal', 'data-dismiss'=>'modal', 'class'=>'btn pull-left', 'title'=>'Назад', 'data-slide'=>'prev'))
            : HTML::anchor('#', '', array('class'=>'btn pull-left disabled'));?>
        <?=($i < ($cnt))
            ? HTML::anchor('#'.$gallery->id.'_'.$slides[$i]->id, '', array('data-toggle' => 'modal', 'data-dismiss'=>'modal', 'class'=>'btn pull-right', 'title'=>'Вперед', 'data-slide'=>'next'))
            : HTML::anchor('#', '', array('class'=>'btn pull-right disabled'));?>
        Слайд <?=$i;?> из <?=$cnt;?>

        <?=HTML::image($slides[$i-1]->path, array('class'=>'img-responsive', 'alt'=>$slides[$i-1]->title));?>

            <?=$slides[$i-1]->caption;?>

<?php endfor; ?>

redpajama_set_name: RedPajamaGithub


text:
using System.Data.Entity.ModelConfiguration;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace NOF2.Demo.Model
{
    public static partial class Mapper
    {
        public static void Map(this EntityTypeBuilder<ProductReview> builder)
        {
            builder.HasKey(t => t.ProductReviewID);

            // Properties
            builder.Property(t => t.mappedReviewerName)
                   .IsRequired()
                   .HasMaxLength(50);

            builder.Property(t => t.mappedEmailAddress)
                   .IsRequired()
                   .HasMaxLength(50);

            builder.Property(t => t.mappedComments)
                   .HasMaxLength(3850);

            // Table & Column Mappings
            builder.ToTable("ProductReview", "Production");
            builder.Property(t => t.ProductReviewID).HasColumnName("ProductReviewID");
            builder.Property(t => t.ProductID).HasColumnName("ProductID");
            builder.Property(t => t.mappedReviewerName).HasColumnName("ReviewerName");
            builder.Property(t => t.mappedReviewDate).HasColumnName("ReviewDate");
            builder.Property(t => t.mappedEmailAddress).HasColumnName("EmailAddress");
            builder.Property(t => t.mappedRating).HasColumnName("Rating");
            builder.Property(t => t.mappedComments).HasColumnName("Comments");
            builder.Property(t => t.mappedModifiedDate).HasColumnName("ModifiedDate").IsConcurrencyToken(false);

            // Relationships
            builder.HasOne(t => t.Product)
                   .WithMany(t => t.mappedProductReviews)
                   .HasForeignKey(d => d.ProductID);
        }
    }
}


text:
const Hashids = require('hashids')

const clearFns = { timeout: clearTimeout, interval: clearInterval, immediate: clearImmediate }
const setFns = { timeout: setTimeout, interval: setInterval, immediate: setImmediate }

class Timer {
  constructor () {
    this.hashids = new Hashids(new Date().toISOString())
    this.counter = 0
    this.map = {}
  }

  runIn (fn, milliseconds, rethrow = true) {
    return this._schedule(fn, 'timeout', milliseconds, rethrow)
  }

  runEvery (fn, milliseconds, rethrow = true) {
    return this._schedule(fn, 'interval', milliseconds, rethrow)
  }

  runNext (fn, rethrow = true) {
    return this._schedule(fn, 'immediate', undefined, rethrow)
  }

  cancel (id) {
    const timer = this.map[id]
    if (!timer) { return false }

    clearFns[timer.type](timer.timer)
    delete this.map[id]

    return true
  }

  check (id) {
    return !!this.map[id]
  }

  list () {
    return Object.keys(this.map)
  }

  _schedule (fn, type, milliseconds, rethrow) {
    const id = this._nextId()
    const timer = setFns[type]((...args) => {
      try {
        fn(...args)
      } catch (err) {
        if (rethrow) { throw err }
      } finally {
        if (type !== 'interval') { delete this.map[id] }
      }
    }, milliseconds)

    this.map[id] = { timer, type }

    return id
  }

  _nextId () {
    return this.hashids.encode(this.counter++)
  }
}

module.exports = Timer


text:
enyo.depends(
	"PalmService.js",
	"PalmServices.js",
	"SystemService.js",
	"DbService.js",
	"TempDbService.js",
	"MockPalmService.js",
	"bridge/"
);


text:
#pragma once

#include "il2cpp-config.h"

#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif

#include <stdint.h>

#include "mscorlib_System_Object2689449295.h"
#include "mscorlib_System_Void1841601450.h"

// System.Type
struct Type_t;
// System.Void
struct Void_t1841601450;

#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif

// System.Reflection.Pointer
struct  Pointer_t937075087  : public Il2CppObject
{
public:
	// System.Void* System.Reflection.Pointer::data
	void* ___data_0;
	// System.Type System.Reflection.Pointer::type
	Type_t * ___type_1;

public:
	inline static int32_t get_offset_of_data_0() { return static_cast<int32_t>(offsetof(Pointer_t937075087, ___data_0)); }
	inline void* get_data_0() const { return ___data_0; }
	inline void** get_address_of_data_0() { return &___data_0; }
	inline void set_data_0(void* value)
	{
		___data_0 = value;
	}

	inline static int32_t get_offset_of_type_1() { return static_cast<int32_t>(offsetof(Pointer_t937075087, ___type_1)); }
	inline Type_t * get_type_1() const { return ___type_1; }
	inline Type_t ** get_address_of_type_1() { return &___type_1; }
	inline void set_type_1(Type_t * value)
	{
		___type_1 = value;
		Il2CppCodeGenWriteBarrier(&___type_1, value);
	}
};

#ifdef __clang__
#pragma clang diagnostic pop
#endif


text:
require("ember-bootstrap/views/item_selection_support");

Bootstrap.PillItem = Ember.View.extend(Bootstrap.ItemSelectionSupport, {
  template: Ember.Handlebars.compile('{{title}}')
});


text:
package keystore

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"testing"

	"github.com/coreos/rkt/pkg/keystore/keystoretest"

	"github.com/coreos/rkt/Godeps/_workspace/src/golang.org/x/crypto/openpgp/errors"
)

func TestStoreTrustedKey(t *testing.T) {
	ks, ksPath, err := NewTestKeystore()
	if err != nil {
		t.Errorf("unexpected error %v", err)
	}
	defer os.RemoveAll(ksPath)

	armoredPublicKey := keystoretest.KeyMap["example.com"].ArmoredPublicKey
	fingerprint := keystoretest.KeyMap["example.com"].Fingerprint

	output, err := ks.StoreTrustedKeyPrefix("example.com/foo", bytes.NewBufferString(armoredPublicKey))
	if err != nil {
		t.Fatalf("unexpected error %v", err)
	}
	if filepath.Base(output) != fingerprint {
		t.Errorf("expected finger print %s, got %v", fingerprint, filepath.Base(output))
	}
	if err := ks.DeleteTrustedKeyPrefix("example.com/foo", fingerprint); err != nil {
		t.Errorf("unexpected error %v", err)
	}
	if _, err := os.Lstat(output); !os.IsNotExist(err) {
		t.Errorf("unexpected error %v", err)
	}

	output, err = ks.MaskTrustedKeySystemPrefix("example.com/foo", fingerprint)
	if err != nil {
		t.Errorf("unexpected error %v", err)
	}
	fi, err := os.Lstat(output)
	if err != nil {
		t.Errorf("unexpected error %v", err)
	}
	if fi.Size() != 0 {
		t.Errorf("expected empty file")
	}

	output, err = ks.StoreTrustedKeyRoot(bytes.NewBufferString(armoredPublicKey))
	if err != nil {
		t.Fatalf("unexpected error %v", err)
	}
	if filepath.Base(output) != fingerprint {
		t.Errorf("expected finger print %s, got %v", fingerprint, filepath.Base(output))
	}
	if err := ks.DeleteTrustedKeyRoot(fingerprint); err != nil {
		t.Errorf("unexpected error %v", err)
	}
	if _, err := os.Lstat(output); !os.IsNotExist(err) {
		t.Errorf("unexpected error %v", err)
	}

	output, err = ks.MaskTrustedKeySystemRoot(fingerprint)
	if err != nil {
		t.Errorf("unexpected error %v", err)
	}
	fi, err = os.Lstat(output)
	if err != nil {
		t.Errorf("unexpected error %v", err)
	}
	if fi.Size() != 0 {
		t.Errorf("expected empty file")
	}
}

func TestCheckSignature(t *testing.T) {
	trustedPrefixKeys := []string{
		"example.com/app",
		"acme.com/services",
		"acme.com/services/web/nginx",
	}
	trustedRootKeys := []string{
		"coreos.com",
	}
	trustedSystemRootKeys := []string{
		"acme.com",
	}

	ks, ksPath, err := NewTestKeystore()
	if err != nil {
		t.Errorf("unexpected error %v", err)
	}
	defer os.RemoveAll(ksPath)

	for _, key := range trustedPrefixKeys {
		if _, err := ks.StoreTrustedKeyPrefix(key, bytes.NewBufferString(keystoretest.KeyMap[key].ArmoredPublicKey)); err != nil {
			t.Fatalf("unexpected error %v", err)
		}
	}
	for _, key := range trustedRootKeys {
		if _, err := ks.StoreTrustedKeyRoot(bytes.NewBufferString(keystoretest.KeyMap[key].ArmoredPublicKey)); err != nil {
			t.Fatalf("unexpected error %v", err)
		}
	}
	for _, key := range trustedSystemRootKeys {
		dst := filepath.Join(ks.SystemRootPath, keystoretest.KeyMap[key].Fingerprint)
		if err := ioutil.WriteFile(dst, []byte(keystoretest.KeyMap[key].ArmoredPublicKey), 0644); err != nil {
			t.Fatalf("unexpected error %v", err)
		}
	}

	if _, err := ks.MaskTrustedKeySystemRoot(keystoretest.KeyMap["acme.com"].Fingerprint); err != nil {
		t.Fatalf("unexpected error %v", err)
	}

	checkSignatureTests := []struct {
		name    string
		key     string
		trusted bool
	}{
		{"coreos.com/etcd", "coreos.com", true},
		{"coreos.com/fleet", "coreos.com", true},
		{"coreos.com/flannel", "coreos.com", true},
		{"example.com/app", "example.com/app", true},
		{"acme.com/services/web/nginx", "acme.com/services/web/nginx", true},
		{"acme.com/services/web/auth", "acme.com/services", true},
		{"acme.com/etcd", "acme.com", false},
		{"acme.com/web/nginx", "acme.com", false},
		{"acme.com/services/web", "acme.com/services/web/nginx", false},
	}
	for _, tt := range checkSignatureTests {
		key := keystoretest.KeyMap[tt.key]
		message, signature, err := keystoretest.NewMessageAndSignature(key.ArmoredPrivateKey)
		if err != nil {
			t.Fatalf("unexpected error %v", err)
			continue
		}
		signer, err := ks.CheckSignature(tt.name, message, signature)
		if tt.trusted {
			if err != nil {
				t.Errorf("unexpected error %v", err)
			}
			fingerprint := fmt.Sprintf("%x", signer.PrimaryKey.Fingerprint)
			if fingerprint != key.Fingerprint {
				t.Errorf("expected fingerprint == %v, got %v", key.Fingerprint, fingerprint)
			}
			continue
		}
		if err == nil {
			t.Errorf("expected ErrUnknownIssuer error")
			continue
		}
		if err.Error() != errors.ErrUnknownIssuer.Error() {
			t.Errorf("unexpected error %v", err)
		}
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using TransApp.Models;

namespace TransApp.Repositories
{
    public class UserRequestRepository
    {
        ApplicationDbContext userRequestDb = new ApplicationDbContext();

        public IEnumerable<UserRequest> GetAllUserRequests()
        {
            return userRequestDb.userRequest;
        }

        public void AddUserRequests(UserRequest newReq)
        {
            userRequestDb.userRequest.Add(newReq);
            Save();
        }

        public void Save()
        {
            userRequestDb.SaveChanges();
        }

        public void UpdateLike(int? reqId)
        {
            foreach(var item in userRequestDb.userRequest)
            {
                if (item.ID == reqId)
                {
                    item.likes += 1;
                    int tala = item.likes;
                    //userRequestDb.Entry(item).CurrentValues.SetValues(item.likes);

                    break;
                }
            }
            Save();
            /*
            var x = userRequestDb.userRequest.Find(reqId);
            userRequestDb.Entry(x).CurrentValues.SetValues(x.Us)
             */
        }

        public bool IsIdValid(int? id)
        {
            foreach(var item in userRequestDb.userRequest)
            {
                if(item.ID == id)
                {
                    return true;
                }
            }

            return false;
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Cladotrichum caesium Preuss

### Remarks
null


text:
module ArLock
  # Creates a critical section around the specified block, in the style of
  # Mutex#synchronize, by locking on the database record in SQL.
  #
  # See ActiveRecord::Locking::Pessimistic#with_lock for details about
  #   the original version of this method.
  #
  # mode::    :exclusive or :shared (or :EX or :SH).  Default is :exclusive.
  #           :exclusive mode will prevent two database callers from entering
  #             the block concurrently.
  #           :shared mode will allow concurrent entry into the block, but will
  #             escalate to an :exclusive lock when ActiveRecord issues an
  #             update to the record.
  # timeout:: The amount of time, in seconds, before the block is timed out.
  #             This prevents the block from blocking others indefinitely.
  #             Default is 60 seconds.
  def lock(mode = :exclusive, timeout = 60.seconds)
    lock = case mode
           when :shared,    :SH then ActiveRecordQueryParts.shared_row_lock
           when :exclusive, :EX then ActiveRecordQueryParts.update_row_lock
           else raise "unknown lock mode <#{mode.inspect}>"
           end

    transaction do
      _log.debug "Acquiring lock on #{self.class.name}::#{id}..."
      lock!(lock)
      _log.debug "Acquired lock"

      begin
        Timeout.timeout(timeout) { yield self }
      ensure
        _log.debug "Releasing lock"
      end
    end
  end
end


text:
<md-content class="md-padding" ng-controller="TodoController as vm">

{{vm.remaining()}} of {{vm.todos.length}} remaining

        <md-button class="md-primary" ng-click="vm.toggleAll()">Toggle All
        </md-button>

    <md-checkbox ng-repeat="todo in vm.todos" ng-model="todo.done">
        {{todo.text}}
    </md-checkbox>

    <form ng-submit="vm.addTodo($event)" novalidate name="tasksForm">

            <md-input-container flex ng-class="{'md-input-invalid':tasksForm.taskText.$error.required && tasksForm.$submitted}">
                Write some todo task here...
                <input ng-model="vm.todoText" name="taskText" required>
            </md-input-container>
            <md-button class="md-fab md-wayrn md-mini" ng-click="vm.addTodo($event)">
                add
            </md-button>

        <md-button class="md-primary" ng-click="vm.archive($event)">
            Remove completed
        </md-button>
    </form>
</md-content>


text:
from lib.exif import EXIF
import lib.io
import json
import os
import string
import threading
import sys
import urllib2, urllib, httplib
import socket
import mimetypes
import random
import string
from Queue import Queue
import threading
import exifread
import time

MAPILLARY_UPLOAD_URL = "https://d22zcsn13kp53w.cloudfront.net/"
MAPILLARY_DIRECT_UPLOAD_URL = "https://s3-eu-west-1.amazonaws.com/mapillary.uploads.images"
PERMISSION_HASH = "eyJleHBpcmF0aW9uIjoiMjAyMC0wMS0wMVQwMDowMDowMFoiLCJjb25kaXRpb25zIjpbeyJidWNrZXQiOiJtYXBpbGxhcnkudXBsb2Fkcy5pbWFnZXMifSxbInN0YXJ0cy13aXRoIiwiJGtleSIsIiJdLHsiYWNsIjoicHJpdmF0ZSJ9LFsic3RhcnRzLXdpdGgiLCIkQ29udGVudC1UeXBlIiwiIl0sWyJjb250ZW50LWxlbmd0aC1yYW5nZSIsMCwyMDQ4NTc2MF1dfQ=="
SIGNATURE_HASH = "f6MHj3JdEq8xQ/CmxOOS7LvMxoI="
BOUNDARY_CHARS = string.digits + string.ascii_letters
NUMBER_THREADS = int(os.getenv('NUMBER_THREADS', '4'))
MAX_ATTEMPTS = int(os.getenv('MAX_ATTEMPTS', '10'))
UPLOAD_PARAMS = {"url": MAPILLARY_UPLOAD_URL, "permission": PERMISSION_HASH, "signature": SIGNATURE_HASH, "move_files":True,  "keep_file_names": True}
CLIENT_ID = "MkJKbDA0bnZuZlcxeTJHTmFqN3g1dzo1YTM0NjRkM2EyZGU5MzBh"
LOGIN_URL = "https://a.mapillary.com/v2/ua/login?client_id={}".format(CLIENT_ID)
PROJECTS_URL = "https://a.mapillary.com/v3/users/{}/projects?client_id={}"
ME_URL = "https://a.mapillary.com/v3/me?client_id={}".format(CLIENT_ID)

class UploadThread(threading.Thread):
    def __init__(self, queue, params=UPLOAD_PARAMS):
        threading.Thread.__init__(self)
        self.q = queue
        self.params = params
        self.total_task = self.q.qsize()

    def run(self):
        while True:
            # fetch file from the queue and upload
            filepath = self.q.get()
            if filepath is None:
                self.q.task_done()
                break
            else:
                lib.io.progress(self.total_task-self.q.qsize(), self.total_task, '... {} images left.'.format(self.q.qsize()))
                upload_file(filepath, **self.params)
                self.q.task_done()

def create_dirs(root_path=''):
    lib.io.mkdir_p(os.path.join(root_path, "success"))
    lib.io.mkdir_p(os.path.join(root_path, "failed"))

def encode_multipart(fields, files, boundary=None):
    """
    Encode dict of form fields and dict of files as multipart/form-data.
    Return tuple of (body_string, headers_dict). Each value in files is a dict
    with required keys 'filename' and 'content', and optional 'mimetype' (if
    not specified, tries to guess mime type or uses 'application/octet-stream').

    From MIT licensed recipe at
    http://code.activestate.com/recipes/578668-encode-multipart-form-data-for-uploading-files-via/
    """
    def escape_quote(s):
        return s.replace('"', '\\"')

    if boundary is None:
        boundary = ''.join(random.choice(BOUNDARY_CHARS) for i in range(30))
    lines = []

    for name, value in fields.items():
        lines.extend((
            '--{0}'.format(boundary),
            'Content-Disposition: form-data; name="{0}"'.format(escape_quote(name)),
            '',
            str(value),
        ))

    for name, value in files.items():
        filename = value['filename']
        if 'mimetype' in value:
            mimetype = value['mimetype']
        else:
            mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
        lines.extend((
            '--{0}'.format(boundary),
            'Content-Disposition: form-data; name="{0}"; filename="{1}"'.format(
                    escape_quote(name), escape_quote(filename)),
            'Content-Type: {0}'.format(mimetype),
            '',
            value['content'],
        ))

    lines.extend((
        '--{0}--'.format(boundary),
        '',
    ))
    body = '\r\n'.join(lines)

    headers = {
        'Content-Type': 'multipart/form-data; boundary={0}'.format(boundary),
        'Content-Length': str(len(body)),
    }
    return (body, headers)

def finalize_upload(params, retry=3, auto_done=False):
    '''
    Finalize and confirm upload
    '''
    # retry if input is unclear
    for i in range(retry):
        if not auto_done:
            proceed = raw_input("Finalize upload? [y/n]: ")
        else:
            proceed = "y"
        if proceed in ["y", "Y", "yes", "Yes"]:
            # upload an empty DONE file
            upload_done_file(params)
            print("Done uploading.")
            break
        elif proceed in ["n", "N", "no", "No"]:
            print("Aborted. No files were submitted. Try again if you had failures.")
            break
        else:
            if i==2:
                print("Aborted. No files were submitted. Try again if you had failures.")
            else:
                print('Please answer y or n. Try again.')

def get_upload_token(mail, pwd):
    '''
    Get upload token
    '''
    params = urllib.urlencode({"email": mail, "password": pwd})
    response = urllib.urlopen(LOGIN_URL, params)
    resp = json.loads(response.read())
    return resp['token']

def get_authentication_info():
    '''
    Get authentication information from env
    '''
    try:
        MAPILLARY_USERNAME = os.environ['MAPILLARY_USERNAME']
        MAPILLARY_EMAIL = os.environ['MAPILLARY_EMAIL']
        MAPILLARY_PASSWORD = os.environ['MAPILLARY_PASSWORD']
    except KeyError:
        return None
    return MAPILLARY_USERNAME, MAPILLARY_EMAIL, MAPILLARY_PASSWORD

def get_full_authentication_info(user=None, email=None):
    # Fetch full authetication info
    try:
        MAPILLARY_EMAIL = email if email is not None else os.environ['MAPILLARY_EMAIL']
        MAPILLARY_SECRET_HASH = os.environ.get('MAPILLARY_SECRET_HASH', None)
        MAPILLARY_UPLOAD_TOKEN = None

        if MAPILLARY_SECRET_HASH is None:
            MAPILLARY_PASSWORD = os.environ['MAPILLARY_PASSWORD']
            MAPILLARY_PERMISSION_HASH = os.environ['MAPILLARY_PERMISSION_HASH']
            MAPILLARY_SIGNATURE_HASH = os.environ['MAPILLARY_SIGNATURE_HASH']
            MAPILLARY_UPLOAD_TOKEN = get_upload_token(MAPILLARY_EMAIL, MAPILLARY_PASSWORD)
            UPLOAD_URL = MAPILLARY_UPLOAD_URL
        else:
            secret_hash = MAPILLARY_SECRET_HASH
            MAPILLARY_PERMISSION_HASH = PERMISSION_HASH
            MAPILLARY_SIGNATURE_HASH = SIGNATURE_HASH
            UPLOAD_URL = MAPILLARY_DIRECT_UPLOAD_URL
        return MAPILLARY_EMAIL, MAPILLARY_UPLOAD_TOKEN, MAPILLARY_SECRET_HASH, UPLOAD_URL
    except KeyError:
        print("You are missing one of the environment variables MAPILLARY_USERNAME, MAPILLARY_EMAIL, MAPILLARY_PASSWORD, MAPILLARY_PERMISSION_HASH or MAPILLARY_SIGNATURE_HASH. These are required.")
        sys.exit()

def get_project_key(project_name, project_key=None):
    '''
    Get project key given project name
    '''
    if project_name is not None or project_key is not None:

        # Get the JWT token
        MAPILLARY_USERNAME, MAPILLARY_EMAIL, MAPILLARY_PASSWORD = get_authentication_info()
        params = urllib.urlencode( {"email": MAPILLARY_EMAIL, "password": MAPILLARY_PASSWORD })
        resp = json.loads(urllib.urlopen(LOGIN_URL, params).read())
        token = resp['token']

        # Get the user key
        req = urllib2.Request(ME_URL)
        req.add_header('Authorization', 'Bearer {}'.format(token))
        resp = json.loads(urllib2.urlopen(req).read())
        userkey = resp['key']

        # Get the user key
        req = urllib2.Request(PROJECTS_URL.format(userkey, CLIENT_ID))
        req.add_header('Authorization', 'Bearer {}'.format(token))
        resp = json.loads(urllib2.urlopen(req).read())
        projects = resp

        # check projects
        found = False
        print "Your projects: "
        for project in projects:
            print(project["name"])
            project_name_matched = project['name'].encode('utf-8').decode('utf-8') == project_name
            project_key_matched = project["key"] == project_key
            if project_name_matched or project_key_matched:
                found = True
                return project['key']

        if not found:
            print "Project {} not found.".format(project_name)

    return ""

def upload_done_file(params):
    print("Upload a DONE file {} to indicate the sequence is all uploaded and ready to submit.".format(params['key']))
    if not os.path.exists("DONE"):
        open("DONE", 'a').close()
    #upload
    upload_file("DONE", **params)
    #remove
    if os.path.exists("DONE"):
        os.remove("DONE")

def upload_file(filepath, url, permission, signature, key=None, move_files=True, keep_file_names=True):
    '''
    Upload file at filepath.

    Move to subfolders 'success'/'failed' on completion if move_files is True.
    '''
    filename = os.path.basename(filepath)

    if keep_file_names:
        s3_filename = filename
    else:
        try:
            s3_filename = EXIF(filepath).exif_name()
        except:
            s3_filename = filename

    # add S3 'path' if given
    if key is None:
        s3_key = s3_filename
    else:
        s3_key = key+s3_filename

    parameters = {"key": s3_key, "AWSAccessKeyId": "AKIAI2X3BJAT2W75HILA", "acl": "private",
                "policy": permission, "signature": signature, "Content-Type":"image/jpeg" }

    with open(filepath, "rb") as f:
        encoded_string = f.read()

    data, headers = encode_multipart(parameters, {'file': {'filename': filename, 'content': encoded_string}})

    root_path = os.path.dirname(filepath)
    success_path = os.path.join(root_path, 'success')
    failed_path = os.path.join(root_path, 'failed')
    lib.io.mkdir_p(success_path)
    lib.io.mkdir_p(failed_path)

    for attempt in range(MAX_ATTEMPTS):

        # Initialize response before each attempt
        response = None

        try:
            request = urllib2.Request(url, data=data, headers=headers)
            response = urllib2.urlopen(request)

            if response.getcode()==204:
                if move_files:
                    os.rename(filepath, os.path.join(success_path, filename))
                # print("Success: {0}".format(filename))
            else:
                if move_files:
                    os.rename(filepath, os.path.join(failed_path, filename))
                print("Failed: {0}".format(filename))
            break # attempts

        except urllib2.HTTPError as e:
            print("HTTP error: {0} on {1}".format(e, filename))
            time.sleep(5)
        except urllib2.URLError as e:
            print("URL error: {0} on {1}".format(e, filename))
            time.sleep(5)
        except httplib.HTTPException as e:
            print("HTTP exception: {0} on {1}".format(e, filename))
            time.sleep(5)
        except OSError as e:
            print("OS error: {0} on {1}".format(e, filename))
            time.sleep(5)
        except socket.timeout as e:
            # Specific timeout handling for Python 2.7
            print("Timeout error: {0} (retrying)".format(filename))
        finally:
            if response is not None:
                response.close()

def upload_file_list(file_list, params=UPLOAD_PARAMS):
    # create upload queue with all files
    q = Queue()
    for filepath in file_list:
        q.put(filepath)

    # create uploader threads
    uploaders = [UploadThread(q, params) for i in range(NUMBER_THREADS)]

    # start uploaders as daemon threads that can be stopped (ctrl-c)
    try:
        print("Uploading with {} threads".format(NUMBER_THREADS))
        for uploader in uploaders:
            uploader.daemon = True
            uploader.start()

        for uploader in uploaders:
            uploaders[i].join(1)

        while q.unfinished_tasks:
            time.sleep(1)
        q.join()
    except (KeyboardInterrupt, SystemExit):
        print("\nBREAK: Stopping upload.")
        sys.exit()

def upload_summary(file_list, total_uploads, split_groups, duplicate_groups, missing_groups):
    total_success = len([f for f in file_list if 'success' in f])
    total_failed = len([f for f in file_list if 'failed' in f])
    lines = []
    if duplicate_groups:
        lines.append('Duplicates (skipping):')
        lines.append('  groups:       {}'.format(len(duplicate_groups)))
        lines.append('  total:        {}'.format(sum([len(g) for g in duplicate_groups])))
    if missing_groups:
        lines.append('Missing Required EXIF (skipping):')
        lines.append('  total:        {}'.format(sum([len(g) for g in missing_groups])))

    lines.append('Sequences:')
    lines.append('  groups:       {}'.format(len(split_groups)))
    lines.append('  total:        {}'.format(sum([len(g) for g in split_groups])))
    lines.append('Uploads:')
    lines.append('  total uploads this run: {}'.format(total_uploads))
    lines.append('  total:        {}'.format(total_success+total_failed))
    lines.append('  success:      {}'.format(total_success))
    lines.append('  failed:       {}'.format(total_failed))
    lines = '\n'.join(lines)
    return lines


text:
import SDK from "./SDK";

module.exports = (PluginSDK) => {
  SDK.setSDK(PluginSDK);

  const PluginHooks = require("./hooks");
  const SecretsReducer = require("./Reducer");
  // Set plugin's hooks
  PluginHooks.initialize();

  return SecretsReducer;
};


text:
<?php

class Util_Layout {

    private $_aField = array();
    private $_sContent = "";
    private $_aChartColumn = array();
    private $_sChartData = "";
    private $_aDataTableColumn = array();
    private $_sDataTableData = "";
    private $_aFormAddColumn = array();
    private $_sFormAddData = "";
    private $_aFormEditColumn = array();
    private $_sFormEditData = "";
    private $_sFormDeleteData = "";
    private $_aParams = array();
    private $_sParamXml = "";
    private $_sSeparator = "\r\n";
    private $_aViewFalseField = array("enable","password","ctime", "mtime");
    private $_sResourceId = "";

    public function __construct($aField, $aParams, $sResourceId) {
        $this->_aField = $aField;
        $this->_aParams = $aParams;
        $this->_sResourceId = $sResourceId;
        $this->loadLayoutTemplate();
    }

    private function loadLayoutTemplate() {
        $oFile = new Util_File();
        $this->_sContent = $oFile->readIniToStr($this->_aParams["layout"]["conf"] . "/layout.xml");
    }

    public function generateLayout() {
        $this->toParamXml();
        foreach ($this->_aField as $row) {
            if(strstr($row->comment,"|")){
                list($sComment,$sCommentType) = explode("|",$row->comment);
                $row->comment = $sComment;
            }
            $this->toChartColumn($row);
            $this->toDataTableColumn($row);
            $this->toFormAddColumn($row);
            $this->toFormEditColumn($row);
        }
        $this->toChartData();
        $this->toDataTableData();
        $this->toFormAddData();
        $this->toFormEditData();
        $this->toFormDeleteData();
        $this->mergeToContent();
        return $this->_sContent;
    }

    private function toChartColumn($row) {

    }

    private function toChartData() {

    }

    private function toDataTableColumn($row) {
        $sColumn = <<<EOB
<column>
	<field>{Field}</field>
	<name>{Name}</name>
	<search>{Search}</search>
        <view>{View}</view>
</column>
EOB;
        $sColumn = str_replace("{Field}", $row->field, $sColumn);
        if (!empty($row->comment)) {
            $sColumn = str_replace("{Name}", $row->comment, $sColumn);
        } else {
            $sColumn = str_replace("{Name}", $row->field, $sColumn);
        }
        if (in_array($row->field, $this->_aViewFalseField)) {
            $sColumn = str_replace("{Search}", "false", $sColumn);
        } else {
            if ($row->type == "varchar(6)") {
                $sColumn = str_replace("{Search}", "true|month|b:e", $sColumn);
            } elseif (strstr($row->type, "varchar(")) {
                $sColumn = str_replace("{Search}", "true", $sColumn);
            } elseif ($row->type == "timestamp") {
                $sColumn = str_replace("{Search}", "true|day|b:e", $sColumn);
            } else {
                $sColumn = str_replace("{Search}", "false", $sColumn);
            }
        }
        if (in_array($row->field, $this->_aViewFalseField)) {
            $sColumn = str_replace("{View}", "false", $sColumn);
        } else {
            $sColumn = str_replace("{View}", "true", $sColumn);
        }
        $this->_aDataTableColumn[] = $sColumn;
    }

    private function toDataTableData() {
        //_aParams["layout"]["edit"]}&id={id}');">删除
        $this->_aDataTableColumn[] =<<<EOB
<column type='text'>
    <name>操作</name>
    <text><![CDATA[
                _aParams["layout"]["edit"]}&id={id}');">编辑
        ]]></text>
</column>
EOB;
        $this->_sDataTableData = <<<EOB
        <params>
            {Params}
        </params>
        <download>
        </download>
        <get_url>Entity:{$this->_sResourceId}:gets</get_url>
	<add_url hidden="false"><![CDATA[{AddUrl}]]></add_url>
EOB;
        $this->_sDataTableData = str_replace("{Params}", $this->_sParamXml, $this->_sDataTableData);
        $this->_sDataTableData = str_replace("{AddUrl}", $this->_aParams["layout"]["add"], $this->_sDataTableData);
    }

    private function toFormAddColumn($row) {
        $this->_aFormAddColumn[] = $this->toCommonModifyColumn($row,"add");
    }

    private function toFormAddData() {
        $this->_sFormAddData = $this->ToOnlyReturnData();
    }

    private function toFormEditColumn($row) {
        $this->_aFormEditColumn[] = $this->toCommonModifyColumn($row,"edit");
    }

    private function toFormEditData() {
        $this->_sFormEditData = <<<EOB
        <params>
            {Params}
        </params>
        <get_url>Entity:{$this->_sResourceId}:gets</get_url>
        <submit_url><![CDATA[{submit_url}]]></submit_url>
        <return_url hidden="false"><![CDATA[{ReturnUrl}]]></return_url>
EOB;
        $this->_sFormEditData = str_replace("{Params}", $this->_sParamXml, $this->_sFormEditData);
        $this->_sFormEditData = str_replace("{submit_url}", $this->_aParams["layout"]["submit"], $this->_sFormEditData);
        $this->_sFormEditData = str_replace("{ReturnUrl}", $this->_aParams["layout"]["return"], $this->_sFormEditData);
    }

    private function toFormDeleteData() {
        $this->_sFormDeleteData = $this->ToOnlyReturnData();
    }

    private function mergeToContent() {
        $this->_sContent = str_replace("<{chart_column}>", implode($this->_sSeparator, $this->_aChartColumn), $this->_sContent);
        $this->_sContent = str_replace("<{chart_data}>", $this->_sChartData, $this->_sContent);
        $this->_sContent = str_replace("<{datables_column}>", implode($this->_sSeparator, $this->_aDataTableColumn), $this->_sContent);
        $this->_sContent = str_replace("<{datables_data}>", $this->_sDataTableData, $this->_sContent);
        $this->_sContent = str_replace("<{formadd_column}>", implode($this->_sSeparator, $this->_aFormAddColumn), $this->_sContent);
        $this->_sContent = str_replace("<{formadd_data}>", $this->_sFormAddData, $this->_sContent);
        $this->_sContent = str_replace("<{formedit_column}>", implode($this->_sSeparator, $this->_aFormEditColumn), $this->_sContent);
        $this->_sContent = str_replace("<{formedit_data}>", $this->_sFormEditData, $this->_sContent);
        $this->_sContent = str_replace("<{formdelete_data}>", $this->_sFormDeleteData, $this->_sContent);
    }

    private function toCommonModifyColumn($row,$sAction) {
        $sColumn = <<<EOB
<column>
	<field>{Field}</field>
	<name>{Name}</name>
	<edit>{Edit}</edit>
        <view>{View}</view>
        <type>{Type}</type>
</column>
EOB;
        $sColumn = str_replace("{Field}", $row->field, $sColumn);
        if (!empty($row->comment)) {
            $sColumn = str_replace("{Name}", $row->comment, $sColumn);
        } else {
            $sColumn = str_replace("{Name}", $row->field, $sColumn);
        }
        if($sAction =='edit' and ($row->key == "PRI" or $row->key == "UNI" or in_array($row->field, $this->_aViewFalseField))){
            $sColumn = str_replace("{Edit}", "false", $sColumn);
        }elseif($sAction =='add' and ($row->field == "id" or in_array($row->field, $this->_aViewFalseField))){
            $sColumn = str_replace("{Edit}", "false", $sColumn);
        }elseif ($row->type == "varchar(6)") {
            $sColumn = str_replace("{Edit}", "true|month|b:e", $sColumn);
        } elseif ($row->type == "timestamp") {
            $sColumn = str_replace("{Edit}", "true|day|b:e", $sColumn);
        } else {
            $sColumn = str_replace("{Edit}", "true", $sColumn);
        }
        if (in_array($row->field, $this->_aViewFalseField)) {
            $sColumn = str_replace("{View}", "false", $sColumn);
        } else {
            $sColumn = str_replace("{View}", "true", $sColumn);
        }
        if(strstr($row->type,"text")){
            $sColumn = str_replace("{Type}", "textarea", $sColumn);
        }else{
            $sColumn = str_replace("{Type}", "input", $sColumn);
        }
        return $sColumn;
    }

    private function ToOnlyReturnData() {
        $sParams = <<<EOB
        <params>
            {Params}
        </params>
        <submit_url><![CDATA[{submit_url}]]></submit_url>
        <return_url hidden="false"><![CDATA[{ReturnUrl}]]></return_url>
EOB;
        $sParams = str_replace("{Params}", $this->_sParamXml, $sParams);
        $sParams = str_replace("{submit_url}", $this->_aParams["layout"]["submit"], $sParams);
        return str_replace("{ReturnUrl}", $this->_aParams["layout"]["return"], $sParams);
    }

    private function toParamXml() {
        $aParams = explode(",", $this->_aParams["layout"]["params"]);
        foreach ($aParams as $sParam) {
            $this->_sParamXml .= "<param>{$sParam}</param>" . $this->_sSeparator;
        }
    }

}


text:
{-
Z%
(c) The University of Glasgow, 2000-2006

\section{Fast functions}
-}

{-# LANGUAGE CPP, MagicHash, UnboxedTuples #-}

module FastFunctions (
    unsafeChr, inlinePerformIO, unsafeDupableInterleaveIO,
    indexWord8OffFastPtr,
    indexWord8OffFastPtrAsFastChar, indexWord8OffFastPtrAsFastInt,
    global, Global
  ) where

#include "HsVersions.h"

import FastTypes
import Data.IORef
import System.IO.Unsafe

import GHC.Exts
import GHC.Word
import GHC.Base (unsafeChr)

import GHC.IO   (IO(..), unsafeDupableInterleaveIO)

-- Just like unsafePerformIO, but we inline it.
{-# INLINE inlinePerformIO #-}
inlinePerformIO :: IO a -> a
inlinePerformIO (IO m) = case m realWorld# of (# _, r #)   -> r

indexWord8OffFastPtr p i = W8# (indexWord8OffAddr# p i)
indexWord8OffFastPtrAsFastChar p i = indexCharOffAddr# p i
indexWord8OffFastPtrAsFastInt p i = word2Int# (indexWord8OffAddr# p i)
-- or ord# (indexCharOffAddr# p i)

--just so we can refer to the type clearly in a macro
type Global a = IORef a
global :: a -> Global a
global a = unsafePerformIO (newIORef a)

indexWord8OffFastPtr :: FastPtr Word8 -> FastInt -> Word8
indexWord8OffFastPtrAsFastChar :: FastPtr Word8 -> FastInt -> FastChar
indexWord8OffFastPtrAsFastInt :: FastPtr Word8 -> FastInt -> FastInt


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Interface org.drip.spline.grid.Span</title>
<meta name="date" content="2017-01-04">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
org.drip.spline.grid.Span

Packages that use Span

Package
Description

org.drip.dynamics.evolution

org.drip.dynamics.lmm

org.drip.spline.grid

org.drip.spline.multidimensional

org.drip.state.curve

org.drip.state.inference

Uses of Span in org.drip.dynamics.evolution

Methods in org.drip.dynamics.evolution that return Span

Modifier and Type
Method and Description

Span
LSQMCurveIncrement.span(LatentStateLabel lsl,
    java.lang.String strQM)

Retrieve the specified Latent State Quantification Metric Span Increment

Methods in org.drip.dynamics.evolution with parameters of type Span

Modifier and Type
Method and Description

boolean
LSQMCurveIncrement.setQMSpan(LatentStateLabel lsl,
         java.lang.String strQM,
         Span spanIncrement)

Set the LSQM Increment Span

Uses of Span in org.drip.dynamics.lmm

Methods in org.drip.dynamics.lmm that return Span

Modifier and Type
Method and Description

Span
BGMCurveUpdate.continuousForwardRateIncrement()

Retrieve the Instantaneous Continuously Compounded Forward Curve Increment Span

Span
BGMCurveUpdate.discountCurveIncrement()

Retrieve the Discount Factor Discount Curve Increment

Span
BGMCurveUpdate.forwardCurveIncrement()

Retrieve the LIBOR Forward Curve Increment Span

Span
BGMCurveUpdate.instantaneousEffectiveForwardRate()

Retrieve the Instantaneous Effective Annual Forward Rate Span

Span
BGMCurveUpdate.instantaneousNominalForwardRate()

Retrieve the Instantaneous Nominal Annual Forward Rate Span

Span
BGMCurveUpdate.spotRateIncrement()

Retrieve the Spot Rate Discount Curve Increment

Methods in org.drip.dynamics.lmm with parameters of type Span

Modifier and Type
Method and Description

static BGMCurveUpdate
BGMCurveUpdate.Create(FundingLabel lslFunding,
      ForwardLabel lslForward,
      int iInitialDate,
      int iFinalDate,
      ForwardCurve fc,
      Span spanLIBORIncrement,
      MergedDiscountForwardCurve dc,
      Span spanDiscountFactorIncrement,
      Span spanContinuousForwardRateIncrement,
      Span spanSpotRateIncrement,
      Span spanInstantaneousEffectiveForward,
      Span spanInstantaneousNominalForward,
      LognormalLIBORVolatility llv)

Construct an Instance of BGMCurveUpdate

Uses of Span in org.drip.spline.grid

Classes in org.drip.spline.grid that implement Span

Modifier and Type
Class and Description

class
AggregatedSpan

AggregatedSpan implements the Span interface.

class
OverlappingStretchSpan

OverlappingStretchSpan implements the Span interface, and the collection functionality of overlapping
  Stretches.

Methods in org.drip.spline.grid that return Span

Modifier and Type
Method and Description

Span
OverlappingStretchSpan.toNonOverlapping()

Convert the Overlapping Stretch Span to a non-overlapping Stretch Span.

Constructor parameters in org.drip.spline.grid with type arguments of type Span

Constructor and Description

AggregatedSpan(java.util.List<Span> lsSpan,
              java.util.List<java.lang.Double> lsWeight)

AggregatedSpan Constructor

Uses of Span in org.drip.spline.multidimensional

Methods in org.drip.spline.multidimensional that return Span

Modifier and Type
Method and Description

Span
WireSurfaceStretch.wireSpanXAnchor(double dblXAnchor)

Retrieve the Surface Span Stretch that corresponds to the given X Anchor

Span
WireSurfaceStretch.wireSpanYAnchor(double dblYAnchor)

Retrieve the Surface Span Stretch that corresponds to the given Y Anchor

Constructor parameters in org.drip.spline.multidimensional with type arguments of type Span

Constructor and Description

WireSurfaceStretch(java.lang.String strName,
                  SegmentCustomBuilderControl scbc,
                  java.util.TreeMap<java.lang.Double,Span> mapWireSpan)

WireSurfaceStretch Constructor

Uses of Span in org.drip.state.curve

Constructors in org.drip.state.curve with parameters of type Span

Constructor and Description

BasisSplineBasisCurve(ForwardLabel friReference,
                     ForwardLabel friDerived,
                     boolean bBasisOnReference,
                     Span span)

BasisSplineBasisCurve constructor

BasisSplineDeterministicVolatility(int iEpochDate,
                                  CustomLabel label,
                                  java.lang.String strCurrency,
                                  Span spanImpliedVolatility)

BasisSplineDeterministicVolatility Constructor

BasisSplineFXForward(CurrencyPair cp,
                    Span span)

BasisSplineFXForward constructor

BasisSplineGovvieYield(java.lang.String strTreasuryCode,
                      java.lang.String strCurrency,
                      Span span)

BasisSplineGovvieYield Constructor

BasisSplineRepoCurve(Component comp,
                    Span span)

BasisSplineRepoCurve constructor

BasisSplineTermStructure(int iEpochDate,
                        CustomLabel label,
                        java.lang.String strCurrency,
                        Span span)

BasisSplineTermStructure Constructor

DiscountFactorDiscountCurve(java.lang.String strCurrency,
                           Span span)

DiscountFactorDiscountCurve constructor

ZeroRateDiscountCurve(java.lang.String strCurrency,
                     Span span)

ZeroRateDiscountCurve constructor

Uses of Span in org.drip.state.inference

Constructors in org.drip.state.inference with parameters of type Span

Constructor and Description

<a href="../../../../../org/drip/state/inference/LatentStateSequenceBuilder.html#LatentStateSequenceBuilder-double-org.drip.state.inference.LatentStateStretchSpec-org.drip.param.valuation.ValuationParams-org.drip.param.pricer.CreditPricerParams-org.drip.param.market.CurveSurfaceQuoteContainer-org.drip.param.valuation.ValuationCustomizationParams-org.drip.spline.grid.Span-org.drip.spline.params.StretchBestFitResponse-org.drip.analytics.support.CaseInsensitiveHashMap-org.drip.spline.params.StretchBestFitResponse-org.drip.spline.stretch.BoundarySettings-">LatentStateSequenceBuilder(double dblEpochResponse,
                          LatentStateStretchSpec stretchSpec,
                          ValuationParams valParams,
                          CreditPricerParams pricerParams,
                          CurveSurfaceQuoteContainer csqs,
                          ValuationCustomizationParams vcp,
                          Span span,
                          StretchBestFitResponse sbfr,
                          CaseInsensitiveHashMap<PreceedingManifestSensitivityControl> mapPMSC,
                          StretchBestFitResponse sbfrQuoteSensitivity,
                          BoundarySettings bs)

LatentStateSequenceBuilder constructor

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
from __future__ import absolute_import

import re
import sentry_sdk

from rest_framework.response import Response
from rest_framework.exceptions import ParseError

from sentry import search
from sentry.api.base import EnvironmentMixin
from sentry.api.bases import OrganizationEventsEndpointBase, NoProjects
from sentry.api.helpers.group_index import build_query_params_from_request
from sentry.api.event_search import parse_search_query, get_function_alias
from sentry.api.serializers import serialize
from sentry.api.serializers.models.group import GroupSerializer
from sentry.snuba import discover

class OrganizationEventsMetaEndpoint(OrganizationEventsEndpointBase):
    def get(self, request, organization):
        try:
            params = self.get_snuba_params(request, organization)
        except NoProjects:
            return Response({"count": 0})

        with self.handle_query_errors():
            result = discover.query(
                selected_columns=["count()"],
                params=params,
                query=request.query_params.get("query"),
                referrer="api.organization-events-meta",
            )

        return Response({"count": result["data"][0]["count"]})

class OrganizationEventBaseline(OrganizationEventsEndpointBase):
    def get(self, request, organization):
        """ Find the event id with the closest value to an aggregate for a given query """
        if not self.has_feature(organization, request):
            return Response(status=404)

        try:
            params = self.get_snuba_params(request, organization)
        except NoProjects:
            return Response(status=404)

        # Assumption is that users will want the 50th percentile
        baseline_function = request.GET.get("baselineFunction", "p50()")
        # If the baseline was calculated already save ourselves a query
        baseline_value = request.GET.get("baselineValue")
        baseline_alias = get_function_alias(baseline_function)

        with self.handle_query_errors():
            if baseline_value is None:
                result = discover.query(
                    selected_columns=[baseline_function],
                    params=params,
                    query=request.GET.get("query"),
                    limit=1,
                    referrer="api.transaction-baseline.get_value",
                )
                baseline_value = result["data"][0].get(baseline_alias) if "data" in result else None
                if baseline_value is None:
                    return Response(status=404)

            delta_column = "absolute_delta(transaction.duration,{})".format(baseline_value)

            result = discover.query(
                selected_columns=[
                    "project",
                    "timestamp",
                    "id",
                    "transaction.duration",
                    delta_column,
                ],
                # Find the most recent transaction that's closest to the baseline value
                # id is the last item of the orderby for consistent results
                orderby=[get_function_alias(delta_column), "-timestamp", "id"],
                params=params,
                query=request.GET.get("query"),
                limit=1,
                referrer="api.transaction-baseline.get_id",
            )
            if len(result["data"]) == 0:
                return Response(status=404)

        baseline_data = result["data"][0]
        baseline_data[baseline_alias] = baseline_value
        return Response(baseline_data)

UNESCAPED_QUOTE_RE = re.compile('(?<!\\\\)"')

class OrganizationEventsRelatedIssuesEndpoint(OrganizationEventsEndpointBase, EnvironmentMixin):
    def get(self, request, organization):
        try:
            # events-meta is still used by events v1 which doesn't require global views
            params = self.get_snuba_params(request, organization, check_global_views=False)
        except NoProjects:
            return Response([])

        with sentry_sdk.start_span(op="discover.endpoint", description="find_lookup_keys") as span:
            possible_keys = ["transaction"]
            lookup_keys = {key: request.query_params.get(key) for key in possible_keys}

            if not any(lookup_keys.values()):
                return Response(
                    {
                        "detail": "Must provide one of {} in order to find related events".format(
                            possible_keys
                        )
                    },
                    status=400,
                )

        with self.handle_query_errors():
            with sentry_sdk.start_span(op="discover.endpoint", description="filter_creation"):
                projects = self.get_projects(request, organization)
                query_kwargs = build_query_params_from_request(
                    request, organization, projects, params.get("environment")
                )
                query_kwargs["limit"] = 5
                try:
                    # Need to escape quotes in case some "joker" has a transaction with quotes
                    transaction_name = UNESCAPED_QUOTE_RE.sub('\\"', lookup_keys["transaction"])
                    parsed_terms = parse_search_query('transaction:"{}"'.format(transaction_name))
                except ParseError:
                    return Response({"detail": "Invalid transaction search"}, status=400)

                if query_kwargs.get("search_filters"):
                    query_kwargs["search_filters"].extend(parsed_terms)
                else:
                    query_kwargs["search_filters"] = parsed_terms

            with sentry_sdk.start_span(op="discover.endpoint", description="issue_search"):
                results = search.query(**query_kwargs)

        with sentry_sdk.start_span(op="discover.endpoint", description="serialize_results") as span:
            results = list(results)
            span.set_data("result_length", len(results))
            context = serialize(
                results,
                request.user,
                GroupSerializer(
                    environment_func=self._get_environment_func(request, organization.id)
                ),
            )

        return Response(context)


text:
use common_types::entity_id::*;

pub type GuidPrefix = [u8; 12];

#[derive(Default, Debug, PartialEq, Copy, Clone)]
pub struct Guid {
    pub guid_prefix: GuidPrefix,
    pub entity_id: EntityId
}

impl Guid {
    pub fn new() -> Self {
        Guid {
            guid_prefix: [0; 12],
            entity_id: EntityId {
                entity_key: [0; 3],
                entity_kind: EntityKind::UserUnknown
            }
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="Perl5LocalSettings">
    <option name="perlInterpreter" value="Perl v5.18.2" />
  </component>
</project>


text:
$show_last_log = function(message) {
  $('#the_last_log').html(message)
}


text:
package org.apache.cassandra.io;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import org.junit.Assert;
import org.junit.Test;

import org.apache.cassandra.Util;
import org.apache.cassandra.cql3.CQLTester;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.db.compaction.CompactionInterruptedException;
import org.apache.cassandra.db.compaction.OperationType;
import org.apache.cassandra.db.lifecycle.LifecycleTransaction;
import org.apache.cassandra.db.lifecycle.SSTableSet;
import org.apache.cassandra.io.sstable.IndexSummaryManager;
import org.apache.cassandra.io.sstable.IndexSummaryRedistribution;
import org.apache.cassandra.io.sstable.format.SSTableReader;
import org.apache.cassandra.schema.TableId;
import org.apache.cassandra.utils.FBUtilities;

public class DiskSpaceMetricsTest extends CQLTester
{
    /**
     * This test runs the system with normal operations and makes sure the disk metrics match reality
     */
    @Test
    public void baseline() throws Throwable
    {
        createTable("CREATE TABLE %s (pk bigint, PRIMARY KEY (pk)) WITH min_index_interval=1");
        ColumnFamilyStore cfs = getCurrentColumnFamilyStore();

        // disable compaction so nothing changes between calculations
        cfs.disableAutoCompaction();

        // create 100 sstables
        for (int i = 0; i < 100; i++)
            insert(cfs, i);
        assertDiskSpaceEqual(cfs);
    }

    /**
     * If index summary downsampling is interrupted in the middle, the metrics still reflect the real data
     */
    @Test
    public void summaryRedistribution() throws Throwable
    {
        createTable("CREATE TABLE %s (pk bigint, PRIMARY KEY (pk)) WITH min_index_interval=1");
        ColumnFamilyStore cfs = getCurrentColumnFamilyStore();

        // disable compaction so nothing changes between calculations
        cfs.disableAutoCompaction();

        // create 100 sstables, make sure they have more than 1 value, else sampling can't happen
        for (int i = 0; i < 100; i++)
            insertN(cfs, 10, i);
        assertDiskSpaceEqual(cfs);

        // summary downsample
        for (int i = 0; i < 100; i++)
        {
            indexDownsampleCancelLastSSTable(cfs);
            assertDiskSpaceEqual(cfs);
        }
    }

    private void insert(ColumnFamilyStore cfs, long value) throws Throwable
    {
        insertN(cfs, 1, value);
    }

    private void insertN(ColumnFamilyStore cfs, int n, long base) throws Throwable
    {
        for (int i = 0; i < n; i++)
            execute("INSERT INTO %s (pk) VALUES (?)", base + i);

        // flush to write the sstable
        Util.flush(cfs);
    }

    private void assertDiskSpaceEqual(ColumnFamilyStore cfs)
    {
        long liveDiskSpaceUsed = cfs.metric.liveDiskSpaceUsed.getCount();
        long actual = 0;
        for (SSTableReader sstable : cfs.getTracker().getView().liveSSTables())
            actual += sstable.bytesOnDisk();

        Assert.assertEquals("bytes on disk does not match current metric liveDiskSpaceUsed", actual, liveDiskSpaceUsed);

        // totalDiskSpaceUsed is based off SStable delete, which is async: LogTransaction's tidy enqueues in ScheduledExecutors.nonPeriodicTasks
        // wait for there to be no more pending sstable releases
        LifecycleTransaction.waitForDeletions();
        long totalDiskSpaceUsed = cfs.metric.totalDiskSpaceUsed.getCount();
        Assert.assertEquals("bytes on disk does not match current metric totalDiskSpaceUsed", actual, totalDiskSpaceUsed);
    }

    private static void indexDownsampleCancelLastSSTable(ColumnFamilyStore cfs)
    {
        List<SSTableReader> sstables = Lists.newArrayList(cfs.getSSTables(SSTableSet.CANONICAL));
        LifecycleTransaction txn = cfs.getTracker().tryModify(sstables, OperationType.UNKNOWN);
        Map<TableId, LifecycleTransaction> txns = ImmutableMap.of(cfs.metadata.id, txn);
        // fail on the last file (* 3 because we call isStopRequested 3 times for each sstable, and we should fail on the last)
        AtomicInteger countdown = new AtomicInteger(3 * sstables.size() - 1);
        IndexSummaryRedistribution redistribution = new IndexSummaryRedistribution(txns, 0, 0) {
            public boolean isStopRequested()
            {
                return countdown.decrementAndGet() == 0;
            }
        };
        try
        {
            IndexSummaryManager.redistributeSummaries(redistribution);
            Assert.fail("Should throw CompactionInterruptedException");
        }
        catch (CompactionInterruptedException e)
        {
            // trying to get this to happen
        }
        catch (IOException e)
        {
            throw new RuntimeException(e);
        }
        finally
        {
            try
            {
                FBUtilities.closeAll(txns.values());
            }
            catch (Exception e)
            {
                throw new RuntimeException(e);
            }
        }
    }
}


text:
/* jshint expr: true */
'use strict';

var expect = require('chai').expect;

describe('barbarian-ombudsman', function() {
  it('shows the report', function() {
    expect(console._log[0]).to.eq('Found 5 keys in total.\n');
  });
});


text:
var editor;

$(function () {
    $('#btnSave').click(function () { savePost(); });
    editor = CKEDITOR.replace('editor1');
});

function savePost() {
    var postData = {
        "postEntity": {
            "Title": $("#title").val(),
            "Content": editor.getData()
        }
    };

    $.ajax({
        url: '/Backend/Post/Create',
        data: postData,
        type: "Post"
    })
    .done(function (data) {

        if (data.result == "Success") {
            layer.alert("Save sucess0", {
                title: 'Tip'
                , btn:['yes']
                , icon: 6
                , yes: function (index) {
                    layer.close(index);
                    location.href = '/Backend/Post/Index';
                }
            });

        } else {
            layer.tips(data.result, "#btnSave");
        };
    })
    .fail(function (xhr, status, errorThrown) {
        var message;
        var statusErrorMap = {
            '400': "Server understood the request, but request content was invalid.",
            '401': "Unauthorized access.",
            '403': "Forbidden resource can't be accessed.",
            '404': "Not found.",
            '500': "Internal server error.",
            '503': "Service unavailable."
        };
        layer.tips("Sorry, there was a problem!", "error");
        console.log("Error: " + errorThrown);
        console.log("Status: " + status);
        message = statusErrorMap[status];
        if (message) {
            layer.tips(message, "");
        }
        console.dir(xhr);
    })
    .always(function (xhr, status) {
        layer.tips("The request is complete!", "");
    });
}


text:
var common = require('./common.js');

module.exports = {
	deleteAuth : function(owner, req) {
		if(common.isAdmin(req.session.user && req.session.user.email)) return true;
		if(owner && owner.email && req.session.user && req.session.user.email && (owner.email != req.session.user.email)) {
			return false;
		}
		return true;
	},
	imageName : function(name) {
		// body...
	},
	serverName : function(name) {
		// body...
	}

}


text:
#include "xmlsyntaxhighlighter.h"

XmlSyntaxHighlighter::XmlSyntaxHighlighter(QTextDocument *parent)
    : QSyntaxHighlighter(parent)
{
    HighlightingRule rule;

    // tag format
    tagFormat.setForeground(Qt::darkBlue);
    tagFormat.setFontWeight(QFont::Bold);
    rule.pattern = QRegExp("(<[a-zA-Z:]+\\b|<\\?[a-zA-Z:]+\\b|\\?>|>|/>|</[a-zA-Z:]+>)");
    rule.format = tagFormat;
    highlightingRules.append(rule);

    // attribute format
    attributeFormat.setForeground(Qt::darkGreen);
    rule.pattern = QRegExp("[a-zA-Z:]+=");
    rule.format = attributeFormat;
    highlightingRules.append(rule);

    // attribute content format
    attributeContentFormat.setForeground(Qt::red);
    rule.pattern = QRegExp("(\"[^\"]*\"|'[^']*')");
    rule.format = attributeContentFormat;
    highlightingRules.append(rule);

    commentFormat.setForeground(Qt::lightGray);
    commentFormat.setFontItalic(true);

    commentStartExpression = QRegExp("<!--");
    commentEndExpression = QRegExp("-->");
}

void XmlSyntaxHighlighter::highlightBlock(const QString &text)
{
     foreach (const HighlightingRule &rule, highlightingRules) {
         QRegExp expression(rule.pattern);
         int index = text.indexOf(expression);
         while (index >= 0) {
             int length = expression.matchedLength();
             setFormat(index, length, rule.format);
             index = text.indexOf(expression, index + length);
         }
     }
     setCurrentBlockState(0);

     int startIndex = 0;
     if (previousBlockState() != 1)
         startIndex = text.indexOf(commentStartExpression);

     while (startIndex >= 0) {
         int endIndex = text.indexOf(commentEndExpression, startIndex);
         int commentLength;
         if (endIndex == -1) {
             setCurrentBlockState(1);
             commentLength = text.length() - startIndex;
         } else {
             commentLength = endIndex - startIndex
                             + commentEndExpression.matchedLength();
         }
         setFormat(startIndex, commentLength, commentFormat);
         startIndex = text.indexOf(commentStartExpression,
                                                 startIndex + commentLength);
     }
}


text:
package z21Drive.actions;

import java.util.Arrays;

public class Z21ActionLanXGetFirmwareVersion extends Z21Action{
    private static final Byte[] rep = new Byte[]{0x07, 0x00, 0x40, 0x00, (byte)0xF1, 0x0A, (byte)0xFB};

    public Z21ActionLanXGetFirmwareVersion() {
        byteRepresentation = Arrays.asList(rep);
    }

    /**
     * Not necessary here.
     * @param objs Whatever
     */
    @Override
    public void addDataToByteRepresentation(Object[] objs) {}
}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.typeFromAST = undefined;

var _invariant = require('../jsutils/invariant');

var _invariant2 = _interopRequireDefault(_invariant);

var _kinds = require('../language/kinds');

var Kind = _interopRequireWildcard(_kinds);

var _definition = require('../type/definition');

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

/**
 * Given a Schema and an AST node describing a type, return a GraphQLType
 * definition which applies to that type. For example, if provided the parsed
 * AST node for `[User]`, a GraphQLList instance will be returned, containing
 * the type called "User" found in the schema. If a type called "User" is not
 * found in the schema, then undefined will be returned.
 */
/* eslint-disable no-redeclare */
function typeFromASTImpl(schema, typeNode) {
  /* eslint-enable no-redeclare */
  var innerType = void 0;
  if (typeNode.kind === Kind.LIST_TYPE) {
    innerType = typeFromAST(schema, typeNode.type);
    return innerType && new _definition.GraphQLList(innerType);
  }
  if (typeNode.kind === Kind.NON_NULL_TYPE) {
    innerType = typeFromAST(schema, typeNode.type);
    return innerType && new _definition.GraphQLNonNull(innerType);
  }
  (0, _invariant2.default)(typeNode.kind === Kind.NAMED_TYPE, 'Must be a named type.');
  return schema.getType(typeNode.name.value);
}
// This will export typeFromAST with the correct type, but currently exposes
// ~26 errors: https://gist.github.com/4a29403a99a8186fcb15064d69c5f3ae
// export var typeFromAST: typeof typeFromASTType = typeFromASTImpl;

/**
 *  Copyright (c) 2015, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 */

var typeFromAST = exports.typeFromAST = typeFromASTImpl;


text:
#pragma once
#ifndef __BARPLOT_H__
#define __BARPLOT_H__

#include "plot/properties/barProperties.h"
#include "plot/pvec.h"

class Palette;

class BarPlot
    : public BarPlotProperties< BarPlot >
{
public:

    enum Orientation
    {
        Vertical,
        Horizontal
    };

    BarPlot(const PVec &x, const PVec &y);

    BarPlot(const std::vector< std::pair< PVec, PVec >> &data);

    BarPlot(const std::vector< std::pair< PVec, PVec >> &data, const std::vector< std::string > &hue);

    template< typename tT, typename tFunc >
    BarPlot(const std::vector< std::pair< PVec, PVec >> &data, const std::vector< tT > &hueData, const tFunc &hueFunc)
    {
        std::vector< std::string > hue;

        for (const auto &hueValue : hueData)
        {
            hue.emplace_back(hueFunc(hueValue));
        }

        InitData(data);
        InitHue(data, hue);
        PlotDataHue();
    }

    virtual std::string ToString() override;

    BarPlot &SetOrder(const PVec &order);

    BarPlot &SetHueOrder(const std::vector< std::string > &order);

    BarPlot &SetConfidenceInterval(double ci);

    BarPlot &SetNBoot(size_t bootstrap);

    BarPlot &SetOrientation(Orientation orientation);

    BarPlot &SetDodge(bool dodge);

    BarPlot &SetColour(const std::string &colour);

    BarPlot &UseColourCycler(const std::string &colourCycler);

    BarPlot &SetColourMap(const Palette &pallet);

    BarPlot &SetSaturation(double sat);

    BarPlot &SetErrorColour(const std::string &colour);

    BarPlot &SetErrorWidth(double width);

    BarPlot &SetCapSize(double size);

private:

    void InitData(const std::vector< std::pair< PVec, PVec >> &data);

    void InitHue(const std::vector< std::pair< PVec, PVec >> &data, const std::vector< std::string > &hue);

    void PlotData();

    void PlotDataHue();
};

#ifndef PLOTLIB_NO_HEADER_ONLY
#   include "../../src/barPlot.cpp"
#endif

#endif


text:
/*
 * The Plaid API
 *
 * The Plaid REST API. Please see https://plaid.com/docs/api for more details.
 *
 * API version: 2020-09-14_1.205.3
 */

// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT.

package plaid

import (
	"encoding/json"
	"fmt"
)

// WebhookEnvironmentValues The Plaid environment the webhook was sent from
type WebhookEnvironmentValues string

var _ = fmt.Printf

// List of WebhookEnvironmentValues
const (
	WEBHOOKENVIRONMENTVALUES_DEVELOPMENT WebhookEnvironmentValues = "development"
	WEBHOOKENVIRONMENTVALUES_SANDBOX WebhookEnvironmentValues = "sandbox"
	WEBHOOKENVIRONMENTVALUES_PRODUCTION WebhookEnvironmentValues = "production"
)

var allowedWebhookEnvironmentValuesEnumValues = []WebhookEnvironmentValues{
	"development",
	"sandbox",
	"production",
}

func (v *WebhookEnvironmentValues) UnmarshalJSON(src []byte) error {
	var value string
	err := json.Unmarshal(src, &value)
	if err != nil {
		return err
	}

	enumTypeValue := WebhookEnvironmentValues(value)

	*v = enumTypeValue
	return nil
}

// NewWebhookEnvironmentValuesFromValue returns a pointer to a valid WebhookEnvironmentValues
// for the value passed as argument, or an error if the value passed is not allowed by the enum
func NewWebhookEnvironmentValuesFromValue(v string) (*WebhookEnvironmentValues, error) {
	ev := WebhookEnvironmentValues(v)

	return &ev, nil
}

// IsValid return true if the value is valid for the enum, false otherwise
func (v WebhookEnvironmentValues) IsValid() bool {
	for _, existing := range allowedWebhookEnvironmentValuesEnumValues {
		if existing == v {
			return true
		}
	}
	return false
}

// Ptr returns reference to WebhookEnvironmentValues value
func (v WebhookEnvironmentValues) Ptr() *WebhookEnvironmentValues {
	return &v
}

type NullableWebhookEnvironmentValues struct {
	value *WebhookEnvironmentValues
	isSet bool
}

func (v NullableWebhookEnvironmentValues) Get() *WebhookEnvironmentValues {
	return v.value
}

func (v *NullableWebhookEnvironmentValues) Set(val *WebhookEnvironmentValues) {
	v.value = val
	v.isSet = true
}

func (v NullableWebhookEnvironmentValues) IsSet() bool {
	return v.isSet
}

func (v *NullableWebhookEnvironmentValues) Unset() {
	v.value = nil
	v.isSet = false
}

func NewNullableWebhookEnvironmentValues(val *WebhookEnvironmentValues) *NullableWebhookEnvironmentValues {
	return &NullableWebhookEnvironmentValues{value: val, isSet: true}
}

func (v NullableWebhookEnvironmentValues) MarshalJSON() ([]byte, error) {
	return json.Marshal(v.value)
}

func (v *NullableWebhookEnvironmentValues) UnmarshalJSON(src []byte) error {
	v.isSet = true
	return json.Unmarshal(src, &v.value)
}


text:
<?php

namespace Propel\Tests\Generator\Builder\Om;

use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Tests\Bookstore\Map\AuthorTableMap;
use Propel\Tests\Bookstore\Map\BookTableMap;
use Propel\Tests\Bookstore\Map\EssayTableMap;
use Propel\Tests\Bookstore\Map\MediaTableMap;
use Propel\Tests\Bookstore\Map\PublisherTableMap;
use Propel\Tests\Helpers\Bookstore\BookstoreTestBase;

/**
 * Tests the generated TableMap classes.
 *
 * This test uses generated Bookstore classes to test the behavior of various
 * TableMap operations.
 *
 * The database is reloaded before every test and flushed after every test. This
 * means that you can always rely on the contents of the databases being the same
 * for each test method in this class. See the BookstoreDataPopulator::populate()
 * method for the exact contents of the database.
 *
 * @see BookstoreDataPopulator
 * @author Hans Lellelid <hans@xmpl.org>
 *
 * @group database
 */
class GeneratedTableMapTest extends BookstoreTestBase
{
    /**
     * @return void
     */
    public function testAlias()
    {
        $this->assertEquals('foo.id', BookTableMap::alias('foo', BookTableMap::COL_ID), 'alias() returns a column name using the table alias');
        $this->assertEquals('book.id', BookTableMap::alias('book', BookTableMap::COL_ID), 'alias() returns a column name using the table alias');
        $this->assertEquals('foo.cover_image', MediaTableMap::alias('foo', MediaTableMap::COL_COVER_IMAGE), 'alias() also works for lazy-loaded columns');
        $this->assertEquals('foo.subtitle', EssayTableMap::alias('foo', EssayTableMap::COL_SUBTITLE), 'alias() also works for columns with custom phpName');
    }

    /**
     * @return void
     */
    public function testAddSelectColumns()
    {
        $c = new Criteria();
        BookTableMap::addSelectColumns($c);
        $expected = [
            BookTableMap::COL_ID,
            BookTableMap::COL_TITLE,
            BookTableMap::COL_ISBN,
            BookTableMap::COL_PRICE,
            BookTableMap::COL_PUBLISHER_ID,
            BookTableMap::COL_AUTHOR_ID,
        ];
        $this->assertEquals($expected, $c->getSelectColumns(), 'addSelectColumns() adds the columns of the model to the criteria');
    }

    /**
     * @return void
     */
    public function testAddSelectColumnsLazyLoad()
    {
        $c = new Criteria();
        MediaTableMap::addSelectColumns($c);
        $expected = [
            MediaTableMap::COL_ID,
            MediaTableMap::COL_BOOK_ID,
        ];
        $this->assertEquals($expected, $c->getSelectColumns(), 'addSelectColumns() does not add lazy loaded columns');
    }

    /**
     * @return void
     */
    public function testAddSelectColumnsAlias()
    {
        $c = new Criteria();
        BookTableMap::addSelectColumns($c, 'foo');
        $expected = [
            'foo.id',
            'foo.title',
            'foo.isbn',
            'foo.price',
            'foo.publisher_id',
            'foo.author_id',
        ];
        $this->assertEquals($expected, $c->getSelectColumns(), 'addSelectColumns() uses the second parameter as a table alias');
    }

    /**
     * @return void
     */
    public function testAddSelectColumnsAliasLazyLoad()
    {
        $c = new Criteria();
        MediaTableMap::addSelectColumns($c, 'bar');
        $expected = [
            'bar.id',
            'bar.book_id',
        ];
        $this->assertEquals($expected, $c->getSelectColumns(), 'addSelectColumns() does not add lazy loaded columns but uses the second parameter as an alias');
    }

    /**
     * @return void
     */
    public function testDefaultStringFormatConstant()
    {
        $this->assertTrue(defined('Propel\Tests\Bookstore\Map\BookTableMap::DEFAULT_STRING_FORMAT'), 'every TableMap class has the DEFAULT_STRING_FORMAT constant');
        $this->assertEquals('YAML', AuthorTableMap::DEFAULT_STRING_FORMAT, 'default string format is YAML by default');
        $this->assertEquals('XML', PublisherTableMap::DEFAULT_STRING_FORMAT, 'default string format can be customized using the defaultStringFormat attribute in the schema');
    }
}


text:
using System;

namespace MathNet.Numerics.LinearAlgebra.Solvers
{
    /// <summary>
    /// Stop criterion that delegates the status determination to a delegate.
    /// </summary>
    public class DelegateStopCriterion<T> : IIterationStopCriterion<T>
        where T : struct, IEquatable<T>, IFormattable
    {
        readonly Func<int, Vector<T>, Vector<T>, Vector<T>, IterationStatus> _determine;
        IterationStatus _status = IterationStatus.Continue;

        /// <summary>
        /// Create a new instance of this criterion with a custom implementation.
        /// </summary>
        /// <param name="determine">Custom implementation with the same signature and semantics as the DetermineStatus method.</param>
        public DelegateStopCriterion(Func<int, Vector<T>, Vector<T>, Vector<T>, IterationStatus> determine)
        {
            _determine = determine;
        }

        /// <summary>
        /// Determines the status of the iterative calculation by delegating it to the provided delegate.
        /// Result is set into <c>Status</c> field.
        /// </summary>
        /// <param name="iterationNumber">The number of iterations that have passed so far.</param>
        /// <param name="solutionVector">The vector containing the current solution values.</param>
        /// <param name="sourceVector">The right hand side vector.</param>
        /// <param name="residualVector">The vector containing the current residual vectors.</param>
        /// <remarks>
        /// The individual stop criteria may internally track the progress of the calculation based
        /// on the invocation of this method. Therefore this method should only be called if the
        /// calculation has moved forwards at least one step.
        /// </remarks>
        public IterationStatus DetermineStatus(int iterationNumber, Vector<T> solutionVector, Vector<T> sourceVector, Vector<T> residualVector)
        {
            return _status = _determine(iterationNumber, solutionVector, sourceVector, residualVector);
        }

        /// <summary>
        /// Gets the current calculation status.
        /// </summary>
        public IterationStatus Status
        {
            get { return _status; }
        }

        /// <summary>
        /// Resets the IIterationStopCriterion to the pre-calculation state.
        /// </summary>
        public void Reset()
        {
            _status = IterationStatus.Continue;
        }

        /// <summary>
        /// Clones this criterion and its settings.
        /// </summary>
        public IIterationStopCriterion<T> Clone()
        {
            return new DelegateStopCriterion<T>(_determine);
        }
    }
}