text:
package eu.appbucket.beaconmonitor.ui;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import eu.appbucket.beaconmonitor.R;

public class ConfigurationActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_configuraiton);
		getActionBar().setDisplayHomeAsUpEnabled(true);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.configuration, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.action_save) {
			saveConfiguration();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

    private void saveConfiguration() {

    }
}

redpajama_set_name: RedPajamaGithub


text:
Description:
- The application is a simulation of a toy robot moving on a square tabletop, of dimensions 5 units x 5 units.
- There are no other obstructions on the table surface.
- The robot is free to roam around the surface of the table, but must be prevented from falling to destruction. Any movement that would result in the robot falling from the table must be prevented, however further valid movement commands must still be allowed.

## Instructions

Create an application that can read in commands of the following form -

```
PLACE X,Y,F

MOVE

LEFT

RIGHT

REPORT
```

- PLACE will put the toy robot on the table in position X,Y and facing NORTH, SOUTH, EAST or WEST.

- The origin (0,0) can be considered to be the SOUTH WEST most corner.

- The first valid command to the robot is a PLACE command, after that, any sequence of commands may be issued, in any order, including another PLACE command. The application should discard all commands in the sequence until a valid PLACE command has been executed.

- MOVE will move the toy robot one unit forward in the direction it is currently facing.

- LEFT and RIGHT will rotate the robot 90 degrees in the specified direction without changing the position of the robot.

- REPORT will announce the X,Y and F of the robot. This can be in any form, but standard output is sufficient.

- A robot that is not on the table can choose the ignore the MOVE, LEFT, RIGHT and REPORT commands.

- Input can be from a file, or from standard input, as the developer chooses.

- Provide test data to exercise the application.

## Constraints:

The toy robot must not fall off the table during movement. This also includes the initial placement of the toy robot. Any move that would cause the robot to fall must be ignored.

## Example Input and Output:

a)
```
PLACE 0,0,NORTH
MOVE
REPORT
Output: 0,1,NORTH
```

b)
```
PLACE 0,0,NORTH
LEFT
REPORT
Output: 0,0,WEST
```

c)
```
PLACE 1,2,EAST
MOVE
MOVE
LEFT
MOVE
REPORT
Output: 3,3,NORTH
```

## Deliverables:

The Ruby source files, the test data and any test code. It is not required to provide any graphical output showing the movement of the toy robot.


text:
/*istanbul ignore next*/"use strict";

exports.__esModule = true;

exports.default = function (ast, comments, tokens) {
  if (ast) {
    if (ast.type === "Program") {
      return t.file(ast, comments || [], tokens || []);
    } else if (ast.type === "File") {
      return ast;
    }
  }

  throw new Error("Not a valid ast?");
};

var /*istanbul ignore next*/_babelTypes = require("babel-types");

/*istanbul ignore next*/
var t = _interopRequireWildcard(_babelTypes);

/*istanbul ignore next*/
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

module.exports = exports["default"];

/**
 * Normalize an AST.
 *
 * - Wrap `Program` node with a `File` node.
 */


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

  <groupId>test</groupId>
  <artifactId>integration-test-parent</artifactId>
  <version>1.0-SNAPSHOT</version>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project-under-test.version>1.10-beta-SNAPSHOT</project-under-test.version>
    <maven-enforcer-plugin.version>1.4.1</maven-enforcer-plugin.version>
  </properties>

  <packaging>pom</packaging>
  <name>Parent POM for integration tests.</name>
</project>


text:
package org.elasticsearch.index.fielddata.plain;

import org.apache.lucene.index.*;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.PagedBytes;
import org.apache.lucene.util.packed.GrowableWriter;
import org.apache.lucene.util.packed.PackedInts;
import org.elasticsearch.ElasticSearchException;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.fielddata.AbstractIndexFieldData;
import org.elasticsearch.index.fielddata.FieldDataType;
import org.elasticsearch.index.fielddata.IndexFieldData;
import org.elasticsearch.index.fielddata.IndexFieldDataCache;
import org.elasticsearch.index.fielddata.fieldcomparator.BytesRefFieldComparatorSource;
import org.elasticsearch.index.fielddata.fieldcomparator.SortMode;
import org.elasticsearch.index.fielddata.ordinals.Ordinals;
import org.elasticsearch.index.fielddata.ordinals.OrdinalsBuilder;
import org.elasticsearch.index.mapper.FieldMapper;
import org.elasticsearch.index.settings.IndexSettings;

/**
 */
public class PagedBytesIndexFieldData extends AbstractIndexFieldData<PagedBytesAtomicFieldData> implements IndexFieldData.WithOrdinals<PagedBytesAtomicFieldData> {

    public static class Builder implements IndexFieldData.Builder {

        @Override
        public IndexFieldData build(Index index, @IndexSettings Settings indexSettings, FieldMapper.Names fieldNames, FieldDataType type, IndexFieldDataCache cache) {
            return new PagedBytesIndexFieldData(index, indexSettings, fieldNames, type, cache);
        }
    }

    public PagedBytesIndexFieldData(Index index, @IndexSettings Settings indexSettings, FieldMapper.Names fieldNames, FieldDataType fieldDataType, IndexFieldDataCache cache) {
        super(index, indexSettings, fieldNames, fieldDataType, cache);
    }

    @Override
    public boolean valuesOrdered() {
        return true;
    }

    @Override
    public PagedBytesAtomicFieldData load(AtomicReaderContext context) {
        try {
            return cache.load(context, this);
        } catch (Throwable e) {
            if (e instanceof ElasticSearchException) {
                throw (ElasticSearchException) e;
            } else {
                throw new ElasticSearchException(e.getMessage(), e);
            }
        }
    }

    @Override
    public PagedBytesAtomicFieldData loadDirect(AtomicReaderContext context) throws Exception {
        AtomicReader reader = context.reader();

        Terms terms = reader.terms(getFieldNames().indexName());
        if (terms == null) {
            return PagedBytesAtomicFieldData.empty(reader.maxDoc());
        }

        final PagedBytes bytes = new PagedBytes(15);
        int startBytesBPV;
        int startTermsBPV;
        int startNumUniqueTerms;

        int maxDoc = reader.maxDoc();
        final int termCountHardLimit;
        if (maxDoc == Integer.MAX_VALUE) {
            termCountHardLimit = Integer.MAX_VALUE;
        } else {
            termCountHardLimit = maxDoc + 1;
        }

        // Try for coarse estimate for number of bits; this
        // should be an underestimate most of the time, which
        // is fine -- GrowableWriter will reallocate as needed
        long numUniqueTerms = terms.size();
        if (numUniqueTerms != -1L) {
            if (numUniqueTerms > termCountHardLimit) {
                // app is misusing the API (there is more than
                // one term per doc); in this case we make best
                // effort to load what we can (see LUCENE-2142)
                numUniqueTerms = termCountHardLimit;
            }

            startBytesBPV = PackedInts.bitsRequired(numUniqueTerms * 4);
            startTermsBPV = PackedInts.bitsRequired(numUniqueTerms);

            startNumUniqueTerms = (int) numUniqueTerms;
        } else {
            startBytesBPV = 1;
            startTermsBPV = 1;
            startNumUniqueTerms = 1;
        }

        // TODO: expose this as an option..., have a nice parser for it...
        float acceptableOverheadRatio = PackedInts.FAST;

        GrowableWriter termOrdToBytesOffset = new GrowableWriter(startBytesBPV, 1 + startNumUniqueTerms, acceptableOverheadRatio);
        OrdinalsBuilder builder = new OrdinalsBuilder(terms, reader.maxDoc());
        try {
            // 0 is reserved for "unset"
            bytes.copyUsingLengthPrefix(new BytesRef());
            TermsEnum termsEnum = terms.iterator(null);
            DocsEnum docsEnum = null;
            for (BytesRef term = termsEnum.next(); term != null; term = termsEnum.next()) {
                final int termOrd = builder.nextOrdinal();
                if (termOrd == termOrdToBytesOffset.size()) {
                    // NOTE: this code only runs if the incoming
                    // reader impl doesn't implement
                    // size (which should be uncommon)
                    termOrdToBytesOffset = termOrdToBytesOffset.resize(ArrayUtil.oversize(1 + termOrd, 1));
                }
                termOrdToBytesOffset.set(termOrd, bytes.copyUsingLengthPrefix(term));
                docsEnum = termsEnum.docs(reader.getLiveDocs(), docsEnum, DocsEnum.FLAG_NONE);
                for (int docId = docsEnum.nextDoc(); docId != DocsEnum.NO_MORE_DOCS; docId = docsEnum.nextDoc()) {
                    builder.addDoc(docId);
                }
            }
            final long sizePointer = bytes.getPointer();
            PagedBytes.Reader bytesReader = bytes.freeze(true);
            PackedInts.Reader termOrdToBytesOffsetReader = termOrdToBytesOffset.getMutable();
            final Ordinals ordinals = builder.build(fieldDataType.getSettings());

            return new PagedBytesAtomicFieldData(bytesReader, sizePointer, termOrdToBytesOffsetReader, ordinals);
        } finally {
            builder.close();
        }
    }

    @Override
    public XFieldComparatorSource comparatorSource(@Nullable Object missingValue, SortMode sortMode) {
        // TODO support "missingValue" for sortMissingValue options here...
        return new BytesRefFieldComparatorSource(this, sortMode);
    }
}


text:
#ifndef H_LUCY_TEST_SEARCH_TESTQUERYPARSERSYNTAX
#define H_LUCY_TEST_SEARCH_TESTQUERYPARSERSYNTAX 1

