text:
from vsa.daemon.daemon import Daemon
from vsa.infra.params import VSAD_XMLRPC_PORT
from vsa.infra import logger
import sys
from vsa.daemon.vsa_agent import VSAAgent
import SimpleXMLRPCServer

class MyXMLRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer):
    allow_reuse_address = True

def init_static_operations():
    """
    The description of init_static_operations comes here.
    @return
    """
    pass

class VSADaemon(Daemon):
    sport = VSAD_XMLRPC_PORT

    def set_port(self, port):
        """
        The description of set_port comes here.
        @param port
        @return
        """
        self.sport = port

    def pre_start(self):
        """
        The description of pre_start comes here.
        @return
        """
        init_static_operations()
        self.server = MyXMLRPCServer(("", self.sport))
        self.server.register_instance(VSAAgent())

    def run(self):
        """
        The description of run comes here.
        @return
        """
        logger.eventlog.info('VSAD started on port %d' % self.sport)
        print 'Listening on port %d' % self.sport
        sys.stdout.flush()
        try:
            self.server.serve_forever()
        finally:
            self.server.server_close()


text:
package io.github.mzmine.datamodel.features.types.numbers;

import io.github.mzmine.datamodel.features.types.numbers.abstr.IntegerType;
import org.jetbrains.annotations.NotNull;

public class ParentChromatogramIDType extends IntegerType {

  @NotNull
  @Override
  public final String getUniqueID() {
    // Never change the ID for compatibility during saving/loading of type
    return "parent_chromatogram_id";
  }

  @Override
  public @NotNull String getHeaderString() {
    return "Parent ID";
  }

}

redpajama_set_name: RedPajamaGithub


text:
dojo.provide("dojox.form.TimeSpinner");

dojo.require("dijit.form._Spinner");
dojo.require("dijit.form.NumberTextBox");
dojo.require("dojo.date");
dojo.require("dojo.date.locale");
dojo.require("dojo.date.stamp");

dojo.declare(
"dojox.form.TimeSpinner",
[dijit.form._Spinner],
{
	// summary: Time Spinner
	// description: This widget is the same as a normal NumberSpinner, but for the time component of a date object instead

	required: false,

	adjust: function(/* Object */ val, /*Number*/ delta){
		return dojo.date.add(val, "minute", delta)
	},

	//FIXME should we allow for constraints in this widget?
	isValid: function(){return true;},

	smallDelta: 5,

	largeDelta: 30,

	timeoutChangeRate: 0.50,

	parse: function(time, locale){
		return dojo.date.locale.parse(time, {selector:"time", formatLength:"short"});
	},

	format: function(time, locale){
		if (dojo.isString(time)) { return time; }
		return dojo.date.locale.format(time, {selector:"time", formatLength:"short"});
	},

	serialize: dojo.date.stamp.toISOString,

	value: "12:00 AM"

});


text:
Overview

Use the Joe Security Sandbox integration to detect and analyze potentially malicious files.
Using the integration you can analyze URL links and sample files on different machine types (Windows, Android, iOS and Mac OS X).

All file types are supported.

This integration was integrated and tested with Joe Security v2.

Playbooks

JoeSecurity -Detonate URL

JoeSecurity -Detonate File

JoeSecurity -Detonate File From URL

Use Cases

Add a file to the integrations war room.

Sample a file.

Get information on an old analysis.

Send a URL sample to Joe Security.

Prerequisites

Before you configure the integration, retrieve the API key from your Joe Security environment.

Use this link to log in to the Joe Security platform.

Click the button in the top-right corner and select Settings.

In the API Key section, select the I Agree checkbox.

Click the Generate API key button.

Copy the API key for later use.

Configure the Joe Security Integration on Cortex XSOAR

Navigate to Settings > Integrations > Servers & Services.

Search for Joe Security.

Click Add instance to create and configure a new integration instance.

Name: A textual name for the integration instance.

Joe Security URL: URL of the Joe Security server

API Key

Trust any certificate (not secure)

Do not use by default

Cortex XSOAR engine

Click Test to validate the URLs and connection.

Commands

You can execute these commands from the Cortex XSOAR CLI, as part of an automation, or in a playbook. After you successfully execute a command, a DBot message appears in the War Room with the command details.

Ping the server: joe-is-online

Submit a URL for analysis: joe-analysis-submit-url

Get analysis information: joe-analysis-info

Get analyes list: joe-list-analysis

Submit sample for analysis: joe-analysis-submit-sample

Search Analyses: joe-search

Download a report: joe-download-report

Download analysis file: joe-download-sample

Detonate a file: joe-detonate-file

Detonate a URL: joe-detonate-url

Ping the server

Pings the Joe Security server to verify that it is responsive.

Base Command

joe-is-online

Input

There is no input for this command.

Context Data

There is no context data for this command.

Raw Output

There is not raw output for this command.

Submit a URL for analysis

Submits a URL to Joe Security for analysis.

Base Command

joe-analysis-submit-url

Input

Parameter
Required
Description

url
Required
URL to submit for analysis.

should_wait
Optional
Specifies if the command polls for the result of the analysis.

comments
Optional
Comments for the analysis.

Systems
Optional

Comma separated list of operating systems to run analysis on.

Valid values are:

w7

w7x64

w7_1

w7_2

w7native

android2

android3

mac1

w7l

w7x64l

w10

android4

w7x64native

w7_3

w10native

android5native_1

w7_4

w7_5

w10x64

w7x64_hvm

android6

iphone1

w7_sec

macvm

w7_lang_packs

w7x64native_hvm

lnxubuntu1

lnxcentos1android7_nougat

internet-access
Optional

If to enable full internet access (boolean).

Default is True.

Context Data

Path
Type
Description

Joe.Analysis.WebID
String
Web ID

Joe.Analysis.FileName
String
Sample data, could be a file name or URL

Joe.Analysis.Status
String
Analysis status

Joe.Analysis.Comments
String
Analysis comments

Joe.Analysis.Time
Date
Time submitted

Joe.Analysis.Runs
Unknown
Sub-analysis information

Joe.Analysis.Result
String
Analysis results

Joe.Analysis.Errors
Unknown
Errors raised during sampling

Joe.Analysis.Systems
Unknown
Analysis operating system

Joe.Analysis.MD5
String
MD5 hash of the analysis sample

Joe.Analysis.SHA1
String
SHA-1 hash of the analysis sample

Joe.Analysis.SHA256
String
SHA-256 has of the analysis sample

DBotScore.Vendor
String
The name of the vendor (JoeSecurity)

DBotScore.Indicator
Unknown
The name of the sample file or URL

DBotScore.Type
String

url - for URL samples

file - for anything not URL sample

DBotScore.Score
String

Cortex XSOAR Dbot Score:

Bad

Suspicious

Good

DBotScore.Malicious.Vendor
String
The name of the vendor (JoeSecurity)

DBotScore.Malicious.Detections
String
The sub analysis detection statuses

DBotScore.Malicious.SHA1
String
SHA-1 hash of the file

Raw Output

There is no raw output for this command.

Get analysis information

Returns information for a specified analysis.

Base Command

joe-analysis-info

Input

Parameter
Required
Description

webId
Required
Web ID. Supports comma-separated arrays.

Context Data

Path
Type
Description

Joe.Analysis.WebID
String
Web ID

Joe.Analysis.SampleName
String
Sample Data, could be a file name or URL

Joe.Analysis.Status
String
Analysis status

Joe.Analysis.Comments
String
Analysis comments

Joe.Analysis.Time
Date
Submitted time

Joe.Analysis.Runs
Unknown
Sub-analysis information

Joe.Analysis.Result
String
Analysis results

Joe.Analysis.Errors
Unknown
Errors raised during sampling

Joe.Analysis.Systems
Unknown
Analysis operating system

Joe.Analysis.MD5
String
MD5 hash of the analysis sample

Joe.Analysis.SHA1
String
SHA-1 hash of the analysis sample

Joe.Analysis.SHA256
String
SHA-256 hash of the analysis sample

DBotScore.Vendor
String
The name of the vendor (JoeSecurity)

DBotScore.Indicator
Unknown
The name of the sample file or URL

DBotScore.Type
string

url - for URL samples

file - for anything not URL sample

DBotScore.Score
String

Cortex XSOAR Dbot Score:

Bad

Suspicious

Good

DBotScore.Malicious.Vendor
String
The name of the vendor (JoeSecurity)

DBotScore.Malicious.Detections
String
The sub analysis detection statuses

DBotScore.Malicious.SHA1
String
The SHA-1 hash of the file

Raw Output

There is no raw output for this command.

Get analyses list

Returns a list of all analyses.

Base Command

joe-list-analysis

Input

There is no input for this command.

Context Data

Path
Type
Description

Joe.Analysis.WebID
String
Web ID

Joe.Analysis.SampleName
String
Sample Data, could be a file name or URL

Joe.Analysis.Status
String
Analysis status

Joe.Analysis.Comments
String
Analysis comments

Joe.Analysis.Time
Date
Submitted time

Joe.Analysis.Runs
Unknown
Sub-analysis information

Joe.Analysis.Result
String
Analysis results

Joe.Analysis.Errors
Unknown
Errors raised during sampling

Joe.Analysis.Systems
Unknown
Analysis operating system

Joe.Analysis.MD5
String
MD5 hash of the analysis sample

Joe.Analysis.SHA1
String
SHA-1 hash of the analysis sample

Joe.Analysis.SHA256
String
SHA-256 hash of the analysis sample

DBotScore.Vendor
String
The name of the vendor (JoeSecurity)

DBotScore.Indicator
Unknown
The name of the sample file or URL

DBotScore.Type
String

url - for URL samples

