text:
{% extends "museum_site/main.html" %}

{% block content %}

Login Error

Too many failed registration attempts!

Your device has been locked out of performing this action for a short period of time.

Server Time: {{now|date:"Y-m-d H:i:s"}}

Unlock Time: {{request.session.reg_expiration|slice:":19"}}

{% endblock %}


text:
"use strict";

import * as m from 'mithril';
import EpgrecModuleModel from './EpgrecModuleModel';
import { KeywordApiModelInterface } from '../Keyword/KeywordApiModel';

interface EnableKeywordEpgrecModuleModelInterface extends EpgrecModuleModel {
    execute(keyword_id: number, status: boolean): void;
    viewUpdate(value: { [key: string]: any; }): void;
}

/**
* epgrec のキーワードの無効化、有効化を行う
*/
class EnableKeywordEpgrecModuleModel extends EpgrecModuleModel implements EnableKeywordEpgrecModuleModelInterface {
    private keywordApiModel: KeywordApiModelInterface;

    constructor(_keywordApiModel: KeywordApiModelInterface) {
        super();
        this.keywordApiModel = _keywordApiModel;
    }

    /**
    * キーワード有効化
    * @param keyword_id keword_id
    * @param status true: 有効化, false: 無効化
    */
    public execute(keyword_id: number, status: boolean): void {
        let query = {
            keyword_id: keyword_id,
            status: status ? 1 : 0
        };

        this.getRequest({
            method: "PUT",
            url: `/api/keyword`,
            data: m.buildQueryString(query)
        },
        null,
        "EnableKeywordEpgrecModuleModel error.");
    }

    public viewUpdate(value: { [key: string]: any; }): void {
        super.viewUpdate(value);
        let keyword_id = Number(value["keyword_id"]);
        let keyword: { [key: string]: any } | null = null;

        this.keywordApiModel.getKeywords().map((data: { [key: string]: any }) => {
            if(data["id"] == keyword_id) {
                keyword = data;
            }
        });
        if(keyword == null) { return; }

        let statusStr = value["enable"] ? "有効化" : "無効化";;
        let snackbarStr = "";
        if(value["status"] == "error") {
            snackbarStr = `キーワード${ statusStr }失敗 ${ keyword["keyword"] }`;
        } else {
            snackbarStr = `キーワード${ statusStr } ${ keyword["keyword"] }`;
        }

        this.keywordApiModel.update();
        this.dialog.close();
        this.snackbar.open(snackbarStr);
    }
}

export { EnableKeywordEpgrecModuleModel, EnableKeywordEpgrecModuleModelInterface };

redpajama_set_name: RedPajamaGithub


text:
import sun.security.krb5.PrincipalName;
import sun.security.krb5.internal.ccache.FileCredentialsCache;

public class kwho {
    public static void main(String[] args) {

        String cache = System.getenv("KRB5CCNAME");
        if (cache == null) {
            System.err.println("Uh-oh, KRB5CCNAME is not set.  Quitting.");
            return;
        }

        // The FileCredentialsCache does not want to see the "FILE:" prefix
        cache = cache.replaceAll("^FILE:", "");

        //assumes credendials cache of type "FILE:"
        FileCredentialsCache fcc = FileCredentialsCache.acquireInstance(null, cache);
        if (fcc == null) {
            return;
        }
        PrincipalName princ = fcc.getPrimaryPrincipal();
        String[] nameStrings = princ.getNameStrings();
        StringBuffer temp = new StringBuffer(nameStrings[0]);
        for (int i=1; i<nameStrings.length; i++) {
            temp.append("/");
            temp.append(nameStrings[i]);
        }
        System.out.println(temp);
    }
}


text:
package com.gikk.streamutil.task;

@FunctionalInterface
public interface GikkTask {
	public void onExecute();
}


text:
package com.intellij.openapi.vfs.newvfs.impl;

import com.intellij.openapi.application.ApplicationAdapter;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.vfs.InvalidVirtualFileAccessException;
import com.intellij.openapi.vfs.newvfs.persistent.FSRecords;
import com.intellij.util.ArrayUtil;
import com.intellij.util.concurrency.AtomicFieldUpdater;
import com.intellij.util.containers.ConcurrentBitSet;
import com.intellij.util.containers.ConcurrentIntObjectMap;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.keyFMap.KeyFMap;
import com.intellij.util.text.CaseInsensitiveStringHashingStrategy;
import gnu.trove.THashSet;
import gnu.trove.TIntHashSet;
import gnu.trove.TObjectHashingStrategy;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.concurrent.atomic.AtomicReferenceArray;

import static com.intellij.openapi.vfs.newvfs.impl.VirtualFileSystemEntry.ALL_FLAGS_MASK;
import static com.intellij.util.ObjectUtils.assertNotNull;

/**
 * The place where all the data is stored for VFS parts loaded into a memory: name-ids, flags, user data, children.
 *
 * The purpose is to avoid holding this data in separate immortal file/directory objects because that involves space overhead, significant
 * when there are hundreds of thousands of files.
 *
 * The data is stored per-id in blocks of {@link #SEGMENT_SIZE}. File ids in one project tend to cluster together,
 * so the overhead for non-loaded id should not be large in most cases.
 *
 * File objects are still created if needed. There might be several objects for the same file, so equals() should be used instead of ==.
 *
 * The lifecycle of a file object is as follows:
 *
 * 1. The file has not been instantiated yet, so {@link #getFileById} returns null.
 *
 * 2. A file is explicitly requested by calling getChildren or findChild on its parent. The parent initializes all the necessary data (in a thread-safe context)
 * and creates the file instance. See {@link #initFile}
 *
 * 3. After that the file is live, an object representing it can be retrieved any time from its parent. File system roots are
 * kept on hard references in {@link com.intellij.openapi.vfs.newvfs.persistent.PersistentFS}
 *
 * 4. If a file is deleted (invalidated), then its data is not needed anymore, and should be removed. But this can only happen after
 * all the listener have been notified about the file deletion and have had their chance to look at the data the last time. See {@link #killInvalidatedFiles()}
 *
 * 5. The file with removed data is marked as "dead" (see {@link #ourDeadMarker}, any access to it will throw {@link com.intellij.openapi.vfs.InvalidVirtualFileAccessException}
 * Dead ids won't be reused in the same session of the IDE.
 *
 * @author peter
 */
public class VfsData {
  private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vfs.newvfs.impl.VfsData");
  private static final int SEGMENT_BITS = 9;
  private static final int SEGMENT_SIZE = 1 << SEGMENT_BITS;
  private static final int OFFSET_MASK = SEGMENT_SIZE - 1;
  private static final Object ourDeadMarker = new String("dead file");

  private static final ConcurrentIntObjectMap<Segment> ourSegments = ContainerUtil.createConcurrentIntObjectMap();
  private static final ConcurrentBitSet ourInvalidatedIds = new ConcurrentBitSet();
  private static TIntHashSet ourDyingIds = new TIntHashSet();
  private static final ConcurrentIntObjectMap<VirtualDirectoryImpl> ourChangedParents = ContainerUtil.createConcurrentIntObjectMap();

  static {
    ApplicationManager.getApplication().addApplicationListener(new ApplicationAdapter() {
      @Override
      public void writeActionFinished(Object action) {
        // after top-level write action is finished, all the deletion listeners should have processed the deleted files
        // and their data is considered safe to remove. From this point on accessing a removed file will result in an exception.
        if (!ApplicationManager.getApplication().isWriteAccessAllowed()) {
          killInvalidatedFiles();
        }
      }
    });
  }

  private static void killInvalidatedFiles() {
    synchronized (ourDeadMarker) {
      if (!ourDyingIds.isEmpty()) {
        for (int id : ourDyingIds.toArray()) {
          assertNotNull(getSegment(id, false)).myObjectArray.set(getOffset(id), ourDeadMarker);
          ourChangedParents.remove(id);
        }
        ourDyingIds = new TIntHashSet();
      }
    }
  }

  @Nullable
  public static VirtualFileSystemEntry getFileById(int id, VirtualDirectoryImpl parent) {
    Segment segment = getSegment(id, false);
    if (segment == null) return null;

    int offset = getOffset(id);
    Object o = segment.myObjectArray.get(offset);
    if (o == null) return null;

    if (o == ourDeadMarker) {
      throw reportDeadFileAccess(new VirtualFileImpl(id, segment, parent));
    }
    final int nameId = segment.getNameId(id);
    if (nameId <= 0) {
      FSRecords.invalidateCaches();
      throw new AssertionError("nameId=" + nameId + "; data=" + o + "; parent=" + parent + "; parent.id=" + parent.getId() + "; db.parent=" + FSRecords.getParent(id));
    }

    return o instanceof DirectoryData ? new VirtualDirectoryImpl(id, segment, (DirectoryData)o, parent, parent.getFileSystem())
                                      : new VirtualFileImpl(id, segment, parent);
  }

  private static InvalidVirtualFileAccessException reportDeadFileAccess(VirtualFileSystemEntry file) {
    return new InvalidVirtualFileAccessException("Accessing dead virtual file: " + file.getUrl());
  }

  private static int getOffset(int id) {
    return id & OFFSET_MASK;
  }

  @Nullable @Contract("_,true->!null")
  public static Segment getSegment(int id, boolean create) {
    int key = id >>> SEGMENT_BITS;
    Segment segment = ourSegments.get(key);
    if (segment != null || !create) return segment;
    return ourSegments.cacheOrGet(key, new Segment());
  }

  public static class FileAlreadyCreatedException extends Exception {
    private FileAlreadyCreatedException(String message) {
      super(message);
    }
  }

  public static void initFile(int id, Segment segment, int nameId, @NotNull Object data) throws FileAlreadyCreatedException {
    assert id > 0;
    int offset = getOffset(id);

    segment.setNameId(id, nameId);

    Object existingData = segment.myObjectArray.get(offset);
    if (existingData != null) {
      FSRecords.invalidateCaches();
      int parent = FSRecords.getParent(id);
      String msg = "File already created: " + nameId + ", data=" + existingData + "; parentId=" + parent;
      if (parent > 0) {
        msg += "; parent.name=" + FSRecords.getName(parent);
        msg += "; parent.children=" + Arrays.toString(FSRecords.listAll(id));
      }
      throw new FileAlreadyCreatedException(msg);
    }
    segment.myObjectArray.set(offset, data);
  }

  static CharSequence getNameByFileId(int id) {
    return FileNameCache.getVFileName(assertNotNull(getSegment(id, false)).getNameId(id));
  }

  static boolean isFileValid(int id) {
    return !ourInvalidatedIds.get(id);
  }

  @Nullable
  static VirtualDirectoryImpl getChangedParent(int id) {
    return ourChangedParents.get(id);
  }

  static void changeParent(int id, VirtualDirectoryImpl parent) {
    ourChangedParents.put(id, parent);
  }

  static void invalidateFile(int id) {
    ourInvalidatedIds.set(id);
    synchronized (ourDeadMarker) {
      ourDyingIds.add(id);
    }
  }

  public static class Segment {
    // user data for files, DirectoryData for folders
    private final AtomicReferenceArray<Object> myObjectArray = new AtomicReferenceArray<Object>(SEGMENT_SIZE);

    // <nameId, flags> pairs, "flags" part containing flags per se and modification stamp
    private final AtomicIntegerArray myIntArray = new AtomicIntegerArray(SEGMENT_SIZE * 2);

    int getNameId(int fileId) {
      return myIntArray.get(getOffset(fileId) * 2);
    }

    void setNameId(int fileId, int nameId) {
      myIntArray.set(getOffset(fileId) * 2, nameId);
    }

    void setUserMap(int fileId, @NotNull KeyFMap map) {
      myObjectArray.set(getOffset(fileId), map);
    }

    KeyFMap getUserMap(VirtualFileSystemEntry file, int id) {
      Object o = myObjectArray.get(getOffset(id));
      if (!(o instanceof KeyFMap)) {
        throw reportDeadFileAccess(file);
      }
      return (KeyFMap)o;
    }

    boolean changeUserMap(int fileId, KeyFMap oldMap, KeyFMap newMap) {
      return myObjectArray.compareAndSet(getOffset(fileId), oldMap, newMap);
    }