#ifdef __cplusplus
extern "C" {
#endif

#include "testlucy_parcel.h"

/* Include the header for this class's parent.
 */

#include "Clownfish\TestHarness\TestBatch.h"

/* Define the struct layout for instances of this class.
 */

#ifdef C_TESTLUCY_TESTQUERYPARSERSYNTAX
extern uint32_t testlucy_TestQPSyntax_IVARS_OFFSET;
typedef struct testlucy_TestQueryParserSyntaxIVARS testlucy_TestQueryParserSyntaxIVARS;
static CFISH_INLINE testlucy_TestQueryParserSyntaxIVARS*
testlucy_TestQPSyntax_IVARS(testlucy_TestQueryParserSyntax *self) {
   char *ptr = (char*)self + testlucy_TestQPSyntax_IVARS_OFFSET;
   return (testlucy_TestQueryParserSyntaxIVARS*)ptr;
}
#ifdef TESTLUCY_USE_SHORT_NAMES
  #define TestQueryParserSyntaxIVARS testlucy_TestQueryParserSyntaxIVARS
  #define TestQPSyntax_IVARS testlucy_TestQPSyntax_IVARS
#endif

#endif /* C_TESTLUCY_TESTQUERYPARSERSYNTAX */

/* Declare this class's inert variables.
 */

/* Declare both this class's inert functions and the C functions which
 * implement this class's dynamic methods.
 */

TESTLUCY_VISIBLE testlucy_TestQueryParserSyntax*
testlucy_TestQPSyntax_new(void);

void
TESTLUCY_TestQPSyntax_Run_IMP(testlucy_TestQueryParserSyntax* self, cfish_TestBatchRunner* runner);

/* Define typedefs for each dynamic method, allowing us to cast generic
 * pointers to the appropriate function pointer type more cleanly.
 */

typedef void*
(*TESTLUCY_TestQPSyntax_To_Host_t)(testlucy_TestQueryParserSyntax* self, void* vcache);

typedef cfish_Obj*
(*TESTLUCY_TestQPSyntax_Clone_t)(testlucy_TestQueryParserSyntax* self);

typedef bool
(*TESTLUCY_TestQPSyntax_Equals_t)(testlucy_TestQueryParserSyntax* self, cfish_Obj* other);

typedef int32_t
(*TESTLUCY_TestQPSyntax_Compare_To_t)(testlucy_TestQueryParserSyntax* self, cfish_Obj* other);

typedef void
(*TESTLUCY_TestQPSyntax_Destroy_t)(testlucy_TestQueryParserSyntax* self);

typedef cfish_String*
(*TESTLUCY_TestQPSyntax_To_String_t)(testlucy_TestQueryParserSyntax* self);

typedef void
(*TESTLUCY_TestQPSyntax_Run_t)(testlucy_TestQueryParserSyntax* self, cfish_TestBatchRunner* runner);

/* Define type-safe wrappers for inert functions of Obj.
 */

static CFISH_INLINE cfish_Class*
testlucy_TestQPSyntax_get_class(testlucy_TestQueryParserSyntax *self) {
    return cfish_Obj_get_class((cfish_Obj*)self);
}

static CFISH_INLINE cfish_String*
testlucy_TestQPSyntax_get_class_name(testlucy_TestQueryParserSyntax *self) {
    return cfish_Obj_get_class_name((cfish_Obj*)self);
}

static CFISH_INLINE bool
testlucy_TestQPSyntax_is_a(testlucy_TestQueryParserSyntax *self, cfish_Class *ancestor) {
    return cfish_Obj_is_a((cfish_Obj*)self, ancestor);
}

/* Define the inline functions which implement this class's virtual methods.
 */

extern TESTLUCY_VISIBLE uint32_t TESTLUCY_TestQPSyntax_To_Host_OFFSET;
static CFISH_INLINE void*
TESTLUCY_TestQPSyntax_To_Host(testlucy_TestQueryParserSyntax* self, void* vcache) {
    const TESTLUCY_TestQPSyntax_To_Host_t method = (TESTLUCY_TestQPSyntax_To_Host_t)cfish_obj_method(self, TESTLUCY_TestQPSyntax_To_Host_OFFSET);
    return method(self, vcache);
}

extern TESTLUCY_VISIBLE uint32_t TESTLUCY_TestQPSyntax_Clone_OFFSET;
static CFISH_INLINE cfish_Obj*
TESTLUCY_TestQPSyntax_Clone(testlucy_TestQueryParserSyntax* self) {
    const TESTLUCY_TestQPSyntax_Clone_t method = (TESTLUCY_TestQPSyntax_Clone_t)cfish_obj_method(self, TESTLUCY_TestQPSyntax_Clone_OFFSET);
    return method(self);
}

extern TESTLUCY_VISIBLE uint32_t TESTLUCY_TestQPSyntax_Equals_OFFSET;
static CFISH_INLINE bool
TESTLUCY_TestQPSyntax_Equals(testlucy_TestQueryParserSyntax* self, cfish_Obj* other) {
    const TESTLUCY_TestQPSyntax_Equals_t method = (TESTLUCY_TestQPSyntax_Equals_t)cfish_obj_method(self, TESTLUCY_TestQPSyntax_Equals_OFFSET);
    return method(self, other);
}

extern TESTLUCY_VISIBLE uint32_t TESTLUCY_TestQPSyntax_Compare_To_OFFSET;
static CFISH_INLINE int32_t
TESTLUCY_TestQPSyntax_Compare_To(testlucy_TestQueryParserSyntax* self, cfish_Obj* other) {
    const TESTLUCY_TestQPSyntax_Compare_To_t method = (TESTLUCY_TestQPSyntax_Compare_To_t)cfish_obj_method(self, TESTLUCY_TestQPSyntax_Compare_To_OFFSET);
    return method(self, other);
}

extern TESTLUCY_VISIBLE uint32_t TESTLUCY_TestQPSyntax_Destroy_OFFSET;
static CFISH_INLINE void
TESTLUCY_TestQPSyntax_Destroy(testlucy_TestQueryParserSyntax* self) {
    const TESTLUCY_TestQPSyntax_Destroy_t method = (TESTLUCY_TestQPSyntax_Destroy_t)cfish_obj_method(self, TESTLUCY_TestQPSyntax_Destroy_OFFSET);
    method(self);
}

extern TESTLUCY_VISIBLE uint32_t TESTLUCY_TestQPSyntax_To_String_OFFSET;
static CFISH_INLINE cfish_String*
TESTLUCY_TestQPSyntax_To_String(testlucy_TestQueryParserSyntax* self) {
    const TESTLUCY_TestQPSyntax_To_String_t method = (TESTLUCY_TestQPSyntax_To_String_t)cfish_obj_method(self, TESTLUCY_TestQPSyntax_To_String_OFFSET);
    return method(self);
}

extern TESTLUCY_VISIBLE uint32_t TESTLUCY_TestQPSyntax_Run_OFFSET;
static CFISH_INLINE void
TESTLUCY_TestQPSyntax_Run(testlucy_TestQueryParserSyntax* self, cfish_TestBatchRunner* runner) {
    const TESTLUCY_TestQPSyntax_Run_t method = (TESTLUCY_TestQPSyntax_Run_t)cfish_obj_method(self, TESTLUCY_TestQPSyntax_Run_OFFSET);
    method(self, runner);
}

/* Declare callbacks for wrapping host overrides.
 */

#ifdef CFISH_NO_DYNAMIC_OVERRIDES
#else
#endif

/* Define "short names" for this class's symbols.
 */

#ifdef TESTLUCY_USE_SHORT_NAMES
  #define TestQueryParserSyntax testlucy_TestQueryParserSyntax
  #define TESTQUERYPARSERSYNTAX TESTLUCY_TESTQUERYPARSERSYNTAX
  #define TestQPSyntax_new testlucy_TestQPSyntax_new
  #define TestQPSyntax_get_class testlucy_TestQPSyntax_get_class
  #define TestQPSyntax_get_class_name testlucy_TestQPSyntax_get_class_name
  #define TestQPSyntax_is_a testlucy_TestQPSyntax_is_a
  #define TestQPSyntax_Run_IMP TESTLUCY_TestQPSyntax_Run_IMP
  #define TestQPSyntax_To_Host TESTLUCY_TestQPSyntax_To_Host
  #define TestQPSyntax_To_Host_t TESTLUCY_TestQPSyntax_To_Host_t
  #define TestQPSyntax_Clone TESTLUCY_TestQPSyntax_Clone
  #define TestQPSyntax_Clone_t TESTLUCY_TestQPSyntax_Clone_t
  #define TestQPSyntax_Equals TESTLUCY_TestQPSyntax_Equals
  #define TestQPSyntax_Equals_t TESTLUCY_TestQPSyntax_Equals_t
  #define TestQPSyntax_Compare_To TESTLUCY_TestQPSyntax_Compare_To
  #define TestQPSyntax_Compare_To_t TESTLUCY_TestQPSyntax_Compare_To_t
  #define TestQPSyntax_Destroy TESTLUCY_TestQPSyntax_Destroy
  #define TestQPSyntax_Destroy_t TESTLUCY_TestQPSyntax_Destroy_t
  #define TestQPSyntax_To_String TESTLUCY_TestQPSyntax_To_String
  #define TestQPSyntax_To_String_t TESTLUCY_TestQPSyntax_To_String_t
  #define TestQPSyntax_Run TESTLUCY_TestQPSyntax_Run
  #define TestQPSyntax_Run_t TESTLUCY_TestQPSyntax_Run_t
#endif /* TESTLUCY_USE_SHORT_NAMES */

#ifdef __cplusplus
}
#endif

#endif /* H_LUCY_TEST_SEARCH_TESTQUERYPARSERSYNTAX */


text:
package org.jamocha.dn.memory.javaimpl;

import java.util.Arrays;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.RequiredArgsConstructor;

import org.jamocha.dn.memory.FactIdentifier;
import org.jamocha.dn.memory.MemoryFact;

/**
 * Implementation of a Fact. Stores values as Objects.
 *
 * @author Fabian Ohler <fabian.ohler1@rwth-aachen.de>
 * @author Christoph Terwelp <christoph.terwelp@rwth-aachen.de>
 */
@RequiredArgsConstructor
@EqualsAndHashCode
class Fact implements MemoryFact {
    @Getter(onMethod = @__({@Override}))
    private final Template template;

    private final Object[] slotValues;

    private final FactIdentifier factIdentifier;

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer();
        sb.append("f-").append(null == this.factIdentifier ? "?" : this.factIdentifier.getId()).append(": (")
                .append(this.template.getName());
        for (int i = 0; i < this.slotValues.length; ++i) {
            final Object value = this.slotValues[i];
            if (null == value) continue;
            sb.append(" (").append(this.template.getSlotName(i)).append(' ').append(value).append(')');
        }
        sb.append(')');
        return sb.toString();
    }

    @Override
    public FactIdentifier getFactIdentifier() {
        return this.factIdentifier;
    }

    /**
     * Retrieves the value stored in the slot identified by {@link SlotAddress slot}.
     *
     * @param slot
     *         {@link SlotAddress slot address} identifying the slot the value is stored in
     * @return the value stored in the slot identified by {@link SlotAddress slot}
     */
    @Override
    public Object getValue(final org.jamocha.dn.memory.SlotAddress slot) {
        if (null == slot) return this.factIdentifier;
        return this.slotValues[((SlotAddress) slot).getIndex()];
    }

    public static boolean equalContent(final Fact a, final Fact b) {
        if (a == b) return true;
        return Arrays.deepEquals(a.slotValues, b.slotValues);
    }

    public static boolean equalReference(final Fact a, final Fact b) {
        return a == b;
    }

    @Override
    public org.jamocha.dn.memory.Fact toMutableFact() {
        return new org.jamocha.dn.memory.Fact(this.template, this.slotValues);
    }

    /**
     * @author Fabian Ohler <fabian.ohler1@rwth-aachen.de>
     */
    public static class MultislotPatternMatching extends Fact {
        final int[] separators;

        MultislotPatternMatching(final Template template, final Object[] slotValues,
                final FactIdentifier factIdentifier, final int[] separators) {
            super(template, slotValues, factIdentifier);
            this.separators = separators;
        }

        MultislotPatternMatching(final Fact origin, final int[] separators) {
            this(origin.template, origin.slotValues, origin.factIdentifier, separators);
        }

        @Override
        public Object getValue(final org.jamocha.dn.memory.SlotAddress slotAddress) {
            final MatchingElementAddress addr = (MatchingElementAddress) slotAddress;
            final Object[] values = (Object[]) super.getValue(addr.origin);
            final int index = addr.matchingIndex;
            final int from = 0 == index ? 0 : this.separators[index - 1];
            final int to = index < this.separators.length ? this.separators[index] : values.length;
            if (addr.single) {
                assert 1 == to - from;
                return values[from];
            }
            return Arrays.copyOfRange(values, from, to);
        }
    }
}


text:
require 'rails_helper'

RSpec.describe Course::Assessment::AssessmentsController do
  let!(:instance) { create(:instance) }

  with_tenant(:instance) do
    let(:user) { create(:user) }
    let!(:course) { create(:course, creator: user) }
    let(:category) { course.assessment_categories.first }
    let(:tab) { category.tabs.first }
    let!(:immutable_assessment) do
      create(:assessment, course: course).tap do |stub|
        allow(stub).to receive(:destroy).and_return(false)
      end
    end

    before { sign_in(user) }

    describe '#index' do
      context 'when a category is given' do
        before do
          post :index,
               course_id: course,
               id: immutable_assessment,
               assessment: { title: '' },
               category: category
        end
        it { expect(controller.instance_variable_get(:@category)).to eq(category) }
      end

      context 'when a tab is given' do
        before do
          post :index,
               course_id: course,
               id: immutable_assessment,
               assessment: { title: '' },
               category: category,
               tab: tab
        end
        it { expect(controller.instance_variable_get(:@tab)).to eq(tab) }
      end
    end

    describe '#update' do
      subject do
        post :update, course_id: course, id: immutable_assessment, assessment: { title: '' }
      end

      context 'when update fails' do
        before do
          controller.instance_variable_set(:@assessment, immutable_assessment)
          subject
        end

        it { is_expected.to render_template('edit') }
      end
    end

    describe '#destroy' do
      subject { delete :destroy, course_id: course, id: immutable_assessment }

      context 'when destroy fails' do
        before { controller.instance_variable_set(:@assessment, immutable_assessment) }

        it 'redirects with a flash message' do
          expect(subject).to redirect_to(course_assessments_path(course))
          expect(flash[:danger]).to eq(I18n.t('course.assessment.assessments.destroy.failure'))
        end
      end
    end

    describe '#add_assessment_breadcrumbs' do
      let(:breadcrumbs) { controller.send(:breadcrumb_names) }
      let(:tabs) { 1 }
      before do
        create_list(:course_assessment_tab, tabs - 1,
                    category: course.assessment_categories.first)
        get :index, course_id: course.id
      end

      context 'when the category has one tab' do
        it 'only displays the category' do
          expect(breadcrumbs).to include(course.assessment_categories.first.title)
          expect(breadcrumbs).not_to include(course.assessment_categories.first.tabs.first.title)
        end
      end

      context 'when the category has more than one tab' do
        let(:tabs) { 2 }
        it 'also displays the tab' do
          expect(breadcrumbs).to include(course.assessment_categories.first.title)
          expect(breadcrumbs).to include(course.assessment_categories.first.tabs.first.title)
        end
      end
    end
  end