file - for anything not URL sample

DBotScore.Score
String

Cortex XSOAR Dbot Score:

Bad

Suspicious

Good

DBotScore.Malicious.Vendor
String
The name of the vendor (JoeSecurity)

DBotScore.Malicious.Detections
String
The sub analysis detection statuses

DBotScore.Malicious.SHA1
String
The SHA-1 hash of the file

Raw Output

There is no raw output for this command.

Submit sample for analysis

Submits a sample to Joe Security for analysis.

Base Command

joe-analysis-submit-sample

Input

Parameter
Required
Description

file_id
Optional
War Room entry of a file (for example, 3245@4).

sample_url
Optional
URL of a sample file. Supports comma-seperated arrays.

should_wait
Optional
Specifies if the command polls for the result of the analysis

comments
Optional
Comments for the analysis

systems
Optional

Comma separated list of operating systems to run analysis on.

Valid values are:

w7

w7x64

w7_1

w7_2

w7native

android2

android3

mac1

w7l

w7x64l

w10

android4

w7x64native

w7_3

w10native

android5native_1

w7_4

w7_5

w10x64

w7x64_hvm

android6

iphone1

w7_sec

macvm

w7_lang_packs

w7x64native_hvm

lnxubuntu1

lnxcentos1

android7_nougat

internet-access
Optional
Enable full internet access. Default is True.

Context Data

Path
Type
Description

Joe.Analysis.WebID
String
Web ID

Joe.Analysis.SampleName
String
Sample data, could be a file name or URL

Joe.Analysis.Status
String
Analysis status

Joe.Analysis.Comments
String
Analysis comments

Joe.Analysis.Time
Date
Submitted time

Joe.Analysis.Runs
Unknown
Sub-analysis information

Joe.Analysis.Result
String
Analysis results

Joe.Analysis.Errors
Unknown
Errors raised during sampling

Joe.Analysis.Systems
Unknown
Analysis operating system

Joe.Analysis.MD5
String
MD5 hash of the analysis sample

Joe.Analysis.SHA1
String
SHA-1 hash of the analysis sample

Joe.Analysis.SHA256
String
SHA-256 hash of the analysis sample

DBotScore.Vendor
String
The name of the vendor (JoeSecurity)

DBotScore.Indicator
Unknown
The name of the sample file or URL

DBotScore.Type
String

url - for URL samples

file - for anything not URL sample

DBotScore.Score
String

Cortex XSOAR Dbot Score:

Bad

Suspicious

Good

DBotScore.Malicious.Vendor
String
The name of the vendor (JoeSecurity)

DBotScore.Malicious.Detections
String
The sub analysis detection statuses

DBotScore.Malicious.SHA1
String
The SHA-1 hash of the file

Raw Output

There is no raw output for this command.

Search Analyses

Search through all analyses in Joe Security.

Base Command

joe-search

Input

Parameter
Description

query

String to search for in these fields:

webID

MD5

SHA1

SHA256

filename

URL

comments

Context Data

Path
Type
Description

Joe.Analysis.WebID
String
Web ID

Joe.Analysis.SampleName
String
Sample data, could be a file name or URL

Joe.Analysis.Status
String
Analysis status

Joe.Analysis.Comments
String
Analysis comments

Joe.Analysis.Time
Date
Submitted time

Joe.Analysis.Runs
Unknown
Sub-analysis information

Joe.Analysis.Result
String
Analysis results

Joe.Analysis.Errors
Unknown
Errors raised during sampling

Joe.Analysis.Systems
Unknown
Analysis operating system

Joe.Analysis.MD5
String
MD5 has of the analysis sample

Joe.Analysis.SHA1
String
SHA-1 hash of the analysis sample

Joe.Analysis.SHA256
String
SHA-256 has of the analysis sample

DBotScore.Vendor
String
The name of the vendor (JoeSecurity)

DBotScore.Indicator
Unknown
The name of the sample file or URL

DBotScore.Type
String

url - for URL samples

file - for anything not URL sample

DBotScore.Score
String

Cortex XSOAR Dbot Score:

Bad

Suspicious

Good

DBotScore.Malicious.Vendor
String
The name of the vendor (JoeSecurity)

DBotScore.Malicious.Detections
String
The sub analysis detection statuses

DBotScore.Malicious.SHA1
String
The SHA-1 hash of the file

Raw Output

There is no raw output for this command.

Download a report

Downloads a resource associated to a report. This can be the full report, dropped binaries, and so on. See all supported report types here:

Base Command

joe-download-report

Input

Parameter
Required
Description

webid
Required

Web ID

type
Optional

Resource type to download, default is html

Context Data

Path
Type
Description

InfoFile.Name
String
Name of the file

InfoFile.EntryID
String
The entry ID of the sample

InfoFile.Size
Number
The size of the file

InfoFile.Type
String
File type (for example, PE)

InfoFile.Info
String
Basic information about the file

File.Extension
String
File extension

Raw Output

There is no raw output for this command.

Download analysis file

Downloads the sample file of an analysis. For security considerations, the extension is dontrun.

Base Command

joe-download-sample

Input

Parameter
Required
Description

webid
Required

Web ID

Context Data

Path
Type
Description

File.Size
Number
The size of the file

File.SHA1
String
SHA-1 hash of the file

File.SHA256
String
SHA-256 hash of the file

File.Name
String
The sample name

File.SSDeep
String
ssdeep hash of the file

File.EntryID
String
War room entry ID of the file

File.Info
String
Basic information of the file

File.Type
String
File type (for example PE)

File MD5
String
MD5 hash of the file

File.Extension
String
File extension

Raw Output

There is no raw output for this command.

Detonate a file

Submits a file for analysis.

Base Command

joe-detonate-file

Input

Parameter
Required
Description

file_id
Optional
War room entry of a file (for example, 3245@4)

sample_url
Optional
URL of a sample file

comments
Optional
Comments for the analysis

systems
Optional

Comma separated list of operating systems to run the analysis on.

Valid values are:

w7

w7x64

w7_1

w7_2

w7native

android2

android3

mac1

w7l

w7x64l

w10

android4

w7x64native

w7_3

w10native

android5native_1

w7_4

w7_5

w10x64

w7x64_hvm

android6

iphone1

w7_sec

macvm

w7_lang_packs

w7x64native_hvm

lnxubuntu1

lnxcentos1

android7_nougat

internet-access
Optional
If to enable full internet access. Default is True

Context Data

Path
Type
Description

Joe.Analysis.WebID
String
Web ID

Joe.Analysis.SampleName
String
Sample Data, could be a file name or URL

Joe.Analysis.Status
String
Analysis status

Joe.Analysis.Comments
String
Analysis comments

Joe.Analysis.Time
Date
Submission time

Joe.Analysis.Runs
Unknown
Sub-analysis information

Joe.Analysis.Result
String
Analysis results

Joe.Analysis.Errors
Unknown
Errors raised during sampling

Joe.Analysis.Systems
Unknown
Analysis operating system

Joe.Analysis.MD5
String
MD5 hash of the analysis sample

Joe.Analysis.SHA1
String
SHA-1 hash of the analysis sample

Joe.Analysis.SHA256
String
SHA-256 hash of the analysis sample

DBotScore.Vendor
String
The name of the vendor (JoeSecurity)

DBotScore.Indicator
Unknown
The name of the sample file or URL

DBotScore.Type
String

url - for URL samples

file - for anything not URL sample

DBotScore.Score
String

Cortex XSOAR Dbot Score:

Bad

Suspicious

Good

DBotScore.Malicious.Vendor
String
The name of the vendor (JoeSecurity)

DBotScore.Malicious.Detections
String
The sub analysis detection statuses

DBotScore.Malicious.SHA1
String
The SHA-1 has of the file

Raw Output

There is no raw output for this command.

Detonate a URL

Submits a URL for analysis.

Base Command

joe-detonate-url

Input

Parameter
Required
Description

url
Required
sample URL

comments
Optional
Comments for the analysis

systems
Optional

Comma separated list of operating systems to run the analysis on.

Valid values are:

w7

w7x64

w7_1

w7_2

w7native

android2

android3

mac1

w7l

w7x64l

w10

android4

w7x64native

w7_3

w10native

android5native_1

w7_4

w7_5

w10x64

w7x64_hvm

android6

iphone1

w7_sec

macvm

w7_lang_packs

w7x64native_hvm

lnxubuntu1

lnxcentos1

android7_nougat

internet-access
Optional
If to enable full internet access. Default is True.

Context Data

Path
Type
Description

Joe.Analysis.WebID
String
Web ID

Joe.Analysis.SampleName
String
Sample data, could be a file name or URL

Joe.Analysis.Status
String
Analysis status

Joe.Analysis.Comments
String
Analysis comments

Joe.Analysis.Time
Date
Submission time

Joe.Analysis.Runs
Unknown
Sub-analysis information

Joe.Analysis.Result
String
Analysis results

Joe.Analysis.Errors
Unknown
Errors raised during sampling

Joe.Analysis.Systems
Unknown
Analysis operating system

Joe.Analysis.MD5
String
MD5 hash of the analysis sample

Joe.Analysis.SHA1
String
SHA-1 hash of the analysis sample

Joe.Analysis.SHA256
String
SHA-256 hash of the analysis sample

DBotScore.Vendor
String
The name of the vendor (JoeSecurity)

DBotScore.Indicator
Unknown
The name of the sample file or URL

DBotScore.Type
String

url - for URL samples

file - for anything not URL sample

DBotScore.Score
String

Cortex XSOAR Dbot Score:

Bad

Suspicious

Good

DBotScore.Malicious.Vendor
String
The name of the vendor (JoeSecurity)

