text:
from operator import itemgetter
import math
import numpy as np
import stop_words

class WSD(object):
    """ Object that for word sense disambiguation. """

    def __init__(self, sense_vectors, word_vectors, window=10, method="sim",
            lang="en", max_context_words=3, ignore_case=False, verbose=False):

        self._sense_vectors = sense_vectors
        self._word_vectors = word_vectors
        self._window = window
        self._ctx_method = method
        self._max_context_words = max_context_words
        self._ignore_case = ignore_case
        self._verbose = verbose
        self._stop_words = self._get_stop_words(lang)

    def _get_stop_words(self, lang="en"):
        _stop_words = set()
        for sw in stop_words.get_stop_words(lang):
            _stop_words.add(sw)
            _stop_words.add(sw.title())
            _stop_words.add(sw.upper())

        return _stop_words

    def get_context(self, text, start, end):
        """ Returns a list of words surrounding the target positioned at [start:end] in the text
        target_pos is a string 'start,end'
        window=5 means 5 words on the left + 5 words on the right are returned, if they exist"""

        l, r = text[:start].split(), text[end:].split()

        # it only makes sense to use context for which we have vectors
        l = [ctx for ctx in l if ctx in self._word_vectors.vocab]
        r = [ctx for ctx in r if ctx in self._word_vectors.vocab]
        lr = set(l[-self._window:] + r[:self._window])

        return list(lr.difference(self._stop_words))

    def _logprob(self, cv, vsense):
        """ Returns P(vsense|cv), where vsense is a vector, cv is a context vector """
        return 1.0 / (1.0 + np.exp(-np.dot(cv, vsense)))

    def _cos(self, v1, v2):
        "compute cosine similarity of v1 to v2: (v1 dot v2)/{||v1||*||v2||)"
        sumxx, sumxy, sumyy = 0, 0, 0
        for i in range(len(v1)):
            x = v1[i];
            y = v2[i]
            sumxx += x * x
            sumyy += y * y
            sumxy += x * y
        return sumxy / math.sqrt(sumxx * sumyy)

    def _filter_context(self, context_vectors, senses, n, context):
        """ Returns n most relevant for WSD context vectors """

        if self._ctx_method == 'prob':
            prob_dist_per_cv = [[self._logprob(cv, self._sense_vectors[sense]) for sense, prob in senses] for cv in context_vectors]
        elif self._ctx_method == 'sim':
            prob_dist_per_cv = [[self._cos(cv, self._sense_vectors[sense]) for sense, prob in senses] for cv in context_vectors]
        else:
            raise ValueError("Unknown context handling method '%s'" % self._ctx_method)

        significance = [abs(max(pd) - min(pd)) for pd in prob_dist_per_cv]
        if self._verbose:
            print("Significance scores of context words:")
            print(significance)
        most_significant_cv = sorted(zip(context_vectors, significance, context), key=itemgetter(1), reverse=True)[:n]

        if self._verbose:
            print("Context words:")
            for _, sign, word in most_significant_cv: print("{}\t{:.3f}".format(word, sign))

        context_vectors = [cv for cv, sign, word in most_significant_cv]

        return context_vectors

    def _disambiguate_context(self, context, word, all_cases):
        """ Disambiguates the sense of a word for a given list of context words
            context - a list of context words
            word  - a target word to be disambiguated in the context
            returns a tuple (word#id, scores_for_senses) """

        senses = self._sense_vectors.get_senses(word, self._ignore_case)

        if self._verbose:
            print("Senses of a target word:")
            print(senses)

        if len(senses) == 0:
            return "{}#0".format(word), [1.0]

        context_vectors = [self._word_vectors[c] for c in context]
        if len(context_vectors) == 0:  # means we have no context
            mfs_sense_id, mfs_prob = self._sense_vectors.get_most_probable_sense(word, self._ignore_case)
            return mfs_sense_id, [p for s, p in senses]

        # filter context vectors, if aplicable
        if self._max_context_words >= 0:
            context_vectors = self._filter_context(context_vectors, senses, self._max_context_words, context)

        if self._ctx_method == 'prob':
            avg_context = np.mean(context_vectors, axis=0)
            scores = [self._logprob(avg_context, self._sense_vectors[sense]) for sense, prob in senses]
        else:
            avg_context = np.mean(context_vectors, axis=0)
            scores = [self._cos(avg_context, self._sense_vectors[sense]) for sense, prob in senses]
            if self._verbose:
                print("Sense probabilities:")
                print(scores)

        return senses[np.argmax(scores)][0], scores

    def disambiguate(self, context, word, all_cases=False):
        begin_index = context.find(word)
        end_index = begin_index + len(word)
        return self._disambiguate(context, word, begin_index, end_index, all_cases)

    def _disambiguate(self, text, target, target_start, target_end, all_cases=False):
        """ Disambiguates the sense of a word in given text
            text - a tokenized string ("Obviously , cats are funny .")
            target  - a target word (lemma) to be disambiguated ("cat")
            target_start - start index of target word occurence in text (12)
            target_end - end index of target word occurence in text, considering flexed forms (16) """

        ctx = self.get_context(text, target_start, target_end)
        if self._verbose:
            print("Extracted context words:")
            print(ctx)
        return self._disambiguate_context(ctx, target, all_cases)

redpajama_set_name: RedPajamaGithub


text:
"""Thin wrappers over functions in connection.introspection that don't require
creating a cursor.

This makes test code less verbose and easier to read/write.
"""

from django.db import connection

def table_names(include_views: bool = True):
    """Gets a flat list of tables in the default database."""

    with connection.cursor() as cursor:
        introspection = connection.introspection
        return introspection.table_names(cursor, include_views)

def get_partitioned_table(table_name: str):
    """Gets the definition of a partitioned table in the default database."""

    with connection.cursor() as cursor:
        introspection = connection.introspection
        return introspection.get_partitioned_table(cursor, table_name)

def get_partitions(table_name: str):
    """Gets a list of partitions for the specified partitioned table in the
    default database."""

    with connection.cursor() as cursor:
        introspection = connection.introspection
        return introspection.get_partitions(cursor, table_name)

def get_constraints(table_name: str):
    """Gets a complete list of constraints and indexes for the specified
    table."""

    with connection.cursor() as cursor:
        introspection = connection.introspection
        return introspection.get_constraints(cursor, table_name)


text:
@implementation GKAddressContainerMock

- (id<GKRegionBackend>)regionBackend
{
  return [[GKRegionBackendImpl alloc] init];
}

- (id<GKAddressService>)addressService
{
  GKAddressServiceImpl *service = [[GKAddressServiceImpl alloc]
          initWithRegionBackend:[self regionBackend]];
  service.backend = [self addressBackend];
  service.repository = [self addressRepository];
  return service;
}

- (id<GKAddressBackend>)addressBackend
{
  return [[GKAddressBackendMock alloc] init];
}

- (id<GKAddressRepository>)addressRepository
{
  return [[GKAddressRepositoryMock alloc] init];
}
@end


text:
package reactor.core.publisher;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Stream;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import reactor.core.Exceptions;
import reactor.core.Scannable;
import reactor.core.publisher.Sinks.EmitResult;
import reactor.test.StepVerifier;
import reactor.util.annotation.Nullable;
import reactor.util.context.Context;

import static org.assertj.core.api.Assertions.assertThat;

@Timeout(5)
public class SinkManySerializedTest {

	@Test
	public void shouldNotThrowFromTryEmitNext() {
		SinkManySerialized<Object> sink = new SinkManySerialized<>(
				new EmptyMany<>(),
				Context::empty
		);

		StepVerifier.create(sink.asFlux(), 0)
		            .expectSubscription()
		            .then(() -> {
			            assertThat(sink.tryEmitNext("boom"))
					            .as("emission")
					            .isEqualTo(EmitResult.FAIL_OVERFLOW);
		            })
		            .then(() -> sink.tryEmitComplete().orThrow())
		            .verifyComplete();
	}

	@Test
	public void shouldSignalErrorOnOverflow() {
		SinkManySerialized<Object> sink = new SinkManySerialized<>(
				new EmptyMany<>(),
				Context::empty
		);

		StepVerifier.create(sink.asFlux(), 0)
		            .expectSubscription()
		            .then(() -> sink.emitNext("boom", Sinks.EmitFailureHandler.FAIL_FAST))
		            .verifyErrorMatches(Exceptions::isOverflow);
	}

	@Test
	public void shouldReturnTheEmission() {
		AtomicReference<SinkManySerialized<Object>> sink = new AtomicReference<>();
		sink.set(
				new SinkManySerialized<>(
						new EmptyMany<Object>() {
							@Override
							public EmitResult tryEmitNext(Object o) {
								SinkManySerialized.LOCKED_AT.set(sink.get(), new Thread());
								return super.tryEmitNext(o);
							}
						},
						Context::empty
				)
		);

		assertThat(sink.get().tryEmitNext("boom"))
				.as("emission")
				.isEqualTo(Sinks.EmitResult.FAIL_OVERFLOW);
	}

	@Test
	public void sameThreadRecursion() throws Exception {
		Sinks.Many<Object> sink = Sinks.unsafe().many().multicast().directBestEffort();
		SinkManySerialized<Object> manySink = new SinkManySerialized<>(sink, Context::empty);

		CompletableFuture<Object> muchFuture = sink.asFlux().doOnNext(o -> {
			if ("first".equals(o)) {
				assertThat(manySink.lockedAt).as("lockedAt").isEqualTo(Thread.currentThread());
				assertThat(manySink.tryEmitNext("second")).as("second").isEqualTo(
						EmitResult.OK);
			}
		}).next().toFuture();

		assertThat(manySink.tryEmitNext("first")).as("first").isEqualTo(EmitResult.OK);
		muchFuture.get(5, TimeUnit.SECONDS);
	}

	static class EmptyMany<T> implements Sinks.Many<T> {

		final Sinks.Many<T> delegate = Sinks.unsafe().many().multicast().directBestEffort();

		@Override
		public EmitResult tryEmitNext(T o) {
			return EmitResult.FAIL_OVERFLOW;
		}

		@Override
		public EmitResult tryEmitComplete() {
			return delegate.tryEmitComplete();
		}

		@Override
		public EmitResult tryEmitError(Throwable error) {
			return delegate.tryEmitError(error);
		}

		@Override
		public void emitNext(T t, Sinks.EmitFailureHandler failureHandler) {
			throw new IllegalStateException("Not expected to be called");
		}

		@Override
		public void emitComplete(Sinks.EmitFailureHandler failureHandler) {
			delegate.emitComplete(failureHandler);
		}

		@Override
		public void emitError(Throwable error, Sinks.EmitFailureHandler failureHandler) {
			delegate.emitError(error, failureHandler);
		}

		@Override
		public int currentSubscriberCount() {
			return delegate.currentSubscriberCount();
		}

		@Override
		public Flux<T> asFlux() {
			return delegate.asFlux();
		}

		@Override
		public Stream<? extends Scannable> inners() {
			return delegate.inners();
		}

		@Nullable
		@Override
		public Object scanUnsafe(Attr key) {
			return delegate.scanUnsafe(key);
		}
	}
}


text:
package com.github.kulebin.myfoursquareapp.model;

public class Location {

    private final double latitude;
    private final double longitude;
    private final String address;
    private final int distance;
    private final String city;
    private final String country;

    public Location(final double pLatitude, final double pLongitude, final String pAddress, final int pDistance, final String pCity, final String pCountry) {
        latitude = pLatitude;
        longitude = pLongitude;
        address = pAddress;
        distance = pDistance;
        city = pCity;
        country = pCountry;
    }

    public double getLatitude() {
        return latitude;
    }

    public double getLongitude() {
        return longitude;
    }

    public String getAddress() {
        return address;
    }

    public int getDistance() {
        return distance;
    }

    public String getCity() {
        return city;
    }

    public String getCountry() {
        return country;
    }

    public String getFormattedAddress() {
        if (address != null) {
            String displayAddress = address;

            if (city != null) {
                displayAddress += ", " + city;
            }

            return displayAddress;
        } else {
            return null;
        }
    }
}