end


text:
$(document).ready(function() {
	$(".colorbox").colorbox({
        maxWidth: '95%',
        maxHeight: '95%',
        current: jsData.jobs.current,
        previous: jsData.jobs.previous,
        next: jsData.jobs.next,
        close: jsData.jobs.close,
        xhrError: jsData.jobs.xhrError,
        imgError: jsData.jobs.imgError
    });
});


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Fusion.GIS.DataSystem.GeoObjectsSources;
using Fusion.GIS.GlobeMath;
using Fusion.Graphics;

namespace Fusion.GIS.LayerSpace.Layers
{
    public partial class GlobeLayer
    {
	    List<GeoVert> chartsCPU;
		VertexBuffer chartsVB;

		void UpdateCharts(List<GeoVert> charts)
		{
			chartsCPU = charts;

			if (chartsVB == null) {
				chartsVB = new VertexBuffer(Game.GraphicsDevice, typeof (GeoVert), chartsCPU.Count);
			}

			if (chartsVB.Capacity != chartsCPU.Count) {
				chartsVB.Dispose();
				chartsVB = new VertexBuffer(Game.GraphicsDevice, typeof(GeoVert), chartsCPU.Count);
			}

			chartsVB.SetData(chartsCPU.ToArray(), 0, chartsCPU.Count);
		}

		void DrawCharts()
		{
			//#if false
			if (chartsCPU == null) return;

			//string signature;
			//shader.SetVertexShader((int)(GlobeFlags.DRAW_LINES | GlobeFlags.VERTEX_SHADER | GlobeFlags.USE_GEOCOORDS), out signature);
			//shader.SetPixelShader((int)GlobeFlags.DRAW_CHARTS);
			//shader.SetGeometryShader((int)GlobeFlags.DRAW_CHARTS);

			//Game.GraphicsDevice.PipelineState = factory[(int)(GlobeFlags.DRAW_LINES | GlobeFlags.VERTEX_SHADER | GlobeFlags.USE_GEOCOORDS | GlobeFlags.DRAW_CHARTS)];
			//Game.GraphicsDevice.PipelineState.BlendState		= BlendState.Opaque;
			//Game.GraphicsDevice.DepthStencilState				= DepthStencilState.Default;
			//Game.GraphicsDevice.PipelineState.RasterizerState	= RasterizerState.CullCCW;

			//Game.GraphicsDevice.SetBlendState(BlendState.Opaque);
			//Game.GraphicsDevice.SetDepthStencilState(DepthStencilState.Default);

			//dotsBuf.SetCBufferVS(1);
			//dotsBuf.SetCBufferGS(1);

			Game.GraphicsDevice.VertexShaderConstants[1]	= dotsBuf;
			Game.GraphicsDevice.GeometryShaderConstants[1]	= dotsBuf;

			//Game.GraphicsDevice.SetRasterizerState(RasterizerState.CullCCW);

			Game.GraphicsDevice.PipelineState = myMiniFactory.ProducePipelineState(
					GlobeFlags.DRAW_VERTEX_LINES | GlobeFlags.VERTEX_SHADER | GlobeFlags.USE_GEOCOORDS | GlobeFlags.DRAW_CHARTS,
					Primitive.PointList,
					BlendState.Opaque,
					RasterizerState.CullCCW,
					DepthStencilState.Default);

			Game.GraphicsDevice.SetupVertexInput(chartsVB, null);
			Game.GraphicsDevice.Draw(/*Primitive.PointList,*/ chartsVB.Capacity, 0);

			//shader.ResetGeometryShader();
			//#endif
		}

    }
}


text:
<?php

namespace ahnames\hidev\config\php;

class Plugin extends \hiqdev\pluginmanager\Plugin
{
    protected $_items = [
        'configFiles' => [
            '@ahnames/hidev/config/php/config.yml',
        ],
        'views' => [
            '@ahnames/hidev/config/php/views',
        ],
    ];
}


text:
package org.gradle.api.publish.maven.internal.publisher;

import org.gradle.api.artifacts.repositories.MavenArtifactRepository;
import org.gradle.api.internal.artifacts.mvnsettings.LocalMavenRepositoryLocator;
import org.gradle.api.logging.LogLevel;
import org.gradle.api.publication.maven.internal.action.MavenPublishAction;
import org.gradle.api.publish.maven.MavenArtifact;
import org.gradle.internal.Factory;
import org.gradle.internal.logging.LoggingManagerInternal;
import org.gradle.util.GUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

public abstract class AbstractMavenPublisher implements MavenPublisher {
    private final Factory<LoggingManagerInternal> loggingManagerFactory;

    private final static Logger LOGGER = LoggerFactory.getLogger(AbstractMavenPublisher.class);
    private final LocalMavenRepositoryLocator mavenRepositoryLocator;

    public AbstractMavenPublisher(Factory<LoggingManagerInternal> loggingManagerFactory, LocalMavenRepositoryLocator mavenRepositoryLocator) {
        this.loggingManagerFactory = loggingManagerFactory;
        this.mavenRepositoryLocator = mavenRepositoryLocator;
    }

    public void publish(MavenNormalizedPublication publication, MavenArtifactRepository artifactRepository) {
        LOGGER.info("Publishing to repository {}", artifactRepository);
        MavenPublishAction deployTask = createDeployTask(publication.getPomFile(), mavenRepositoryLocator, artifactRepository);
        addPomAndArtifacts(deployTask, publication);
        execute(deployTask);
    }

    abstract protected MavenPublishAction createDeployTask(File pomFile, LocalMavenRepositoryLocator mavenRepositoryLocator, MavenArtifactRepository artifactRepository);

    private void addPomAndArtifacts(MavenPublishAction publishAction, MavenNormalizedPublication publication) {
        MavenArtifact mainArtifact = publication.getMainArtifact();
        if (mainArtifact != null) {
            publishAction.setMainArtifact(mainArtifact.getFile());
        }

        for (MavenArtifact mavenArtifact : publication.getArtifacts()) {
            if (mavenArtifact == mainArtifact) {
                continue;
            }
            publishAction.addAdditionalArtifact(mavenArtifact.getFile(), GUtil.elvis(mavenArtifact.getExtension(), ""), GUtil.elvis(mavenArtifact.getClassifier(), ""));
        }
    }

    private void execute(MavenPublishAction publishAction) {
        LoggingManagerInternal loggingManager = loggingManagerFactory.create();
        loggingManager.captureStandardOutput(LogLevel.INFO).start();
        try {
            publishAction.publish();
        } finally {
            loggingManager.stop();
        }
    }

}


text:
PyObject * hello(PyObject * self) {
	return PyUnicode_FromFormat("Hello C extension!");
}


text:
import {QuantizerCelebi} from '../quantize/quantizer_celebi';
import {Score} from '../score/score';

import {argbFromRgb} from './color_utils';

/**
 * Get the source color from an image.
 *
 * @param image The image element
 * @return Source color - the color most suitable for creating a UI theme
 */
export async function sourceColorFromImage(image: HTMLImageElement) {
  // Convert Image data to Pixel Array
  const imageBytes = await new Promise<Uint8ClampedArray>((resolve, reject) => {
    const canvas = document.createElement('canvas');
    const context = canvas.getContext('2d');
    if (!context) {
        return reject(new Error('Could not get canvas context'));
    }
    image.onload = () => {
      canvas.width = image.width;
      canvas.height = image.height;
      context.drawImage(image, 0, 0);
      resolve(context.getImageData(0, 0, image.width, image.height).data);
    };
  });

  // Convert Image data to Pixel Array
  const pixels: number[] = [];
  for (let i = 0; i < imageBytes.length; i += 4) {
    const r = imageBytes[i];
    const g = imageBytes[i + 1];
    const b = imageBytes[i + 2];
    const a = imageBytes[i + 3];
    if (a < 255) {
      continue;
    }
    const argb = argbFromRgb(r, g, b);
    pixels.push(argb);
  }

  // Convert Pixels to Material Colors
  const result = QuantizerCelebi.quantize(pixels, 128);
  const ranked = Score.score(result);
  const top = ranked[0];
  return top;
}


text:
package sunday.resi.example.counter10;

import java.util.concurrent.TimeUnit;

import sunday.resi.common.Circuit;
import sunday.resi.common.Power;
import sunday.resi.common.Signal;
import sunday.resi.common.Simulator;
import sunday.resi.library.BCDDecoder10;
import sunday.resi.library.Clock;
import sunday.resi.library.Counter16;
import sunday.resi.library.Relay;
import sunday.resi.library.SevenSegmentDecoder16;
import sunday.resi.library.SevenSegmentDisplay;
import sunday.resi.util.PartConsoleMonitor;
import sunday.resi.util.console.SystemConsole;

/**
 * Simulates a decimal counter and shows the result on a 7-segment display.
 *
 * @author Peter Hänsgen
 */
public class Counter10Main
{
    public static void main(String[] args)
    {
        Circuit circuit = new Circuit();

        Power power = new Power(circuit, "VCC");
        Clock clock = new Clock(circuit, "Clock", 500, TimeUnit.MILLISECONDS);

        Counter16 counter = new Counter16(circuit, "Counter");

        BCDDecoder10 bcd = new BCDDecoder10(circuit, "BCD");

        Relay reset = new Relay(circuit, "Reset");

        SevenSegmentDecoder16 decoder = new SevenSegmentDecoder16(circuit, "Decoder");

        SevenSegmentDisplay display = new SevenSegmentDisplay(circuit, "Display");
        circuit.addMonitor(new PartConsoleMonitor(display, new SystemConsole()));

        // internal wiring
        new Signal(circuit).from(power.getOut()).to(decoder.getPowerIn(), bcd.getPowerIn(), reset.getMiddleIn(0));

        new Signal(circuit).from(clock.get_Out()).to(counter.get_Clock());
        new Signal(circuit).from(clock.getOut()).to(counter.getClock());

        new Signal(circuit).from(reset.get_Out(0)).to(counter.getPowerIn());

        new Signal(circuit).from(counter.getOut0()).to(bcd.getIn0());
        new Signal(circuit).from(counter.getOut1()).to(bcd.getIn1());
        new Signal(circuit).from(counter.getOut2()).to(bcd.getIn2());
        new Signal(circuit).from(counter.getOut3()).to(bcd.getIn3());

        new Signal(circuit).from(bcd.getOut0()).to(decoder.getIn0());
        new Signal(circuit).from(bcd.getOut1()).to(decoder.getIn1());
        new Signal(circuit).from(bcd.getOut2()).to(decoder.getIn2());
        new Signal(circuit).from(bcd.getOut3()).to(decoder.getIn3());
        new Signal(circuit).from(bcd.getOut4()).to(decoder.getIn4());
        new Signal(circuit).from(bcd.getOut5()).to(decoder.getIn5());
        new Signal(circuit).from(bcd.getOut6()).to(decoder.getIn6());
        new Signal(circuit).from(bcd.getOut7()).to(decoder.getIn7());
        new Signal(circuit).from(bcd.getOut8()).to(decoder.getIn8());
        new Signal(circuit).from(bcd.getOut9()).to(decoder.getIn9());
        new Signal(circuit).from(bcd.getOutA()).to(reset.getCoilIn());

        new Signal(circuit).from(decoder.getOutA()).to(display.getInA());
        new Signal(circuit).from(decoder.getOutB()).to(display.getInB());
        new Signal(circuit).from(decoder.getOutC()).to(display.getInC());
        new Signal(circuit).from(decoder.getOutD()).to(display.getInD());
        new Signal(circuit).from(decoder.getOutE()).to(display.getInE());
        new Signal(circuit).from(decoder.getOutF()).to(display.getInF());
        new Signal(circuit).from(decoder.getOutG()).to(display.getInG());

        Simulator sim = new Simulator(circuit, 10);
        sim.start();
    }
}


text:
from interface import interface
from enum import *
from annotations import ClassAnnotation, Annotations