DBotScore.Malicious.Detections
String
The sub analysis detection statuses

DBotScore.Malicious.SHA1
String
The SHA-1 hash of the file

Raw Output

There is no raw output for this command.


text:
![Planning](img/statespace.png)

For the AIND Project 3 on planning we learnt the language of formal logic to describe and define complex planning problems and how they can be implemented as a graph. Once in graph form, solutions to planning problems can be found using many well known graph search algorithms.

## The Air Cargo Transport Problem
In the air cargo problem, there are three distinct variables, airports, planes and cargo. There are several states and actions available such as, cargo can either be at airports or in planes and be loaded or unloaded from planes, while planes are at an airport, but as an action can travel between airports.

The problems begin with cargo and planes in an initial state and define which airport each piece of cargo should be at in the goal state.

Airports are defined by their 3 letter airport code such as SFO for San Francisco, cargo and planes are simply numbered C1, C2 and P1, P2 etc.

## Instructions
```
$ python run_search.py -m
```

## Additional Material

1. [Heuristics Analysis](heuristic_analysis.md)

2. [Research Review](research_review.md)


text:
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea;

import com.intellij.dvcs.DvcsUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.changes.patch.BlobIndexUtil;
import com.intellij.openapi.vcs.history.ShortVcsRevisionNumber;
import com.intellij.openapi.vcs.history.VcsRevisionNumber;
import com.intellij.openapi.vfs.VirtualFile;
import git4idea.commands.Git;
import git4idea.commands.GitCommand;
import git4idea.commands.GitHandler;
import git4idea.commands.GitLineHandler;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

import java.util.Date;
import java.util.StringTokenizer;

public class GitRevisionNumber implements ShortVcsRevisionNumber {
  /**
   * the hash from 40 zeros representing not yet created commit
   */
  public static final String NOT_COMMITTED_HASH = BlobIndexUtil.NOT_COMMITTED_HASH;

  public static final GitRevisionNumber HEAD = new GitRevisionNumber("HEAD");

  /**
   * the revision number (40 character hashcode, tag, or reference). In some cases incomplete hashcode could be used.
   */
  @NotNull private final String myRevisionHash;
  @NotNull private final Date myTimestamp;

  private static final Logger LOG = Logger.getInstance(GitRevisionNumber.class);

  /**
   * A constructor from version. The current date is used.
   */
  public GitRevisionNumber(@NonNls @NotNull String version) {
    // TODO review usages
    myRevisionHash = version;
    myTimestamp = new Date();
  }

  public GitRevisionNumber(@NotNull String version, @NotNull Date timeStamp) {
    myTimestamp = timeStamp;
    myRevisionHash = version;
  }

  @Override
  @NotNull
  public String asString() {
    return myRevisionHash;
  }

  @Override
  public String toShortString() {
    return asString().substring(0, 7);
  }

  @NotNull
  public Date getTimestamp() {
    return myTimestamp;
  }

  @NotNull
  public String getRev() {
    return myRevisionHash;
  }

  @NotNull
  public String getShortRev() {
    return DvcsUtil.getShortHash(myRevisionHash);
  }

  @Override
  public int compareTo(VcsRevisionNumber crev) {
    if (this == crev) return 0;

    if (crev instanceof GitRevisionNumber) {
      GitRevisionNumber other = (GitRevisionNumber)crev;
      if (myRevisionHash.equals(other.myRevisionHash)) {
        return 0;
      }

      if (other.myRevisionHash.indexOf("[") > 0) {
        return myTimestamp.compareTo(other.myTimestamp);
      }

      // check for parent revs
      String otherName = null;
      String thisName = null;
      int otherParents = -1;
      int thisParent = -1;

      if (other.myRevisionHash.contains("~")) {
        int tildeIndex = other.myRevisionHash.indexOf('~');
        otherName = other.myRevisionHash.substring(0, tildeIndex);
        otherParents = Integer.parseInt(other.myRevisionHash.substring(tildeIndex));
      }

      if (myRevisionHash.contains("~")) {
        int tildeIndex = myRevisionHash.indexOf('~');
        thisName = myRevisionHash.substring(0, tildeIndex);
        thisParent = Integer.parseInt(myRevisionHash.substring(tildeIndex));
      }

      if (otherName == null && thisName == null) {
        final int result = myTimestamp.compareTo(other.myTimestamp);
        if (result == 0) {
          // it can NOT be 0 - it would mean that revisions are equal but they have different hash codes
          // but this is NOT correct. but we don't know here how to sort
          return myRevisionHash.compareTo(other.myRevisionHash);
        }
        return result;
      }
      else if (otherName == null) {
        return 1;  // I am an ancestor of the compared revision
      }
      else if (thisName == null) {
        return -1; // the compared revision is my ancestor
      }
      else {
        return thisParent - otherParents;  // higher relative rev numbers are older ancestors
      }
    }

    return -1;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj) return true;
    if ((obj == null) || (obj.getClass() != getClass())) return false;

    GitRevisionNumber test = (GitRevisionNumber)obj;
    // TODO normalize revision string?
    return myRevisionHash.equals(test.myRevisionHash);
  }

  @Override
  public int hashCode() {
    return myRevisionHash.hashCode();
  }

  @NotNull
  public static GitRevisionNumber resolve(Project project, VirtualFile vcsRoot, @NonNls String rev) throws VcsException {
    GitLineHandler h = new GitLineHandler(project, vcsRoot, GitCommand.REV_LIST);
    h.setSilent(true);
    h.addParameters("--timestamp", "--max-count=1", rev);
    h.endOptions();
    final String output = Git.getInstance().runCommand(h).getOutputOrThrow();
    return parseRevlistOutputAsRevisionNumber(h, output);
  }

  @NotNull
  public static GitRevisionNumber parseRevlistOutputAsRevisionNumber(@NotNull GitHandler h, @NotNull String output)
    throws VcsException
  {
    try {
      StringTokenizer tokenizer = new StringTokenizer(output, "\n\r \t", false);
      LOG.assertTrue(tokenizer.hasMoreTokens(), "No required tokens in the output: \n" + output);
      Date timestamp = GitUtil.parseTimestampWithNFEReport(tokenizer.nextToken(), h, output);
      return new GitRevisionNumber(tokenizer.nextToken(), timestamp);
    }
    catch (Exception e) {
      throw new VcsException("Couldn't parse the output: ["  + output + "]", e);
    }
  }

  @Override
  public String toString() {
    return myRevisionHash;
  }
}


text:
/**
 * Created by schape on 21/10/14.
 */

$(document).ready(function() {
    'use strict';
    /* delete confirm */
    $('form#delete').submit(function (e) {
        var $form = $(this), $hidden = $form.find('input[name="modal"]');
        if ($hidden.val() === '0') {
            e.preventDefault();
            $('#delete_confirm').modal('show');
            $('#delete_confirm').find('button.btn-danger').click(function () {
                $('#delete_confirm').modal('hide');
                $hidden.val('1');
                $form.submit();
            });
        }
    });
});


text:
package org.lwjgl.llvm;

import org.lwjgl.system.*;
import org.lwjgl.system.libffi.*;

import static org.lwjgl.system.APIUtil.*;
import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.system.libffi.LibFFI.*;

/**
 * Instances of this interface may be passed to the {@link LLVMDisassembler#LLVMCreateDisasm CreateDisasm}, {@link LLVMDisassembler#LLVMCreateDisasmCPU CreateDisasmCPU} and {@link LLVMDisassembler#LLVMCreateDisasmCPUFeatures CreateDisasmCPUFeatures} methods.
 *
 *
Type

 *
 *

 * int (*{@link #invoke}) (
 *     void *DisInfo,
 *     uint64_t PC,
 *     uint64_t Offset,
 *     uint64_t Size,
 *     int TagType,
 *     void *TagBuf
 * )

 */
@FunctionalInterface
@NativeType("int (*) (void *, uint64_t, uint64_t, uint64_t, int, void *)")
public interface LLVMOpInfoCallbackI extends CallbackI {

    FFICIF CIF = apiCreateCIF(
        FFI_DEFAULT_ABI,
        ffi_type_sint32,
        ffi_type_pointer, ffi_type_uint64, ffi_type_uint64, ffi_type_uint64, ffi_type_sint32, ffi_type_pointer
    );

    @Override
    default FFICIF getCallInterface() { return CIF; }

    @Override
    default void callback(long ret, long args) {
        int __result = invoke(
            memGetAddress(memGetAddress(args)),
            memGetLong(memGetAddress(args + POINTER_SIZE)),
            memGetLong(memGetAddress(args + 2 * POINTER_SIZE)),
            memGetLong(memGetAddress(args + 3 * POINTER_SIZE)),
            memGetInt(memGetAddress(args + 4 * POINTER_SIZE)),
            memGetAddress(memGetAddress(args + 5 * POINTER_SIZE))
        );
        apiClosureRet(ret, __result);
    }

    /**
     * The type for the operand information call back function.
     *
     *
This is called to get the symbolic information for an operand of an instruction. Typically this is from the relocation information, symbol table, etc.
     * That block of information is saved when the disassembler context is created and passed to the call back in the {@code DisInfo} parameter. The
     * instruction containing operand is at the {@code PC} parameter. For some instruction sets, there can be more than one operand with symbolic information.
     * To determine the symbolic operand information for each operand, the bytes for the specific operand in the instruction are specified by the
     * {@code Offset} parameter and its byte width is the size parameter. For instructions sets with fixed widths and one symbolic operand per instruction,
     * the {@code Offset} parameter will be zero and {@code Size} parameter will be the instruction width. The information is returned in {@code TagBuf} and
     * is {@code Triple} specific with its specific information defined by the value of {@code TagType} for that {@code Triple}. If symbolic information is
     * returned the function returns 1, otherwise it returns 0.

     */
    int invoke(@NativeType("void *") long DisInfo, @NativeType("uint64_t") long PC, @NativeType("uint64_t") long Offset, @NativeType("uint64_t") long Size, int TagType, @NativeType("void *") long TagBuf);

}


