text:
package genapp

import (
	"fmt"
	"os"
	"path/filepath"
	"regexp"
	"strconv"
	"text/template"

	"github.com/goadesign/goa/design"
	"github.com/goadesign/goa/goagen/codegen"
)

func makeTestDir(g *Generator, apiName string) (outDir string, err error) {
	outDir = filepath.Join(g.outDir, "test")
	if err = os.RemoveAll(outDir); err != nil {
		return
	}
	if err = os.MkdirAll(outDir, 0755); err != nil {
		return
	}
	g.genfiles = append(g.genfiles, outDir)
	return
}

// TestMethod structure
type TestMethod struct {
	Name           string
	Comment        string
	ResourceName   string
	ActionName     string
	ControllerName string
	ContextVarName string
	ContextType    string
	RouteVerb      string
	FullPath       string
	Status         int
	ReturnType     *ObjectType
	Params         []ObjectType
	Payload        *ObjectType
}

// ObjectType structure
type ObjectType struct {
	Label       string
	Name        string
	Type        string
	Pointer     string
	Validatable bool
}

func (g *Generator) generateResourceTest(api *design.APIDefinition) error {
	if len(api.Resources) == 0 {
		return nil
	}
	testTmpl := template.Must(template.New("resources").Parse(testTmpl))
	outDir, err := makeTestDir(g, api.Name)
	if err != nil {
		return err
	}
	appPkg, err := codegen.PackagePath(g.outDir)
	if err != nil {
		return err
	}
	imports := []*codegen.ImportSpec{
		codegen.SimpleImport("bytes"),
		codegen.SimpleImport("fmt"),
		codegen.SimpleImport("net/http"),
		codegen.SimpleImport("net/http/httptest"),
		codegen.SimpleImport("net/url"),
		codegen.SimpleImport("testing"),
		codegen.SimpleImport(appPkg),
		codegen.SimpleImport("github.com/goadesign/goa"),
		codegen.SimpleImport("github.com/goadesign/goa/goatest"),
		codegen.SimpleImport("golang.org/x/net/context"),
	}

	return api.IterateResources(func(res *design.ResourceDefinition) error {
		filename := filepath.Join(outDir, codegen.SnakeCase(res.Name)+".go")
		file, err := codegen.SourceFileFor(filename)
		if err != nil {
			return err
		}
		if err := file.WriteHeader("", "test", imports); err != nil {
			return err
		}

		var methods = []TestMethod{}

		if err := res.IterateActions(func(action *design.ActionDefinition) error {
			if err := action.IterateResponses(func(response *design.ResponseDefinition) error {
				if response.Status == 101 { // SwitchingProtocols, Don't currently handle WebSocket endpoints
					return nil
				}
				for routeIndex, route := range action.Routes {
					mediaType := design.Design.MediaTypeWithIdentifier(response.MediaType)
					if mediaType == nil {
						methods = append(methods, g.createTestMethod(res, action, response, route, routeIndex, nil, nil))
					} else {
						if err := mediaType.IterateViews(func(view *design.ViewDefinition) error {
							methods = append(methods, g.createTestMethod(res, action, response, route, routeIndex, mediaType, view))
							return nil
						}); err != nil {
							return err
						}
					}
				}
				return nil
			}); err != nil {
				return err
			}
			return nil
		}); err != nil {
			return err
		}
		g.genfiles = append(g.genfiles, filename)
		err = testTmpl.Execute(file, methods)
		if err != nil {
			panic(err)
		}
		return file.FormatCode()
	})
}

func (g *Generator) createTestMethod(resource *design.ResourceDefinition, action *design.ActionDefinition, response *design.ResponseDefinition, route *design.RouteDefinition, routeIndex int, mediaType *design.MediaTypeDefinition, view *design.ViewDefinition) TestMethod {
	routeNameQualifier := suffixRoute(action.Routes, routeIndex)
	viewNameQualifier := func() string {
		if view != nil && view.Name != "default" {
			return view.Name
		}
		return ""
	}()
	method := TestMethod{}
	method.Name = fmt.Sprintf("%s%s%s%s%s", codegen.Goify(action.Name, true), codegen.Goify(resource.Name, true), codegen.Goify(response.Name, true), routeNameQualifier, codegen.Goify(viewNameQualifier, true))
	method.ActionName = codegen.Goify(action.Name, true)
	method.ResourceName = codegen.Goify(resource.Name, true)
	method.Comment = fmt.Sprintf("test setup")
	method.ControllerName = fmt.Sprintf("%s.%sController", g.target, codegen.Goify(resource.Name, true))
	method.ContextVarName = fmt.Sprintf("%sCtx", codegen.Goify(action.Name, false))
	method.ContextType = fmt.Sprintf("%s.New%s%sContext", g.target, codegen.Goify(action.Name, true), codegen.Goify(resource.Name, true))
	method.RouteVerb = route.Verb
	method.Status = response.Status
	method.FullPath = goPathFormat(route.FullPath())

	if view != nil && mediaType != nil {
		p, _, err := mediaType.Project(view.Name)
		if err != nil {
			panic(err)
		}
		tmp := codegen.GoTypeName(p, nil, 0, false)
		if !p.IsBuiltIn() {
			tmp = fmt.Sprintf("%s.%s", g.target, tmp)
		}
		validate := codegen.RecursiveChecker(p.AttributeDefinition, false, false, false, "payload", "raw", 1, true)

		returnType := ObjectType{}
		returnType.Type = tmp
		if p.IsObject() {
			returnType.Pointer = "*"
		}
		returnType.Validatable = validate != ""

		method.ReturnType = &returnType
	}

	if len(route.Params()) > 0 {
		var params = []ObjectType{}
		for _, paramName := range route.Params() {
			for name, att := range action.Params.Type.ToObject() {
				if name == paramName {
					param := ObjectType{}
					param.Label = name
					param.Name = codegen.Goify(name, false)
					param.Type = codegen.GoTypeRef(att.Type, nil, 0, false)
					if att.Type.IsPrimitive() && action.Params.IsPrimitivePointer(name) {
						param.Pointer = "*"
					}
					params = append(params, param)
				}
			}
		}
		method.Params = params
	}

	if action.Payload != nil {
		payload := ObjectType{}
		payload.Name = "payload"
		payload.Type = fmt.Sprintf("%s.%s", g.target, codegen.Goify(action.Payload.TypeName, true))
		if !action.Payload.IsPrimitive() && !action.Payload.IsArray() && !action.Payload.IsHash() {
			payload.Pointer = "*"
		}

		validate := codegen.RecursiveChecker(action.Payload.AttributeDefinition, false, false, false, "payload", "raw", 1, false)
		if validate != "" {
			payload.Validatable = true
		}
		method.Payload = &payload
	}
	return method
}

func goPathFormat(path string) string {
	re := regexp.MustCompile(":[a-zA-Z]+")
	return re.ReplaceAllString(path, "%v")
}

func suffixRoute(routes []*design.RouteDefinition, currIndex int) string {
	if len(routes) > 1 && currIndex > 0 {
		return strconv.Itoa(currIndex)
	}
	return ""
}

