text:
package graphs;
import java.util.*;

public class GraphMethods {

	public static <TYPE> boolean pathExist(TYPE from, TYPE to, Graph<TYPE> graph){
		Set<TYPE> visited = new HashSet<TYPE>();
		dfs(from, visited, graph);
		return visited.contains(to);
	}
	private static <TYPE> void dfs(TYPE where, Set<TYPE> visited,  Graph<TYPE> graph){
		visited.add(where);
		for (Edge<TYPE> e : graph.getEdgesFrom(where))
			if (!visited.contains(e.getDestination()))
				dfs(e.getDestination(), visited,graph);
	}
	public static <TYPE> List<Edge<TYPE>> getPath(TYPE from, TYPE to,Graph<TYPE> graph) {
		if (!pathExist(to, from,graph))
			return null;
		Set<TYPE> visited = new HashSet<TYPE>();
		List<Edge<TYPE>> bestpath = new ArrayList<>();
		dfs(to, visited,graph);
		TYPE whereAmI = to;

		Map<TYPE, Integer> weight = new HashMap<TYPE, Integer>();
		Map<TYPE, Boolean> isBest = new HashMap<TYPE, Boolean>();
		Map<TYPE, TYPE> whereFrom = new HashMap<TYPE, TYPE>();
		for (TYPE t : visited) {
			weight.put(t, Integer.MAX_VALUE);
			isBest.put(t, false);
			whereFrom.put(t, null);
		}
		weight.put(to, 0);
		isBest.put(to, true);

		do {
			List<Edge<TYPE>> neighbour = graph.getEdgesFrom(whereAmI);
			for(Edge<TYPE> e : neighbour)
				if (e.getWeight() + weight.get(whereAmI) < weight.get(e.getDestination())){
					weight.put(e.getDestination(),e.getWeight() + weight.get(whereAmI));
					whereFrom.put(e.getDestination(), whereAmI);
				}
			int cheapest = Integer.MAX_VALUE;
			for(TYPE t : weight.keySet())
				if (weight.get(t) < cheapest && !isBest.get(t)){
					whereAmI = t;
					cheapest = weight.get(t);
				}
			isBest.put(whereAmI, true);
		}while (!isBest.get(from));

		whereAmI = from;

		while (whereAmI != to) {
			for (Edge<TYPE> e : graph.getEdgesFrom(whereAmI))
				if (e.getDestination().equals(whereFrom.get(whereAmI))) {
					bestpath.add(e);
					break;
				}
			whereAmI = whereFrom.get(whereAmI);
		}
		return bestpath;
	}
}


text:
import argparse
import os
from collections import OrderedDict
import sys
import time
import subprocess
from typing import List

from aws_requests_auth.boto_utils import BotoAWSRequestsAuth
import requests

def retry(f):
    def inner():
        resp = None
        for _ in range(5):
            resp = f()
            print("Getting Presigned URL, status_code", resp.status_code)
            if resp.status_code >= 500:
                print("errored, retrying...")
                print(resp.text)
                time.sleep(5)
            else:
                return resp
        if resp is None or resp.status_code >= 500:
            print("still errorred after many retries")
            sys.exit(1)

    return inner

@retry
def perform_auth():
    auth = BotoAWSRequestsAuth(
        aws_host="vop4ss7n22.execute-api.us-west-2.amazonaws.com",
        aws_region="us-west-2",
        aws_service="execute-api",
    )
    resp = requests.get(
        "https://vop4ss7n22.execute-api.us-west-2.amazonaws.com/endpoint/",
        auth=auth,
        params={"job_id": os.environ["BUILDKITE_JOB_ID"]})
    return resp

def handle_docker_login(resp):
    pwd = resp.json()["docker_password"]
    subprocess.call(
        ["docker", "login", "--username", "raytravisbot", "--password", pwd])

def gather_paths(dir_path) -> List[str]:
    assert os.path.exists(dir_path)
    if os.path.isdir(dir_path):
        paths = [os.path.join(dir_path, f) for f in os.listdir(dir_path)]
    else:
        paths = [dir_path]
    return paths

dest_resp_mapping = {
    "wheels": "presigned_resp_prod_wheels",
    "branch_wheels": "presigned_resp_prod_wheels",
    "jars": "presigned_resp_prod_wheels",
    "branch_jars": "presigned_resp_prod_wheels",
    "logs": "presigned_logs",
}