text:
/* */

var homedir = process.env.HOME || '.';
var rcdir = homedir + '/.server';

var config = {
	sockfile: rcdir + '/backend.sock',
	pidfile: rcdir + '/backend.pid',
	logfile: rcdir + '/backend.log'
};

var backend_logic = require('./backend.js');

var fs = require('fs');
var server = undefined;

function do_cleanup() {
	fs.exists(config.sockfile, function(exists) {
		if(!exists) return;
		fs.unlink(config.sockfile, function(err) {
			if(err) process.stderr.write('Failed to unlink ' + config.sockfile +': ' + err + "\n");
		});
	});
}

var init = require('init');
function do_start(cb) {

	if(!fs.existsSync(rcdir)) {
		fs.mkdirSync(rcdir);
	}

	init.start({
	    pidfile : config.pidfile,
	    logfile : config.logfile,
	    run     : function () {
			var dnode = require('dnode');
			var net = require('net');
			server = net.createServer(function (c) {
			    var d = dnode(backend_logic);
			    c.pipe(d).pipe(c);
			});
			server.listen(config.sockfile);
			server.on('error', function(err) {
				process.stderr.write('Error: ' + err + "̛\n");
			});
			server.on('close', function() {
				do_cleanup();
			});
	    },
		success: function(pid, wasRunning) {
			cb(undefined, pid, wasRunning);
		},
		failure: function(error) {
			cb(error);
		}
	});
}

function do_stop(cb) {
	if(server) {
		service.on('close', function() {
			init.stop(config.pidfile, cb);
		});
		service.close();
	} else {
		init.stop(config.pidfile, cb);
		do_cleanup();
	}
}

/* */

function do_connect(cb) {
	var net = require('net');
	var c = net.connect(config.sockfile);
	c.on('error', function(e) {
		if( (e.code == 'ECONNREFUSED') || (e.code == 'ENOENT') ) {
			process.stderr.write('Failed to connect, trying to restart service...\n');

			var spawn = require('child_process').spawn,
			    child = spawn(process.argv[0], [process.argv[1], 'start']);
			child.on('error', function(err) {
				process.stderr.write('Error: ' + err + "\n");
			});
			child.on('exit', function(code) {
				if(code !== 0) {
					cb('Failed to start service');
				} else {
					process.stderr.write('Service restarted.\n');
					setTimeout(function() {
						do_connect(cb);
					}, 250);
				}
			});
		} else {
			cb(e, c);
		}
	});
	c.on('connect', function() {
		cb(undefined, c);
	});
}

if(process.argv[2] === 'start') {
	do_start(function(err, pid, wasRunning) {
		if(err) {
			process.stderr.write('Failed to start service: ' + err + "\n");
		} else if(wasRunning) {
			process.stderr.write('Service was running already.\n');
		} else {
			process.stderr.write('Started service.\n');
		}
	});
} else if(process.argv[2] === 'status') {
	init.status(config.pidfile, function(results) {
		process.stderr.write(JSON.stringify(results) + "\n");
	});
} else if(process.argv[2] === 'stop') {
	do_stop(function(stopped) {
		if(!stopped) {
			process.stderr.write('Failed to stop service!\n');
		} else {
			process.stderr.write('Service stopped.\n');
		}
	});
} else {
	var stderr = process.stderr,
	    stdout = process.stdout,
	    stdin = process.stdin;
	do_connect(function(err, c) {
		if(err) {
			stderr.write('Error: ' + err + "\n");
		} else {
			stdin.resume();
			stdin.pipe(c).pipe(stdout);
		}
	});
}

/* EOF */


text:
<?php

namespace Phpbr\AppBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;

class ForumTopicFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder
            ->add('subject', TextType::class, array('attr' => array('class' => ''), 'required' => true))
            ->add(
                'message',
                TextareaType::class,
                array(
                    'attr' => array(
                        'class' => 'meltdown-editor',
                        'rows' => 15
                    ),
                    'required' => true
                )
            )
            ->add('Salvar', SubmitType::class)
        ;
    }

    public function configureOptions(OptionsResolver $resolver) {
        $resolver->setDefaults(array(
            'data_class' => 'Phpbr\AppBundle\Entity\Forum\Topic'
        ));
    }

    public function getBlockPrefix() {
        return 'phpbr_forum_topic_new';
    }

    public function getName() {
        return $this->getBlockPrefix();
    }
}


text:
package io.motown.ocpp.viewmodel.persistence.repositories;

import io.motown.ocpp.viewmodel.persistence.entities.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;

public class TransactionRepository {

    private static final Logger LOG = LoggerFactory.getLogger(ReservationIdentifierRepository.class);

    private EntityManagerFactory entityManagerFactory;

    public Transaction findTransactionById(Long id) {
        EntityManager entityManager = getEntityManager();
        try {
            return entityManager.find(Transaction.class, id);
        } finally {
            entityManager.close();
        }
    }

    public void insert(Transaction transaction) {
        EntityManager em = getEntityManager();
        EntityTransaction tx = null;

        try {
            tx = em.getTransaction();
            tx.begin();

            em.persist(transaction);
            tx.commit();
        } catch (Exception e) {
            if (tx != null && tx.isActive()) {
                LOG.warn("Transaction is still active while it should not be, rolling back.");
                tx.rollback();
            }
            throw e;
        } finally {
            em.close();
        }
    }

    public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
        this.entityManagerFactory = entityManagerFactory;
    }

    private EntityManager getEntityManager() {
        return this.entityManagerFactory.createEntityManager();
    }
}


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="register">

        <roleset framnet="" id="register.01" name="measure" vncls="54.1">
            <roles>
                <role descr="measurer" f="" n="0">

                    <vnrole vncls="54.1" vntheta="agent"/>
                </role>

                <role descr="thing measured" f="" n="1">

                    <vnrole vncls="54.1" vntheta="theme"/>
                </role>

                <role descr="yardstick, standard of measurement" f="" n="2"/>
                <role descr="measurement" f="" n="3">

                    <vnrole vncls="54.1" vntheta="attribute"/>
                </role>

                <note>Additional roles not seen in any examples.  See verb entry for semantics of these roles.</note>
            </roles>

            <example name="Args 0 & 1, within LVC" src="CallHome" type="">
                <text>actually I was a bit bad too because %um I had you know you-1 had PRO-1 to keep register of the movement of the baby.</text>

                <note/>
                <arg f="" n="0">PRO-1</arg>
                <arg f="lvb" n="m">keep</arg>
                <rel f="">register</rel>
                <arg f="" n="1">of the movement of the baby</arg>
            </example>

            <note>Roleset based on register.01</note>
        </roleset>

        <note/>
    </predicate>
    <note/>
</frameset>


text:
"""
Types for objects parsed from the configuration.
"""
import json
import ntpath
import os
import re
from collections import namedtuple

from docker.utils.ports import build_port_bindings

from ..const import COMPOSEFILE_V1 as V1
from ..utils import unquote_path
from .errors import ConfigurationError
from compose.const import IS_WINDOWS_PLATFORM
from compose.utils import splitdrive

win32_root_path_pattern = re.compile(r'^[A-Za-z]\:\\.*')

class VolumeFromSpec(namedtuple('_VolumeFromSpec', 'source mode type')):

    # TODO: drop service_names arg when v1 is removed
    @classmethod
    def parse(cls, volume_from_config, service_names, version):
        func = cls.parse_v1 if version == V1 else cls.parse_v2
        return func(service_names, volume_from_config)

    @classmethod
    def parse_v1(cls, service_names, volume_from_config):
        parts = volume_from_config.split(':')
        if len(parts) > 2:
            raise ConfigurationError(
                "volume_from {} has incorrect format, should be "
                "service[:mode]".format(volume_from_config))

        if len(parts) == 1:
            source = parts[0]
            mode = 'rw'
        else:
            source, mode = parts

        type = 'service' if source in service_names else 'container'
        return cls(source, mode, type)

    @classmethod
    def parse_v2(cls, service_names, volume_from_config):
        parts = volume_from_config.split(':')
        if len(parts) > 3:
            raise ConfigurationError(
                "volume_from {} has incorrect format, should be one of "
                "'<service name>[:<mode>]' or "
                "'container:<container name>[:<mode>]'".format(volume_from_config))

        if len(parts) == 1:
            source = parts[0]
            return cls(source, 'rw', 'service')

        if len(parts) == 2:
            if parts[0] == 'container':
                type, source = parts
                return cls(source, 'rw', type)

            source, mode = parts
            return cls(source, mode, 'service')

        if len(parts) == 3:
            type, source, mode = parts
            if type not in ('service', 'container'):
                raise ConfigurationError(
                    "Unknown volumes_from type '{}' in '{}'".format(
                        type,
                        volume_from_config))

        return cls(source, mode, type)

    def repr(self):
        return '{v.type}:{v.source}:{v.mode}'.format(v=self)

def parse_restart_spec(restart_config):
    if not restart_config:
        return None
    parts = restart_config.split(':')
    if len(parts) > 2:
        raise ConfigurationError(
            "Restart %s has incorrect format, should be "
            "mode[:max_retry]" % restart_config)
    if len(parts) == 2:
        name, max_retry_count = parts
    else:
        name, = parts
        max_retry_count = 0

    return {'Name': name, 'MaximumRetryCount': int(max_retry_count)}