text:
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>

#include "perf.h"
#include "../utils/util.h"
#include "../log/log.h"

void ch_perf_open_output(ch_perf_output_e output,const char* filename)
{
    switch(output){
        case ch_perf_output_tofile: {
            ch_perf.fd = open(filename, O_WRONLY | O_APPEND | O_CREAT, S_IRWXU);
            if(ch_perf.fd < 0){
                ch_log_error("Could not open file \"%s\". Error returned is \"%s\", reverting to stderr\n",
                                filename,
                                strerror(errno));
                ch_perf.fd = STDERR_FILENO;
            }
            break;
        }
        case ch_perf_output_tostderr:{
            ch_perf.fd = STDERR_FILENO;
            break;
        }
        case ch_perf_output_tostdout:{
            ch_perf.fd = STDOUT_FILENO;
            break;
        }

    }
}

// CH PERF LOG Binary Format
// 0    "CHPLVVV\0" -- CHPL, followed by version number in XX.X format, followed by a null.
// 8    Number of events in this file 64bit int
// 16   NUmber of events seen 64bit int -- This is in case the perf logger runs out of space
// 24   Record 0 - Cycles Stamp - 64bits RDTSC counter value
// 32   Record 0 - Event ID
// 36   Record 0 - Condition ID
// 40   Record 1 - Cycles Stamp
// ...

static int ch_perf_write_header_binary(){
    //Write out a 7 char head + 1 null char
    int result = write(ch_perf.fd,"CHPERF1", strlen("CHPL010") + 1); //"CH Perf Logger version 1.0
    result += write(ch_perf.fd, &ch_perf.event_index, sizeof(u64));
    result += write(ch_perf.fd, &ch_perf.event_count, sizeof(u64));
    return result;
}

//Simple write out the raw binary event
static int ch_perf_write_event_binary(const ch_perf_event_t* event){
    return write(ch_perf.fd, event, sizeof(ch_perf_event_t));
}

static int ch_perf_write_event_ascii(const ch_perf_event_t* event, ch_bool use_csv)
{
    const char sep = use_csv ? ',' : ' ';
    const char start_stop = event->event_id >= (1ULL<<31) ? 'O' : 'A'; //"stArt", "stOp"
    const uint64_t event_id = event->event_id >= (1ULL<<31) ? event->event_id & ~(1<<31) : event->event_id;
    return dprintf(ch_perf.fd,"%c%c%llu%c%u%c%llu%c%llu\n",  start_stop, sep, event_id, sep, event->cond_id, sep, event->ts, sep, event->data);
}

static int ch_perf_write_header_csv(){
    const char* header = "Event Type, Event ID, Condition ID, TSC, DATA\n";
    return dprintf(ch_perf.fd,header,"%s",header);
}

static int ch_perf_write_event_csv(const ch_perf_event_t* event){
    return ch_perf_write_event_ascii(event,true);
}

static int ch_perf_write_header_ssv(){
    return 0; //No header for ssv!
}

static int ch_perf_write_event_ssv(const ch_perf_event_t* event){
    return ch_perf_write_event_ascii(event, false);
}

int ch_perf_write_header(ch_perf_format_e format, ch_perf_output_e output)
{
    if(output != ch_perf_output_tofile   &&
       output != ch_perf_output_tostderr &&
       output != ch_perf_output_tostdout ){
        ch_log_fatal("Unknown output type. Giving up!");
    }

    switch(format){
        case ch_perf_format_binary:{
            return ch_perf_write_header_binary();
        }
        case ch_perf_format_csv:{
            return ch_perf_write_header_csv();
        }
        case ch_perf_format_ssv:{
            return ch_perf_write_header_ssv();
        }
        default:
            return -1;
    }

}

int ch_perf_write_event(const ch_perf_event_t* event, ch_perf_format_e format, ch_perf_output_e output)
{
    //This is here in case we add non fd style outputs
    if(output != ch_perf_output_tofile   &&
       output != ch_perf_output_tostderr &&
       output != ch_perf_output_tostdout ){
        ch_log_fatal("Unknown output type. Giving up!");
    }

    switch(format){
        case ch_perf_format_binary:{
            return ch_perf_write_event_binary(event);
        }
        case ch_perf_format_csv:{
            return ch_perf_write_event_csv(event);
        }
        case ch_perf_format_ssv:{
            return ch_perf_write_event_ssv(event);
        }
        default:
            return -1;
    }
}

//Write one last word and close
void ch_perf_close(ch_perf_output_e output)
{
    //This is here in case we add non fd style outputs
    if(output != ch_perf_output_tofile   &&
       output != ch_perf_output_tostderr &&
       output != ch_perf_output_tostdout ){
        ch_log_fatal("Unknown output type. Giving up!");
    }

    close(ch_perf.fd);
}

void ch_perf_finish_(ch_perf_output_e output, ch_perf_format_e format, const char* filename){
    if(ch_perf.event_index && ch_perf.max_events){
        ch_perf_open_output(output,filename);
        ch_perf_write_header(format,output);

        DBG("Outputting %lli items\n", MIN(ch_perf.event_index, ch_perf.max_events));
        for(u64 i = 0; i < MIN(ch_perf.event_index, ch_perf.max_events); i++ ){
            const ch_perf_event_t* event = ch_perf.events + i;
            ch_perf_write_event(event,format,output);
        }

        if(ch_perf.fd != STDERR_FILENO &&
           ch_perf.fd != STDOUT_FILENO ){
            ch_perf_close(output);
        }
    }
    else{
        ERR("Nothing to output\n");
    }

}

inline u64 ch_perf_get_watch_ticks()
{
    return ch_perf.timer_stop - ch_perf.timer_start;
}

inline u64 ch_perf_get_tsc_sample()
{
    return ch_perf.tsc;
}


text:
FOUNDATION_EXPORT double Pods_CBJsonModel_TestsVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_CBJsonModel_TestsVersionString[];


text:
package com.lmj.demo2;

public class Mum {

}


text:
prod-build: Dockerfile
	sudo docker build -t gcr.io/symbolic-datum-552/gobuilder-arm64-aws:latest .

# run on arm64 instance
prod-push: prod-build
	sudo docker login -u oauth2accesstoken https://gcr.io
	sudo docker push gcr.io/symbolic-datum-552/gobuilder-arm64-aws:latest
	sudo rm /root/.docker/config.json

env-var-check:
ifndef AWS_ACCESS_KEY_ID
	$(error AWS_ACCESS_KEY_ID env var is not set)
endif

ifndef AWS_SECRET_ACCESS_KEY
	$(error AWS_SECRET_ACCESS_KEY env var is not set)
endif

create-aws-image: env-var-check
	packer build packer_image_aws_arm64.json


text:
/*
Navicat MySQL Data Transfer

Source Server         : csci321
Source Server Version : 50617
Source Host           : 127.0.0.1:3306
Source Database       : conforg_db

Target Server Type    : MYSQL
Target Server Version : 50617
File Encoding         : 65001

Date: 2015-01-25 12:32:16
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for permissions
-- ----------------------------
DROP TABLE IF EXISTS `permissions`;
CREATE TABLE `permissions` (
  `permission_Id` int(11) NOT NULL,
  `permission_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `permission_remarks` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`permission_Id`),
  UNIQUE KEY `permission_name_UNIQUE` (`permission_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


text:
package org.onosproject.isis.io.isispacket.tlv;

import com.google.common.base.MoreObjects;
import com.google.common.primitives.Bytes;
import org.jboss.netty.buffer.ChannelBuffer;
import org.onosproject.isis.io.util.IsisUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Representation of area address TLV.
 */
public class AreaAddressTlv extends TlvHeader implements IsisTlv {

    private List<String> areaAddress = new ArrayList<>();

    /**
     * Creates an instance of area address TLV.
     *
     * @param tlvHeader TLV header
     */
    public AreaAddressTlv(TlvHeader tlvHeader) {
        this.setTlvType(tlvHeader.tlvType());
        this.setTlvLength(tlvHeader.tlvLength());
    }

    /**
     * Adds the area address to the area address TLV.
     *
     * @param areaAddress area address
     */
    public void addAddress(String areaAddress) {
        this.areaAddress.add(areaAddress);
    }

    /**
     * Returns the area address of area address TLV.
     *
     * @return areaAddress area address
     */
    public List<String> areaAddress() {
        return this.areaAddress;
    }

    @Override
    public void readFrom(ChannelBuffer channelBuffer) {
        while (channelBuffer.readableBytes() > 0) {
            int addressLength = channelBuffer.readByte();
            byte[] addressbytes = new byte[addressLength];
            channelBuffer.readBytes(addressbytes, 0, addressLength);
            String areaAddress = IsisUtil.areaAddress(addressbytes);
            this.areaAddress.add(areaAddress);
        }
    }

    @Override
    public byte[] asBytes() {
        byte[] bytes = null;
        byte[] tlvHeader = tlvHeaderAsByteArray();
        byte[] tlvBody = tlvBodyAsBytes();
        tlvHeader[1] = (byte) tlvBody.length;
        bytes = Bytes.concat(tlvHeader, tlvBody);
        return bytes;
    }

    /**
     * Returns TLV body of area address TLV.
     *
     * @return byteArray TLV body of area address TLV
     */
    private byte[] tlvBodyAsBytes() {
        List<Byte> bytes = new ArrayList<>();
        for (String areaAddress : this.areaAddress) {
            bytes.add((byte) (areaAddress.length() / 2));
            bytes.addAll(IsisUtil.areaAddressToBytes(areaAddress));
        }
        return Bytes.toArray(bytes);
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(getClass())
                .omitNullValues()
                .add("areaAddress", areaAddress)
                .toString();
    }
}


text:
from __future__ import unicode_literals

AUTHOR = 'Trustees of the Natural History Museum, London'
SITENAME = 'Inselect'

SITEURL = 'https://naturalhistorymuseum.github.io/inselect'

PATH = 'content'

TIMEZONE = 'Europe/London'

DEFAULT_LANG = 'en'

# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEED_ATOM = None
AUTHOR_FEED_RSS = None

CC_LICENSE = 'CC-BY'

# Blogroll
LINKS = (
    ('SYNTHESYS', 'http://www.synthesys.info/'),
)

# Social widget
SOCIAL = (
    ('github', 'https://github.com/NaturalHistoryMuseum/inselect/'),
)

MENUITEMS = (
    ('Gallery', '{siteurl}/pages/gallery.html'.format(siteurl=SITEURL)),
    ('Install', '{siteurl}/pages/install.html'.format(siteurl=SITEURL)),
    ('Documentation', '{siteurl}/pages/documentation.html'.format(siteurl=SITEURL)),
    ('News', '{siteurl}/category/news.html'.format(siteurl=SITEURL)),
    ('Newsletter', '{siteurl}/pages/newsletter.html'.format(siteurl=SITEURL)),
    ('FAQs', '{siteurl}/pages/faqs.html'.format(siteurl=SITEURL)),
)

DEFAULT_PAGINATION = False

DISPLAY_CATEGORIES_ON_MENU = False
DISPLAY_PAGES_ON_MENU = False

GITHUB_URL = "https://github.com/NaturalHistoryMuseum/inselect"

THEME = "../../pelican-themes/pelican-bootstrap3"
BOOTSTRAP_THEME = 'readable'

FAVICON = 'images/favicon.png'
SITELOGO = 'images/inselect128.png'
SITELOGO_SIZE = 32

PYGMENTS_STYLE = 'friendly'

SHOW_COPYRIGHT = False
CC_ATTR_MARKUP = True


text:
/*jshint unused:false*/

/* === preFormatCSS ===
 * preformats the css to ensure we won't run into and problems in our parsing
 * removes comments (actually would be anough to remove/replace {} chars.. TODO
 * replaces } char inside content: '' properties.
 */