text:
package io.renren.modules.sys.excel;

import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.Data;

import java.util.Date;

/**
 * 用户管理
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0
 */
@Data
public class SysUserExcel {
    @Excel(name = "用户名")
    private String username;
    @Excel(name = "姓名")
    private String realName;
    @Excel(name = "性别", replace = {"男_0", "女_1", "保密_2"})
    private Integer gender;
    @Excel(name = "邮箱")
    private String email;
    @Excel(name = "手机号")
    private String mobile;
    @Excel(name = "部门名称")
    private String deptName;
    @Excel(name = "状态", replace = {"停用_0", "正常_1"})
    private Integer status;
    @Excel(name = "备注")
    private String remark;
    @Excel(name = "创建时间", format = "yyyy-MM-dd HH:mm:ss")
    private Date createDate;

}


text:
package org.kuali.rice.krms.api.repository;

import org.kuali.rice.core.api.exception.RiceIllegalArgumentException;
import org.kuali.rice.krms.api.KrmsConstants;
import org.kuali.rice.krms.api.repository.agenda.AgendaTreeDefinition;
import org.kuali.rice.krms.api.repository.context.ContextDefinition;
import org.kuali.rice.krms.api.repository.context.ContextSelectionCriteria;
import org.kuali.rice.krms.api.repository.rule.RuleDefinition;
import org.springframework.cache.annotation.Cacheable;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import java.util.List;

/**
 * The rule repository contains all of the information about context definitions,
 * agendas, and business rules.
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 *
 */
@WebService(name = "ruleRepositoryService", targetNamespace = KrmsConstants.Namespaces.KRMS_NAMESPACE_2_0)
@SOAPBinding(style = SOAPBinding.Style.DOCUMENT, use = SOAPBinding.Use.LITERAL, parameterStyle = SOAPBinding.ParameterStyle.WRAPPED)
public interface RuleRepositoryService {

	/**
	 * Locates a ContextDefinition based on the given map of context qualifiers. The requirements for valid selection
     * criteria are implementation dependent.  An IllegalArgumentException may be thrown if the implementation can't
     * operate with the given criteria.
	 *
	 * @param contextSelectionCriteria
	 * @return
     * @see ContextSelectionCriteria
     * @throws RiceIllegalArgumentException if the implementation can't handle the given ContextSelectionCriteria
	 */
	@WebMethod(operationName = "selectContext")
	@WebResult(name = "contextDefinition")
	public ContextDefinition selectContext(@WebParam(name = "contextSelectionCriteria") ContextSelectionCriteria contextSelectionCriteria)
            throws RiceIllegalArgumentException;

	/**
	 * Retrieves the agenda tree for the given agendaId.  The agenda tree includes
	 * the entire agenda definition in the appropriate order and with the
	 * defined agenda branching.
	 *
	 * @param agendaId the id of the agenda for which to retrieve the agenda tree
	 * @return the agenda tree, or null if no agenda could be located for the given agendaId
	 *
	 * @throws RiceIllegalArgumentException if the given agendaId is null
	 */
	@WebMethod(operationName = "getAgendaTree")
	@WebResult(name = "agendaTree")
    @Cacheable(value= AgendaTreeDefinition.Cache.NAME, key="'agendaId=' + #p0")
	public AgendaTreeDefinition getAgendaTree(@WebParam(name = "agendaId") String agendaId)
            throws RiceIllegalArgumentException;

    /**
	 * Retrieves all of the agendas trees for the given list of agendaIds.  The agenda tree includes
	 * the entire agenda definition in the appropriate order and with the
	 * defined agenda branching.
	 *
	 *
The list which is returned from this operation may not be the same size as the list
	 * which is passed to this method.  If an agenda doesn't exist for a given agenda id then
	 * no result for that id will be returned in the list.  As a result of this, the returned
	 * list can be empty, but it will never be null.
	 *
	 * @param agendaIds the list of agenda ids for which to retrieve the agenda trees
	 * @return the list of agenda trees for the given ids, this list will only contain agenda trees for the ids
	 * that were resolved successfully, it will never return null but could return an empty list if no agenda
	 * trees could be loaded for the given set of ids
	 *
	 * @throws RiceIllegalArgumentException if the given list of agendaIds is null
	 */
	@WebMethod(operationName = "getAgendaTrees")
    @XmlElementWrapper(name = "agendaTrees", required = true)
    @XmlElement(name = "agendaTree", required = false)
	@WebResult(name = "agendaTrees")
	public List<AgendaTreeDefinition> getAgendaTrees(@WebParam(name = "agendaIds") List<String> agendaIds)
            throws RiceIllegalArgumentException;

    /**
	 * Retrieves the rule for the given ruleId.  The rule includes the propositions
	 * which define the condition that is to be evaluated on the rule.  It also
	 * defines a collection of actions which will be invoked if the rule succeeds.
	 *
	 * @param ruleId the id of the rule to retrieve
	 * @return the rule definition, or null if no rule could be located for the given ruleId
	 *
	 * @throws RiceIllegalArgumentException if the given ruleId is null
	 */
	@WebMethod(operationName = "getRule")
	@WebResult(name = "rule")
    @Cacheable(value= RuleDefinition.Cache.NAME, key="'ruleId=' + #p0")
	public RuleDefinition getRule(@WebParam(name = "ruleId") String ruleId) throws RiceIllegalArgumentException;

	/**
	 * Retrieves all of the rules for the given list of ruleIds.  The rule includes the propositions
	 * which define the condition that is to be evaluated on the rule.  It also
	 * defines a collection of actions which will be invoked if the rule succeeds.
	 *
	 *
The list which is returned from this operation may not be the same size as the list
	 * which is passed to this method.  If a rule doesn't exist for a given rule id then
	 * no result for that id will be returned in the list.  As a result of this, the returned
	 * list can be empty, but it will never be null.
	 *
	 * @param ruleIds the list of rule ids for which to retrieve the rules
	 * @return the list of rules for the given ids, this list will only contain rules for the ids
	 * that were resolved successfully, it will never return null but could return an empty list if no
	 * rules could be loaded for the given set of ids
	 *
	 * @throws RiceIllegalArgumentException if the given list of ruleIds is null
	 */
	@WebMethod(operationName = "getRules")
    @XmlElementWrapper(name = "rules", required = true)
    @XmlElement(name = "rule", required = false)
	@WebResult(name = "rules")
	public List<RuleDefinition> getRules(@WebParam(name = "ruleIds") List<String> ruleIds)
            throws RiceIllegalArgumentException;

}


text:
mod progress;

use self::progress::Progress;
use anyhow::Result;
use flate2::read::GzDecoder;
use std::fs;
use std::path::Path;
use tar::Archive;
use walkdir::DirEntry;

const REVISION: &str = "98ad6a5519651af36e246c0335c964dd52c554ba";

#[rustfmt::skip]
static EXCLUDE_FILES: &[&str] = &[
    // TODO: impl ~const T {}
    // https://github.com/dtolnay/syn/issues/1051
    "src/test/ui/rfc-2632-const-trait-impl/syntax.rs",

    // Compile-fail expr parameter in const generic position: f::<1 + 2>()
    "src/test/ui/const-generics/early/closing-args-token.rs",
    "src/test/ui/const-generics/early/const-expression-parameter.rs",

    // Need at least one trait in impl Trait, no such type as impl 'static
    "src/test/ui/type-alias-impl-trait/generic_type_does_not_live_long_enough.rs",

    // Deprecated anonymous parameter syntax in traits
    "src/test/ui/issues/issue-13105.rs",
    "src/test/ui/issues/issue-13775.rs",
    "src/test/ui/issues/issue-34074.rs",
    "src/test/ui/proc-macro/trait-fn-args-2015.rs",
    "src/tools/rustfmt/tests/source/trait.rs",
    "src/tools/rustfmt/tests/target/trait.rs",

    // Various extensions to Rust syntax made up by rust-analyzer
    "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/0012_type_item_where_clause.rs",
    "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/0040_crate_keyword_vis.rs",
    "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/0131_existential_type.rs",
    "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/0179_use_tree_abs_star.rs",
    "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/0188_const_param_default_path.rs",
    "src/tools/rust-analyzer/crates/parser/test_data/parser/ok/0015_use_tree.rs",
    "src/tools/rust-analyzer/crates/parser/test_data/parser/ok/0029_range_forms.rs",
    "src/tools/rust-analyzer/crates/parser/test_data/parser/ok/0051_parameter_attrs.rs",
    "src/tools/rust-analyzer/crates/parser/test_data/parser/ok/0055_dot_dot_dot.rs",
    "src/tools/rust-analyzer/crates/parser/test_data/parser/ok/0068_item_modifiers.rs",
    "src/tools/rust-analyzer/crates/syntax/test_data/parser/validation/0031_block_inner_attrs.rs",
    "src/tools/rust-analyzer/crates/syntax/test_data/parser/validation/0045_ambiguous_trait_object.rs",
    "src/tools/rust-analyzer/crates/syntax/test_data/parser/validation/0046_mutable_const_item.rs",

    // Placeholder syntax for "throw expressions"
    "src/test/pretty/yeet-expr.rs",
    "src/test/ui/try-trait/yeet-for-option.rs",
    "src/test/ui/try-trait/yeet-for-result.rs",

    // Excessive nesting
    "src/test/ui/issues/issue-74564-if-expr-stack-overflow.rs",

    // Testing tools on invalid syntax
    "src/test/run-make/translation/test.rs",
    "src/test/ui/generics/issue-94432-garbage-ice.rs",
    "src/tools/rustfmt/tests/coverage/target/comments.rs",
    "src/tools/rustfmt/tests/parser/issue-4126/invalid.rs",
    "src/tools/rustfmt/tests/parser/issue_4418.rs",
    "src/tools/rustfmt/tests/parser/unclosed-delims/issue_4466.rs",
    "src/tools/rustfmt/tests/source/configs/disable_all_formatting/true.rs",
    "src/tools/rustfmt/tests/source/configs/spaces_around_ranges/false.rs",
    "src/tools/rustfmt/tests/source/configs/spaces_around_ranges/true.rs",
    "src/tools/rustfmt/tests/source/type.rs",
    "src/tools/rustfmt/tests/target/configs/spaces_around_ranges/false.rs",
    "src/tools/rustfmt/tests/target/configs/spaces_around_ranges/true.rs",
    "src/tools/rustfmt/tests/target/type.rs",

    // Generated file containing a top-level expression, used with `include!`
    "compiler/rustc_codegen_gcc/src/intrinsic/archs.rs",

    // Clippy lint lists represented as expressions
    "src/tools/clippy/clippy_lints/src/lib.deprecated.rs",
    "src/tools/clippy/clippy_lints/src/lib.register_all.rs",
    "src/tools/clippy/clippy_lints/src/lib.register_cargo.rs",
    "src/tools/clippy/clippy_lints/src/lib.register_complexity.rs",
    "src/tools/clippy/clippy_lints/src/lib.register_correctness.rs",
    "src/tools/clippy/clippy_lints/src/lib.register_internal.rs",
    "src/tools/clippy/clippy_lints/src/lib.register_lints.rs",
    "src/tools/clippy/clippy_lints/src/lib.register_nursery.rs",
    "src/tools/clippy/clippy_lints/src/lib.register_pedantic.rs",
    "src/tools/clippy/clippy_lints/src/lib.register_perf.rs",
    "src/tools/clippy/clippy_lints/src/lib.register_restriction.rs",
    "src/tools/clippy/clippy_lints/src/lib.register_style.rs",
    "src/tools/clippy/clippy_lints/src/lib.register_suspicious.rs",

    // Not actually test cases
    "src/test/ui/lint/expansion-time-include.rs",
    "src/test/ui/macros/auxiliary/macro-comma-support.rs",
    "src/test/ui/macros/auxiliary/macro-include-items-expr.rs",
    "src/test/ui/macros/include-single-expr-helper.rs",
    "src/test/ui/macros/include-single-expr-helper-1.rs",
    "src/test/ui/parser/issues/auxiliary/issue-21146-inc.rs",
];