def upload_paths(paths, resp, destination):
    dest_key = dest_resp_mapping[destination]
    c = resp.json()[dest_key]
    of = OrderedDict(c["fields"])

    sha = os.environ["BUILDKITE_COMMIT"]
    branch = os.environ["BUILDKITE_BRANCH"]
    bk_job_id = os.environ["BUILDKITE_JOB_ID"]

    for path in paths:
        fn = os.path.split(path)[-1]
        of["key"] = {
            "wheels": f"latest/{fn}",
            "branch_wheels": f"{branch}/{sha}/{fn}",
            "jars": f"jars/latest/{fn}",
            "branch_jars": f"jars/{branch}/{sha}/{fn}",
            "logs": f"bazel_events/{branch}/{sha}/{bk_job_id}/{fn}"
        }[destination]
        of["file"] = open(path, "rb")
        r = requests.post(c["url"], files=of)
        print(f"Uploaded {path} to {of['key']}", r.status_code)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Helper script to upload files to S3 bucket")
    parser.add_argument("--path", type=str, required=False)
    parser.add_argument("--destination", type=str)
    args = parser.parse_args()

    assert args.destination in {
        "branch_jars", "branch_wheels", "jars", "logs", "wheels",
        "docker_login"
    }
    assert "BUILDKITE_JOB_ID" in os.environ
    assert "BUILDKITE_COMMIT" in os.environ

    resp = perform_auth()

    if args.destination == "docker_login":
        handle_docker_login(resp)
    else:
        paths = gather_paths(args.path)
        print("Planning to upload", paths)
        upload_paths(paths, resp, args.destination)

redpajama_set_name: RedPajamaGithub


text:
from charms.reactive import (
    hook,
    when,
    only_once,
    is_state
)

import os.path as path
from charmhelpers.core import hookenv, host
from charmhelpers.core.templating import render
from shell import shell

# ./lib/nginxlib
import nginxlib

# ./lib/rubylib
from rubylib import ruby_dist_dir, bundle

# ./lib/huginnlib.py
import huginnlib

config = hookenv.config()

# HOOKS -----------------------------------------------------------------------
@hook('config-changed')
def config_changed():

    if not is_state('nginx.available'):
        return

    target = path.join(ruby_dist_dir(), '.env.local')
    render(source='app.env',
           target=target,
           context=config)

    host.service_restart('nginx')
    hookenv.status_set('active', 'Ready')

# REACTORS --------------------------------------------------------------------
@when('nginx.available')
@only_once
def install_app():
    """ Performs application installation
    """

    hookenv.log('Installing Huginn', 'info')

    # Configure NGINX vhost
    nginxlib.configure_site('default', 'vhost.conf',
                            app_path=ruby_dist_dir())

    # Update application
    huginnlib.download_archive()
    shell("mkdir -p %s/{log,tmp/pids,tmp/sockets}" % (ruby_dist_dir()))
    shell("cp %(dir)s/config/unicorn.rb.example "
          "%(dir)s/config/unicorn.rb" % {'dir': ruby_dist_dir()})

    bundle("install --deployment --without development test")
    procfile = path.join(hookenv.charm_dir(), 'templates/Procfile')
    shell("cp %(procfile)s %(dir)s/Procfile" % {
        'procfile': procfile,
        'dir': ruby_dist_dir()
    })

    bundle("exec rake assets:precompile RAILS_ENV=production")

    host.service_restart('nginx')
    hookenv.status_set('active', 'Huginn is installed!')

@when('nginx.available', 'database.available')
def setup_mysql(mysql):
    """ Mysql is available, update Huginn
    """
    hookenv.status_set('maintenance', 'Huginn is connecting to MySQL!')
    target = path.join(ruby_dist_dir(), '.env.local')
    render(source='db.env',
           target=target,
           context=dict(db=mysql))

    bundle("exec rake db:create RAILS_ENV=production")
    bundle("exec rake db:migrate RAILS_ENV=production")
    bundle("exec rake db:seed RAILS_ENV=production")
    host.service_restart('nginx')
    hookenv.status_set('active', 'Ready')


