text:
from __future__ import annotations

import pkgutil
from dataclasses import dataclass
from pathlib import PurePath
from typing import Generator

from pants.backend.docker.target_types import DockerImageSources
from pants.backend.python.goals.lockfile import PythonLockfileRequest, PythonToolLockfileSentinel
from pants.backend.python.subsystems.python_tool_base import PythonToolRequirementsBase
from pants.backend.python.target_types import EntryPoint
from pants.backend.python.util_rules.pex import PexRequest, VenvPex, VenvPexProcess
from pants.engine.fs import CreateDigest, Digest, FileContent
from pants.engine.process import Process, ProcessResult
from pants.engine.rules import Get, collect_rules, rule
from pants.engine.target import HydratedSources, HydrateSourcesRequest
from pants.engine.unions import UnionRule
from pants.util.docutil import git_url
from pants.util.logging import LogLevel

_DOCKERFILE_SANDBOX_TOOL = "dockerfile_wrapper_script.py"
_DOCKERFILE_PACKAGE = "pants.backend.docker.subsystems"

class DockerfileParser(PythonToolRequirementsBase):
    options_scope = "dockerfile-parser"
    help = "Used to parse Dockerfile build specs to infer their dependencies."

    default_version = "dockerfile==3.2.0"

    register_interpreter_constraints = True
    default_interpreter_constraints = ["CPython>=3.7"]

    register_lockfile = True
    default_lockfile_resource = (_DOCKERFILE_PACKAGE, "dockerfile_lockfile.txt")
    default_lockfile_path = (
        f"src/python/{_DOCKERFILE_PACKAGE.replace('.', '/')}/dockerfile_lockfile.txt"
    )
    default_lockfile_url = git_url(default_lockfile_path)

class DockerfileParserLockfileSentinel(PythonToolLockfileSentinel):
    options_scope = DockerfileParser.options_scope

@rule
def setup_lockfile_request(
    _: DockerfileParserLockfileSentinel, dockerfile_parser: DockerfileParser
) -> PythonLockfileRequest:
    return PythonLockfileRequest.from_tool(dockerfile_parser)

@dataclass(frozen=True)
class ParserSetup:
    pex: VenvPex

@rule
async def setup_parser(dockerfile_parser: DockerfileParser) -> ParserSetup:
    parser_script_content = pkgutil.get_data(_DOCKERFILE_PACKAGE, _DOCKERFILE_SANDBOX_TOOL)
    if not parser_script_content:
        raise ValueError(
            "Unable to find source to {_DOCKERFILE_SANDBOX_TOOL!r} in {_DOCKERFILE_PACKAGE}."
        )

    parser_content = FileContent(
        path="__pants_df_parser.py",
        content=parser_script_content,
        is_executable=True,
    )

    parser_digest = await Get(Digest, CreateDigest([parser_content]))

    parser_pex = await Get(
        VenvPex,
        PexRequest(
            output_filename="dockerfile_parser.pex",
            internal_only=True,
            requirements=dockerfile_parser.pex_requirements(),
            interpreter_constraints=dockerfile_parser.interpreter_constraints,
            main=EntryPoint(PurePath(parser_content.path).stem),
            sources=parser_digest,
        ),
    )

    return ParserSetup(parser_pex)

@dataclass(frozen=True)
class DockerfileParseRequest:
    sources_digest: Digest
    args: tuple[str, ...]

@rule
async def setup_process_for_parse_dockerfile(
    request: DockerfileParseRequest, parser: ParserSetup
) -> Process:
    process = await Get(
        Process,
        VenvPexProcess(
            parser.pex,
            argv=request.args,
            description="Parse Dockerfile.",
            input_digest=request.sources_digest,
            level=LogLevel.DEBUG,
        ),
    )
    return process

@dataclass(frozen=True)
class DockerfileInfo:
    putative_target_addresses: tuple[str, ...] = ()
    version_tags: tuple[str, ...] = ()

def split_iterable(
    sep: str, obj: list[str] | tuple[str, ...]
) -> Generator[tuple[str, ...], None, None]:
    while sep in obj:
        idx = obj.index(sep)
        yield tuple(obj[:idx])
        obj = obj[idx + 1 :]
    yield tuple(obj)

@rule
async def parse_dockerfile(sources: DockerImageSources) -> DockerfileInfo:
    hydrated_sources = await Get(HydratedSources, HydrateSourcesRequest(sources))
    result = await Get(
        ProcessResult,
        DockerfileParseRequest(
            hydrated_sources.snapshot.digest,
            ("version-tags,putative-targets", *hydrated_sources.snapshot.files),
        ),
    )

    output = result.stdout.decode("utf-8").strip().split("\n")
    version_tags, putative_targets = split_iterable("---", output)
    return DockerfileInfo(
        putative_target_addresses=putative_targets,
        version_tags=version_tags,
    )

def rules():
    return (
        *collect_rules(),
        UnionRule(PythonToolLockfileSentinel, DockerfileParserLockfileSentinel),
    )


text:
ace.define("ace/snippets/typescript",["require","exports","module"], function(require, exports, module) {
"use strict";

exports.snippetText =undefined;
exports.scope = "typescript";

});                (function() {
                    ace.require(["ace/snippets/typescript"], function(m) {
                        if (typeof module == "object" && typeof exports == "object" && module) {
                            module.exports = m;
                        }
                    });
                })();

redpajama_set_name: RedPajamaGithub


text:
package com.badlogic.gdx.utils;

import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import com.badlogic.gdx.files.FileHandle;

/** Generates the gdx.gwt.xml file by running through the gdx/src/ directory and cross-referencing it with the gdx-backends-gwt
 * directory.
 * @author mzechner */
public class GwtModuleGenerator {
	private static void gatherJavaFiles (FileHandle dir, Set<String> names, Map<String, FileHandle> fileHandles, boolean recursive) {
		if (dir.name().equals(".svn")) return;
		FileHandle[] files = dir.list();
		for (FileHandle file : files) {
			if (file.isDirectory() && recursive) {
				gatherJavaFiles(file, names, fileHandles, recursive);
			} else {
				if (file.extension().equals("java")) {
					System.out.println(file.name());
					if (names.contains(file.name())) System.out.println(file.name() + " duplicate!");
					names.add(file.name());
					fileHandles.put(file.name(), file);
				}
			}
		}
	}

	public static void main (String[] args) throws IOException {
		Set<String> excludes = new HashSet<String>();
		Map<String, FileHandle> excludesHandles = new HashMap<String, FileHandle>();
		System.out.println("Excludes -------------------------------------------------");
		gatherJavaFiles(new FileHandle("../backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/badlogic/gdx"),
			excludes, excludesHandles, true);
		System.out.println("#" + excludes.size());

		// build and shared library loading utils
		excludes.add("GdxBuild.java");
		excludes.add("GdxNativesLoader.java");
		excludes.add("GwtModuleGenerator.java");
		excludes.add("SharedLibraryLoader.java");

		// native pixmap routines
		excludes.add("Gdx2DPixmap.java");
		excludes.add("PixmapIO.java");
		excludes.add("ETC1.java");
		excludes.add("ETC1TextureData.java");
		excludes.add("ScreenUtils.java");

		// remote input
		excludes.add("RemoteInput.java");
		excludes.add("RemoteSender.java");

		// tiled support
		excludes.add("TiledLoader.java"); // FIXME?
		excludes.add("TileMapRendererLoader.java"); // FIXME?

		// various utils
		excludes.add("AtomicQueue.java");
		excludes.add("LittleEndianInputStream.java");
		excludes.add("PauseableThread.java");
		excludes.add("DesktopClipboard.java");
		excludes.add("AndroidClipboard.java");

		// scene2d ui package
// gatherJavaFiles(new FileHandle("src/com/badlogic/gdx/scenes/scene2d/ui"), excludes, excludesHandles, true);

		Set<String> includes = new HashSet<String>();
		Map<String, FileHandle> includesHandles = new TreeMap<String, FileHandle>();
		System.out.println("Includes -------------------------------------------------");
		gatherJavaFiles(new FileHandle("src"), includes, includesHandles, true);
		System.out.println("#" + includes.size());

		for (String include : includes) {
			if (!excludes.contains(include)) continue;
			FileHandle includeFile = includesHandles.get(include);
			FileHandle excludeFile = excludesHandles.get(include);
			includesHandles.remove(include);
			System.out.println("excluded '" + include + "'");
		}

		System.out.println("diff: " + includesHandles.size());

		StringWriter writer = new StringWriter();
		writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
		XmlWriter builder = new XmlWriter(writer);
		builder.element("module").attribute("rename-to", "com.badlogic.gdx");
		builder.element("inherits").attribute("name", "com.esotericsoftware.tablelayout").pop();
		builder.element("source").attribute("path", "gdx");
		for (String include : includesHandles.keySet()) {
			String name = includesHandles.get(include).path().replace("\\", "/").replace("src/com/badlogic/gdx/", "");
			builder.element("include").attribute("name", name).pop();
		}
		// duplicate names...
		builder.element("include").attribute("name", "graphics/g2d/Animation.java").pop();
		builder.element("include").attribute("name", "graphics/g3d/Animation.java").pop();
		builder.pop();
		builder.pop();
		builder.close();
		System.out.println(writer);

		new FileHandle("src/com/badlogic/gdx.gwt.xml").writeString(writer.toString(), false);
	}
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>org.jxq</groupId>
	<artifactId>utility</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>utility</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.8.2</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.3.2</version>
		</dependency>
		<dependency>
			<groupId>commons-codec</groupId>
			<artifactId>commons-codec</artifactId>
			<version>1.9</version>
		</dependency>

		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>3.0-alpha-1</version>
		</dependency>

		<!-- Log4j -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.6.4</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.6.4</version>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>1.6.4</version>
		</dependency>
	</dependencies>
</project>


text:
class Api::V7::AgentsController < Api::BaseController
  before_filter :authenticate_user_from_token!

  swagger_controller :agents, "Agents"

  swagger_api :index do
    summary 'Returns all agents, sorted by group'
    response :ok
    response :unprocessable_entity
    response :not_found
  end

  swagger_api :show do
    summary 'Returns agent by name'
    param :path, :name, :string, :required, "Agent name"
    response :ok
    response :unprocessable_entity
    response :not_found
  end

  def index
    collection = Agent.visible.includes(:group)
    @agents = collection.decorate
  end