def serialize_restart_spec(restart_spec):
    if not restart_spec:
        return ''
    parts = [restart_spec['Name']]
    if restart_spec['MaximumRetryCount']:
        parts.append(str(restart_spec['MaximumRetryCount']))
    return ':'.join(parts)

def parse_extra_hosts(extra_hosts_config):
    if not extra_hosts_config:
        return {}

    if isinstance(extra_hosts_config, dict):
        return dict(extra_hosts_config)

    if isinstance(extra_hosts_config, list):
        extra_hosts_dict = {}
        for extra_hosts_line in extra_hosts_config:
            # TODO: validate string contains ':' ?
            host, ip = extra_hosts_line.split(':', 1)
            extra_hosts_dict[host.strip()] = ip.strip()
        return extra_hosts_dict

def normalize_path_for_engine(path):
    """Windows paths, c:\\my\\path\\shiny, need to be changed to be compatible with
    the Engine. Volume paths are expected to be linux style /c/my/path/shiny/
    """
    drive, tail = splitdrive(path)

    if drive:
        path = '/' + drive.lower().rstrip(':') + tail

    return path.replace('\\', '/')

def normpath(path, win_host=False):
    """ Custom path normalizer that handles Compose-specific edge cases like
        UNIX paths on Windows hosts and vice-versa. """

    sysnorm = ntpath.normpath if win_host else os.path.normpath
    # If a path looks like a UNIX absolute path on Windows, it probably is;
    # we'll need to revert the backslashes to forward slashes after normalization
    flip_slashes = path.startswith('/') and IS_WINDOWS_PLATFORM
    path = sysnorm(path)
    if flip_slashes:
        path = path.replace('\\', '/')
    return path

class MountSpec:
    options_map = {
        'volume': {
            'nocopy': 'no_copy'
        },
        'bind': {
            'propagation': 'propagation'
        },
        'tmpfs': {
            'size': 'tmpfs_size'
        }
    }
    _fields = ['type', 'source', 'target', 'read_only', 'consistency']

    @classmethod
    def parse(cls, mount_dict, normalize=False, win_host=False):
        if mount_dict.get('source'):
            if mount_dict['type'] == 'tmpfs':
                raise ConfigurationError('tmpfs mounts can not specify a source')

            mount_dict['source'] = normpath(mount_dict['source'], win_host)
            if normalize:
                mount_dict['source'] = normalize_path_for_engine(mount_dict['source'])

        return cls(**mount_dict)

    def __init__(self, type, source=None, target=None, read_only=None, consistency=None, **kwargs):
        self.type = type
        self.source = source
        self.target = target
        self.read_only = read_only
        self.consistency = consistency
        self.options = None
        if self.type in kwargs:
            self.options = kwargs[self.type]

    def as_volume_spec(self):
        mode = 'ro' if self.read_only else 'rw'
        return VolumeSpec(external=self.source, internal=self.target, mode=mode)

    def legacy_repr(self):
        return self.as_volume_spec().repr()

    def repr(self):
        res = {}
        for field in self._fields:
            if getattr(self, field, None):
                res[field] = getattr(self, field)
        if self.options:
            res[self.type] = self.options
        return res

    @property
    def is_named_volume(self):
        return self.type == 'volume' and self.source

    @property
    def is_tmpfs(self):
        return self.type == 'tmpfs'

    @property
    def external(self):
        return self.source

class VolumeSpec(namedtuple('_VolumeSpec', 'external internal mode')):
    win32 = False

    @classmethod
    def _parse_unix(cls, volume_config):
        parts = volume_config.split(':')

        if len(parts) > 3:
            raise ConfigurationError(
                "Volume %s has incorrect format, should be "
                "external:internal[:mode]" % volume_config)

        if len(parts) == 1:
            external = None
            internal = os.path.normpath(parts[0])
        else:
            external = os.path.normpath(parts[0])
            internal = os.path.normpath(parts[1])

        mode = 'rw'
        if len(parts) == 3:
            mode = parts[2]

        return cls(external, internal, mode)

    @classmethod
    def _parse_win32(cls, volume_config, normalize):
        # relative paths in windows expand to include the drive, eg C:\
        # so we join the first 2 parts back together to count as one
        mode = 'rw'

        def separate_next_section(volume_config):
            drive, tail = splitdrive(volume_config)
            parts = tail.split(':', 1)
            if drive:
                parts[0] = drive + parts[0]
            return parts

        parts = separate_next_section(volume_config)
        if len(parts) == 1:
            internal = parts[0]
            external = None
        else:
            external = parts[0]
            parts = separate_next_section(parts[1])
            external = normpath(external, True)
            internal = parts[0]
            if len(parts) > 1:
                if ':' in parts[1]:
                    raise ConfigurationError(
                        "Volume %s has incorrect format, should be "
                        "external:internal[:mode]" % volume_config
                    )
                mode = parts[1]

        if normalize:
            external = normalize_path_for_engine(external) if external else None

        result = cls(external, internal, mode)
        result.win32 = True
        return result

    @classmethod
    def parse(cls, volume_config, normalize=False, win_host=False):
        """Parse a volume_config path and split it into external:internal[:mode]
        parts to be returned as a valid VolumeSpec.
        """
        if IS_WINDOWS_PLATFORM or win_host:
            return cls._parse_win32(volume_config, normalize)
        else:
            return cls._parse_unix(volume_config)

    def repr(self):
        external = self.external + ':' if self.external else ''
        mode = ':' + self.mode if self.external else ''
        return '{ext}{v.internal}{mode}'.format(mode=mode, ext=external, v=self)

    @property
    def is_named_volume(self):
        res = self.external and not self.external.startswith(('.', '/', '~'))
        if not self.win32:
            return res

        return (
            res and not self.external.startswith('\\') and
            not win32_root_path_pattern.match(self.external)
        )

class ServiceLink(namedtuple('_ServiceLink', 'target alias')):

    @classmethod
    def parse(cls, link_spec):
        target, _, alias = link_spec.partition(':')
        if not alias:
            alias = target
        return cls(target, alias)

    def repr(self):
        if self.target == self.alias:
            return self.target
        return '{s.target}:{s.alias}'.format(s=self)

    @property
    def merge_field(self):
        return self.alias

class ServiceConfigBase(namedtuple('_ServiceConfigBase', 'source target uid gid mode name')):
    @classmethod
    def parse(cls, spec):
        if isinstance(spec, str):
            return cls(spec, None, None, None, None, None)
        return cls(
            spec.get('source'),
            spec.get('target'),
            spec.get('uid'),
            spec.get('gid'),
            spec.get('mode'),
            spec.get('name')
        )

    @property
    def merge_field(self):
        return self.source

    def repr(self):
        return {
            k: v for k, v in zip(self._fields, self) if v is not None
        }

class ServiceSecret(ServiceConfigBase):
    pass

class ServiceConfig(ServiceConfigBase):
    pass

class ServicePort(namedtuple('_ServicePort', 'target published protocol mode external_ip')):
    def __new__(cls, target, published, *args, **kwargs):
        try:
            if target:
                target = int(target)
        except ValueError:
            raise ConfigurationError('Invalid target port: {}'.format(target))

        if published:
            if isinstance(published, str) and '-' in published:  # "x-y:z" format
                a, b = published.split('-', 1)
                if not a.isdigit() or not b.isdigit():
                    raise ConfigurationError('Invalid published port: {}'.format(published))
            else:
                try:
                    published = int(published)
                except ValueError:
                    raise ConfigurationError('Invalid published port: {}'.format(published))

        return super().__new__(
            cls, target, published, *args, **kwargs
        )

    @classmethod
    def parse(cls, spec):
        if isinstance(spec, cls):
            # When extending a service with ports, the port definitions have already been parsed
            return [spec]

        if not isinstance(spec, dict):
            result = []
            try:
                for k, v in build_port_bindings([spec]).items():
                    if '/' in k:
                        target, proto = k.split('/', 1)
                    else:
                        target, proto = (k, None)
                    for pub in v:
                        if pub is None:
                            result.append(
                                cls(target, None, proto, None, None)
                            )
                        elif isinstance(pub, tuple):
                            result.append(
                                cls(target, pub[1], proto, None, pub[0])
                            )
                        else:
                            result.append(
                                cls(target, pub, proto, None, None)
                            )
            except ValueError as e:
                raise ConfigurationError(str(e))

            return result

        return [cls(
            spec.get('target'),
            spec.get('published'),
            spec.get('protocol'),
            spec.get('mode'),
            None
        )]

    @property
    def merge_field(self):
        return (self.target, self.published, self.external_ip, self.protocol)

    def repr(self):
        return {
            k: v for k, v in zip(self._fields, self) if v is not None
        }

    def legacy_repr(self):
        return normalize_port_dict(self.repr())

class GenericResource(namedtuple('_GenericResource', 'kind value')):
    @classmethod
    def parse(cls, dct):
        if 'discrete_resource_spec' not in dct:
            raise ConfigurationError(
                'generic_resource entry must include a discrete_resource_spec key'
            )
        if 'kind' not in dct['discrete_resource_spec']:
            raise ConfigurationError(
                'generic_resource entry must include a discrete_resource_spec.kind subkey'
            )
        return cls(
            dct['discrete_resource_spec']['kind'],
            dct['discrete_resource_spec'].get('value')
        )

    def repr(self):
        return {
            'discrete_resource_spec': {
                'kind': self.kind,
                'value': self.value,
            }
        }

    @property
    def merge_field(self):
        return self.kind

