text:
.class Landroid/app/IUiModeManager$Stub$Proxy;
.super Ljava/lang/Object;
.source "IUiModeManager.java"

# interfaces
.implements Landroid/app/IUiModeManager;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/app/IUiModeManager$Stub;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "Proxy"
.end annotation

# instance fields
.field private mRemote:Landroid/os/IBinder;

# direct methods
.method constructor <init>(Landroid/os/IBinder;)V
    .registers 2
    .param p1, "remote"    # Landroid/os/IBinder;

    .prologue
    .line 98
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 100
    iput-object p1, p0, Landroid/app/IUiModeManager$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    .line 98
    return-void
.end method

# virtual methods
.method public asBinder()Landroid/os/IBinder;
    .registers 2

    .prologue
    .line 104
    iget-object v0, p0, Landroid/app/IUiModeManager$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    return-object v0
.end method

.method public disableCarMode(I)V
    .registers 7
    .param p1, "flags"    # I
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    .prologue
    .line 134
    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v0

    .line 135
    .local v0, "_data":Landroid/os/Parcel;
    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v1

    .line 137
    .local v1, "_reply":Landroid/os/Parcel;
    :try_start_8
    const-string/jumbo v2, "android.app.IUiModeManager"

    invoke-virtual {v0, v2}, Landroid/os/Parcel;->writeInterfaceToken(Ljava/lang/String;)V

    .line 138
    invoke-virtual {v0, p1}, Landroid/os/Parcel;->writeInt(I)V

    .line 139
    iget-object v2, p0, Landroid/app/IUiModeManager$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    const/4 v3, 0x2

    const/4 v4, 0x0

    invoke-interface {v2, v3, v0, v1, v4}, Landroid/os/IBinder;->transact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z

    .line 140
    invoke-virtual {v1}, Landroid/os/Parcel;->readException()V
    :try_end_1b
    .catchall {:try_start_8 .. :try_end_1b} :catchall_22

    .line 143
    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    .line 144
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    .line 132
    return-void

    .line 142
    :catchall_22
    move-exception v2

    .line 143
    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    .line 144
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    .line 142
    throw v2
.end method

.method public enableCarMode(I)V
    .registers 7
    .param p1, "flags"    # I
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    .prologue
    .line 116
    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v0

    .line 117
    .local v0, "_data":Landroid/os/Parcel;
    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v1

    .line 119
    .local v1, "_reply":Landroid/os/Parcel;
    :try_start_8
    const-string/jumbo v2, "android.app.IUiModeManager"

    invoke-virtual {v0, v2}, Landroid/os/Parcel;->writeInterfaceToken(Ljava/lang/String;)V

    .line 120
    invoke-virtual {v0, p1}, Landroid/os/Parcel;->writeInt(I)V

    .line 121
    iget-object v2, p0, Landroid/app/IUiModeManager$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    const/4 v3, 0x1

    const/4 v4, 0x0

    invoke-interface {v2, v3, v0, v1, v4}, Landroid/os/IBinder;->transact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z

    .line 122
    invoke-virtual {v1}, Landroid/os/Parcel;->readException()V
    :try_end_1b
    .catchall {:try_start_8 .. :try_end_1b} :catchall_22

    .line 125
    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    .line 126
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    .line 114
    return-void

    .line 124
    :catchall_22
    move-exception v2

    .line 125
    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    .line 126
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    .line 124
    throw v2
.end method

.method public getCurrentModeType()I
    .registers 7
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    .prologue
    .line 152
    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v0

    .line 153
    .local v0, "_data":Landroid/os/Parcel;
    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v1

    .line 156
    .local v1, "_reply":Landroid/os/Parcel;
    :try_start_8
    const-string/jumbo v3, "android.app.IUiModeManager"

    invoke-virtual {v0, v3}, Landroid/os/Parcel;->writeInterfaceToken(Ljava/lang/String;)V

    .line 157
    iget-object v3, p0, Landroid/app/IUiModeManager$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    const/4 v4, 0x3

    const/4 v5, 0x0

    invoke-interface {v3, v4, v0, v1, v5}, Landroid/os/IBinder;->transact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z

    .line 158
    invoke-virtual {v1}, Landroid/os/Parcel;->readException()V

    .line 159
    invoke-virtual {v1}, Landroid/os/Parcel;->readInt()I
    :try_end_1b
    .catchall {:try_start_8 .. :try_end_1b} :catchall_23

    move-result v2

    .line 162
    .local v2, "_result":I
    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    .line 163
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    .line 165
    return v2

    .line 161
    .end local v2    # "_result":I
    :catchall_23
    move-exception v3

    .line 162
    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    .line 163
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    .line 161
    throw v3
.end method

.method public getInterfaceDescriptor()Ljava/lang/String;
    .registers 2

    .prologue
    .line 108
    const-string/jumbo v0, "android.app.IUiModeManager"

    return-object v0
.end method

.method public getNightMode()I
    .registers 7
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    .prologue
    .line 195
    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v0

    .line 196
    .local v0, "_data":Landroid/os/Parcel;
    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v1

    .line 199
    .local v1, "_reply":Landroid/os/Parcel;
    :try_start_8
    const-string/jumbo v3, "android.app.IUiModeManager"

    invoke-virtual {v0, v3}, Landroid/os/Parcel;->writeInterfaceToken(Ljava/lang/String;)V

    .line 200
    iget-object v3, p0, Landroid/app/IUiModeManager$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    const/4 v4, 0x5

    const/4 v5, 0x0

    invoke-interface {v3, v4, v0, v1, v5}, Landroid/os/IBinder;->transact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z

    .line 201
    invoke-virtual {v1}, Landroid/os/Parcel;->readException()V

    .line 202
    invoke-virtual {v1}, Landroid/os/Parcel;->readInt()I
    :try_end_1b
    .catchall {:try_start_8 .. :try_end_1b} :catchall_23

    move-result v2

    .line 205
    .local v2, "_result":I
    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    .line 206
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    .line 208
    return v2

    .line 204
    .end local v2    # "_result":I
    :catchall_23
    move-exception v3

    .line 205
    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    .line 206
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    .line 204
    throw v3
.end method

.method public setNightMode(I)V
    .registers 7
    .param p1, "mode"    # I
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    .prologue
    .line 176
    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v0

    .line 177
    .local v0, "_data":Landroid/os/Parcel;
    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v1

    .line 179
    .local v1, "_reply":Landroid/os/Parcel;
    :try_start_8
    const-string/jumbo v2, "android.app.IUiModeManager"

    invoke-virtual {v0, v2}, Landroid/os/Parcel;->writeInterfaceToken(Ljava/lang/String;)V

    .line 180
    invoke-virtual {v0, p1}, Landroid/os/Parcel;->writeInt(I)V

    .line 181
    iget-object v2, p0, Landroid/app/IUiModeManager$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    const/4 v3, 0x4

    const/4 v4, 0x0

    invoke-interface {v2, v3, v0, v1, v4}, Landroid/os/IBinder;->transact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z

    .line 182
    invoke-virtual {v1}, Landroid/os/Parcel;->readException()V
    :try_end_1b
    .catchall {:try_start_8 .. :try_end_1b} :catchall_22

    .line 185
    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    .line 186
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    .line 174
    return-void

    .line 184
    :catchall_22
    move-exception v2

    .line 185
    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    .line 186
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    .line 184
    throw v2
.end method


text:
class CreateUserGroups < ActiveRecord::Migration
  def self.up
    create_table :user_groups do |t|
      t.string :name, :string, :not_null => true
      t.text :display_name, :string
      t.text :note
      t.integer :position
      t.timestamps
      t.datetime :deleted_at
    end
  end

  def self.down
    drop_table :user_groups
  end
end

redpajama_set_name: RedPajamaGithub


text:
package main // import "github.com/hashicorp/consul/connect/certgen"

import (
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"os"

	"github.com/hashicorp/consul/agent/connect"
	"github.com/hashicorp/consul/agent/structs"
	"github.com/mitchellh/go-testing-interface"
)

func main() {
	var numCAs = 2
	var services = []string{"web", "db", "cache"}
	var outDir string

	flag.StringVar(&outDir, "out-dir", "",
		"REQUIRED: the dir to write certificates to")
	flag.Parse()

	if outDir == "" {
		flag.PrintDefaults()
		os.Exit(1)
	}

	// Create CA certs
	var prevCA *structs.CARoot
	for i := 1; i <= numCAs; i++ {
		ca := connect.TestCA(&testing.RuntimeT{}, prevCA)
		prefix := fmt.Sprintf("%s/ca%d-ca", outDir, i)
		writeFile(prefix+".cert.pem", ca.RootCert)
		writeFile(prefix+".key.pem", ca.SigningKey)
		if prevCA != nil {
			fname := fmt.Sprintf("%s/ca%d-xc-by-ca%d.cert.pem", outDir, i, i-1)
			writeFile(fname, ca.SigningCert)
		}
		prevCA = ca

		// Create service certs for each CA
		for _, svc := range services {
			certPEM, keyPEM := connect.TestLeaf(&testing.RuntimeT{}, svc, ca)
			prefix := fmt.Sprintf("%s/ca%d-svc-%s", outDir, i, svc)
			writeFile(prefix+".cert.pem", certPEM)
			writeFile(prefix+".key.pem", keyPEM)
		}
	}
}

func writeFile(name, content string) {
	fmt.Println("Writing ", name)
	err := ioutil.WriteFile(name, []byte(content), 0600)
	if err != nil {
		log.Fatalf("failed writing file: %s", err)
	}
}


text:
package com.vmware.vim25;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

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

 * <complexType name="SwapDatastoreUnset">
 *   <complexContent>
 *     <extension base="{urn:vim25}VimFault">
 *       <sequence>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SwapDatastoreUnset")
public class SwapDatastoreUnset
    extends VimFault
{

}


text:
RSpec.describe Cassie::ConnectionHandler::Sessions do
  let(:klass) do
    Class.new do
      include Cassie::ConnectionHandler::Sessions

      def keyspace
      end

      def cluster
      end

      def logger
        @logger ||= Logger.new('/dev/null')
        # @logger ||= Logger.new(STDOUT)
      end
    end
  end
  let(:mod){ klass.new }

  before(:each) do
    allow(mod).to receive(:keyspace){default_keyspace}
    allow(mod).to receive(:cluster){cluster}
  end
  let(:default_keyspace){ "default_keyspace" }
  let(:cluster){double("Cassandra::Cluster", connect: session)}
  let(:session){ double("Cassandra::Session", keyspace: keyspace) }
  let(:keyspace){ "explicit_keyspace" }

  describe ".sessions" do
    it "is enumerable" do
      expect(mod.sessions).to be_a_kind_of(Enumerable)
    end
  end

  describe ".session" do
    context "when a keyspace argument is passed" do
      context "when no session exists for requested keyspace" do
        it "creates session for keyspace" do
          expect(cluster).to receive(:connect).with(keyspace)

          mod.session(keyspace)
        end
        it "instruments connection opening" do
          allow(cluster).to receive(:connect).with(keyspace)

          expect(Cassie.instrumenter).to receive(:instrument).with('cassie.session.connect')

          mod.session(keyspace)
        end
      end
      context "when a session exists for requested keyspace" do
        before(:each){ mod.session(keyspace) }
        it "doesn't create another session" do
          expect(cluster).not_to receive(:connect)

          mod.session(keyspace)
        end
      end
      context "passing nil keyspace argument" do
        it "creates session for no keyspace" do
          expect(cluster).to receive(:connect).with(nil)

          mod.session(nil)
        end
      end
    end
    context "when a keyspace argument is not passed" do
      it "uses self.keyspace" do
        expect(cluster).to receive(:connect).with(default_keyspace)

        mod.session
      end
    end
  end
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>
  Class: TTYCoke::TTYCokeLogFormat

    — TTYCoke Documentation

</title>

  <link rel="stylesheet" href="../css/style.css" type="text/css" media="screen" charset="utf-8" />

  <link rel="stylesheet" href="../css/common.css" type="text/css" media="screen" charset="utf-8" />

    Index (T) »
    TTYCoke
     »
    TTYCokeLogFormat

(no frames)

    Class List

    Method List

    File List

Class: TTYCoke::TTYCokeLogFormat

Inherits:

      Logger::Formatter