function cssPreformatter (css){
  //remove comments from css (including multi-line coments)
  css = css.replace(/\/\*[\s\S]*?\*\//g, '');

  //replace Windows \r\n with \n,
  //otherwise final output might get converted into /r/r/n
  css = css.replace(/\r\n/gm, '\n');

  //we also need to replace eventual close curly bracket characters inside content: '' property declarations, replace them with their ASCI code equivalent
  //\7d (same as:   '\' + '}'.charCodeAt(0).toString(16)  );

  var m,
    regexP = /(content\s*:\s*['"][^'"]*)}([^'"]*['"])/gm,
    matchedData = [];

  //for each content: '' rule that contains at least one end bracket ('}')
  while ((m = regexP.exec(css)) !== null) {
    //we need to replace ALL end brackets in the rule
    //we can't do it in here, because it will mess up ongoing exec, store data and do after

    //unshift - add to beginning of array - we need to remove rules in reverse order,
    //otherwise indeces will become incorrect.
    matchedData.unshift({
      start: m.index,
      end: m.index + m[0].length,
      replaceStr: m[0].replace(/\}/gm, '\\7d')
    });
  }

  for (var i = 0; i < matchedData.length; i++) {
    var item = matchedData[0];
    css = css.substring(0, item.start) + item.replaceStr + css.substring(item.end);
  }

  return css;
};

if(typeof module !== 'undefined') {
    module.exports = cssPreformatter;
}


text:
command += rw_command (OIIO_TESTSUITE_IMAGEDIR, "caspian.tif")

# cramps.tif	800x607 8-bit b&w (packbits) "cramps poster"
#    This tests 1-bit images, and packbits compression
# cramps-tile.tif	256x256 tiled version of cramps.tif (no compression)
#    Tests tiled images (especially tiled 1-bit) -- compare it to cramps
# dscf0013.tif  640x480 YCbCr digital camera image which lacks Reference
#       Black/White values. Contains EXIF SubIFD. No compression.
command += rw_command (OIIO_TESTSUITE_IMAGEDIR, "cramps.tif")
command += rw_command (OIIO_TESTSUITE_IMAGEDIR, "cramps-tile.tif")
command += diff_command (OIIO_TESTSUITE_IMAGEDIR + "/cramps-tile.tif",
                         OIIO_TESTSUITE_IMAGEDIR + "/cramps.tif")
command += rw_command (OIIO_TESTSUITE_IMAGEDIR, "dscf0013.tif")

# fax2d.tif	1728x1082 1-bit b&w (G3/2D) facsimile
# FIXME - we read the pixel data fine, but we fail to recognize that
#   differing XResolution and YResolution imply a non-square pixel
#   aspect ratio, and iv fails to display it well for this reason.
command += rw_command (OIIO_TESTSUITE_IMAGEDIR, "fax2d.tif")

# g3test.tif	TIFF equivalent of g3test.g3 created by fax2tiff
command += rw_command (OIIO_TESTSUITE_IMAGEDIR, "g3test.tif")
# FIXME - same aspect ratio issue as fax2d.tif

# jello.tif	256x192 8-bit RGB (packbits palette) Paul Heckbert "jello"
command += rw_command (OIIO_TESTSUITE_IMAGEDIR, "jello.tif")

# ladoga.tif	158x118 16-bit unsigned, single band, deflate
# NOTE -- I have no idea if we read this correctly.  Neither ImageMagick
#    nor OSX preview display a meaningful image.

# off_l16.tif	333x225 8-bit CIE LogL (SGILog) office from Greg Larson
# off_luv24.tif	333x225 8-bit CIE LogLuv (SGILog24) office from " "
# off_luv32.tif	333x225	8-bit CIE LogLuv (SGILog) office from " "
command += rw_command (OIIO_TESTSUITE_IMAGEDIR, "off_l16.tif")
command += rw_command (OIIO_TESTSUITE_IMAGEDIR, "off_luv24.tif")
command += rw_command (OIIO_TESTSUITE_IMAGEDIR, "off_luv32.tif")

# pc260001.tif	640x480 8-bit RGB digital camera image. Contains EXIF SubIFD.
# 		No compression.
# FIXME? - we don't seem to recognize additional Exif data that's in the
#    'Maker Note', which includes GainControl
command += rw_command (OIIO_TESTSUITE_IMAGEDIR, "pc260001.tif")

# quad-lzw.tif	512x384 8-bit RGB (lzw) "quadric surfaces"
# quad-tile.tif	512x384 tiled version of quad-lzw.tif (lzw)
# quad-jpeg.tif 512x384 8-bit YCbCr (jpeg) version of quad-lzw.tif

# FIXME - temporarily disable quad-lzw.tif to address a regression in
# libtiff 4.0.8. Re-enable these tests after libtiff is patched.
#command += rw_command (OIIO_TESTSUITE_IMAGEDIR, "quad-lzw.tif")
command += rw_command (OIIO_TESTSUITE_IMAGEDIR, "quad-tile.tif")
#command += diff_command (OIIO_TESTSUITE_IMAGEDIR + "/quad-tile.tif",
#                         OIIO_TESTSUITE_IMAGEDIR + "/quad-lzw.tif")
command += rw_command (OIIO_TESTSUITE_IMAGEDIR, "quad-jpeg.tif",
                       extraargs="-compression zip")

# strike.tif	256x200 8-bit RGBA (lzw) "bowling pins" from Pixar
command += rw_command (OIIO_TESTSUITE_IMAGEDIR, "strike.tif")

# text.tif	1512x359 4-bit b&w (thunderscan) am-express credit card
#  FIXME -- we don't get this right

# ycbcr-cat.tif	250x325 8-bit YCbCr (lzw) "kitty" created by rgb2ycbcr
command += rw_command (OIIO_TESTSUITE_IMAGEDIR, "ycbcr-cat.tif")

# smallliz.tif	160x160 8-bit YCbCr (OLD jpeg) lizard from HP**
command += rw_command (OIIO_TESTSUITE_IMAGEDIR, "smallliz.tif", 0)
# zackthecat.tif 234x213 8-bit YCbCr (OLD jpeg) tiled "ZackTheCat" from NeXT**
#   considered a deprecated format, not supported by libtiff
command += rw_command (OIIO_TESTSUITE_IMAGEDIR, "zackthecat.tif", 0)

# oxford.tif	601x81 8-bit RGB (lzw) screendump off oxford
command += rw_command (OIIO_TESTSUITE_IMAGEDIR, "oxford.tif", 0)

# The other images are from Hewlett Packard and exemplify the use of the
# HalftoneHints tag (in their words):
# The images are all the same subject, and should all appear the same
# after rendering.  Each of the images is slightly different as outlined
# by the following table:
#
#   FileName	   ToneRange  HalftoneHints
# jim___cg.tif      	A	    Y
# jim___dg.tif      	B	    N
# jim___gg.tif      	B	    Y
#
# NOTE -- OIIO appears to read this fine, but I'm really not sure how to
#    judge if it's "correct"


text:
package by.vshkl.pxlsrt.mvp.presenter;

import android.net.Uri;

import com.arellomobile.mvp.InjectViewState;
import com.arellomobile.mvp.MvpPresenter;

import java.io.FileOutputStream;

import by.vshkl.pxlsrt.core.utils.TempStorageUtils;
import by.vshkl.pxlsrt.mvp.model.CameraFacing;
import by.vshkl.pxlsrt.mvp.view.CameraView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

@InjectViewState
public class CameraPresenter extends MvpPresenter<CameraView> {

    private Disposable disposable;
    private CameraFacing cameraFacing = CameraFacing.REAR;

    public void onDestroy() {
        if (disposable != null) {
            disposable.dispose();
        }
    }

    public void setCameraFacing(CameraFacing cameraFacing) {
        this.cameraFacing = cameraFacing;
    }

    public void checkPermissions() {
        getViewState().checkPermissions();
    }

    public void showPermissionsRationale() {
        getViewState().showPermissionsRationale();
    }

    public void requestPermissions() {
        getViewState().requestPermissions();
    }

    public void showPermissionsMessage(int resId) {
        getViewState().showPermissionMessage(resId);
    }

    public void showAppSystemSettings() {
        getViewState().showAppSystemSettings();
    }

    public void toggleGrid() {
        getViewState().toggleGrid();
    }

    public void toggleCamera() {
        getViewState().toggleCamera();
    }

    public void toggleFlash() {
        getViewState().toggleFlash();
    }

    public void openGallery() {
        getViewState().openGallery();
    }

    public void openCropper(String image) {
        getViewState().openCropper(image);
    }

    public void takePicture() {
        getViewState().takePicture();
    }

    public void openSettings() {
        getViewState().openSettings();
    }

    public void processPicture(FileOutputStream fos, String filename, byte[] data, int resolution) {
        disposable = TempStorageUtils.saveTempBitmap(fos, filename, data, resolution, cameraFacing)
                .subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String string) throws Exception {
                        getViewState().sendPictureData(string);
                    }
                });
    }

    public void processPicture(FileOutputStream fos, String filename, Uri uri) {
        disposable = TempStorageUtils.saveTempBitmap(fos, filename, uri)
                .subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String string) throws Exception {
                        getViewState().sendPictureData(string);
                    }
                });
    }

    public void cleanTempFiles() {
        getViewState().cleanTempFiles();
    }
}


text:
package de.opitzconsulting.orcas.diff;

import de.opitzconsulting.origOrcasDsl.Model;

public abstract class LoadIst
{
  public abstract Model loadModel( boolean pWithSequeneceMayValueSelect );
}


text:
#import "../Pinning/ssl_pin_verifier.h"

#if __has_feature(modules)
@import Foundation;
#else
#import <Foundation/Foundation.h>
#endif

/**
 `TSKSimpleBackgroundReporter` is a class for uploading pin failure reports using the background transfer service.

 */
@interface TSKBackgroundReporter : NSObject <NSURLSessionTaskDelegate>

///---------------------
/// @name Initialization
///---------------------

/**
 Initializes a background reporter.

 @param shouldRateLimitReports Prevent identical pin failure reports from being sent more than once per day.
 @param sharedContainerIdentifier The container identifier for an app extension. This must be set in order
    for reports to be sent from an app extension. See
    https://developer.apple.com/documentation/foundation/nsurlsessionconfiguration/1409450-sharedcontaineridentifier
 @exception NSException Thrown when the App does not have a bundle ID, meaning we're running in unit tests where the background transfer service can't be used.

 */
- (nonnull instancetype)initAndRateLimitReports:(BOOL)shouldRateLimitReports
                      sharedContainerIdentifier:(nullable NSString *)sharedContainerIdentifier;

///----------------------
/// @name Sending Reports
///----------------------

/**
 Send a pin validation failure report; each argument is described section 3. of RFC 7469.
 */
- (void)pinValidationFailedForHostname:(nonnull NSString *)serverHostname
                                  port:(nullable NSNumber *)serverPort
                      certificateChain:(nonnull NSArray *)certificateChain
                         notedHostname:(nonnull NSString *)notedHostname
                            reportURIs:(nonnull NSArray<NSURL *> *)reportURIs
                     includeSubdomains:(BOOL)includeSubdomains
                        enforcePinning:(BOOL)enforcePinning
                             knownPins:(nonnull NSSet<NSData *> *)knownPins
                      validationResult:(TSKTrustEvaluationResult)validationResult
                        expirationDate:(nullable NSDate *)knownPinsExpirationDate;

- (void)URLSession:(nonnull NSURLSession *)session task:(nonnull NSURLSessionTask *)task didCompleteWithError:(nullable NSError *)error;

@end


text:
package net.risenphoenix.ipcheck.commands.block;

import net.risenphoenix.commons.Plugin;
import net.risenphoenix.commons.commands.Command;
import net.risenphoenix.commons.commands.CommandType;
import net.risenphoenix.commons.configuration.ConfigurationManager;
import net.risenphoenix.ipcheck.IPCheck;
import org.bukkit.command.CommandSender;
import org.bukkit.permissions.Permission;

public class CmdUnblock extends Command {

    private BlockManager cBlockManager;
    private ConfigurationManager CM;