var testTmpl = `
{{ range $test := . }}
// {{ $test.Name }} {{ $test.Comment }}
func {{ $test.Name }}(t *testing.T, ctrl {{ $test.ControllerName}}{{/*
*/}}{{ range $param := $test.Params }}, {{ $param.Name }} {{ $param.Pointer }}{{ $param.Type }}{{ end }}{{/*
*/}}{{ if $test.Payload }}, {{ $test.Payload.Name }} {{ $test.Payload.Pointer }}{{ $test.Payload.Type }}{{ end }}){{/*
*/}}{{ if $test.ReturnType }} {{ $test.ReturnType.Pointer }}{{ $test.ReturnType.Type }}{{ end }} {
	{{ if $test.ReturnType }}return {{ end }}{{ $test.Name }}Ctx(t, context.Background(), ctrl{{/*
*/}}{{ range $param := $test.Params }}, {{ $param.Name }}{{ end }}{{ if $test.Payload }}, {{ $test.Payload.Name }}{{ end }})
}

// {{ $test.Name }}Ctx {{ $test.Comment }}
func {{ $test.Name }}Ctx(t *testing.T, ctx context.Context, ctrl {{ $test.ControllerName}}{{/*
*/}}{{ range $param := $test.Params }}, {{ $param.Name }} {{ $param.Pointer }}{{ $param.Type }}{{ end }}{{/*
*/}}{{ if $test.Payload }}, {{ $test.Payload.Name }} {{ $test.Payload.Pointer }}{{ $test.Payload.Type }}{{ end }}){{/*
*/}}{{ if $test.ReturnType }} {{ $test.ReturnType.Pointer }}{{ $test.ReturnType.Type }}{{ end }} { {{/*
*/}}{{ if $test.Payload }}{{ if $test.Payload.Validatable }}
	err := {{ $test.Payload.Name }}.Validate()
	if err != nil {
		e, ok := err.(*goa.Error)
		if !ok {
			panic(err) //bug
		}
		if e.Status != {{ $test.Status }} {
			t.Errorf("unexpected payload validation error: %+v", e)
		}
		{{ if $test.ReturnType }}{{ if $test.ReturnType.Pointer }}return nil{{/*
                                     */}}{{ else }}return {{ $test.ReturnType.Type }}{}{{ end }}{{/*
            */}}{{ else }}return{{ end }}
	}{{ end }}{{ end }}
	var logBuf bytes.Buffer
	var resp interface{}
	respSetter := func(r interface{}) { resp = r }
	service := goatest.Service(&logBuf, respSetter)
	rw := httptest.NewRecorder()
	req, err := http.NewRequest("{{ $test.RouteVerb }}", fmt.Sprintf("{{ $test.FullPath }}"{{ range $param := $test.Params }}, {{ $param.Name }}{{ end }}), nil)
	if err != nil {
		panic("invalid test " + err.Error()) // bug
	}
	prms := url.Values{}
	{{ range $param := $test.Params }}prms["{{ $param.Label }}"] = []string{fmt.Sprintf("%v",{{ $param.Name}})}
	{{ end }}
	goaCtx := goa.NewContext(goa.WithAction(ctx, "{{ $test.ResourceName }}Test"), rw, req, prms)
	{{ $test.ContextVarName }}, err := {{ $test.ContextType }}(goaCtx, service)
	if err != nil {
		panic("invalid test data " + err.Error()) // bug
	}
	{{ if $test.Payload }}{{ $test.ContextVarName }}.Payload = {{ $test.Payload.Name }}{{ end }}

	err = ctrl.{{ $test.ActionName}}({{ $test.ContextVarName }})
	if err != nil {
		t.Fatalf("controller returned %s, logs:\n%s", err, logBuf.String())
	}
	{{if $test.ReturnType }}
	a, ok := resp.({{ $test.ReturnType.Pointer }}{{ $test.ReturnType.Type }})
	if !ok {
		t.Errorf("invalid response media: got %+v, expected instance of {{ $test.ReturnType.Type }}", resp)
	}
	{{ end }}
	if rw.Code != {{ $test.Status }} {
		t.Errorf("invalid response status code: got %+v, expected {{ $test.Status }}", rw.Code)
	}
	{{ if $test.ReturnType }}{{ if $test.ReturnType.Validatable }}
	err = a.Validate()
	if err != nil {
		t.Errorf("invalid response payload: got %v", err)
	}
	{{ end }}return a
	{{ end }}
}
{{ end }}`


text:
#pragma once
#include <aws/ec2/EC2_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSStreamFwd.h>
#include <aws/ec2/model/FleetStateCode.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Xml
{
  class XmlNode;
} // namespace Xml
} // namespace Utils
namespace EC2
{
namespace Model
{

  /**
   *
Describes an EC2 Fleet that was successfully deleted.

See
   * Also:
   AWS
   * API Reference

   */
  class AWS_EC2_API DeleteFleetSuccessItem
  {
  public:
    DeleteFleetSuccessItem();
    DeleteFleetSuccessItem(const Aws::Utils::Xml::XmlNode& xmlNode);
    DeleteFleetSuccessItem& operator=(const Aws::Utils::Xml::XmlNode& xmlNode);

    void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const;
    void OutputToStream(Aws::OStream& oStream, const char* location) const;

    /**
     *
The current state of the EC2 Fleet.

     */
    inline const FleetStateCode& GetCurrentFleetState() const{ return m_currentFleetState; }

    /**
     *
The current state of the EC2 Fleet.

     */
    inline bool CurrentFleetStateHasBeenSet() const { return m_currentFleetStateHasBeenSet; }

    /**
     *
The current state of the EC2 Fleet.

     */
    inline void SetCurrentFleetState(const FleetStateCode& value) { m_currentFleetStateHasBeenSet = true; m_currentFleetState = value; }

    /**
     *
The current state of the EC2 Fleet.

     */
    inline void SetCurrentFleetState(FleetStateCode&& value) { m_currentFleetStateHasBeenSet = true; m_currentFleetState = std::move(value); }

    /**
     *
The current state of the EC2 Fleet.

     */
    inline DeleteFleetSuccessItem& WithCurrentFleetState(const FleetStateCode& value) { SetCurrentFleetState(value); return *this;}

    /**
     *
The current state of the EC2 Fleet.

     */
    inline DeleteFleetSuccessItem& WithCurrentFleetState(FleetStateCode&& value) { SetCurrentFleetState(std::move(value)); return *this;}

    /**
     *
The previous state of the EC2 Fleet.

     */
    inline const FleetStateCode& GetPreviousFleetState() const{ return m_previousFleetState; }

    /**
     *
The previous state of the EC2 Fleet.

     */
    inline bool PreviousFleetStateHasBeenSet() const { return m_previousFleetStateHasBeenSet; }

    /**
     *
The previous state of the EC2 Fleet.

     */
    inline void SetPreviousFleetState(const FleetStateCode& value) { m_previousFleetStateHasBeenSet = true; m_previousFleetState = value; }

    /**
     *
The previous state of the EC2 Fleet.

     */
    inline void SetPreviousFleetState(FleetStateCode&& value) { m_previousFleetStateHasBeenSet = true; m_previousFleetState = std::move(value); }

    /**
     *
The previous state of the EC2 Fleet.

     */
    inline DeleteFleetSuccessItem& WithPreviousFleetState(const FleetStateCode& value) { SetPreviousFleetState(value); return *this;}

    /**
     *
The previous state of the EC2 Fleet.

     */
    inline DeleteFleetSuccessItem& WithPreviousFleetState(FleetStateCode&& value) { SetPreviousFleetState(std::move(value)); return *this;}

    /**
     *
The ID of the EC2 Fleet.

     */
    inline const Aws::String& GetFleetId() const{ return m_fleetId; }

    /**
     *
The ID of the EC2 Fleet.

     */
    inline bool FleetIdHasBeenSet() const { return m_fleetIdHasBeenSet; }

    /**
     *
The ID of the EC2 Fleet.

     */
    inline void SetFleetId(const Aws::String& value) { m_fleetIdHasBeenSet = true; m_fleetId = value; }

    /**
     *
The ID of the EC2 Fleet.

     */
    inline void SetFleetId(Aws::String&& value) { m_fleetIdHasBeenSet = true; m_fleetId = std::move(value); }

    /**
     *
The ID of the EC2 Fleet.

     */
    inline void SetFleetId(const char* value) { m_fleetIdHasBeenSet = true; m_fleetId.assign(value); }

    /**
     *
The ID of the EC2 Fleet.

     */
    inline DeleteFleetSuccessItem& WithFleetId(const Aws::String& value) { SetFleetId(value); return *this;}

    /**
     *
The ID of the EC2 Fleet.

     */
    inline DeleteFleetSuccessItem& WithFleetId(Aws::String&& value) { SetFleetId(std::move(value)); return *this;}

    /**
     *
The ID of the EC2 Fleet.

     */
    inline DeleteFleetSuccessItem& WithFleetId(const char* value) { SetFleetId(value); return *this;}

  private:

    FleetStateCode m_currentFleetState;
    bool m_currentFleetStateHasBeenSet;