Object

Logger::Formatter

TTYCoke::TTYCokeLogFormat

        show all

Defined in:

lib/ttycoke/log.rb

      Instance Method Summary
      (collapse)

      - (Object) call(severity, time, program_name, message)

Instance Method Details

    - (<tt>Object</tt>) call(severity, time, program_name, message)

6
7
8
9
10
11
12
13
14
15
16
17
18
19

# File 'lib/ttycoke/log.rb', line 6

def call severity, time, program_name, message
  case severity
  when "DEBUG"
    datetime      = time.strftime("%Y-%m-%d %H:%M")
    print_message = "DEBUG".yellow + "--- (#{datetime})\n#{String(message)}"
    [print_message].join("\n") + "\n\n"
  when "ERROR"
    datetime      = time.strftime("%Y-%m-%d %H:%M")
    print_message = "ERROR".red + " --- (#{datetime})\n#{String(message)}"
    [print_message].join("\n") + "\n\n"
  else
    super
  end
end

  Generated on Mon Jan 30 03:06:12 2012 by
  yard
  0.7.4 (ruby-1.9.3).


text:
package hudson.plugins.scm_sync_configuration.strategies.model;

import java.util.regex.Pattern;

public class PageMatcher {

	private Pattern urlRegex;
	private String targetFormSelector;

	public PageMatcher(String _urlRegexStr, String _targetFormSelector){
		this.urlRegex = Pattern.compile(_urlRegexStr);
		this.targetFormSelector = _targetFormSelector;
	}

	public Pattern getUrlRegex() {
		return urlRegex;
	}

	public String getTargetFormSelector() {
		return targetFormSelector;
	}
}


text:
package web

import (
	"encoding/json"
	"fmt"
	"html/template"
	"log"
	"net/http"
	"path/filepath"
	"strconv"
	"time"

	"github.com/craigfurman/woodhouse-ci/chunkedio"
	"github.com/craigfurman/woodhouse-ci/jobs"
	"github.com/craigfurman/woodhouse-ci/web/helpers"

	"github.com/gorilla/mux"
)

//go:generate counterfeiter -o fake_job_service/fake_job_service.go . JobService
type JobService interface {
	AllLatestBuilds() ([]jobs.Build, error)
	Save(job *jobs.Job) error
	RunJob(id string) (int, error)
	FindBuild(jobId string, buildNumber int) (jobs.Build, error)
	HighestBuild(jobId string) (int, error)
	Stream(jobId string, buildNumber int, streamOffset int64) (*chunkedio.ChunkedReader, error)
}

type Handler struct {
	*mux.Router

	jobService   JobService
	templates    map[string]*template.Template
	templateSets map[string][]string
}

func New(jobService JobService, templateDir string, preloadTemplates bool) *Handler {
	templateSets := collectTemplates(templateDir)
	templates := make(map[string]*template.Template)
	if preloadTemplates {
		for viewName, templateSet := range templateSets {
			templates[viewName] = template.Must(template.ParseFiles(templateSet...))
		}
	}

	router := mux.NewRouter()

	h := &Handler{
		Router:       router,
		templates:    templates,
		templateSets: templateSets,
		jobService:   jobService,
	}

	h.HandleFunc("/", h.rootHandler).Methods("GET")
	h.HandleFunc("/jobs", h.listJobs).Methods("GET")
	h.HandleFunc("/jobs/status", h.listJobStatuses).Methods("GET")
	h.HandleFunc("/jobs/new", h.newJob).Methods("GET")
	h.HandleFunc("/jobs", h.createJob).Methods("POST")
	h.HandleFunc("/jobs/{jobId}/builds", h.createBuild).Methods("POST")
	h.HandleFunc("/jobs/{jobId}/builds/{buildId}", h.showBuild).Methods("GET")
	h.HandleFunc("/jobs/{jobId}/builds/{buildId}/output", h.streamBuild).Methods("GET")

	return h
}

func (h *Handler) rootHandler(w http.ResponseWriter, r *http.Request) {
	http.Redirect(w, r, "/jobs", 302)
}

func (h *Handler) listJobs(w http.ResponseWriter, r *http.Request) {
	if list, err := h.jobService.AllLatestBuilds(); err == nil {
		type cell struct {
			ID     string
			Name   string
			Status string
		}

		cells := [][]cell{}
		for _, buildRow := range helpers.JobGrid(list) {
			cellRow := []cell{}
			for _, build := range buildRow {
				cellRow = append(cellRow, cell{
					ID:     build.ID,
					Name:   build.Name,
					Status: helpers.Classes(build),
				})
			}
			cells = append(cells, cellRow)
		}

		p := struct {
			BuildRows [][]cell
		}{
			BuildRows: cells,
		}
		h.renderTemplate("list_jobs", p, w)
	} else {
		h.renderErrPage("listing jobs", err, w, r)
	}
}

func (h *Handler) listJobStatuses(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/event-stream\n\n")

	for {
		list, err := h.jobService.AllLatestBuilds()
		must(err)

		statuses := make(map[string]string)
		for _, build := range list {
			statuses[build.ID] = helpers.Classes(build)
			msg, err := json.Marshal(statuses)
			must(err)
			if _, err := w.Write([]byte(eventMessage("jobs", string(msg)))); err != nil {
				log.Printf("trying to write job statuses JSON. assuming remote end hung up. Cause: %v\n", err)
				return
			}

			w.(http.Flusher).Flush()
			time.Sleep(time.Millisecond * 100)
		}
	}
}

func (h *Handler) newJob(w http.ResponseWriter, r *http.Request) {
	h.renderTemplate("new_job", nil, w)
}

func (h *Handler) createJob(w http.ResponseWriter, r *http.Request) {
	job := jobs.Job{
		Name:          r.FormValue("name"),
		Command:       r.FormValue("command"),
		DockerImage:   r.FormValue("dockerImage"),
		GitRepository: r.FormValue("gitRepo"),
	}

	if err := h.jobService.Save(&job); err != nil {
		h.renderErrPage("saving job", err, w, r)
		return
	}

	if buildNumber, err := h.jobService.RunJob(job.ID); err == nil {
		http.Redirect(w, r, fmt.Sprintf("/jobs/%s/builds/%d", job.ID, buildNumber), 302)
	} else {
		h.renderErrPage("running job", err, w, r)
	}
}

func (h *Handler) createBuild(w http.ResponseWriter, r *http.Request) {
	jobID := mux.Vars(r)["jobId"]
	if buildNumber, err := h.jobService.RunJob(jobID); err == nil {
		http.Redirect(w, r, fmt.Sprintf("/jobs/%s/builds/%d", jobID, buildNumber), 302)
	} else {
		h.renderErrPage("running job", err, w, r)
	}
}

func (h *Handler) showBuild(w http.ResponseWriter, r *http.Request) {
	jobId := mux.Vars(r)["jobId"]
	buildIdStr := mux.Vars(r)["buildId"]

	if buildIdStr == "latest" {
		buildNumber, err := h.jobService.HighestBuild(jobId)
		must(err)
		http.Redirect(w, r, fmt.Sprintf("/jobs/%s/builds/%d", jobId, buildNumber), 302)
		return
	}

	buildId, err := strconv.Atoi(buildIdStr)
	must(err)

	if build, err := h.jobService.FindBuild(jobId, buildId); err == nil {
		sanitizedOutput := helpers.SanitisedHTML(build.Output)
		highestBuildNumber, err := h.jobService.HighestBuild(jobId)
		if err != nil {
			h.renderErrPage("finding highest build number for job", err, w, r)
			return
		}
		buildNumbers := []int{}
		for i := highestBuildNumber; i > 0; i-- {
			buildNumbers = append(buildNumbers, i)
		}

		buildView := struct {
			Build                jobs.Build
			BuildNumber          int
			Output               template.HTML
			BytesAlreadyReceived int
			ExitMessage          string
			BuildNumbers         []int
		}{
			Build:                build,
			BuildNumber:          buildId,
			Output:               sanitizedOutput,
			BytesAlreadyReceived: len(sanitizedOutput),
			ExitMessage:          helpers.Message(build),
			BuildNumbers:         buildNumbers,
		}
		h.renderTemplate("show_build", buildView, w)
	} else {
		h.renderErrPage("retrieving job", err, w, r)
	}
}

func (h *Handler) streamBuild(w http.ResponseWriter, r *http.Request) {
	jobId := mux.Vars(r)["jobId"]
	buildId, err := strconv.Atoi(mux.Vars(r)["buildId"])
	must(err)

	must(r.ParseForm())
	streamOffset, err := strconv.Atoi(r.Form.Get("offset"))
	must(err)

	streamer, err := h.jobService.Stream(jobId, buildId, int64(streamOffset))
	must(err)

	w.Header().Set("Content-Type", "text/event-stream\n\n")

	for {
		bytes, done := streamer.Next()
		_, err = w.Write([]byte(eventMessage("output", string(helpers.SanitisedHTML(bytes)))))
		must(err)

		w.(http.Flusher).Flush()

		if done {
			break
		}
	}

	must(streamer.Close())

	build, err := h.jobService.FindBuild(jobId, buildId)
	must(err)

	w.Write([]byte(eventMessage("end", helpers.Message(build))))
}

func eventMessage(eventName, data string) string {
	return fmt.Sprintf("event: %s\ndata: %s\n\n", eventName, data)
}

type Error struct {
	Error string
}

func (h Handler) renderErrPage(message string, err error, w http.ResponseWriter, r *http.Request) {
	log.Printf("Error: %s: %v", message, err)
	w.WriteHeader(500)
	h.renderTemplate("error", Error{Error: err.Error()}, w)
}

func (h Handler) renderTemplate(name string, pageObject interface{}, w http.ResponseWriter) {
	w.Header().Set("Content-Type", "text/html")
	if t, ok := h.templates[name]; ok {
		must(t.Execute(w, pageObject))
	} else {
		log.Printf("template %s not found, parsing. If debug mode is not active, then something has gone wrong!\n", name)
		must(template.Must(template.ParseFiles(h.templateSets[name]...)).Execute(w, pageObject))
	}
}

func collectTemplates(templateDir string) map[string][]string {
	templateFor := func(viewType, view string) string {
		return filepath.Join(templateDir, viewType, view+".html")
	}

	layoutFor := func(layout string) string {
		return templateFor("layouts", layout)
	}

	viewFor := func(view string) string {
		return templateFor("views", view)
	}

	listJobs := "list_jobs"
	newJob := "new_job"
	showBuild := "show_build"
	errorPage := "error"

	return map[string][]string{
		listJobs:  {layoutFor("outer"), viewFor(listJobs)},
		newJob:    {layoutFor("outer"), layoutFor("single_column"), viewFor(newJob)},
		showBuild: {layoutFor("outer"), layoutFor("single_column"), viewFor(showBuild)},
		errorPage: {layoutFor("outer"), layoutFor("single_column"), viewFor(errorPage)},
	}
}

func must(err error) {
	if err != nil {
		panic(err)
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:p="http://www.springframework.org/schema/p"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

  <context:annotation-config/>

</beans>


text:
namespace NLog.Internal
{
#if !NET4_6 && !NETSTANDARD && !SILVERLIGHT
    using System;
    using System.Runtime.Serialization;
    using NLog.Common;

    [Serializable]
    internal class ObjectHandleSerializer : ISerializable
    {
        [NonSerialized]
        private readonly object _wrapped;

        public ObjectHandleSerializer()
        {
        }

        public ObjectHandleSerializer(object wrapped)
        {
            _wrapped = wrapped;
        }

        protected ObjectHandleSerializer(SerializationInfo info, StreamingContext context)
        {
            Type type = null;
            try
            {
                type = (Type)info.GetValue("wrappedtype", typeof(Type));
                _wrapped = info.GetValue("wrappedvalue", type);
            }
            catch (Exception ex)
            {
                _wrapped = string.Empty;    // Type cannot be resolved in this AppDomain
                InternalLogger.Debug(ex, "ObjectHandleSerializer failed to deserialize object: {0}", type);
            }
        }

#if NET4_5
        [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, SerializationFormatter = true)]
#endif
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            try
            {
                if (_wrapped is ISerializable || _wrapped.GetType().IsSerializable)
                {
                    info.AddValue("wrappedtype", _wrapped.GetType());
                    info.AddValue("wrappedvalue", _wrapped);
                }
                else
                {
                    info.AddValue("wrappedtype", typeof(string));
                    string serializedString = string.Empty;
                    try
                    {
                        serializedString = _wrapped?.ToString();
                    }
                    finally
                    {
                        info.AddValue("wrappedvalue", serializedString ?? string.Empty);
                    }
                }
            }
            catch (Exception ex)
            {
                // ToString on random object can throw exception
                InternalLogger.Debug(ex, "ObjectHandleSerializer failed to serialize object: {0}", _wrapped?.GetType());
            }
        }

        public object Unwrap()
        {
            return _wrapped ?? string.Empty;
        }
    }
#endif
}