  def show
    agent = Agent.where(name: params[:id]).first
    @agent = agent.decorate
  end
end


text:
ACCEPTED

#### According to
Interim Register of Marine and Nonmarine Genera

#### Published in
in Zhigulina, Paleontol Zh 5, Sentyabr'-Oktyabr': 25.

#### Original name
null

### Remarks
null


text:
require 'whois/record/parser/base'
require 'whois/record/parser/scanners/verisign'

module Whois
  class Record
    class Parser

      # Parser for the jobswhois.verisign-grs.com server.
      class JobswhoisVerisignGrsCom < Base
        include Scanners::Ast

        property_supported :disclaimer do
          node("Disclaimer")
        end

        property_supported :domain do
          node("Domain Name") { |raw| raw.downcase }
        end

        property_not_supported :domain_id

        property_supported :referral_whois do
          node("Whois Server")
        end

        property_supported :referral_url do
          node("Referral URL") do |raw|
            last_useful_item(raw)
          end
        end

        property_supported :status do
          node("Status")
        end

        property_supported :available? do
          node("Registrar").nil?
        end

        property_supported :registered? do
          !available?
        end

        property_supported :created_on do
          node("Creation Date") { |raw| Time.parse(raw) }
        end

        property_supported :updated_on do
          node("Updated Date") { |raw| Time.parse(raw) }
        end

        property_supported :expires_on do
          node("Expiration Date") { |raw| Time.parse(raw) }
        end

        property_supported :registrar do
          node("Registrar") do |raw|
            Whois::Record::Registrar.new(:name => last_useful_item(raw), :organization => last_useful_item(raw), :url => referral_url)
          end
        end

        property_supported :nameservers do
          Array.wrap(node("Name Server")).reject { |value| value =~ /no nameserver/i }.map do |name|
            Nameserver.new(name.downcase)
          end
        end

        # Initializes a new {Scanners::Verisign} instance
        # passing the {#content_for_scanner}
        # and calls +parse+ on it.
        #
        # @return [Hash]
        def parse
          Scanners::Verisign.new(content_for_scanner).parse
        end

        protected

          # In case of "SPAM Response", the response contains more than one item
          # for the same value and the value becomes an Array.
          def last_useful_item(values)
            values.is_a?(Array) ? values.last : values
          end

      end

    end
  end
end


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;

namespace Microsoft.CodeAnalysis.Semantics
{
    ///
    /// Represents a conversion operation.
    ///
    /// <remarks>
    /// This interface is reserved for implementation by its associated APIs. We reserve the right to
    /// change it in the future.
    /// </remarks>
    public interface IConversionExpression : IOperation
    {
        ///
        /// Value to be converted.
        ///
        IOperation Operand { get; }
        ///
        /// Operator method used by the operation, null if the operation does not use an operator method.
        ///
        IMethodSymbol OperatorMethod { get; }

#pragma warning disable RS0010 // Avoid using cref tags with a prefix
        ///
        /// Gets the underlying common conversion information.
        ///
        /// <remarks>
        /// If you need conversion information that is language specific, use either
        /// <see cref="T:Microsoft.CodeAnalysis.CSharp.IConversionExpressionExtensions.GetConversion(IConversionExpression)"/> or
        /// <see cref="T:Microsoft.CodeAnalysis.VisualBasic.GetConversion(IConversionExpression)"/>.
        /// </remarks>
#pragma warning restore RS0010 // Avoid using cref tags with a prefix
        CommonConversion Conversion { get; }
        ///
        /// True if and only if the conversion is indicated explicity by a cast operation in the source code.
        ///
        bool IsExplicitInCode { get; }
        ///
        /// False if the conversion will fail with a <see cref="InvalidCastException"/> at runtime if the cast fails. This is true for C#'s
        /// as operator and for VB's TryCast operator.
        ///
        bool IsTryCast { get; }
        ///
        /// True if the conversion can fail at runtime with an overflow exception. This corresponds to C# checked and unchecked blocks.
        ///
        bool IsChecked { get; }
    }
}


text:
package dump.q183.packageB;

public class XMLMessage extends dump.q183.packageA.Message {
	String getText() { return "<msg>text</msg>";}
	public static void main(String[] args) {
	System.out.println(new XMLMessage().getText());
	}}


text:
package main

import (
	"encoding/json"
	"net"
	"reflect"
	"time"

	c "github.com/flynn/flynn/Godeps/_workspace/src/github.com/flynn/go-check"
	"github.com/flynn/flynn/discoverd/client"
	"github.com/flynn/flynn/logaggregator/client"
)

type LogAggregatorSuite struct {
	Helper
}

var _ = c.Suite(&LogAggregatorSuite{})

func (s *LogAggregatorSuite) TestReplication(t *c.C) {
	app := s.newCliTestApp(t)
	app.flynn("scale", "ish=1")
	defer app.flynn("scale", "ish=0")
	defer app.cleanup()

	aggHost := "logaggregator.discoverd"
	waitForAggregator := func(wantUp bool) func() {
		ch := make(chan *discoverd.Event)
		stream, err := app.disc.Service("logaggregator").Watch(ch)
		t.Assert(err, c.IsNil)
		up := make(chan struct{})
		go func() {
			timeout := time.After(60 * time.Second)
			defer close(up)
			defer stream.Close()
			var current bool
			for {
				select {
				case <-timeout:
					t.Error("logaggregator did not come back within a minute")
					return
				case event := <-ch:
					switch {
					case event.Kind == discoverd.EventKindCurrent:
						current = true
					case !wantUp && current && event.Kind == discoverd.EventKindDown:
						return
					case wantUp && current && event.Kind == discoverd.EventKindUp:
						aggHost, _, _ = net.SplitHostPort(event.Instance.Addr)
						return
					}
				}
			}
		}()
		return func() {
			<-up
		}
	}

	wait := waitForAggregator(false)
	flynn(t, "/", "-a", "logaggregator", "scale", "app=1")
	wait()

	instances, err := app.disc.Instances(app.name, time.Second*100)
	t.Assert(err, c.IsNil)
	ish := instances[0]
	cc := s.controllerClient(t)

	readLines := func(expectedLines ...string) {
		lineCount := 10
		lc, _ := client.New("http://" + aggHost)
		out, err := lc.GetLog(app.id, &client.LogOpts{Follow: true, Lines: &lineCount})
		t.Assert(err, c.IsNil)

		done := make(chan struct{})
		var lines []string
		go func() {
			defer close(done)
			dec := json.NewDecoder(out)
			for {
				var msg client.Message
				if err := dec.Decode(&msg); err != nil {
					return
				}
				lines = append(lines, msg.Msg)
				if reflect.DeepEqual(lines, expectedLines) {
					return
				}
			}
		}()

		select {
		case <-time.After(60 * time.Second):
		case <-done:
		}
		out.Close()

		t.Assert(lines, c.DeepEquals, expectedLines)
	}

	runIshCommand(ish, "echo line1")
	runIshCommand(ish, "echo line2")
	readLines("line1", "line2")

	// kill logaggregator
	wait = waitForAggregator(true)
	jobs, err := cc.JobList("logaggregator")
	t.Assert(err, c.IsNil)
	for _, j := range jobs {
		if j.State == "up" {
			t.Assert(cc.DeleteJob(app.name, j.ID), c.IsNil)
		}
	}
	wait()

	// confirm that logs are replayed when it comes back
	runIshCommand(ish, "echo line3")
	readLines("line1", "line2", "line3")

	// start new logaggregator
	wait = waitForAggregator(true)
	flynn(t, "/", "-a", "logaggregator", "scale", "app=2")
	wait()

	// confirm that logs show up in the new aggregator
	runIshCommand(ish, "echo line4")
	readLines("line1", "line2", "line3", "line4")
}


text:
Customizing Forms
=================

The forms in Sylius are placed in the ``Sylius\Bundle\*BundleName*\Form\Type`` namespaces and the extensions
will be placed in `App\Form\Extension`.

Why would you customize a Form?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

There are plenty of reasons to modify forms that have already been defined in Sylius.
Your business needs may sometimes slightly differ from our internal assumptions.

You can:

* add completely **new fields**,
* **modify** existing fields, make them required, change their HTML class, change labels etc.,
* **remove** fields that are not used.

How to customize a Form?
~~~~~~~~~~~~~~~~~~~~~~~~

.. tip::

    You can browse the full implementation of this example on `this GitHub Pull Request.
    <https://github.com/Sylius/Customizations/pull/8>`__

If you want to modify the form for the ``Customer Profile`` in your system there are a few steps that you should take.
Assuming that you would like to (for example):

* Add a ``secondaryPhoneNumber`` field,
* Remove the ``gender`` field,
* Change the label for the ``lastName`` from ``sylius.form.customer.last_name`` to ``app.form.customer.surname``

These will be the steps that you will have to take to achieve that:

**1.** If you are planning to add new fields remember that beforehand they need to be added on the model that the form type is based on.

    In case of our example if you need to have the ``secondaryPhoneNumber`` on the model and the entity mapping for the ``Customer`` resource.
    To get to know how to prepare that go :doc:`there </customization/model>`.

**2.** Create a **Form Extension**.

Your form has to extend a proper base class. How can you check that?

For the ``CustomerProfileType`` run:

.. code-block:: bash

    php bin/console debug:container sylius.form.type.customer_profile

As a result you will get the ``Sylius\Bundle\CustomerBundle\Form\Type\CustomerProfileType`` - this is the class that you need to be extending.

.. code-block:: php

    <?php

    declare(strict_types=1);

    namespace App\Form\Extension;

    use Sylius\Bundle\CustomerBundle\Form\Type\CustomerProfileType;
    use Symfony\Component\Form\AbstractTypeExtension;
    use Symfony\Component\Form\Extension\Core\Type\TextType;
    use Symfony\Component\Form\FormBuilderInterface;

    final class CustomerProfileTypeExtension extends AbstractTypeExtension
    {
        public function buildForm(FormBuilderInterface $builder, array $options): void
        {
            $builder
                // Adding new fields works just like in the parent form type.
                ->add('secondaryPhoneNumber', TextType::class, [
                    'required' => false,
                    'label' => 'app.form.customer.secondary_phone_number',
                ])
                // To remove a field from a form simply call ->remove(`fieldName`).
                ->remove('gender')
                // You can change the label by adding again the same field with a changed `label` parameter.
                ->add('lastName', TextType::class, [
                    'label' => 'app.form.customer.surname',
                ]);
        }

        public static function getExtendedTypes(): iterable
        {
            return [CustomerProfileType::class];
        }
    }

.. note::
    Of course remember that you need to define new labels for your fields
    in the ``translations\messages.en.yaml`` for english contents of your messages.

**3.** After creating your class, register this extension as a service in the ``config/services.yaml``:

.. code-block:: yaml