#[rustfmt::skip]
static EXCLUDE_DIRS: &[&str] = &[
    // Inputs that intentionally do not parse
    "src/tools/rust-analyzer/crates/parser/test_data/parser/err",
    "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/err",

    // Inputs that lex but do not necessarily parse
    "src/tools/rust-analyzer/crates/parser/test_data/lexer",

    // Inputs that used to crash rust-analyzer, but aren't necessarily supposed to parse
    "src/tools/rust-analyzer/crates/syntax/test_data/parser/fuzz-failures",
    "src/tools/rust-analyzer/crates/syntax/test_data/reparse/fuzz-failures",
];

pub fn base_dir_filter(entry: &DirEntry) -> bool {
    let path = entry.path();

    let mut path_string = path.to_string_lossy();
    if cfg!(windows) {
        path_string = path_string.replace('\\', "/").into();
    }
    let path_string = if path_string == "tests/rust" {
        return true;
    } else if let Some(path) = path_string.strip_prefix("tests/rust/") {
        path
    } else {
        panic!("unexpected path in Rust dist: {}", path_string);
    };

    if path.is_dir() {
        return !EXCLUDE_DIRS.contains(&path_string);
    }

    if path.extension().map_or(true, |e| e != "rs") {
        return false;
    }

    if path_string.starts_with("src/test/ui") || path_string.starts_with("src/test/rustdoc-ui") {
        let stderr_path = path.with_extension("stderr");
        if stderr_path.exists() {
            // Expected to fail in some way
            return false;
        }
    }

    !EXCLUDE_FILES.contains(&path_string)
}

#[allow(dead_code)]
pub fn edition(path: &Path) -> &'static str {
    if path.ends_with("dyn-2015-no-warnings-without-lints.rs") {
        "2015"
    } else {
        "2018"
    }
}

pub fn clone_rust() {
    let needs_clone = match fs::read_to_string("tests/rust/COMMIT") {
        Err(_) => true,
        Ok(contents) => contents.trim() != REVISION,
    };
    if needs_clone {
        download_and_unpack().unwrap();
    }
    let mut missing = String::new();
    let test_src = Path::new("tests/rust");
    for exclude in EXCLUDE_FILES {
        if !test_src.join(exclude).is_file() {
            missing += "\ntests/rust/";
            missing += exclude;
        }
    }
    for exclude in EXCLUDE_DIRS {
        if !test_src.join(exclude).is_dir() {
            missing += "\ntests/rust/";
            missing += exclude;
            missing += "/";
        }
    }
    if !missing.is_empty() {
        panic!("excluded test file does not exist:{}\n", missing);
    }
}