text:
package org.openfact.subsystem.server.extension;

import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.StringListAttributeDefinition;
import org.jboss.as.controller.operations.common.GenericSubsystemDescribeHandler;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.openfact.subsystem.server.attributes.ProvidersListAttributeBuilder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Definition of subsystem=openfact-server.
 *
 * @author Stan Silvert ssilvert@redhat.com (C) 2013 Red Hat Inc.
 */
public class OpenfactSubsystemDefinition extends SimpleResourceDefinition {

    static final SimpleAttributeDefinition WEB_CONTEXT =
        new SimpleAttributeDefinitionBuilder("web-context", ModelType.STRING, true)
            .setAllowExpression(true)
            .setDefaultValue(new ModelNode("auth"))
            .setRestartAllServices()
            .build();

    static final StringListAttributeDefinition PROVIDERS = new ProvidersListAttributeBuilder().build();

    static final SimpleAttributeDefinition MASTER_ORGANIZATION_NAME =
        new SimpleAttributeDefinitionBuilder("master-organization-name", ModelType.STRING, true)
            .setAllowExpression(true)
            .setDefaultValue(new ModelNode("master"))
            .setRestartAllServices()
            .build();

    static final SimpleAttributeDefinition SCHEDULED_TASK_INTERVAL =
        new SimpleAttributeDefinitionBuilder("scheduled-task-interval", ModelType.LONG, true)
            .setAllowExpression(true)
            .setDefaultValue(new ModelNode("900"))
            .setRestartAllServices()
            .build();

    static final List<AttributeDefinition> ALL_ATTRIBUTES = new ArrayList<AttributeDefinition>();

    static {
        ALL_ATTRIBUTES.add(WEB_CONTEXT);
        ALL_ATTRIBUTES.add(PROVIDERS);
        ALL_ATTRIBUTES.add(MASTER_ORGANIZATION_NAME);
        ALL_ATTRIBUTES.add(SCHEDULED_TASK_INTERVAL);
    }

    private static final Map<String, AttributeDefinition> DEFINITION_LOOKUP = new HashMap<String, AttributeDefinition>();
    static {
        for (AttributeDefinition def : ALL_ATTRIBUTES) {
            DEFINITION_LOOKUP.put(def.getXmlName(), def);
        }
    }

    private static OpenfactSubsystemWriteAttributeHandler attrHandler = new OpenfactSubsystemWriteAttributeHandler(ALL_ATTRIBUTES);

    protected OpenfactSubsystemDefinition() {
        super(OpenfactExtension.PATH_SUBSYSTEM,
            OpenfactExtension.getResourceDescriptionResolver("subsystem"),
            OpenfactSubsystemAdd.INSTANCE,
            OpenfactSubsystemRemoveHandler.INSTANCE
        );
    }

    @Override
    public void registerOperations(ManagementResourceRegistration resourceRegistration) {
        super.registerOperations(resourceRegistration);
        resourceRegistration.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE);
        resourceRegistration.registerOperationHandler(MigrateJsonOperation.DEFINITION, new MigrateJsonOperation());
    }

    @Override
    public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
        super.registerAttributes(resourceRegistration);
        for (AttributeDefinition attrDef : ALL_ATTRIBUTES) {
            resourceRegistration.registerReadWriteAttribute(attrDef, null, attrHandler);
        }
    }

    public static AttributeDefinition lookup(String name) {
        return DEFINITION_LOOKUP.get(name);
    }
}


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/documentai/v1/document_io.proto

namespace Google\Cloud\DocumentAI\V1\DocumentOutputConfig;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * The configuration used when outputting documents.
 *
 * Generated from protobuf message google.cloud.documentai.v1.DocumentOutputConfig.GcsOutputConfig
 */
class GcsOutputConfig extends \Google\Protobuf\Internal\Message
{
    /**
     * The Cloud Storage uri (a directory) of the output.
     *
     * Generated from protobuf field string gcs_uri = 1;
     */
    private $gcs_uri = '';

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type string $gcs_uri
     *           The Cloud Storage uri (a directory) of the output.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Cloud\Documentai\V1\DocumentIo::initOnce();
        parent::__construct($data);
    }

    /**
     * The Cloud Storage uri (a directory) of the output.
     *
     * Generated from protobuf field string gcs_uri = 1;
     * @return string
     */
    public function getGcsUri()
    {
        return $this->gcs_uri;
    }

    /**
     * The Cloud Storage uri (a directory) of the output.
     *
     * Generated from protobuf field string gcs_uri = 1;
     * @param string $var
     * @return $this
     */
    public function setGcsUri($var)
    {
        GPBUtil::checkString($var, True);
        $this->gcs_uri = $var;

        return $this;
    }

}


text:
package unit.com.vendingontime.backend.services;

import com.vendingontime.backend.models.AbstractEntity;
import com.vendingontime.backend.models.bodymodels.PersonRequest;
import com.vendingontime.backend.models.company.Company;
import com.vendingontime.backend.models.machine.Machine;
import com.vendingontime.backend.models.person.Person;
import com.vendingontime.backend.repositories.MachineRepository;
import com.vendingontime.backend.services.RemoveMachineService;
import com.vendingontime.backend.services.utils.AuthProvider;
import com.vendingontime.backend.services.utils.BusinessLogicException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import testutils.FixtureFactory;

import java.util.Optional;

import static com.vendingontime.backend.models.bodymodels.PersonRequest.EMPTY_REQUESTER;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;

public class RemoveMachineServiceTest {
    private MachineRepository repository;

    private RemoveMachineService removeMachineService;
    private AuthProvider authProvider;

    private Machine machine;
    private Person requester;
    private PersonRequest personRequest;

    @Before
    public void setUp() throws Exception {
        repository = mock(MachineRepository.class);
        authProvider = mock(AuthProvider.class);

        removeMachineService = new RemoveMachineService(repository, authProvider);

        Company company = FixtureFactory.generateCompanyWithOwner();
        requester = company.getOwner();
        machine = FixtureFactory.generateMachine().setId("MACHINE_ID");
        company.addMachine(machine);

        personRequest = FixtureFactory.generatePersonRequestFrom(machine, requester);

        when(repository.findById(anyString())).thenReturn(Optional.empty());
        when(repository.findById(machine.getId())).thenReturn(Optional.of(machine));
        when(repository.update(machine)).thenReturn(Optional.of(machine));

        when(authProvider.canModify(any(), any(AbstractEntity.class))).thenReturn(true);
    }

    @After
    public void tearDown() throws Exception {
        repository = null;
        authProvider = null;

        removeMachineService = null;

        machine = null;
        requester = null;
        personRequest = null;
    }

    @Test
    public void removeMachine() {
        Optional<Machine> possibleRemoved = removeMachineService.removeBy(personRequest);

        assertThat(possibleRemoved.isPresent(), is(true));

        verify(repository, times(1)).findById(machine.getId());
        verify(repository, times(1)).update(any());

        Machine savedMachine = repository.findById(machine.getId()).get();
        assertThat(savedMachine.isDisabled(), is(true));
    }

    @Test
    public void removeMachine_withInvalidRequester_throwsException() {
        try {
            personRequest.setRequester(null);
            removeMachineService.removeBy(personRequest);
            fail();
        } catch (BusinessLogicException ex) {
            assertArrayEquals(new String[]{EMPTY_REQUESTER}, ex.getCauses());

            verify(repository, never()).findById(any());
            verify(repository, never()).update(any());
        }
    }

    @Test
    public void removeMachine_withUnknownId_returnsEmpty() throws Exception {
        String unknownId = "UNKNOWN_ID";
        personRequest.setId(unknownId);
        Optional<Machine> possibleRemoved = removeMachineService.removeBy(personRequest);

        assertThat(possibleRemoved.isPresent(), is(false));

        verify(repository, times(1)).findById(unknownId);
        verify(repository, never()).update(any());
    }

    @Test
    public void removeMachine_requesterNotAuthorized_throwsException() {
        when(authProvider.canModify(requester, (AbstractEntity) machine)).thenReturn(false);

        try {
            requester.setOwnedCompany(FixtureFactory.generateCompany().setId("ANOTHER_COMPANY_ID"));
            removeMachineService.removeBy(personRequest);
            fail();
        } catch (BusinessLogicException ex) {
            assertArrayEquals(new String[]{RemoveMachineService.INSUFFICIENT_PERMISSIONS}, ex.getCauses());

            verify(repository, times(1)).findById(machine.getId());
            verify(repository, never()).update(any());
        }
    }
}


text:
using System;
using System.Collections.Generic;
using Amazon.CloudWatch;
using Amazon.CloudWatch.Model;
using QueueIT.ScalingDynamoDB.Configuration;
using QueueIT.ScalingDynamoDB.BusinessLogic.Model;
using Amazon.DynamoDBv2;
using Microsoft.Practices.EnterpriseLibrary.Logging;

namespace QueueIT.ScalingDynamoDB.BusinessLogic.Statistics
{
    public class Table : ITable
    {
        readonly SettingsSection _settings;
        private LogWriter _logger;
        private AWS.DynamoDB _AWSDynamoDBFunctions;
        public Table(SettingsSection Settings, IAmazonDynamoDB Client, LogWriter Logger)
        {
            _settings = Settings;
            _logger = Logger;
            _AWSDynamoDBFunctions = new AWS.DynamoDB(_settings, Client, _logger);
        }
        public int get_consumed_units_percent(Enums.ReadOrWriteType updateType, string table_name, string logTextTableGSIName,
            int lookback_window_start = 15, string gsi_name="")
        {
            double consumed_units = 0;
            int consumed_units_percent = 0;
            long provisioned_units = 0;
            string aws_metric_name = updateType == Enums.ReadOrWriteType.read ? "ConsumedReadCapacityUnits" : "ConsumedWriteCapacityUnits";
            List<Datapoint> metrics = __get_aws_metric(table_name, lookback_window_start, aws_metric_name, gsi_name);
            if (metrics != null && metrics.Count > 0)
            {
                consumed_units = (Math.Ceiling(metrics[0].Sum / 300.0));
            }
            try
            {
                provisioned_units = _AWSDynamoDBFunctions.get_provisioned_units(updateType, table_name, gsi_name);
                consumed_units_percent = (int)Math.Ceiling(
                        (consumed_units / provisioned_units)
                        * 100);
            }
            catch (Exception)
            {

                throw;
            }
            _logger.Write(new DebugLogEntry(
                               string.Format("{0} - Consumed {1} units: {2:d}% ({3}/{4} units)",
                               logTextTableGSIName, System.Enum.GetName(typeof(Enums.ReadOrWriteType), updateType), consumed_units_percent, consumed_units, provisioned_units)
                               , 3000));
            return consumed_units_percent;
        }

        public int get_throttled_event_count(Enums.ReadOrWriteType updateType, string table_name, string logTextTableGSIName,
            int lookback_window_start = 15, string gsi_name = "")
        {
            int throttled_count = 0;
            string aws_metric_name = updateType == Enums.ReadOrWriteType.read ? "ReadThrottleEvents" : "WriteThrottleEvents";
            List<Datapoint> metrics = __get_aws_metric(table_name, lookback_window_start, aws_metric_name, gsi_name);
            if (metrics != null && metrics.Count > 0)
            {
                throttled_count = (int)metrics[0].Sum;
            }
            _logger.Write(new DebugLogEntry(
                               string.Format("{0} - {1} throttle count: {2:d}", logTextTableGSIName, System.Enum.GetName(typeof(Enums.ReadOrWriteType), updateType), throttled_count)
                               , 3001));
            return throttled_count;
        }