    FleetStateCode m_previousFleetState;
    bool m_previousFleetStateHasBeenSet;

    Aws::String m_fleetId;
    bool m_fleetIdHasBeenSet;
  };

} // namespace Model
} // namespace EC2
} // namespace Aws

redpajama_set_name: RedPajamaGithub


text:
#ifndef OMNI_CORE_MODEL_FUNCTION_HPP
#define OMNI_CORE_MODEL_FUNCTION_HPP

#include <omni/core/core.hpp>
#include <omni/core/model/function_prototype.hpp>

#include <memory>

namespace omni {
namespace core {
namespace model {
    class module;

    /**
    @class function function.hpp omni/core/model/function.hpp
    @brief Defines a function implementation that can be called with a function_call_expression.

    A function consists of a name that should be unique within a scope, a return-type, a number of parameters and a body.
    For more information about the return-type and the parameters, see function_prototype.
    A function can be exported. An exported function is visible from other modules than the one the function is defined in.

    A function is not emitted to a binary if it has not been added to a module via scope::addFunction.
    Currently, only top-level functions that are directly added to a module are supported.
    Functions that are added to any other scope deeper within a module are not emitted.
    **/
    class OMNI_CORE_API function : public function_prototype {
    public:
        function (std::string const & name,
                  std::shared_ptr <type> returnType = std::shared_ptr <type> (),
                  std::shared_ptr <block> body = std::shared_ptr <block> (),
                  std::vector <std::shared_ptr <parameter>> parameters = std::vector <std::shared_ptr <parameter>> (),
                  bool isExported = false);

        static meta_info & getStaticMetaInfo ();

        meta_info & getMetaInfo () const override;

        domain getDomain () const override;

        void setExported (bool isExported);
        bool isExported () const;

        void setBody (std::shared_ptr <block> body);
        const std::shared_ptr <block> getBody () const;
        std::shared_ptr <block> getBody ();

        llvm::Function * llvmFunction () override;

    private:
        llvm::Function * _llvmFunction;
        bool _isExported;
    };

} // namespace model
} // namespace core
} // namespace omni

#endif // include guard


text:
var MIDI = require('./build/default/MIDI.node');

var output = new MIDI.MIDIOutput('DSI Tetra');
var input = new MIDI.MIDIInput('DSI Tetra');

input.recv(function (messages) {
    if (messages.length > 1) {
        console.log('more than one message, unexpected');
        return;
    }
    var message = messages[0];
    var str = '';
    for (i in message) {
        str += ' ' + message[i].toString(16);
    }
    console.log('message length: ' + message.length + ' message:' + str);
    var globalParameterName = ['master transpose',
                               'master fine tune',
                               'midi channel',
                               'poly chain',
                               'midi clock source',
                               'local control',
                               'parameter send',
                               'parameter receive',
                               'midi controller send/receive',
                               'midi sysex send/receive',
                               'audio out',
                               'balance tweak',
                               'pot mode',
                               'midi out select',
                               'multi mode',
                               'layer',
                               'program/combo',
                               'select voice'];
    for (i = 4; i < message.length; i += 2) {
        var value = message[i] + (message[i + 1] << 4);
        var index = ((i - 4) / 2);
        console.log(globalParameterName[index] + ": " + value);
    }
});

output.send('f0 01 26 0e f7');


text:
package com.hazelcast.client.impl.protocol.task.queue;

import com.hazelcast.client.impl.protocol.ClientMessage;
import com.hazelcast.client.impl.protocol.codec.QueueIsEmptyCodec;
import com.hazelcast.client.impl.protocol.task.AbstractPartitionMessageTask;
import com.hazelcast.collection.impl.queue.QueueService;
import com.hazelcast.collection.impl.queue.operations.IsEmptyOperation;
import com.hazelcast.instance.Node;
import com.hazelcast.nio.Connection;
import com.hazelcast.security.permission.ActionConstants;
import com.hazelcast.security.permission.QueuePermission;
import com.hazelcast.spi.Operation;

import java.security.Permission;

/**
 * Client Protocol Task for handling messages with type id:
 * {@link com.hazelcast.client.impl.protocol.codec.QueueMessageType#QUEUE_ISEMPTY}
 */
public class QueueIsEmptyMessageTask
        extends AbstractPartitionMessageTask<QueueIsEmptyCodec.RequestParameters> {

    public QueueIsEmptyMessageTask(ClientMessage clientMessage, Node node, Connection connection) {
        super(clientMessage, node, connection);
    }

    @Override
    protected Operation prepareOperation() {
        return new IsEmptyOperation(parameters.name);
    }

    @Override
    protected ClientMessage encodeResponse(Object response) {
        return QueueIsEmptyCodec.encodeResponse((Boolean) response);
    }

    @Override
    protected QueueIsEmptyCodec.RequestParameters decodeClientMessage(ClientMessage clientMessage) {
        return QueueIsEmptyCodec.decodeRequest(clientMessage);
    }

    @Override
    public Permission getRequiredPermission() {
        return new QueuePermission(parameters.name, ActionConstants.ACTION_READ);
    }

    @Override
    public String getMethodName() {
        return "isEmpty";
    }

    @Override
    public String getServiceName() {
        return QueueService.SERVICE_NAME;
    }

    @Override
    public Object[] getParameters() {
        return null;
    }

    @Override
    public String getDistributedObjectName() {
        return parameters.name;
    }
}


text:
package org.saddle

import org.saddle.Serde._
import org.specs2.mutable.Specification
import org.specs2.ScalaCheck
import org.scalacheck.{Gen, Arbitrary}
import org.scalacheck.Prop._
import scalar.Scalar
import org.joda.time._

class IndexCheck extends Specification with ScalaCheck {
  "Int Index Tests" in {
    implicit val arbIndex = Arbitrary(IndexArbitraries.indexIntWithDups)

    "access works" in {
      forAll { (ix: Index[Int]) =>
        val idx = Gen.choose(0, ix.length - 1)
        forAll(idx) { i =>
          ix.at(i) must_== Scalar(ix.toVec.contents(i))
          ix.raw(i) must_== ix.toVec.contents(i)
        }
      }
    }

    "key lookup works" in {
      forAll { (ix: Index[Int]) =>
        val idx = Gen.choose(0, ix.length - 1)
        forAll(idx) { i =>
          val v = ix.raw(i)
          ix.apply(v) must_== array.range(0, ix.length).filter(ix.raw(_) == v)
        }
      }
    }

    "key counts work" in {
      forAll { (ix: Index[Int]) =>
        val idx = Gen.choose(0, ix.length - 1)
        forAll(idx) { i =>
          val v = ix.raw(i)
          ix.count(v) must_== array.range(0, ix.length).map(l => if(ix.raw(l) == v) 1 else 0).sum
        }
      }
    }

    "index joins work" in {
      forAll { (ix1: Index[Int], ix2: Index[Int]) =>
        val all = Seq(index.LeftJoin, index.RightJoin, index.OuterJoin, index.InnerJoin) map { jointype =>
          val res = ix1.join(ix2, how = jointype)

          val exp = res.index.toVec
          val lix = ix1.toVec
          val rix = ix2.toVec
          val lft = res.lTake.map(x => lix.take(x)) getOrElse lix fillNA { exp.raw(_) }
          val rgt = res.rTake.map(x => rix.take(x)) getOrElse rix fillNA { exp.raw(_) }

          lft must_== exp
          rgt must_== exp
        }
        all.foldLeft(true)((acc, v) => acc && v.isSuccess)
      }
    }

    "index union works" in {
      implicit val arbIndex = Arbitrary(IndexArbitraries.indexIntNoDups)
      forAll { (ix1: Index[Int], ix2: Index[Int]) =>
        ix1.union(ix2).index.toSeq.toSet must_== { ix1.toSeq ++ ix2.toSeq }.toSet
      }
    }

    "without dups, index union is outer join" in {
      implicit val arbIndex = Arbitrary(IndexArbitraries.indexIntNoDups)

      forAll { (ix1: Index[Int], ix2: Index[Int]) =>
        ix1.join(ix2, how=index.OuterJoin).index.toSeq.toSet must_== { ix1.toSeq ++ ix2.toSeq }.toSet
      }
    }

    "index intersect works" in {
      implicit val arbIndex = Arbitrary(IndexArbitraries.indexIntNoDups)

      forAll { (ix1: Index[Int], ix2: Index[Int]) =>
        ix1.intersect(ix2).index.toSeq.toSet must_== ix1.toSeq.toSet[Int].intersect(ix2.toSeq.toSet[Int])
      }
    }

    "joins preserves index order with dups" in {
      implicit val arbIndex = Arbitrary(IndexArbitraries.indexIntWithDups)

      forAll { (ix1: Index[Int], ix2: Index[Int]) =>
        val ixs1 = ix1.sorted
        val ixs2 = ix2.sorted

        ixs1.join(ixs2, how=index.RightJoin).index.isMonotonic must beTrue
        ixs1.join(ixs2, how=index.LeftJoin).index.isMonotonic must beTrue
        ixs1.join(ixs2, how=index.InnerJoin).index.isMonotonic must beTrue
        ixs1.join(ixs2, how=index.OuterJoin).index.isMonotonic must beTrue
      }
    }

    "joins preserves index order no dups" in {
      implicit val arbIndex = Arbitrary(IndexArbitraries.indexIntNoDups)

      forAll { (ix1: Index[Int], ix2: Index[Int]) =>
        val ixs1 = ix1.sorted
        val ixs2 = ix2.sorted

        ixs1.join(ixs2, how=index.RightJoin).index.isMonotonic must beTrue
        ixs1.join(ixs2, how=index.LeftJoin).index.isMonotonic must beTrue
        ixs1.join(ixs2, how=index.InnerJoin).index.isMonotonic must beTrue
        ixs1.join(ixs2, how=index.OuterJoin).index.isMonotonic must beTrue
      }
    }

    "serialization works" in  {
      implicit val arbIndex = Arbitrary(IndexArbitraries.indexIntNoDups)

      forAll { (ix1: Index[Int], ix2: Index[Int]) => {
        ix1 must_== serializedCopy(ix1)
        ix2 must_== serializedCopy(ix2)
      }
      }
    }

  }