    services:
        app.form.extension.type.customer_profile:
            class: App\Form\Extension\CustomerProfileTypeExtension
            tags:
                - { name: form.type_extension, extended_type: Sylius\Bundle\CustomerBundle\Form\Type\CustomerProfileType }

.. note::
    Of course remember that you need to render the new fields you have created,
    and remove the rendering of the fields that you have removed **in your views**.

In our case you will need to copy the original template from ``vendor/sylius/sylius/src/Sylius/Bundle/ShopBundle/Resources/views/Account/profileUpdate.html.twig``
to ``templates/bundles/SyliusShopBundle/Account/`` and add the fields inside the copy.

.. code-block:: html

    {{ form_row(form.phoneNumber) }}
    {{ form_row(form.subscribedToNewsletter) }}

    <!-- your fields -->
    {{ form_row(form.birthday) }}
    {{ form_row(form.secondaryPhoneNumber) }}

    {{ sonata_block_render_event('sylius.shop.account.profile.update.form', {'customer': customer, 'form': form}) }}

Need more information?
----------------------

.. warning::

    Some of the forms already have extensions in Sylius. Learn more about Extensions `here <https://symfony.com/doc/current/form/create_form_type_extension.html>`_.

For instance the ``ProductVariant`` admin form is defined under ``Sylius/Bundle/ProductBundle/Form/Type/ProductVariantType.php`` and later extended in
``Sylius/Bundle/CoreBundle/Form/Extension/ProductVariantTypeExtension.php``. If you again extend the base type form like this:

.. code-block:: yaml

    services:
        app.form.extension.type.product_variant:
            class: App\Form\Extension\ProductVariantTypeMyExtension
            tags:
                - { name: form.type_extension, extended_type: Sylius\Bundle\ProductBundle\Form\Type\ProductVariantType, priority: -5 }

your form extension will also be executed. Whether before or after the other extensions depends on priority tag set.

`How to customize forms that are already extended in Core?`
-----------------------------------------------------------

.. tip::

    You can browse the full implementation of this example on `this GitHub Pull Request.
    <https://github.com/Sylius/Customizations/pull/9>`__

Having a look at the extensions and possible additionally defined event handlers can also be useful when form elements are embedded dynamically,
as is done in the ``ProductVariantTypeExtension`` by the ``CoreBundle``:

.. code-block:: php

    <?php

    // ...

    final class ProductVariantTypeExtension extends AbstractTypeExtension
    {
        public function buildForm(FormBuilderInterface $builder, array $options): void
        {
            // ...

            $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
                $productVariant = $event->getData();

                $event->getForm()->add('channelPricings', ChannelCollectionType::class, [
                    'entry_type' => ChannelPricingType::class,
                    'entry_options' => function (ChannelInterface $channel) use ($productVariant) {
                        return [
                            'channel' => $channel,
                            'product_variant' => $productVariant,
                            'required' => false,
                        ];
                    },
                    'label' => 'sylius.form.variant.price',
                ]);
            });
        }

        // ...

    }

The ``channelPricings`` get added on ``FormEvents::PRE_SET_DATA``, so when you wish to remove or alter this form definition,
you will also have to set up an event listener and then remove the field:

.. code-block:: php

    <?php

    //...

    final class ProductVariantTypeMyExtension extends AbstractTypeExtension
    {
        // ...

        public function buildForm(FormBuilderInterface $builder, array $options): void
        {
            //...

            $builder
                ->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
                    $event->getForm()->remove('channelPricings');
                })
                ->addEventSubscriber(new AddCodeFormSubscriber(NULL, ['label' => 'app.form.my_other_code_label']))
            ;

            // ...

        }
    }

Adding constraints inside a form extension
------------------------------------------

.. warning::

    When adding your constraints dynamically from inside a form extension, be aware to add the correct validation groups.

Although it is advised to follow the :doc:`Validation Customization Guide </customization/validation>`, it might happen that you
want to define the form constraints from inside the form extension. They will not be used unless the correct validation group(s)
has been added. The example below shows how to add the default `sylius` group to a constraint.

.. tip::

    You can browse the full implementation of this example on `this GitHub Pull Request.
    <https://github.com/Sylius/Customizations/pull/8>`__

.. code-block:: php

    <?php

    // ...

    final class CustomerProfileTypeExtension extends AbstractTypeExtension
    {
        // ...

        public function buildForm(FormBuilderInterface $builder, array $options): void
        {
            //...

            $builder
            // Adding new fields works just like in the parent form type.
            ->add('secondaryPhoneNumber', TextType::class, [
                'required' => false,
                'label' => 'app.form.customer.secondary_phone_number',
                'constraints' => [
                    new Length([
                        'min' => 6,
                        'max' => 10,
                        'groups' => ['sylius'],
                    ]),
                ],
            ]);

            // ...

        }

        // ...

    }

Overriding forms completely
---------------------------

.. tip::

    If you need to create a new form type on top of an existing one -  create this new alternative form type and define `getParent()`
    to the old one. `See details in the Symfony docs <https://symfony.com/doc/current/form/create_custom_field_type.html>`_.

.. include:: /customization/plugins.rst.inc


text:
package hackerrank;

import org.junit.Test;

import java.io.FileInputStream;

public class StaircaseTest {
    @Test
    public void test1() throws Exception {
        System.setIn(new FileInputStream("src/test/resources/staircase/test1.txt"));
        Staircase.main(new String[]{});
    }
}


text:
.PHONY: tests clean

init:
	pip3 install -r requirements.txt
	pip3 install --editable .

tests:
	nosetests3 tests

install:
	pip3 install .

clean:
	rm -rf build
	rm -rf boilerplate.egg-info
	rm -f boilerplate/*.so


text:
<?php

namespace LPDW\Bundle\CinestationBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Search
 *
 * @ORM\Table(name="search")
 * @ORM\Entity(repositoryClass="LPDW\Bundle\CinestationBundle\Entity\SearchRepository")
 */
class Search
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="time", type="datetime")
     */
    private $time;

    protected $stations;

    /**
    * @ORM\ManyToOne(targetEntity="Line", inversedBy="searchs", cascade={"remove"})
    * @ORM\JoinColumn(name="line_id", referencedColumnName="id")
    */
    protected $line;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set time
     *
     * @param \DateTime $time
     * @return Search
     */
    public function setTime($time)
    {
        $this->time = $time;

        return $this;
    }

    /**
     * Get time
     *
     * @return \DateTime
     */
    public function getTime()
    {
        return $this->time;
    }

    /**
     * Set line
     *
     * @param \LPDW\Bundle\CinestationBundle\Entity\line $line
     * @return Search
     */
    public function setLine(\LPDW\Bundle\CinestationBundle\Entity\Line $line = null)
    {
        $this->line = $line;
        $this->setStations($this->line->getStations());

        return $this;
    }

    /**
     * Get station
     *
     * @return \LPDW\Bundle\CinestationBundle\Entity\Line
     */
    public function getLine()
    {
        return $this->line;
    }

    function __construct($line = null) {
        $this->line = $line;
    }

    public function getStations() {
        return $this->stations;
    }

    public function setStations($stations) {
        $this->stations = $stations;
    }

}


text:
package nz.gen.geek_central.view_cache_demo;

import android.graphics.PointF;
import android.graphics.RectF;

public class SampleDrawer implements Drawer
  {
    protected final RectF Bounds; /* bounds of image in user space */
    protected final int StrokeColor = 0xff240896;
    protected final int BackgroundColor = 0xffbdaa7d;
    protected final float Radius = 250.0f;
    protected final int LowComplexityLevels = 9;
    protected final int HighComplexityLevels = 12;
  /* try playing with these, for extra fun: */
    protected final float Kink = 0.7f; /* acuteness of corner bend */
    protected final float Skew = -0.2f; /* asymmetry of subdivision */
    protected int NrLevels; /* controls complexity of pattern */

    public SampleDrawer()
      {
        final float Fudge = 1.3f; /* quick-and-dirty adjust for spillover of skewed pattern */
        final float FRadius = Radius * Fudge;
        Bounds = new RectF(-FRadius, -FRadius, FRadius, FRadius);
        NrLevels = HighComplexityLevels;
      } /*SampleDrawer*/

    protected void DrawSegment
      (
        android.graphics.Path In,
        PointF From,
        PointF To,
        int Level
      )
      {
        if (Level > 0)
          {
            final PointF Mid = new PointF
              (
                (From.x + To.x) / 2.0f,
                (From.y + To.y) / 2.0f
              );
            final PointF Delta = new PointF(To.x - From.x, To.y - From.y);
            final PointF Corner = new PointF
              (
                Mid.x + Delta.y * 0.5f * Kink + Delta.x * Skew,
                Mid.y - Delta.x * 0.5f * Kink + Delta.y * Skew
              );
              /* Corner forms angle between From and To points */
          /* note reversed order of points in recursive calls so subdivided corners go opposite way */
            DrawSegment(In, To, Corner, Level - 1);
            DrawSegment(In, Corner, From, Level - 1);
          }
        else
          {
            In.moveTo(From.x, From.y);
            In.lineTo(To.x, To.y);
          } /*if*/
      } /*DrawSegment*/

    public RectF GetBounds()
      {
        return
            new RectF(Bounds);
      } /*GetBounds*/

    public void Draw
      (
        android.graphics.Canvas Dest,
        RectF DestRect
      )
      {
        final android.graphics.Matrix ViewMapping = new android.graphics.Matrix();
        ViewMapping.setRectToRect
          (
            /*src =*/ Bounds,
            /*dst =*/ DestRect,
            /*stf =*/ android.graphics.Matrix.ScaleToFit.CENTER
          );
          {
            final android.graphics.Paint BG = new android.graphics.Paint();
            BG.setStyle(android.graphics.Paint.Style.FILL);
            BG.setColor(BackgroundColor);
            Dest.drawRect(DestRect, BG);
          }
          {
            final android.graphics.Path p = new android.graphics.Path();
            DrawSegment
              (
                /*In =*/ p,
                /*From =*/ new PointF(-Radius, Radius),
                /*To =*/ new PointF(Radius, Radius),
                /*Level =*/ NrLevels
              );
            DrawSegment
              (
                /*In =*/ p,
                /*From =*/ new PointF(Radius, Radius),
                /*To =*/ new PointF(Radius, -Radius),
                /*Level =*/ NrLevels
              );
            DrawSegment
              (
                /*In =*/ p,
                /*From =*/ new PointF(Radius, -Radius),
                /*To =*/ new PointF(-Radius, -Radius),
                /*Level =*/ NrLevels
              );
            DrawSegment
              (
                /*In =*/ p,
                /*From =*/ new PointF(-Radius, -Radius),
                /*To =*/ new PointF(-Radius, Radius),
                /*Level =*/ NrLevels
              );
            p.close();
            p.transform(ViewMapping);
            final android.graphics.Paint How = new android.graphics.Paint();
            How.setAntiAlias(true);
            How.setStyle(android.graphics.Paint.Style.STROKE);
            How.setColor(StrokeColor);
            How.setStrokeWidth(2.0f); /* note this is not scaled by ViewMapping */
            Dest.drawPath(p, How);
          }
      } /*Draw*/

    public void SetComplexity
      (
        boolean High /* false for low complexity */
      )
      {
        NrLevels = High ? HighComplexityLevels : LowComplexityLevels;
      } /*SetComplexity*/

    public boolean GetComplexity()
      {
        return
            NrLevels != LowComplexityLevels;
      } /*GetComplexity*/

  } /*SampleDrawer*/