def normalize_port_dict(port):
    return '{external_ip}{has_ext_ip}{published}{is_pub}{target}/{protocol}'.format(
        published=port.get('published', ''),
        is_pub=(':' if port.get('published') is not None or port.get('external_ip') else ''),
        target=port.get('target'),
        protocol=port.get('protocol', 'tcp'),
        external_ip=port.get('external_ip', ''),
        has_ext_ip=(':' if port.get('external_ip') else ''),
    )

class SecurityOpt(namedtuple('_SecurityOpt', 'value src_file')):
    @classmethod
    def parse(cls, value):
        if not isinstance(value, str):
            return value
        # based on https://github.com/docker/cli/blob/9de1b162f/cli/command/container/opts.go#L673-L697
        con = value.split('=', 2)
        if len(con) == 1 and con[0] != 'no-new-privileges':
            if ':' not in value:
                raise ConfigurationError('Invalid security_opt: {}'.format(value))
            con = value.split(':', 2)

        if con[0] == 'seccomp' and con[1] != 'unconfined':
            try:
                with open(unquote_path(con[1])) as f:
                    seccomp_data = json.load(f)
            except (OSError, ValueError) as e:
                raise ConfigurationError('Error reading seccomp profile: {}'.format(e))
            return cls(
                'seccomp={}'.format(json.dumps(seccomp_data)), con[1]
            )
        return cls(value, None)

    def repr(self):
        if self.src_file is not None:
            return 'seccomp:{}'.format(self.src_file)
        return self.value

    @property
    def merge_field(self):
        return self.value


text:
// © 2013 the Ui Authors under the MIT license. See AUTHORS for the list of authors.

// Package ui provides a higher-level user-interface API using SDL2.
package ui

/*
#include "ui.h"
*/
import "C"

import (
	"errors"
	"os"
	"runtime"
	"time"
	"unsafe"
)

func init() {
	runtime.LockOSThread()
}

const eventChanSize = 100

var (
	doChan  = make(chan func(), 1)
	windows = make(map[windowID]*Window, 1)
)

// Start starts the user interface.  It must be called by the main go routine, and it
// never returns. The function f is called in a new go routine as the new "main"
// function.  Rate is the rate at which the user interface should poll for events.
func Start(f func(), rate time.Duration) {
	if C.SDL_Init(C.SDL_INIT_EVERYTHING) < 0 {
		panic(sdlError())
	}

	initAudio()

	go func() {
		f()
		os.Exit(0)
	}()

	tick := time.NewTicker(rate)
	for {
		select {
		case f := <-doChan:
			f()
		case <-tick.C:
			pollEvents()
		}
	}
}

func do(f func()) {
	done := make(chan struct{})
	doChan <- func() {
		f()
		done <- struct{}{}
	}
	<-done
}

type windowID C.Uint32

type windowIDer interface {
	windowID() windowID
}

func pollEvents() {
	for {
		if ev := pollEvent(); ev == nil {
			break
		} else if e, ok := ev.(windowIDer); ok {
			win, ok := windows[e.windowID()]
			if !ok {
				return
			}
			select {
			case win.events <- e:
			default: // too many events queued, junk it.
			}
		}
	}
}

// A Window is a single window on the user's graphical interface.
type Window struct {
	win    *C.SDL_Window
	rend   *C.SDL_Renderer
	id     windowID
	events chan interface{}
	imgs   map[string]texture
}

type texture struct {
	tex           *C.SDL_Texture
	width, height int
}

// NewWindow returns a new window.
func NewWindow(title string, w, h int) *Window {
	win := &Window{
		events: make(chan interface{}, eventChanSize),
		imgs:   make(map[string]texture),
	}
	do(func() {
		ctitle := C.CString(title)
		defer C.free(unsafe.Pointer(ctitle))
		x, y := C.SDL_WINDOWPOS_UNDEFINED, C.SDL_WINDOWPOS_UNDEFINED
		flags := C.SDL_WINDOW_SHOWN | C.SDL_WINDOW_OPENGL

		win.win = C.SDL_CreateWindow(ctitle, C.int(x), C.int(y), C.int(w), C.int(h), C.Uint32(flags))
		if win.win == nil {
			panic(sdlError())
		}

		win.rend = C.SDL_CreateRenderer(win.win, 0, C.SDL_RENDERER_ACCELERATED)
		if win.rend == nil {
			panic(sdlError())
		}
		if C.SDL_SetRenderDrawBlendMode(win.rend, C.SDL_BLENDMODE_BLEND) < 0 {
			panic(sdlError())
		}

		win.id = windowID(C.SDL_GetWindowID(win.win))
		windows[win.id] = win
	})
	return win
}

// Destroy destroys the window.
func (win *Window) Destroy() {
	do(func() {
		C.SDL_DestroyRenderer(win.rend)
		C.SDL_DestroyWindow(win.win)
		delete(windows, win.id)
	})
}

// FlushCache flushes any cached textures on this window.
func (win *Window) FlushCache() {
	do(func() {
		for _, img := range win.imgs {
			C.SDL_DestroyTexture(img.tex)
		}
		win.imgs = make(map[string]texture)
	})
}

// Events returns the event channel for the window.
func (win *Window) Events() <-chan interface{} {
	return win.events
}

// Draw calls f from the main go routine. F is passed a canvas which can draw to the
// window. The Canvas's methods can only safely be called from the main go routine.
func (win *Window) Draw(f func(win Canvas)) {
	do(func() {
		f(Canvas{win: win})
		C.SDL_RenderPresent(win.rend)
	})
}

func sdlError() error {
	return errors.New(C.GoString(C.SDL_GetError()))
}


text:
require 'test_helper'

class SearchInputTest < ActionView::TestCase
  def text_case_form_for(object, attribute, options={})
    concat(case_form_for(object) { |f| f.text(attribute, options) })
  end

  test "should generate text input" do
    text_case_form_for(@user, :description)
    assert_select "textarea", 1
  end
end


text:
package cgeo.geocaching.settings;

import cgeo.geocaching.R;
import cgeo.geocaching.location.IConversion;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;

import java.util.Locale;

public class ProximityPreference extends SeekbarPreference {

    private boolean highRes = false;

    public ProximityPreference(final Context context) {
        this(context, null);
    }

    public ProximityPreference(final Context context, final AttributeSet attrs) {
        this(context, attrs, android.R.attr.preferenceStyle);
    }

    public ProximityPreference(final Context context, final AttributeSet attrs, final int defStyle) {
        super(context, attrs, defStyle);

        final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ProximityPreference);
        highRes = a.getBoolean(R.styleable.ProximityPreference_highRes, false);
        a.recycle();
    }

    // init() gets called by super constructor, therefore before class constructor / class variable assignments!
    @Override
    protected void init() {
        minProgress = 1;
        maxProgress = valueToProgressHelper(Settings.getKeyInt(R.integer.proximitynotification_distance_max));
        hasDecimals = Settings.useImperialUnits();
    }

    @Override
    protected int valueToProgressHelper(final int value) {
        return (int) Math.round(250.0 * Math.log10(value + 1));
    }

    @Override
    protected int valueToProgress(final int value) {
        final int progress = valueToProgressHelper(value);
        return progress < minProgress ? minProgress : Math.min(progress, maxProgress);
    }

    @Override
    protected int progressToValue(final int progress) {
        final int value = (int) Math.pow(10, (double) progress / 250.0) - 1;
        return value < 0 ? 0 : Math.min(value, Settings.getKeyInt(R.integer.proximitynotification_distance_max));
    }

    @Override
    protected String valueToShownValue(final int value) {
        return Settings.useImperialUnits() ? String.format(Locale.getDefault(), "%.2f", value / ((highRes ? 1 : 1000) * IConversion.MILES_TO_KILOMETER)) : String.valueOf(value);
    }

    @Override
    protected int shownValueToValue(final float shownValue) {
        return Math.round(Settings.useImperialUnits() ? shownValue * (highRes ? 1 : 1000) * IConversion.MILES_TO_KILOMETER : shownValue);
    }

    @Override
    protected String getValueString(final int progress) {
        return valueToShownValue(progressToValue(progress)) + (Settings.useImperialUnits() ? " mi" : (highRes ? " m" : " km"));
    }

}


text:
	var Module = function (name, fn) {
			_.extend(this, {
				name: name,
				deps: [],
				options: {},
				exportsFn: noop
			});
			try {
				fn.call(this, app, modulesController);
			}
			catch (e) {
				console.log('error in module: ' + name);
			}
			app.trigger('MODULE_DEFINED', this);
	};

	_.extend(Module.prototype, {
		use: function (moduleName, options) {
			options = options || {};
			this.deps.push({name: this._toFullName(moduleName), options: options});
			return this;
		},

		cloneOriginal: function (options) {
			options = options || {};
			this.set({isClone: true});
			//добавляется приставка, для того чтобы скачать его из оригинального проекта
			this.deps.push({name: 'Original:' + this._toFullName(this.name), options: options});
			return this;
		},

		set: function (options, value) {
			if (_.isString(options) && !!value)
				this.options[options] = value;
			if (_.isObject(options) && !!options)
				_.extend(this.options, options);
			return this;
		},

		exports: function (fn) {
			this.exportsFn = fn;
			return this;
		},

		get: function (prop) {
			return this.options[prop];
		},

		init: function () {
			return this.exportsFn.call(this.get('context') || this);
		},

		getAlias: function () {
			var t = this.name.split(':');
			t.splice(-1, 1);
			return t.join(':');
		},

		getShorthand: function () {
			var t = this.name.split(':');
			return t.splice(-1, 1);
		},

		getDeps: function () {
			return this.deps;
		},

		_isShortHand: function (name) {
			return name[0] === ':';
		},

		_toFullName: function (name) {
			if (!this._isShortHand(name))
				return name;
			var t = this.name.split(':');
			t.splice(-1, 1);
			return	t.join(':') + name;
		}
	});