        public List<Datapoint> __get_aws_metric(string table_name, int lookback_window_start, string metric_name, string gsi_name ="")
        {
            //    @retry(
            //wait='exponential_sleep',
            //wait_exponential_multiplier=1000,
            //wait_exponential_max=10000,
            //stop_max_attempt_number=10)

            try
            {
                DateTime start_time = DateTime.UtcNow.AddMinutes(-1 * lookback_window_start);
                DateTime end_time = DateTime.UtcNow.AddMinutes(-1 * (lookback_window_start - 5));

                Amazon.CloudWatch.AmazonCloudWatchClient _client = GetCloudWatchClient();
                Dimension dimension = new Dimension() { Name = "TableName", Value = table_name };
                List<Dimension> dimensions = new List<Dimension>() { dimension };
                if (gsi_name != "")
                    dimensions.Add(new Dimension() { Name = "GlobalSecondaryIndexName", Value = gsi_name });

                return _client.GetMetricStatistics(new GetMetricStatisticsRequest
                {
                    Period = 300,                 // Always look at 5 minutes windows
                    StartTime = start_time,
                    EndTime = end_time,
                    MetricName = metric_name,
                    Namespace = "AWS/DynamoDB",
                    Statistics = { "Sum" },
                    Dimensions = dimensions,
                    Unit = "Count"
                }).Datapoints;

            }
            catch (Exception ex)
            {
                _logger.Write(new ErrorLogEntry(
                              string.Format("Unexpected exception: {0} : {1}", ex.Message, ex.StackTrace)
                              , 3002,
                              System.Diagnostics.TraceEventType.Critical));
                throw;
            }
        }

        private AmazonCloudWatchClient GetCloudWatchClient(int retries = 3)
        {
            AmazonCloudWatchClient client = null;
            if (_settings.AWSAccessKey != string.Empty && _settings.AWSSecretAccessKey != string.Empty)
            {
                //TODO: log Authenticating to CloudWatch using credentials in configuration file
                AmazonCloudWatchConfig config = new AmazonCloudWatchConfig
                {
                    ServiceURL = _settings != null
                        ? _settings.CloudWatchServiceURL
                        : "http://monitoring.eu-west-1.amazonaws.com",
                    MaxErrorRetry = retries
                };

                client = new AmazonCloudWatchClient(_settings.AWSAccessKey, _settings.AWSSecretAccessKey, config);
            }
            return client;
        }
    }
}


text:
<?php

namespace spec\Sylius\Bundle\ShippingBundle\Processor;

use PhpSpec\ObjectBehavior;
use Sylius\Bundle\ShippingBundle\Model\ShipmentInterface;

/**
 * @author Saša Stamenković <umpirsky@gmail.com>
 */
class ShipmentProcessorSpec extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType('Sylius\Bundle\ShippingBundle\Processor\ShipmentProcessor');
    }

    function it_implements_Sylius_shipment_processor_interface()
    {
        $this->shouldImplement('Sylius\Bundle\ShippingBundle\Processor\ShipmentProcessorInterface');
    }

    /**
     * @param Sylius\Bundle\ShippingBundle\Model\ShipmentInterface     $shipment
     * @param Sylius\Bundle\ShippingBundle\Model\ShipmentItemInterface $item
     */
    function it_updates_shipment_states($shipment, $item)
    {
        $shipment->getState()->shouldBeCalled()->willReturn(ShipmentInterface::STATE_READY);
        $shipment->setState(ShipmentInterface::STATE_SHIPPED)->shouldBeCalled();
        $shipment->getItems()->shouldBeCalled()->willReturn(array($item));

        $item->getShippingState()->shouldBeCalled()->willReturn(ShipmentInterface::STATE_READY);
        $item->setShippingState(ShipmentInterface::STATE_SHIPPED)->shouldBeCalled();

        $this->updateShipmentStates(array($shipment), ShipmentInterface::STATE_SHIPPED, ShipmentInterface::STATE_READY);
    }

    /**
     * @param Sylius\Bundle\ShippingBundle\Model\ShipmentInterface     $shipment
     * @param Sylius\Bundle\ShippingBundle\Model\ShipmentItemInterface $item
     */
    function it_does_not_update_shipment_states_if_state_from_does_not_match($shipment, $item)
    {
        $shipment->getState()->shouldBeCalled()->willReturn(ShipmentInterface::STATE_SHIPPED);
        $shipment->setState(ShipmentInterface::STATE_SHIPPED)->shouldNotBeCalled();
        $shipment->getItems()->shouldBeCalled()->willReturn(array($item));

        $item->getShippingState()->shouldBeCalled()->willReturn(ShipmentInterface::STATE_SHIPPED);
        $item->setShippingState(ShipmentInterface::STATE_SHIPPED)->shouldNotBeCalled();

        $this->updateShipmentStates(array($shipment), ShipmentInterface::STATE_SHIPPED, ShipmentInterface::STATE_READY);
    }

    /**
     * @param Sylius\Bundle\ShippingBundle\Model\ShipmentItemInterface $item
     */
    function it_updates_item_states($item)
    {
        $item->getShippingState()->shouldBeCalled()->willReturn(ShipmentInterface::STATE_READY);
        $item->setShippingState(ShipmentInterface::STATE_SHIPPED)->shouldBeCalled();

        $this->updateItemStates(array($item), ShipmentInterface::STATE_SHIPPED, ShipmentInterface::STATE_READY);
    }

    /**
     * @param Sylius\Bundle\ShippingBundle\Model\ShipmentItemInterface $item
     */
    function it_does_not_update_item_states_if_state_from_does_not_match($item)
    {
        $item->getShippingState()->shouldBeCalled()->willReturn(ShipmentInterface::STATE_SHIPPED);
        $item->setShippingState(ShipmentInterface::STATE_SHIPPED)->shouldNotBeCalled();

        $this->updateItemStates(array($item), ShipmentInterface::STATE_SHIPPED, ShipmentInterface::STATE_READY);
    }
}


text:
#ifndef TextTrackResource_h
#define TextTrackResource_h

#include "core/loader/cache/Resource.h"

namespace WebCore {

class TextTrackResource : public Resource {
public:
    TextTrackResource(const ResourceRequest&);
    virtual ~TextTrackResource();

    virtual void appendData(const char*, int) OVERRIDE;
};

}

#endif


text:
module.exports = {
  createSchema: require('./createSchema'),
  parse: require('./parse'),
  path: require('./path'),
  query: require('./query'),
  stringify: require('./stringify'),
  toxml: require('./toxml'),
  validate: require('./validate'),
  tpath: require('./tpath')
}


text:
import path from 'path';
const fileOperations = require('../src/file-operations');
const { readFile, parseFile } = fileOperations;

describe('JS: Combined', () => {
  const templateName = 'TestModule';
  const readDirPath = path.join(__dirname, '..', 'templates', 'combined', 'js');

  it('creates a TemplateNativeModule.js', async () => {
    const fileData = await readFile('TemplateNativeModule.js', readDirPath);
    const parsedFile = parseFile(fileData, { templateName });
    expect(parsedFile).toMatchSnapshot();
  });

  it('creates a TemplateNativeView.js', async () => {
    const fileData = await readFile('TemplateNativeView.js', readDirPath);
    const parsedFile = parseFile(fileData, { templateName });
    expect(parsedFile).toMatchSnapshot();
  });
});

describe('JS: Native Modules', () => {
  const templateName = 'TestModule';
  const readDirPath = path.join(__dirname, '..', 'templates', 'modules', 'js');

  it('creates a TemplateNativeModule.js', async () => {
    const fileData = await readFile('TemplateNativeModule.js', readDirPath);
    const parsedFile = parseFile(fileData, { templateName });
    expect(parsedFile).toMatchSnapshot();
  });
});

describe('JS: UI Components', () => {
  const templateName = 'TestModule';
  const readDirPath = path.join(
    __dirname,
    '..',
    'templates',
    'ui-components',
    'js',
  );

  it('creates a TemplateNativeView.js', async () => {
    const fileData = await readFile('TemplateNativeView.js', readDirPath);
    const parsedFile = parseFile(fileData, { templateName });
    expect(parsedFile).toMatchSnapshot();
  });
});


text:
package com.hazelcast.wm.test;

import com.hazelcast.core.IMap;
import com.hazelcast.spi.serialization.SerializationService;
import com.hazelcast.web.SessionState;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.impl.client.BasicCookieStore;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

public abstract class WebFilterSlowTests extends AbstractWebFilterTest {

    String testName;

    protected WebFilterSlowTests(String serverXml1) {
        super(serverXml1);
    }

    protected WebFilterSlowTests(String serverXml1, String serverXml2) {
        super(serverXml1, serverXml2);
        testName = serverXml1;
    }

    @Test
    public void test_github_issue_3360() throws Exception {
        CookieStore cookieStore = new BasicCookieStore();
        //Creates session on server1
        executeRequest("write", serverPort1, cookieStore);
        //Reads value on server 1 (just to check that method works)
        assertEquals("value", executeRequest("readIfExist", serverPort1, cookieStore));
        //Reads value on server 2
        assertEquals("value", executeRequest("readIfExist", serverPort2, cookieStore));
    }

    @Test
    public void test_github_issue_2887() throws Exception {
        CookieStore cookieStore = new BasicCookieStore();
        executeRequest("write", serverPort1, cookieStore);
        executeRequest("read", serverPort2, cookieStore);
        //expire session only on server2
        executeRequest("timeout", serverPort2, cookieStore);
        //Wait till session on server2 is expired
        sleepSeconds(2);
        //send redirect to server2 which has no local session but there is a distributed session.
        HttpResponse resp = request("redirect", serverPort2, cookieStore);
        assertEquals(302, resp.getStatusLine().getStatusCode());
    }

    @Test(timeout = 60000)
    public void testAttributeRemoval_issue_2618() throws Exception {
        IMap<String, Object> map = hz.getMap(DEFAULT_MAP_NAME);
        CookieStore cookieStore = new BasicCookieStore();
        assertEquals("true", executeRequest("write", serverPort1, cookieStore));
        assertEquals(1, map.size());
        assertEquals("value", executeRequest("read", serverPort2, cookieStore));
        assertEquals("true", executeRequest("remove_set_null", serverPort2, cookieStore));
        assertEquals("null", executeRequest("read", serverPort1, cookieStore));
    }

    @Test(timeout = 20000)
    public void test_getAttributeNames_AfterGetAttribute() throws Exception {
        CookieStore cookieStore = new BasicCookieStore();
        executeRequest("read", serverPort1, cookieStore);
        assertEquals("", executeRequest("names", serverPort1, cookieStore));
    }

    @Test(timeout = 60000)
    public void test_update_server2_and_fetch_server1() throws Exception {
        CookieStore cookieStore = new BasicCookieStore();

        assertEquals("true", executeRequest("write", serverPort1, cookieStore));
        assertEquals("value", executeRequest("read", serverPort2, cookieStore));

        assertEquals("value-updated", executeRequest("update-and-read-same-request", serverPort2, cookieStore));
        assertEquals("value-updated", executeRequest("update-and-read-same-request", serverPort1, cookieStore));
    }

    @Test(timeout = 60000)
    public void testAttributeNames_issue_2434() throws Exception {
        CookieStore cookieStore = new BasicCookieStore();
        assertEquals("null", executeRequest("read", serverPort1, cookieStore));
        //no name should be created
        assertEquals("", executeRequest("names", serverPort1, cookieStore));
    }

    @Test(timeout = 60000)
    public void test_github_issue_2187() throws Exception {
        IMap<String, String> map = hz.getMap(DEFAULT_MAP_NAME);
        CookieStore cookieStore = new BasicCookieStore();
        assertEquals("null", executeRequest("read", serverPort1, cookieStore));
        assertEquals("true", executeRequest("write", serverPort1, cookieStore));
        assertEquals(1, map.size());
        assertEquals("value", executeRequest("read", serverPort1, cookieStore));
    }

    @Test(timeout = 60000)
    public void testAttributeDistribution() throws Exception {
        IMap<String, Object> map = hz.getMap(DEFAULT_MAP_NAME);
        CookieStore cookieStore = new BasicCookieStore();
        assertEquals("true", executeRequest("write", serverPort1, cookieStore));
        assertEquals(1, map.size());
        assertEquals("value", executeRequest("read", serverPort2, cookieStore));
    }