text:
layout: post
title:  TGT English posts by Haryana SSC last date 21st Sep-2015
date: 2015-07-24 19:21
comments: true
tags: Commission Education English Haryana Online School SSC Teacher
archive: false
---
Haryana State Selection Commission (HSSC) invites Online applications from eligible candidates for to the following  posts for Trained Graduate Teachers (TGT) English various Government Schools of Haryana Government :

- TGT (English) : 694 posts  TGT (English) : 341 posts for Mewat District

Age : 18-42 years as 21/09/2015. Pay Scale : Rs. 9300-34800 grade pay Rs.4600/-

**How to Apply** :  Apply online at Haryana SSC website from 21/08/2015 to 21/09/2015 only.

For details and instructions etc. for HSSC Advt. No. 09/2015, please visit at <http://hssc.gov.in/advertisements.htm> and visit <http://www.onlinehssc.in> for more details and online submission of application.


text:
package net.firejack.platform.service.directory.broker.directory.ldap;

import net.firejack.platform.api.directory.domain.User;
import net.firejack.platform.core.domain.NamedValues;
import net.firejack.platform.core.external.ldap.LdapServiceFacade;
import net.firejack.platform.core.request.ServiceRequest;
import net.firejack.platform.core.response.ServiceResponse;
import net.firejack.platform.web.statistics.annotation.TrackDetails;
import org.springframework.stereotype.Component;

@Component
@TrackDetails
public class CreateLdapUserBroker extends BaseLdapBroker<User> {

    public static final String PARAM_USER = "PARAM_USER";

    @Override
    protected ServiceResponse<User> performInternal(
            ServiceRequest<NamedValues<Object>> request, LdapServiceFacade ldapService) {
        ServiceResponse<User> response;
        try {
            User user = (User) request.getData().get(PARAM_USER);
            ldapService.createUser(user);
            response = new ServiceResponse<User>(user, "User created successfully.", true);
        } catch (Throwable e) {
            logger.error("Failed to create ldap user. Reason: " + e.getMessage(), e);
            response = new ServiceResponse<User>(e.getMessage(), false);
        }
        return response;
    }
}


text:
using namespace std;
using namespace FileGDBAPI;