fn download_and_unpack() -> Result<()> {
    let url = format!(
        "https://github.com/rust-lang/rust/archive/{}.tar.gz",
        REVISION
    );
    let response = reqwest::blocking::get(url)?.error_for_status()?;
    let progress = Progress::new(response);
    let decoder = GzDecoder::new(progress);
    let mut archive = Archive::new(decoder);
    let prefix = format!("rust-{}", REVISION);

    let tests_rust = Path::new("tests/rust");
    if tests_rust.exists() {
        fs::remove_dir_all(tests_rust)?;
    }

    for entry in archive.entries()? {
        let mut entry = entry?;
        let path = entry.path()?;
        if path == Path::new("pax_global_header") {
            continue;
        }
        let relative = path.strip_prefix(&prefix)?;
        let out = tests_rust.join(relative);
        entry.unpack(&out)?;
    }

    fs::write("tests/rust/COMMIT", REVISION)?;
    Ok(())
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="date_format">EEEE، d MMMM</string>
    <string name="today">امروز</string>
    <string name="tomorrow">فردا</string>
    <string name="aqi_pure">\'AQI \'+#weather_aqilevel</string>
    <string name="aqi_good">\'AQI \'+#weather_aqilevel</string>
    <string name="aqi_moderate">\'AQI \'+#weather_aqilevel</string>
    <string name="aqi_pollution">\'AQI \'+#weather_aqilevel</string>
    <string name="aqi_unhealthy">\'AQI \'+#weather_aqilevel</string>
    <string name="aqi_dangerous">\'AQI \'+#weather_aqilevel</string>
    <string name="aqi_hazardous">\'AQI \'+#weather_aqilevel</string>
    <string name="aqi_break">\'AQI \'+#weather_aqilevel</string>
    <string name="weather_type_null">'بدون داده'</string>
    <string name="weather_type_0">صاف</string>
    <string name="weather_type_1">ابری</string>
    <string name="weather_type_2">غبارآلود</string>
    <string name="weather_type_3">مه‌آلود</string>
    <string name="weather_type_4">رگبار شدید</string>
    <string name="weather_type_5">رگبار</string>
    <string name="weather_type_6">بارش بسیار سنگین باران</string>
    <string name="weather_type_7">رعد و برق</string>
    <string name="weather_type_8">بارندگی</string>
    <string name="weather_type_9">بارش سنگین باران</string>
    <string name="weather_type_10">بارانی</string>
    <string name="weather_type_11">نم‌نم باران</string>
    <string name="weather_type_12">برف و باران</string>
    <string name="weather_type_13">کولاک</string>
    <string name="weather_type_14">بارش پراکنده برف</string>
    <string name="weather_type_15">بارش سنگین برف</string>
    <string name="weather_type_16">بارش برف</string>
    <string name="weather_type_17">بارش سبک برف</string>
    <string name="weather_type_18">توفان شدید شن</string>
    <string name="weather_type_19">توفان شن</string>
    <string name="weather_type_20">توفان سبک شن</string>
    <string name="weather_type_21">توفان شن</string>
    <string name="weather_type_22">تگرگ</string>
    <string name="weather_type_23">گرد و غبار شناور</string>
    <string name="weather_type_24">مه</string>
</resources>


text:
package com.facebook.buck.rust;

import static com.facebook.buck.rust.RustLinkables.extendLinkerArgs;

import com.facebook.buck.cxx.CxxPlatform;
import com.facebook.buck.cxx.Linker;
import com.facebook.buck.model.BuildTargets;
import com.facebook.buck.parser.NoSuchBuildTargetException;
import com.facebook.buck.rules.BinaryBuildRule;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildTargetSourcePath;
import com.facebook.buck.rules.CommandTool;
import com.facebook.buck.rules.ExternalTestRunnerRule;
import com.facebook.buck.rules.ExternalTestRunnerTestSpec;
import com.facebook.buck.rules.Label;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.TestRule;
import com.facebook.buck.rules.Tool;
import com.facebook.buck.rules.args.SourcePathArg;
import com.facebook.buck.step.ExecutionContext;
import com.facebook.buck.step.Step;
import com.facebook.buck.test.TestCaseSummary;
import com.facebook.buck.test.TestResultSummary;
import com.facebook.buck.test.TestResults;
import com.facebook.buck.test.TestRunningOptions;
import com.facebook.buck.test.result.type.ResultType;
import com.facebook.buck.util.MoreCollectors;
import com.google.common.base.Charsets;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.function.BiConsumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@SuppressWarnings("PMD.TestClassWithoutTestCases")
public class RustTest
    extends RustCompile
    implements BinaryBuildRule, TestRule, ExternalTestRunnerRule {
  private static final Pattern TEST_STDOUT_PATTERN = Pattern.compile(
      "^---- (?<name>.+) stdout ----$");
  private static final Pattern FAILURES_LIST_PATTERN = Pattern.compile(
      "^failures:$");
  private final String crate;
  private final Path testOutputFile;
  private final Path testStdoutFile;

  public RustTest(
      BuildRuleParams params,
      SourcePathResolver resolver,
      String crate,
      Optional<SourcePath> crateRoot,
      ImmutableSortedSet<SourcePath> srcs,
      ImmutableSortedSet<String> features,
      ImmutableList<String> rustcFlags,
      Supplier<Tool> compiler,
      Supplier<Tool> linker,
      ImmutableList<String> linkerArgs,
      CxxPlatform cxxPlatform,
      Linker.LinkableDepType linkStyle) throws NoSuchBuildTargetException {
    super(
        RustLinkables.addNativeDependencies(params, resolver, cxxPlatform, linkStyle),
        resolver,
        crate,
        crateRoot,
        srcs,
        ImmutableList.<String>builder()
            .add("--test")
            .addAll(rustcFlags)
            .build(),
        features,
        RustLinkables.getNativeDirs(params.getDeps(), linkStyle, cxxPlatform),
        BuildTargets.getGenPath(
            params.getProjectFilesystem(),
            params.getBuildTarget(),
            "%s").resolve(crate),
        compiler,
        linker,
        extendLinkerArgs(
            linkerArgs,
            params.getDeps(),
            linkStyle,
            cxxPlatform),
        linkStyle);

    this.crate = crate;
    this.testOutputFile = getProjectFilesystem().resolve(getPathToTestResults());
    this.testStdoutFile = getProjectFilesystem().resolve(getPathToTestStdout());
  }

  @Override
  public boolean hasTestResultFiles() {
    return false;
  }

  @Override
  public ImmutableList<Step> runTests(
      ExecutionContext executionContext,
      TestRunningOptions options,
      TestReportingCallback testReportingCallback) {
    Path workingDirectory = getProjectFilesystem().resolve(getPathToTestOutputDirectory());
    return ImmutableList.of(
        new RustTestStep(
            getProjectFilesystem(),
            workingDirectory,
            getTestCommand("--logfile", testOutputFile.toString()),
            ImmutableMap.of(), // TODO(StanislavGlebik): environment
            workingDirectory.resolve("exitcode"),
            Optional.empty(),
            this.testStdoutFile
        )
    );
  }

  @Override
  public Callable<TestResults> interpretTestResults(
      ExecutionContext executionContext, boolean isUsingTestSelectors) {
    return () -> {
      ImmutableList<TestCaseSummary> summaries = ImmutableList.of();
      summaries = ImmutableList.of(
          new TestCaseSummary(
              getBuildTarget().getFullyQualifiedName(),
              parseTestResults()));
      return TestResults.of(
          getBuildTarget(),
          summaries,
          getContacts(),
          getLabels().stream()
              .map(Object::toString)
              .collect(MoreCollectors.toImmutableSet()));
    };
  }

  @Override
  public ImmutableSet<Label> getLabels() {
    return ImmutableSet.of();
  }

  @Override
  public ImmutableSet<String> getContacts() {
    // TODO(StanislavGlebik)
    return ImmutableSet.of();
  }

  @Override
  protected ImmutableSet<String> getDefaultSources() {
    return ImmutableSet.of("main.rs", "lib.rs");
  }

  @Override
  public Path getPathToTestOutputDirectory() {
    return BuildTargets.getGenPath(
        getProjectFilesystem(),
        getBuildTarget(),
        "%s");
  }

  @Override
  public boolean runTestSeparately() {
    return false;
  }

  @Override
  public boolean supportsStreamingTests() {
    return false;
  }

  @Override
  public ExternalTestRunnerTestSpec getExternalTestRunnerSpec(
      ExecutionContext executionContext, TestRunningOptions testRunningOptions) {
    return ExternalTestRunnerTestSpec.builder()
        .setTarget(getBuildTarget())
        .setType("rust")
        .addAllCommand(getTestCommand())
        .addAllLabels(getLabels())
        .addAllContacts(getContacts())
        .build();
  }

  private ImmutableList<String> getTestCommand(String... additionalArgs) {
    Path workingDirectory = getProjectFilesystem().resolve(getPathToTestOutputDirectory());
    ImmutableList.Builder<String> args = ImmutableList.builder();
    args.add(workingDirectory.toAbsolutePath().resolve(crate).toString());
    args.add(additionalArgs);
    return args.build();
  }

  private Path getPathToTestResults() {
    return getPathToTestOutputDirectory().resolve("output");
  }

  private Path getPathToTestStdout() {
    return getPathToTestOutputDirectory().resolve("stdout");
  }

  private ImmutableList<TestResultSummary> parseTestResults() throws IOException {

    Map<String, ResultType> testToResult = new HashMap<>();
    try (BufferedReader reader = Files.newBufferedReader(testOutputFile, Charsets.UTF_8)) {
      String line;
      while ((line = reader.readLine()) != null) {
        String[] resultAndTestName = line.split(" ");
        if (resultAndTestName.length != 2) {
          throw new RuntimeException(String.format("Unknown test output format %s", line));
        }
        ResultType result;
        if (resultAndTestName[0].equals("ok")) {
          result = ResultType.SUCCESS;
        } else if (resultAndTestName[0].equals("failed")) {
          result = ResultType.FAILURE;
        } else if (resultAndTestName[0].equals("ignored")) {
          result = ResultType.DISABLED;
        } else {
          throw new RuntimeException(String.format("Unknown test status %s", line));
        }
        testToResult.put(resultAndTestName[1], result);
      }
    }

    Map<String, String> testToStdout = new HashMap<>();
    try (BufferedReader reader = Files.newBufferedReader(testStdoutFile, Charsets.UTF_8)) {

      StringBuilder stdout = new StringBuilder();
      String currentStdoutTestName = null;
      BiConsumer<String, String> addTestStdout = (key, value) -> {
        testToStdout.put(key, value);
        stdout.setLength(0);
      };
      String line;
      while ((line = reader.readLine()) != null) {
        Matcher matcher;
        if ((matcher = TEST_STDOUT_PATTERN.matcher(line)).matches()) {
          if (currentStdoutTestName != null) {
            // Start of stdout output for new test
            // Save current stdout
            addTestStdout.accept(currentStdoutTestName, stdout.toString());
          }
          currentStdoutTestName = matcher.group("name");
        } else if (FAILURES_LIST_PATTERN.matcher(line).matches()) {
          if (currentStdoutTestName != null) {
            addTestStdout.accept(currentStdoutTestName, stdout.toString());
          }
        } else if (currentStdoutTestName != null) {
          stdout.append("\n");
          stdout.append(line);
        }
      }
    }

    ImmutableList.Builder<TestResultSummary> summariesBuilder = ImmutableList.builder();
    for (Map.Entry<String, ResultType> entry : testToResult.entrySet()) {
      summariesBuilder.add(
          new TestResultSummary(
              "rust_test",
              entry.getKey(),
              entry.getValue(),
              0, // TODO(StanislavGlebik) time
              "", // message
              "", // stack trace,
              testToStdout.get(entry.getKey()),
              "" // stderr
          ));
    }
    return summariesBuilder.build();
  }

  @Override
  public Tool getExecutableCommand() {
    return new CommandTool.Builder()
        .addArg(new SourcePathArg(getResolver(), new BuildTargetSourcePath(getBuildTarget())))
        .build();
  }
}


text:
"""
Wrapper for Salmon:
https://github.com/COMBINE-lab/salmon
http://biorxiv.org/content/early/2015/06/27/021592
"""

import os

from bcbio.rnaseq import sailfish
import bcbio.pipeline.datadict as dd
from bcbio.utils import (file_exists, safe_makedir, is_gzipped)
import bcbio.utils as utils
from bcbio.distributed.transaction import file_transaction
from bcbio.provenance import do
from bcbio.pipeline import config_utils
from bcbio import bam
from bcbio.log import logger

def run_salmon_bam(data):
    samplename = dd.get_sample_name(data)
    work_dir = dd.get_work_dir(data)
    salmon_dir = os.path.join(work_dir, "salmon", samplename)
    gtf_file = dd.get_gtf_file(data)
    bam_file = dd.get_transcriptome_bam(data)
    assert file_exists(gtf_file), "%s was not found, exiting." % gtf_file
    fasta_file = dd.get_ref_file(data)
    assert file_exists(fasta_file), "%s was not found, exiting." % fasta_file
    out_file = salmon_quant_bam(bam_file, salmon_dir, gtf_file, fasta_file, data)
    data = dd.set_salmon(data, out_file)
    data = dd.set_salmon_dir(data, salmon_dir)
    return [[data]]

def run_salmon_reads(data):
    data = utils.to_single_data(data)
    samplename = dd.get_sample_name(data)
    work_dir = dd.get_work_dir(data)
    salmon_dir = os.path.join(work_dir, "salmon", samplename)
    gtf_file = dd.get_gtf_file(data)
    files = dd.get_input_sequence_files(data)
    if len(files) == 2:
        fq1, fq2 = files
    else:
        fq1, fq2 = files[0], None
    assert file_exists(gtf_file), "%s was not found, exiting." % gtf_file
    fasta_file = dd.get_ref_file(data)
    assert file_exists(fasta_file), "%s was not found, exiting." % fasta_file
    out_file = salmon_quant_reads(fq1, fq2, salmon_dir, gtf_file, fasta_file, data)
    data = dd.set_salmon(data, out_file)
    data = dd.set_salmon_dir(data, salmon_dir)
    return [[data]]

def salmon_quant_reads(fq1, fq2, salmon_dir, gtf_file, ref_file, data):
    samplename = dd.get_sample_name(data)
    quant_dir = os.path.join(salmon_dir, "quant")
    safe_makedir(salmon_dir)
    out_file = os.path.join(quant_dir, "quant.sf")
    if file_exists(out_file):
        return out_file
    num_cores = dd.get_num_cores(data)
    strandedness = dd.get_strandedness(data).lower()
    salmon = config_utils.get_program("salmon", dd.get_config(data))
    libtype = sailfish._libtype_string(fq1, fq2, strandedness)
    num_cores = dd.get_num_cores(data)
    index = salmon_index(gtf_file, ref_file, data, os.path.dirname(salmon_dir))
    resources = config_utils.get_resources("salmon", dd.get_config(data))
    params = ""
    if resources.get("options") is not None:
        params = " ".join([str(x) for x in resources.get("options", [])])
    cmd = ("{salmon} quant {libtype} -i {index} -p {num_cores} "
           "--gcBias "
           "-o {tx_out_dir} {params} ")
    fq1_cmd = "<(cat {fq1})" if not is_gzipped(fq1) else "<(gzip -cd {fq1})"
    fq1_cmd = fq1_cmd.format(fq1=fq1)
    if not fq2:
        cmd += " -r {fq1_cmd} "
    else:
        fq2_cmd = "<(cat {fq2})" if not is_gzipped(fq2) else "<(gzip -cd {fq2})"
        fq2_cmd = fq2_cmd.format(fq2=fq2)
        cmd += " -1 {fq1_cmd} -2 {fq2_cmd} "
    # skip --useVBOpt for now, it can cause segfaults
    cmd += "--numBootstraps 30 "
    with file_transaction(data, quant_dir) as tx_out_dir:
        message = ("Quantifying transcripts in %s and %s with Salmon."
                   %(fq1, fq2))
        do.run(cmd.format(**locals()), message, None)
        sailfish.sleuthify_sailfish(tx_out_dir)
    return out_file

def salmon_quant_bam(bam_file, salmon_dir, gtf_file, ref_file, data):
    samplename = dd.get_sample_name(data)
    quant_dir = os.path.join(salmon_dir, "quant")
    safe_makedir(salmon_dir)
    out_file = os.path.join(quant_dir, "quant.sf")
    if file_exists(out_file):
        return out_file
    gtf_fa = sailfish.create_combined_fasta(data, salmon_dir)
    num_cores = dd.get_num_cores(data)
    strandedness = dd.get_strandedness(data).lower()
    salmon = config_utils.get_program("salmon", dd.get_config(data))
    libtype = _libtype_string(bam_file, strandedness)
    num_cores = dd.get_num_cores(data)
    cmd = ("{salmon} quant {libtype} -p {num_cores} -t {gtf_fa} "
           "-o {tx_out_dir} -a {bam_file} ")
    cmd += "--numBootstraps 30 "
    with file_transaction(data, quant_dir) as tx_out_dir:
        message = "Quantifying transcripts in %s with Salmon." % bam_file
        do.run(cmd.format(**locals()), message, None)
    return out_file

def _libtype_string(bam_file, strandedness):
    libtype = "-l I" if bam.is_paired(bam_file) else "-l "
    strand = sailfish._sailfish_strand_string(strandedness)
    return libtype + strand

def run_salmon_index(*samples):
    for data in dd.sample_data_iterator(samples):
        work_dir = dd.get_work_dir(data)
        salmon_dir = os.path.join(work_dir, "salmon")
        gtf_file = dd.get_gtf_file(data)
        assert file_exists(gtf_file), "%s was not found, exiting." % gtf_file
        fasta_file = dd.get_ref_file(data)
        assert file_exists(fasta_file), "%s was not found, exiting." % fasta_file
        salmon_index(gtf_file, fasta_file, data, salmon_dir)
    return samples

def salmon_index(gtf_file, ref_file, data, out_dir):
    out_dir = os.path.join(out_dir, "index", sailfish.get_build_string(data))
    if dd.get_disambiguate(data):
        out_dir = "-".join([out_dir] + dd.get_disambiguate(data))
    salmon = config_utils.get_program("salmon", dd.get_config(data))
    num_cores = dd.get_num_cores(data)
    if dd.get_transcriptome_fasta(data):
        gtf_fa = dd.get_transcriptome_fasta(data)
    else:
        gtf_fa = sailfish.create_combined_fasta(data)
    assert file_exists(gtf_fa), "%s was not found, exiting." % gtf_fa
    tmpdir = dd.get_tmp_dir(data)
    out_file = os.path.join(out_dir, "versionInfo.json")
    if file_exists(out_file):
        logger.info("Transcriptome index for %s detected, skipping building." % gtf_fa)
        return out_dir
    files = dd.get_input_sequence_files(data)
    kmersize = sailfish.pick_kmersize(files[0])
    with file_transaction(data, out_dir) as tx_out_dir:
        cmd = "{salmon} index -k {kmersize} -p {num_cores} -i {tx_out_dir} -t {gtf_fa}"
        message = "Creating Salmon index for {gtf_fa} with {kmersize} bp kmers."
        do.run(cmd.format(**locals()), message.format(**locals()), None)
    return out_dir


text:
<?xml version="1.0"?>
<!--

    Copyright 2015-2016 the original author or authors.

    Licensed 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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.nanoframework</groupId>
    <artifactId>nano</artifactId>
    <version>1.4.11-SNAPSHOT</version>
  </parent>
  <artifactId>nano-jetty-server</artifactId>
  <name>Nano Embedded Jetty Server</name>
  <url>http://maven.apache.org</url>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <cs.dir>${project.parent.basedir}</cs.dir>
  </properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.eclipse.jetty.aggregate</groupId>
      <artifactId>jetty-all</artifactId>
    </dependency>

		<!-- JSP Support -->
    <dependency>
      <groupId>org.glassfish.web</groupId>
      <artifactId>javax.servlet.jsp</artifactId>
    </dependency>

        <!-- EL Support -->
    <dependency>
      <groupId>org.glassfish.web</groupId>
      <artifactId>javax.el</artifactId>
    </dependency>

    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.nanoframework</groupId>
      <artifactId>nano-webmvc</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>org.nanoframework</groupId>
      <artifactId>nano-orm-jedis</artifactId>
      <version>${project.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.nanoframework</groupId>
      <artifactId>nano-orm-jdbc</artifactId>
      <version>${project.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.nanoframework</groupId>
      <artifactId>nano-concurrent</artifactId>
      <version>${project.version}</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>

  <build>
    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <targetPath>${project.basedir}/</targetPath>
        <includes>
          <include>webRoot/**</include>
        </includes>
      </resource>
    </resources>
  </build>
</project>


text:
package com.ixeption.spark.dota2.util

import spray.json.DefaultJsonProtocol

/**
  * Created by ixeption on 27.06.2016.
  */
object GetMatchDetailsModel {

  case class Ability_upgrades(
                               ability: Double,
                               time: Double,
                               level: Double
                             )

  case class Players(
                      account_id: Double,
                      player_slot: Double,
                      hero_id: Double,
                      item_0: Double,
                      item_1: Double,
                      item_2: Double,
                      item_3: Double,
                      item_4: Double,
                      item_5: Double,
                      kills: Double,
                      deaths: Double,
                      assists: Double,
                      leaver_status: Double,
                      last_hits: Double,
                      denies: Double,
                      gold_per_min: Double,
                      xp_per_min: Double,
                      level: Double,
                      gold: Double,
                      gold_spent: Double,
                      hero_damage: Double,
                      ability_upgrades: List[Ability_upgrades]
                    )

  case class ResultBis(
                        players: List[Players],
                        radiant_win: Boolean,
                        duration: Double,
                        pre_game_duration: Double,
                        start_time: Double,
                        match_id: Double,
                        match_seq_num: Double,
                        tower_status_radiant: Double,
                        tower_status_dire: Double,
                        barracks_status_radiant: Double,
                        barracks_status_dire: Double,
                        cluster: Double,
                        first_blood_time: Double,
                        lobby_type: Double,
                        human_players: Double,
                        leagueid: Double,
                        positive_votes: Double,
                        negative_votes: Double,
                        game_mode: Double,
                        flags: Double,
                        radiant_score: Double,
                        dire_score: Double
                      )

  case class MatchDetails(
                           result: ResultBis
                         )

  object Ability_upgradesProtocol extends DefaultJsonProtocol {
    implicit val MatchesFormat = jsonFormat3(Ability_upgrades)
  }

  object PlayersProtocol extends DefaultJsonProtocol {

    import com.ixeption.spark.dota2.util.GetMatchDetailsModel.Ability_upgradesProtocol._

    implicit val PlayersFormat = jsonFormat22(Players)
  }

  object ResultBisProtocol extends DefaultJsonProtocol {

    import com.ixeption.spark.dota2.util.GetMatchDetailsModel.PlayersProtocol._

    implicit val ResultBisFormat = jsonFormat22(ResultBis)
  }

  object MatchDetailsProtocol extends DefaultJsonProtocol {

    import com.ixeption.spark.dota2.util.GetMatchDetailsModel.ResultBisProtocol._

    implicit val MatchHistoryFormat = jsonFormat1(MatchDetails)
  }

}


text:
#include <stdlib.h>
#include <assert.h>

#include "connsbuf.h"

#ifndef NULL
#define NULL (void *)0
#endif

void addSimpleC(C_SimpleConns *simpleConns, int y, int par_id)
{
	int num = simpleConns->paramsNumber[y];
	simpleConns->paramId[y][num] = par_id;
	++simpleConns->paramsNumber[y];
}

void addCompoundC(C_CompoundConns *compoundConns, int py, int y, int par_id)
{
	int i = compoundConns->connsMap[y][py] - 1;
	if(i == -1) {
		i = compoundConns->prevNumber[y];
		compoundConns->prevLabels[y][i] = py;
		compoundConns->paramsNumber[y][i] = 0;

		++compoundConns->prevNumber[y];
		compoundConns->connsMap[y][py] = i + 1;
	}

	int num = compoundConns->paramsNumber[y][i];
	compoundConns->paramId[y][i][num] = par_id;
	++compoundConns->paramsNumber[y][i];
}

/*void addC(int *conn, int cn, C_ConnsBuf *connsBuf)
{
	C_SimpleConns *simpleConns = connsBuf->simpleConns;
	C_CompoundConns *compoundConns = connsBuf->compoundConns;
	C_CompoundConns *revCompoundConns = connsBuf->revCompoundConns;

	int k;
        for (k = 0; k < 3 * cn; k += 3) {
		int y1 = conn[k];
		int y2 = conn[k + 1];
		int par_id = conn[k + 2];

		if(y1 == -1)
			addSimpleC(simpleConns, y2, par_id);
		else {
			addCompoundC(compoundConns, y1, y2, par_id);
			addCompoundC(revCompoundConns, y2, y1, par_id);
		}
	}
}*/

void fillSimpleConns(int *conn, int cn, C_ConnsBuf *connsBuf)
{
	C_SimpleConns *simpleConns = connsBuf->simpleConns;

	int k;
        for (k = 0; k < 3 * cn; k += 3) {
		int y1 = conn[k];
		int y2 = conn[k + 1];
		int par_id = conn[k + 2];	// parameter/feature id

		assert(y1 == -1);
		addSimpleC(simpleConns, y2, par_id);
	}
}

void fillCompoundConns(int *conn, int cn, C_ConnsBuf *connsBuf)
{
	C_CompoundConns *compoundConns = connsBuf->compoundConns;
	C_CompoundConns *revCompoundConns = connsBuf->revCompoundConns;

	int k;
        for (k = 0; k < 3 * cn; k += 3) {
		int y1 = conn[k];
		int y2 = conn[k + 1];
		int par_id = conn[k + 2];

		assert(y1 != -1);
		addCompoundC(compoundConns, y1, y2, par_id);
		addCompoundC(revCompoundConns, y2, y1, par_id);
	}
}

void fillConnsBuf(C_ConnsBuf* connsBuf, C_Conns* conns, C_Sentence* sent, int wid)
{
	int k;
	for(k = 0 ; k < sent->snum[wid] ; ++k) {
		int x = sent->singles[wid][k];
		if(x < conns->xn)
			// addC(conns->conns[x], conns->csizes[x], connsBuf);
			fillSimpleConns(conns->conns[x], conns->csizes[x], connsBuf);
	}

	for(k = 0 ; k < sent->pnum[wid] ; ++k) {
		int x = sent->pairs[wid][k];
		if(x < conns->xn)
			// addC(conns->conns[x], conns->csizes[x], connsBuf);
			fillCompoundConns(conns->conns[x], conns->csizes[x], connsBuf);
	}
}

/*void fillConnsBuf(C_ConnsBuf* connsBuf, C_Conns* conns, int *word, int wn)
{
	int k;
	for(k = 0; k < wn; ++k) {
		int x = word[k];
		if(x < conns->xn)
			addC(conns->conns[x], conns->csizes[x], connsBuf);
	}
}*/

//obstype_num - liczba typow obserwacji
C_SimpleConns* initSimpleConns(int yn, int obstype_num)
{
	C_SimpleConns *simpleConns = (C_SimpleConns*)malloc(sizeof(C_SimpleConns));
	if(simpleConns == NULL)
		return NULL;

	//Musi byc wyzerowane !
	simpleConns->paramsNumber = (int*)calloc(yn, sizeof(int));
	if(simpleConns->paramsNumber == NULL)
		return NULL;

	simpleConns->paramId = (int**)malloc(yn * sizeof(int*));
	if(simpleConns->paramId == NULL)
		return NULL;

	int i;
	for(i = 0 ; i < yn ; ++i) {
		simpleConns->paramId[i] = malloc(obstype_num * sizeof(int));
		if(simpleConns->paramId[i] == NULL)
			return NULL;
	}

	return simpleConns;
}

C_CompoundConns* initCompoundConns(int yn, int obstype_num)
{
	C_CompoundConns *compoundConns = (C_CompoundConns*)malloc(sizeof(C_CompoundConns));
	if(compoundConns == NULL)
		return NULL;

	compoundConns->prevNumber = (int*)calloc(yn, sizeof(int));
	if(compoundConns->prevNumber == NULL)
		return NULL;

	compoundConns->prevLabels = (int**)malloc(yn * sizeof(int*));
	if(compoundConns->prevLabels == NULL)
		return NULL;

	compoundConns->paramsNumber = (int**)malloc(yn * sizeof(int*));
	if(compoundConns->paramsNumber == NULL)
		return NULL;

	compoundConns->connsMap = (int**)malloc(yn * sizeof(int*));
	if(compoundConns->connsMap == NULL)
		return NULL;

	int i, j;
	for(i = 0 ; i < yn ; ++i) {
		compoundConns->prevLabels[i] = malloc(yn * sizeof(int));
		if(compoundConns->prevLabels[i] == NULL)
			return NULL;
		compoundConns->paramsNumber[i] = malloc(yn * sizeof(int));
		if(compoundConns->paramsNumber[i] == NULL)
			return NULL;
		//connsMap musi byc wyzerowana !
		compoundConns->connsMap[i] = calloc(yn, sizeof(int));
		if(compoundConns->connsMap[i] == NULL)
			return NULL;
	}

	compoundConns->paramId = malloc(yn * sizeof(int**));
	if(compoundConns->paramId == NULL)
		return NULL;

	for(i = 0 ; i < yn ; ++i) {
		compoundConns->paramId[i] = malloc(yn * sizeof(int*));
		if(compoundConns->paramId[i] == NULL)
			return NULL;

		for(j = 0 ; j < yn ; ++j) {
			compoundConns->paramId[i][j] = malloc(obstype_num * sizeof(int));
			if(compoundConns->paramId[i][j] == NULL)
				return NULL;
		}
	}

	return compoundConns;
}

C_ConnsBuf *newConnsBuf(int yn, int obstype_num)
{
	C_ConnsBuf *connsBuffer = (C_ConnsBuf *)malloc(sizeof(C_ConnsBuf));
	if(connsBuffer == NULL)
		return NULL;

	connsBuffer->yn = yn;

	connsBuffer->simpleConns = initSimpleConns(yn, obstype_num);
	if(connsBuffer->simpleConns == NULL)
		return NULL;

	connsBuffer->compoundConns = initCompoundConns(yn, obstype_num);
	if(connsBuffer->compoundConns == NULL)
		return NULL;

	connsBuffer->revCompoundConns = initCompoundConns(yn, obstype_num);
	if(connsBuffer->revCompoundConns == NULL)
		return NULL;

	return connsBuffer;
}

void freeSimpleConns(C_SimpleConns *simpleConns, int yn)
{
	free(simpleConns->paramsNumber);

	int i;
	for(i = 0 ; i < yn ; ++i)
		free(simpleConns->paramId[i]);
	free(simpleConns->paramId);

	free(simpleConns);
}

void freeCompoundConns(C_CompoundConns *compoundConns, int yn)
{
	free(compoundConns->prevNumber);

	int i, j;
	for(i = 0 ; i < yn ; ++i) {
		free(compoundConns->prevLabels[i]);
		free(compoundConns->paramsNumber[i]);
		free(compoundConns->connsMap[i]);
	}
	free(compoundConns->prevLabels);
	free(compoundConns->paramsNumber);
	free(compoundConns->connsMap);

	for(i = 0 ; i < yn ; ++i) {
		for(j = 0 ; j < yn ; ++j)
			free(compoundConns->paramId[i][j]);
		free(compoundConns->paramId[i]);
	}
	free(compoundConns->paramId);

	free(compoundConns);
}

void freeConnsBuf(C_ConnsBuf* connsBuffer)
{
	int yn = connsBuffer->yn;
	freeSimpleConns(connsBuffer->simpleConns, yn);
	freeCompoundConns(connsBuffer->compoundConns, yn);
	freeCompoundConns(connsBuffer->revCompoundConns, yn);
	free(connsBuffer);
}

void clearSimpleConns(C_SimpleConns* simpleConns, int yn)
{
	int i;
	for(i = 0 ; i < yn ; ++i)
		simpleConns->paramsNumber[i] = 0;
}

void clearCompoundConns(C_CompoundConns* compoundConns, int yn)
{
	int y, k;
	for(y = 0 ; y < yn ; ++y) {
		int prevNum = compoundConns->prevNumber[y];

		for(k = 0 ; k < prevNum ; ++k) {
			int py = compoundConns->prevLabels[y][k];
			compoundConns->connsMap[y][py] = 0;
		}

		compoundConns->prevNumber[y] = 0;
	}
}

void clearConnsBuf(C_ConnsBuf *connsBuf)
{
	int yn = connsBuf->yn;
	clearSimpleConns(connsBuf->simpleConns, yn);
	clearCompoundConns(connsBuf->compoundConns, yn);
	clearCompoundConns(connsBuf->revCompoundConns, yn);
}


text:
import {timerFor} from './timer';
import {user} from './log';

/** @const {string}  */
const LOAD_FAILURE_PREFIX = 'Failed to load:';

/**
 * @type {function(*, !Element=)|undefined}
 */
let reportError;

/**
 * Sets reportError function. Called from error.js to break cyclic
 * dependency.
 * @param {function(*, !Element=)|undefined} fn
 */
export function setReportError(fn) {
  reportError = fn;
}

/**
 * Listens for the specified event on the element.
 * @param {!EventTarget} element
 * @param {string} eventType
 * @param {function(!Event)} listener
 * @param {boolean=} opt_capture
 * @return {!UnlistenDef}
 */
export function listen(element, eventType, listener, opt_capture) {
  let localElement = element;
  let localListener = listener;
  /** @type {?Function}  */
  let wrapped = event => {
    try {
      return localListener.call(this, event);
    } catch (e) {
      reportError(e);
      throw e;
    }
  };
  const capture = opt_capture || false;
  localElement.addEventListener(eventType, wrapped, capture);
  return () => {
    if (localElement) {
      localElement.removeEventListener(eventType, wrapped, capture);
    }
    localListener = null;
    localElement = null;
    wrapped = null;
  };
}

/**
 * Listens for the specified event on the element and removes the listener
 * as soon as event has been received.
 * @param {!EventTarget} element
 * @param {string} eventType
 * @param {function(!Event)} listener
 * @param {boolean=} opt_capture
 * @return {!UnlistenDef}
 */
export function listenOnce(element, eventType, listener, opt_capture) {
  let localElement = element;
  let localListener = listener;
  const capture = opt_capture || false;
  let unlisten;
  let proxy = event => {
    try {
      localListener(event);
    } catch (e) {
      reportError(e);
      throw e;
    } finally {
      unlisten();
    }
  };
  unlisten = () => {
    if (localElement) {
      localElement.removeEventListener(eventType, proxy, capture);
    }
    localElement = null;
    proxy = null;
    localListener = null;
  };
  localElement.addEventListener(eventType, proxy, capture);
  return unlisten;
}

/**
 * Returns  a promise that will resolve as soon as the specified event has
 * fired on the element. Optionally, opt_timeout can be specified that will
 * reject the promise if the event has not fired by then.
 * @param {!EventTarget} element
 * @param {string} eventType
 * @param {boolean=} opt_capture
 * @param {number=} opt_timeout
 * @return {!Promise<!Event>}
 */
export function listenOncePromise(element, eventType, opt_capture,
    opt_timeout) {
  let unlisten;
  const eventPromise = new Promise((resolve, unusedReject) => {
    unlisten = listenOnce(element, eventType, resolve, opt_capture);
  });
  return racePromise_(eventPromise, unlisten, undefined, opt_timeout);
}

/**
 * Whether the specified element/window has been loaded already.
 * @param {!Element|!Window} eleOrWindow
 * @return {boolean}
 */
export function isLoaded(eleOrWindow) {
  return !!(eleOrWindow.complete || eleOrWindow.readyState == 'complete'
      // If the passed in thing is a Window, infer loaded state from
      //
      || (eleOrWindow.document
          && eleOrWindow.document.readyState == 'complete'));
}

/**
 * Returns a promise that will resolve or fail based on the eleOrWindow's 'load'
 * and 'error' events. Optionally this method takes a timeout, which will reject
 * the promise if the resource has not loaded by then.
 * @param {T} eleOrWindow Supports both Elements and as a special case Windows.
 * @param {number=} opt_timeout
 * @return {!Promise<T>}
 * @template T
 */
export function loadPromise(eleOrWindow, opt_timeout) {
  let unlistenLoad;
  let unlistenError;
  if (isLoaded(eleOrWindow)) {
    return Promise.resolve(eleOrWindow);
  }
  let loadingPromise = new Promise((resolve, reject) => {
    // Listen once since IE 5/6/7 fire the onload event continuously for
    // animated GIFs.
    const tagName = eleOrWindow.tagName;
    if (tagName === 'AUDIO' || tagName === 'VIDEO') {
      unlistenLoad = listenOnce(eleOrWindow, 'loadstart', resolve);
    } else {
      unlistenLoad = listenOnce(eleOrWindow, 'load', resolve);
    }
    // For elements, unlisten on error (don't for Windows).
    if (tagName) {
      unlistenError = listenOnce(eleOrWindow, 'error', reject);
    }
  });
  loadingPromise = loadingPromise.then(() => eleOrWindow, failedToLoad);
  return racePromise_(loadingPromise, unlistenLoad, unlistenError,
      opt_timeout);
}

/**
 * Emit error on load failure.
 * @param {*} event
 */
function failedToLoad(event) {
  // Report failed loads as user errors so that they automatically go
  // into the "document error" bucket.
  let target = event.target;
  if (target && target.src) {
    target = target.src;
  }
  throw user().createError(LOAD_FAILURE_PREFIX, target);
}

/**
 * Returns true if this error message is was created for a load error.
 * @param {string} message An error message
 * @return {boolean}
 */
export function isLoadErrorMessage(message) {
  return message.indexOf(LOAD_FAILURE_PREFIX) != -1;
}

/**
 * @param {!Promise<TYPE>} promise
 * @param {UnlistenDef|undefined} unlisten1
 * @param {UnlistenDef|undefined} unlisten2
 * @param {number|undefined} timeout
 * @return {!Promise<TYPE>}
 * @template TYPE
 */
function racePromise_(promise, unlisten1, unlisten2, timeout) {
  let racePromise;
  if (timeout === undefined) {
    // Timeout is not specified: return promise.
    racePromise = promise;
  } else {
    // Timeout has been specified: add a timeout condition.
    racePromise = timerFor(self).timeoutPromise(timeout || 0, promise);
  }
  if (unlisten1) {
    racePromise.then(unlisten1, unlisten1);
  }
  if (unlisten2) {
    racePromise.then(unlisten2, unlisten2);
  }
  return racePromise;
}


text:
using UnityEngine;

namespace Klak.Math
{
    static class BasicMath
    {
        public static float Lerp(float a, float b, float mix)
        {
            return a * (1 - mix) + b * mix;
        }
        public static Vector3 Lerp(Vector3 a, Vector3 b, float mix)
        {
            return a * (1 - mix) + b * mix;
        }
    }
}


text:
<?php namespace Regulus\Fractal\Controllers\Media;

use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\View;

use Fractal;

use Regulus\Fractal\Models\Media\Type;
use Regulus\Fractal\Models\Content\FileType;

use Regulus\ActivityLog\Models\Activity;
use Auth;
use Form;
use Format;
use Site;

class TypesController extends MediaController {

	public function __construct()
	{
		parent::__construct();

		Fractal::setControllerPath($this);

		Site::set('section', 'Media');
		Site::set('subSection', 'Types');
		Site::setTitle(Fractal::transChoice('labels.media_type', 2));

		// set content type and views location
		Fractal::setContentType('media-type');

		Fractal::setViewsLocation('media.types');

		Fractal::addTrailItem(Fractal::transChoice('labels.type', 2), Fractal::getControllerPath());
	}

	public function index()
	{
		$data       = Fractal::initPagination();
		$categories = Type::getSearchResults($data);

		Fractal::setContentForPagination($categories);

		$data     = Fractal::setPaginationMessage(true);
		$messages = Fractal::getPaginationMessageArray();

		if (!count($categories))
			$categories = Type::orderBy($data['sortField'], $data['sortOrder'])->paginate($data['itemsPerPage']);

		Fractal::addButton([
			'label' => Fractal::trans('labels.create_item', ['item' => Fractal::transChoice('labels.media_type')]),
			'icon'  => 'flag-o',
			'uri'   => Fractal::uri('create', true),
		]);

		return View::make(Fractal::view('list'))
			->with('content', $categories)
			->with('messages', $messages);
	}

	public function search()
	{
		$data       = Fractal::initPagination();
		$categories = Type::getSearchResults($data);

		Fractal::setContentForPagination($categories);

		$data = Fractal::setPaginationMessage();

		if (!count($categories))
			$data['content'] = Type::orderBy($data['sortField'], $data['sortOrder'])->paginate($data['itemsPerPage']);

		$data['result']['pages']     = Fractal::getLastPage();
		$data['result']['tableBody'] = Fractal::createTable($data['content'], true);

		return $data['result'];
	}

	public function create()
	{
		Site::setTitle(Fractal::trans('labels.create_item', ['item' => Fractal::transChoice('labels.media_type')]));

		Type::setDefaultsForNew();
		Form::setErrors();

		Fractal::addButton([
			'label' => Fractal::trans('labels.return_to_items_list', ['items' => Fractal::transChoice('labels.media_type', 2)]),
			'icon'  => 'list',
			'uri'   => Fractal::uri('', true),
		]);

		Fractal::addTrailItem(Fractal::trans('labels.create'), Request::url());

		return View::make(Fractal::view('form'));
	}

	public function store()
	{
		Form::setValidationRules(Type::validationRules());

		$messages = [];
		if (Form::isValid())
		{
			$messages['success'] = Fractal::trans('messages.success.created', ['item' => Fractal::transChoiceLowerA('labels.media_type')]);

			$input = Input::all();
			$input['user_id'] = Auth::user()->id;

			$type = Type::createNew($input);

			Activity::log([
				'contentId'   => $type->id,
				'contentType' => 'Type',
				'action'      => 'Create',
				'description' => 'Created a Media Type',
				'details'     => 'Name: '.$type->name,
			]);

			return Redirect::to(Fractal::uri('', true))
				->with('messages', $messages);
		} else {
			$messages['error'] = Fractal::trans('messages.errors.general');
		}

		return Redirect::to(Fractal::uri('create', true))
			->with('messages', $messages)
			->with('errors', Form::getErrors())
			->withInput();
	}

	public function edit($slug)
	{
		$type = Type::findBySlug($slug);
		if (empty($type))
		{
			// attempt to find by ID and redirect to slugged URL if foun
			$type = Type::find($slug);

			if (!empty($type))
				return Redirect::to(Fractal::uri($type->slug.'/edit', true));
			else
				return Redirect::to(Fractal::uri('pages'))->with('messages', [
					'error' => Fractal::trans('messages.errors.not_found', ['item' => Fractal::transChoiceLower('labels.media_type')])
				]);
		}

		Site::setTitle($type->name.' ('.Fractal::transChoice('labels.media_type').')');
		Site::setHeading(Fractal::trans('labels.update_item', ['item' => Fractal::transChoice('labels.media_type')]).': '.Format::entities($type->name).'');

		Form::setDefaults($type);
		Form::setErrors();

		Fractal::addButton([
			'label' => Fractal::trans('labels.return_to_items_list', ['items' => Fractal::transChoice('labels.media_type', 2)]),
			'icon'  => 'list',
			'uri'   => Fractal::uri('', true),
		]);

		Fractal::addTrailItem(Fractal::trans('labels.update'), Request::url());

		return View::make(Fractal::view('form'))
			->with('update', true)
			->with('id', $type->id);
	}

	public function update($slug)
	{
		$type = Type::findBySlug($slug);
		if (empty($type))
			return Redirect::to(Fractal::uri('', true))->with('messages', [
				'error' => Fractal::trans('messages.errors.not_found', ['item' => Fractal::transChoiceLower('labels.media_type')])
			]);

		$type->setValidationRules();

		$messages = [];
		if (Form::isValid())
		{
			$messages['success'] = Fractal::trans('messages.success.updated', ['item' => Fractal::transChoiceLowerA('labels.media_type')]);

			$type->saveData();

			$slug = $type->slug;

			Activity::log([
				'contentId'   => $type->id,
				'contentType' => 'Type',
				'action'      => 'Update',
				'description' => 'Updated a Media Type',
				'details'     => 'Name: '.$type->name,
				'updated'     => true,
			]);

			return Redirect::to(Fractal::uri('', true))
				->with('messages', $messages);
		} else {
			$messages['error'] = Fractal::trans('messages.errors.general');

			return Redirect::to(Fractal::uri($slug.'/edit', true))
				->with('messages', $messages)
				->with('errors', Form::getErrors())
				->withInput();
		}
	}

	public function destroy($id)
	{
		$type = Type::find($id);
		if (empty($type))
			return $this->error();

		if ($type->items()->count())
			return $this->error();

		Activity::log([
			'contentId'   => $type->id,
			'contentType' => 'Type',
			'action'      => 'Delete',
			'description' => 'Deleted a Media Type',
			'details'     => 'Name: '.$type->name,
		]);

		$type->delete();

		return $this->success(Fractal::trans('messages.success.deleted', ['item' => ''.$type->name.'']));
	}

}


text:
function internet\? {
  (ping -c 3 -t 3 google.com >/dev/null 2>&1 && echo 'yep') || echo 'nope'
}

# Remove the need for bundle exec ... or ./bin/...
# by adding ./bin to path if the current project is trusted

function set_local_bin_path() {
  # Replace any existing local bin paths with our new one
  export PATH="${1:-""}`echo "$PATH"|sed -e 's,[^:]*\.git/[^:]*bin:,,g'`"
}

function add_trusted_local_bin_to_path() {
  if [[ -d "$PWD/.git/safe"  ]]; then
  # We're in a trusted project directory so update our local bin path
  set_local_bin_path "$PWD/.git/safe/../../bin:"
  fi
}

# Make sure add_trusted_local_bin_to_path runs after chruby so we
# prepend the default chruby gem paths
if [[ -n "$ZSH_VERSION"  ]]; then
  if [[ ! "$preexec_functions" == *add_trusted_local_bin_to_path*  ]]; then
  preexec_functions+=("add_trusted_local_bin_to_path")
  fi
fi