text:
layout: blog_by_category
permalink: /blog/category/productivity/
category: productivity
title: Productivity
---


text:
// .NAME vtkTypeTemplate - Provides the equivalent of vtkTypeMacro
// for use with template classes
//
// .SECTION Thanks
// Developed by Timothy M. Shead (tshead@sandia.gov) at Sandia National Laboratories.

#ifndef vtkTypeTemplate_h
#define vtkTypeTemplate_h

#include "vtkObjectBase.h"
#include <string>
#include <typeinfo>

template<class ThisT, class BaseT>
class vtkTypeTemplate :
  public BaseT
{
public:
  typedef BaseT Superclass;

  ThisT* NewInstance() const
  {
    return ThisT::SafeDownCast(this->NewInstanceInternal());
  }

  static ThisT* SafeDownCast(vtkObjectBase* o)
  {
    if(o &&
       o->IsA(vtkTypeTemplate<ThisT, BaseT>::GetClassNameInternalCachedName()))
      {
      return static_cast<ThisT*>(o);
      }

    return 0;
  }

protected:
  virtual vtkObjectBase* NewInstanceInternal() const
  {
    return ThisT::New();
  }

  // We don't expose this publicly, because the typename we generate
  // for our template instantiations isn't human-readable, unlike
  // "normal" VTK classes.
  static int IsTypeOf(const char* type)
  {
    if (strcmp(vtkTypeTemplate<ThisT, BaseT>::GetClassNameInternalCachedName(),
               type) == 0)
      {
      return 1;
      }
    return BaseT::IsTypeOf(type);
  }

  // We don't expose this publicly, because the typename we generate
  // for our template instantiations isn't human-readable, unlike
  // "normal" VTK classes.
  virtual int IsA(const char *type)
  {
    return this->IsTypeOf(type);
  }

  vtkTypeTemplate() {}

private:
  // not implemented:
  vtkTypeTemplate(const vtkTypeTemplate<ThisT, BaseT>&);
  void operator=(const vtkTypeTemplate<ThisT, BaseT>&);

  static const char* GetClassNameInternalCachedName()
  {
    static std::string thisType(typeid(ThisT).name());
    return thisType.c_str();
  }

  virtual const char* GetClassNameInternal() const
  {
    return this->GetClassNameInternalCachedName();
  }
};

#endif

// VTK-HeaderTest-Exclude: vtkTypeTemplate.h


text:
/* $Xorg: DPMS.c,v 1.3 2000/08/17 19:45:50 cpqbld Exp $ */
/*****************************************************************

Copyright (c) 1996 Digital Equipment Corporation, Maynard, Massachusetts.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software.

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

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

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

******************************************************************/
/* $XFree86: xc/lib/Xext/DPMS.c,v 3.5 2002/10/16 00:37:27 dawes Exp $ */

/*
 * HISTORY
 */

#define NEED_REPLIES
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <X11/Xlibint.h>
#include <X11/extensions/dpms.h>
#include <X11/extensions/dpmsstr.h>
#include <X11/extensions/Xext.h>
#include <X11/extensions/extutil.h>
#include <stdio.h>

static XExtensionInfo _dpms_info_data;
static XExtensionInfo *dpms_info = &_dpms_info_data;
static char *dpms_extension_name = DPMSExtensionName;

#define DPMSCheckExtension(dpy,i,val) \
  XextCheckExtension (dpy, i, dpms_extension_name, val)

/*****************************************************************************
 *                                                                           *
 *                         private utility routines                          *
 *                                                                           *
 *****************************************************************************/

static int close_display(Display *dpy, XExtCodes *codes);
static /* const */ XExtensionHooks dpms_extension_hooks = {
    NULL,                               /* create_gc */
    NULL,                               /* copy_gc */
    NULL,                               /* flush_gc */
    NULL,                               /* free_gc */
    NULL,                               /* create_font */
    NULL,                               /* free_font */
    close_display,                      /* close_display */
    NULL,                               /* wire_to_event */
    NULL,                               /* event_to_wire */
    NULL,                               /* error */
    NULL                                /* error_string */
};

static XEXT_GENERATE_FIND_DISPLAY (find_display, dpms_info,
				   dpms_extension_name,
                                   &dpms_extension_hooks, DPMSNumberEvents,
                                   NULL)

static XEXT_GENERATE_CLOSE_DISPLAY (close_display, dpms_info)

/*****************************************************************************
 *                                                                           *
 *                  public routines                                          *
 *                                                                           *
 *****************************************************************************/

Bool
DPMSQueryExtension (Display *dpy, int *event_basep, int *error_basep)
{
    XExtDisplayInfo *info = find_display (dpy);

    if (XextHasExtension(info)) {
	*event_basep = info->codes->first_event;
	*error_basep = info->codes->first_error;
	return True;
    } else {
	return False;
    }
}

Status
DPMSGetVersion(Display *dpy, int *major_versionp, int *minor_versionp)
{
    XExtDisplayInfo *info = find_display (dpy);
    xDPMSGetVersionReply	    rep;
    register xDPMSGetVersionReq  *req;

    DPMSCheckExtension (dpy, info, 0);

    LockDisplay (dpy);
    GetReq (DPMSGetVersion, req);
    req->reqType = info->codes->major_opcode;
    req->dpmsReqType = X_DPMSGetVersion;
    if (!_XReply (dpy, (xReply *) &rep, 0, xTrue)) {
	UnlockDisplay (dpy);
	SyncHandle ();
	return 0;
    }
    *major_versionp = rep.majorVersion;
    *minor_versionp = rep.minorVersion;
    UnlockDisplay (dpy);
    SyncHandle ();
    return 1;
}

Bool
DPMSCapable(Display *dpy)
{
    XExtDisplayInfo *info = find_display (dpy);
    register xDPMSCapableReq *req;
    xDPMSCapableReply rep;

    DPMSCheckExtension (dpy, info, 0);

    LockDisplay(dpy);
    GetReq(DPMSCapable, req);
    req->reqType = info->codes->major_opcode;
    req->dpmsReqType = X_DPMSCapable;

    if (!_XReply(dpy, (xReply *)&rep, 0, xFalse)) {
	UnlockDisplay(dpy);
	SyncHandle();
	return False;
    }
    UnlockDisplay(dpy);
    SyncHandle();
    return rep.capable;
}

Status
DPMSSetTimeouts(Display *dpy, CARD16 standby, CARD16 suspend, CARD16 off)
{
    XExtDisplayInfo *info = find_display (dpy);
    register xDPMSSetTimeoutsReq *req;

    if ((off != 0)&&(off < suspend))
    {
	return BadValue;
    }
    if ((suspend != 0)&&(suspend < standby))
    {
	return BadValue;
    }

    DPMSCheckExtension (dpy, info, 0);
    LockDisplay(dpy);
    GetReq(DPMSSetTimeouts, req);
    req->reqType = info->codes->major_opcode;
    req->dpmsReqType = X_DPMSSetTimeouts;
    req->standby = standby;
    req->suspend = suspend;
    req->off = off;

    UnlockDisplay(dpy);
    SyncHandle();
    return 1;
}

Bool
DPMSGetTimeouts(Display *dpy, CARD16 *standby, CARD16 *suspend, CARD16 *off)
{
    XExtDisplayInfo *info = find_display (dpy);
    register xDPMSGetTimeoutsReq *req;
    xDPMSGetTimeoutsReply rep;

    DPMSCheckExtension (dpy, info, 0);

    LockDisplay(dpy);
    GetReq(DPMSGetTimeouts, req);
    req->reqType = info->codes->major_opcode;
    req->dpmsReqType = X_DPMSGetTimeouts;

    if (!_XReply(dpy, (xReply *)&rep, 0, xTrue)) {
	UnlockDisplay(dpy);
	SyncHandle();
	return False;
    }
    UnlockDisplay(dpy);
    SyncHandle();
    *standby = rep.standby;
    *suspend = rep.suspend;
    *off = rep.off;
    return 1;
}

Status
DPMSEnable(Display *dpy)
{
    XExtDisplayInfo *info = find_display (dpy);
    register xDPMSEnableReq *req;

    DPMSCheckExtension (dpy, info, 0);
    LockDisplay(dpy);
    GetReq(DPMSEnable, req);
    req->reqType = info->codes->major_opcode;
    req->dpmsReqType = X_DPMSEnable;

    UnlockDisplay(dpy);
    SyncHandle();
    return 1;
}

Status
DPMSDisable(Display *dpy)
{
    XExtDisplayInfo *info = find_display (dpy);
    register xDPMSDisableReq *req;

    DPMSCheckExtension (dpy, info, 0);
    LockDisplay(dpy);
    GetReq(DPMSDisable, req);
    req->reqType = info->codes->major_opcode;
    req->dpmsReqType = X_DPMSDisable;

    UnlockDisplay(dpy);
    SyncHandle();
    return 1;
}

Status
DPMSForceLevel(Display *dpy, CARD16 level)
{
    XExtDisplayInfo *info = find_display (dpy);
    register xDPMSForceLevelReq *req;

    DPMSCheckExtension (dpy, info, 0);

    if ((level != DPMSModeOn) &&
	(level != DPMSModeStandby) &&
	(level != DPMSModeSuspend) &&
	(level != DPMSModeOff))
	return BadValue;

    LockDisplay(dpy);
    GetReq(DPMSForceLevel, req);
    req->reqType = info->codes->major_opcode;
    req->dpmsReqType = X_DPMSForceLevel;
    req->level = level;

    UnlockDisplay(dpy);
    SyncHandle();
    return 1;
}