  "Time Index Tests" in {
    "access works" in {
      implicit val arbIndex = Arbitrary(IndexArbitraries.indexTimeWithDups)
      forAll { (ix: Index[DateTime]) =>
        val idx = Gen.choose(0, ix.length - 1)
        forAll(idx) { i =>
          ix.at(i) must_== Scalar(ix.toVec.contents(i))
          ix.raw(i) must_== ix.toVec.contents(i)
        }
      }
    }

    "key lookup works" in {
      implicit val arbIndex = Arbitrary(IndexArbitraries.indexTimeWithDups)
      forAll { (ix: Index[DateTime]) =>
        val idx = Gen.choose(0, ix.length - 1)
        forAll(idx) { i =>
          val v = ix.raw(i)
          ix.apply(v) must_== array.range(0, ix.length).filter(ix.raw(_) == v)
        }
      }
    }

    "key counts work" in {
      implicit val arbIndex = Arbitrary(IndexArbitraries.indexTimeWithDups)
      forAll { (ix: Index[DateTime]) =>
        val idx = Gen.choose(0, ix.length - 1)
        forAll(idx) { i =>
          val v = ix.raw(i)
          ix.count(v) must_== array.range(0, ix.length).map(l => if(ix.raw(l) == v) 1 else 0).sum
        }
      }
    }

    "index joins work" in {
      implicit val arbIndex = Arbitrary(IndexArbitraries.indexTimeWithDups)

      forAll { (ix1: Index[DateTime], ix2: Index[DateTime]) =>
        val all = Seq(index.LeftJoin, index.RightJoin, index.OuterJoin, index.InnerJoin) map { jointype =>
          val res = ix1.join(ix2, how = jointype)

          val exp = res.index.toVec
          val lix = ix1.toVec
          val rix = ix2.toVec
          val lft = res.lTake.map(x => lix.take(x)) getOrElse lix fillNA { exp.raw(_) }
          val rgt = res.rTake.map(x => rix.take(x)) getOrElse rix fillNA { exp.raw(_) }

          lft must_== exp
          rgt must_== exp
        }
        all.foldLeft(true)((acc, v) => acc && v.isSuccess)
      }
    }

    "index union works" in {
      implicit val arbIndex = Arbitrary(IndexArbitraries.indexTimeNoDups)

      forAll { (ix1: Index[DateTime], ix2: Index[DateTime]) =>
        ix1.union(ix2).index.toSeq.toSet must_== { ix1.toSeq ++ ix2.toSeq }.toSet
      }
    }

    "without dups, index union is outer join" in {
      implicit val arbIndex = Arbitrary(IndexArbitraries.indexTimeNoDups)

      forAll { (ix1: Index[DateTime], ix2: Index[DateTime]) =>
        ix1.join(ix2, how=index.OuterJoin).index.toSeq.toSet must_== { ix1.toSeq ++ ix2.toSeq }.toSet
      }
    }

    "index intersect works" in {
      implicit val arbIndex = Arbitrary(IndexArbitraries.indexTimeNoDups)

      forAll { (ix1: Index[DateTime], ix2: Index[DateTime]) =>
        ix1.intersect(ix2).index.toSeq.toSet must_== ix1.toSeq.toSet[DateTime].intersect(ix2.toSeq.toSet[DateTime])
      }
    }

    "joins preserves index order with dups" in {
      implicit val arbIndex = Arbitrary(IndexArbitraries.indexTimeWithDups)

      forAll { (ix1: Index[DateTime], ix2: Index[DateTime]) =>
        val ixs1 = ix1.sorted
        val ixs2 = ix2.sorted

        ixs1.join(ixs2, how=index.RightJoin).index.isMonotonic must beTrue
        ixs1.join(ixs2, how=index.LeftJoin).index.isMonotonic must beTrue
        ixs1.join(ixs2, how=index.InnerJoin).index.isMonotonic must beTrue
        ixs1.join(ixs2, how=index.OuterJoin).index.isMonotonic must beTrue
      }
    }

    "joins preserves index order no dups" in {
      implicit val arbIndex = Arbitrary(IndexArbitraries.indexTimeNoDups)

      forAll { (ix1: Index[DateTime], ix2: Index[DateTime]) =>
        val ixs1 = ix1.sorted
        val ixs2 = ix2.sorted

        ixs1.join(ixs2, how=index.RightJoin).index.isMonotonic must beTrue
        ixs1.join(ixs2, how=index.LeftJoin).index.isMonotonic must beTrue
        ixs1.join(ixs2, how=index.InnerJoin).index.isMonotonic must beTrue
        ixs1.join(ixs2, how=index.OuterJoin).index.isMonotonic must beTrue
      }
    }

    "serialization works" in  {

      implicit val arbIndex = Arbitrary(IndexArbitraries.indexTimeWithDups)

      forAll { (ix1: Index[DateTime], ix2: Index[DateTime]) => {
        ix1 must_== serializedCopy(ix1)
        ix2 must_== serializedCopy(ix2)
      }
      }
    }

  }
}


text:
<?php

namespace Navigation\Controller\Admin;

use Navigation\Model\Navigation;
use Navigation\Model\NavigationLinks as Links;
use Navigation\Lib\Helper;

class NavigationController extends \AdminController
{
    public function before()
    {
        $this->menu->activeParent('appearance');

        $allGroups = Navigation::all();
        $this->links = array();
        $this->groups = array();
        $items = array();
        $default = array();
        foreach ($allGroups as $g) {

            $id = $g->id;

            $obj = \Cache::solve('Navigation::navigation_group'.$id,
                        function () use ($id) {
                            return Links::where('navigation_id', '=', $id)
                                    ->orderBy('link_order', 'asc')
                                    ->get()->toArray();
                        });

            $this->links[$g->slug] = Helper::getNavTree($obj);
            $this->groups[$g->slug] = $g;
            $default[] = $g->id;
        }

        $this->groupSelect = e2s($allGroups, 'id', 'title');
        $this->moduleSelect = Helper::moduleSelect();
        $this->defaultGroup = $default[0];
        $this->pageSelects = Helper::pageSelect();

        $this->template->style('form.css')
                        ->style('navigation.css','navigation' )
                        ->script('plugins/jquery.mjs.nestedSortable.js')
                        ->script('navigation.js', 'navigation', 'footer');
    }