    @Test(timeout = 60000)
    public void testAttributeRemoval() throws Exception {
        IMap<String, Object> map = hz.getMap(DEFAULT_MAP_NAME);
        CookieStore cookieStore = new BasicCookieStore();
        assertEquals("true", executeRequest("write", serverPort1, cookieStore));
        assertEquals(1, map.size());
        assertEquals("value", executeRequest("read", serverPort2, cookieStore));
        assertEquals("true", executeRequest("remove", serverPort2, cookieStore));
        assertEquals("null", executeRequest("read", serverPort1, cookieStore));
        //overwrite previously removed value
        assertEquals("true", executeRequest("write", serverPort1, cookieStore));
        assertEquals(1, map.size());
        assertEquals("value", executeRequest("read", serverPort2, cookieStore));
    }

    @Test(timeout = 60000)
    public void testAttributeUpdate() throws Exception {
        IMap<String, Object> map = hz.getMap(DEFAULT_MAP_NAME);
        CookieStore cookieStore = new BasicCookieStore();
        assertEquals("true", executeRequest("write", serverPort1, cookieStore));
        assertEquals(1, map.size());
        assertEquals("value", executeRequest("read", serverPort2, cookieStore));
        assertEquals("true", executeRequest("update", serverPort2, cookieStore));
        assertEquals("value-updated", executeRequest("read", serverPort1, cookieStore));
    }

    @Test(timeout = 60000)
    public void testAttributeInvalidate() throws Exception {
        IMap<String, Object> map = hz.getMap(DEFAULT_MAP_NAME);
        CookieStore cookieStore = new BasicCookieStore();
        assertEquals("true", executeRequest("write", serverPort1, cookieStore));
        assertEquals(1, map.size());
        assertEquals("value", executeRequest("read", serverPort2, cookieStore));
        assertEquals("true", executeRequest("invalidate", serverPort2, cookieStore));
        assertTrue(map.isEmpty());
    }

    @Test(timeout = 60000)
    public void testAttributeReloadSession() throws Exception {
        IMap<String, Object> map = hz.getMap(DEFAULT_MAP_NAME);
        CookieStore cookieStore = new BasicCookieStore();
        assertEquals("true", executeRequest("write", serverPort1, cookieStore));
        assertEquals(1, map.size());
        String oldSessionId = findHazelcastSessionId(map);
        assertNotNull(oldSessionId);
        assertEquals("value", executeRequest("read", serverPort2, cookieStore));
        assertEquals("true", executeRequest("reload", serverPort2, cookieStore));
        String newSessionId = findHazelcastSessionId(map);
        assertEquals(1, map.size());
        assertNotNull(map.get(newSessionId));
        SessionState sessionState = (SessionState) map.get(newSessionId);
        SerializationService ss = getNode(hz).getSerializationService();
        assertEquals("first-value", ss.toObject(sessionState.getAttributes().get("first-key")));
        assertEquals("second-value", ss.toObject(sessionState.getAttributes().get("second-key")));
    }

    @Test
    public void testUpdateAndReadSameRequest() throws Exception {
        CookieStore cookieStore = new BasicCookieStore();
        assertEquals("true", executeRequest("write", serverPort1, cookieStore));
        assertEquals("value-updated", executeRequest("update-and-read-same-request", serverPort2, cookieStore));
    }

    @Test
    public void testUpdateAndReadSameRequestWithRestart() throws Exception {
        CookieStore cookieStore = new BasicCookieStore();
        assertEquals("true", executeRequest("write", serverPort1, cookieStore));
        server1.restart();
        assertEquals("value-updated", executeRequest("update-and-read-same-request", serverPort1, cookieStore));
    }

    @Test
    public void testIssue3132() throws Exception {
        CookieStore cookieStore = new BasicCookieStore();
        assertEquals("true", executeRequest("isNew", serverPort1, cookieStore));
        assertEquals("false", executeRequest("isNew", serverPort1, cookieStore));
        assertEquals("false", executeRequest("isNew", serverPort2, cookieStore));
        server1.restart();
        assertEquals("false", executeRequest("isNew", serverPort1, cookieStore));
        assertEquals("false", executeRequest("isNew", serverPort2, cookieStore));
    }
}


text:
using namespace foundation;
using namespace std;

namespace appleseed {
namespace studio {

//
// ChartBase class implementation.
//

ChartBase::ChartBase()
  : m_equidistant(false)
  , m_margin(15.0, 15.0)
  , m_grid_brush(QBrush(QColor(50, 50, 50, 255)))
{
}

void ChartBase::set_equidistant(const bool equidistant)
{
    m_equidistant = equidistant;
}

void ChartBase::set_grid_brush(const QBrush& brush)
{
    m_grid_brush = brush;
}

void ChartBase::set_tooltip_formatter(auto_ptr<IToolTipFormatter> formatter)
{
    m_tooltip_formatter = formatter;
}

void ChartBase::add_point(const Vector2d& p)
{
    m_original_points.push_back(p);
}

void ChartBase::add_point(const double x, const double y)
{
    m_original_points.push_back(Vector2d(x, y));
}

void ChartBase::prepare_drawing(QPainter& painter)
{
    m_points = m_original_points;

    if (m_equidistant)
    {
        for (size_t i = 0; i < m_points.size(); ++i)
            m_points[i].x = static_cast<double>(i);

    }

    m_points_bbox = compute_points_bbox();
    m_rcp_points_bbox_extent = Vector2d(1.0) / m_points_bbox.extent();

    const QRect window = painter.window();

    m_window_origin = Vector2d(window.x(), window.y());
    m_window_size = Vector2d(window.width(), window.height());
}

void ChartBase::draw_grid(QPainter& painter) const
{
    QPen pen;
    pen.setBrush(m_grid_brush);
    pen.setWidthF(1.0);
    painter.setPen(pen);

    draw_horizontal_grid(painter);
    draw_vertical_grid(painter);
}

void ChartBase::draw_tooltip(QPainter& painter, const QPoint& mouse_position) const
{
    size_t point_index;

    if (!on_chart(mouse_position, point_index))
        return;

    const int ShiftX = 2;
    const int ShiftY = 2;
    const int MarginX = 8;
    const int MarginY = 5;
    const int FrameMargin = 3;
    const qreal CornerRadius = 2.0;
    const int Opacity = 180;
    const QColor TextColor(210, 210, 210, Opacity);
    const QColor BorderColor(40, 40, 40, Opacity);
    const QColor BackgroundColor(80, 80, 80, Opacity);

    if (m_tooltip_formatter.get() == 0)
        return;

    const Vector2d& point = m_original_points[point_index];
    const QString text = m_tooltip_formatter->format(point);
    const QRect text_rect = painter.fontMetrics().boundingRect(QRect(), Qt::AlignCenter, text);

    QRect tooltip_rect(
        mouse_position.x() + ShiftX,
        mouse_position.y() - text_rect.height() - 2 * MarginY - ShiftY,
        text_rect.width() + 2 * MarginX,
        text_rect.height() + 2 * MarginY);

    if (tooltip_rect.left() < FrameMargin)
        tooltip_rect.moveLeft(FrameMargin);

    if (tooltip_rect.top() < FrameMargin)
        tooltip_rect.moveTop(FrameMargin);

    const int MaxRight = painter.window().right() - FrameMargin;
    if (tooltip_rect.right() > MaxRight)
        tooltip_rect.moveRight(MaxRight);

    const int MaxBottom = painter.window().bottom() - FrameMargin;
    if (tooltip_rect.bottom() > MaxBottom)
        tooltip_rect.moveBottom(MaxBottom);

    painter.setPen(BorderColor);
    painter.setBrush(QBrush(BackgroundColor));
    painter.drawRoundedRect(tooltip_rect, CornerRadius, CornerRadius);

    painter.setPen(TextColor);
    painter.drawText(tooltip_rect, Qt::AlignCenter, text);
}

void ChartBase::draw_highlight(QPainter& painter, const QPoint& mouse_position) const
{
}

AABB2d ChartBase::compute_points_bbox() const
{
    AABB2d bbox;
    bbox.invalidate();

    bbox.insert(Vector2d(0.0));

    for (size_t i = 0; i < m_points.size(); ++i)
        bbox.insert(m_points[i]);

    return bbox;
}

Vector2d ChartBase::convert_to_frame(const Vector2d& point) const
{
    const Vector2d window_size = m_window_size - 2.0 * m_margin;
    const Vector2d window_origin = m_window_origin + m_margin;

    Vector2d u = (point - m_points_bbox.min) * m_rcp_points_bbox_extent;

    u.y = 1.0 - u.y;

    return window_origin + u * window_size;
}

Vector2d ChartBase::convert_to_data(const Vector2d& point) const
{
    const Vector2d min = m_window_origin + m_margin;
    const Vector2d max = m_window_origin + m_window_size - m_margin - Vector2d(1.0);

    Vector2d p = point;

    if (p.x < min.x) p.x = min.x;
    if (p.x > max.x) p.x = max.x;
    if (p.y < min.y) p.y = min.y;
    if (p.y > max.y) p.y = max.y;

    Vector2d u = (p - min) / (max - min);

    u.y = 1.0 - u.y;

    return u * m_points_bbox.extent() + m_points_bbox.min;
}

void ChartBase::draw_horizontal_grid(QPainter& painter) const
{
    const size_t Subdivisions = 10;

    for (size_t i = 0; i < Subdivisions; ++i)
    {
        const double k = static_cast<double>(i) / (Subdivisions - 1);
        const double y = mix(m_points_bbox.min.y, m_points_bbox.max.y, k);

        const Vector2d p = convert_to_frame(Vector2d(0.0, y));

        painter.drawLine(
            m_window_origin.x, p.y,
            m_window_origin.x + m_window_size.x, p.y);
    }
}

void ChartBase::draw_vertical_grid(QPainter& painter) const
{
    if (m_points.size() > 2)
    {
        for (size_t i = 0; i < m_points.size(); ++i)
        {
            const Vector2d p = convert_to_frame(m_points[i]);

            painter.drawLine(
                p.x, m_window_origin.y,
                p.x, m_window_origin.y + m_window_size.y);
        }
    }
}

//
// LineChart class implementation.
//

LineChart::LineChart()
  : m_curve_brush(QBrush(QColor(255, 255, 255, 255)))
{
}

void LineChart::set_curve_brush(const QBrush& brush)
{
    m_curve_brush = brush;
}

void LineChart::draw_chart(QPainter& painter) const
{
    if (m_points.size() > 1)
    {
        QPen pen;
        pen.setBrush(m_curve_brush);
        pen.setWidthF(2.0);
        painter.setPen(pen);

        for (size_t i = 0; i < m_points.size() - 1; ++i)
        {
            const Vector2d from = convert_to_frame(m_points[i]);
            const Vector2d to = convert_to_frame(m_points[i + 1]);
            painter.drawLine(from.x, from.y, to.x, to.y);
        }
    }
}

bool LineChart::on_chart(const QPoint& mouse_position, size_t& point_index) const
{
    const double MinDistance = 8.0;

    const Vector2d mp(mouse_position.x(), mouse_position.y());

    double closest_square_distance = numeric_limits<double>::max();
    size_t closest_index = 0;

    for (size_t i = 0; i < m_points.size(); ++i)
    {
        const Vector2d p = convert_to_frame(m_points[i]);
        const double d = square_distance(mp, p);

        if (closest_square_distance > d)
        {
            closest_square_distance = d;
            closest_index = i;
        }
    }

    if (closest_square_distance < MinDistance * MinDistance)
    {
        point_index = closest_index;
        return true;
    }

    return false;
}

void LineChart::draw_highlight(QPainter& painter, const QPoint& mouse_position) const
{
    draw_point_highlight(painter, mouse_position);
    draw_cross(painter, mouse_position);
}

void LineChart::draw_point_highlight(QPainter& painter, const QPoint& mouse_position) const
{
    size_t point_index;

    if (on_chart(mouse_position, point_index))
    {
        const QColor DiskColor(140, 200, 255);
        const qreal DiskRadius = 3.0;

        const Vector2d p = convert_to_frame(m_points[point_index]);

        painter.setPen(DiskColor);
        painter.setBrush(QBrush(DiskColor));
        painter.drawEllipse(QPointF(p.x, p.y), DiskRadius, DiskRadius);
    }
}

void LineChart::draw_cross(QPainter& painter, const QPoint& mouse_position) const
{
    const QColor CrossColor(100, 100, 100);

    QPen pen;
    pen.setStyle(Qt::DotLine);
    pen.setColor(CrossColor);
    pen.setWidthF(0.5);
    painter.setPen(pen);

    painter.drawLine(
        m_window_origin.x, mouse_position.y(),
        m_window_origin.x + m_window_size.x, mouse_position.y());

    painter.drawLine(
        mouse_position.x(), m_window_origin.y,
        mouse_position.x(), m_window_origin.y + m_window_size.y);
}

//
// ChartWidget class implementation.
//

ChartWidget::ChartWidget(QWidget* parent)
  : QFrame(parent)
  , m_mouse_inside_widget(false)
{
    setMouseTracking(true);
}

ChartWidget::~ChartWidget()
{
    clear();
}

void ChartWidget::clear()
{
    for (const_each<ChartCollection> i = m_charts; i; ++i)
        delete *i;

    m_charts.clear();
}

void ChartWidget::add_chart(auto_ptr<ChartBase> chart)
{
    assert(chart.get());

    m_charts.push_back(chart.release());
}

void ChartWidget::mouseMoveEvent(QMouseEvent* event)
{
    m_mouse_inside_widget = true;
    m_mouse_position = event->pos();

    update();
}

void ChartWidget::leaveEvent(QEvent* event)
{
    m_mouse_inside_widget = false;

    update();
}

void ChartWidget::paintEvent(QPaintEvent* event)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing, true);