    public CmdUnblock(final Plugin plugin, String[] callArgs, CommandType type) {
        super(plugin, callArgs, type);

        IPCheck ipc = IPCheck.getInstance();
        this.cBlockManager = ipc.getBlockManager();
        this.CM = ipc.getConfigurationManager();

        setName(getLocalString("CMD_UNBLOCK"));
        setHelp(getLocalString("HELP_UNBLOCK"));
        setSyntax("ipc unblock <COUNTRY_ID | help>");
        setPermissions(new Permission[]{
                new Permission("ipcheck.use"),
                new Permission("ipcheck.unblock")
        });
    }

    @Override
    public void onExecute(CommandSender sender, String[] args) {
        if (cBlockManager != null) {

            // If GeoIP Services have been disabled, return
            if (!cBlockManager.getStatus()) {
                sendPlayerMessage(sender, getLocalString("GEOIP_DISABLED"));
                return;
            }

            // If the player requests help, return a link to Bukkit.
            if (args[1].equalsIgnoreCase("help")) {
                sendPlayerMessage(sender, getLocalString("BLOCK_HELP"));
                return;
            }

            boolean result = cBlockManager.unblockCountry(args[1]);
            String msg = ((result) ? getLocalString("UNBLOCK_SUC") :
                    getLocalString("UNBLOCK_ERR"));

            // Determine if the blacklist is off. If so, warn the player.
            String addon = "";
            if (result) {
                addon = (CM.getBoolean("use-country-blacklist")) ? "" : " " +
                        getLocalString("BLACK_LIST_OFF");
            }

            // Respond to Sender
            sendPlayerMessage(sender, msg + addon);
        } else {
            // Warn Sender that this command is not functioning
            sendPlayerMessage(sender, getLocalString("BLOCK_CMD_DISABLE"));
        }
    }

}


text:
{{ "Set status"|t }}

 {{ "Enabled"|t }}

 {{ "Disabled"|t }}


text:
namespace arc {

class ControlCameraAppDelegate {
 public:
  virtual ~ControlCameraAppDelegate() = default;

  // Launches the camera app from Android camera intent with the intent
  // information as url |queries|. |task_id| represents the id of the caller
  // task in ARC.
  virtual void LaunchCameraApp(const std::string& queries, int32_t task_id) = 0;

  // Closes the camera app.
  virtual void CloseCameraApp() = 0;

  // Checks if Chrome Camera App is enabled.
  virtual bool IsCameraAppEnabled() = 0;
};

}  // namespace arc

#endif  // COMPONENTS_ARC_INTENT_HELPER_CONTROL_CAMERA_APP_DELEGATE_H_


text:
#ifndef __COMMON_H
#define __COMMON_H

#define SAMPLE_16BIT	0x01
#define SAMPLE_UNSIGNED	0x02
#define SAMPLE_LOOP		0x04
#define SAMPLE_PINGPONG	0x08
#define SAMPLE_REVERSE	0x10
#define SAMPLE_SUSTAIN	0x20
#define SAMPLE_ENVELOPE	0x40
#define SAMPLE_CLAMPED	0x80

#ifdef DEBUG_SAMPLES
#define SAMPLE_CONVERT_DEBUG(dx) printf("\r%s\n",dx)
#else
#define SAMPLE_CONVERT_DEBUG(dx)
#endif

extern unsigned short int _WM_SampleRate;

struct _sample {
	unsigned int data_length;
	unsigned int loop_start;
	unsigned int loop_end;
	unsigned int loop_size;
	unsigned char loop_fraction;
	unsigned short rate;
	unsigned int freq_low;
	unsigned int freq_high;
	unsigned int freq_root;
	unsigned char modes;
	signed int env_rate[7];
	signed int env_target[7];
	unsigned int inc_div;
	signed short *data;
	struct _sample *next;
};

struct _env {
	float time;
	float level;
	unsigned char set;
};

struct _patch {
	unsigned short patchid;
	unsigned char loaded;
	char *filename;
	signed short int amp;
	unsigned char keep;
	unsigned char remove;
	struct _env env[6];
	unsigned char note;
	unsigned long int inuse_count;
	struct _sample *first_sample;
	struct _patch *next;
};

/* Set our global defines here */
#ifndef M_PI
#define M_PI  3.14159265358979323846
#endif

#ifndef M_LN2
#define M_LN2 0.69314718055994530942
#endif

#endif /* __COMMON_H */


text:
package com.hazelcast.nio.tcp;

import com.hazelcast.internal.networking.ChannelInboundHandler;
import com.hazelcast.internal.networking.nio.ChannelInboundHandlerWithCounters;
import com.hazelcast.nio.Packet;
import com.hazelcast.spi.impl.PacketHandler;

import java.nio.ByteBuffer;

/**
 * The {@link ChannelInboundHandler} for member to member communication.
 *
 * It reads as many packets from the src ByteBuffer as possible, and each of the Packets is send to the {@link PacketHandler}.
 *
 * @see PacketHandler
 * @see MemberChannelOutboundHandler
 */
public class MemberChannelInboundHandler extends ChannelInboundHandlerWithCounters {

    protected final TcpIpConnection connection;
    protected Packet packet;

    private final PacketHandler handler;

    public MemberChannelInboundHandler(TcpIpConnection connection, PacketHandler handler) {
        this.connection = connection;
        this.handler = handler;
    }

    @Override
    public void onRead(ByteBuffer src) throws Exception {
        while (src.hasRemaining()) {
            if (packet == null) {
                packet = new Packet();
            }
            boolean complete = packet.readFrom(src);
            if (complete) {
                handlePacket(packet);
                packet = null;
            } else {
                break;
            }
        }
    }

    protected void handlePacket(Packet packet) throws Exception {
        if (packet.isFlagRaised(Packet.FLAG_URGENT)) {
            priorityPacketsRead.inc();
        } else {
            normalPacketsRead.inc();
        }

        packet.setConn(connection);

        handler.handle(packet);
    }
}


text:
from tsadm.jobq.cmd import TSAdmJobQCmd

MYSQL_CMD_MAP = {
    'mysql.sync': TSAdmJobQCmd,
}


text:
using System;
using System.Runtime.InteropServices;