    public function index()
    {
        $this->template
                ->title(\Translate::get('navigation::navigation.title'))
                ->set('links', $this->links)
                ->set('groups', $this->groups)
                ->set('groupSelect', $this->groupSelect)
                ->set('moduleSelect', $this->moduleSelect)
                ->set('pageSelect', $this->pageSelects)
                ->set('defaultGroup', $this->defaultGroup)
                ->view('admin/index');
    }

    /**
     * Order the Menu Items
     */
    public function order()
    {
        $order	= \Input::get('order');
        $group	= \Input::get('group');

        if (is_array($order)) {

            // Update the db result's parent are 0
            $g = Links::where('navigation_id', '=', $group)
                    ->update(array('parent_id' => 0));

            foreach ($order as $key => $link) {
                Links::where('id', '=', $link['id'])
                            ->update(array('link_order' => $key));
                if (isset($link['children'])) {
                    Links::setTheChild($link);
                }
            }

            \Cache::deleteFolder('Navigation');
        }

        return $this->returnJson(array('status' => 'ok'));
    }

    /**
     * Create the new Menu item
     */
    public function create()
    {
        if (\Input::isPost()) {

            $v = $this->validation();

            if ($v->valid()) {

                $link = new Links();

                $link->title = \Input::get('title');
                $link->navigation_id = \Input::get('group');
                $link->link_type = \Input::get('type');
                $link->url = $this->getUrl();
                $link->parent_id = 0;
                $link->link_order = Links::getLinkOrder(\Input::get('group'));
                $link->class = \Input::get('class');
                $link->target = \Input::get('target');
                $link->permission = \Input::get('permission', '');

                if ($link->save()) {
                    \Cache::deleteFolder('Navigation');
                    $msg = \Translate::get('navigation::navigation.message.create_success');
                    \Flash::success($msg);

                    return \Redirect::toAdmin('navigation');
                } else {
                    $msg = \Translate::get('navigation::navigation.message.create_error');
                    \Flash::error($msg);

                    return \Redirect::toAdmin('navigation');
                }
            } else {
                $errors = $v->getErrors();
                \Flash::error(implode("\n\r", $errors));

                return \Redirect::toAdmin('navigation');
            }
        }
    }

    public function edit($id)
    {
        if (!user_has_access('nav.edit')) {
            return $this->template->set('make', 'editing')
                                ->set('type', 'link')
                                ->partialOnly()
                                ->view('admin/noaccess')->render();
        }
        $link = Links::find($id);

        switch ($link->type) {
            case 'module' :
                $link->module = $link->url;
            break;

            case 'url' :
                $link->urlStr = $link->url;
            break;

            case 'page' :
                $link->page = $link->url;
            break;

            default :
                $link->uri = $link->url;
            break;
        }

        if (\Input::isPost()) {
            $v = $this->validation();

            if ($v->valid()) {
                if (\Input::get('current_group') != \Input::get('group')) {
                    $parent = 0;
                    $group_change = true;
                    $link_order = Links::getLinkOrder((int) \Input::get('group'));
                } else {
                    $parent = (int) \Input::get('parent');
                    $group_change = false;
                    $link_order = (int) \Input::get('order');
                }

                $link->title = \Input::get('title');
                $link->navigation_id = \Input::get('group');
                $link->link_type = \Input::get('type');
                $link->url = $this->getUrl();
                $link->parent_id = $parent;
                $link->link_order = $link_order;
                $link->class = \Input::get('class');
                $link->target = \Input::get('target');
                $link->permission = \Input::get('permission', '');

                unset($link->uri);
                unset($link->module);
                unset($link->page);
                unset($link->urlStr);

                if ($link->updateLink(\Input::get('current_group'), $group_change)) {

                    \Cache::deleteFolder('Navigation');

                    return $this->returnJson(array('status' => 'success', 'message' => t('navigation::navigation.message.edit_success') ));

                } else {
                    return $this->returnJson(array('status' => 'fail', 'message' => t('navigation::navigation.message.edit_error') ));
                }
            } else {
                return $this->returnJson(array('status' => 'error', 'message' => 'Validation Error' ));
            }
        }

        $type = array(
                'uri'		=> t('navigation::navigation.labels.uri'),
                'page'		=> t('navigation::navigation.labels.page'),
                'module'	=> t('navigation::navigation.labels.module'),
                'url'		=> t('navigation::navigation.labels.url'),
            );

        $this->template->title(t('navigation::navigation.link.title'))
                        ->set('link', $link)
                        ->set('groups', $this->groups)
                        ->set('groupSelect', $this->groupSelect)
                        ->set('moduleSelect', $this->moduleSelect)
                        ->set('pageSelect', $this->pageSelects)
                        ->set('defaultGroup', $this->defaultGroup)
                        ->set('type', $type)
                        ->partialOnly()
                        ->view('admin/edit');
    }

    public function delete($id)
    {
        $link = Links::find($id);

        if (is_null($link)) {
            return $this->notFound();
        }

        $link->updateParent();

        try {
            $link->delete();
            \Cache::deleteFolder('Navigation');
            $msg = \Translate::get('navigation::navigation.message.delete_success');
            \Flash::success($msg);
        } catch (\Exception $e) {
            $msg = \Translate::get('navigation::navigation.message.delete_error');
            \Flash::error($msg);
        }

        return \Redirect::toAdmin('navigation');
    }

    public function group()
    {
        $groups = Navigation::all();

        $this->template->title(t('navigation::navigation.group.title'))
                        ->set('groups', $groups)
                        ->view('admin/group');
    }

    public function groupCreate()
    {
        if (! \Input::isPost()) {
            return \Redirect::toAdmin('navigation/group');
        }

        if (is_null(\Input::get('group'))) {
            \Flash::error(t('navigation::navigation.message.required'));

            return \Redirect::toAdmin('navigation/group');
        }

        if (in_array(ucfirst(\Input::get('group')), $this->groupSelect)) {
            \Flash::error(t('navigation::navigation.message.exists'));

            return \Redirect::toAdmin('navigation/group');
        }

        $group = new Navigation();
        $group->title = \Input::get('group');
        $group->slug = slug(\Input::get('group'));
        if ($group->save()) {
            \Flash::success(t('navigation::navigation.message.group_success'));
        } else {
            \Flash::error(t('navigation::navigation.message.group_error'));
        }

        return \Redirect::toAdmin('navigation/group');
    }

    /**
     * Get the URL for menu base on menu type
     */
    protected function getUrl()
    {
        $type = \Input::get('type');

        switch ($type) {
            case 'url' :
                $url = \Input::get('url');
            break;

            case 'module':
                $url = \Input::get('module');
            break;

            case 'page':
                $url = \Input::get('page');
            break;

            default :
                $url = \Input::get('uri');
            break;
        }

        return $url;
    }

    /**
     * Validation check for module item
     */
    protected function validation()
    {
        $rule = array(
                    'title' => 'required|maxLength:100',
                    'type' => 'required',
                    'url' => 'navUrl',
                    'uri' => 'navUrl',
                    'module' => 'navUrl',
                    'page' => 'navUrl',
                    'group' => 'required',
                    'class' => 'maxLength:255'
                );

        $v = new \Reborn\Form\Validation(\Input::get('*'), $rule);

        $ins = $this;
        $v->addRule('navUrl',
                    'Test is fail',
                    function () use ($ins) {
                        $type = \Input::get('type');
                        switch ($type) {
                            case 'module':
                                $value = \Input::get('module');

                                return array_key_exists($value, $ins->moduleSelect);
                            break;

                            case 'page':
                                $value = \Input::get('page');

                                return array_key_exists($value, $ins->pageSelects);
                            break;

                            default :
                                return true;
                            break;
                        }
                    }
                );

        return $v;
    }
}