Status
DPMSInfo(Display *dpy, CARD16 *power_level, BOOL *state)
{
    XExtDisplayInfo *info = find_display (dpy);
    register xDPMSInfoReq *req;
    xDPMSInfoReply rep;

    DPMSCheckExtension (dpy, info, 0);

    LockDisplay(dpy);
    GetReq(DPMSInfo, req);
    req->reqType = info->codes->major_opcode;
    req->dpmsReqType = X_DPMSInfo;

    if (!_XReply(dpy, (xReply *)&rep, 0, xTrue)) {
	UnlockDisplay(dpy);
	SyncHandle();
	return False;
    }
    UnlockDisplay(dpy);
    SyncHandle();
    *power_level = rep.power_level;
    *state = rep.state;
    return 1;
}


text:
package org.apache.hyracks.storage.am.lsm.btree.impls;

import java.util.LinkedList;
import java.util.List;

import org.apache.hyracks.api.dataflow.value.IBinaryComparatorFactory;
import org.apache.hyracks.storage.am.btree.api.IBTreeLeafFrame;
import org.apache.hyracks.storage.am.btree.impls.BTree;
import org.apache.hyracks.storage.am.btree.impls.BTreeOpContext;
import org.apache.hyracks.storage.am.common.api.IModificationOperationCallback;
import org.apache.hyracks.storage.am.common.api.ISearchOperationCallback;
import org.apache.hyracks.storage.am.common.api.ISearchPredicate;
import org.apache.hyracks.storage.am.common.api.ITreeIndexFrameFactory;
import org.apache.hyracks.storage.am.common.impls.NoOpOperationCallback;
import org.apache.hyracks.storage.am.common.ophelpers.IndexOperation;
import org.apache.hyracks.storage.am.common.ophelpers.MultiComparator;
import org.apache.hyracks.storage.am.common.tuples.PermutingTupleReference;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMComponent;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMIndexOperationContext;

public final class LSMBTreeOpContext implements ILSMIndexOperationContext {

    public ITreeIndexFrameFactory insertLeafFrameFactory;
    public ITreeIndexFrameFactory deleteLeafFrameFactory;
    public IBTreeLeafFrame insertLeafFrame;
    public IBTreeLeafFrame deleteLeafFrame;
    public final BTree[] mutableBTrees;
    public BTree.BTreeAccessor[] mutableBTreeAccessors;
    public BTreeOpContext[] mutableBTreeOpCtxs;
    public BTree.BTreeAccessor currentMutableBTreeAccessor;
    public BTreeOpContext currentMutableBTreeOpCtx;
    public IndexOperation op;
    public final MultiComparator cmp;
    public final MultiComparator bloomFilterCmp;
    public final IModificationOperationCallback modificationCallback;
    public final ISearchOperationCallback searchCallback;
    private final List<ILSMComponent> componentHolder;
    private final List<ILSMComponent> componentsToBeMerged;
    private final List<ILSMComponent> componentsToBeReplicated;
    public final PermutingTupleReference indexTuple;
    public final MultiComparator filterCmp;
    public final PermutingTupleReference filterTuple;
    public ISearchPredicate searchPredicate;

    public LSMBTreeOpContext(List<ILSMComponent> mutableComponents, ITreeIndexFrameFactory insertLeafFrameFactory,
            ITreeIndexFrameFactory deleteLeafFrameFactory, IModificationOperationCallback modificationCallback,
            ISearchOperationCallback searchCallback, int numBloomFilterKeyFields, int[] btreeFields, int[] filterFields) {
        LSMBTreeMemoryComponent c = (LSMBTreeMemoryComponent) mutableComponents.get(0);
        IBinaryComparatorFactory cmpFactories[] = c.getBTree().getComparatorFactories();
        if (cmpFactories[0] != null) {
            this.cmp = MultiComparator.create(c.getBTree().getComparatorFactories());
        } else {
            this.cmp = null;
        }

        bloomFilterCmp = MultiComparator.create(c.getBTree().getComparatorFactories(), 0, numBloomFilterKeyFields);

        mutableBTrees = new BTree[mutableComponents.size()];
        mutableBTreeAccessors = new BTree.BTreeAccessor[mutableComponents.size()];
        mutableBTreeOpCtxs = new BTreeOpContext[mutableComponents.size()];
        for (int i = 0; i < mutableComponents.size(); i++) {
            LSMBTreeMemoryComponent mutableComponent = (LSMBTreeMemoryComponent) mutableComponents.get(i);
            mutableBTrees[i] = mutableComponent.getBTree();
            mutableBTreeAccessors[i] = (BTree.BTreeAccessor) mutableBTrees[i].createAccessor(modificationCallback,
                    NoOpOperationCallback.INSTANCE);
            mutableBTreeOpCtxs[i] = mutableBTreeAccessors[i].getOpContext();
        }

        this.insertLeafFrameFactory = insertLeafFrameFactory;
        this.deleteLeafFrameFactory = deleteLeafFrameFactory;
        this.insertLeafFrame = (IBTreeLeafFrame) insertLeafFrameFactory.createFrame();
        this.deleteLeafFrame = (IBTreeLeafFrame) deleteLeafFrameFactory.createFrame();
        if (insertLeafFrame != null && this.cmp != null) {
            insertLeafFrame.setMultiComparator(cmp);
        }
        if (deleteLeafFrame != null && this.cmp != null) {
            deleteLeafFrame.setMultiComparator(cmp);
        }
        this.componentHolder = new LinkedList<ILSMComponent>();
        this.componentsToBeMerged = new LinkedList<ILSMComponent>();
        this.componentsToBeReplicated = new LinkedList<ILSMComponent>();
        this.modificationCallback = modificationCallback;
        this.searchCallback = searchCallback;

        if (filterFields != null) {
            indexTuple = new PermutingTupleReference(btreeFields);
            filterCmp = MultiComparator.create(c.getLSMComponentFilter().getFilterCmpFactories());
            filterTuple = new PermutingTupleReference(filterFields);
        } else {
            indexTuple = null;
            filterCmp = null;
            filterTuple = null;
        }
    }

    @Override
    public void setOperation(IndexOperation newOp) {
        reset();
        this.op = newOp;
    }

    public void setInsertMode() {
        currentMutableBTreeOpCtx.leafFrame = insertLeafFrame;
        currentMutableBTreeOpCtx.leafFrameFactory = insertLeafFrameFactory;
    }

    public void setDeleteMode() {
        currentMutableBTreeOpCtx.leafFrame = deleteLeafFrame;
        currentMutableBTreeOpCtx.leafFrameFactory = deleteLeafFrameFactory;
    }

    @Override
    public void reset() {
        componentHolder.clear();
        componentsToBeMerged.clear();
        componentsToBeReplicated.clear();
    }

    public IndexOperation getOperation() {
        return op;
    }

    @Override
    public List<ILSMComponent> getComponentHolder() {
        return componentHolder;
    }

    @Override
    public ISearchOperationCallback getSearchOperationCallback() {
        return searchCallback;
    }

    @Override
    public IModificationOperationCallback getModificationCallback() {
        return modificationCallback;
    }

    @Override
    public void setCurrentMutableComponentId(int currentMutableComponentId) {
        currentMutableBTreeAccessor = mutableBTreeAccessors[currentMutableComponentId];
        currentMutableBTreeOpCtx = mutableBTreeOpCtxs[currentMutableComponentId];
        switch (op) {
            case SEARCH:
                break;
            case DISKORDERSCAN:
            case UPDATE:
                // Attention: It is important to leave the leafFrame and
                // leafFrameFactory of the mutableBTree as is when doing an update.
                // Update will only be set if a previous attempt to delete or
                // insert failed, so we must preserve the semantics of the
                // previously requested operation.
                break;
            case UPSERT:
            case INSERT:
                setInsertMode();
                break;
            case PHYSICALDELETE:
            case DELETE:
                setDeleteMode();
                break;
        }
    }

    @Override
    public List<ILSMComponent> getComponentsToBeMerged() {
        return componentsToBeMerged;
    }

    @Override
    public void setSearchPredicate(ISearchPredicate searchPredicate) {
        this.searchPredicate = searchPredicate;
    }

    @Override
    public ISearchPredicate getSearchPredicate() {
        return searchPredicate;
    }

    @Override
    public List<ILSMComponent> getComponentsToBeReplicated() {
        return componentsToBeReplicated;
    }
}


text:
import sys
import re
import os
import shutil
import commands

"""Copy Special exercise
"""

# +++your code here+++
# Write functions and modify main() to call them

# Return absolute paths of files in a given directory
def get_special_paths(dir):
  filenames = os.listdir(dir)
  paths = []
  for filename in filenames:
    if re.search(r'__\w+__', filename):
      paths.append(os.path.abspath(os.path.join(dir, filename)))
  return paths

# Copy files into a given directory
def copy_to(paths, dir):
  if not os.path.exists(dir):
    os.mkdir(dir)
  for filename in paths:
    shutil.copy(filename, dir)

# Zip files up into a given zipfile
def zip_to(paths, zippath):
  cmd = 'zip -j ' + zippath + ' ' + ' '.join(paths)
  (status, output) = commands.getstatusoutput(cmd)
  if status:
    sys.stderr.write(output)
    sys.exit(1)

def main():
  # This basic command line argument parsing code is provided.
  # Add code to call your functions below.

  # Make a list of command line arguments, omitting the [0] element
  # which is the script itself.
  args = sys.argv[1:]
  if not args:
    print "usage: [--todir dir][--tozip zipfile] dir [dir ...]";
    sys.exit(1)

  # todir and tozip are either set from command line
  # or left as the empty string.
  # The args array is left just containing the dirs.
  todir = ''
  if args[0] == '--todir':
    todir = args[1]
    del args[0:2]

  tozip = ''
  if args[0] == '--tozip':
    tozip = args[1]
    del args[0:2]

  if len(args) == 0:
    print "error: must specify one or more dirs"
    sys.exit(1)

  paths = []
  for dir in args:
    paths.extend(get_special_paths(dir))

  if len(todir) > 0:
    copy_to(paths, todir)
  elif len(tozip) > 0:
    zip_to(paths, tozip)
  else:
    for path in paths:
      print path

if __name__ == "__main__":
  main()


text:
package petablox.program;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Collections;
import java.io.InputStream;
import java.io.DataInputStream;
import java.io.DataInput;
import java.io.IOException;