    boolean getFlag(int id, int mask) {
      assert (mask & ~ALL_FLAGS_MASK) == 0 : "Unexpected flag";
      return (myIntArray.get(getOffset(id) * 2 + 1) & mask) != 0;
    }

    void setFlag(int id, int mask, boolean value) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("Set flag " + Integer.toHexString(mask) + "=" + value + " for id=" + id);
      }
      assert (mask & ~ALL_FLAGS_MASK) == 0 : "Unexpected flag";
      int offset = getOffset(id) * 2 + 1;
      while (true) {
        int oldInt = myIntArray.get(offset);
        int updated = value ? (oldInt | mask) : (oldInt & ~mask);
        if (myIntArray.compareAndSet(offset, oldInt, updated)) {
          return;
        }
      }
    }

    long getModificationStamp(int id) {
      return myIntArray.get(getOffset(id) * 2 + 1) & ~ALL_FLAGS_MASK;
    }

    void setModificationStamp(int id, long stamp) {
      int offset = getOffset(id) * 2 + 1;
      while (true) {
        int oldInt = myIntArray.get(offset);
        int updated = (oldInt & ALL_FLAGS_MASK) | ((int)stamp & ~ALL_FLAGS_MASK);
        if (myIntArray.compareAndSet(offset, oldInt, updated)) {
          return;
        }
      }
    }

  }

  // non-final field accesses are synchronized on this instance, but this happens in VirtualDirectoryImpl
  public static class DirectoryData {
    private static final AtomicFieldUpdater<DirectoryData, KeyFMap> updater = AtomicFieldUpdater.forFieldOfType(DirectoryData.class, KeyFMap.class);
    @NotNull volatile KeyFMap myUserMap = KeyFMap.EMPTY_MAP;
    @NotNull int[] myChildrenIds = ArrayUtil.EMPTY_INT_ARRAY;
    private Set<String> myAdoptedNames;

    VirtualFileSystemEntry[] getFileChildren(int fileId, VirtualDirectoryImpl parent) {
      assert fileId > 0;
      VirtualFileSystemEntry[] children = new VirtualFileSystemEntry[myChildrenIds.length];
      for (int i = 0; i < myChildrenIds.length; i++) {
        children[i] = assertNotNull(getFileById(myChildrenIds[i], parent));
      }
      return children;
    }

    boolean changeUserMap(KeyFMap oldMap, KeyFMap newMap) {
      return updater.compareAndSet(this, oldMap, newMap);
    }

    boolean isAdoptedName(String name) {
      return myAdoptedNames != null && myAdoptedNames.contains(name);
    }

    void removeAdoptedName(String name) {
      if (myAdoptedNames != null) {
        myAdoptedNames.remove(name);
        if (myAdoptedNames.isEmpty()) {
          myAdoptedNames = null;
        }
      }
    }
    void addAdoptedName(String name, boolean caseSensitive) {
      if (myAdoptedNames == null) {
        //noinspection unchecked
        myAdoptedNames = new THashSet<String>(0, caseSensitive ? TObjectHashingStrategy.CANONICAL : CaseInsensitiveStringHashingStrategy.INSTANCE);
      }
      myAdoptedNames.add(name);
    }

    List<String> getAdoptedNames() {
      return myAdoptedNames == null ? Collections.<String>emptyList() : ContainerUtil.newArrayList(myAdoptedNames);
    }

    void clearAdoptedNames() {
      myAdoptedNames = null;
    }

    @Override
    public String toString() {
      return "DirectoryData{" +
             "myUserMap=" + myUserMap +
             ", myChildrenIds=" + Arrays.toString(myChildrenIds) +
             ", myAdoptedNames=" + myAdoptedNames +
             '}';
    }
  }

}


text:
import sqlite3
import time

conn = sqlite3.connect('log.db')
c = conn.cursor()

# Create table
c.execute("CREATE TABLE if not exists log (log_timestamp DECIMAL(12,8), "
          "log_source text, msg_sequence integer, log_message text, status text)")

for x in range(0, 1000):
    insertquery = "INSERT INTO log (log_timestamp, log_source, msg_sequence, log_message) " \
              "VALUES ({0},'tst source', {1}, 'log message')".format(time.time(), x)
    c.execute(insertquery)

conn.commit()
conn.close()


text:
package ru.job4j.tree;
import org.junit.Test;

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

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
 * Тесты класса Tree.
 */
public class TreeTest {
    /**
     * Тест добавления элеменов и итератора.
     */
    @Test
    public void whenAddElementsToTreeThenRecieveThemInList() {
        Tree<Integer> tree = new Tree<>();
        tree.add(8, 1);
        tree.add(8, 2);
        tree.add(2, 4);
        List<Integer> result = new LinkedList<>();

        for (Integer value : tree) {
            result.add(value);
        }

        List<Integer> expected = new LinkedList<>(Arrays.asList(8, 1, 2, 4));

        assertThat(result, is(expected));
    }

    /**
     * Проверка, является ли созданное дерево двоичным.
     */
    @Test
    public void whenTreeIsBinaryThenCheckReturnsTrue() {
        Tree<Integer> tree = new Tree<>();
        tree.add(8, 5);
        tree.add(8, 2);
        tree.add(5, 4);
        tree.add(5, 10);
        tree.add(2, 22);
        tree.add(2, 23);
        assertThat(tree.isBinary(), is(true));
    }
}


text:
class EditFile
{
	long last_edit;
	string file_name;
public:
	void init(const string& file){
		last_edit = -1;
		file_name = ofFilePath::getAbsolutePath(file, true);
		isEdit();
	}

	bool isEdit(){
		long t_last_Edit = GetLastEdit(file_name.c_str());
		if(t_last_Edit != last_edit){
			last_edit = t_last_Edit;
			return true;
		}
		return false;
	}

	static long GetLastEdit(const char* path_to_file){
		struct tm* clock;
		struct stat attrib;
		stat(path_to_file, &attrib);
#if 0
		time_t rawtime;
		time(&rawtime);
		clock = gmtime(&rawtime);
#endif
		clock = gmtime(&( attrib.st_mtime ));
		return  clock->tm_hour * 10000
			+ clock->tm_min * 100
			+ clock->tm_sec;
	}
};

class ofShader_check :public ofShader
{
	EditFile EditFile_v;
	EditFile EditFile_f;
	ofShader t_shader;
	std::string file_name;
public:
	virtual bool load(string shaderName){
		file_name = shaderName;
		bool ret = ofShader::load(file_name);
		//shaderName + ".vert", shaderName + ".frag");
		EditFile_v.init(file_name + ".vert");
		EditFile_f.init(file_name + ".frag");
		return ret;
	}

	void update(){
		bool isEdit = EditFile_v.isEdit() + EditFile_f.isEdit();
		if(isEdit && isLoaded()){
			t_shader.load(file_name);
			if(t_shader.isLoaded() && t_shader.checkProgramLinkStatus(t_shader.getProgram())){
				t_shader.unload();
				ofLogNotice("ofShader") << "\n" << "##########################\n" << "reload shader";
				ofShader::load(file_name);
			}
		}
	}
};


text:
<?php
namespace BadaBoom\ChainNode\Filter;

use BadaBoom\DataHolder\DataHolderInterface;

class ExceptionClassFilter extends AbstractFilter
{
    /**
     * @var array
     */
    protected $rules = array();

    /**
     * @var bool
     */
    protected $defaultRule = true;

    /**
     * @return void
     */
    public function allowAll()
    {
        $this->defaultRule = true;
    }

    /**
     * @return void
     */
    public function denyAll()
    {
        $this->defaultRule = false;
    }

    /**
     * @param string $exceptionClass
     *
     * @throws InvalidArgumentException if not a exception sub class
     *
     * @return void
     */
    public function allow($exceptionClass)
    {
        $this->setRule($exceptionClass, true);
    }

    /**
     * @param string $exceptionClass
     *
     * @throws InvalidArgumentException if not a exception sub class
     *
     * @return void
     */
    public function deny($exceptionClass)
    {
        $this->setRule($exceptionClass, false);
    }

    /**
     * {@inheritdoc}
     */
    public function shouldContinue(\Exception $exception, DataHolderInterface $data)
    {
        $caughtExceptionClass = get_class($exception);
        while ($caughtExceptionClass) {
            foreach ($this->rules as $exceptionClass => $rule) {
                if ($caughtExceptionClass === $exceptionClass) {
                    return $rule;
                }
            }

            $rc = new \ReflectionClass($caughtExceptionClass);
            if ($prc = $rc->getParentClass()) {
                $caughtExceptionClass = $prc->getName();
            } else {
                $caughtExceptionClass = null;
            }
        }

        return $this->defaultRule;
    }

    /**
     * @param string $exceptionClass
     * @param boolean $rule
     *
     * @throws \InvalidArgumentException
     * @throws \InvalidArgumentException
     *
     * @return void
     */
    protected function setRule($exceptionClass, $rule)
    {
        if (false == \class_exists($exceptionClass)) {
            throw new \InvalidArgumentException('Class not exists: `'.$exceptionClass.'`');
        }

        $rc = new \ReflectionClass($exceptionClass);
        if ('Exception' != $exceptionClass  && false == $rc->isSubclassOf('Exception')) {
            throw new \InvalidArgumentException('Class `'.$exceptionClass.'` is not a subclass of `Exception`');
        }

        $this->rules[$exceptionClass] = $rule;
    }
}


text:
<?php

namespace suver\editor;

use yii\web\AssetBundle;

/**
 * @author Shiyang <dr@shiyang.me>
 */
class EditorAsset extends AssetBundle
{
    public $sourcePath = '@vendor/suver/yii2-editor/assets';
    public $js = [
        'simplemde.min.js'
    ];
    public $css = [
        'simplemde.min.css'
    ];
    public $depends = [
        'yii\web\JqueryAsset',
    ];
}


text:
script_dir="$( cd "$( dirname "$0" )" && pwd )"
prefix="$1"

[[ -z "$service_dir" ]] && service_dir="/etc/systemd/system"
[[ -z "$prefix" ]] && prefix="/usr/local"
mkdir -p "$prefix/bin"

service="$service_dir/bcache-stop.service"
script="$prefix/bin/bcache-stop.sh"

cp "$script_dir/bcache-stop.service" "$service"
chown root:root "$service"
chmod 644 "$service"
sed -i -e "s|__bcache_stop_script__|$script|g" "$service"

cp "$script_dir/bcache-stop.sh" "$script"
chown root:root "$script"
chmod 750 "$script"

systemctl daemon-reload
systemctl stop bcache-stop.service
systemctl disable bcache-stop.service
systemctl enable bcache-stop.service


text:
/*-------------distributions.h------------------------------------------------//
*
* Purpose: to hold all possible distributions for SDL and OGL stuff
*
*-----------------------------------------------------------------------------*/

#ifndef PLOT_H
#define PLOT_H

#include "../include/GL_setup.h"

// test anim functions
void plot_key(Param &par, SDL_Keysym* Keysym, bool is_down);
void plot_fn(Param &par);
void plot_par(Param &par);
void plot_OGL(Param &par);

#endif