    draw_charts(painter);

    if (m_mouse_inside_widget)
    {
        draw_highlights(painter);
        draw_tooltips(painter);
    }

    draw_frame(painter);
}

void ChartWidget::draw_charts(QPainter& painter) const
{
    for (const_each<ChartCollection> i = m_charts; i; ++i)
    {
        ChartBase* chart = *i;
        chart->prepare_drawing(painter);
        chart->draw_grid(painter);
    }

    for (const_each<ChartCollection> i = m_charts; i; ++i)
    {
        const ChartBase* chart = *i;
        chart->draw_chart(painter);
    }
}

void ChartWidget::draw_highlights(QPainter& painter) const
{
    for (const_each<ChartCollection> i = m_charts; i; ++i)
    {
        const ChartBase* chart = *i;
        chart->draw_highlight(painter, m_mouse_position);
    }
}

void ChartWidget::draw_tooltips(QPainter& painter) const
{
    for (const_each<ChartCollection> i = m_charts; i; ++i)
    {
        const ChartBase* chart = *i;
        chart->draw_tooltip(painter, m_mouse_position);
    }
}

void ChartWidget::draw_frame(QPainter& painter) const
{
    QStyleOptionFrame option;
    option.initFrom(this);
    style()->drawPrimitive(QStyle::PE_Frame, &option, &painter, this);
}

}   // namespace studio
}   // namespace appleseed


text:
<?php

namespace PB\Bundle\SuluStorageBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

/**
 * @author Paweł Brzeziński <pawel.brzezinski@smartint.pl>
 */
class PBSuluStorageExtension extends Extension
{
    const BUNDLE_CONFIG_PARAM = 'pb_sulu_storage.config';

    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $container->setParameter(self::BUNDLE_CONFIG_PARAM, $config);

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yaml');
    }
}


text:
require 'cocoa/bindings/NSTableView'
module Cocoa
  class NSOutlineView < Cocoa::NSTableView
    attach_method :autoresizesOutlineColumn, :args=>0, :names=>[], :types=>[], :retval=>"B"
    attach_method :autosaveExpandedItems, :args=>0, :names=>[], :types=>[], :retval=>"B"
    attach_method :collapseItem, [{:args=>1, :names=>[], :types=>["@"], :retval=>"v"}, {:args=>2, :names=>[:collapseChildren], :types=>["@", "B"], :retval=>"v"}]
    attach_method :dataSource, :args=>0, :names=>[], :types=>[], :retval=>"@"
    attach_method :delegate, :args=>0, :names=>[], :types=>[], :retval=>"@"
    attach_method :expandItem, [{:args=>1, :names=>[], :types=>["@"], :retval=>"v"}, {:args=>2, :names=>[:expandChildren], :types=>["@", "B"], :retval=>"v"}]
    attach_method :frameOfOutlineCellAtRow, :args=>1, :names=>[], :types=>["q"], :retval=>"{CGRect={CGPoint=dd}{CGSize=dd}}"
    attach_method :indentationMarkerFollowsCell, :args=>0, :names=>[], :types=>[], :retval=>"B"
    attach_method :indentationPerLevel, :args=>0, :names=>[], :types=>[], :retval=>"d"
    attach_method :insertItemsAtIndexes, :args=>3, :names=>[:inParent, :withAnimation], :types=>["@", "@", "Q"], :retval=>"v"
    attach_method :isExpandable, :args=>1, :names=>[], :types=>["@"], :retval=>"B"
    attach_method :isItemExpanded, :args=>1, :names=>[], :types=>["@"], :retval=>"B"
    attach_method :itemAtRow, :args=>1, :names=>[], :types=>["q"], :retval=>"@"
    attach_method :levelForItem, :args=>1, :names=>[], :types=>["@"], :retval=>"q"
    attach_method :levelForRow, :args=>1, :names=>[], :types=>["q"], :retval=>"q"
    attach_method :moveItemAtIndex, :args=>4, :names=>[:inParent, :toIndex, :inParent], :types=>["q", "@", "q", "@"], :retval=>"v"
    attach_method :outlineTableColumn, :args=>0, :names=>[], :types=>[], :retval=>"@"
    attach_method :parentForItem, :args=>1, :names=>[], :types=>["@"], :retval=>"@"
    attach_method :reloadItem, [{:args=>1, :names=>[], :types=>["@"], :retval=>"v"}, {:args=>2, :names=>[:reloadChildren], :types=>["@", "B"], :retval=>"v"}]
    attach_method :removeItemsAtIndexes, :args=>3, :names=>[:inParent, :withAnimation], :types=>["@", "@", "Q"], :retval=>"v"
    attach_method :rowForItem, :args=>1, :names=>[], :types=>["@"], :retval=>"q"
    attach_method :setAutoresizesOutlineColumn, :args=>1, :names=>[], :types=>["B"], :retval=>"v"
    attach_method :setAutosaveExpandedItems, :args=>1, :names=>[], :types=>["B"], :retval=>"v"
    attach_method :setDataSource, :args=>1, :names=>[], :types=>["@"], :retval=>"v"
    attach_method :setDelegate, :args=>1, :names=>[], :types=>["@"], :retval=>"v"
    attach_method :setDropItem, :args=>2, :names=>[:dropChildIndex], :types=>["@", "q"], :retval=>"v"
    attach_method :setIndentationMarkerFollowsCell, :args=>1, :names=>[], :types=>["B"], :retval=>"v"
    attach_method :setIndentationPerLevel, :args=>1, :names=>[], :types=>["d"], :retval=>"v"
    attach_method :setOutlineTableColumn, :args=>1, :names=>[], :types=>["@"], :retval=>"v"
    attach_method :shouldCollapseAutoExpandedItemsForDeposited, :args=>1, :names=>[], :types=>["B"], :retval=>"B"
  end
end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>slickgrid-colfix-plugin example</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="../bower_components/slickgrid/slick.grid.css" type="text/css" />
    <link rel="stylesheet" href="../bower_components/slickgrid/css/smoothness/jquery-ui-1.8.16.custom.css" type="text/css" />
    <link rel="stylesheet" href="../bower_components/bootstrap/dist/css/bootstrap.min.css" type="text/css" media="screen" />
    <link rel="stylesheet" href="../bower_components/slickgrid/examples/examples.css" type="text/css" />

      you can manipulate data with right-click context menu.

Edit

Insert row above

Insert row below

Remove row


text:
#include "fsl_mpu.h"

/*******************************************************************************
 * Variables
 ******************************************************************************/

#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
const clock_ip_name_t g_mpuClock[FSL_FEATURE_SOC_MPU_COUNT] = MPU_CLOCKS;
#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */

/*******************************************************************************
 * Codes
 ******************************************************************************/

void MPU_Init(MPU_Type *base, const mpu_config_t *config)
{
    assert(config);
    uint8_t count;

#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
    /* Un-gate MPU clock */
    CLOCK_EnableClock(g_mpuClock[0]);
#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */

    /* Initializes the regions. */
    for (count = 1; count < FSL_FEATURE_MPU_DESCRIPTOR_COUNT; count++)
    {
        base->WORD[count][3] = 0; /* VLD/VID+PID. */
        base->WORD[count][0] = 0; /* Start address. */
        base->WORD[count][1] = 0; /* End address. */
        base->WORD[count][2] = 0; /* Access rights. */
        base->RGDAAC[count] = 0;  /* Alternate access rights. */
    }

    /* MPU configure. */
    while (config)
    {
        MPU_SetRegionConfig(base, &(config->regionConfig));
        config = config->next;
    }
    /* Enable MPU. */
    MPU_Enable(base, true);
}

void MPU_Deinit(MPU_Type *base)
{
    /* Disable MPU. */
    MPU_Enable(base, false);

#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
    /* Gate the clock. */
    CLOCK_DisableClock(g_mpuClock[0]);
#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */
}

void MPU_GetHardwareInfo(MPU_Type *base, mpu_hardware_info_t *hardwareInform)
{
    assert(hardwareInform);

    uint32_t cesReg = base->CESR;

    hardwareInform->hardwareRevisionLevel = (cesReg & MPU_CESR_HRL_MASK) >> MPU_CESR_HRL_SHIFT;
    hardwareInform->slavePortsNumbers = (cesReg & MPU_CESR_NSP_MASK) >> MPU_CESR_NSP_SHIFT;
    hardwareInform->regionsNumbers = (mpu_region_total_num_t)((cesReg & MPU_CESR_NRGD_MASK) >> MPU_CESR_NRGD_SHIFT);
}

void MPU_SetRegionConfig(MPU_Type *base, const mpu_region_config_t *regionConfig)
{
    assert(regionConfig);
    assert(regionConfig->regionNum < FSL_FEATURE_MPU_DESCRIPTOR_COUNT);

    uint32_t wordReg = 0;
    uint8_t msPortNum;
    uint8_t regNumber = regionConfig->regionNum;

    /* The start and end address of the region descriptor. */
    base->WORD[regNumber][0] = regionConfig->startAddress;
    base->WORD[regNumber][1] = regionConfig->endAddress;

    /* Set the privilege rights for master 0 ~ master 3. */
    for (msPortNum = 0; msPortNum <= MPU_PRIVILEGED_RIGHTS_MASTER_MAX_INDEX; msPortNum++)
    {
        wordReg |= MPU_REGION_RWXRIGHTS_MASTER(
            msPortNum, (((uint32_t)regionConfig->accessRights1[msPortNum].superAccessRights << 3U) |
                        (uint32_t)regionConfig->accessRights1[msPortNum].userAccessRights));

#if FSL_FEATURE_MPU_HAS_PROCESS_IDENTIFIER
        wordReg |=
            MPU_REGION_RWXRIGHTS_MASTER_PE(msPortNum, regionConfig->accessRights1[msPortNum].processIdentifierEnable);
#endif /* FSL_FEATURE_MPU_HAS_PROCESS_IDENTIFIER */
    }

    /* Set the normal read write rights for master 4 ~ master 7. */
    for (msPortNum = FSL_FEATURE_MPU_PRIVILEGED_RIGHTS_MASTER_COUNT; msPortNum < FSL_FEATURE_MPU_MASTER_COUNT;
         msPortNum++)
    {
        wordReg |= MPU_REGION_RWRIGHTS_MASTER(msPortNum,
            ((uint32_t)regionConfig->accessRights2[msPortNum - FSL_FEATURE_MPU_PRIVILEGED_RIGHTS_MASTER_COUNT].readEnable << 1U |
            (uint32_t)regionConfig->accessRights2[msPortNum - FSL_FEATURE_MPU_PRIVILEGED_RIGHTS_MASTER_COUNT].writeEnable));
    }

    /* Set region descriptor access rights. */
    base->WORD[regNumber][2] = wordReg;

    wordReg = MPU_WORD_VLD(1);
#if FSL_FEATURE_MPU_HAS_PROCESS_IDENTIFIER
    wordReg |= MPU_WORD_PID(regionConfig->processIdentifier) | MPU_WORD_PIDMASK(regionConfig->processIdMask);
#endif /* FSL_FEATURE_MPU_HAS_PROCESS_IDENTIFIER */

    base->WORD[regNumber][3] = wordReg;
}