import joeq.Class.jq_ClassFileConstants;
import joeq.UTF.Utf8;
import petablox.project.Config;
import petablox.project.Messages;
import petablox.util.ArraySet;
import petablox.util.Utils;
import petablox.util.soot.Classpath;
import petablox.util.soot.ClasspathElement;
import petablox.util.tuple.object.Pair;

/**
 * Class hierarchy implementation.
 *
 * @author Mayur Naik (mhn@cs.stanford.edu)
 */
public class ClassHierarchy {
    private static final String IGNORED_DUPLICATE_TYPES =
        "INFO: Class hierarchy builder: Ignored the following duplicate classes/interfaces coming from the indicated classpath elements:";
    private static final String EXCLUDED_TYPES_IN_CHORD =
        "WARN: Excluded the following classes/interfaces from scope because the classpath elements from which they originate are in petablox.main.class.path:";
    private static final String EXCLUDED_TYPES_NOT_DYN_LOADED =
        "WARN: Excluded the following classes/interfaces from scope because they were not loaded dynamically and petablox.ch.dynamic=true:";
    private static final String MISSING_TYPES =
        "WARN: Class hierarchy builder: Following classes/interfaces were not found in scope but each of them was either declared as a superclass or an implemented/extended interface of some class/interface in scope:";
    private static final String MISSING_SUPERCLASSES =
        "WARN: Class hierarchy builder: Ignored the following classes as some (direct or transitive) superclass of each of them is missing in scope:";
    private static final String MISSING_SUPERINTERFS =
        "WARN: Class hierarchy builder: Ignored the following classes/interfaces as some (direct or transitive) interface implemented/extended by each of them is missing in scope:";

    /**
     * Map from each class or interface in scope to the kind of its type (interface, abstract class, or concrete class).
     */
    private Map<String, TypeKind> clintToKind;
    /**
     * Map from each (concrete or abstract) class c in scope to the class d (not necessarily in scope) such that:
     * 1. if c == java.lang.Object then d == null, and
     * 2. if c is a class other than java.lang.Object then d is the declared superclass of c.
     * Note that c cannot be an interface.
     */
    private Map<String, String> classToDeclaredSuperclass;
    /**
     * Map from each class/interface c in scope to the set of interfaces S (not necessarily in scope) such that:
     * 1. if c is an interface then S is the set of interfaces that c declares it extends, and
     * 2. if c is a class then S is the set of interfaces that c declares it implements.
     */
    private Map<String, Set<String>> clintToDeclaredInterfaces;
    /**
     * Map from:
     * 1. each (concrete or abstract) class in scope to the set of all its concrete subclasses in scope (including itself if it is concrete).
     * 2. each interface in scope to the set of all concrete classes in scope that implement it.
     */
    private Map<String, Set<String>> clintToAllConcreteSubs;

    /**
     * Set consisting of:
     * 1. each class not in scope but declared as the superclass of some class in scope, and
     * 2. each interface not in scope but declared as an implemented/extended interface of some class/interface respectively in scope.
     */
    private Set<String> missingClints;

    public String getDeclaredSuperclass(String c) {
        if (classToDeclaredSuperclass == null)
            build();
        return classToDeclaredSuperclass.get(c);
    }

    public Set<String> getDeclaredInterfaces(String t) {
        if (clintToDeclaredInterfaces == null)
            build();
        return clintToDeclaredInterfaces.get(t);
    }

    /**
     * Provides the set of all concrete classes that subclass/implement a given class/interface.
     *
     * @param s The name of a class or interface.
     *
     * @return The set of all concrete classes that subclass/implement (directly or transitively) the
     *         class/interface named s, if it exists in the class hierarchy, and null otherwise.
     */
    public Set<String> getConcreteSubclasses(final String s) {
        if (clintToAllConcreteSubs == null) {
            if (clintToKind == null)
                build();
            missingClints = new HashSet<String>();
            Set<String> missingSuperclasses = new HashSet<String>();
            Set<String> missingSuperInterfs = new HashSet<String>();
            // Map from each concrete class in scope to set containing
            // itself and its (direct and transitive) superclasses and
            // its implemented interfaces (not necessarily in scope).
            Map<String, Set<String>> concreteClassToAllSups =
                new HashMap<String, Set<String>>();
            clintToAllConcreteSubs = new HashMap<String, Set<String>>();
            Set<String> emptyRdOnlySet = Collections.emptySet();
            for (String c : clintToKind.keySet()) {
                clintToAllConcreteSubs.put(c, emptyRdOnlySet);
                if (clintToKind.get(c) != TypeKind.CONCRETE_CLASS)
                    continue;
                Set<String> clints = new ArraySet<String>(2);
                clints.add(c);  // every concrete class is a concrete successor to itself
                boolean success1 = true;
                boolean success2 = true;
                String d = c;
                while (true) {
                    success2 &= populateInterfaces(d, clints);
                    String superClass = classToDeclaredSuperclass.get(d);
                    if (superClass == null) {
                        if (!d.equals("java.lang.Object")) {
                            missingClints.add(d);
                            success1 = false;
                        }
                        break;
                    }
                    boolean added = clints.add(superClass);
                    assert (added);
                    d = superClass;
                }
                if (success1 && success2) {
                    concreteClassToAllSups.put(c, clints);
                    continue;
                }
                if (!success1)
                    missingSuperclasses.add(c);
                if (!success2)
                    missingSuperInterfs.add(c);
            }
            if (!missingClints.isEmpty()) {
                Messages.log(MISSING_TYPES);
                for (String c : missingClints)
                    Messages.log("\t" + c);
            }
            if (!missingSuperclasses.isEmpty()) {
                Messages.log(MISSING_SUPERCLASSES);
                for (String c : missingSuperclasses)
                    Messages.log("\t" + c);
            }
            if (!missingSuperInterfs.isEmpty()) {
                Messages.log(MISSING_SUPERINTERFS);
                for (String c : missingSuperInterfs)
                    Messages.log("\t" + c);
            }
            for (String c : concreteClassToAllSups.keySet()) {
                Set<String> sups = concreteClassToAllSups.get(c);
                for (String d : sups) {
                    Set<String> subs = clintToAllConcreteSubs.get(d);
                    if (subs == null || subs == emptyRdOnlySet) {
                        subs = new ArraySet<String>(2);
                        clintToAllConcreteSubs.put(d, subs);
                    }
                    subs.add(c);
                }
            }
            missingClints.clear();
        }

        return clintToAllConcreteSubs.get(s);
    }

    // builds maps clintToKind, classToDeclaredSuperclass, and clintToDeclaredInterfaces
    private void build() {
        System.out.println("Starting to build class hierarchy; this may take a while ...");
        Set<String> dynLoadedTypes = null;
        if (Config.CHkind.equals("dynamic")) {
            List<String> list = Program.g().getDynamicallyLoadedClasses();
            dynLoadedTypes = new HashSet<String>(list.size());
            dynLoadedTypes.addAll(list);
        }
        Classpath cp = new Classpath();
        cp.addToClasspath(System.getProperty("sun.boot.class.path"));
        cp.addExtClasspath();
        cp.addToClasspath(Config.userClassPathName);
        List<ClasspathElement> cpeList = cp.getClasspathElements();

        // logging info
        List<Pair<String, String>> duplicateTypes = new ArrayList<Pair<String, String>>();
        List<String> excludedTypes = new ArrayList<String>();
        List<String> typesNotDynLoaded = new ArrayList<String>();

        clintToKind = new HashMap<String, TypeKind>();
        classToDeclaredSuperclass = new HashMap<String, String>();
        clintToDeclaredInterfaces = new HashMap<String, Set<String>>();

        for (ClasspathElement cpe : cpeList) {
            for (String fileName : cpe.getEntries()) {
                if (!fileName.endsWith(".class"))
                    continue;
                String baseName = fileName.substring(0, fileName.length() - 6);
                String typeName = baseName.replace('/', '.');

                // ignore types excluded from scope
                if (Config.isExcludedFromScope(typeName)) {
                    excludedTypes.add(typeName);
                    continue;
                }

                // ignore duplicate types in classpath
                if (clintToKind.containsKey(typeName)) {
                    duplicateTypes.add(new Pair<String, String>(typeName, cpe.toString()));
                    continue;
                }

                if (dynLoadedTypes != null && !dynLoadedTypes.contains(typeName)) {
                    typesNotDynLoaded.add(typeName);
                    continue;
                }
                InputStream is = cpe.getResourceAsStream(fileName);
                assert (is != null);
                DataInputStream in = new DataInputStream(is);
                if (Config.verbose >= 2)
                    Messages.log("Processing class file %s from %s", fileName, cpe);
                processClassFile(in, typeName);
            }
        }

        if (Config.verbose >= 2) {
            if (!duplicateTypes.isEmpty()) {
                Messages.log(IGNORED_DUPLICATE_TYPES);
                for (Pair<String, String> p : duplicateTypes)
                    Messages.log("\t%s, %s", p.val0, p.val1);
            }
            if (!excludedTypes.isEmpty()) {
                Messages.log(EXCLUDED_TYPES_IN_CHORD);
                for (String s : excludedTypes)
                    Messages.log("\t" + s);
            }
            if (!typesNotDynLoaded.isEmpty()) {
                Messages.log(EXCLUDED_TYPES_NOT_DYN_LOADED);
                for (String s : typesNotDynLoaded)
                    Messages.log("\t" + s);
            }
        }
        System.out.println("Finished building class hierarchy.");
    }