text:
Noise is a concise, friendly language for graphic design that translates directly to [SVG 1.1](http://www.w3.org/TR/SVG11/). You can learn more about the language at [its webpage](http://tombrow.com/noise).

This project is an implementation of Noise written in [Haskell](http://haskell.org). It includes an interpreter and a library of modules that you can use to write your own interpreter.

## Installation

First, install the [Haskell Platform](http://www.haskell.org/platform/). Then:

    cabal install noise

To test the installation, invoke `noise`:

    $ noise --help
    Usage: noise [file]
      -h  --help  Print this help text.

## Usage

`noise` reads Noise code from standard input and writes SVG to standard output:

    echo "shape.circle(10,10,10,fill:color.red)" | noise > circle.svg

It can also read from a file:

    echo "shape.rectangle(0,0,10,10,fill:color.blue)" > rectangle.noise
    noise rectangle.noise > rectangle.svg

Use `convert` from the [ImageMagick](http://www.imagemagick.org/) package to write other image formats:

    echo "shape.circle(10,10,10,fill:color.green)" | noise | convert -size 20x20 svg:- circle.png

## Development

I recommend using `cabal-dev` to maintain a sandboxed build environment. If you don't have it already:

    cabal install cabal-dev

Then do this:

    git clone git@github.com:brow/noise.git
    cd noise
    cabal-dev install --only-dependencies --enable-tests
    cabal-dev configure --enable-tests

After performing the above setup once, you can build and test `noise` like so:

    cabal-dev build && cabal-dev test

For a more detailed and colorful test report, try this:

    cabal-dev build && ./dist/build/test/test


text:
typedef NS_ENUM(NSInteger, FLEXNetworkObserverMode) {
    FLEXNetworkObserverModeFirebase = 0,
    FLEXNetworkObserverModeREST,
    FLEXNetworkObserverModeWebsockets,
};

@interface FLEXNetworkMITMViewController ()

@property (nonatomic) BOOL updateInProgress;
@property (nonatomic) BOOL pendingReload;

@property (nonatomic) FLEXNetworkObserverMode mode;

@property (nonatomic, readonly) FLEXMITMDataSource<FLEXNetworkTransaction *> *dataSource;
@property (nonatomic, readonly) FLEXMITMDataSource<FLEXHTTPTransaction *> *HTTPDataSource;
@property (nonatomic, readonly) FLEXMITMDataSource<FLEXWebsocketTransaction *> *websocketDataSource;
@property (nonatomic, readonly) FLEXMITMDataSource<FLEXFirebaseTransaction *> *firebaseDataSource;

@end

@implementation FLEXNetworkMITMViewController

#pragma mark - Lifecycle

- (id)init {
    return [self initWithStyle:UITableViewStylePlain];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.showsSearchBar = YES;
    self.pinSearchBar = YES;
    self.showSearchBarInitially = NO;
    NSMutableArray *scopeTitles = [NSMutableArray arrayWithObject:@"REST"];

    _HTTPDataSource = [FLEXMITMDataSource dataSourceWithProvider:^NSArray * {
        return FLEXNetworkRecorder.defaultRecorder.HTTPTransactions;
    }];

    if (kFirebaseAvailable) {
        _firebaseDataSource = [FLEXMITMDataSource dataSourceWithProvider:^NSArray * {
            return FLEXNetworkRecorder.defaultRecorder.firebaseTransactions;
        }];
        [scopeTitles insertObject:@"Firebase" atIndex:0]; // First space
    }

    if (kWebsocketsAvailable) {
        [scopeTitles addObject:@"Websockets"]; // Last space
        _websocketDataSource = [FLEXMITMDataSource dataSourceWithProvider:^NSArray * {
            return FLEXNetworkRecorder.defaultRecorder.websocketTransactions;
        }];
    }

    // Scopes will only be shown if we have either firebase or websockets available
    self.searchController.searchBar.showsScopeBar = scopeTitles.count > 1;
    self.searchController.searchBar.scopeButtonTitles = scopeTitles;
    self.mode = NSUserDefaults.standardUserDefaults.flex_lastNetworkObserverMode;

    [self addToolbarItems:@[
        [UIBarButtonItem
            flex_itemWithImage:FLEXResources.gearIcon
            target:self
            action:@selector(settingsButtonTapped:)
        ],
        [[UIBarButtonItem
          flex_systemItem:UIBarButtonSystemItemTrash
          target:self
          action:@selector(trashButtonTapped:)
        ] flex_withTintColor:UIColor.redColor]
    ]];

    [self.tableView
        registerClass:FLEXNetworkTransactionCell.class
        forCellReuseIdentifier:FLEXNetworkTransactionCell.reuseID
    ];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight = FLEXNetworkTransactionCell.preferredCellHeight;

    [self registerForNotifications];
    [self updateTransactions:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    // Reload the table if we received updates while not on-screen
    if (self.pendingReload) {
        [self.tableView reloadData];
        self.pendingReload = NO;
    }
}

- (void)dealloc {
    [NSNotificationCenter.defaultCenter removeObserver:self];
}

- (void)registerForNotifications {
    NSDictionary *notifications = @{
        kFLEXNetworkRecorderNewTransactionNotification:
            NSStringFromSelector(@selector(handleNewTransactionRecordedNotification:)),
        kFLEXNetworkRecorderTransactionUpdatedNotification:
            NSStringFromSelector(@selector(handleTransactionUpdatedNotification:)),
        kFLEXNetworkRecorderTransactionsClearedNotification:
            NSStringFromSelector(@selector(handleTransactionsClearedNotification:)),
        kFLEXNetworkObserverEnabledStateChangedNotification:
            NSStringFromSelector(@selector(handleNetworkObserverEnabledStateChangedNotification:)),
    };

    for (NSString *name in notifications.allKeys) {
        [NSNotificationCenter.defaultCenter addObserver:self
            selector:NSSelectorFromString(notifications[name]) name:name object:nil
        ];
    }
}

#pragma mark - Private

#pragma mark Button Actions

- (void)settingsButtonTapped:(UIBarButtonItem *)sender {
    UIViewController *settings = [FLEXNetworkSettingsController new];
    settings.navigationItem.rightBarButtonItem = FLEXBarButtonItemSystem(
        Done, self, @selector(settingsViewControllerDoneTapped:)
    );
    settings.title = @"Network Debugging Settings";

    // This is not a FLEXNavigationController because it is not intended as a new tab
    UIViewController *nav = [[UINavigationController alloc] initWithRootViewController:settings];
    [self presentViewController:nav animated:YES completion:nil];
}

- (void)trashButtonTapped:(UIBarButtonItem *)sender {
    [FLEXAlert makeSheet:^(FLEXAlert *make) {
        BOOL clearAll = !self.dataSource.isFiltered;
        if (!clearAll) {
            make.title(@"Clear Filtered Requests?");
            make.message(@"This will only remove the requests matching your search string on this screen.");
        } else {
            make.title(@"Clear All Recorded Requests?");
            make.message(@"This cannot be undone.");
        }

        make.button(@"Cancel").cancelStyle();
        make.button(@"Clear").destructiveStyle().handler(^(NSArray *strings) {
            if (clearAll) {
                [FLEXNetworkRecorder.defaultRecorder clearRecordedActivity];
            } else {
                FLEXNetworkTransactionKind kind = (FLEXNetworkTransactionKind)self.mode;
                [FLEXNetworkRecorder.defaultRecorder clearRecordedActivity:kind matching:self.searchText];
            }
        });
    } showFrom:self source:sender];
}

- (void)settingsViewControllerDoneTapped:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark Transactions

- (FLEXNetworkObserverMode)mode {
    FLEXNetworkObserverMode mode = self.searchController.searchBar.selectedScopeButtonIndex;
    switch (mode) {
        case FLEXNetworkObserverModeFirebase:
            if (kFirebaseAvailable) {
                return FLEXNetworkObserverModeFirebase;
            }

            return FLEXNetworkObserverModeREST;
        case FLEXNetworkObserverModeREST:
            if (kFirebaseAvailable) {
                return FLEXNetworkObserverModeREST;
            }

            return FLEXNetworkObserverModeWebsockets;
        case FLEXNetworkObserverModeWebsockets:
            return FLEXNetworkObserverModeWebsockets;
    }
}

- (void)setMode:(FLEXNetworkObserverMode)mode {
// The segmentd control will have different appearances based on which APIs
// are available. For example, when only Websockets is available:
//
//               0                           1
// ┌───────────────────────────┬────────────────────────────┐
// │            REST           │         Websockets         │
// └───────────────────────────┴────────────────────────────┘
//
// And when both Firebase and Websockets are available:
//
//          0                  1                  2
// ┌──────────────────┬──────────────────┬──────────────────┐
// │     Firebase     │       REST       │    Websockets    │
// └──────────────────┴──────────────────┴──────────────────┘
//
// As a result, we need to adjust the input mode variable accordingly
// before we actually set it. When we try to set it to Firebase but
// Firebase is not available, we don't do anything, because when Firebase
// is unavailable, FLEXNetworkObserverModeFirebase represents the same index
// as REST would without Firebase. For each of the others, we subtract 1
// from them for every relevant API that is unavailable. So for Websockets,
// if it is unavailable, we subtract 1 and it becomes FLEXNetworkObserverModeREST.
// And if Firebase is also unavailable, we subtract 1 again.

    switch (mode) {
        case FLEXNetworkObserverModeFirebase:
            // Will default to REST if Firebase is unavailable
            break;
        case FLEXNetworkObserverModeREST:
            // Firebase will become REST when Firebase is unavailable
            if (!kFirebaseAvailable) {
                mode--;
            }
            break;
        case FLEXNetworkObserverModeWebsockets:
            // Default to REST if Websockets are unavailable
            if (!kWebsocketsAvailable) {
                mode--;
            }
            // Firebase will become REST when Firebase is unavailable
            if (!kFirebaseAvailable) {
                mode--;
            }
    }

    self.searchController.searchBar.selectedScopeButtonIndex = mode;
}

- (FLEXMITMDataSource<FLEXNetworkTransaction *> *)dataSource {
    switch (self.mode) {
        case FLEXNetworkObserverModeREST:
            return self.HTTPDataSource;
        case FLEXNetworkObserverModeWebsockets:
            return self.websocketDataSource;
        case FLEXNetworkObserverModeFirebase:
            return self.firebaseDataSource;
    }
}

- (void)updateTransactions:(void(^)(void))callback {
    id completion = ^(FLEXMITMDataSource *dataSource) {
        // Update byte count
        [self updateFirstSectionHeader];
        if (callback && dataSource == self.dataSource) callback();
    };

    [self.HTTPDataSource reloadData:completion];
    [self.websocketDataSource reloadData:completion];
    [self.firebaseDataSource reloadData:completion];
}

#pragma mark Header

- (void)updateFirstSectionHeader {
    UIView *view = [self.tableView headerViewForSection:0];
    if ([view isKindOfClass:[UITableViewHeaderFooterView class]]) {
        UITableViewHeaderFooterView *headerView = (UITableViewHeaderFooterView *)view;
        headerView.textLabel.text = [self headerText];
        [headerView setNeedsLayout];
    }
}

- (NSString *)headerText {
    long long bytesReceived = self.dataSource.bytesReceived;
    NSInteger totalRequests = self.dataSource.transactions.count;

    NSString *byteCountText = [NSByteCountFormatter
        stringFromByteCount:bytesReceived countStyle:NSByteCountFormatterCountStyleBinary
    ];
    NSString *requestsText = totalRequests == 1 ? @"Request" : @"Requests";

    // Exclude byte count from Firebase
    if (self.mode == FLEXNetworkObserverModeFirebase) {
        return [NSString stringWithFormat:@"%@ %@",
            @(totalRequests), requestsText
        ];
    }

    return [NSString stringWithFormat:@"%@ %@ (%@ received)",
        @(totalRequests), requestsText, byteCountText
    ];
}

#pragma mark - FLEXGlobalsEntry

+ (NSString *)globalsEntryTitle:(FLEXGlobalsRow)row {
    return @"📡  Network History";
}

+ (FLEXGlobalsEntryRowAction)globalsEntryRowAction:(FLEXGlobalsRow)row {
    return ^(UITableViewController *host) {
        if (FLEXNetworkObserver.isEnabled) {
            [host.navigationController pushViewController:[
                self globalsEntryViewController:row
            ] animated:YES];
        } else {
            [FLEXAlert makeAlert:^(FLEXAlert *make) {
                make.title(@"Network Monitor Disabled");
                make.message(@"You must enable network monitoring to proceed.");

                make.button(@"Turn On").handler(^(NSArray<NSString *> *strings) {
                    FLEXNetworkObserver.enabled = YES;
                    [host.navigationController pushViewController:[
                        self globalsEntryViewController:row
                    ] animated:YES];
                }).cancelStyle();
                make.button(@"Dismiss");
            } showFrom:host];
        }
    };
}

+ (UIViewController *)globalsEntryViewController:(FLEXGlobalsRow)row {
    UIViewController *controller = [self new];
    controller.title = [self globalsEntryTitle:row];
    return controller;
}

#pragma mark - Notification Handlers

- (void)handleNewTransactionRecordedNotification:(NSNotification *)notification {
    [self tryUpdateTransactions];
}

- (void)tryUpdateTransactions {
    // Don't do any view updating if we aren't in the view hierarchy
    if (!self.viewIfLoaded.window) {
        [self updateTransactions:nil];
        self.pendingReload = YES;
        return;
    }

    // Let the previous row insert animation finish before starting a new one to avoid stomping.
    // We'll try calling the method again when the insertion completes,
    // and we properly no-op if there haven't been changes.
    if (self.updateInProgress) {
        return;
    }

    self.updateInProgress = YES;

    // Get state before update
    NSString *currentFilter = self.searchText;
    FLEXNetworkObserverMode currentMode = self.mode;
    NSInteger existingRowCount = self.dataSource.transactions.count;

    [self updateTransactions:^{
        // Compare to state after update
        NSString *newFilter = self.searchText;
        FLEXNetworkObserverMode newMode = self.mode;
        NSInteger newRowCount = self.dataSource.transactions.count;
        NSInteger rowCountDiff = newRowCount - existingRowCount;

        // Abort if the observation mode changed, or if the search field text changed
        if (newMode != currentMode || ![currentFilter isEqualToString:newFilter]) {
            self.updateInProgress = NO;
            return;
        }

        if (rowCountDiff) {
            // Insert animation if we're at the top.
            if (self.tableView.contentOffset.y <= 0.0 && rowCountDiff > 0) {
                [CATransaction begin];

                [CATransaction setCompletionBlock:^{
                    self.updateInProgress = NO;
                    // This isn't an infinite loop, it won't run a third time
                    // if there were no new transactions the second time
                    [self tryUpdateTransactions];
                }];

                NSMutableArray<NSIndexPath *> *indexPathsToReload = [NSMutableArray new];
                for (NSInteger row = 0; row < rowCountDiff; row++) {
                    [indexPathsToReload addObject:[NSIndexPath indexPathForRow:row inSection:0]];
                }

                [self.tableView insertRowsAtIndexPaths:indexPathsToReload withRowAnimation:UITableViewRowAnimationAutomatic];
                [CATransaction commit];
            } else {
                // Maintain the user's position if they've scrolled down.
                CGSize existingContentSize = self.tableView.contentSize;
                [self.tableView reloadData];
                CGFloat contentHeightChange = self.tableView.contentSize.height - existingContentSize.height;
                self.tableView.contentOffset = CGPointMake(self.tableView.contentOffset.x, self.tableView.contentOffset.y + contentHeightChange);
                self.updateInProgress = NO;
            }
        } else {
            self.updateInProgress = NO;
        }
    }];
}

- (void)handleTransactionUpdatedNotification:(NSNotification *)notification {
    [self.HTTPDataSource reloadByteCounts];
    [self.websocketDataSource reloadByteCounts];
    // Don't need to reload Firebase here

    FLEXNetworkTransaction *transaction = notification.userInfo[kFLEXNetworkRecorderUserInfoTransactionKey];

    // Update both the main table view and search table view if needed.
    for (FLEXNetworkTransactionCell *cell in self.tableView.visibleCells) {
        if ([cell.transaction isEqual:transaction]) {
            // Using -[UITableView reloadRowsAtIndexPaths:withRowAnimation:] is overkill here and kicks off a lot of
            // work that can make the table view somewhat unresponsive when lots of updates are streaming in.
            // We just need to tell the cell that it needs to re-layout.
            [cell setNeedsLayout];
            break;
        }
    }

    [self updateFirstSectionHeader];
}

- (void)handleTransactionsClearedNotification:(NSNotification *)notification {
    [self updateTransactions:^{
        [self.tableView reloadData];
    }];
}

- (void)handleNetworkObserverEnabledStateChangedNotification:(NSNotification *)notification {
    // Update the header, which displays a warning when network debugging is disabled
    [self updateFirstSectionHeader];
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.transactions.count;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return [self headerText];
}

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    if ([view isKindOfClass:[UITableViewHeaderFooterView class]]) {
        UITableViewHeaderFooterView *headerView = (UITableViewHeaderFooterView *)view;
        headerView.textLabel.font = [UIFont systemFontOfSize:14.0 weight:UIFontWeightSemibold];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    FLEXNetworkTransactionCell *cell = [tableView
        dequeueReusableCellWithIdentifier:FLEXNetworkTransactionCell.reuseID
        forIndexPath:indexPath
    ];

    cell.transaction = [self transactionAtIndexPath:indexPath];

    // Since we insert from the top, assign background colors bottom up to keep them consistent for each transaction.
    NSInteger totalRows = [tableView numberOfRowsInSection:indexPath.section];
    if ((totalRows - indexPath.row) % 2 == 0) {
        cell.backgroundColor = FLEXColor.secondaryBackgroundColor;
    } else {
        cell.backgroundColor = FLEXColor.primaryBackgroundColor;
    }

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (self.mode) {
        case FLEXNetworkObserverModeREST: {
            FLEXHTTPTransaction *transaction = [self HTTPTransactionAtIndexPath:indexPath];
            UIViewController *details = [FLEXHTTPTransactionDetailController withTransaction:transaction];
            [self.navigationController pushViewController:details animated:YES];
            break;
        }

        case FLEXNetworkObserverModeWebsockets: {
            if (@available(iOS 13.0, *)) { // This check will never fail
                FLEXWebsocketTransaction *transaction = [self websocketTransactionAtIndexPath:indexPath];

                UIViewController *details = nil;
                if (transaction.message.type == NSURLSessionWebSocketMessageTypeData) {
                    details = [FLEXObjectExplorerFactory explorerViewControllerForObject:transaction.message.data];
                } else {
                    details = [[FLEXWebViewController alloc] initWithText:transaction.message.string];
                }

                [self.navigationController pushViewController:details animated:YES];
            }
            break;
        }

        case FLEXNetworkObserverModeFirebase: {
            FLEXFirebaseTransaction *transaction = [self firebaseTransactionAtIndexPath:indexPath];
//            id obj = transaction.documents.count == 1 ? transaction.documents.firstObject : transaction.documents;
            UIViewController *explorer = [FLEXObjectExplorerFactory explorerViewControllerForObject:transaction];
            [self.navigationController pushViewController:explorer animated:YES];
        }
    }
}

#pragma mark - Menu Actions

- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
    return action == @selector(copy:);
}

- (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
    if (action == @selector(copy:)) {
        UIPasteboard.generalPasteboard.string = [self transactionAtIndexPath:indexPath].copyString;
    }
}

- (UIContextMenuConfiguration *)tableView:(UITableView *)tableView contextMenuConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath point:(CGPoint)point __IOS_AVAILABLE(13.0) {

    FLEXNetworkTransaction *transaction = [self transactionAtIndexPath:indexPath];

    return [UIContextMenuConfiguration
        configurationWithIdentifier:nil
        previewProvider:nil
        actionProvider:^UIMenu *(NSArray<UIMenuElement *> *suggestedActions) {
            UIAction *copy = [UIAction
                actionWithTitle:@"Copy URL"
                image:nil
                identifier:nil
                handler:^(__kindof UIAction *action) {
                    UIPasteboard.generalPasteboard.string = transaction.copyString;
                }
            ];

            NSArray *children = @[copy];
            if (self.mode == FLEXNetworkObserverModeREST) {
                NSURLRequest *request = [self HTTPTransactionAtIndexPath:indexPath].request;
                UIAction *denylist = [UIAction
                    actionWithTitle:[NSString stringWithFormat:@"Exclude '%@'", request.URL.host]
                    image:nil
                    identifier:nil
                    handler:^(__kindof UIAction *action) {
                        NSMutableArray *denylist =  FLEXNetworkRecorder.defaultRecorder.hostDenylist;
                        [denylist addObject:request.URL.host];
                        [FLEXNetworkRecorder.defaultRecorder clearExcludedTransactions];
                        [FLEXNetworkRecorder.defaultRecorder synchronizeDenylist];
                        [self tryUpdateTransactions];
                    }
                ];

                children = [children arrayByAddingObject:denylist];
            }
            return [UIMenu
                menuWithTitle:@"" image:nil identifier:nil
                options:UIMenuOptionsDisplayInline
                children:children
            ];
        }
    ];
}

- (FLEXNetworkTransaction *)transactionAtIndexPath:(NSIndexPath *)indexPath {
    return self.dataSource.transactions[indexPath.row];
}

- (FLEXHTTPTransaction *)HTTPTransactionAtIndexPath:(NSIndexPath *)indexPath {
    return self.HTTPDataSource.transactions[indexPath.row];
}

- (FLEXWebsocketTransaction *)websocketTransactionAtIndexPath:(NSIndexPath *)indexPath {
    return self.websocketDataSource.transactions[indexPath.row];
}

- (FLEXFirebaseTransaction *)firebaseTransactionAtIndexPath:(NSIndexPath *)indexPath {
    return self.firebaseDataSource.transactions[indexPath.row];
}

#pragma mark - Search Bar

- (void)updateSearchResults:(NSString *)searchString {
    id callback = ^(FLEXMITMDataSource *dataSource) {
        if (self.dataSource == dataSource) {
            [self.tableView reloadData];
        }
    };

    [self.HTTPDataSource filter:searchString completion:callback];
    [self.websocketDataSource filter:searchString completion:callback];
    [self.firebaseDataSource filter:searchString completion:callback];
}

- (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)newScope {
    [self updateFirstSectionHeader];
    [self.tableView reloadData];

    NSUserDefaults.standardUserDefaults.flex_lastNetworkObserverMode = self.mode;
}

- (void)willDismissSearchController:(UISearchController *)searchController {
    [self.tableView reloadData];
}

@end


text:
/* jshint node: true */
'use strict';
var path = require('path');

module.exports = {
  name: 'ember-ui-pagination',
  blueprintsPath: function() {
    return path.join(__dirname, 'blueprints');
  },
  included: function(app) {
    this._super.included(app);
    // TODO it should be included on demand only
    this.app.import(app.bowerDirectory + '/comma-separated-values/csv.js');
  }
};


text:
package tournamentRunner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Observable;
import java.util.Scanner;
import java.util.Set;

import java.util.TreeSet;
/*
 * The central governing class of the program, holding state information about the brackets, names and competitors
 */
public class TournamentModel extends Observable{
	private Set<Person>[] competitors;		//Array of Sets of Person of added competitors
	private String tournamentName;
	public TournamentModel(int num, int size, String name){		//Number, size of brackets, and tournament name
		int newSize;
		for(newSize=2;newSize<size || newSize<8;newSize*=2);
		int numByes = newSize - size;
		size = newSize;
		competitors = new Set[num];
		for(int i = 0; i < num; i++) competitors[i] = new TreeSet<Person>();
		tournamentName = name;
		Brackets.setBrackets(num,size);
		for(int bracket = 0;bracket<num;bracket++)
			for(int i = 0; i<numByes;i++)
				addPerson(new Bye(),bracket);
		setChanged();
		notifyObservers();
	}
	//Attempt to restore the state to the passed file, and throw an error on failure. The file format is specified in the manual
	public TournamentModel(File file, TournamentView view) throws FileNotFoundException {
		Scanner scan = new Scanner(file);
		int numBrack = Integer.parseInt(scan.nextLine());
		int brackSize = Integer.parseInt(scan.nextLine());
		tournamentName = scan.nextLine();
		Brackets.setBrackets(numBrack, brackSize);
		competitors = new Set[numBrack];
		for(int i = 0; i < numBrack; i++){
			competitors[i]=new TreeSet<Person>();
			Brackets.getBracket(i).setName(scan.nextLine());
			for(int j = 0; j < brackSize-1; j++){
				String matchLine = scan.nextLine();
				String[] data = matchLine.split(",");

				Brackets.getBracket(i).restoreState(data);
				for(int k = 0; k < 2; k++){
					if(!(data[k].equals(Match.DEFAULT_BLANK_NAME + "/" + Match.DEFAULT_BLANK_SCHOOL) || data[k].equals(Match.DEFAULT_WINNER_NAME + "/" + Match.DEFAULT_WINNER_SCHOOL))){		//Add people back to set
						competitors[i].add(new Person(data[k].substring(0, data[k].indexOf('/')), data[k].substring(data[k].indexOf('/')+1)));
					}
				}
			}
		}

		this.addObserver(view);
		scan.close();
		setChanged();
		notifyObservers();
	}
	/*
	 * Attempt to add the given person to the bracket with index [bracket]. If seeded, add to given seed, if unseeded, add from bottom to top
	 * 			If an equal person has already been added, or the bracket is full, return false
	 */
	public boolean addPerson(Person person, int bracket){
		return addPerson(person,bracket,-1);
	}

	public boolean addPerson(Person person, int bracket, int seed){
		if(competitors[bracket].add(person)){
			boolean result;
			if(seed!=-1){
				result = Brackets.getBracket(bracket).addPerson(person,seed);
			}
			else{
				seed = Brackets.getSize();
				while(seed > 0  && !Brackets.getBracket(bracket).addPerson(person,seed--));
				result = seed!=0;
			}
			Brackets.getBracket(bracket).promoteByes(false);
			if(result){
				setChanged();
				notifyObservers();
			}
			return result;
		}
		competitors[bracket].remove(person);
		return false;
	}
	/*
	 * Attempt to advance the given person one match in the bracket.
	 */
	public void advancePerson(Person person, int bracket, String notes, int matchID){
		Brackets.getBracket(bracket).recordWin(person, notes, matchID);
		setChanged();
		notifyObservers();
	}
	/*
	 * Return a Set<Person> of all competitors in the specified bracket
	 */
	public Set<Person> getCompetitors(int bracket){
		return competitors[bracket];
	}
	//Set the tournament name
	public void setName(String name){
		tournamentName = name;
	}
	//Return the tournament name
	public String getName(){
		return tournamentName;
	}
	//Set the name of the bracket specified by [index] to the string [newName]
	public void setBracketName(int index, String newName) {
		Brackets.getBracket(index).setName(newName);
		setChanged();
		notifyObservers();
	}
	//Set the match in [bracket] with id [index] to the data specified
	public void setMatch(Person left, Person right, Person winner, String notes, int bracket, int index){
		Brackets.getBracket(bracket).setMatch(left,right,winner,notes,index);

		setChanged();
		notifyObservers();
	}

	//Attempt to write all state to the file located at currPathway, and throw an error on failure. The file format is specified in the manual
	public void writeFile(File file) throws IOException {
			FileWriter writer = new FileWriter(file);
			writer.write(Brackets.getNum() + "\n" + Brackets.getSize() + "\n" + getName() + "\n");
			for(int i=0;i<Brackets.getNum();i++){
				writer.write(Brackets.getBracket(i).getName() + "\n");
				writer.write(Brackets.getBracket(i).getInfo() + "\n");
			}
			writer.close();
	}

	//Add a roster from a certain school, using the convention specified in the manual
	public void addRoster(String school, File file) throws FileNotFoundException {
		Scanner scan = new Scanner(file);
		int num = Brackets.getNum();
		for(int i = 0; i < num && scan.hasNextLine(); i++){
			String name = scan.nextLine()+",";
			while(name.length()>1){
				addPerson(new Person(name.substring(0,name.indexOf(',')),school),i);
				name = name.substring(name.indexOf(',')+1);
			}
		}
		scan.close();
		setChanged();
		notifyObservers();
	}
}


text:
function [biggest_corr,corr_vec,lags]=lagged_corr(low,low_phase,hi_amp)

signal_length=length(low);

peaks=[find(mod(low_phase,2*pi)/pi>1.99); signal_length];
extrema=peaks(find(diff(peaks)>1));
if length(extrema)>1
    cycle_length=max(diff(extrema));
else
    cycle_length=signal_length;
end

I=1:signal_length;

lags=1:ceil(cycle_length/100):cycle_length;

corr_vec=[];

for i=1:length(lags)
    indices=mod(I+lags(i),signal_length)+1;
    corr_vec(i)=corr(low(indices),hi_amp);
end

max_corr=max(corr_vec);
min_corr=min(corr_vec);
biggest_corr=sign(max_corr-min_corr)*max(abs(max_corr),abs(min_corr));


text:
class AbsoluteValuesOfAmountInExpenses < ActiveRecord::Migration
  def change
    Expense.all.each do |bucket|
      bucket.update!(amount: bucket.amount * -1)
    end
  end
end


text:
package org.etower.common.security;

/**
 * 认证信息错误异常。如:密码错误。
 *
 * @author dawei.li
 *
 */
@SuppressWarnings("serial")
public class BadCredentialsException extends AuthenticationException {

	public BadCredentialsException() {
	}

	public BadCredentialsException(String msg) {
		super(msg);
	}

}


text:
package BotSource.Commands.VoiceCommands;

import DiscordBotCode.CommandFiles.DiscordCommand;
import DiscordBotCode.Extra.FileGetter;
import DiscordBotCode.Main.ChatUtils;
import DiscordBotCode.Main.CommandHandeling.CommandUtils;
import DiscordBotCode.Main.DiscordBotBase;
import com.darkprograms.speech.recognizer.FlacEncoder;
import com.darkprograms.speech.recognizer.GoogleResponse;
import com.darkprograms.speech.recognizer.Recognizer;
import com.darkprograms.speech.synthesiser.SynthesiserV2;
import com.google.code.chatterbotapi.ChatterBot;
import com.google.code.chatterbotapi.ChatterBotFactory;
import com.google.code.chatterbotapi.ChatterBotSession;
import com.google.code.chatterbotapi.ChatterBotType;
import org.apache.commons.lang.ArrayUtils;
import sx.blah.discord.api.events.IListener;
import sx.blah.discord.handle.audio.IAudioReceiver;
import sx.blah.discord.handle.impl.events.guild.voice.user.UserSpeakingEvent;
import sx.blah.discord.handle.impl.events.guild.voice.user.UserVoiceChannelJoinEvent;
import sx.blah.discord.handle.impl.events.guild.voice.user.UserVoiceChannelLeaveEvent;
import sx.blah.discord.handle.obj.*;
import sx.blah.discord.util.RequestBuffer;
import sx.blah.discord.util.audio.AudioPlayer;

import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.TimeUnit;

public class VoiceCommandsSystem
{
	public static final String API_KEY = "AIzaSyBuY4cdCFmMUi5D8nYbKp7ScifF7YYUY9g";

	public static IAudioReceiver receiver;

	public static CopyOnWriteArraySet<Long> talkingUsers = new CopyOnWriteArraySet<>();
	public static ConcurrentHashMap<Long, Long> talkingUsersStart = new ConcurrentHashMap<>();
	public static ConcurrentHashMap<Long, Long> lastTalked = new ConcurrentHashMap<>();

	public static ConcurrentHashMap<Long, CopyOnWriteArrayList<Byte>> talkingData = new ConcurrentHashMap<>();

	public static Recognizer recognizer;
	public static SynthesiserV2 synthesiser;

	//TODO Only check a message once a min or something from each person and only if audio isnt being queued by the bot?
	public static void init(){
		recognizer = new Recognizer(Recognizer.Languages.ENGLISH_US, API_KEY);
		synthesiser = new SynthesiserV2(API_KEY);

		try {
			bot = factory.create(ChatterBotType.CLEVERBOT, "d20ea770d7e367e53281e5eb5af91c48");
		} catch (Exception e) {
			DiscordBotBase.handleException(e);
		}

		session = bot.createSession(Locale.ENGLISH);

		receiver = ( audio, user, sequence, timestamp ) -> {
			if(user != null && user.isBot()){
				return;
			}

			if(user != null && audio != null && audio.length > 0 && talkingUsers.contains(user.getLongID())) {
				List<Byte> arrayList = Arrays.asList(ArrayUtils.toObject(audio));

				if(!talkingData.containsKey(user.getLongID())){
					talkingData.put(user.getLongID(), new CopyOnWriteArrayList<>());
				}

				talkingData.get(user.getLongID()).addAll(arrayList);
			}
		};

		DiscordBotBase.discordClient.getDispatcher().registerListener((IListener<UserSpeakingEvent>) (UserSpeakingEvent event) ->{
			if(event.getGuild() == null || event.getUser() == null || event.getUser() != null && event.getUser().isBot()){
				return;
			}

			if(event.getVoiceChannel().isConnected()) {
				if (event.isSpeaking()) {
					if (!talkingUsers.contains(event.getUser().getLongID())) {
						talkingUsers.add(event.getUser().getLongID());
						talkingUsersStart.put(event.getUser().getLongID(), System.currentTimeMillis());
					}

					talkingData.put(event.getUser().getLongID(), new CopyOnWriteArrayList<>());

				} else {
					if (talkingUsers.contains(event.getUser().getLongID())) {
						talkingUsers.remove(event.getUser().getLongID());
					}

					handleData(event.getUser(), event.getGuild());
					talkingData.remove(event.getUser().getLongID());
					talkingUsersStart.remove(event.getUser().getLongID());
				}
			}
		});

		DiscordBotBase.discordClient.getDispatcher().registerListener((IListener<UserVoiceChannelJoinEvent>) ( UserVoiceChannelJoinEvent event) ->{
			if(event.getGuild() == null || event.getUser() == null || event.getUser() != null && event.getUser().isBot()){
				return;
			}
			if(event.getVoiceChannel().isConnected())
				talkingData.put(event.getUser().getLongID(), new CopyOnWriteArrayList<>());
		});

		DiscordBotBase.discordClient.getDispatcher().registerListener((IListener<UserVoiceChannelLeaveEvent>) ( UserVoiceChannelLeaveEvent event) ->{
			if(event.getGuild() == null || event.getUser() == null){
				return;
			}

			talkingData.remove(event.getUser().getLongID());
		});
	}

	public static AudioFormat PCM = new AudioFormat(48000, 16, 2, true, true);

	public static final Long timeToWait = TimeUnit.MILLISECONDS.convert(30, TimeUnit.SECONDS);

	public static boolean shouldCheck(IUser user, IGuild guild){
		if(!DiscordBotBase.debug){
			return false;
		}

		Long start;
		Long time = -1L;

		if(talkingUsersStart.containsKey(user.getLongID())){
			start = talkingUsersStart.get(user.getLongID());
			time = System.currentTimeMillis() - start;
		}

		if(time != -1){
			if(time < 1000){
				System.out.println("Too short!");
				return false;
			}
		}

		if(AudioPlayer.getAudioPlayerForGuild(guild).getPlaylist().size() > 0){
			return false;
		}

		if(lastTalked.containsKey(user.getLongID())){
			if(System.currentTimeMillis() - lastTalked.get(user.getLongID()) < timeToWait){
				System.out.println("Too early to check!");
//				return false; //TODO This is quite annoying but kinda needed
			}
		}
		return true;
	}

	public static ChatterBotFactory factory = new ChatterBotFactory();
	public static ChatterBot bot = null;
	public static ChatterBotSession session;

	public static void handleData( IUser user, IGuild guild ){
		if(user == null || !talkingData.containsKey(user.getLongID()) || talkingData.get(user.getLongID()) == null){
			return;
		}

		if(!shouldCheck(user, guild)){
			return;
		}

		lastTalked.put(user.getLongID(), System.currentTimeMillis());

		try {
			byte[] bt = ArrayUtils.toPrimitive(talkingData.get(user.getLongID()).toArray(new Byte[]{}));
			AudioInputStream stream = new AudioInputStream(new ByteArrayInputStream(bt), PCM, bt.length);
			FlacEncoder encoder = new FlacEncoder();

			File fe = File.createTempFile("tempFile", ".wav", DiscordBotBase.tempFolder);
			File flacFile = FileGetter.getFile(fe + ".flac");

			AudioSystem.write(stream, AudioFileFormat.Type.WAVE, fe);

			encoder.convertWaveToFlac(fe, flacFile);
			GoogleResponse response = recognizer.getRecognizedDataForFlac(flacFile, 1, (int)PCM.getSampleRate());

			fe.delete();
			flacFile.delete();

			if(response != null && response.getResponse() != null) {
				System.out.println("Google response" +  " (Confi: " + response.getConfidence() + ")" + ": " + response.getResponse());

				ArrayList<Long> mentions = new ArrayList<>();

				String txt = response.getResponse().toLowerCase();

				for(IUser users : guild.getUsers()){
					if(txt.contains(users.getName().toLowerCase()) || txt.toLowerCase().contains(users.getDisplayName(guild).toLowerCase())){
						txt = txt.replace(users.getName().toLowerCase(), users.mention());
						txt = txt.replace(users.getDisplayName(guild).toLowerCase(), users.mention());
						mentions.add(users.getLongID());
					}
				}

				IChannel channel = DiscordBotBase.discordClient.getChannelByID(guild.getLongID());
				IMessage message = ChatUtils.createMessage(user, DiscordBotBase.discordBotBase.getCommandSign() + txt, channel, false, new ArrayList<>(), new ArrayList<>(), new ArrayList<IReaction>(), 0L, mentions);

				DiscordCommand cc = CommandUtils.getDiscordCommand(message.getContent(), channel);

				if(cc != null) {
//					ChatUtils.sendMessage(channel, "Voice command: \"" + DiscordBotBase.discordBotBase.getCommandSign() + txt + "\"");
					RequestBuffer.request(() -> ChatUtils.incomingMessageHandle(message));
				}else if(txt.startsWith("say ")){
					ChatUtils.sendMessage(channel, txt.substring(4));
				}else if(txt.startsWith("text to speech ") || txt.startsWith("text-to-speech ")){
					try {
						InputStream stream1 = synthesiser.getMP3Data(txt.substring(15));
						AudioInputStream stream2 = AudioSystem.getAudioInputStream(stream1);

						AudioPlayer.getAudioPlayerForGuild(guild).queue(stream2);
					}catch (Exception e){}
				}else if(txt.startsWith("ask ")){
					String response1 = session.think(txt.substring(4));

					try {
						InputStream stream1 = synthesiser.getMP3Data(response1);
						AudioInputStream stream2 = AudioSystem.getAudioInputStream(stream1);

						AudioPlayer.getAudioPlayerForGuild(guild).queue(stream2);
					}catch (Exception e){

					}
				}
			}

		} catch (IOException e) {
			System.err.println("IOException: " + e.getMessage());
//			DiscordBotBase.handleException(e);
		} catch (Exception e) {
			DiscordBotBase.handleException(e);
		}
	}

	public static void startReceive( IVoiceChannel channel){
		channel.getGuild().getAudioManager().subscribeReceiver(receiver);
	}

	public static void stopReceive(IVoiceChannel channel){
		channel.getGuild().getAudioManager().unsubscribeReceiver(receiver);
	}

}


text:
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;

namespace NobelLaureates.HydraVM
{
    internal class HydraObservable<T> : IObservable<T>, IObserver<T>
    {
        private IObserver<T> _observer;
        private ConcurrentBag<IDisposable> _disposables = new ConcurrentBag<IDisposable>();

        public IDisposable Subscribe(IObserver<T> observer)
        {
            _observer = observer;

            return new DisposableAction(() => Dispose());
        }

        public void OnNext(T value)
        {
            _observer?.OnNext(value);
        }

        public void OnError(Exception error)
        {
            _observer?.OnError(error);
        }

        public void OnCompleted()
        {
            _observer?.OnCompleted();
        }

        public void AddDisposable(IDisposable disposable)
        {
            _disposables.Add(disposable);
        }

        private void Dispose()
        {
            _observer = null;

            var disposables = _disposables;
            Interlocked.Exchange(ref _disposables, new ConcurrentBag<IDisposable>());
            disposables.ToList().ForEach(x => x.Dispose());
        }
    }
}


text:
from pyxb.bundles.wssplat.raw.wsdl11 import *
import pyxb.bundles.wssplat.raw.wsdl11 as raw_wsdl11

import pyxb.namespace
import pyxb.utils.domutils as domutils
import xml.dom

def ImportRelatedNamespaces ():
    """Import modules for related namespaces so they are available to
    create binding instances from the WSDL sources."""
    try:
        import pyxb.bundles.wssplat.soapbind11
    except ImportError:
        pass
    try:
        import pyxb.bundles.wssplat.soapbind12
    except ImportError:
        pass
    try:
        import pyxb.bundles.wssplat.soap11
    except ImportError:
        pass
    try:
        import pyxb.bundles.wssplat.soap12
    except ImportError:
        pass
    try:
        import pyxb.bundles.wssplat.soapenv
    except ImportError:
        pass
    try:
        import pyxb.bundles.wssplat.httpbind
    except ImportError:
        pass
    try:
        import pyxb.bundles.wssplat.mimebind
    except ImportError:
        pass

class _WSDL_binding_mixin (object):
    """Mix-in class to mark element Python bindings that are expected
    to be wildcard matches in WSDL binding elements."""
    pass

class _WSDL_port_mixin (object):
    """Mix-in class to mark element Python bindings that are expected
    to be wildcard matches in WSDL port elements."""
    pass

class _WSDL_operation_mixin (object):
    """Mix-in class to mark element Python bindings that are expected
    to be wildcard matches in WSDL (binding) operation elements."""
    pass

class tPort (raw_wsdl11.tPort):
    def __getBindingReference (self):
        return self.__bindingReference
    def _setBindingReference (self, binding_reference):
        self.__bindingReference = binding_reference
    __bindingReference = None
    bindingReference = property(__getBindingReference)

    def __getAddressReference (self):
        return self.__addressReference
    def _setAddressReference (self, address_reference):
        self.__addressReference = address_reference
    __addressReference = None
    addressReference = property(__getAddressReference)

raw_wsdl11.tPort._SetSupersedingClass(tPort)

class tBinding (raw_wsdl11.tBinding):
    def __getPortTypeReference (self):
        return self.__portTypeReference
    def setPortTypeReference (self, port_type_reference):
        self.__portTypeReference = port_type_reference
    __portTypeReference = None
    portTypeReference = property(__getPortTypeReference)

    def __getProtocolBinding (self):
        """Return the protocol-specific binding information."""
        return self.__protocolBinding
    def _setProtocolBinding (self, protocol_binding):
        self.__protocolBinding = protocol_binding
    __protocolBinding = None
    protocolBinding = property(__getProtocolBinding)

    def operationMap (self):
        return self.__operationMap
    __operationMap = None

    def __init__ (self, *args, **kw):
        super(tBinding, self).__init__(*args, **kw)
        self.__operationMap = { }
raw_wsdl11.tBinding._SetSupersedingClass(tBinding)

class tPortType (raw_wsdl11.tPortType):
    def operationMap (self):
        return self.__operationMap
    __operationMap = None

    def __init__ (self, *args, **kw):
        super(tPortType, self).__init__(*args, **kw)
        self.__operationMap = { }
raw_wsdl11.tPortType._SetSupersedingClass(tPortType)

class tParam (raw_wsdl11.tParam):
    def __getMessageReference (self):
        return self.__messageReference
    def _setMessageReference (self, message_reference):
        self.__messageReference = message_reference
    __messageReference = None
    messageReference = property(__getMessageReference)
raw_wsdl11.tParam._SetSupersedingClass(tParam)

class tFault (raw_wsdl11.tFault):
    def __getMessageReference (self):
        return self.__messageReference
    def _setMessageReference (self, message_reference):
        self.__messageReference = message_reference
    __messageReference = None
    messageReference = property(__getMessageReference)
raw_wsdl11.tFault._SetSupersedingClass(tFault)

class tPart (raw_wsdl11.tPart):
    def __getElementReference (self):
        return self.__elementReference
    def _setElementReference (self, element_reference):
        self.__elementReference = element_reference
    __elementReference = None
    elementReference = property(__getElementReference)

    def __getTypeReference (self):
        return self.__typeReference
    def _setTypeReference (self, type_reference):
        self.__typeReference = type_reference
    __typeReference = None
    typeReference = property(__getTypeReference)
raw_wsdl11.tPart._SetSupersedingClass(tPart)

class tBindingOperation (raw_wsdl11.tBindingOperation):
    def __getOperationReference (self):
        return self.__operationReference
    def _setOperationReference (self, operation_reference):
        self.__operationReference = operation_reference
    __operationReference = None
    operationReference = property(__getOperationReference)
raw_wsdl11.tBindingOperation._SetSupersedingClass(tBindingOperation)

class tDefinitions (raw_wsdl11.tDefinitions):
    def messageMap (self):
        return self.targetNamespace().messages()

    def namespaceContext (self):
        return self.__namespaceContext
    __namespaceContext = None

    def bindingMap (self):
        return self.__bindingMap
    __bindingMap = None

    def targetNamespace (self):
        return self.namespaceContext().targetNamespace()

    def namespace (self):
        return self.__namespace
    __namespace = None

    def _addToMap (self, map, qname, value):
        map[qname] = value
        (ns, ln) = qname
        if (ns == self.targetNamespace()):
            map[(None, ln)] = value
        elif (ns is None):
            map[(self.targetNamespace(), ln)] = value
        return map

    def schema (self):
        return self.__schema
    __schema = None

    @classmethod
    def _PreFactory_vx (self, args, kw):
        # Import standard bindings.  If we do this, then wildcard
        # binding, port, and operation elements will be recognized and
        # converted into bindings.
        import pyxb.bundles.wssplat.soapbind11
        import pyxb.bundles.wssplat.soapbind12
        import pyxb.bundles.wssplat.httpbind

        # Ensure we have definitions for any externally-referenced
        # things we might need.  @todo: This might have to
        # chronologically precede the import above.
        pyxb.namespace.archive.NamespaceArchive.PreLoadArchives()

        raw_wsdl11.Namespace.validateComponentModel()
        state = ( kw.pop('process_schema', False),
                  kw.pop('generation_uid', None),
                  kw.get('_dom_node') )
        return state

    def _postFactory_vx (self, state):
        (process_schema, generation_uid, dom_node) = state
        assert isinstance(dom_node, xml.dom.Node)
        node_en = pyxb.namespace.ExpandedName(dom_node)
        self.__namespaceContext = pyxb.namespace.resolution.NamespaceContext.GetNodeContext(dom_node)
        self.__buildMaps()
        if process_schema:
            self.__processSchema(generation_uid)
        self.__finalizeReferences()
        return self

    __WSDLCategories = ( 'service', 'port', 'message', 'binding', 'portType' )
    def __buildMaps (self):
        tns = self.namespaceContext().targetNamespace()
        tns.configureCategories(self.__WSDLCategories)
        for m in self.message:
            tns.messages()[m.name] = m
        for pt in self.portType:
            tns.portTypes()[pt.name] = pt
            for op in pt.operation:
                pt.operationMap()[op.name] = op
                params = op.fault[:]
                if op.input is not None:
                    params.append(op.input)
                if op.output is not None:
                    params.append(op.output)
                for p in params:
                    msg_en = m._namespaceContext().interpretQName(p.message)
                    p._setMessageReference(msg_en.message())
        for b in self.binding:
            tns.bindings()[b.name] = b
            port_type_en = b._namespaceContext().interpretQName(b.type)
            b.setPortTypeReference(port_type_en.portType())
            for wc in b.wildcardElements():
                if isinstance(wc, _WSDL_binding_mixin):
                    b._setProtocolBinding(wc)
                    break
            for op in b.operation:
                b.operationMap()[op.name] = op
                for wc in op.wildcardElements():
                    if isinstance(wc, _WSDL_operation_mixin):
                        op._setOperationReference(wc)
                        break
        for s in self.service:
            tns.services()[s.name] = s
            for p in s.port:
                binding_en = p._namespaceContext().interpretQName(p.binding)
                p._setBindingReference(binding_en.binding())
                for wc in p.wildcardElements():
                    if isinstance(wc, _WSDL_port_mixin):
                        p._setAddressReference(wc)
                        break

    def __processSchema (self, generation_uid):
        global pyxb
        import pyxb.xmlschema

        print 'PS %s' % (generation_uid,)
        if self.__schema is not None:
            print 'Already have schema'
            return self.__schema
        for t in self.types:
            for wc in t.wildcardElements():
                if isinstance(wc, xml.dom.Node) and pyxb.namespace.XMLSchema.nodeIsNamed(wc, 'schema'):
                    # Try to load component models for any namespace referenced by this.
                    # Probably shouldn't need to do this except for imported ones.
                    for ns in self.namespaceContext().inScopeNamespaces().itervalues():
                        try:
                            ns.validateComponentModel()
                        except Exception as e:
                            print 'Error validating component model for %s: %s' % (ns.uri(), e)
                    self.__schema = pyxb.xmlschema.schema.CreateFromDOM(wc, namespace_context=self.namespaceContext(), generation_uid=generation_uid)
                elif isinstance(wc, pyxb.xmlschema.schema):
                    self.__schema = wc
                else:
                    print 'No match: %s %s' % (wc.namespaceURI, namespace.localName)
                if self.__schema is not None:
                    return self.__schema
        return None

    def __finalizeReferences (self):
        tns = self.namespaceContext().targetNamespace()
        for m in tns.messages().itervalues():
            for p in m.part:
                if (p.element is not None) and (p.elementReference is None):
                    elt_en = p._namespaceContext().interpretQName(p.element)
                    p._setElementReference(elt_en.elementDeclaration())
                if (p.type is not None) and (p.typeReference is None):
                    type_en = p._namespaceContext().interpretQName(p.type)
                    p._setTypeReference(type_en.typeDefinition())

raw_wsdl11.tDefinitions._SetSupersedingClass(tDefinitions)

pyxb.namespace.resolution.NamespaceContext._AddTargetNamespaceAttribute(raw_wsdl11.Namespace.createExpandedName('definitions'), pyxb.namespace.ExpandedName('targetNamespace'))


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Charts</title>
<link rel="stylesheet" type="text/css" href="../../resources/css/ext-all.css" />

    <link rel="stylesheet" type="text/css" href="../shared/examples.css" />

Stacked Bar Chart Sample

The js is not minified so it is readable. See stacked-bar-chart.js.


text:
FROM ubuntu:trusty

ENV LC_ALL C
ENV DEBIAN_FRONTEND noninteractive
ENV DEBCONF_NONINTERACTIVE_SEEN true

MAINTAINER Jacek Migdal <jacek@migdal.pl>

RUN apt-get install -y -q software-properties-common wget
RUN add-apt-repository -y ppa:chris-lea/node.js
RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add -
RUN echo "deb http://dl.google.com/linux/chrome/deb/ stable main" > /etc/apt/sources.list.d/google.list

RUN apt-get update -y

RUN apt-get install -y -q \
  firefox \
  google-chrome-stable \
  openjdk-7-jre-headless \
  nodejs \
  x11vnc \
  xvfb \
  xfonts-100dpi \
  xfonts-75dpi \
  xfonts-scalable \
  xfonts-cyrillic \
  xdotool \
  psmisc

RUN npm install -g \
  selenium-standalone@2.44.0-1 \
  phantomjs@1.9.13 \
  nightwatch@0.5.35

# Disable the SUID sandbox so that chrome can launch without being in a privileged container
# From: https://github.com/danielfrg/docker-selenium (MIT license)
RUN dpkg-divert --add --rename --divert /opt/google/chrome/google-chrome.real /opt/google/chrome/google-chrome
RUN echo "#!/bin/bash\nexec /opt/google/chrome/google-chrome.real --disable-setuid-sandbox \"\$@\"" > /opt/google/chrome/google-chrome
RUN chmod 755 /opt/google/chrome/google-chrome

RUN groupadd -g 1000 selenium
RUN useradd -d /home/selenium -u 1000 -g 1000 -m selenium
RUN mkdir -p /home/selenium/chrome
RUN chown -R selenium:selenium /home/selenium

RUN groupadd -g 1001 tests
RUN useradd -d /home/tests -u 1001 -g 1001 -m tests
ADD ./config/nightwatch/ /home/tests

ADD ./bin/ /home/root/bin

EXPOSE 4444 5555
ENTRYPOINT ["sh", "/home/root/bin/start.sh"]


text:
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}

module Network.PeyoTLS.HandshakeType (
	Handshake, HandshakeItem(..),
	ClientHello(..), ServerHello(..), SessionId(..),
		CipherSuite(..), KeyExchange(..), BulkEncryption(..),
		CompressionMethod(..),
	ServerKeyExchange(..), ServerKeyExDhe(..), ServerKeyExEcdhe(..),
	CertificateRequest(..), certificateRequest, ClientCertificateType(..),
		SignAlg(..), HashAlg(..),
	ServerHelloDone(..), ClientKeyExchange(..), Epms(..),
	DigitallySigned(..), Finished(..) ) where

import Control.Applicative ((<$>), (<*>))
import Data.Word (Word8, Word16)
import Data.Word.Word24 (Word24)

import qualified Data.ByteString as BS
import qualified Data.X509 as X509
import qualified Codec.Bytable.BigEndian as B
import qualified Crypto.PubKey.DH as DH
import qualified Crypto.Types.PubKey.ECC as ECC

import Network.PeyoTLS.Hello (
	ClientHello(..), ServerHello(..), SessionId(..),
	CipherSuite(..), KeyExchange(..), BulkEncryption(..),
	CompressionMethod(..), HashAlg(..), SignAlg(..) )
import Network.PeyoTLS.Certificate (
	CertificateRequest(..), certificateRequest, ClientCertificateType(..),
	ClientKeyExchange(..), DigitallySigned(..) )

data Handshake
	= HClientHello ClientHello           | HServerHello ServerHello
	| HCertificate X509.CertificateChain | HServerKeyEx BS.ByteString
	| HCertificateReq CertificateRequest | HServerHelloDone
	| HCertVerify DigitallySigned        | HClientKeyEx ClientKeyExchange
	| HFinished BS.ByteString            | HRaw Type BS.ByteString
	deriving Show

instance B.Bytable Handshake where
	decode = B.evalBytableM B.parse; encode = encodeH

instance B.Parsable Handshake where
	parse = do
		t <- B.take 1
		len <- B.take 3
		case t of
			TClientHello -> HClientHello <$> B.take len
			TServerHello -> HServerHello <$> B.take len
			TCertificate -> HCertificate <$> B.take len
			TServerKeyEx -> HServerKeyEx <$> B.take len
			TCertificateReq -> HCertificateReq <$> B.take len
			TServerHelloDone -> let 0 = len in return HServerHelloDone
			TCertVerify -> HCertVerify <$> B.take len
			TClientKeyEx -> HClientKeyEx <$> B.take len
			TFinished -> HFinished <$> B.take len
			_ -> HRaw t <$> B.take len

encodeH :: Handshake -> BS.ByteString
encodeH (HClientHello ch) = encodeH . HRaw TClientHello $ B.encode ch
encodeH (HServerHello sh) = encodeH . HRaw TServerHello $ B.encode sh
encodeH (HCertificate crts) = encodeH . HRaw TCertificate $ B.encode crts
encodeH (HServerKeyEx ske) = encodeH $ HRaw TServerKeyEx ske
encodeH (HCertificateReq cr) = encodeH . HRaw TCertificateReq $ B.encode cr
encodeH HServerHelloDone = encodeH $ HRaw TServerHelloDone ""
encodeH (HCertVerify ds) = encodeH . HRaw TCertVerify $ B.encode ds
encodeH (HClientKeyEx epms) = encodeH . HRaw TClientKeyEx $ B.encode epms
encodeH (HFinished bs) = encodeH $ HRaw TFinished bs
encodeH (HRaw t bs) = B.encode t `BS.append` B.addLen (undefined :: Word24) bs

class HandshakeItem hi where
	fromHandshake :: Handshake -> Maybe hi;
	toHandshake :: hi -> Handshake

instance (HandshakeItem l, HandshakeItem r) => HandshakeItem (Either l r) where
	fromHandshake hs = let
		l = fromHandshake hs
		r = fromHandshake hs in maybe (Right <$> r) (Just . Left) l
	toHandshake (Left l) = toHandshake l
	toHandshake (Right r) = toHandshake r

instance HandshakeItem ClientHello where
	fromHandshake (HClientHello ch) = Just ch
	fromHandshake _ = Nothing
	toHandshake = HClientHello

instance HandshakeItem ServerHello where
	fromHandshake (HServerHello sh) = Just sh
	fromHandshake _ = Nothing
	toHandshake = HServerHello

instance HandshakeItem X509.CertificateChain where
	fromHandshake (HCertificate cc) = Just cc
	fromHandshake _ = Nothing
	toHandshake = HCertificate

data ServerKeyExchange = ServerKeyEx BS.ByteString BS.ByteString
	HashAlg SignAlg BS.ByteString deriving Show

data ServerKeyExDhe = ServerKeyExDhe DH.Params DH.PublicNumber
	HashAlg SignAlg BS.ByteString deriving Show

data ServerKeyExEcdhe = ServerKeyExEcdhe ECC.Curve ECC.Point
	HashAlg SignAlg BS.ByteString deriving Show

instance HandshakeItem ServerKeyExchange where
	fromHandshake = undefined
	toHandshake = HServerKeyEx . B.encode

instance HandshakeItem ServerKeyExDhe where
	toHandshake = HServerKeyEx . B.encode
	fromHandshake (HServerKeyEx ske) =
		either (const Nothing) Just $ B.decode ske
	fromHandshake _ = Nothing

instance HandshakeItem ServerKeyExEcdhe where
	toHandshake = HServerKeyEx . B.encode
	fromHandshake (HServerKeyEx ske) =
		either (const Nothing) Just $ B.decode ske
	fromHandshake _ = Nothing

instance B.Bytable ServerKeyExchange where
	decode = undefined
	encode (ServerKeyEx ps pv ha sa sn) = BS.concat [
		ps, pv, B.encode ha, B.encode sa,
		B.addLen (undefined :: Word16) sn ]

instance B.Bytable ServerKeyExDhe where
	encode (ServerKeyExDhe ps pv ha sa sn) = BS.concat [
		B.encode ps, B.encode pv, B.encode ha, B.encode sa,
		B.addLen (undefined :: Word16) sn ]
	decode = B.evalBytableM B.parse

instance B.Bytable ServerKeyExEcdhe where
	encode (ServerKeyExEcdhe cv pnt ha sa sn) = BS.concat [
		B.encode cv, B.encode pnt, B.encode ha, B.encode sa,
		B.addLen (undefined :: Word16) sn ]
	decode = B.evalBytableM B.parse

instance B.Parsable ServerKeyExDhe where
	parse = do
		ps <- B.parse
		pv <- B.parse
		(ha, sa, sn) <- hasasn
		return $ ServerKeyExDhe ps pv ha sa sn

instance B.Parsable ServerKeyExEcdhe where
	parse = do
		cv <- B.parse
		pnt <- B.parse
		(ha, sa, sn) <- hasasn
		return $ ServerKeyExEcdhe cv pnt ha sa sn

hasasn :: B.BytableM (HashAlg, SignAlg, BS.ByteString)
hasasn = (,,) <$> B.parse <*> B.parse <*> (B.take =<< B.take 2)

instance HandshakeItem CertificateRequest where
	fromHandshake (HCertificateReq cr) = Just cr
	fromHandshake _ = Nothing
	toHandshake = HCertificateReq

instance HandshakeItem ServerHelloDone where
	fromHandshake HServerHelloDone = Just ServerHelloDone
	fromHandshake _ = Nothing
	toHandshake _ = HServerHelloDone

instance HandshakeItem DigitallySigned where
	fromHandshake (HCertVerify ds) = Just ds
	fromHandshake _ = Nothing
	toHandshake = HCertVerify

instance HandshakeItem ClientKeyExchange where
	fromHandshake (HClientKeyEx cke) = Just cke
	fromHandshake _ = Nothing
	toHandshake = HClientKeyEx

data Epms = Epms BS.ByteString

instance HandshakeItem Epms where
	fromHandshake (HClientKeyEx cke) = ckeToEpms cke
	fromHandshake _ = Nothing
	toHandshake = HClientKeyEx . epmsToCke

ckeToEpms :: ClientKeyExchange -> Maybe Epms
ckeToEpms (ClientKeyExchange cke) = case B.runBytableM (B.take =<< B.take 2) cke of
	Right (e, "") -> Just $ Epms e
	_ -> Nothing

epmsToCke :: Epms -> ClientKeyExchange
epmsToCke (Epms epms) = ClientKeyExchange $ B.addLen (undefined :: Word16) epms

data Finished = Finished BS.ByteString deriving (Show, Eq)

instance HandshakeItem Finished where
	fromHandshake (HFinished f) = Just $ Finished f
	fromHandshake _ = Nothing
	toHandshake (Finished f) = HFinished f

data ServerHelloDone = ServerHelloDone deriving Show

data Type
	= TClientHello | TServerHello
	| TCertificate | TServerKeyEx | TCertificateReq | TServerHelloDone
	| TCertVerify  | TClientKeyEx | TFinished       | TRaw Word8
	deriving Show

instance B.Bytable Type where
	decode bs = case BS.unpack bs of
		[1] -> Right TClientHello
		[2] -> Right TServerHello
		[11] -> Right TCertificate
		[12] -> Right TServerKeyEx
		[13] -> Right TCertificateReq
		[14] -> Right TServerHelloDone
		[15] -> Right TCertVerify
		[16] -> Right TClientKeyEx
		[20] -> Right TFinished
		[ht] -> Right $ TRaw ht
		_ -> Left "Handshake.decodeT"
	encode TClientHello = BS.pack [1]
	encode TServerHello = BS.pack [2]
	encode TCertificate = BS.pack [11]
	encode TServerKeyEx = BS.pack [12]
	encode TCertificateReq = BS.pack [13]
	encode TServerHelloDone = BS.pack [14]
	encode TCertVerify = BS.pack [15]
	encode TClientKeyEx = BS.pack [16]
	encode TFinished = BS.pack [20]
	encode (TRaw w) = BS.pack [w]


text:
newparam(:oracle_user) do
  include EasyType

  defaultto 'oracle'

  desc 'The oracle user'

end


text:
/*

74. Search a 2D Matrix

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
For example,

Consider the following matrix:

[
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
Given target = 3, return true.

*/

class Solution {

public:

    // treat matrix as a sorted array
    bool searchMatrix(vector<vector<int>>& matrix, int target) {

        if(matrix.empty())  return false;
        int row = matrix.size(), col = matrix[0].size();
        int left = 0, right = row * col - 1;
        while (left <= right)
        {
            int mid = left + (right - left)/2;
            if (matrix[mid/col][mid%col] == target)
                return true;
            else if( matrix[mid/col][mid%col] > target)
                right = mid -1;
            else
                left = mid + 1;
        }
        return false;
        /* if we do while(left < right)
           we can return matrix[left/col][left%col] == target;
           Same thing but could be easier for book keeping
        */
    }
};

/*  treat as a matrix

    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        if(matrix.empty())  return false;
        int up = 0, down = matrix.size() - 1;
        while (up <= down)
        {
            int row = up + (down - up)/2;
            if (matrix[row][0] == target)
                return true;
            else if (matrix[row][0] > target)
                down = row-1;
            else if (matrix[row].back() < target)
                up = row+1;
            else {
                int left = 0, right = matrix[row].size() - 1;
                while ( left <= right)
                {
                    int col = left + (right - left)/2;
                    if (matrix[row][col] == target)
                        return true;
                    else if (matrix[row][col] > target)
                        right = col - 1;
                    else
                        left = col + 1;
                }
                return false;
            }
        }
        return false;
    }

*/


text:
CFLAGS = `sdl2-config --cflags` -Wall -Wextra -Wfloat-equal -pedantic -std=c99 -lm -O4 -lSDL2_image -lSDL2_mixer
INCS = $(TARGET).h input.h grid.h entity.h base.h bgame.h display.h quizGame.h
TARGET = game
TEST = test
TSOURCES =  quizGame.c grid.c input.c display.c entity.c bgame.c  $(TEST).c
SOURCES =  quizGame.c grid.c input.c display.c entity.c bgame.c  $(TARGET).c
LIBS =  `sdl2-config --libs`
CC = gcc

all: $(TARGET)

$(TARGET): $(SOURCES) $(INCS)
	$(CC) $(SOURCES) -o $(TARGET) $(CFLAGS) $(LIBS)

clean:
	rm -f $(TARGET)

run: all
	./$(TARGET)
test: quizGame.c grid.c input.c display.c entity.c bgame.c  test.c
	gcc quizGame.c grid.c input.c display.c entity.c bgame.c  test.c -o test `sdl2-config --cflags` -Wall -Wextra -Wfloat-equal -pedantic -std=c99 -lm -lSDL2_image -lSDL2_mixer -lSDL2_ttf `sdl2-config --libs`
	./$(TEST)

push:
	git commit -a -m $$(date +%d-%m-%Y/%H:%M)
	git push
pull:
	git pull
debug:
	valgrind ./game
gdebug:
	gdb ./game


text:
var partial = require("ap").partial
    , mongoSetOptions = {
        safe: true
        , upsert: true
    }
    , mongoDeleteOptions = {
        safe: true
    }
    , NOT_REMOVED_ERROR_MESSAGE = "MongoDB could not remove collection"
    , NOT_UPDATED_ERROR_MESSAGE = "MongoDB could not update collection"

module.exports = createMongoStore

function createMongoStore(collection) {
    return {
        _collection: collection
        , get: mongoGet
        , set: mongoSet
        , delete: mongoDelete
    }
}

function mongoGet(key, callback) {
    this._collection.findOne({
        key: key
    }, partial(returnData, callback))
}

function returnData(callback, err, value) {
    if (err) {
        return callback(err)
    }

    if (value === null) {
        return callback(null, null)
    }

    callback(null, value.data)
}

function mongoSet(key, value, callback) {
    this._collection.update({
        key: key
    }, {
        $set: {
            key: key
            , data: value
        }
    }, mongoSetOptions, partial(returnError, callback))
}

function returnError(callback, err, value) {
    if (err) {
        return callback(err)
    }

    if (value === 0) {
        return callback(new Error(NOT_UPDATED_ERROR_MESSAGE))
    }

    callback(null)
}

function mongoDelete(key, callback) {
    this._collection.remove({
        key: key
    }, mongoDeleteOptions, partial(errorIfNotRemoved, callback))
}

function errorIfNotRemoved(callback, err, value) {
    if (err) {
        return callback(err)
    }

    if (value === 0) {
        return callback(new Error(NOT_REMOVED_ERROR_MESSAGE))
    }

    callback(null)
}


text:
class Foo extends BooComponent {}
class Bar extends CustomComponent {}


text:
require "spec_helper"

describe TopicsController do
  describe "routing" do

    it "routes to #index" do
      get("/topics").should route_to("topics#index")
    end

    it "routes to #new" do
      get("/topics/new").should route_to("topics#new")
    end

    it "routes to #show" do
      get("/topics/1").should route_to("topics#show", :id => "1")
    end

    it "routes to #edit" do
      get("/topics/1/edit").should route_to("topics#edit", :id => "1")
    end

    it "routes to #create" do
      post("/topics").should route_to("topics#create")
    end

    it "routes to #update" do
      put("/topics/1").should route_to("topics#update", :id => "1")
    end

    it "routes to #destroy" do
      delete("/topics/1").should route_to("topics#destroy", :id => "1")
    end

  end
end


text:
use driver::session::Session;

use std::vec;
use syntax::ast;
use syntax::attr;
use syntax::codemap::DUMMY_SP;
use syntax::codemap;
use syntax::fold::Folder;
use syntax::fold;
use syntax::opt_vec;
use syntax::util::small_vector::SmallVector;

pub static VERSION: &'static str = "0.10-pre";

pub fn maybe_inject_libstd_ref(sess: Session, crate: ast::Crate)
                               -> ast::Crate {
    if use_std(&crate) {
        inject_libstd_ref(sess, crate)
    } else {
        crate
    }
}

fn use_std(crate: &ast::Crate) -> bool {
    !attr::contains_name(crate.attrs, "no_std")
}

fn use_uv(crate: &ast::Crate) -> bool {
    !attr::contains_name(crate.attrs, "no_uv")
}

fn no_prelude(attrs: &[ast::Attribute]) -> bool {
    attr::contains_name(attrs, "no_implicit_prelude")
}

fn spanned<T>(x: T) -> codemap::Spanned<T> {
    codemap::Spanned {
        node: x,
        span: DUMMY_SP,
    }
}

struct StandardLibraryInjector {
    sess: Session,
}

pub fn with_version(crate: &str) -> Option<(@str, ast::StrStyle)> {
    match option_env!("CFG_DISABLE_INJECT_STD_VERSION") {
        Some("1") => None,
        _ => {
            Some((format!("{}\\#{}", crate, VERSION).to_managed(),
                  ast::CookedStr))
        }
    }
}

impl fold::Folder for StandardLibraryInjector {
    fn fold_crate(&mut self, crate: ast::Crate) -> ast::Crate {
        let mut vis = ~[ast::ViewItem {
            node: ast::ViewItemExternMod(self.sess.ident_of("std"),
                                         with_version("std"),
                                         ast::DUMMY_NODE_ID),
            attrs: ~[],
            vis: ast::Inherited,
            span: DUMMY_SP
        }];

        if use_uv(&crate) && !self.sess.building_library.get() {
            vis.push(ast::ViewItem {
                node: ast::ViewItemExternMod(self.sess.ident_of("green"),
                                             with_version("green"),
                                             ast::DUMMY_NODE_ID),
                attrs: ~[],
                vis: ast::Inherited,
                span: DUMMY_SP
            });
            vis.push(ast::ViewItem {
                node: ast::ViewItemExternMod(self.sess.ident_of("rustuv"),
                                             with_version("rustuv"),
                                             ast::DUMMY_NODE_ID),
                attrs: ~[],
                vis: ast::Inherited,
                span: DUMMY_SP
            });
        }

        vis.push_all(crate.module.view_items);
        let mut new_module = ast::Mod {
            view_items: vis,
            ..crate.module.clone()
        };

        if !no_prelude(crate.attrs) {
            // only add `use std::prelude::*;` if there wasn't a
            // `#[no_implicit_prelude];` at the crate level.
            new_module = self.fold_mod(&new_module);
        }

        ast::Crate {
            module: new_module,
            ..crate
        }
    }

    fn fold_item(&mut self, item: @ast::Item) -> SmallVector<@ast::Item> {
        if !no_prelude(item.attrs) {
            // only recur if there wasn't `#[no_implicit_prelude];`
            // on this item, i.e. this means that the prelude is not
            // implicitly imported though the whole subtree
            fold::noop_fold_item(item, self)
        } else {
            SmallVector::one(item)
        }
    }

    fn fold_mod(&mut self, module: &ast::Mod) -> ast::Mod {
        let prelude_path = ast::Path {
            span: DUMMY_SP,
            global: false,
            segments: ~[
                ast::PathSegment {
                    identifier: self.sess.ident_of("std"),
                    lifetimes: opt_vec::Empty,
                    types: opt_vec::Empty,
                },
                ast::PathSegment {
                    identifier: self.sess.ident_of("prelude"),
                    lifetimes: opt_vec::Empty,
                    types: opt_vec::Empty,
                },
            ],
        };

        let vp = @spanned(ast::ViewPathGlob(prelude_path, ast::DUMMY_NODE_ID));
        let vi2 = ast::ViewItem {
            node: ast::ViewItemUse(~[vp]),
            attrs: ~[],
            vis: ast::Inherited,
            span: DUMMY_SP,
        };

        let vis = vec::append(~[vi2], module.view_items);

        // FIXME #2543: Bad copy.
        let new_module = ast::Mod {
            view_items: vis,
            ..(*module).clone()
        };
        fold::noop_fold_mod(&new_module, self)
    }
}

fn inject_libstd_ref(sess: Session, crate: ast::Crate) -> ast::Crate {
    let mut fold = StandardLibraryInjector {
        sess: sess,
    };
    fold.fold_crate(crate)
}


text:
<!DOCTYPE html>

<meta charset="UTF-8">
<title>Maven Compass test</title>

<link rel="stylesheet" href="css/compiled.css" type="text/css"
	media="screen" />

Maven Compass test

Showing off the TODO class.

Lorem Ipsum is simply dummy text of the printing
		and typesetting industry. Lorem Ipsum has been the industry's standard
		dummy text ever since the 1500s, when an unknown printer took a galley
		of type and scrambled it to make a type specimen book. It has survived
		not only five centuries, but also the leap into electronic
		typesetting, remaining essentially unchanged. It was popularised in
		the 1960s with the release of Letraset sheets containing Lorem Ipsum
		passages, and more recently with desktop publishing software like
		Aldus PageMaker including versions of Lorem Ipsum.