namespace SharpVk
{
    /// <summary>
    ///
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    public partial struct PhysicalDeviceShaderSubgroupExtendedTypesFeatures
    {
        /// <summary>
        ///
        /// </summary>
        public bool ShaderSubgroupExtendedTypes
        {
            get;
            set;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="pointer">
        /// </param>
        internal unsafe void MarshalTo(SharpVk.Interop.PhysicalDeviceShaderSubgroupExtendedTypesFeatures* pointer)
        {
            pointer->SType = StructureType.PhysicalDeviceShaderSubgroupExtendedTypesFeaturesVersion;
            pointer->Next = null;
            pointer->ShaderSubgroupExtendedTypes = this.ShaderSubgroupExtendedTypes;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="pointer">
        /// </param>
        internal static unsafe PhysicalDeviceShaderSubgroupExtendedTypesFeatures MarshalFrom(SharpVk.Interop.PhysicalDeviceShaderSubgroupExtendedTypesFeatures* pointer)
        {
            PhysicalDeviceShaderSubgroupExtendedTypesFeatures result = default(PhysicalDeviceShaderSubgroupExtendedTypesFeatures);
            result.ShaderSubgroupExtendedTypes = pointer->ShaderSubgroupExtendedTypes;
            return result;
        }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>alternative Standard Libary: std::internal::rb_tree_key_wrapper< TKey > Template-Strukturreferenz</title>
<link href="../../tabs.css" rel="stylesheet" type="text/css"/>

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

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

alternative Standard Libary
    0.29.8

Öffentliche Methoden |
Öffentliche Attribute |
Aufstellung aller Elemente

std::internal::rb_tree_key_wrapper< TKey > Template-Strukturreferenz

#include <rb_tree.hpp>

Öffentliche Methoden

 	rb_tree_key_wrapper ()

 	rb_tree_key_wrapper (const TKey &key_)

const TKey & 	get_key () const

Öffentliche Attribute

TKey 	key

Ausführliche Beschreibung

template<typename TKey>

struct std::internal::rb_tree_key_wrapper< TKey >

Beschreibung der Konstruktoren und Destruktoren

◆ rb_tree_key_wrapper() [1/2]

template<typename TKey >

          std::internal::rb_tree_key_wrapper< TKey >::rb_tree_key_wrapper
          (
          	)

inline

   54 {}

◆ rb_tree_key_wrapper() [2/2]

template<typename TKey >

          std::internal::rb_tree_key_wrapper< TKey >::rb_tree_key_wrapper
          (
          const TKey &
          key_	)

inline

   55 : key(key_) {}

std::internal::rb_tree_key_wrapper::key

TKey key

Definition: rb_tree.hpp:53

Dokumentation der Elementfunktionen

◆ get_key()

template<typename TKey >

          const TKey& std::internal::rb_tree_key_wrapper< TKey >::get_key
          (
          	)
           const

inline

   56 { return key; }

std::internal::rb_tree_key_wrapper::key

TKey key

Definition: rb_tree.hpp:53

Dokumentation der Datenelemente

◆ key

template<typename TKey >

          TKey std::internal::rb_tree_key_wrapper< TKey >::key

Die Dokumentation für diese Struktur wurde erzeugt aufgrund der Datei:

include/rb_tree.hpp

std

internal

rb_tree_key_wrapper

Erzeugt von

     1.8.13


text:
var GameRoom = (function () {
  'use strict';

  var timeStart, timeEnd, gameEndCheck;

  /**
   * Gets a query parameter by name
   * @param  {[type]} name [description]
   * @return {[type]}      [description]
   */
  function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
      results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  }

  //get guid
  var socket = io(location.origin + '/game-' + getParameterByName('id'));

  socket.on('connect', function () {
    GameRoom.connected();
    socket.emit('ready', socket.id, getParameterByName(email));
  });

  socket.on('play', function (cards, role) {
    if (role === 'pawn') {
      // update role display
      $('#role').html('Pawn');
      // display cards
      for (var i = 0; i < cards.length; i++) {
        var card = cards[i];
        //update display
        var cardDisplay = cardTemplate.replace(/\{\{id\}\}/g, i);
        cardDisplay = cardDisplay.replace(/\{\{img\}\}/g, card.cardPicture);
        cardDisplay = cardDisplay.replace(/\{\{label\}\}/g, card.cardLabel);
        $('#player-cards').append(cardDisplay);
      }
      //start game!
      timeStart = new Date();
      timeEnd = new Date(timeStart.getSeconds() + 30);
      gameEndCheck = setInterval(function () {
        if (new Date() > timeEnd) {
          GameRoom.pawnChoose(); // no answer
          window.location = '/profile';
          socket.emit('endGame', timeStart, timeEnd);
        }
      }, 1000);
    }
  });

  return {
    connected: function () {
      //TODO Update game room display
      alert('Connected');
    }
  };
})();

/*jshint multistr: true */
var cardTemplate = '
\
        \
          \
            \
        \

';

var modalTemplate = '\

\

\
      \

{{label}}
\

\

\
        <button href="#!" class="btn modal-action btn-flat" onclick="GameRoom.select({{id}})">Select</button>\
        <button href="#!" class="btn modal-action modal-close btn-flat">Close</button>\

\

';


text:
package com.example.restservicedemo;

import static com.jayway.restassured.RestAssured.given;

import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;

import org.dbunit.Assertion;
import org.dbunit.IDatabaseTester;
import org.dbunit.JdbcDatabaseTester;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.ITable;
import org.dbunit.dataset.filter.DefaultColumnFilter;
import org.dbunit.dataset.xml.FlatXmlDataSetBuilder;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import com.example.restservicedemo.domain.Person;
import com.jayway.restassured.RestAssured;

public class PersonServiceRESTDBTest {

	private static IDatabaseConnection connection ;
	private static IDatabaseTester databaseTester;

	@BeforeClass
	public static void setUp() throws Exception{
		RestAssured.baseURI = "http://localhost";
		RestAssured.port = 8080;
		RestAssured.basePath = "/restservicedemo";

		Connection jdbcConnection;
		jdbcConnection = DriverManager.getConnection(
				"jdbc:hsqldb:hsql://localhost/workdb", "sa", "");
		connection = new DatabaseConnection(jdbcConnection);

		databaseTester = new JdbcDatabaseTester(
				"org.hsqldb.jdbcDriver", "jdbc:hsqldb:hsql://localhost/workdb", "sa", "");
		IDataSet dataSet = new FlatXmlDataSetBuilder().build(
				new FileInputStream(new File("src/test/resources/fullData.xml")));
		databaseTester.setDataSet(dataSet);
		databaseTester.onSetup();
	}

	@Test
	public void addPeson() throws Exception{

		Person aPerson = new Person("Ziutek", 2010);
		given().contentType("application/json; charset=UTF-16").body(aPerson)
				.when().post("/persons/").then().assertThat().statusCode(201);

		IDataSet dbDataSet = connection.createDataSet();
		ITable actualTable = dbDataSet.getTable("PERSON");
		ITable filteredTable = DefaultColumnFilter.excludedColumnsTable
				(actualTable, new String[]{"ID"});

		IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(
				new File("src/test/resources/personData.xml"));
		ITable expectedTable = expectedDataSet.getTable("PERSON");

		Assertion.assertEquals(expectedTable, filteredTable);
	}

	@AfterClass
	public static void tearDown() throws Exception{
		databaseTester.onTearDown();
	}

}


text:
//@ts-check
"use strict";

const { $, cd } = require("@itchio/bob");
const { readdirSync } = require("fs");
const { resolve } = require("path");

/**
 * @param {string[]} _args
 */
async function main(_args) {
  /** @type {string} */
  let channelSuffix;
  /** @type {string} */
  let userVersion;

  if (process.env.CI_COMMIT_TAG) {
    // pushing a stable version
    channelSuffix = "";
    // v9.0.0 => 9.0.0
    userVersion = process.env.CI_COMMIT_TAG.replace(/^v/, "");
  } else if (process.env.CI_COMMIT_REF_NAME === "master") {
    // pushing head
    channelSuffix = "-head";
    userVersion = process.env.CI_COMMIT_SHA || "";
  } else {
    // pushing a branch that isn't master
    console.log(
      `Not pushing non-master branch ${process.env.CI_COMMIT_REF_NAME}`
    );
    return;
  }

  // upload to itch.io
  let toolsDir = resolve(process.cwd(), "tools");
  $(`mkdir -p ${toolsDir}`);
  await cd(toolsDir, async () => {
    let butlerUrl = `https://broth.itch.ovh/butler/linux-amd64-head/LATEST/.zip`;
    $(`curl -sLo butler.zip "${butlerUrl}"`);
    $(`unzip butler.zip`);
  });

  $(`${toolsDir}/butler -V`);

  for (let target of ["itch-setup", "kitch-setup"]) {
    await cd(`artifacts/${target}`, async () => {
      let variants = readdirSync(".");
      for (let variant of variants) {
        let channelName = `${variant}${channelSuffix}`;
        let itchTarget = `fasterthanlime/${target}:${channelName}`;
        let butlerArgs = [
          "push",
          `--userversion "${userVersion}"`,
          `"${variant}"`,
          `"${itchTarget}"`,
        ];
        $(`${toolsDir}/butler ${butlerArgs.join(" ")}`);
      }
    });
  }
}

main(process.argv.slice(2));


text:
<?php

class MercadoPago_Core_Model_Source_Country
    extends Mage_Payment_Model_Method_Abstract
{
    public function toOptionArray()
    {
        $country = array();
        $country[] = array('value' => "mla", 'label' => Mage::helper('mercadopago')->__("Argentina"), 'code' => 'AR');
        $country[] = array('value' => "mlb", 'label' => Mage::helper('mercadopago')->__("Brasil"), 'code' => 'BR');
        $country[] = array('value' => "mco", 'label' => Mage::helper('mercadopago')->__("Colombia"), 'code' => 'CO');
        $country[] = array('value' => "mlm", 'label' => Mage::helper('mercadopago')->__("Mexico"), 'code' => 'MX');
        $country[] = array('value' => "mlc", 'label' => Mage::helper('mercadopago')->__("Chile"), 'code' => 'CL');
        $country[] = array('value' => "mlv", 'label' => Mage::helper('mercadopago')->__("Venezuela"), 'code' => 'VE');

        //force order by key
        ksort($country);

        return $country;
    }

    public function getCodeByValue($value)
    {
        $countries = $this->toOptionArray();
        foreach ($countries as $country) {
            if ($value == $country['value']) {
                return $country['code'];
            }
        }
        return '';
    }
}


text:
require 'spec_helper'
require 'support/transliteration_file'

require 'unit/transliteration/ordinary'
require 'unit/transliteration/ukrainian'

describe "Transliteration rule for" do
  transliterations_dir = File.join('rails', 'transliteration')

  let(:file) do
    filename = Dir[File.join(transliterations_dir, "#{example.metadata[:locale]}*")].first
    RailsI18n::Spec::TransliterationFile.make(filename)
  end

  let(:rule) do
    file.traverse_path(example.metadata[:locale], :i18n, :transliterate, :rule)
  end

  def t(string)
    file.transliterate(string)
  end

  describe "Bulgarian", :locale => :bg do
    it_behaves_like "an ordinary transliteration rule"

    it "works" do
      t('съществуват').should == 'sashtestvuvat'
    end
  end

  describe "Russian", :locale => :ru do
    it_behaves_like "an ordinary transliteration rule"

    # https://github.com/yaroslav/russian/blob/master/spec/transliteration_spec.rb
    it "should transliterate properly" do
      t("Это просто некий текст").should == "Eto prosto nekiy tekst"
      t("щ").should == "sch"
      t("стансы").should == "stansy"
      t("упущение").should == "upuschenie"
      t("ш").should == "sh"
      t("Ш").should == "SH"
      t("ц").should == "ts"
    end

    it "should properly transliterate mixed russian-english strings" do
      t("Это кусок строки русских букв v peremeshku s latinizey i амперсандом (pozor!) & something").should ==
        "Eto kusok stroki russkih bukv v peremeshku s latinizey i ampersandom (pozor!) & something"
    end

    it "should properly transliterate mixed case chars in a string" do
      t("НЕВЕРОЯТНОЕ УПУЩЕНИЕ").should == "NEVEROYATNOE UPUSCHENIE"
      t("Невероятное Упущение").should == "Neveroyatnoe Upuschenie"
      t("Шерстяной Заяц").should == "Sherstyanoy Zayats"
      t("Н.П. Шерстяков").should == "N.P. Sherstyakov"
      t("ШАРОВАРЫ").should == "SHAROVARY"
    end

    it "should work for multi-char substrings" do
      t("38 воробьёв").should == "38 vorobiev"
      t("Вася Воробьёв").should == "Vasya Vorobiev"
      t("Алябьев").should == "Alyabiev"
      t("АЛЯБЬЕВ").should == "ALYABIEV"
    end
  end

  describe "Ukrainian", :locale => :uk do
    it_behaves_like "an ordinary transliteration rule"

    include_examples "Ukrainian transliteration"
  end
end


text:
:man_page: mongoc_collection_create_index_with_opts

mongoc_collection_create_index_with_opts()
==========================================

Synopsis
--------

.. code-block:: c

  bool
  mongoc_collection_create_index_with_opts (mongoc_collection_t *collection,
                                            const bson_t *keys,
                                            const mongoc_index_opt_t *index_opts,
                                            const bson_t *command_opts,
                                            bson_t *reply,
                                            bson_error_t *error);

Deprecated
----------

This function is deprecated and should not be used in new code. See :doc:`create-indexes`.

Parameters
----------

* ``collection``: A :symbol:`mongoc_collection_t`.
* ``keys``: A :symbol:`bson:bson_t`.
* ``index_opts``: A mongoc_index_opt_t.
* ``command_opts``: A :symbol:`bson:bson_t` with extra options, such as writeConcern or collation, or ``NULL``.
* ``reply``: An optional location for a :symbol:`bson:bson_t` which will store the server's reply.
* ``error``: An optional location for a :symbol:`bson_error_t <errors>` or ``NULL``.

Description
-----------

This function will request the creation of a new index.

This function will use the ``createIndexes`` command if available on the MongoDB server. If not, it will fallback to inserting into ``system.indexes`` for compatibility with MongoDB <= 2.4.

The server's reply is stored in ``reply``.

If no write concern is provided in ``command_opts``, the collection's write concern is used.

See :symbol:`mongoc_index_opt_t` for options on creating indexes.

Errors
------

Errors are propagated via the ``error`` parameter.

Returns
-------

Returns ``true`` if successful. Returns ``false`` and sets ``error`` if there are invalid arguments or a server or network error.

``reply`` is always initialized and must be destroyed with :symbol:`bson:bson_destroy()`. If the server is running an obsolete version of MongoDB then ``reply`` may be empty, though it will still be initialized.


text:
using System;
using engenious;

namespace OctoAwesome
{
    /// <summary>
    /// Helper class for collision detection with blocks.
    /// </summary>
    public static class Block
    {
        /// <summary>
        /// Intersection check between collision boxes of a block and a ray.
        /// </summary>
        /// <param name="collisionBoxes">The collision boxes of the block, local to the block.</param>
        /// <param name="boxPosition">The position of the block.</param>
        /// <param name="ray">The selection ray to check intersections with.</param>
        /// <param name="collisionAxis">The axis direction of the AABB the intersection happened on.</param>
        /// <returns>
        /// The distance of the ray-box-collision from the ray start; or <c>null</c> if no intersection occured.
        /// </returns>
        public static float? Intersect(ReadOnlySpan<BoundingBox> collisionBoxes, Index3 boxPosition, Ray ray, out Axis? collisionAxis)
        {
            Vector3 min = new Vector3(1, 1, 1);
            float raylength = Player.SELECTIONRANGE * 2;
            float? minDistance = null;
            bool collided = false;

            foreach (var localBox in collisionBoxes)
            {
                BoundingBox box = new BoundingBox(localBox.Min + boxPosition, localBox.Max + boxPosition);

                float? distance = ray.Intersects(box);

                if (!distance.HasValue)
                    continue;

                if (!minDistance.HasValue || minDistance > distance)
                    minDistance = distance;

                Vector3 boxCorner = new Vector3(
                        ray.Direction.X > 0 ? box.Min.X : box.Max.X,
                        ray.Direction.Y > 0 ? box.Min.Y : box.Max.Y,
                        ray.Direction.Z > 0 ? box.Min.Z : box.Max.Z);

                Vector3 n = (boxCorner - ray.Position) / (ray.Direction * raylength);
                min = new Vector3(Math.Min(min.X, n.X), Math.Min(min.Y, n.Y), Math.Min(min.Z, n.Z));
                collided = true;
            }

            if (!collided)
            {
                collisionAxis = null;
                return null;
            }

            float max = -5f;
            Axis? axis = null;

            // Fall X
            if (min.X < 1f && min.X > max)
            {
                max = min.X;
                axis = Axis.X;
            }

            // Fall Y
            if (min.Y < 1f && min.Y > max)
            {
                max = min.Y;
                axis = Axis.Y;
            }

            // Fall Z
            if (min.Z < 1f && min.Z > max)
            {
                max = min.Z;
                axis = Axis.Z;
            }

            collisionAxis = axis;

            if (axis.HasValue)
                return max * raylength;

            return null;
        }
        /// <summary>
        /// Intersection check between collision boxes of a block and entity collision box.
        /// </summary>
        /// <param name="collisionBoxes">The collision boxes of the block, local to the block.</param>
        /// <param name="boxPosition">The position of the block.</param>
        /// <param name="player">The collision box of the entity.</param>
        /// <param name="move">The movement vector of the entity.</param>
        /// <param name="collisionAxis">The axis direction of the AABB the intersection happened on.</param>
        /// <returns>
        /// The distance of the entity-block-collision; or <c>null</c> if no intersection occured.
        /// </returns>
        public static float? Intersect(ReadOnlySpan<BoundingBox> collisionBoxes, Index3 boxPosition, BoundingBox player, Vector3 move, out Axis? collisionAxis)
        {
            Vector3 playerCorner = new Vector3(
                        (move.X > 0 ? player.Max.X : player.Min.X),
                        (move.Y > 0 ? player.Max.Y : player.Min.Y),
                        (move.Z > 0 ? player.Max.Z : player.Min.Z));

            Vector3 targetPosition = playerCorner + move;

            Vector3 playerMin = player.Min + move;
            Vector3 playerMax = player.Max + move;

            Vector3 min = new Vector3(1, 1, 1);
            bool collided = false;

            foreach (var localBox in collisionBoxes)
            {
                Vector3 boxMin = localBox.Min + new Vector3(boxPosition.X, boxPosition.Y, boxPosition.Z);
                Vector3 boxMax = localBox.Max + new Vector3(boxPosition.X, boxPosition.Y, boxPosition.Z);

                bool collide =
                    playerMin.X <= boxMax.X && playerMax.X >= boxMin.X &&
                    playerMin.Y <= boxMax.Y && playerMax.Y >= boxMin.Y &&
                    playerMin.Z <= boxMax.Z && playerMax.Z >= boxMin.Z;

                if (!collide)
                    continue;

                Vector3 boxCorner = new Vector3(
                        move.X > 0 ? boxMin.X : boxMax.X,
                        move.Y > 0 ? boxMin.Y : boxMax.Y,
                        move.Z > 0 ? boxMin.Z : boxMax.Z);

                Vector3 n = (boxCorner - playerCorner) / move;
                min = new Vector3(Math.Min(min.X, n.X), Math.Min(min.Y, n.Y), Math.Min(min.Z, n.Z));
                collided = true;
            }

            if (!collided)
            {
                collisionAxis = null;
                return null;
            }
            float max = 0f;
            Axis? axis = null;

            // Fall X
            if (min.X < 1f && min.X > max)
            {
                max = min.X;
                axis = Axis.X;
            }

            // Fall Y
            if (min.Y < 1f && min.Y > max)
            {
                max = min.Y;
                axis = Axis.Y;
            }

            // Fall Z
            if (min.Z < 1f && min.Z > max)
            {
                max = min.Z;
                axis = Axis.Z;
            }

            collisionAxis = axis;

            if (axis.HasValue)
                return max;

            return null;
        }
    }
}


text:
var app = require('./app');
app.listen(process.env.PORT);

console.log("PID:", process.pid);
console.log("PORT:", process.env.PORT);
console.log("Development:", !!process.env.HLRDESK_DEV);
console.log("Hostname:", process.env.HLRDESK_HOST);
console.log("URL:", 'http://' + process.env.HLRDESK_HOST + ':' + process.env.PORT);


text: Some utilities of Redis written in Go language.


text:
Heavy metal SOAP client

[Documentation](http://savonrb.com) | [RDoc](http://rubydoc.info/gems/savon) |
[Mailing list](https://groups.google.com/forum/#!forum/savonrb) | [Twitter](http://twitter.com/savonrb)

[![Build Status](https://secure.travis-ci.org/savonrb/savon.png?branch=master)](http://travis-ci.org/savonrb/savon)
[![Gem Version](https://badge.fury.io/rb/savon.png)](http://badge.fury.io/rb/savon)
[![Code Climate](https://codeclimate.com/github/savonrb/savon.png)](https://codeclimate.com/github/savonrb/savon)
[![Coverage Status](https://coveralls.io/repos/savonrb/savon/badge.png?branch=master)](https://coveralls.io/r/savonrb/savon)

## Version 3

**Status: Unstable.** Savon version 3 is currently under development and available for testing on GitHub.
Use this version if you can handle changes and want to provide feedback.

Version 3 is still in a very early stage, but [there is some documentation!](http://savonrb.com/version3/)

## Stable version

If you're looking for the latest stable version, please [check out the version2 branch](https://github.com/savonrb/savon/tree/version2).
There's also a [version1 branch](https://github.com/savonrb/savon/tree/version2), for everyone stuck on that version.

## Give back

If you're using Savon and you or your company is making money from it, then please consider
donating via [Gittip](https://www.gittip.com/rubiii/) so that I can continue to improve it.

[![donate](donate.png)](https://www.gittip.com/rubiii/)

Donate icon from the [Noun Project](http://thenounproject.com/noun/donate/#icon-No285).


text:
package org.scriptonbasestar.spring.web.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * @author archmagece
 */
@Slf4j
public class AjaxResponseHandler
	implements HandlerMethodReturnValueHandler {

	@Override
	public boolean supportsReturnType(MethodParameter returnType) {
		return false;
	}

	@Override
	public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
		System.out.println(webRequest.getParameter("com.scriptonbasestar.request.startTime"));
//		if(returnValue instanceof AjaxResponse){AjaxResponseHandler
//			((AjaxResponse) returnValue).responseTime((long)webRequest.getAttribute("com.scriptonbasestar.request.startTime"));
//		}
	}
}


text:
class AdbWebSocket : public base::RefCountedThreadSafe<AdbWebSocket> {
 public:
  class Delegate {
   public:
    virtual void OnSocketOpened() = 0;
    virtual void OnFrameRead(const std::string& message) = 0;
    virtual void OnSocketClosed(bool closed_by_device) = 0;
    virtual bool ProcessIncomingMessage(const std::string& message) = 0;

   protected:
    virtual ~Delegate() {}
  };

  AdbWebSocket(scoped_refptr<DevToolsAdbBridge::AndroidDevice> device,
               const std::string& socket_name,
               const std::string& url,
               base::MessageLoop* adb_message_loop,
               Delegate* delegate);

  void Disconnect();

  void SendFrame(const std::string& message);

  void SendFrameOnHandlerThread(const std::string& message);

 private:
  friend class base::RefCountedThreadSafe<AdbWebSocket>;

  virtual ~AdbWebSocket();

  void ConnectOnHandlerThread();
  void ConnectedOnHandlerThread(int result, net::StreamSocket* socket);
  void StartListeningOnHandlerThread();
  void OnBytesRead(scoped_refptr<net::IOBuffer> response_buffer, int result);
  void SendPendingRequests(int result);
  void DisconnectOnHandlerThread(bool closed_by_device);

  void OnSocketOpened();
  void OnFrameRead(const std::string& message);
  void OnSocketClosed(bool closed_by_device);

  scoped_refptr<DevToolsAdbBridge::AndroidDevice> device_;
  std::string socket_name_;
  std::string url_;
  base::MessageLoop* adb_message_loop_;
  scoped_ptr<net::StreamSocket> socket_;
  Delegate* delegate_;
  std::string response_buffer_;
  std::string request_buffer_;
  DISALLOW_COPY_AND_ASSIGN(AdbWebSocket);
};

#endif  // CHROME_BROWSER_DEVTOOLS_ADB_WEB_SOCKET_H_


text:
package org.ovirt.engine.ui.webadmin.section.main.view.tab.datacenter;

import javax.inject.Inject;

import org.ovirt.engine.core.common.businessentities.AuditLog;
import org.ovirt.engine.core.common.businessentities.StoragePool;
import org.ovirt.engine.ui.common.idhandler.ElementIdHandler;
import org.ovirt.engine.ui.common.system.ClientStorage;
import org.ovirt.engine.ui.common.uicommon.model.SearchableDetailModelProvider;
import org.ovirt.engine.ui.uicommonweb.models.datacenters.DataCenterEventListModel;
import org.ovirt.engine.ui.uicommonweb.models.datacenters.DataCenterListModel;
import org.ovirt.engine.ui.webadmin.ApplicationConstants;
import org.ovirt.engine.ui.webadmin.section.main.presenter.tab.datacenter.SubTabDataCenterEventPresenter;
import org.ovirt.engine.ui.webadmin.section.main.view.AbstractSubTabEventView;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;

public class SubTabDataCenterEventView extends AbstractSubTabEventView<StoragePool, DataCenterListModel, DataCenterEventListModel>
        implements SubTabDataCenterEventPresenter.ViewDef {

    interface ViewIdHandler extends ElementIdHandler<SubTabDataCenterEventView> {
        ViewIdHandler idHandler = GWT.create(ViewIdHandler.class);
    }

    @Inject
    public SubTabDataCenterEventView(SearchableDetailModelProvider<AuditLog, DataCenterListModel, DataCenterEventListModel> modelProvider,
            EventBus eventBus,
            ClientStorage clientStorage, ApplicationConstants contants) {
        super(modelProvider, eventBus, clientStorage, contants);
    }

    @Override
    protected void generateIds() {
        ViewIdHandler.idHandler.generateAndSetIds(this);
    }

}


text:
package org.rapidnewsawards.messages;

import java.io.Serializable;
import java.util.Date;
import java.util.LinkedList;

import org.rapidnewsawards.core.Periodical;
import org.rapidnewsawards.core.User;

public class InfluenceMessage implements Comparable<InfluenceMessage>,
Serializable {
	private static final long serialVersionUID = 1L;
	public User user;
	public String fundedStr;
	public int funded;
	public LinkedList<User> supportingEditors;
	public String timeStr;
	public long timeLong;

	public InfluenceMessage (User u, int funded) {
		this.user = u;
		this.funded = funded;
		this.fundedStr = Periodical.moneyPrint(funded);
		this.supportingEditors = new LinkedList<User>();
	}

	public InfluenceMessage() {};

	public int compareTo(InfluenceMessage ua) {
		// descending
		return funded < ua.funded ? 1 : funded == ua.funded ? 0 : -1;
	}

	public void setTime(Date time) {
		this.timeStr = Periodical.timeFormat(time);
		this.timeLong = time.getTime();
	}

}


text:
import Popen()

def check_system (OS_Type, OS_Platform, Platform_Release):
	import os, platform
		print os.name
		platform.system()
		platform.release()

	os = platform.system() #defines os as the general operating system type determined above

		os [:] = [f for f in os if (f[len(f):len(f)] == "Windows")] #if windows...

			import win32com.client
			from ctypes import *
			from ctypes.wintypes import *
			import pythoncom
			import pywintypes
			import datetime

			class MEMORYSTATUS(Structure):
				fields = [
					('dwLength', DWORD),
					('dwMemoryLoad', DWORD),
					('dwTotalPhys', DWORD),
					('dwAvailPhys', DWORD),
					('dwTotalPageFile', DWORD),
					('dwAvailPageFile', DWORD),
					('dwTotalVirtual', DWORD),
					('dwAvailVirtual', DWORD),
					]

			def winmem():
				x = MEMORYSTATUS()
				windll.kernel32.GlobalMemoryStatus(byref(x)) #FUNCTIONS FOR 32 BIT OPERATING SYSTEMS?
				return x

# The following runs for Linux (unix based) operating Systems
		os [:] = [f for f in os if (f[len(f):len(f)] == "Linux")]
			import subprocess

			class MemoryMonitor(object):

				def __init__(self, username):
					"""Create new MemoryMonitor instance."""
					self.username = username

				def usage(self):
					"""Return int containing memory used by user's processes."""
					self.process = subprocess.Popen("ps -u %s -o rss | awk '{sum+=$1} END {print sum}'" % self.username,
                                        shell=True,
                                        stdout=subprocess.PIPE,
                                        )
					self.stdout_list = self.process.communicate()[0].split('\n')
					return int(self.stdout_list[0])


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline;
using Microsoft.Xna.Framework.Content.Pipeline.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline.Processors;
using Microsoft.Xna.Framework.Content.Pipeline.Serialization.Compiler;

using TWrite = LevelLibrary.Level;

namespace LevelContentPipelineExtension
{
    [ContentTypeWriter]
    public class LevelWriter : ContentTypeWriter<TWrite>
    {
        protected override void Write(ContentWriter output, TWrite value)
        {
            output.Write(value.Rows);
            output.Write(value.Columns);
            for (int row = 0; row < value.Rows; row++)
            {
                for (int column = 0; column < value.Columns; column++)
                {
                    output.Write(value.GetValue(row, column));
                }
            }
        }

        public override string GetRuntimeReader(TargetPlatform targetPlatform)
        {
            return "LevelLibrary.LevelReader, LevelLibrary";
        }
    }
}


text:
/*****************************************************************************
  tagBam.h

  (c) 2009 - Aaron Quinlan
  Hall Laboratory
  Department of Biochemistry and Molecular Genetics
  University of Virginia
  aaronquinlan@gmail.com

  Licenced under the GNU General Public License 2.0 license.
******************************************************************************/
#ifndef TAGBAM_H
#define TAGBAM_H

#include "bedFile.h"

#include "api/BamReader.h"
#include "api/BamWriter.h"
#include "api/BamAux.h"
#include "BamAncillary.h"
using namespace BamTools;

#include "bedFile.h"
#include <vector>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <stdlib.h>

using namespace std;

//************************************************
// Class methods and elements
//************************************************
class TagBam {

public:

    // constructor
    TagBam(const string &bamFile, const vector<string> &annoFileNames,
                const vector<string> &annoLabels, const string &tag,
                bool useNames, bool useScores, bool useIntervals, bool sameStrand,
                bool diffStrand, float overlapFraction);

    // destructor
    ~TagBam(void);

    // annotate the BAM file with all of the annotation files.
    void Tag();

private:

    // input files.
    string _bamFile;
    vector<string> _annoFileNames;
    vector<string> _annoLabels;

    string _tag;

    // instance of a bed file class.
    vector<BedFile*> _annoFiles;

    // should we use the name field from the annotation files?
    bool _useNames;
    bool _useScores;
    bool _useIntervals;

    // do we care about strandedness when tagging?
    bool _sameStrand;
    bool _diffStrand;
    float _overlapFraction;

    // private function for reporting coverage information
    void ReportAnnotations();

    void OpenAnnoFiles();

    void CloseAnnoFiles();

};
#endif /* TAGBAM_H */


text:
import java.util.Collections;
import java.util.List;

public class Extracted {
    public Extracted() {
    }

    List<Test> foo() {
        return Collections.emptyList();
    }
}


text:
<?xml version="1.0"?>
<ArrayOfCommand xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Command xsi:type="Release">
    <StartTime>0</StartTime>
  </Command>
  <Command xsi:type="Ignition">
    <StartTime>0</StartTime>
    <Duration>0.1</Duration>
    <Throttle>100</Throttle>
    <EngineIds>
      <int>0</int>
      <int>1</int>
      <int>2</int>
      <int>3</int>
      <int>4</int>
      <int>5</int>
      <int>6</int>
      <int>7</int>
    </EngineIds>
  </Command>
  <Command xsi:type="Pitch">
    <StartTime>1</StartTime>
    <Duration>8</Duration>
    <TargetOrientation>-140</TargetOrientation>
  </Command>
  <Command xsi:type="Pitch">
    <StartTime>8</StartTime>
    <Duration>20</Duration>
    <TargetOrientation>-180</TargetOrientation>
  </Command>
    <Command xsi:type="Stage">
    <StartTime>15</StartTime>
  </Command>
</ArrayOfCommand>


text:
'use strict';

var Contact = require('./contact.model');
var contactService = require('./contact.service');
var userService = require('../user.service');
var mongoose = require('mongoose');

exports.create = function(req, res, next) {
  var userId = req.params.userId;
  var idContact = mongoose.Types.ObjectId();
  var userUpdate = req.body.userId;
  var isValidTypeContact = contactService.validateTypeContactSync(req.body.type);
  if(!isValidTypeContact){
    return res.status(400).json({
      "code": "ValidationError",
      "message": "Contact Type is not accepted"
    });
  }
  var filter = {_id:userId};
  if(userUpdate != userId) {
    filter = {createdBy : userId, _id:userUpdate};
  }
  userService.findOne(filter, '', function(err, userFind) {
    if(err) return res.status(409).json(res, err);
    if(!userFind){
      return res.status(404).json({
        "code": "AuthCredentialNotExists",
        "message": "User Id does not exist"
      });
    }
    var contacts = {
      contactId : idContact,
      label : req.body.label,
      type : req.body.type,
      value : req.body.value
    };
    userFind.contacts.push(contacts);
    userService.save(userFind, function(err, userSave) {
      if(err) {
        return res.status(404).json({
          "code": "AuthCredentialNotExists",
          "message": "User contact id does exist"
        });
      }
      res.status(200).json({contactId:idContact});
    });
  });
};

exports.list = function(req, res, next) {
  var userId = req.params.userId;
  var userUpdate = req.body.userId;
  var filter = userId;
  if(userUpdate != userId) {
    filter = userUpdate;
  }
  userService.findOne({_id:filter},'-contacts.label -contacts.value', function(err, userFind) {
    if(err) return res.status(400).json({
      code: 'ValidationError',
      message: 'The given user id is invalid'
    });
    if(!userFind || filter != userFind.id){
      return res.status(404).json({
        "code": "AuthCredentialNotExists",
        "message": "User contact id does not exist"
      });
    }
    res.status(200).json(userFind.contacts);
  });
};

exports.load = function(req, res, next) {
  if(!req.params && !req.params.contactId) {
    return res.status(400).json({
      "code": "ValidationError",
      "message": "Contact Id is required"
    });
  }
  var idContact;
  var userId;
  try {
    userId = mongoose.Types.ObjectId(req.params.userId);
    idContact = mongoose.Types.ObjectId(req.params.contactId);
  }
  catch (err) {
    return res.status(400).json({
      code: "ValidationError",
      message: "The given contact id is not valid"
    });
  }
  var filter = {_id:userId,'contacts.contactId':idContact};
  userService.findOne(filter,{contacts: {$elemMatch: {'contactId': idContact}}}, function(err, userFind) {
      if(err) return res.status(400).json({
        code: "ValidationError",
        message: "The given contact id is not valid"
      });
      if(!userFind){
        return res.status(404).json({
          "code": "AuthCredentialNotExists",
          "message": "Telephone does not exist"
        });
      }
      return res.status(200).json(userFind.contacts[0]);
    }
  );
};

exports.update = function(req, res, next) {
  var userId = req.params.userId;
  var userUpdate = req.body.userId;
  if(!req.params && !req.params.contactId) {
    return res.status(400).json({
      "code": "ValidationError",
      "message": "Contact Id is required"
    });
  }
  var userId;
  var contacts;
  try {
    userId = mongoose.Types.ObjectId(req.params.userId);
    contacts = mongoose.Types.ObjectId(req.params.contactId);
  }
  catch (err) {
    return res.status(400).json({
      code: "ValidationError",
      message: "The given contact id is not valid"
    });
  }
  var filter = {_id:userId,'contacts.contactId':contacts};
  if(userUpdate != userId) {
    filter = {createdBy : userId, _id:userUpdate,'contacts.contactId':contacts};
  }
  userService.findOne(filter, '', function(err, userFind) {
    if(err) return res.status(400).json({
      code: "ValidationError",
      message: "The given contact id is not valid"
    });
    if(!userFind){
      return res.status(404).json({
        "code": "AuthCredentialNotExists",
        "message": "Telephone/user does not exist"
      });
    }
    userService.update(filter, {'$set': {'contacts.$.value': req.body.value}}, function(err, data){
      if(err) {
        return res.status(404).json({
          "code": "AuthCredentialNotExists",
          "message": "User contact/user id does not update"
        });
      }
      res.status(200).json({contactId:contacts});
    });
  });
};

exports.delete = function(req, res, next) {
  if(!req.params && !req.params.contactId) {
    return res.status(400).json({
      "code": "ValidationError",
      "message": "Contact Id is required"
    });
  }
  var userId;
  var contactId;
  try {
    userId = mongoose.Types.ObjectId(req.params.userId);
    contactId = mongoose.Types.ObjectId(req.params.contactId);
  }
  catch (err) {
    return res.status(400).json({
      code: "ValidationError",
      message: "The given contact id is not valid"
    });
  }
  var filter = {_id:userId,'contacts.contactId':contactId};
  userService.findOne(filter,{contacts: {$elemMatch: {'contactId': contactId}}}, function(err, userFind) {
      if(err) return res.status(400).json({
        code: "ValidationError",
        message: "The given contact id is not valid"
      });
      if(!userFind){
        return res.status(404).json({
          "code": "AuthCredentialNotExists",
          "message": "Contact does not exists"
        });
      }
      userService.update(filter, { $pull: { "contacts" : { 'contactId': contactId} } },function(err,data){
        if(err) {
          return res.status(404).json({
            "code": "AuthCredentialNotExists",
            "message": "User contact id does not delete"
          });
        }
        return res.status(200).json({});
      });

    }
  );
};


text:
function scene = sceneInitSpatial(scene)
%Initialize the scene field of view to 10 deg.
%
%     scene = sceneInitSpatial(scene)
%
%  This field of view is small as most cameras see a 40 deg.  But it is the right size for
%  a small sensor at 8 um and 100x100, as we use for many evaluations.
%
%  We are leaving this trivial routine here for potential future
%  development.
%
%  If the parameter is already set, then it is not modified by this
%  routine.
%
% Copyright ImagEval Consultants, LLC, 2003.

% Degrees
if ~checkfields(scene,'wAngular'),  scene = sceneSet(scene,'fov',10);  end

return;


text:
package net.dirtyfilthy.bouncycastle.asn1.x509;

import java.util.Enumeration;
import java.util.Vector;

import net.dirtyfilthy.bouncycastle.asn1.ASN1Encodable;
import net.dirtyfilthy.bouncycastle.asn1.ASN1EncodableVector;
import net.dirtyfilthy.bouncycastle.asn1.ASN1Sequence;
import net.dirtyfilthy.bouncycastle.asn1.DERObject;
import net.dirtyfilthy.bouncycastle.asn1.DERSequence;

/**
 * This extension may contain further X.500 attributes of the subject. See also
 * RFC 3039.
 *
 *

 *     SubjectDirectoryAttributes ::= Attributes
 *     Attributes ::= SEQUENCE SIZE (1..MAX) OF Attribute
 *     Attribute ::= SEQUENCE
 *     {
 *       type AttributeType
 *       values SET OF AttributeValue
 *     }
 *
 *     AttributeType ::= OBJECT IDENTIFIER
 *     AttributeValue ::= ANY DEFINED BY AttributeType
 *

 *
 * @see net.dirtyfilthy.bouncycastle.asn1.x509.X509Name for AttributeType ObjectIdentifiers.
 */
public class SubjectDirectoryAttributes
    extends ASN1Encodable
{
    private Vector attributes = new Vector();

    public static SubjectDirectoryAttributes getInstance(
        Object obj)
    {
        if (obj == null || obj instanceof SubjectDirectoryAttributes)
        {
            return (SubjectDirectoryAttributes)obj;
        }

        if (obj instanceof ASN1Sequence)
        {
            return new SubjectDirectoryAttributes((ASN1Sequence)obj);
        }

        throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName());
    }

    /**
     * Constructor from ASN1Sequence.
     *
     * The sequence is of type SubjectDirectoryAttributes:
     *
     *

     *      SubjectDirectoryAttributes ::= Attributes
     *      Attributes ::= SEQUENCE SIZE (1..MAX) OF Attribute
     *      Attribute ::= SEQUENCE
     *      {
     *        type AttributeType
     *        values SET OF AttributeValue
     *      }
     *
     *      AttributeType ::= OBJECT IDENTIFIER
     *      AttributeValue ::= ANY DEFINED BY AttributeType
     *

     *
     * @param seq
     *            The ASN.1 sequence.
     */
    public SubjectDirectoryAttributes(ASN1Sequence seq)
    {
        Enumeration e = seq.getObjects();

        while (e.hasMoreElements())
        {
            ASN1Sequence s = ASN1Sequence.getInstance(e.nextElement());
            attributes.addElement(new Attribute(s));
        }
    }

    /**
     * Constructor from a vector of attributes.
     *
     * The vector consists of attributes of type {@link Attribute Attribute}
     *
     * @param attributes
     *            The attributes.
     *
     */
    public SubjectDirectoryAttributes(Vector attributes)
    {
        Enumeration e = attributes.elements();

        while (e.hasMoreElements())
        {
            this.attributes.addElement(e.nextElement());
        }
    }

    /**
     * Produce an object suitable for an ASN1OutputStream.
     *
     * Returns:
     *
     *

     *      SubjectDirectoryAttributes ::= Attributes
     *      Attributes ::= SEQUENCE SIZE (1..MAX) OF Attribute
     *      Attribute ::= SEQUENCE
     *      {
     *        type AttributeType
     *        values SET OF AttributeValue
     *      }
     *
     *      AttributeType ::= OBJECT IDENTIFIER
     *      AttributeValue ::= ANY DEFINED BY AttributeType
     *

     *
     * @return a DERObject
     */
    public DERObject toASN1Object()
    {
        ASN1EncodableVector vec = new ASN1EncodableVector();
        Enumeration e = attributes.elements();

        while (e.hasMoreElements())
        {

            vec.add((Attribute)e.nextElement());
        }

        return new DERSequence(vec);
    }

    /**
     * @return Returns the attributes.
     */
    public Vector getAttributes()
    {
        return attributes;
    }
}


text:
package org.ovirt.engine.ui.webadmin.uicommon;

import org.ovirt.engine.core.common.businessentities.DisplayType;
import org.ovirt.engine.core.compat.Event;
import org.ovirt.engine.core.compat.EventArgs;
import org.ovirt.engine.core.compat.EventDefinition;
import org.ovirt.engine.core.compat.IEventListener;
import org.ovirt.engine.core.compat.Version;
import org.ovirt.engine.ui.common.uicommon.ClientAgentType;
import org.ovirt.engine.ui.common.uicommon.DocumentationPathTranslator;
import org.ovirt.engine.ui.common.uicommon.SpiceInterfaceImpl;
import org.ovirt.engine.ui.common.uicommon.model.UiCommonInitEvent;
import org.ovirt.engine.ui.common.uicommon.model.UiCommonInitEvent.UiCommonInitHandler;
import org.ovirt.engine.ui.frontend.AsyncQuery;
import org.ovirt.engine.ui.frontend.INewAsyncCallback;
import org.ovirt.engine.ui.uicommonweb.Configurator;
import org.ovirt.engine.ui.uicommonweb.dataprovider.AsyncDataProvider;
import org.ovirt.engine.ui.uicommonweb.models.vms.ISpice;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.inject.Inject;

public class WebAdminConfigurator extends Configurator implements IEventListener, UiCommonInitHandler {

    // Temporarily save the locations of webadmin and userportal.
    // TODO: create a new SPICE RPM for webadmin
    private static final String WEBADMIN_ROOT_FOLDER = "/webadmin/webadmin/";
    private static final String USERPORTAL_ROOT_FOLDER = "/userportal-gwtp/userportal/";

    public static final String DOCUMENTATION_GUIDE_PATH = "Administration_Guide/index.html";

    public EventDefinition spiceVersionFileFetchedEvent_Definition =
            new EventDefinition("spiceVersionFileFetched", WebAdminConfigurator.class);

    public Event spiceVersionFileFetchedEvent = new Event(spiceVersionFileFetchedEvent_Definition);

    public EventDefinition documentationFileFetchedEvent_Definition = new EventDefinition("documentationFileFetched",
            WebAdminConfigurator.class);
    public Event documentationFileFetchedEvent = new Event(documentationFileFetchedEvent_Definition);

    private boolean isInitialized;

    @Inject
    public WebAdminConfigurator(EventBus eventBus)
    {
        eventBus.addHandler(UiCommonInitEvent.getType(), this);

        // Set default configuration values
        setIsAdmin(true);
        setSpiceAdminConsole(true);
        setSpiceFullScreen(false);

        // Add event listeners
        spiceVersionFileFetchedEvent.addListener(this);
        documentationFileFetchedEvent.addListener(this);

        // Update Spice version if needed
        updateSpiceVersion();
    }

    private void updateSpiceVersion() {
        // Update spice version from the text files which are located on the server.
        // If can't update spice version - leave the default value from the Configurator.
        ClientAgentType cat = new ClientAgentType();
        if ((cat.os.equalsIgnoreCase("Windows")) && (cat.browser.equalsIgnoreCase("Explorer"))) {
            if (cat.getPlatform().equalsIgnoreCase("win32")) {
                updateSpice32Version();
            } else if (cat.getPlatform().equalsIgnoreCase("win64")) {
                updateSpice64Version();
            }
        }
    }

    public void updateSpice32Version() {
        fetchFile(getSpiceBaseURL() + "SpiceVersion.txt", spiceVersionFileFetchedEvent);
    }

    public void updateSpice64Version() {
        fetchFile(getSpiceBaseURL() + "SpiceVersion_x64.txt", spiceVersionFileFetchedEvent);
    }

    public void updateDocumentationPathFile() {
        fetchFile(getDocumentationBaseURL() + "DocumentationPath.csv", documentationFileFetchedEvent);
    }

    public void updateIsUsbEnabled(final ISpice spice) {
        // Get 'EnableUSBAsDefault' value from database
        AsyncDataProvider.IsUSBEnabledByDefault(new AsyncQuery(this, new INewAsyncCallback() {
            @Override
            public void OnSuccess(Object target, Object returnValue) {
                // Update IsUsbEnabled value
                setIsUsbEnabled((Boolean) returnValue);
            }
        }));
    }

    public void updateDocumentationBaseURL() {
        // Get 'EnableUSBAsDefault' value from database
        AsyncDataProvider.GetDocumentationBaseURL(new AsyncQuery(this,
                new INewAsyncCallback() {
                    @Override
                    public void OnSuccess(Object target, Object returnValue) {
                        String documentationBaseURL = (String) returnValue;
                        boolean isDocumentationAvailable = !documentationBaseURL.equals("");

                        setDocumentationAvailable(isDocumentationAvailable);
                        setDocumentationBasePath(documentationBaseURL);
                        updateDocumentationPathFile();
                    }
                }));
    }

    public String getSpiceBaseURL() {
        return GWT.getModuleBaseURL().replace(WEBADMIN_ROOT_FOLDER, USERPORTAL_ROOT_FOLDER);
    }

    // Fetch file from a specified path
    public void fetchFile(String filePath, final Event onFetched) {

        RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, filePath);
        try {
            requestBuilder.sendRequest(null, new RequestCallback() {
                @Override
                public void onError(Request request, Throwable exception) {
                }

                @Override
                public void onResponseReceived(Request request, Response response) {
                    String result = response.getText();
                    onFetched.raise(this, new FileFetchEventArgs(result));
                }
            });
        } catch (RequestException e) {
        }
    }

    // Create a Version object from string
    public Version parseVersion(String versionStr) {
        return new Version(versionStr.replace(',', '.').replace("\n", ""));
    }

    @Override
    public void eventRaised(Event ev, Object sender, EventArgs args) {
        if (ev.equals(spiceVersionFileFetchedEvent_Definition)) {
            Version spiceVersion = parseVersion(((FileFetchEventArgs) args).getFileContent());
            setSpiceVersion(spiceVersion);
        }
        else if (ev.equals(documentationFileFetchedEvent_Definition))
        {
            String documentationPathFileContent = ((FileFetchEventArgs) args).getFileContent();
            DocumentationPathTranslator.init(documentationPathFileContent);
        }
    }

    public final class FileFetchEventArgs extends EventArgs {
        private String fileContent;

        public String getFileContent() {
            return fileContent;
        }

        public void setFileContent(String fileContent) {
            this.fileContent = fileContent;
        }

        public FileFetchEventArgs(String fileContent) {
            setFileContent(fileContent);
        }
    }

    // Check whether the specified displayType is currently supported
    @Override
    public boolean IsDisplayTypeSupported(DisplayType displayType) {
        switch (displayType) {
        case vnc:
            return false;

        case qxl:
            ClientAgentType cat = new ClientAgentType();
            return (cat.os.equalsIgnoreCase("Windows") && cat.browser.equalsIgnoreCase("Explorer")) ||
                    (cat.os.equalsIgnoreCase("Linux") && cat.browser.equalsIgnoreCase("Firefox"));
        }

        return false;
    }

    @Override
    public void Configure(ISpice spiceImpl) {
        SpiceInterfaceImpl spice = (SpiceInterfaceImpl) spiceImpl;
        spice.setDesiredVersion(getSpiceVersion());
        spice.setCurrentVersion(getSpiceVersion());
        spice.setAdminConsole(getSpiceAdminConsole());
        spice.setFullScreen(getSpiceFullScreen());
        spice.setSpiceBaseURL(getSpiceBaseURL());

        if (!isInitialized) {
            updateIsUsbEnabled(spice);
            isInitialized = true;
        }
    }

    @Override
    public void onUiCommonInit(UiCommonInitEvent event) {
        updateDocumentationBaseURL();
    }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE ldml SYSTEM "../../common/dtd/ldml.dtd">
<!-- Copyright © 1991-2015 Unicode, Inc.
CLDR data files are interpreted according to the LDML specification (http://unicode.org/reports/tr35/)
For terms of use, see http://www.unicode.org/copyright.html
-->
<ldml>
	<identity>
		<version number="$Revision: 11324 $"/>
		<generation date="$Date: 2015-02-26 16:53:17 -0600 (Thu, 26 Feb 2015) $"/>
		<language type="sr"/>
		<script type="Latn"/>
		<territory type="XK"/>
	</identity>
</ldml>


text:
module Nmunch

  # Public: A class to represent a network node
  #
  # For now it is a simple wrapper around IP and MAC address information but might
  # contain more information in the future.
  class Node
    attr_reader :ip_address, :mac_address

    # Public: Initialize a new node
    #
    # options - A hash that must contain the keys :ip_address and :mac_address
    #
    # Returns nothing
    def initialize(options)
      @ip_address  = options[:ip_address]
      @mac_address = options[:mac_address]
    end

    # Public: Determine if node has a meta address
    #
    # A node will have a meta address (0.0.0.0) if it has not yet been given a
    # DHCP lease
    #
    # Returns TRUE if meta address and FALSE if not
    def meta_address?
      ip_address == '0.0.0.0'
    end

    # Public: Convert node to string
    #
    # Returns IP address
    def to_s
      ip_address
    end

    # Public: Compare string version of node
    #
    # Returns TRUE if same and FALSE if not
    def ==(obj)
      self.to_s == obj.to_s
    end

    # Public: Convenience method to create a node from an Nmunch::Dissector instance
    #
    # dissector - An instance of Nmunch::Dissector
    #
    # Returns instance of Nmunch::Node with details from dissector
    def self.create_from_dissector(dissector)
      self.new(ip_address: dissector.ip_address, mac_address: dissector.mac_address)
    end
  end
end


text:
<?php

namespace Sylius\Bundle\ThemeBundle\Translation\Finder;

/**
 * @author Kamil Kokot <kamil@kokot.me>
 */
final class OrderingTranslationFilesFinder implements TranslationFilesFinderInterface
{
    /**
     * @var TranslationFilesFinderInterface
     */
    private $translationFilesFinder;

    /**
     * @param TranslationFilesFinderInterface $translationFilesFinder
     */
    public function __construct(TranslationFilesFinderInterface $translationFilesFinder)
    {
        $this->translationFilesFinder = $translationFilesFinder;
    }

    public function findTranslationFiles($path)
    {
        $files = $this->translationFilesFinder->findTranslationFiles($path);

        /*
         * PHP 5.* bug, fixed in PHP 7: https://bugs.php.net/bug.php?id=50688
         * "usort(): Array was modified by the user comparison function"
         */
        @usort($files, function ($firstFile, $secondFile) use ($path) {
            $firstFile = str_replace($path, '', $firstFile);
            $secondFile = str_replace($path, '', $secondFile);

            return strpos($secondFile, 'translations') - strpos($firstFile, 'translations');
        });

        return $files;
    }
}