    // Description of superclass and interfaces sections in class file of class c:
    // 1. superclass d:
    //   if c is an interface then d is java.lang.Object
    //   if c == java.lang.Object then d is null (has index 0 in constant pool)
    //   if c is a class other than java.lang.Object then d is the declared superclass of c
    // 2. interfaces S:
    //   if c is an interface then S is the set of interfaces c declares it extends
    //   if c is a class then S is the set of interfaces c declares it implements
    private void processClassFile(DataInputStream in, String className) {
        try {
            int magicNum = in.readInt(); // 0xCAFEBABE
            if (magicNum != 0xCAFEBABE) {
                throw new ClassFormatError("bad magic number: " + Integer.toHexString(magicNum));
            }
            in.readUnsignedShort(); // read minor_version
            in.readUnsignedShort(); // read major_version
            int constant_pool_count = in.readUnsignedShort();
            Object[] constant_pool = processConstantPool(in, constant_pool_count);
            char access_flags = (char) in.readUnsignedShort();  // read access_flags
            int self_index = in.readUnsignedShort();
            int super_index = in.readUnsignedShort();
            if (super_index == 0) {
                assert (className.equals("java.lang.Object"));
                classToDeclaredSuperclass.put(className, null);
                clintToKind.put(className, TypeKind.CONCRETE_CLASS);
            } else {
                int c = (Integer) constant_pool[super_index];
                Utf8 utf8 = (Utf8) constant_pool[c];
                String superclassName = utf8.toString().replace('/', '.');
                if (isInterface(access_flags)) {
                    assert (superclassName.equals("java.lang.Object"));
                    clintToKind.put(className, TypeKind.INTERFACE);
                } else {
                    classToDeclaredSuperclass.put(className, superclassName);
                    if (isAbstract(access_flags))
                        clintToKind.put(className, TypeKind.ABSTRACT_CLASS);
                    else
                        clintToKind.put(className, TypeKind.CONCRETE_CLASS);
                }
            }
            int n_interfaces = (int) in.readUnsignedShort();
            Set<String> interfaces = new ArraySet<String>(n_interfaces);
            clintToDeclaredInterfaces.put(className, interfaces);
            for (int i = 0; i < n_interfaces; ++i) {
                int interface_index = in.readUnsignedShort();
                int c = (Integer) constant_pool[interface_index];
                Utf8 utf8 = (Utf8) constant_pool[c];
                String interfaceName = utf8.toString().replace('/', '.');
                interfaces.add(interfaceName);
            }
            in.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            System.exit(1);
        }
    }

    private static boolean isInterface(char access_flags) {
        return (access_flags & jq_ClassFileConstants.ACC_INTERFACE) != 0;
    }

    private static boolean isAbstract(char access_flags) {
        return (access_flags & jq_ClassFileConstants.ACC_ABSTRACT) != 0;
    }

    private boolean populateInterfaces(String c, Set<String> result) {
        Set<String> interfaces = clintToDeclaredInterfaces.get(c);
        if (interfaces == null) {
            missingClints.add(c);
            return false;
        }
        boolean success = true;
        for (String d : interfaces) {
            if (result.add(d)) {
                success &= populateInterfaces(d, result);
            }
        }
        return success;
    }

    private Object[] processConstantPool(DataInput in, int size) throws IOException {
        Object[] constant_pool = new Object[size];
        for (int i = 1; i < size; ++i) { // CP slot 0 is unused
            byte b = in.readByte();
            switch (b) {
            case jq_ClassFileConstants.CONSTANT_Integer:
                in.readInt();
                break;
            case jq_ClassFileConstants.CONSTANT_Float:
                in.readFloat();
                break;
            case jq_ClassFileConstants.CONSTANT_Long:
                ++i;
                in.readLong();
                break;
            case jq_ClassFileConstants.CONSTANT_Double:
                ++i;
                in.readDouble();
                break;
            case jq_ClassFileConstants.CONSTANT_Utf8:
            {
                byte utf[] = new byte[in.readUnsignedShort()];
                in.readFully(utf);
                constant_pool[i] = Utf8.get(utf);
                break;
            }
            case jq_ClassFileConstants.CONSTANT_Class:
                constant_pool[i] = new Integer(in.readUnsignedShort());
                break;
            case jq_ClassFileConstants.CONSTANT_String:
                in.readUnsignedShort();
                break;
            case jq_ClassFileConstants.CONSTANT_NameAndType:
            case jq_ClassFileConstants.CONSTANT_FieldRef:
            case jq_ClassFileConstants.CONSTANT_MethodRef:
            case jq_ClassFileConstants.CONSTANT_InterfaceMethodRef:
                in.readUnsignedShort();
                in.readUnsignedShort();
                break;
            default:
                throw new ClassFormatError("bad constant pool entry tag: entry="+i+", tag="+b);
            }
        }
        return constant_pool;
    }

    /**
     * Returns the set of every class name examined by ClassHierarchy
     */
    public Set<String> allClassNamesInPath() {
        if (clintToKind == null)
            build();
        return clintToKind.keySet();
    }
}


text:
__authors__ = [
  '"Leo (Chong Liu)" <HiddenPython@gmail.com>',
  ]

import datetime
import httplib

from google.appengine.api import users
from google.appengine.ext import db

from soc.logic.models.host import logic as host_logic
from soc.logic.models.sponsor import logic as sponsor_logic
from soc.logic.models.timeline import logic as timeline_logic
from soc.logic.models.user import logic as user_logic

from soc.modules.gsoc.logic.models.grading_record import logic \
    as grading_record_logic
from soc.modules.gsoc.logic.models.grading_survey_group import logic \
    as survey_group_logic
from soc.modules.gsoc.logic.models.mentor import logic as mentor_logic
from soc.modules.gsoc.logic.models.program import logic as program_logic
from soc.modules.gsoc.logic.models.org_admin import logic \
    as gsoc_org_admin_logic
from soc.modules.gsoc.logic.models.organization import logic \
    as gsoc_organization_logic
from soc.modules.gsoc.logic.models.student import logic as student_logic
from soc.modules.gsoc.logic.models.student_project import logic \
    as student_project_logic
from soc.modules.gsoc.logic.models.survey import project_logic \
    as project_survey_logic
from soc.modules.gsoc.logic.models.survey import grading_logic \
    as grading_survey_logic

from soc.tasks.grading_survey_group import DEF_BATCH_SIZE

from tests.test_utils import DjangoTestCase
from tests.test_utils import MailTestCase
from tests.test_utils import TaskQueueTestCase