text:
from .tika import doTranslate1, callServer, Translator, ServerEndpoint

def from_file(filename, srcLang, destLang, serverEndpoint=ServerEndpoint, requestOptions={}):
    '''
    Traslates the content of source file to destination language
    :param filename: file whose contents needs translation
    :param srcLang: name of language of input file
    :param destLang: name of language of desired language
    :param serverEndpoint: Tika server end point (Optional)
    :return: translated content
    '''
    jsonOutput = doTranslate1(srcLang+':'+destLang, filename, serverEndpoint, requestOptions=requestOptions)
    return jsonOutput[1]

def from_buffer(string, srcLang, destLang, serverEndpoint=ServerEndpoint, requestOptions={}):
    '''
    Translates content from source language to desired destination language
    :param string: input content which needs translation
    :param srcLang: name of language of the input content
    :param destLang: name of the desired language for translation
    :param serverEndpoint:
    :return:
    '''
    status, response = callServer('put', ServerEndpoint, '/translate/all/'+Translator+'/'+srcLang+'/'+destLang,
                                  string, {'Accept': 'text/plain'}, False, requestOptions=requestOptions)
    return response

def auto_from_file(filename, destLang, serverEndpoint=ServerEndpoint, requestOptions={}):
    '''
    Translates contents of a file to desired language by auto detecting the source language
    :param filename: file whose contents needs translation
    :param destLang: name of the desired language for translation
    :param serverEndpoint: Tika server end point (Optional)
    :return:
    '''
    jsonOutput = doTranslate1(destLang, filename, serverEndpoint, requestOptions=requestOptions)
    return jsonOutput[1]

def auto_from_buffer(string, destLang, serverEndpoint=ServerEndpoint, requestOptions={}):
    '''
    Translates content to desired language by auto detecting the source language
    :param string: input content which needs translation
    :param destLang: name of the desired language for translation
    :param serverEndpoint: Tika server end point (Optional)
    :return:
    '''
    status, response = callServer('put', ServerEndpoint, '/translate/all/'+Translator+'/'+destLang,
                                  string, {'Accept': 'text/plain'}, False, requestOptions=requestOptions)
    return response


text:
@(userId: String)