int main()
{
  fgdbError hr;
  wstring   errorText;

  // Open the geodatabase.
  Geodatabase geodatabase;
  if ((hr = OpenGeodatabase(L"../data/Editing.gdb", geodatabase)) != S_OK)
  {
    wcout << "An error occurred while opening the geodatabase." << endl;
    ErrorInfo::GetErrorDescription(hr, errorText);
    wcout << errorText << "(" << hr << ")." << endl;
    return -1;
  }

  // Open the Cities table.
  Table table;
  if ((hr = geodatabase.OpenTable(L"\\Cities", table)) != S_OK)
  {
    wcout << "An error occurred while opening the table." << endl;
    ErrorInfo::GetErrorDescription(hr, errorText);
    wcout << errorText << "(" << hr << ")." << endl;
    return -1;
  }

  // Create a new feature for Cabazon.
  Row cabazonRow;
  table.CreateRowObject(cabazonRow);

  // Set the row's attributes.
  cabazonRow.SetString(L"AREANAME", L"Cabazon");
  cabazonRow.SetString(L"CLASS", L"town");
  cabazonRow.SetInteger(L"POP2000", 2939); // 2007

  // Create and assign a point geometry.
  PointShapeBuffer cabazonGeom;
  hr = cabazonGeom.Setup(shapePoint);

  Point* point;
  hr = cabazonGeom.GetPoint(point);

  point->x = -116.78443;
  point->y =   33.919902;

  cabazonRow.SetGeometry(cabazonGeom);

  // Store the row.
  if ((hr = table.Insert(cabazonRow)) != S_OK)
  {
    wcout << "An error occurred while inserting a row." << endl;
    ErrorInfo::GetErrorDescription(hr, errorText);
    wcout << errorText << "(" << hr << ")." << endl;
    return -1;
  }
  else
  {
    wcout << "Inserted two strings, one integer and a point." << endl;
  }

  // Get the row for Apple Valley by querying the table. Make sure to disable
  // recycling when intending to edit rows.
  EnumRows avQueryResult;
  if ((hr = table.Search(L"*", L"AREANAME = 'Apple Valley'", false, avQueryResult)) != S_OK)
  {
    wcout << "An error occurred while performing attribute search." << endl;
    ErrorInfo::GetErrorDescription(hr, errorText);
    wcout << errorText << "(" << hr << ")." << endl;
    return -1;
  }

  Row avRow;
  if ((hr = avQueryResult.Next(avRow)) != S_OK)
  {
    wcout << "An error occurred while querying the table." << endl;
    ErrorInfo::GetErrorDescription(hr, errorText);
    wcout << errorText << "(" << hr << ")." << endl;
    return -1;
  }

  // Modify the "CLASS" attribute and persist the change.
  avRow.SetString(L"CLASS", L"city");
  if ((hr = table.Update(avRow)) != S_OK)
  {
    wcout << "An error occurred while updating a row." << endl;
    ErrorInfo::GetErrorDescription(hr, errorText);
    wcout << errorText << "(" << hr << ")." << endl;
    return -1;
  }
  avQueryResult.Close(); // Close the EnumRows

  wcout << "Updated the CLASS field." << endl;

  // Delete the rows that fall into an envelope and have a null elevation value.
  // As with updating, make sure recycling is disabled when deleting rows.
  Envelope envelope;
  envelope.xMin = -117.4;
  envelope.yMin =   33.65;
  envelope.xMax = -116.8;
  envelope.yMax =   33.86;
  EnumRows deleteRows;
  if ((hr = table.Search(L"*", L"", envelope, false, deleteRows)) != S_OK)
  {
    wcout << "An error occurred while performing spatial search." << endl;
    ErrorInfo::GetErrorDescription(hr, errorText);
    wcout << errorText << "(" << hr << ")." << endl;
    return -1;
  }

  Row     deleteRow;
  wstring cityName;
  bool    isNull;
  while ((hr = deleteRows.Next(deleteRow)) == S_OK)
  {
    deleteRow.GetString(L"AREANAME", cityName);
    deleteRow.IsNull(L"ELEVATION", isNull);
    if (isNull)
    {
      wcout << "Deleting: " << cityName << endl;
      table.Delete(deleteRow);
    }
  }
  deleteRows.Close(); // Close the EnumRows

  // Close the table.
  if ((hr = geodatabase.CloseTable(table)) != S_OK)
  {
    wcout << "An error occurred while closing Cities." << endl;
    ErrorInfo::GetErrorDescription(hr, errorText);
    wcout << errorText << "(" << hr << ")." << endl;
    return -1;
  }

  // Compact the geodatabase. Recomended after bulk updates.
  if ((hr = geodatabase.CompactDatabase()) != S_OK)
  {
    wcout << "An error occurred while compacting the geodatabase." << endl;
    ErrorInfo::GetErrorDescription(hr, errorText);
    wcout << errorText << "(" << hr << ")." << endl;
    return -1;
  }

  // Close the geodatabase
  if ((hr = CloseGeodatabase(geodatabase)) != S_OK)
  {
    wcout << "An error occurred while closing the geodatabase." << endl;
    ErrorInfo::GetErrorDescription(hr, errorText);
    wcout << errorText << "(" << hr << ")." << endl;
    return -1;
  }

  return 0;
}