text:
using System.Collections.Generic;
using System.Linq;
using Frapid.Configuration;

namespace Frapid.Areas.Tests.Fakes
{
    public sealed class FakeDomainSerializer : IDomainSerializer
    {
        public FakeDomainSerializer()
        {
            this.Domains = new List<ApprovedDomain>
                           {
                               new ApprovedDomain
                               {
                                   EnforceSsl = true,
                                   DomainName = "mixerp.org",
                                   AdminEmail = "",
                                   BackupDirectory = "",
                                   BackupDirectoryIsFixedPath = false,
                                   CdnDomain = "static.mixerp.org",
                                   DbProvider = "Npgsql",
                                   Synonyms = new[]
                                              {
                                                  "www.mixerp.org",
                                                  "mixerp.com",
                                                  "www.mixerp.com",
                                                  "mixerp.net",
                                                  "www.mixerp.net"
                                              }
                               },
                               new ApprovedDomain
                               {
                                   EnforceSsl = false,
                                   DomainName = "frapid.com",
                                   AdminEmail = "",
                                   BackupDirectory = "",
                                   BackupDirectoryIsFixedPath = false,
                                   CdnDomain = "cdn.frapid.com",
                                   DbProvider = "System.Data.SqlClient",
                                   Synonyms = new[]
                                              {
                                                  "www.frapid.com"
                                              }
                               },
                               new ApprovedDomain
                               {
                                   EnforceSsl = true,
                                   DomainName = "example.com",
                                   AdminEmail = "",
                                   BackupDirectory = "",
                                   BackupDirectoryIsFixedPath = false,
                                   CdnDomain = "cdn.example.com",
                                   DbProvider = "Npgsql",
                                   Synonyms = new[]
                                              {
                                                  "www.example.com"
                                              }
                               }
                           };
        }

        private List<ApprovedDomain> Domains { get; set; }
        public string FileName { get; set; }

        public void Add(ApprovedDomain domain)
        {
            this.Domains.Add(domain);
        }

        public List<ApprovedDomain> Get()
        {
            return this.Domains;
        }

        public List<string> GetMemberSites()
        {
            var domains = new List<string>();

            foreach (var domain in this.Domains)
            {
                domains.Add(domain.DomainName);
                domains.AddRange(domain.Synonyms);
                domains.Add(domain.CdnDomain);
            }

            return domains;
        }

        public void Remove(string domain)
        {
            var tenant = this.Domains.FirstOrDefault(x => x.DomainName.Equals(domain));

            if (tenant != null)
            {
                this.Domains.Remove(tenant);
            }
        }

        public void Save(List<ApprovedDomain> domains)
        {
            this.Domains = domains;
        }
    }
}


text:
@interface UIImageView(BeeUILayout)
@end

#endif	// #if (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.yousoft.stram.domain.application;

import com.yousoft.stram.domain.Vehicule;
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *
 * @author jguinart
 */
public class Email implements Serializable {

    /**
	 *
	 */
	private static final long serialVersionUID = 1L;
	private String subject;
    private String body;
    private Long fechSentEmail;
    private Date fechEntry;
    private List<File> attachments;
    private List<Vehicule> vehicules;

    public Email() {
    }

    public Email(String subject, long time) {
        this.subject = subject;
        this.fechSentEmail = time;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public Long getFechSentEmail() {
        return fechSentEmail;
    }

    public void setFechSentEmail(Long fechSentEmail) {
        this.fechSentEmail = fechSentEmail;
    }

    public List<File> getAttachments() {
        if (attachments == null) {
            attachments = new ArrayList<>();
        }
        return attachments;
    }

    public void setAttachments(List<File> attachments) {
        this.attachments = attachments;
    }

    public List<Vehicule> getVehicules() {
        return vehicules;
    }

    public void setVehicules(List<Vehicule> vehicules) {
        this.vehicules = vehicules;
    }

    @Override
    public String toString() {
        return "Email{" + "subject=" + subject + ", body=" + body + ", fechSentEmail=" + fechSentEmail + ", fechEntry=" + fechEntry + ", attachments=" + attachments + ", vehicules=" + vehicules + '}';
    }

}


text:
package com.google.android.apps.common.testing.accessibility.framework;

/**
 * Abstract base class for all accessibility checks. Abstract subclasses include
 * {@code AccessibilityViewCheck}, the base class for all that run against {@code View}s, and
 * {@code AccessibilityInfoCheck}, the base class for checks that run against
 * {@code AccessibilityNodeInfo}s.
 *
 * <p>Classes extending this one must implement {@code runCheck...} that return {@code List}s of
 * a subclass of {@code AccessibilityCheckResult}.
 */
public abstract class AccessibilityCheck {
}


text:
class FakeHeroku
  RECORDER = File.expand_path(File.join('..', '..', 'tmp', 'heroku_commands'), File.dirname(__FILE__))

  def initialize(args)
    @args = args
  end

  def run!
    File.open(RECORDER, 'a') do |file|
      file.puts @args.join(' ')
    end
  end

  def self.clear!
    FileUtils.rm_rf RECORDER
  end

  def self.has_gem_included?(project_path, gem_name)
    gemfile = File.open(File.join(project_path, 'Gemfile'), 'a')