void MPU_SetRegionAddr(MPU_Type *base, uint32_t regionNum, uint32_t startAddr, uint32_t endAddr)
{
    assert(regionNum < FSL_FEATURE_MPU_DESCRIPTOR_COUNT);

    base->WORD[regionNum][0] = startAddr;
    base->WORD[regionNum][1] = endAddr;
}

void MPU_SetRegionRwxMasterAccessRights(MPU_Type *base,
                                        uint32_t regionNum,
                                        uint32_t masterNum,
                                        const mpu_rwxrights_master_access_control_t *accessRights)
{
    assert(accessRights);
    assert(regionNum < FSL_FEATURE_MPU_DESCRIPTOR_COUNT);
    assert(masterNum <= MPU_PRIVILEGED_RIGHTS_MASTER_MAX_INDEX);

    uint32_t mask = MPU_REGION_RWXRIGHTS_MASTER_MASK(masterNum);
    uint32_t right = base->RGDAAC[regionNum];

#if FSL_FEATURE_MPU_HAS_PROCESS_IDENTIFIER
    mask |= MPU_REGION_RWXRIGHTS_MASTER_PE_MASK(masterNum);
#endif

    /* Build rights control value. */
    right &= ~mask;
    right |= MPU_REGION_RWXRIGHTS_MASTER(
        masterNum, ((uint32_t)(accessRights->superAccessRights << 3U) | accessRights->userAccessRights));
#if FSL_FEATURE_MPU_HAS_PROCESS_IDENTIFIER
    right |= MPU_REGION_RWXRIGHTS_MASTER_PE(masterNum, accessRights->processIdentifierEnable);
#endif /* FSL_FEATURE_MPU_HAS_PROCESS_IDENTIFIER */

    /* Set low master region access rights. */
    base->RGDAAC[regionNum] = right;
}

#if FSL_FEATURE_MPU_HAS_MASTER_4_7
void MPU_SetRegionRwMasterAccessRights(MPU_Type *base,
                                       uint32_t regionNum,
                                       uint32_t masterNum,
                                       const mpu_rwrights_master_access_control_t *accessRights)
{
    assert(accessRights);
    assert(regionNum < FSL_FEATURE_MPU_DESCRIPTOR_COUNT);
    assert(masterNum > MPU_PRIVILEGED_RIGHTS_MASTER_MAX_INDEX);
    assert(masterNum <= FSL_FEATURE_MPU_MASTER_MAX_INDEX);

    uint32_t mask = MPU_REGION_RWRIGHTS_MASTER_MASK(masterNum);
    uint32_t right = base->RGDAAC[regionNum];

    /* Build rights control value. */
    right &= ~mask;
    right |=
        MPU_REGION_RWRIGHTS_MASTER(masterNum, (((uint32_t)accessRights->readEnable << 1U) | accessRights->writeEnable));
    /* Set low master region access rights. */
    base->RGDAAC[regionNum] = right;
}
#endif /* FSL_FEATURE_MPU_HAS_MASTER_4_7 */

bool MPU_GetSlavePortErrorStatus(MPU_Type *base, mpu_slave_t slaveNum)
{
    uint8_t sperr;

    sperr = ((base->CESR & MPU_CESR_SPERR_MASK) >> MPU_CESR_SPERR_SHIFT) & (0x1U << (MPU_SLAVE_PORT_NUM - slaveNum));

    return (sperr != 0) ? true : false;
}

void MPU_GetDetailErrorAccessInfo(MPU_Type *base, mpu_slave_t slaveNum, mpu_access_err_info_t *errInform)
{
    assert(errInform);

    uint16_t value;
    uint32_t cesReg;

    /* Error address. */
    errInform->address = base->SP[slaveNum].EAR;

    /* Error detail information. */
    value = (base->SP[slaveNum].EDR & MPU_EDR_EACD_MASK) >> MPU_EDR_EACD_SHIFT;
    if (!value)
    {
        errInform->accessControl = kMPU_NoRegionHit;
    }
    else if (!(value & (uint16_t)(value - 1)))
    {
        errInform->accessControl = kMPU_NoneOverlappRegion;
    }
    else
    {
        errInform->accessControl = kMPU_OverlappRegion;
    }

    value = base->SP[slaveNum].EDR;
    errInform->master = (uint32_t)((value & MPU_EDR_EMN_MASK) >> MPU_EDR_EMN_SHIFT);
    errInform->attributes = (mpu_err_attributes_t)((value & MPU_EDR_EATTR_MASK) >> MPU_EDR_EATTR_SHIFT);
    errInform->accessType = (mpu_err_access_type_t)((value & MPU_EDR_ERW_MASK) >> MPU_EDR_ERW_SHIFT);
#if FSL_FEATURE_MPU_HAS_PROCESS_IDENTIFIER
    errInform->processorIdentification = (uint8_t)((value & MPU_EDR_EPID_MASK) >> MPU_EDR_EPID_SHIFT);
#endif

    /* Clears error slave port bit. */
    cesReg = (base->CESR & ~MPU_CESR_SPERR_MASK) | ((0x1U << slaveNum) << MPU_CESR_SPERR_SHIFT);
    base->CESR = cesReg;
}


text:
This section deals with developing and testing the billing system.

## Common setup

- Create a Stripe account
  - Make sure that the country of your Stripe account is set to USA when
    you create the account.
  - You might need to use a VPN for this.