class GradingSurveyGroupTasksTest(DjangoTestCase,
                                  TaskQueueTestCase,
                                  MailTestCase):
  """Tests related to the soc.tasks.grading_survey_group view.
  """

  def setUp(self):
    """Set up required for the view tests.
    """
    # Setup TaskQueueTestCase and MailTestCase first
    super(GradingSurveyGroupTasksTest, self).setUp()
    # Create a user for the founder of sponsor
    email = "a_sponsor@example.com"
    account = users.User(email=email)
    link_id = 'a_sponsor_user'
    name = 'A Sponsor User'
    sponsor_user_properties = {
        'account': account,
        'link_id': link_id,
        'name': name,
        }
    sponsor_user = user_logic.updateOrCreateFromFields(sponsor_user_properties)
    # Create sponsor
    link_id = 'a_sponsor'
    name = 'A Sponsor'
    founder = 'a_founder'
    phone = '01234567'
    contact_postalcode = 'A postalcode'
    description = 'A description'
    contact_country = 'United States'
    short_name = 'AS'
    contact_city = 'A city'
    home_page = 'http://www.asponsor.com'
    email = 'email@asponsor.com'
    sponsor_properties = {
        'link_id': link_id,
        'name': name,
        'short_name': short_name,
        'founder': sponsor_user,
        'phone': phone,
        'description': description,
        'contact_country': contact_country,
       'contact_city': 'A City',
       'contact_street': 'A Street',
        'contact_postalcode': contact_postalcode,
        'home_page': home_page,
        'email': email,
        'status': 'active',
        }
    sponsor = sponsor_logic.updateOrCreateFromFields(sponsor_properties)
    # Create a timeline for a program
    timeline_properties = {
        'link_id': 'a_program',
        'scope_path': 'a_sponsor',
        'scope': sponsor,
          }
    timeline = timeline_logic.updateOrCreateFromFields(timeline_properties)
    # Create a program for a_sponsor
    program_properties = {
        'key_name': 'a_sponsor/a_program',
        'link_id': 'a_program',
        'scope': sponsor,
        'scope_path': 'a_sponsor',
        'name': 'A Program 2010',
        'short_name': 'AP2010',
        'group_label': 'AP',
        'description': 'This is the program for AP2010.',
        'apps_tasks_limit': 42,
        'slots': 42,
        'allocations_visible': True,
        'timeline': timeline,
        'status': 'visible',
        }
    # GSoC program logic does not work: error in updatePredefinedOrgTags
    from soc.modules.gsoc.models.program import GSoCProgram
    program = GSoCProgram(**program_properties)
    program.put()
    self.program = program
    # Create an organization for a_program
    organization_properties = {
      'link_id': 'an_org',
      'name': 'An Organization',
      'short_name': 'AO',
      'scope_path': 'a_sponsor/a_program',
      'scope': program,
      'founder': sponsor_user,
      'home_page': 'http://www.an_org.com',
      'phone': '1-555-2222',
      'description': 'An Organization',
      'license_name': 'Apache License',
      'ideas': 'http://www.an_org.com/ideas',
        'contact_country': contact_country,
       'contact_city': 'A City',
       'contact_street': 'A Street',
        'contact_postalcode': contact_postalcode,
        'home_page': home_page,
        'email': email,
        'status': 'active',
      }
    organization = gsoc_organization_logic.updateOrCreateFromFields(
        organization_properties)
    # Create a user for all roles except sponsor
    email = "a_role_user@example.com"
    account = users.User(email=email)
    link_id = 'a_role_user'
    name = 'A Role User'
    properties = {
        'account': account,
        'link_id': link_id,
        'name': name,
        }
    key_name = user_logic.getKeyNameFromFields(properties)
    role_user = user_logic.updateOrCreateFromKeyName(properties, key_name)
    # Create an admin for an_org
    gsoc_org_admin_properties = {
      'link_id': 'an_org_admin',
      'given_name': 'A',
      'surname': 'Orgadmin',
      'scope_path': organization.scope_path + '/' + organization.link_id,
      'scope': organization,
      'program': program,
      'phone': '1-555-2222',
      'email': 'an_org_admin@email.com',
      'res_country': 'United States',
      'res_city': 'A City',
      'res_street': 'A Street',
      'res_postalcode': '12345',
      'birth_date': db.DateProperty.now(),
      'user': role_user,
      }
    gsoc_org_admin_logic.updateOrCreateFromFields(gsoc_org_admin_properties)
    # Create a mentor for an_org
    mentor_properties = gsoc_org_admin_properties.copy()
    mentor_properties.update({
        'link_id': 'a_mentor',
        'given_name': 'A',
        'surname': 'Mentor',
      'email': 'a_mentor@email.com',
        })
    mentor = mentor_logic.updateOrCreateFromFields(mentor_properties)
    self.mentor = mentor
    # Create students for a_program
    student_properties = gsoc_org_admin_properties.copy()
    student_properties.update({
        'scope_path': program.scope_path + '/' + program.link_id,
        'scope': program,
        'program': program,
        'given_name': 'A',
        'surname': 'Student',
        'major': 'A Major',
        'name_on_documents': 'A Name on Documents',
        'publish_location': True,
        'blog': 'http://www.ablog.com/',
        'home_page': 'http://www.ahomepage.com/',
        'photo_url': 'http://www.astudent.com/aphoto.png',
        'expected_graduation': 2011,
        'school_country': 'United States',
        'school_name': 'A School',
        'tshirt_size': 'XS',
        'tshirt_style': 'male',
        'degree': 'Undergraduate',
        'phone': '1650253000',
        'can_we_contact_you': True,
        'program_knowledge': 'I heard about this program through a friend.'
        })
    # Create projects for a_program, an_org and a_mentor
    project_properties = {
        'scope_path': organization.scope_path + '/' + organization.link_id,
        'scope': organization,
        'title': 'test project',
        'abstract': 'test abstract',
        'status': 'accepted',
        'mentor': mentor,
        'program': program,
         }
    #The string order of students' link_id is the same with that of students
    #in the array in order to make sure the last student is handled last
    size = DEF_BATCH_SIZE
    num_digits = 0
    while True:
      size /= 10
      num_digits += 1
      if size == 0:
        break
    students, projects = [], []
    for i in xrange(DEF_BATCH_SIZE+1):
      student_link_id = ('student%0'+str(num_digits)+'d') % i
      student_properties.update({
          'link_id': student_link_id,
          'email': student_link_id + '@email.com',
          })
      student = student_logic.updateOrCreateFromFields(student_properties)
      students.append(student)
      project_link_id = ('project%0'+str(num_digits)+'d') % i
      project_properties.update({
          'link_id': project_link_id,
          'student': student,
          })
      project = student_project_logic.updateOrCreateFromFields(
          project_properties)
      projects.append(project)
    self.students = students
    self.projects = projects
    # Create a project survey for a_program
    link_id = 'a_project_survey'
    fields = {'SelectionQ': [u'SelectionQ Option 2 for %s' % link_id,
                             u'SelectionQ Option 1 for %s'  % link_id
                             ],
              'PickMultipleQ': ['PickMultipleQ Checkbox 1 for %s' % link_id,
                                'PickMultipleQ Checkbox 2 for %s' % link_id,
                                ],
              'LongQ': 'LongQ Custom Prompt for %s' % link_id,
              'ShortQ': 'ShortQ Custom Prompt for %s' % link_id,
              }
    schema = {u'PickMultipleQ': {'index': 5, 'type': 'pick_multi',
                                 'render': 'multi_checkbox'},
              u'LongQ': {'index': 2, 'type': 'long_answer'},
              u'ShortQ': {'index': 3, 'type': 'short_answer'},
              u'SelectionQ': {'index': 4, 'type': 'selection',
                              'render': 'single_select'}
              }
    survey_properties = {
        'link_id': link_id,
        'scope_path': program.scope_path + '/' + program.link_id,
        'scope': None,
        'prefix': 'program',
        'author': role_user,
        'title': 'A Project Survey',
        'short_name': 'APS',
        'modified_by': role_user,
        'is_featured': True,
        'fields': fields,
        'schema': schema,
        'deadline': datetime.datetime.now() + datetime.timedelta(10),
        'taking_access': 'student',
        }
    project_survey = project_survey_logic.updateOrCreateFromFields(
        survey_properties)
    self.project_survey = project_survey
    # Create a grading survey for a_program
    link_id = 'a_grading_survey'
    survey_properties.update({
        'link_id': link_id,
        'title': 'A Grading Survey',
        'short_name': 'AGS',
        'taking_access': 'mentor',
        })
    grading_survey = grading_survey_logic.updateOrCreateFromFields(
        survey_properties)
    self.grading_survey = grading_survey
    # Create a survey group for a_grading_survey and a_project_survey
    # of a_program
    survey_group_properties = {
        'link_id': link_id,
        'scope_path': program.scope_path + '/' + program.link_id,
        'scope': program,
        'name': 'A Survey Group',
        'grading_survey': grading_survey,
        'student_survey': project_survey,
        }
    survey_group = survey_group_logic.updateOrCreateFromFields(
        survey_group_properties)
    self.survey_group = survey_group

  def createGradingRecords(self):
    """Creates DEF_BATCH_SIZE+1 grading records (one for each project).
    """
    grading_records = []
    grading_record_properties = {
        'grading_survey_group': self.survey_group,
        'project': self.projects[0],
        'grade_decision': 'undecided',
        }
    for i in xrange(DEF_BATCH_SIZE+1):
      choices = ['undecided', 'pass', 'fail']
      grading_record_properties.update({
          'project': self.projects[i],
          'grade_decision': choices[i%3],
        })
      grading_record = grading_record_logic.updateOrCreateFromFields(
          grading_record_properties)
      grading_records.append(grading_record)
      self.grading_records = grading_records

  def testUpdateRecordsThroughPostWithoutCorrectXsrfToken(self):
    """Tests that it is forbidden to update records with incorrect XSRF token.

    Without a correct XSRF token, the attempt to update or create records for
    survey group records is forbidden.
    """
    url = '/tasks/grading_survey_group/update_records'
    postdata = {'group_key': self.survey_group.key().name(),
                'project_key': self.projects[0].key().name()}
    response = self.client.post(url, postdata)
    self.assertEqual(response.status_code, httplib.FORBIDDEN)

  def testUpdateRecordsThroughPostWithCorrectXsrfToken(self):
    """Tests that grading records are created with a correct XSRF.

    With correct XSRF token, DEF_BATCH_SIZE
    grading records are created (one for each project) and a taskqueue to
    create more is spawned if there are more than DEF_BATCH_SIZE projects
    to update.
    """
    url = '/tasks/grading_survey_group/update_records'
    postdata = {'group_key': self.survey_group.key().name(),
                'project_key': self.projects[0].key().name()}
    xsrf_token = self.getXsrfToken(url, data=postdata)
    postdata.update(xsrf_token=xsrf_token)
    response = self.client.post(url, postdata)
    self.assertEqual(response.status_code, httplib.OK)
    grading_records = grading_record_logic.getForFields()
    expected_num_grading_records = DEF_BATCH_SIZE
    actual_num_grading_records = len(grading_records)
    self.assertEqual(expected_num_grading_records, actual_num_grading_records)
    task_url = url
    self.assertTasksInQueue(n=1, url=task_url)

  def testUpdateProjectsThroughPostWithoutCorrectXsrfToken(self):
    """Tests that it is forbidden to update project with incorrect XSRF token.

    The attempt to update each student project for which
    a GradingRecord is found without a correct XSRF token is forbidden.
    """
    self.createGradingRecords()
    url = '/tasks/grading_survey_group/update_projects'
    postdata = {'group_key': self.survey_group.key().name(),
                'record_key': self.grading_records[0].key().id(),
                'send_mail': 'yes'}
    response = self.client.post(url, postdata)
    self.assertEqual(response.status_code, httplib.FORBIDDEN)

  def testUpdateProjectsThroughPostWithCorrectXsrfToken(self):
    """Tests that tasks are spawned with a correct XSRF token.

    Through HTTP POST with correct XSRF token, DEF_BATCH_SIZE
    tasks of sending mails (one for each grading record) are spawned and a
    taskqueue to update more projects is spawned if there are more than
    DEF_BATCH_SIZE projects to update. Also Test that the status of the project
    with 'undecided' grading is still 'accepted', the status of the project
    with 'pass' grading is still 'accepted', and the status of the project
    with 'fail' grading is changed to 'failed'.
    """
    self.createGradingRecords()
    url = '/tasks/grading_survey_group/update_projects'
    postdata = {'group_key': self.survey_group.key().name(),
                'record_key': self.grading_records[0].key().id(),
                'send_mail': 'yes'}
    xsrf_token = self.getXsrfToken(url, data=postdata)
    postdata.update(xsrf_token=xsrf_token)
    response = self.client.post(url, postdata)
    self.assertEqual(response.status_code, httplib.OK)
    # Test that the status of the project with 'undecided' grading is
    # still 'accepted'
    self.assertEqual(db.get(self.projects[0].key()).status, 'accepted')
    # Test that the status of the project with 'pass' grading is
    # still 'accepted'
    self.assertEqual(db.get(self.projects[1].key()).status, 'accepted')
    # Test that the status of the project with 'fail' grading is changed
    # to 'failed'
    self.assertEqual(db.get(self.projects[2].key()).status, 'failed')
    task_url = '/tasks/grading_survey_group/mail_result'
    queue_names = ['mail']
    # Only DEF_BATCH_SIZE tasks of sending mails are spawned
    self.assertTasksInQueue(n=DEF_BATCH_SIZE, url=task_url,
                            queue_names=queue_names)
    task_url = url
    self.assertTasksInQueue(n=1, url=task_url)

  def testMailResultWithoutCorrectXsrfToken(self):
    """Tests that sending grading result is forbidden with incorrect XSRF token.

    Without a correct XSRF token, The attempt to send out a mail about the
    result of one grading record is forbidden.
    """
    self.createGradingRecords()
    url = '/tasks/grading_survey_group/mail_result'
    postdata = {'record_key': self.grading_records[0].key().id()}
    response = self.client.post(url, postdata)
    self.assertEqual(response.status_code, httplib.FORBIDDEN)

  def testMailResultWithCorrectXsrfToken(self):
    """Tests that grading result can be sent out with correct XSRF token.

    With a correct XSRF token, the result of grading
    can be sent out to students.
    """
    self.createGradingRecords()
    url = '/tasks/grading_survey_group/mail_result'
    postdata = {'record_key': self.grading_records[0].key().id()}
    xsrf_token = self.getXsrfToken(url, data=postdata)
    postdata.update(xsrf_token=xsrf_token)
    response = self.client.post(url, postdata)
    self.assertEqual(response.status_code, httplib.OK)
    self.assertEmailSent(to=self.grading_records[0].project.student.email,
                         html='evaluation')


text:
class Module

  private

  # Creates a class attribute reader that will delegate to the superclass
  # if not defined on self. Default values can be a Proc object that takes the class as a parameter.
  def inheriting_cattr_reader(*names)
    receiver =
      if self.class == Module
        self
      else
        singleton_class
      end

    names_with_defaults = (names.pop if names.last.is_a?(Hash)) || {}

    (names + names_with_defaults.keys).each do |name|
      ivar_name = "@#{name}"
      block = names_with_defaults[name]

      receiver.send(:define_method, name) do
        if instance_variable_defined? ivar_name
          instance_variable_get(ivar_name)
        else
          superclass.respond_to?(name) && superclass.send(name) ||
          block && begin
            result = block.is_a?(Proc) ? block.call(self) : block
            instance_variable_set(ivar_name, result) if result
          end
        end
      end
    end
  end
end