    File.foreach(gemfile).any? do |line|
      line.match(/#{Regexp.quote(gem_name)}/)
    end
  end

  def self.has_created_app_for?(environment, flags = nil)
    app_name = "#{SuspendersTestHelpers::APP_NAME.dasherize}-#{environment}"

    command = if flags
                "create #{app_name} #{flags} --remote #{environment}\n"
              else
                "create #{app_name} --remote #{environment}\n"
              end

    File.foreach(RECORDER).any? { |line| line == command }
  end

  def self.has_configured_vars?(remote_name, var)
    File.foreach(RECORDER).any? do |line|
      line =~ /^config:add #{var}=.+ --remote #{remote_name}\n$/
    end
  end
end


text:
var sass = require('node-sass');

function sassFile( input, options ) {
	options = options || {};
	options.data = input;
	return sass.renderSync(options).css;
}

sassFile.defaults = {
	accept: ['.scss'],
	ext: '.css'
};

module.exports = sassFile;


text:
package com.jaksona.app;

import com.jaksona.app.config.*;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import java.util.Enumeration;

/**
 *  服务器启动入口
 *  @author jaksona chenluyuanit@gmail.com
 */
public class WebApplicationStartup extends AbstractAnnotationConfigDispatcherServletInitializer {

	/**
	 * Specify {@link Configuration @Configuration}
	 * and/or {@link Component @Component} classes to be
	 * provided to the {@linkplain #createRootApplicationContext() root application context}.
	 *
	 * @return the configuration classes for the root application context, or {@code null}
	 * if creation and registration of a root context is not desired
	 */
	@Override
	protected Class<?>[] getRootConfigClasses() {
		return null;
	}

	/**
	 * Specify {@link Configuration @Configuration}
	 * and/or {@link Component @Component} classes to be
	 * provided to the {@linkplain #createServletApplicationContext() dispatcher servlet
	 * application context}.
	 *
	 * @return the configuration classes for the dispatcher servlet application context or
	 * {@code null} if all configuration is specified through root config classes.
	 */
	@Override
	protected Class<?>[] getServletConfigClasses() {
		return new Class<?>[]{WebMvcConfig.class};
	}

	/**
	 * Specify the servlet mapping(s) for the {@code DispatcherServlet} —
	 * for example {@code "/"}, {@code "/app"}, etc.
	 *
	 * @see #registerDispatcherServlet(ServletContext)
	 */
	@Override
	protected String[] getServletMappings() {
		return new String[]{"/"};
	}

}


text:
import { expect } from 'chai'
import request from 'supertest'

import { application } from '../../src/'
import { default as env } from '../../config/env'

describe('ping api', () => {
  let app

  before(async function() {
    app = await application({ env })
  })

  describe('/ping', () => {
    it('should return array for /api/ping', done => {
      request(app).get('/api/ping').expect(200).end((err, res) => {
        if (err) {
          done(err)
          return
        }

        expect(res.body).to.be.instanceof(Array)
        res.body.forEach((obj, index) => {
          expect(obj).to.have.property('status', index)
        })
        done()
      })
    })

    it('show throw not found', done => {
      request(app).get('/api/notfound').expect(404).end(done)
    })
  })
})


text:
using System;
using System.IO;

namespace MonoTorrent.TorrentWatcher
{
    public class TorrentFolderWatcher : ITorrentWatcher
    {
        #region Events

        public event EventHandler<TorrentWatcherEventArgs> TorrentFound;
        public event EventHandler<TorrentWatcherEventArgs> TorrentLost;

        #endregion Events

        #region Member Variables

        private FileSystemWatcher watcher;
        private string torrentDirectory;
        private string watchFilter;

        #endregion

        #region Constructors

        public TorrentFolderWatcher(string torrentDirectory, string watchFilter)
        {
            if (torrentDirectory == null)
                throw new ArgumentNullException("torrentDirectory");

            if (watchFilter == null)
                throw new ArgumentNullException("watchFilter");

            if (!Directory.Exists(torrentDirectory))
                Directory.CreateDirectory(torrentDirectory);

            this.torrentDirectory = torrentDirectory;
            this.watchFilter = watchFilter;
        }

        public TorrentFolderWatcher(DirectoryInfo torrentDirectory)
            : this(torrentDirectory.FullName, "*.torrent")
        {

        }

        #endregion

        #region ITorrentWatcher implementations

        public void ForceScan()
        {
            foreach (string path in Directory.GetFiles(torrentDirectory, this.watchFilter))
                RaiseTorrentFound(path);
        }

        public void Start()
        {
            if (this.watcher == null)
            {
                this.watcher = new FileSystemWatcher(torrentDirectory);
                this.watcher.Filter = this.watchFilter;
                //this.watcher.NotifyFilter = NotifyFilters.LastWrite;
                this.watcher.Created += new FileSystemEventHandler(OnCreated);
                this.watcher.Deleted += new FileSystemEventHandler(OnDeleted);
            }
            this.watcher.EnableRaisingEvents = true;
        }

        public void Stop()
        {
            this.watcher.EnableRaisingEvents = false;
        }

        #endregion

        #region Event Handlers

        ///Gets called when a File with .torrent extension was added to the torrentDirectory
        private void OnCreated(object sender, FileSystemEventArgs e)
        {
            RaiseTorrentFound(e.FullPath);
        }

        ///Gets called when a File with .torrent extension was deleted from the torrentDirectory
        private void OnDeleted(object sender, FileSystemEventArgs e)
        {
            RaiseTorrentLost(e.FullPath);
        }

        protected virtual void RaiseTorrentFound(string path)
        {
            if (TorrentFound != null)
                TorrentFound(this, new TorrentWatcherEventArgs(path));
        }

        protected virtual void RaiseTorrentLost(string path)
        {
            if (TorrentLost != null)
                TorrentLost(this, new TorrentWatcherEventArgs(path));
        }

        #endregion
    }
}


text:
package controller

import (
	"encoding/json"
	"fmt"
	"html"
	"html/template"
	"io/ioutil"
	"log"
	"net/http"

	"github.com/hkohlsaat/vtr/model"
	"github.com/julienschmidt/httprouter"
)

// GetTeachers serves the list of all teachers.
func GetTeachers(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	redirected, _ := ensureLoggedIn(w, r)
	if redirected {
		return
	}

	showTeachers(w, r, "")
}

// NewTeacher serves the form to create a new teacher.
func NewTeacher(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
	redirected, _ := ensureLoggedIn(w, r)
	if redirected {
		return
	}

	short := html.EscapeString(r.URL.Query().Get("short"))
	templateData := struct {
		generalTemplateData
		Short string
	}{Short: short}

	template, err := template.ParseFiles("templates/base.html", "templates/teacher/new.html")
	if err != nil {
		log.Printf("error: %v\n", err)
	}

	err = template.Execute(w, templateData)
	if err != nil {
		log.Printf("error: %v\n", err)
	}
}

// CreateTeacher creates a new teacher and serves the list of all teachers.
func CreateTeacher(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	redirected, _ := ensureLoggedIn(w, r)
	if redirected {
		return
	}

	// Parse and validate.
	r.ParseForm()
	short := html.EscapeString(r.Form.Get("short"))
	name := html.EscapeString(r.Form.Get("name"))
	sex := html.EscapeString(r.Form.Get("sex"))

	valid, message := validateTeacherData(short, name, sex)
	if valid {
		teacher := model.Teacher{Short: short}
		if teacher.Exists() {
			message = fmt.Sprintf("Es gibt bereits einen Lehrer mit dem Kürzel %s.", short)
			valid = false
		}
	}

	// Render message if the data is not valid.
	if !valid {
		template, err := template.ParseFiles("templates/base.html", "templates/teacher/new.html")
		if err != nil {
			log.Printf("error: %v\n", err)
		}

		err = template.Execute(w, simpleMessage(message, false))
		if err != nil {
			log.Printf("error: %v\n", err)
		}
		return
	}

	// Create the teacher.
	teacher := model.Teacher{Short: short, Name: name, Sex: sex}
	teacher.Create()

	unknown := model.UnknownTeacher{Short: short}
	unknown.Delete()

	// Render all teachers
	message = fmt.Sprintf("%s wurde gespeichert.", short)
	showTeachers(w, r, message)
}

// showTeachers is a helper function to show a list of all teachers.
func showTeachers(w http.ResponseWriter, r *http.Request, message string) {
	redirected, _ := ensureLoggedIn(w, r)
	if redirected {
		return
	}

	// Prepare the template data with all teachers.
	templateData := struct {
		generalTemplateData
		Teachers []model.Teacher
		Unknown  []model.UnknownTeacher
	}{Teachers: model.ReadAllTeachers(),
		Unknown: model.ReadAllUnknownTeachers()}
	// Add the message if there is one.
	if message != "" {
		templateData.Messages = []templateMessage{templateMessage{Text: message, Positive: true}}
	}

	// Render.
	template, err := template.ParseFiles("templates/base.html", "templates/teacher/index.html")
	if err != nil {
		log.Printf("error: %v\n", err)
	}

	err = template.Execute(w, &templateData)
	if err != nil {
		log.Printf("error: %v\n", err)
	}
}

// NewTeachers serves the upload form to submit multiple teacher records.
func NewTeachers(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	template, err := template.ParseFiles("templates/base.html", "templates/teacher/upload.html")
	if err != nil {
		log.Printf("error: %v\n", err)
	}

	err = template.Execute(w, nil)
	if err != nil {
		log.Printf("error: %v\n", err)
	}
}

// CreateTeachers creates multiple teachers from json upload and serves the list
// of all teachers.
func CreateTeachers(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	redirected, _ := ensureLoggedIn(w, r)
	if redirected {
		return
	}

	r.ParseMultipartForm(16384)
	file, _, err := r.FormFile("teacherjson")
	if err != nil {
		log.Printf("error recieving teacher file from upload: %v\n", err)
		return
	}
	defer file.Close()

	bytes, err := ioutil.ReadAll(file)
	if err != nil {
		log.Printf("error reading teacher file: %v\n", err)
		return
	}

	type tmpTeacher struct {
		model.Teacher
		Compellation string
	}
	teachers := []tmpTeacher{}
	err = json.Unmarshal(bytes, &teachers)
	if err != nil {
		log.Printf("error unmarshaling teacher data: %v\n", err)
		return
	}
	for _, teacher := range teachers {
		if teacher.Compellation == "Herr" {
			teacher.Sex = "m"
		} else {
			teacher.Sex = "w"
		}
		teacher.Create()

		unknown := model.UnknownTeacher{Short: teacher.Short}
		unknown.Delete()
	}

	http.Redirect(w, r, "/teachers", http.StatusSeeOther)
}

// GetTeacher serves one teacher.
func GetTeacher(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
	redirected, _ := ensureLoggedIn(w, r)
	if redirected {
		return
	}

	short := html.EscapeString(params.ByName("short"))
	teacher := model.Teacher{Short: short}
	if !teacher.Exists() {
		http.NotFound(w, r)
		return
	} else {
		teacher.Read()
	}

	// Execute template with teacher as template data.
	template, err := template.ParseFiles("templates/base.html", "templates/teacher/get.html")
	if err != nil {
		log.Printf("error: %v\n", err)
	}

	templateData := struct {
		generalTemplateData
		model.Teacher
	}{Teacher: teacher}

	err = template.Execute(w, &templateData)
	if err != nil {
		log.Printf("error: %v\n", err)
	}
}

// EditTeacher serves a form to edit a teacher.
func EditTeacher(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
	redirected, _ := ensureLoggedIn(w, r)
	if redirected {
		return
	}

	short := html.EscapeString(params.ByName("short"))
	teacher := model.Teacher{Short: short}
	if !teacher.Exists() {
		http.NotFound(w, r)
		return
	}
	teacher.Read()

	// Execute template with teacher as template data.
	template, err := template.ParseFiles("templates/base.html", "templates/teacher/edit.html")
	if err != nil {
		log.Printf("error: %v\n", err)
	}

	templateData := struct {
		generalTemplateData
		model.Teacher
	}{}
	templateData.Teacher = teacher

	err = template.Execute(w, &templateData)
	if err != nil {
		log.Printf("error: %v\n", err)
	}
}

// UpdateTeacher updates a teacher with the uploaded information.
func UpdateTeacher(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
	redirected, _ := ensureLoggedIn(w, r)
	if redirected {
		return
	}

	short := html.EscapeString(params.ByName("short"))
	teacher := model.Teacher{Short: short}
	if !teacher.Exists() {
		http.NotFound(w, r)
		return
	}

	// Parse and validate teacher data.
	r.ParseForm()
	nshort := html.EscapeString(r.Form.Get("short"))
	name := html.EscapeString(r.Form.Get("name"))
	sex := html.EscapeString(r.Form.Get("sex"))

	valid, message := validateTeacherData(short, name, sex)
	if !valid {
		http.Error(w, message, http.StatusNotAcceptable)
		return
	}

	// Update teacher and send the new URL back to the client.
	// It might have changed with an update of short.
	updTeacher := model.Teacher{Short: nshort, Name: name, Sex: sex}
	updTeacher.UpdateShort(short)
	w.Write([]byte(fmt.Sprintf("/teacher/%s", nshort)))
}

// DeleteTeacher deletes a teacher and serves nothing (empty 200 OK response).
func DeleteTeacher(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
	redirected, _ := ensureLoggedIn(w, r)
	if redirected {
		return
	}

	short := html.EscapeString(params.ByName("short"))
	teacher := model.Teacher{Short: short}
	if teacher.Exists() {
		teacher.Delete()
	} else {
		http.NotFound(w, r)
		return
	}
}

func validateTeacherData(short, name, sex string) (valid bool, message string) {
	if sex != "m" && sex != "w" {
		return false, "Falsche Eingabe: Herr: \"m\", Frau: \"w\""
	} else if len(short) == 0 {
		return false, "Das Kürzel ist zu kurz."
	} else if len(name) == 0 {
		return false, "Der Name ist zu kurz."
	}
	return true, ""
}