text:
package com.vmware.vim25;

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

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

 * <complexType name="OptionProfile">
 *   <complexContent>
 *     <extension base="{urn:vim25}ApplyProfile">
 *       <sequence>
 *         <element name="key" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "OptionProfile", propOrder = {
    "key"
})
public class OptionProfile
    extends ApplyProfile
{

    @XmlElement(required = true)
    protected String key;

    /**
     * Gets the value of the key property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getKey() {
        return key;
    }

    /**
     * Sets the value of the key property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setKey(String value) {
        this.key = value;
    }

}


text:
class Profile;
class ManagedConfigurationAPI;

namespace base {
template <typename T>
struct DefaultSingletonTraits;
}  // namespace base

// Factory for BrowserKeyedService ManagedConfigurationAPI.
class ManagedConfigurationAPIFactory
    : public BrowserContextKeyedServiceFactory {
 public:
  static ManagedConfigurationAPI* GetForProfile(Profile* profile);

  static ManagedConfigurationAPIFactory* GetInstance();

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

 private:
  friend struct base::DefaultSingletonTraits<ManagedConfigurationAPIFactory>;

  ManagedConfigurationAPIFactory();
  ~ManagedConfigurationAPIFactory() override;

  // BrowserContextKeyedServiceFactory:
  KeyedService* BuildServiceInstanceFor(
      content::BrowserContext* context) const override;
  void RegisterProfilePrefs(
      user_prefs::PrefRegistrySyncable* registry) override;
  bool ServiceIsCreatedWithBrowserContext() const override;
};

#endif  // CHROME_BROWSER_DEVICE_API_MANAGED_CONFIGURATION_API_FACTORY_H_


text:
    <title> Ruby Gnuplot - How To </title>

 Ruby Gnuplot - How To

      [Rubyforge Project
	page]
      [ChangeLog]
      [Authors]
      [License]

 History and Background

      Gnuplot is a program that has a rich language for the generation of
      plots.  It has a unique place in academia as it was one of the first
      freely available programs for plot generation.  I started using gnuplot
      over 10 years ago while pursuing my Master's degree in Physics and have
      been using it actively ever since.

Version 0.9

      My first attempt at a Ruby interface to gnuplot was an object interface
      encapsulating gnuplot language. This was taken directly from the Python
      gnuplot interface. In spite of my being very familiar with Gnuplot and
      Ruby and being the author of the RGnuplot package, I found it
      non-intuitive to use the RGnuplot package.  I found myself constantly
      looking at the code to figure out what I needed to do.

      This was not sufficient and did not sit well.

Version 1.0

      The second attempt at a Ruby interface was to do absolutely nothing but
      use Ruby's built in string manipulation methods.  This meant that I
      could simply use my knowledge of Gnuplot without having to worry about
      objects.

      While in some ways an improvement over Version 0.9, it still did not sit
      well with me.

 Version 2.0

      After attending RubyConf 2004 I was inspired by Rich Kilmer's use of
      Ruby to implement domain specific languages.  That is the current
      implementation of Gnuplot and quite probably the one that I'll stick
      with for some time.  This version combines the direct mapping of the
      gnuplot language without wrapping with the ruby syntax and mechanism of
      adding methods to existing classes to interface Ruby objects with
      gnuplot.

Setup

Version 2.2

 If the 'gnuplot' command is in your path then there is no required
    setup. If the gnuplot executable for your system is called something other
    than simply 'gnuplot' then set the RB_GNUPLOT environment variable to the
    name of the executable.  This must either be a full path to the gnuplot
    command or an executable filename that exists in your PATH environment
    variable.

 Ruby Gnuplot Concepts

      Gnuplot has a very simple conceptual model.  Calls to Set are
      made to set parameters and either Plot or Splot is
      called to generate the actual plot.  The dataset to be
      plotted can be specified in a number of ways, contained in a seperate
      file, generated from a function, read from standard input, or read
      immediately after the plot command.

      The object model for the Ruby gnuplot wrapper directly mimics this
      layout and flow.  The following are the standard steps for generating a
      plot:

 Instantiate a Plot or Splot object and set parameters by gnuplot
	variable name.

Instantiate DataSet objects and attach Ruby objects containing
	  the data to be plotted to the DataSet. Attach properties that modify
	  the plot command using the modifier name.

Send the Plot/Splot object to a Gnuplot instance for
	  plotting.

      The Version 2.0 interface makes very heavy use of blocks leading to very
      readable code.

Gnuplot.open

      Instantiates a new Gnuplot process.  The path to the executable is
      determined on a Unix or MacOSX system using the which command.  Windows
      users, I have no idea what to do.

      If a block is given to the function the opened process is passed into
      the block.  This mimics the most common usage of the File.open method.

Plot.new

SPlot.new

      Create a new Plot or Splot object.  DataSets are attached to the object
      to specify the data and its properties.

      If a block is given to the function, the plot object is passed into the
      block.

DataSet.new

      Associates a Ruby object containing the data to plot with the properties
      that will be passed to the plot command for that dataset.  Any Ruby
      object can be associated with a DataSet as long as it understands the
      to_gplot method.

 to_gplot

      Within Gnuplot, plot data is read in very simple formats.  The
      to_gplot method is expected to write the data of the object in a format
      that is understandable by Gnuplot.  One of the many great things about
      Ruby is that methods can be added after the original declaration.  The
      gnuplot module defines the to_gplot method on the following classes:

      Array, String, and Matrix.

      Simply define a to_gplot method on your own class to tie the class into
      gnuplot.

 Examples

 Simple sin wave

 The following example simply plots the value of sin(x) between the
      ranges of -10 and 10.  A few points to notice:

 The code uses nested blocks to construct the plot.  The newly
	  created object is passed to the block so it can be modified in
	  place.

 Each of the gnuplot plot variables are modified using the
	  variable name as a method name on the plot object or on the dataset
	  object.  The wrapper also takes care of the single quoting that is
	  required on some of the variables like title, ylabel, and xlabel.

 The plot object simply has an array of DataSets.  The
	  constructor initializes this empty array before yielding to the
	  block.  This method uses the << operator to add the DataSet to
	  the plot.

 When the plot block ends, if an IO object is given to the Plot
	  constructor, the plot commands will be written to the IO object.
	  Any object can be passed to the constructor as long as it
	  understands the << operator.

Gnuplot.open do |gp|
  Gnuplot::Plot.new( gp ) do |plot|

    plot.xrange "[-10:10]"
    plot.title  "Sin Wave Example"
    plot.ylabel "x"
    plot.xlabel "sin(x)"

    plot.data << Gnuplot::DataSet.new( "sin(x)" ) do |ds|
      ds.with = "lines"
      ds.linewidth = 4
    end

  end

end

 Plotting discrete points

      Array data can be plotted quite easily since Arrays have a defined
      to_gplot method.

Simply pass an array of data to the constructor of the DataSet
	  object or set the data property of the DataSet.  In this example,
	  because there are two arrays, each array will be a single column of
	  data to the gnuplot process.

Gnuplot.open do |gp|
  Gnuplot::Plot.new( gp ) do |plot|

    plot.title  "Array Plot Example"
    plot.ylabel "x"
    plot.xlabel "x^2"

    x = (0..50).collect { |v| v.to_f }
    y = x.collect { |v| v ** 2 }

    plot.data << Gnuplot::DataSet.new( [x, y] ) do |ds|
      ds.with = "linespoints"
      ds.notitle
    end
  end
end

 Multiple Data Sets

 As many data sets as are desired can be attached to a plot.  Each of
      these can have their own plot modifiers.  Notice in this example how the
      data array is explicitly set instead of using the << operator.

 Also in this example, the commands are not written to the Gnuplot
      process but are instead written to a File called gnuplot.dat.  This file
      can later be run directly by a gnuplot process as it contains only the
      gnuplot commands.

File.open( "gnuplot.dat", "w") do |gp|
  Gnuplot::Plot.new( gp ) do |plot|

    plot.xrange "[-10:10]"
    plot.title  "Sin Wave Example"
    plot.ylabel "x"
    plot.xlabel "sin(x)"

    x = (0..50).collect { |v| v.to_f }
    y = x.collect { |v| v ** 2 }

    plot.data = [
      Gnuplot::DataSet.new( "sin(x)" ) { |ds|
	ds.with = "lines"
	ds.title = "String function"
	ds.linewidth = 4
      },

      Gnuplot::DataSet.new( [x, y] ) { |ds|
	ds.with = "linespoints"
	ds.title = "Array data"
      }
    ]

  end

end


text:
from .base import Base

class Atoi(Base):
    is_loaded = False

    def __init__(self, compiler):
        Base.__init__(self, compiler)

        if Atoi.is_loaded:
            return

        self.load('atoi.asm', 'atoi')
        Atoi.is_loaded = True


text:
class EnvDumpPage < Page

  description %{
    Instead of rendering a page in the normal fashion the Env Dump
    behavior will output all of the environment variables on the
    request. This is occasionally useful for debugging.
  }

  def render
    %{
#{ request.env.collect { |k,v| "#{k} => #{v}\n" } }
}
  end

  def cache?
    false
  end

end


text:
class EventVacancyFillService < CivilService::Service
  class Result < CivilService::Result
    attr_accessor :move_results
  end
  self.result_class = Result

  attr_reader :run, :bucket_key, :move_results, :suppress_notifications, :immovable_signups
  delegate :event, to: :run
  delegate :convention, to: :event

  include SkippableAdvisoryLock
  include ConventionRegistrationFreeze

  def initialize(run, bucket_key, immovable_signups: [], skip_locking: false, suppress_notifications: false)
    @run = run
    @bucket_key = bucket_key
    @skip_locking = skip_locking
    @immovable_signups = immovable_signups
    @move_results = []
    @suppress_notifications = suppress_notifications
  end

  private

  def inner_call
    bucket = event.registration_policy.bucket_with_key(bucket_key)
    return success(move_results: []) if bucket.slots_unlimited?

    with_advisory_lock_unless_skip_locking("run_#{run.id}_signups") { fill_bucket_vacancy(bucket_key) }

    move_results.each { |result| notify_moved_signup(result) if result.should_notify? }

    success(move_results: move_results)
  end

  def fill_bucket_vacancy(bucket_key)
    signup_to_move = best_signup_to_fill_bucket_vacancy(bucket_key)
    return unless signup_to_move

    bucket = event.registration_policy.bucket_with_key(bucket_key)
    moving_confirmed_signup = signup_to_move.confirmed?
    prev_bucket_key = signup_to_move.bucket_key
    prev_state = signup_to_move.state
    signup_to_move.update!(state: 'confirmed', bucket_key: bucket_key, counted: bucket.counted?)
    signup_to_move.log_signup_change!(action: 'vacancy_fill')
    move_results << SignupMoveResult.from_signup(signup_to_move, prev_state, prev_bucket_key)

    # We left a vacancy by moving a confirmed signup out of its bucket, so recursively try to fill
    # that vacancy
    fill_bucket_vacancy(prev_bucket_key) if moving_confirmed_signup
  end

  def best_signup_to_fill_bucket_vacancy(bucket_key)
    bucket = event.registration_policy.bucket_with_key(bucket_key)
    signups_ordered.find do |signup|
      next if signup.bucket_key == bucket.key
      next unless signup_can_fill_bucket_vacancy?(signup, bucket)
      next if signup_already_in_best_slot?(signup)

      signup
    end
  end

  def signup_already_in_best_slot?(signup)
    return false unless signup.confirmed?

    (signup.requested_bucket_key == signup.bucket_key)
    # TODO: figure out how to do something like the next line.  We'd rather not move a no-pref
    # signup out of flex but at this point I am not sure how to do that while allowing it to be
    # moved at all.
    #  || (signup.no_preference? && signup.anything? && move_results.empty?)
  end

  def signup_can_fill_bucket_vacancy?(signup, bucket_with_vacancy)
    return false unless signup.bucket.nil? || counted_limited_bucket?(signup.bucket)

    (
      (signup.no_preference? && counted_limited_bucket?(bucket_with_vacancy)) ||
        signup.requested_bucket_key == bucket_with_vacancy.key || bucket_with_vacancy.anything?
    )
  end

  def counted_limited_bucket?(bucket)
    bucket&.slots_limited? && bucket&.counted?
  end

  def all_signups_ordered
    @all_signups_ordered ||= all_signups.to_a.sort_by { |signup| signup_priority_key(signup) }
  end

  def all_signups
    @all_signups ||=
      begin
        run.signups.reload
        run.signups.where.not(state: 'withdrawn').where.not(id: team_member_signups.map(&:id))
      end
  end

  def signups_ordered
    all_signups_ordered.select { |signup| signup_movable?(signup) }
  end

  def signup_movable?(signup)
    return false if immovable_signups.include?(signup)
    return false if move_results.any? { |result| result.signup_id == signup.id }
    true
  end

  def signup_priority_key(signup)
    [
      # Move waitlisted signups first
      signup.confirmed? ? 1 : 0,
      # don't move confirmed no-preference signups unless necessary
      signup.no_preference? && signup.confirmed? ? 1 : 0,
      # When moving confirmed signups, try to keep the earlier signups stable
      signup.created_at.to_i * (signup.confirmed? ? -1 : 1)
    ]
  end

  def team_member_signups
    @team_member_signups ||=
      run
        .signups
        .reload
        .where(user_con_profile_id: TeamMember.where(event_id: run.event_id).select(:user_con_profile_id))
        .to_a
  end

  def notify_moved_signup(result)
    return if suppress_notifications

    # Wait 30 seconds because the transaction hasn't been committed yet
    Signups::UserSignupMovedNotifier.new(move_result: result).deliver_later(wait: 5.seconds)
  end
end