@main("WorksetUpload", userId) {

                Upload Workset

                @helper.form(action = routes.WorksetManagement.uploadWorkset, 'enctype -> "multipart/form-data") {

Workset must be in CSV(comma-separated-values) or TXT format.

                        Workset Name
                        <input type="text" id="uploadWorksetName" class="form-control" name="uploadWorksetName" placeholder="Workset Name" required="required" aria-describedby="wsname-feedback-status"/>

                        (success)
                        @*
*@
                        @*
*@

                            Only characters A-Z 0-9 ( )- or _ allowed.

                        Description
                        <input type="text" id="uploadWSdescription" class="form-control" name="uploadWSdescription" placeholder="Description" maxlength="100">

                        CSV File:
                        <input type="file" name="csv" accept="text/csv,text/plain" id="inputCSV" required="required">

                        (success)

                            You can only upload worksets as CSV(comma-separated-values)or TXT format..

                            <input type="checkbox" name="privateWorkset" checked="checked"/> Private workset.

                            <button type="submit" class="btn btn-primary btn-sm" id="ws-submit">Upload Workset</button>

                }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->
<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/maven-v4_0_0.xsd">

  <parent>
    <groupId>com.kasabi</groupId>
    <artifactId>kasabi</artifactId>
    <version>2-SNAPSHOT</version>
  </parent>

  <modelVersion>4.0.0</modelVersion>
  <groupId>com.kasabi.data.links</groupId>
  <artifactId>dataset-links</artifactId>
  <version>0.1-SNAPSHOT</version>
  <packaging>jar</packaging>
  <name>Kasabi Dataset Links</name>

  <properties>
    <dataset-lib.version>0.1-SNAPSHOT</dataset-lib.version>
    <slf4j.version>1.6.4</slf4j.version>
    <commons-io.version>2.1</commons-io.version>
    <commons-cli.version>1.2</commons-cli.version>
    <jsoup.version>1.6.1</jsoup.version>
    <junit.version>4.8.2</junit.version>
    <tdb.version>0.9.0-incubating-SNAPSHOT</tdb.version>
    <jena.version>2.7.0-incubating</jena.version>
    <arq.version>2.9.0-incubating</arq.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>${commons-io.version}</version>
    </dependency>
    <dependency>
      <groupId>commons-cli</groupId>
      <artifactId>commons-cli</artifactId>
      <version>${commons-cli.version}</version>
    </dependency>
    <dependency>
      <groupId>com.kasabi.labs</groupId>
      <artifactId>dataset-lib</artifactId>
      <version>${dataset-lib.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>jcl-over-slf4j</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
      </plugin>
      <plugin>
        <artifactId>maven-source-plugin</artifactId>
      </plugin>
      <plugin>
        <artifactId>maven-eclipse-plugin</artifactId>
        <configuration>
          <useProjectReferences>false</useProjectReferences>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>2.2.2</version>
        <configuration>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
        </configuration>
        <executions>
          <execution>
            <id>make-assembly</id>
            <phase>package</phase>
            <goals>
              <goal>single</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

  <repositories>
    <repository>
      <id>talis-releases</id>
      <url>http://oss.talisplatform.com/content/repositories/talis-releases</url>
    </repository>
    <repository>
      <id>talis-snapshots</id>
      <url>http://oss.talisplatform.com/content/repositories/talis-snapshots</url>
    </repository>
  </repositories>

</project>


text:
package org.unitime.timetable.onlinesectioning.solver;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Set;

import org.unitime.localization.impl.Localization;
import org.unitime.timetable.gwt.resources.StudentSectioningMessages;
import org.unitime.timetable.gwt.shared.ClassAssignmentInterface;
import org.unitime.timetable.gwt.shared.SectioningException;
import org.unitime.timetable.onlinesectioning.OnlineSectioningAction;
import org.unitime.timetable.onlinesectioning.OnlineSectioningHelper;
import org.unitime.timetable.onlinesectioning.OnlineSectioningServer;
import org.unitime.timetable.onlinesectioning.OnlineSectioningServer.Lock;
import org.unitime.timetable.onlinesectioning.custom.StudentEnrollmentProvider.EnrollmentRequest;
import org.unitime.timetable.onlinesectioning.model.XConfig;
import org.unitime.timetable.onlinesectioning.model.XCourse;
import org.unitime.timetable.onlinesectioning.model.XCourseRequest;
import org.unitime.timetable.onlinesectioning.model.XEnrollment;
import org.unitime.timetable.onlinesectioning.model.XEnrollments;
import org.unitime.timetable.onlinesectioning.model.XOffering;
import org.unitime.timetable.onlinesectioning.model.XRequest;
import org.unitime.timetable.onlinesectioning.model.XReservation;
import org.unitime.timetable.onlinesectioning.model.XSection;
import org.unitime.timetable.onlinesectioning.model.XStudent;
import org.unitime.timetable.onlinesectioning.model.XSubpart;

/**
 * @author Tomas Muller
 */
public class CheckAssignmentAction implements OnlineSectioningAction<List<EnrollmentRequest>>{
	private static final long serialVersionUID = 1L;
	private static StudentSectioningMessages MSG = Localization.create(StudentSectioningMessages.class);
	private Long iStudentId;
	private Collection<ClassAssignmentInterface.ClassAssignment> iAssignment;

	public CheckAssignmentAction forStudent(Long studentId) {
		iStudentId = studentId;
		return this;
	}

	public CheckAssignmentAction withAssignment(Collection<ClassAssignmentInterface.ClassAssignment> assignment) {
		iAssignment = assignment;
		return this;
	}

	public Long getStudentId() { return iStudentId; }
	public Collection<ClassAssignmentInterface.ClassAssignment> getAssignment() { return iAssignment; }

	@Override
	public List<EnrollmentRequest> execute(OnlineSectioningServer server, OnlineSectioningHelper helper) {
		Lock readLock = server.readLock();
		try {
			Set<Long> offeringIds = new HashSet<Long>();
			for (ClassAssignmentInterface.ClassAssignment ca: getAssignment())
				if (ca != null && !ca.isFreeTime()) {
					XCourse course = server.getCourse(ca.getCourseId());
					if (course != null) offeringIds.add(course.getOfferingId());
				}

			Lock lock = server.lockStudent(getStudentId(), offeringIds, name());
			try {
				return check(server, helper);
			} finally {
				lock.release();
			}
		} finally {
			readLock.release();
		}
	}

	public List<EnrollmentRequest> check(OnlineSectioningServer server, OnlineSectioningHelper helper) {
		XStudent student = server.getStudent(getStudentId());
		if (student == null) throw new SectioningException(MSG.exceptionBadStudentId());
		List<EnrollmentRequest> requests = new ArrayList<EnrollmentRequest>();
		Hashtable<Long, EnrollmentRequest> courseId2request = new Hashtable<Long, EnrollmentRequest>();
		Hashtable<Long, XOffering> courseId2offering = new Hashtable<Long, XOffering>();
		for (ClassAssignmentInterface.ClassAssignment ca: getAssignment()) {
			// Skip free times and dummy sections
			if (ca == null || ca.isFreeTime() || ca.getClassId() == null || ca.isDummy()) continue;

			XCourse course = server.getCourse(ca.getCourseId());
			if (course == null)
				throw new SectioningException(MSG.exceptionCourseDoesNotExist(MSG.courseName(ca.getSubject(), ca.getClassNumber())));
			XOffering offering = server.getOffering(course.getOfferingId());
			if (offering == null)
				throw new SectioningException(MSG.exceptionCourseDoesNotExist(MSG.courseName(ca.getSubject(), ca.getClassNumber())));

			// Check section limits
			XSection section = offering.getSection(ca.getClassId());
			if (section == null)
				throw new SectioningException(MSG.exceptionEnrollNotAvailable(MSG.clazz(ca.getSubject(), ca.getCourseNbr(), ca.getSubpart(), ca.getSection())));

			// Check cancelled flag
			if (section.isCancelled()) {
				if (server.getConfig().getPropertyBoolean("Enrollment.CanKeepCancelledClass", false)) {
					boolean contains = false;
					for (XRequest r: student.getRequests())
						if (r instanceof XCourseRequest) {
							XCourseRequest cr = (XCourseRequest)r;
							if (cr.getEnrollment() != null && cr.getEnrollment().getSectionIds().contains(section.getSectionId())) { contains = true; break; }
						}
					if (!contains)
						throw new SectioningException(MSG.exceptionEnrollCancelled(MSG.clazz(ca.getSubject(), ca.getCourseNbr(), ca.getSubpart(), ca.getSection())));
				} else {
					throw new SectioningException(MSG.exceptionEnrollCancelled(MSG.clazz(ca.getSubject(), ca.getCourseNbr(), ca.getSubpart(), ca.getSection())));
				}
			}

			EnrollmentRequest request = courseId2request.get(ca.getCourseId());
			if (request == null) {
				request = new EnrollmentRequest(course, new ArrayList<XSection>());
				courseId2request.put(ca.getCourseId(), request);
				requests.add(request);
			}
			request.getSections().add(section);
			courseId2offering.put(course.getCourseId(), offering);
		}

		// Check for NEW and CHANGE deadlines
		check: for (EnrollmentRequest request: requests) {
			XCourse course = request.getCourse();
			List<XSection> sections = request.getSections();

			for (XRequest r: student.getRequests()) {
				if (r instanceof XCourseRequest) {
					XEnrollment enrollment = ((XCourseRequest)r).getEnrollment();
					if (enrollment != null && enrollment.getCourseId().equals(course.getCourseId())) { // course change
						for (XSection s: sections)
							if (!enrollment.getSectionIds().contains(s.getSectionId()) && !server.checkDeadline(course.getCourseId(), s.getTime(), OnlineSectioningServer.Deadline.CHANGE))
								throw new SectioningException(MSG.exceptionEnrollDeadlineChange(MSG.clazz(course.getSubjectArea(), course.getCourseNumber(), s.getSubpartName(), s.getName(course.getCourseId()))));
						continue check;
					}
				}
			}

			// new course
			for (XSection section: sections) {
				if (!server.checkDeadline(course.getOfferingId(), section.getTime(), OnlineSectioningServer.Deadline.NEW))
					throw new SectioningException(MSG.exceptionEnrollDeadlineNew(MSG.clazz(course.getSubjectArea(), course.getCourseNumber(), section.getSubpartName(), section.getName(course.getCourseId()))));
			}
		}

		// Check for DROP deadlines
		for (XRequest r: student.getRequests()) {
			if (r instanceof XCourseRequest) {
				XEnrollment enrollment = ((XCourseRequest)r).getEnrollment();
				if (enrollment != null && !courseId2offering.containsKey(enrollment.getCourseId())) {
					XOffering offering = server.getOffering(enrollment.getOfferingId());
					if (offering != null)
						for (XSection section: offering.getSections(enrollment)) {
							if (!server.checkDeadline(offering.getOfferingId(), section.getTime(), OnlineSectioningServer.Deadline.DROP))
								throw new SectioningException(MSG.exceptionEnrollDeadlineDrop(enrollment.getCourseName()));
						}
				}
			}
		}

		Hashtable<Long, XConfig> courseId2config = new Hashtable<Long, XConfig>();
		for (EnrollmentRequest request: requests) {
			XCourse course = request.getCourse();
			XOffering offering = courseId2offering.get(course.getCourseId());
			XEnrollments enrollments = server.getEnrollments(course.getOfferingId());
			List<XSection> sections = request.getSections();
			XSubpart subpart = offering.getSubpart(sections.get(0).getSubpartId());
			XConfig config = offering.getConfig(subpart.getConfigId());
			courseId2config.put(course.getCourseId(), config);

			XReservation reservation = null;
			reservations: for (XReservation r: offering.getReservations()) {
				if (!r.isApplicable(student)) continue;
				if (r.getLimit() >= 0 && r.getLimit() <= enrollments.countEnrollmentsForReservation(r.getReservationId())) {
					boolean contain = false;
					for (XEnrollment e: enrollments.getEnrollmentsForReservation(r.getReservationId()))
						if (e.getStudentId().equals(student.getStudentId())) { contain = true; break; }
					if (!contain) continue;
				}
				if (!r.getConfigsIds().isEmpty() && !r.getConfigsIds().contains(config.getConfigId())) continue;
				for (XSection section: sections)
					if (r.getSectionIds(section.getSubpartId()) != null && !r.getSectionIds(section.getSubpartId()).contains(section.getSectionId())) continue reservations;
				if (reservation == null || r.compareTo(reservation) < 0)
					reservation = r;
			}

			if (reservation == null || !reservation.canAssignOverLimit()) {
				for (XSection section: sections) {
					if (section.getLimit() >= 0 && section.getLimit() <= enrollments.countEnrollmentsForSection(section.getSectionId())) {
						boolean contain = false;
						for (XEnrollment e: enrollments.getEnrollmentsForSection(section.getSectionId()))
							if (e.getStudentId().equals(student.getStudentId())) { contain = true; break; }
						if (!contain)
							throw new SectioningException(MSG.exceptionEnrollNotAvailable(MSG.clazz(course.getSubjectArea(), course.getCourseNumber(), section.getSubpartName(), section.getName())));
					}
					if ((reservation == null || !offering.getSectionReservations(section.getSectionId()).contains(reservation)) && offering.getUnreservedSectionSpace(section.getSectionId(), enrollments) <= 0) {
						boolean contain = false;
						for (XEnrollment e: enrollments.getEnrollmentsForSection(section.getSectionId()))
							if (e.getStudentId().equals(student.getStudentId())) { contain = true; break; }
						if (!contain)
							throw new SectioningException(MSG.exceptionEnrollNotAvailable(MSG.clazz(course.getSubjectArea(), course.getCourseNumber(), section.getSubpartName(), section.getName())));
					}
				}

				if (config.getLimit() >= 0 && config.getLimit() <= enrollments.countEnrollmentsForConfig(config.getConfigId())) {
					boolean contain = false;
					for (XEnrollment e: enrollments.getEnrollmentsForConfig(config.getConfigId()))
						if (e.getStudentId().equals(student.getStudentId())) { contain = true; break; }
					if (!contain)
						throw new SectioningException(MSG.exceptionEnrollNotAvailable(MSG.courseName(course.getSubjectArea(), course.getCourseNumber())) + " " + config.getName());
				}
				if ((reservation == null || !offering.getConfigReservations(config.getConfigId()).contains(reservation)) && offering.getUnreservedConfigSpace(config.getConfigId(), enrollments) <= 0) {
					boolean contain = false;
					for (XEnrollment e: enrollments.getEnrollmentsForConfig(config.getConfigId()))
						if (e.getStudentId().equals(student.getStudentId())) { contain = true; break; }
					if (!contain)
						throw new SectioningException(MSG.exceptionEnrollNotAvailable(MSG.courseName(course.getSubjectArea(), course.getCourseNumber())) + " " + config.getName());
				}

				if (course.getLimit() >= 0 && course.getLimit() <= enrollments.countEnrollmentsForCourse(course.getCourseId())) {
					boolean contain = false;
					for (XEnrollment e: enrollments.getEnrollmentsForCourse(course.getCourseId()))
						if (e.getStudentId().equals(student.getStudentId())) { contain = true; break; }
					if (!contain)
						throw new SectioningException(MSG.exceptionEnrollNotAvailable(MSG.courseName(course.getSubjectArea(), course.getCourseNumber())));
				}
			}
		}

		for (EnrollmentRequest request: requests) {
			XCourse course = request.getCourse();
			XOffering offering = courseId2offering.get(course.getCourseId());
			List<XSection> sections = request.getSections();
			XSubpart subpart = offering.getSubpart(sections.get(0).getSubpartId());
			XConfig config = offering.getConfig(subpart.getConfigId());
			if (sections.size() < config.getSubparts().size()) {
				throw new SectioningException(MSG.exceptionEnrollmentIncomplete(MSG.courseName(course.getSubjectArea(), course.getCourseNumber())));
			} else if (sections.size() > config.getSubparts().size()) {
				throw new SectioningException(MSG.exceptionEnrollmentInvalid(MSG.courseName(course.getSubjectArea(), course.getCourseNumber())));
			}
			for (XSection s1: sections) {
				for (XSection s2: sections) {
					if (s1.getSectionId() < s2.getSectionId() && s1.isOverlapping(offering.getDistributions(), s2)) {
						throw new SectioningException(MSG.exceptionEnrollmentOverlapping(MSG.courseName(course.getSubjectArea(), course.getCourseNumber())));
					}
					if (!s1.getSectionId().equals(s2.getSectionId()) && s1.getSubpartId().equals(s2.getSubpartId())) {
						throw new SectioningException(MSG.exceptionEnrollmentInvalid(MSG.courseName(course.getSubjectArea(), course.getCourseNumber())));
					}
				}
				if (!offering.getSubpart(s1.getSubpartId()).getConfigId().equals(config.getConfigId())) {
					throw new SectioningException(MSG.exceptionEnrollmentInvalid(MSG.courseName(course.getSubjectArea(), course.getCourseNumber())));
				}
			}
			if (!offering.isAllowOverlap(student, config.getConfigId(), sections))
				for (EnrollmentRequest otherRequest: requests) {
					XOffering other = courseId2offering.get(otherRequest.getCourse().getCourseId());
					XConfig otherConfig = courseId2config.get(otherRequest.getCourse().getCourseId());
					if (!other.equals(offering) && !other.isAllowOverlap(student, otherConfig.getConfigId(), otherRequest.getSections())) {
						List<XSection> assignment = otherRequest.getSections();
						for (XSection section: sections)
							if (section.isOverlapping(offering.getDistributions(), assignment))
								throw new SectioningException(MSG.exceptionEnrollmentConflicting(MSG.courseName(course.getSubjectArea(), course.getCourseNumber())));
					}
				}
		}

		return requests;
	}

	@Override
	public String name() {
		return "check-assignment";
	}
}


text:
+++
categories = ["kotlin", "android", "teachingkotlin"]
date = 2019-09-30
description = "The second post in #TeachingKotlin series, this post goes over Kotlin's variables and their attributes, like visibility and getters/setters."
devLink = "https://dev.to/msfjarvis/teachingkotlin-part-2-variables-2api"
slug = "teaching-kotlin--variables"
socialImage = "uploads/teachingkotlin_social.webp"
tags = []
title = "#TeachingKotlin Part 2 - Variables"
+++

Even the variables in Kotlin are supercharged!

Let's start with a simple [data class](https://kotlinlang.org/docs/reference/data-classes.html#data-classes) and see how the variables in there behave.

```kotlin
data class Student(val name: String, val age: Int, val subjects: ArrayList<String>)
```

To use the variables in this class, Kotlin let's you directly use the dot notation for accessing.

```kotlin

>>> val s1 = Student("Keith Hernandez", 21, arrayListOf("Mathematics", "Social Studies"))
>>> println(s1.name)

Keith Hernandez

>>> println(s1) // data classes automatically generate `toString` and `hashCode`

Student(name=Keith Hernandez, age=21, subjects=[Mathematics, Social Studies])
```

For Java callers, Kotlin also generates getters and setter methods.

```java
final Student s1 = new Student("Keith Hernandez", 21, arrayListOf("Mathematics", "Social Studies"));
System.out.println(s1.getName());
System.out.println(s1);
```

The same properties apply to variables in non-data classes as well.

```kotlin

>>> class Item(id: Int, name: String) {

...     val itemId = id
...     val itemName = name
... }

>>> val item = Item(0, "Bricks")
>>> println(item.itemId)

0

>>> println(item)

Line_4$Item@46fb460a

>> >

```

As you can notice, the `toString` implementation is not identical to our data classes but that's a topic for another post. Back to variables!

## Customizing getters and setters

While Kotlin creates getters and setters automatically, we can customize their behavior.

```kotlin
class Item(id: Int, name: String) {
    var itemId = id
    var itemName = name
    var currentState: Pair<Int, String> = Pair(itemId, itemName)
        set(value) {
            itemId = value.first
            itemName = value.second
            field = value
        }
    override fun toString() : String {
        return "id=$itemId,name=$itemName"
    }
}
```

Let's take this for a spin in the Kotlin REPL and see how our `currentState` field behaves.

```kotlin
>>> val item = Item(0, "Nails")
>>> println(item)
id=0,name=Nails
>>> item.currentState = Pair(1, "Bricks")
>>> println(item)
id=1,name=Bricks
```

Notice how setting a new value to currentState mutates the other variables as well? That's because of our custom setter. These setters are identical to a normal top-level function except a reference to the field in question is available as the variable `field` for manipulation.

## Visibility modifiers

Kotlin's visibility modifiers aren't very well explained. There's the standard `public`, `private` and `protected`, but also the new `inner` and `internal`. I'll attempt to fill in those gaps.

### `inner`

`inner` is a modifier that only applies to classes declared within another one. It allows you to access members of the enclosing class. A sample might help explain this better.

```kotlin
class Outer {
    private val bar: Int = 1
    inner class Inner {
        fun foo() = bar
    }
}

val demo = Outer().Inner().foo() // == 1
```

The keyword `this` does not behave as some would normally expect in inner classes, go through the Kotlin documentation for `this` [here](https://kotlinlang.org/docs/reference/this-expressions.html) and I'll be happy to answer any further questions :)

### `internal`

`internal` applies to methods and properties in classes. It makes the field/method 'module-local', allowing it to be accessed within the same module and nowhere else. A module in this context is a logical compilation unit, like a Gradle subproject.

That's all for today! Hope you're liking the series so far. I'd love to hear feedback on what you want me to cover next and how to improve what I write :)


text:
@class PDFDocumentCrop;

@interface PDFPageCropViewController : PDFPageViewController
@property (nonatomic, strong) PDFDocumentCrop *crop;
@property (nonatomic, readonly) CGRect cropRect;
@end