- Ensure that the [API version](https://stripe.com/docs/api/versioning) of
  your Stripe account is same as `STRIPE_API_VERSION` defined in
  `corporate/lib/stripe.py`. You can upgrade to a higher version from
  the Stripe dashboard.
- Set the private API key.
  - Go to <https://dashboard.stripe.com/account/apikeys>
  - Add `stripe_secret_key` to `zproject/dev-secrets.conf`.

## Manual testing

Manual testing involves testing the various flows like upgrade, card change,
etc. through the browser. This is the bare minimum testing that you need to
do when you review a billing PR or when you are working on adding a new
feature to billing.

### Setup

Apart from the common setup mentioned above, you also need to set up your
development environment to receive webhook events from Stripe.

- Install the Stripe CLI locally by following the instructions
  [here](https://stripe.com/docs/webhooks/test).
- Log in to Stripe CLI using the command `stripe login`.
- You can get Stripe CLI to forward all Stripe webhook events to our local
  webhook endpoint using the following command:
  `stripe listen --forward-to http://localhost:9991/stripe/webhook/`
- Wait for the `stripe listen` command in the previous step to output the
  webhook signing secret.
  - The signing secret would be used by our billing system to verify that
    the events received by our webhook endpoint are sent by Stripe and not
    by an intruder. In production, there is no Stripe CLI, so the step for
    configuring this is a bit different. See Stripe's documentation on
    [taking webhooks live](https://stripe.com/docs/webhooks/go-live) for
    more details.
- Copy the webhook signing secret and set it as `stripe_webhook_endpoint_secret`
  in `zproject/dev-secrets.conf`.
- Your development environment is now all set to receive webhook events from
  Stripe.

### Test card numbers

Stripe provides various card numbers to test for specific responses from Stripe.
The most commonly used ones are mentioned in below wherever appropriate. The full
list is available [here](https://stripe.com/docs/testing#cards).

### Flows to test

There are various flows that you can test manually from the browser. Here are
a few things to keep in mind while conducting these tests manually:

- The flows work from start to end as expected.
- We show appropriate success and error messages to users.
- Charges are made or not made (free trial) as expected. You can verify this
  through the Stripe dashboard. However, this is not super important since
  our automated tests take care of such granular testing for us.
- Renewals cannot be tested manually and are tested in our automated tests.

#### Upgrading a Zulip organization

Here are some flows to test when upgrading a Zulip organization:

- When free trials are not enabled, i.e. `FREE_TRIAL_DAYS` is not set
  to any value in `dev_settings.py` (aka the default). You can
  double-check that the setting is disabled by verifying
  `./scripts/get-django-setting FREE_TRIAL_DAYS` returns 0.

  - Using a valid card number like `4242 4242 4242 4242`.
  - Using an invalid card number like `4000000000000341`, which will add the card
    to the customer account but the charge will fail.
    - Retry the upgrade after adding a new card by clicking on the retry upgrade
      link.
    - Retry the upgrade from scratch.

- Upgrade an organization when free trials are enabled. The free
  trials setting has been (possibly permanently) disabled in
  production for some time now, so testing this code path is not a
  priority. You can set `FREE_TRIAL_DAYS` to any number greater than
  `0` in `dev_settings.py` to enable free trials. There are two
  different flows to test here:
  - Right after the organization is created by following the instructions in the
    onboarding page.
    - Make sure that after the upgrade is complete the billing page shows a link to
      go to the organization.
  - By manually going to the `/billing` page and upgrading the organization.

#### Changing the card

The following flow should be tested when updating cards in our billing system:

- Go to the `/billing` page of an organization that has already been upgraded
  using a card. Try changing the card to another valid card such as
  `5555555555554444`.
  - Make sure that the flow completes without any errors and that the new card
    details are now shown on the billing page instead of the older card.
- You can also try adding a card number that results in it getting attached to
  the customer's account but charges fail. However, to test this, you need pending
  invoices since we try to charge for pending invoices when the card is updated.
  This is tested in our automated tests so it is not strictly necessary to test this
  manually.

## Upgrading Stripe API versions

Stripe makes pretty regular updates to their API. The process for upgrading
our code is:

- Go to the [Stripe Dashboard](https://dashboard.stripe.com/developers) in
  your Stripe account.
- Upgrade the API version.
- Run `tools/test-backend --generate-stripe-fixtures`.
- Fix any failing tests, and manually look through `git diff` to understand
  the changes. Ensure that there are no material changes.
- Update the value of `STRIPE_API_VERSION` in `corporate/lib/stripe.py`.
- Commit the changes, and open a PR.
- Ask Tim Abbott to upgrade the API version on the
  [Stripe Dashboard](https://dashboard.stripe.com/developers) for Zulip's official
  Stripe account.

We currently aren't set up to do version upgrades where there are breaking
changes, though breaking changes should be unlikely given the parts of the
product we use. The main remaining work for handling breaking version upgrades
is ensuring that we set the stripe version in our API calls.
Stripe's documentation for
[Upgrading your API version](https://stripe.com/docs/upgrades#how-can-i-upgrade-my-api)
has some additional information.


text:
var SteamCommunity = require('steamcommunity');

module.exports = TradeOfferManager;

TradeOfferManager.SteamID = require('steamid');
TradeOfferManager.ETradeOfferState = require('../resources/ETradeOfferState.js');
TradeOfferManager.EOfferFilter = require('../resources/EOfferFilter.js');
TradeOfferManager.EResult = require('../resources/EResult.js');

TradeOfferManager.getStateName = function(state) {
	for(var i in TradeOfferManager.ETradeOfferState) {
		if(TradeOfferManager.ETradeOfferState[i] == state) {
			return i;
		}
	}

	return state;
};

require('util').inherits(TradeOfferManager, require('events').EventEmitter);

function TradeOfferManager(options) {
	options = options || {};

	this._steam = options.steam;
	this._domain = options.domain || 'localhost';
	this._language = options.language;

	this._community = new SteamCommunity();
	this._request = this._community.request;
	this._assetCache = {};
	this._pollTimer = null;
	this._lastPoll = 0;

	this.pollInterval = options.pollInterval || 30000;
	this.cancelTime = options.cancelTime;

	this.pollData = {};
	this.apiKey = null;
	this.steamID = null;

	if(this._language) {
		var lang = require('languages').getLanguageInfo(this._language);
		if(!lang.name) {
			this._language = null;
			this._languageName = null;
		} else {
			this._languageName = lang.name.toLowerCase();
		}
	}

	if(this._steam) {
		this._steam.on('tradeOffers', function(count) {
			this.doPoll();
		}.bind(this));

		// This is an instance of https://www.npmjs.com/package/steam-user, and newItems is emitted when new items are announced
		this._steam.on('newItems', function(count) {
			this.doPoll();
		}.bind(this));
	}
}

TradeOfferManager.prototype.setCookies = function(cookies, callback) {
	if(this._languageName) {
		cookies = cookies.concat(['Steam_Language=' + this._languageName]);
	}

	this._community.setCookies(cookies);
	this.steamID = this._community.steamID;
	this._checkApiKey(function(err) {
		if(!err) {
			if(!this._pollTimer && this.pollInterval >= 1000) {
				this.doPoll();
			}
		}

		callback(err);
	}.bind(this));
};

TradeOfferManager.prototype.shutdown = function() {
	clearTimeout(this._pollTimer);
	this._community = new SteamCommunity();
	this._request = this._community.request;
	this._steam = null;
};

TradeOfferManager.prototype.parentalUnlock = function(pin, callback) {
	this._community.parentalUnlock(pin, function(err) {
		if(err && callback) {
			callback(err);
		}
	});
};

TradeOfferManager.prototype._checkApiKey = function(callback) {
	if(this.apiKey) {
		if(callback) {
			callback();
		}

		return;
	}

	this._community.getWebApiKey(this._domain, function(err, key) {
		if(err) {
			callback(err);
			return;
		}

		this.apiKey = key;
		callback();
	}.bind(this));
};

TradeOfferManager.prototype.loadInventory = function(appid, contextid, tradableOnly, callback) {
	this._community.getUserInventory(this._community.steamID, appid, contextid, tradableOnly, callback);
};

TradeOfferManager.prototype.getOfferToken = function(callback) {
	this._request("https://steamcommunity.com/my/tradeoffers/privacy", function(err, response, body) {
		if(err || response.statusCode != 200) {
			callback(err || new Error("HTTP error " + response.statusCode));
			return;
		}

		var match = body.match(/https?:\/\/(www.)?steamcommunity.com\/tradeoffer\/new\/?\?partner=\d+(&|&)token=([a-zA-Z0-9-_]+)/);
		if(match) {
			callback(null, match[3]);
		} else {
			callback(new Error("Malformed response"));
		}
	});
};

function makeAnError(error, callback) {
	if(callback) {
		callback(error);
	}
}

require('./webapi.js');
require('./assets.js');
require('./polling.js');
require('./classes/TradeOffer.js');


text:
namespace Patterns.Playground.AbstractFactory.Ingredients
{
    internal interface IIngredientProvider
    {
        IPizzaFoundation GetPizzaFoundation();
        IIngredient GetTomatoTopping();
        IIngredient GetOreganoTopping();
    }
}


text:
/**
 * @fileoverview A Gears implementation of dbwrapperapi ResultSet.
 */

/**
 * Creates a Gears ResultSet object.
 * @see google.wspl.ResultSet#ResultSet
 *
 * @constructor
 * @extends google.wspl.ResultSet
 * @param {!Array.<Object>} resultArray An array of hash objects where the
 *     column names in the query are used as members of the objects.
 */
google.wspl.gears.ResultSet = function(resultArray) {
  google.wspl.ResultSet.call(this);

  /**
   * The result set as an array of hash objects.
   * @type {!Array.<Object>}
   * @private
   */
  this.resultArray_ = resultArray;
};
google.inherits(google.wspl.gears.ResultSet, google.wspl.ResultSet);

/**
 * The current record in the result set.
 * @type {number}
 * @private
 */
google.wspl.gears.ResultSet.prototype.current_ = 0;

/**
 * @see google.wspl.ResultSet#isValidRow
 * @inheritDoc
 */
google.wspl.gears.ResultSet.prototype.isValidRow = function() {
  return this.current_ < this.resultArray_.length;
};

/**
 * @see google.wspl.ResultSet#next
 * @inheritDoc
 */
google.wspl.gears.ResultSet.prototype.next = function() {
  this.current_++;
};

/**
 * @see google.wspl.ResultSet#getRow
 * @inheritDoc
 */
google.wspl.gears.ResultSet.prototype.getRow = function() {
  return this.resultArray_[this.current_];
};


text:
"""A simple parser for power tool output"""

from __future__ import print_function
from collections import namedtuple
import argparse
import re
import sys

PowerOutput = namedtuple('PowerOutput', ['filename', 'frequency', 'realtime',
                                         'systime', 'usrtime', 'pkg_energy',
                                         'pp0_energy', 'pkg_power'])

def process_arguments():
    """Returns a dictionary of command line arguments values."""
    parser = argparse.ArgumentParser(description='Power Output Formatter')
    parser.add_argument('-if', '--infiles', required=True, nargs='+',
                        type=argparse.FileType('r'),
                        help='Output files to consider')
    return parser.parse_args()

def parse_file(infile):
    """Parses a single entry of the form:
    program output
    ...
    Real Time:  1m  00s 628us
    Sys Time: 0s 0us
    User Time:  0s 0us
    PKG Energy: 43.785278J
    PP0 Energy: 0.000000J
    PKG Power:  0.729747W
    """
    frequency_re = re.compile(r"(\d+\.\d+|\d+)\s?(GHz|MHz)")
    frequency_match = re.search(frequency_re, infile.name)
    if frequency_match is None:
        sys.exit("ERROR! Filename {} lacks CPU frequency".format(infile.name))
    if frequency_match.group(2) == 'GHz':
        frequency_unit = 1e9
    elif frequency_match.group(2) == 'MHz':
        frequency_unit = 1e6
    else:
        sys.exit('Unknown frequency unit: {}'.format(frequency_unit))
    frequency_hz = float(frequency_match.group(1)) * frequency_unit
    realtime_re = re.compile(r"^Real Time:\s*(\d+)m\s*(\d+)s\s*(\d+)us$")
    systime_re = re.compile(r"^Sys Time:\s*(\d+)s\s*(\d+)us$")
    usrtime_re = re.compile(r"^User Time:\s*(\d+)s\s*(\d+)us$")
    pkg_energy_re = re.compile(r"^PKG Energy:\s*(\d+\.?\d+?)J$")
    pp0_energy_re = re.compile(r"^PP0 Energy:\s*(\d+\.?\d+?)J$")
    pkg_power_re = re.compile(r"^PKG Power:\s*(\d+\.?\d+?)W$")

    realtime = None
    systime = None
    usrtime = None
    pkg_energy = None
    pp0_energy = None
    pkg_power = None
    for line in infile:
        match = re.match(realtime_re, line)
        if match is not None:
            print(match.group(0))
            if realtime is not None:
                sys.exit("Duplicate Real Time value in {}".format(infile.name))
            realtime = int(match.group(1)) * 60 \
                     + int(match.group(2))      \
                     + int(match.group(3)) * 1e-6  # Mins, Secs, Microsecs
        match = re.match(systime_re, line)
        if match is not None:
            print(match.group(0))
            if systime is not None:
                sys.exit("Duplicate Sys Time value in {}".format(infile.name))
            systime = int(match.group(1)) + int(match.group(2)) * 1e-6
        match = re.match(usrtime_re, line)
        if match is not None:
            print(match.group(0))
            if usrtime is not None:
                sys.exit("Duplicate User Time value in {}".format(infile.name))
            usrtime = int(match.group(1)) + int(match.group(2)) * 1e-6
        match = re.match(pkg_energy_re, line)
        if match is not None:
            print(match.group(0))
            if pkg_energy is not None:
                sys.exit("Duplicate PKG Energy in {}".format(infile.name))
            pkg_energy = float(match.group(1))
        match = re.match(pp0_energy_re, line)
        if match is not None:
            print(match.group(0))
            if pp0_energy is not None:
                sys.exit("Duplicate PP0 Energy in {}".format(infile.name))
            pp0_energy = float(match.group(1))
        match = re.match(pkg_power_re, line)
        if match is not None:
            print(match.group(0))
            if pkg_power is not None:
                sys.exit("Duplicate PKG Power in {}".format(infile.name))
            pkg_power = float(match.group(1))
    return PowerOutput(filename=infile.name,
                       frequency=frequency_hz,
                       realtime=realtime,
                       systime=systime,
                       usrtime=usrtime,
                       pkg_energy=pkg_energy,
                       pp0_energy=pp0_energy,
                       pkg_power=pkg_power)

def main():
    """Program Entry Point"""
    args = process_arguments()
    data = []
    for infile in args.infiles:
        data.append(parse_file(infile))
        infile.close()
    print(data)

if __name__ == '__main__':
    main()


text:
<?php

namespace Symfony\Bundle\FrameworkBundle\CacheWarmer;

use Psr\Cache\CacheItemPoolInterface;
use Symfony\Component\Cache\Adapter\AdapterInterface;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\Cache\Adapter\PhpArrayAdapter;
use Symfony\Component\Cache\Adapter\ProxyAdapter;
use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface;
use Symfony\Component\Validator\Mapping\Cache\Psr6Cache;
use Symfony\Component\Validator\Mapping\Factory\LazyLoadingMetadataFactory;
use Symfony\Component\Validator\Mapping\Loader\LoaderChain;
use Symfony\Component\Validator\Mapping\Loader\LoaderInterface;
use Symfony\Component\Validator\Mapping\Loader\XmlFileLoader;
use Symfony\Component\Validator\Mapping\Loader\YamlFileLoader;
use Symfony\Component\Validator\ValidatorBuilderInterface;

/**
 * Warms up XML and YAML validator metadata.
 *
 * @author Titouan Galopin <galopintitouan@gmail.com>
 */
class ValidatorCacheWarmer implements CacheWarmerInterface
{
    private $validatorBuilder;
    private $phpArrayFile;
    private $fallbackPool;

    /**
     * @param ValidatorBuilderInterface $validatorBuilder
     * @param string                    $phpArrayFile     The PHP file where metadata are cached.
     * @param CacheItemPoolInterface    $fallbackPool     The pool where runtime-discovered metadata are cached.
     */
    public function __construct(ValidatorBuilderInterface $validatorBuilder, $phpArrayFile, CacheItemPoolInterface $fallbackPool)
    {
        $this->validatorBuilder = $validatorBuilder;
        $this->phpArrayFile = $phpArrayFile;
        if (!$fallbackPool instanceof AdapterInterface) {
            $fallbackPool = new ProxyAdapter($fallbackPool);
        }
        $this->fallbackPool = $fallbackPool;
    }

    /**
     * {@inheritdoc}
     */
    public function warmUp($cacheDir)
    {
        if (!method_exists($this->validatorBuilder, 'getLoaders')) {
            return;
        }

        $adapter = new PhpArrayAdapter($this->phpArrayFile, $this->fallbackPool);
        $arrayPool = new ArrayAdapter(0, false);

        $loaders = $this->validatorBuilder->getLoaders();
        $metadataFactory = new LazyLoadingMetadataFactory(new LoaderChain($loaders), new Psr6Cache($arrayPool));

        foreach ($this->extractSupportedLoaders($loaders) as $loader) {
            foreach ($loader->getMappedClasses() as $mappedClass) {
                $metadataFactory->getMetadataFor($mappedClass);
            }
        }

        $values = $arrayPool->getValues();
        $adapter->warmUp($values);

        foreach ($values as $k => $v) {
            $item = $this->fallbackPool->getItem($k);
            $this->fallbackPool->saveDeferred($item->set($v));
        }
        $this->fallbackPool->commit();
    }

    /**
     * {@inheritdoc}
     */
    public function isOptional()
    {
        return true;
    }

    /**
     * @param LoaderInterface[] $loaders
     *
     * @return XmlFileLoader[]|YamlFileLoader[]
     */
    private function extractSupportedLoaders(array $loaders)
    {
        $supportedLoaders = array();

        foreach ($loaders as $loader) {
            if ($loader instanceof XmlFileLoader || $loader instanceof YamlFileLoader) {
                $supportedLoaders[] = $loader;
            } elseif ($loader instanceof LoaderChain) {
                $supportedLoaders = array_merge($supportedLoaders, $this->extractSupportedLoaders($loader->getDelegatedLoaders()));
            }
        }

        return $supportedLoaders;
    }
}