text:
import { outputAggregatedData } from './createAggregatedDataCollection'
import { outputEnrolmentTrendData } from './createEnrolmentTrendCollection'
import { outputFacultyDeptData } from './createFacultyAndDeptDataCollection'
import { outputOverallInstructorData } from './createOverallInstructorCollection'
import { outputUMIInstructor } from './createUMIInstructorCollection'
import { outputCoursePerformance } from './createCoursePerformanceCollection'
import { outputMetaData } from './createMetaData'

// the nested callbacks are necessary because the inner functions rely on the files that the outer function writes
outputAggregatedData(() => {
  outputEnrolmentTrendData()
  outputOverallInstructorData()
  outputUMIInstructor(() => {
    outputFacultyDeptData(() => {
      outputCoursePerformance(() =>
        console.log('All files created successfully!'))
    })
  })
  outputMetaData()
})


text:
var dir_dcd684713a046488f606ed3ee36b0989 =
[
    [ "ChannelConnectionListener.java", "ChannelConnectionListener_8java.html", [
      [ "ChannelConnectionListener", "classorg_1_1onosproject_1_1ovsdb_1_1controller_1_1impl_1_1ChannelConnectionListener.html", "classorg_1_1onosproject_1_1ovsdb_1_1controller_1_1impl_1_1ChannelConnectionListener" ]
    ] ],
    [ "Controller.java", "protocols_2ovsdb_2ctl_2src_2main_2java_2org_2onosproject_2ovsdb_2controller_2impl_2Controller_8java.html", [
      [ "Controller", "classorg_1_1onosproject_1_1ovsdb_1_1controller_1_1impl_1_1Controller.html", "classorg_1_1onosproject_1_1ovsdb_1_1controller_1_1impl_1_1Controller" ]
    ] ],
    [ "MessageDecoder.java", "protocols_2ovsdb_2ctl_2src_2main_2java_2org_2onosproject_2ovsdb_2controller_2impl_2MessageDecoder_8java.html", [
      [ "MessageDecoder", "classorg_1_1onosproject_1_1ovsdb_1_1controller_1_1impl_1_1MessageDecoder.html", "classorg_1_1onosproject_1_1ovsdb_1_1controller_1_1impl_1_1MessageDecoder" ]
    ] ],
    [ "OvsdbControllerImpl.java", "OvsdbControllerImpl_8java.html", [
      [ "OvsdbControllerImpl", "classorg_1_1onosproject_1_1ovsdb_1_1controller_1_1impl_1_1OvsdbControllerImpl.html", "classorg_1_1onosproject_1_1ovsdb_1_1controller_1_1impl_1_1OvsdbControllerImpl" ]
    ] ],
    [ "OvsdbJsonRpcHandler.java", "OvsdbJsonRpcHandler_8java.html", [
      [ "OvsdbJsonRpcHandler", "classorg_1_1onosproject_1_1ovsdb_1_1controller_1_1impl_1_1OvsdbJsonRpcHandler.html", "classorg_1_1onosproject_1_1ovsdb_1_1controller_1_1impl_1_1OvsdbJsonRpcHandler" ]
    ] ],
    [ "package-info.java", "protocols_2ovsdb_2ctl_2src_2main_2java_2org_2onosproject_2ovsdb_2controller_2impl_2package-info_8java.html", null ]
];

redpajama_set_name: RedPajamaGithub


text:
package org.apache.hadoop.contrib.failmon;

import java.io.IOException;
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**********************************************************
 * An object of this class parses a Unix system log file to create appropriate
 * EventRecords. Currently, only the syslogd logging daemon is supported.
 *
 **********************************************************/

public class SystemLogParser extends LogParser {

	static String[] months = { "January", "February", "March", "April", "May",
			"June", "July", "August", "September", "October", "November",
			"December" };

	/**
	 * Create a new parser object .
	 */
	public SystemLogParser(String fname) {
		super(fname);
		if ((dateformat = Environment.getProperty("log.system.dateformat")) == null)
			dateformat = "(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\\s+(\\d+)";
		if ((timeformat = Environment.getProperty("log.system.timeformat")) == null)
			timeformat = "\\d{2}:\\d{2}:\\d{2}";
	}

	/**
	 * Parses one line of the log. If the line contains a valid log entry, then
	 * an appropriate EventRecord is returned, after all relevant fields have
	 * been parsed.
	 *
	 * @param line
	 *            the log line to be parsed
	 *
	 * @return the EventRecord representing the log entry of the line. If the
	 *         line does not contain a valid log entry, then the EventRecord
	 *         returned has isValid() = false. When the end-of-file has been
	 *         reached, null is returned to the caller.
	 */
	public EventRecord parseLine(String line) throws IOException {

		EventRecord retval = null;

		if (line != null) {
			// process line
			String patternStr = "(" + dateformat + ")";
			patternStr += "\\s+";
			patternStr += "(" + timeformat + ")";
			patternStr += "\\s+(\\S*)\\s"; // for hostname
			// patternStr += "\\s*([\\w+\\.?]+)"; // for source
			patternStr += ":?\\s*(.+)"; // for the message
			Pattern pattern = Pattern.compile(patternStr);
			Matcher matcher = pattern.matcher(line);
			if (matcher.find() && matcher.groupCount() >= 0) {
				retval = new EventRecord(hostname, ips, parseDate(matcher
						.group(1), matcher.group(4)), "SystemLog", "Unknown", // loglevel
						"Unknown", // source
						matcher.group(6)); // message
			} else {
				retval = new EventRecord();
			}
		}

		return retval;
	}

	/**
	 * Parse a date found in the system log.
	 *
	 * @return a Calendar representing the date
	 */
	protected Calendar parseDate(String strDate, String strTime) {
		Calendar retval = Calendar.getInstance();
		// set date
		String[] fields = strDate.split("\\s+");
		retval.set(Calendar.MONTH, parseMonth(fields[0]));
		retval.set(Calendar.DATE, Integer.parseInt(fields[1]));
		// set time
		fields = strTime.split(":");
		retval.set(Calendar.HOUR_OF_DAY, Integer.parseInt(fields[0]));
		retval.set(Calendar.MINUTE, Integer.parseInt(fields[1]));
		retval.set(Calendar.SECOND, Integer.parseInt(fields[2]));
		return retval;
	}

	/**
	 * Convert the name of a month to the corresponding int value.
	 *
	 * @return the int representation of the month.
	 */
	private int parseMonth(String month) {
		for (int i = 0; i < months.length; i++)
			if (months[i].startsWith(month))
				return i;
		return -1;
	}

	/**
	 * Return a String with information about this class
	 *
	 * @return A String describing this class
	 */
	public String getInfo() {
		return ("System Log Parser for file : " + file.getAbsoluteFile());
	}
}


text:
/****************************************************************************
 *  Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995               *
 *     and: Eric S. Raymond <esr@snark.thyrsus.com>                         *
 *     and: Thomas E. Dickey                        1996-on                 *
 ****************************************************************************/

/*
 *	comp_hash.c --- Routines to deal with the hashtable of capability
 *			names.
 *
 */

#define USE_TERMLIB 1
#include <curses.priv.h>

#include <tic.h>
#include <hashsize.h>

#ifdef MAIN_PROGRAM
#include <ctype.h>
#undef  DEBUG
#define DEBUG(level, params)	/*nothing */
#endif

MODULE_ID("$Id: comp_hash.c,v 1.36 2008/08/16 17:06:53 tom Exp $")

static int hash_function(const char *);

/*
 *	_nc_make_hash_table()
 *
 *	Takes the entries in table[] and hashes them into hash_table[]
 *	by name.  There are CAPTABSIZE entries in table[] and HASHTABSIZE
 *	slots in hash_table[].
 *
 */

#ifdef MAIN_PROGRAM

#undef MODULE_ID
#define MODULE_ID(id)		/*nothing */
#include <tinfo/doalloc.c>

static void
_nc_make_hash_table(struct name_table_entry *table,
		    short *hash_table)
{
    short i;
    int hashvalue;
    int collisions = 0;

    for (i = 0; i < HASHTABSIZE; i++) {
	hash_table[i] = -1;
    }
    for (i = 0; i < CAPTABSIZE; i++) {
	hashvalue = hash_function(table[i].nte_name);

	if (hash_table[hashvalue] >= 0)
	    collisions++;

	if (hash_table[hashvalue] != 0)
	    table[i].nte_link = hash_table[hashvalue];
	hash_table[hashvalue] = i;
    }

    DEBUG(4, ("Hash table complete: %d collisions out of %d entries",
	      collisions, CAPTABSIZE));
}
#endif

/*
 *	int hash_function(string)
 *
 *	Computes the hashing function on the given string.
 *
 *	The current hash function is the sum of each consectutive pair
 *	of characters, taken as two-byte integers, mod HASHTABSIZE.
 *
 */

static int
hash_function(const char *string)
{
    long sum = 0;

    DEBUG(9, ("hashing %s", string));
    while (*string) {
	sum += (long) (*string + (*(string + 1) << 8));
	string++;
    }

    DEBUG(9, ("sum is %ld", sum));
    return (int) (sum % HASHTABSIZE);
}

/*
 *	struct name_table_entry *
 *	find_entry(string)
 *
 *	Finds the entry for the given string in the hash table if present.
 *	Returns a pointer to the entry in the table or 0 if not found.
 *
 */

#ifndef MAIN_PROGRAM
NCURSES_EXPORT(struct name_table_entry const *)
_nc_find_entry(const char *string,
	       const short *hash_table)
{
    int hashvalue;
    struct name_table_entry const *ptr = 0;
    struct name_table_entry const *real_table;

    hashvalue = hash_function(string);

    if (hash_table[hashvalue] >= 0) {
	real_table = _nc_get_table(hash_table != _nc_get_hash_table(FALSE));
	ptr = real_table + hash_table[hashvalue];
	while (strcmp(ptr->nte_name, string) != 0) {
	    if (ptr->nte_link < 0)
		return 0;
	    ptr = real_table + (ptr->nte_link + hash_table[HASHTABSIZE]);
	}
    }

    return (ptr);
}

/*
 *	struct name_table_entry *
 *	find_type_entry(string, type, table)
 *
 *	Finds the first entry for the given name with the given type in the
 *	given table if present (as distinct from find_entry, which finds the
 *	the last entry regardless of type).  You can use this if you detect
 *	a name clash.  It's slower, though.  Returns a pointer to the entry
 *	in the table or 0 if not found.
 */

NCURSES_EXPORT(struct name_table_entry const *)
_nc_find_type_entry(const char *string,
		    int type,
		    const struct name_table_entry *table)
{
    struct name_table_entry const *ptr;

    for (ptr = table; ptr < table + CAPTABSIZE; ptr++) {
	if (ptr->nte_type == type && strcmp(string, ptr->nte_name) == 0)
	    return (ptr);
    }

    return ((struct name_table_entry *) NULL);
}
#endif

#ifdef MAIN_PROGRAM
/*
 * This filter reads from standard input a list of tab-delimited columns,
 * (e.g., from Caps.filtered) computes the hash-value of a specified column and
 * writes the hashed tables to standard output.
 *
 * By compiling the hash table at build time, we're able to make the entire
 * set of terminfo and termcap tables readonly (and also provide some runtime
 * performance enhancement).
 */

#define MAX_COLUMNS BUFSIZ	/* this _has_ to be worst-case */

static char **
parse_columns(char *buffer)
{
    static char **list;

    int col = 0;

    if (list == 0 && (list = typeCalloc(char *, MAX_COLUMNS)) == 0)
	  return (0);

    if (*buffer != '#') {
	while (*buffer != '\0') {
	    char *s;
	    for (s = buffer; (*s != '\0') && !isspace(UChar(*s)); s++)
		/*EMPTY */ ;
	    if (s != buffer) {
		char mark = *s;
		*s = '\0';
		if ((s - buffer) > 1
		    && (*buffer == '"')
		    && (s[-1] == '"')) {	/* strip the quotes */
		    assert(s > buffer + 1);
		    s[-1] = '\0';
		    buffer++;
		}
		list[col] = buffer;
		col++;
		if (mark == '\0')
		    break;
		while (*++s && isspace(UChar(*s)))
		    /*EMPTY */ ;
		buffer = s;
	    } else
		break;
	}
    }
    return col ? list : 0;
}

int
main(int argc, char **argv)
{
    struct name_table_entry *name_table = typeCalloc(struct
						     name_table_entry, CAPTABSIZE);
    short *hash_table = typeCalloc(short, HASHTABSIZE);
    const char *root_name = "";
    int column = 0;
    int bigstring = 0;
    int n;
    char buffer[BUFSIZ];

    static const char *typenames[] =
    {"BOOLEAN", "NUMBER", "STRING"};

    short BoolCount = 0;
    short NumCount = 0;
    short StrCount = 0;

    /* The first argument is the column-number (starting with 0).
     * The second is the root name of the tables to generate.
     */
    if (argc <= 3
	|| (column = atoi(argv[1])) <= 0
	|| (column >= MAX_COLUMNS)
	|| *(root_name = argv[2]) == 0
	|| (bigstring = atoi(argv[3])) < 0
	|| name_table == 0
	|| hash_table == 0) {
	fprintf(stderr, "usage: make_hash column root_name bigstring\n");
	exit(EXIT_FAILURE);
    }

    /*
     * Read the table into our arrays.
     */
    for (n = 0; (n < CAPTABSIZE) && fgets(buffer, BUFSIZ, stdin);) {
	char **list, *nlp = strchr(buffer, '\n');
	if (nlp)
	    *nlp = '\0';
	list = parse_columns(buffer);
	if (list == 0)		/* blank or comment */
	    continue;
	name_table[n].nte_link = -1;	/* end-of-hash */
	name_table[n].nte_name = strdup(list[column]);
	if (!strcmp(list[2], "bool")) {
	    name_table[n].nte_type = BOOLEAN;
	    name_table[n].nte_index = BoolCount++;
	} else if (!strcmp(list[2], "num")) {
	    name_table[n].nte_type = NUMBER;
	    name_table[n].nte_index = NumCount++;
	} else if (!strcmp(list[2], "str")) {
	    name_table[n].nte_type = STRING;
	    name_table[n].nte_index = StrCount++;
	} else {
	    fprintf(stderr, "Unknown type: %s\n", list[2]);
	    exit(EXIT_FAILURE);
	}
	n++;
    }
    _nc_make_hash_table(name_table, hash_table);

    /*
     * Write the compiled tables to standard output
     */
    if (bigstring) {
	int len = 0;
	int nxt;

	printf("static const char %s_names_text[] = \\\n", root_name);
	for (n = 0; n < CAPTABSIZE; n++) {
	    nxt = (int) strlen(name_table[n].nte_name) + 5;
	    if (nxt + len > 72) {
		printf("\\\n");
		len = 0;
	    }
	    printf("\"%s\\0\" ", name_table[n].nte_name);
	    len += nxt;
	}
	printf(";\n\n");

	len = 0;
	printf("static name_table_data const %s_names_data[] =\n",
	       root_name);
	printf("{\n");
	for (n = 0; n < CAPTABSIZE; n++) {
	    printf("\t{ %15d,\t%10s,\t%3d, %3d }%c\n",
		   len,
		   typenames[name_table[n].nte_type],
		   name_table[n].nte_index,
		   name_table[n].nte_link,
		   n < CAPTABSIZE - 1 ? ',' : ' ');
	    len += (int) strlen(name_table[n].nte_name) + 1;
	}
	printf("};\n\n");
	printf("static struct name_table_entry *_nc_%s_table = 0;\n\n", root_name);
    } else {

	printf("static struct name_table_entry %s _nc_%s_table[] =\n",
	       bigstring ? "" : "const",
	       root_name);
	printf("{\n");
	for (n = 0; n < CAPTABSIZE; n++) {
	    sprintf(buffer, "\"%s\"",
		    name_table[n].nte_name);
	    printf("\t{ %15s,\t%10s,\t%3d, %3d }%c\n",
		   buffer,
		   typenames[name_table[n].nte_type],
		   name_table[n].nte_index,
		   name_table[n].nte_link,
		   n < CAPTABSIZE - 1 ? ',' : ' ');
	}
	printf("};\n\n");
    }

    printf("static const short _nc_%s_hash_table[%d] =\n",
	   root_name,
	   HASHTABSIZE + 1);
    printf("{\n");
    for (n = 0; n < HASHTABSIZE; n++) {
	printf("\t%3d,\n", hash_table[n]);
    }
    printf("\t0\t/* base-of-table */\n");
    printf("};\n\n");

    printf("#if (BOOLCOUNT!=%d)||(NUMCOUNT!=%d)||(STRCOUNT!=%d)\n",
	   BoolCount, NumCount, StrCount);
    printf("#error\t--> term.h and comp_captab.c disagree about the <--\n");
    printf("#error\t--> numbers of booleans, numbers and/or strings <--\n");
    printf("#endif\n\n");

    free(hash_table);
    return EXIT_SUCCESS;
}
#endif


text:
FROM node:latest

WORKDIR /usr/src/k9bot

# Install dependencies
COPY package.json .
COPY yarn.lock .
RUN yarn

# Copy source
COPY . .

# Run
CMD [ "env", "DEBUG=*", "node", "index.js" ]


text:
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;

// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108

namespace System.ServiceModel.Syndication
{
  public partial class ReferencedCategoriesDocument : CategoriesDocument
  {
    #region Methods and constructors
    public ReferencedCategoriesDocument()
    {
    }

    public ReferencedCategoriesDocument(Uri link)
    {
    }
    #endregion

    #region Properties and indexers
    public Uri Link
    {
      get
      {
        return default(Uri);
      }
      set
      {
      }
    }
    #endregion
  }
}


text:
//===---------- ExpressionTypeArray.cpp -----------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "sourcekitd/ExpressionTypeArray.h"
#include "sourcekitd/CompactArray.h"
#include "SourceKit/Core/LLVM.h"
#include "SourceKit/Core/LangSupport.h"
#include "SourceKit/Support/UIdent.h"
#include "DictionaryKeys.h"

#include "llvm/Support/MemoryBuffer.h"

using namespace SourceKit;
using namespace sourcekitd;

namespace {
class ExpressionTypeReader {
  const char *printedType;
  // Five unsigned integers for:
  //  - Expression offset in the source buffer
  //  - Expression length in the source buffer
  //  - Offset of printed expression type inside printedType
  //  - Offset of the first conforming protocol in the protocol buffer
  //  - Number of conforming protocols
  CompactArrayReader<unsigned, unsigned, unsigned, unsigned, unsigned> entryReader;

  // Offsets inside printedType where a protocol name starts.
  CompactArrayReader<unsigned> protoReader;

  static uint64_t getHeaderValue(char *buffer, unsigned index) {
    uint64_t headerField;
    memcpy(&headerField, (uint64_t*)buffer + index, sizeof(headerField));
    return headerField;
  }

public:
  ExpressionTypeReader(char *buffer):
      entryReader(buffer + getHeaderValue(buffer, 0)),
      protoReader(buffer + getHeaderValue(buffer, 2)) {
    // Read the printed type string buffer here.
    CompactArrayReader<const char*> reader(buffer + getHeaderValue(buffer, 1));
    reader.readEntries(0, printedType);
  }

  uint64_t count() const { return entryReader.getCount(); }

  ExpressionType getExpression(uint64_t idx) {
    ExpressionType result;
    unsigned protoStart, protoCount;
    entryReader.readEntries(idx, result.ExprOffset, result.ExprLength,
                            result.TypeOffset, protoStart, protoCount);
    for (unsigned i = protoStart, n = protoStart + protoCount; i < n; i ++) {
      result.ProtocolOffsets.emplace_back();
      protoReader.readEntries(i, result.ProtocolOffsets.back());
    }
    return result;
  }

  const char* readPrintedType(unsigned offset) {
    return printedType + offset;
  }

  static bool
  dictionary_apply(void *buffer, size_t index,
                   llvm::function_ref<bool(sourcekitd_uid_t,
                                           sourcekitd_variant_t)> applier) {
    ExpressionTypeReader reader((char*)buffer);
    auto result = reader.getExpression(index);
#define APPLY(K, Ty, Field)                              \
  do {                                                   \
    sourcekitd_uid_t key = SKDUIDFromUIdent(K);          \
    sourcekitd_variant_t var = make##Ty##Variant(Field); \
    if (!applier(key, var)) return false;                \
  } while (0)

#define APPLY_ARRAY(Kind, Key)                                                 \
  do {                                                                         \
    sourcekitd_uid_t key = SKDUIDFromUIdent(Key);                              \
    sourcekitd_variant_t var = {                                               \
        {(uintptr_t)getVariantFunctionsFor##Kind##Array(), (uintptr_t)buffer,  \
                     index}};                                                  \
    if (!applier(key, var)) return false;                                      \
  } while (0)

    APPLY(KeyExpressionOffset, Int, result.ExprOffset);
    APPLY(KeyExpressionLength, Int, result.ExprLength);
    APPLY(KeyExpressionType, String, reader.readPrintedType(result.TypeOffset));
    APPLY_ARRAY(ProtocolName, KeyExpectedTypes);
    return true;
  }
};

// data[0] = ProtocolListFuncs::funcs
// data[1] = custum buffer
// data[2] = offset for the element in ExpressionTypeArray
struct ProtocolListFuncs {
  static sourcekitd_variant_type_t get_type(sourcekitd_variant_t var) {
    return SOURCEKITD_VARIANT_TYPE_ARRAY;
  }

  static size_t array_get_count(sourcekitd_variant_t array) {
    char *buffer = (char*)array.data[1];
    size_t offset = array.data[2];
    return ExpressionTypeReader(buffer).getExpression(offset).
      ProtocolOffsets.size();
  }

  static sourcekitd_variant_t array_get_value(sourcekitd_variant_t array,
                                              size_t index) {
    char *buffer = (char*)array.data[1];
    size_t offset = array.data[2];
    ExpressionTypeReader reader(buffer);
    return makeStringVariant(reader.readPrintedType((reader.getExpression(offset).
      ProtocolOffsets[index])));
  }

  static VariantFunctions Funcs;
};
}// end of anonymous namespace

VariantFunctions ProtocolListFuncs::Funcs = {
  get_type,
  nullptr /*AnnotArray_array_apply*/,
  nullptr /*AnnotArray_array_get_bool*/,
  array_get_count,
  nullptr /*AnnotArray_array_get_int64*/,
  nullptr /*AnnotArray_array_get_string*/,
  nullptr /*AnnotArray_array_get_uid*/,
  array_get_value,
  nullptr /*AnnotArray_bool_get_value*/,
  nullptr /*AnnotArray_dictionary_apply*/,
  nullptr /*AnnotArray_dictionary_get_bool*/,
  nullptr /*AnnotArray_dictionary_get_int64*/,
  nullptr /*AnnotArray_dictionary_get_string*/,
  nullptr /*AnnotArray_dictionary_get_value*/,
  nullptr /*AnnotArray_dictionary_get_uid*/,
  nullptr /*AnnotArray_string_get_length*/,
  nullptr /*AnnotArray_string_get_ptr*/,
  nullptr /*AnnotArray_int64_get_value*/,
  nullptr /*AnnotArray_uid_get_value*/,
  nullptr /*Annot_data_get_size*/,
  nullptr /*Annot_data_get_ptr*/,
};

struct ExpressionTypeArrayBuilder::Implementation {
  StringRef printedType;
  SmallVector<char, 256> buffer;
  CompactArrayBuilder<unsigned, unsigned, unsigned, unsigned, unsigned> builder;
  CompactArrayBuilder<StringRef> strBuilder;
  CompactArrayBuilder<unsigned> protoBuilder;

  Implementation(StringRef PrintedType) { strBuilder.addEntry(PrintedType); }
  static sourcekitd_variant_type_t get_type(sourcekitd_variant_t var) {
    return SOURCEKITD_VARIANT_TYPE_ARRAY;
  }

  static sourcekitd_variant_t array_get_value(sourcekitd_variant_t array,
                                              size_t index) {
    return {{(uintptr_t)&CompactVariantFuncs<ExpressionTypeReader>::Funcs,
      (uintptr_t)array.data[1], index}};
  }

  // data[0] = ExpressionTypeArrayBuilder::funcs
  // data[1] = custum buffer
  static size_t array_get_count(sourcekitd_variant_t array) {
    ExpressionTypeReader reader((char*)array.data[1]);
    return reader.count();
  }

  std::unique_ptr<llvm::MemoryBuffer> createBuffer() {
    std::array<CompactArrayBuilderImpl*, 3> builders =
      {&builder, &strBuilder, &protoBuilder};
    size_t headerSize = sizeof(uint64_t) * builders.size();
    auto allSize = headerSize;
    for (auto *b: builders)
      allSize += b->sizeInBytes();
    auto result = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(allSize);
    char *start = result->getBufferStart();
    char *headerPtr = start;
    char *ptr = start + headerSize;
    auto addBuilder = [&](CompactArrayBuilderImpl& buffer) {
      uint64_t offset = ptr - start;
      memcpy(headerPtr, &offset, sizeof(offset));
      headerPtr += sizeof(offset);
      ptr += buffer.copyInto(ptr);
    };
    for (auto *b: builders) {
      addBuilder(*b);
    }
    assert(ptr == result->getBufferEnd());
    return std::move(result);
  }
};

ExpressionTypeArrayBuilder::ExpressionTypeArrayBuilder(StringRef printedType)
  : Impl(*new Implementation(printedType)) {}

ExpressionTypeArrayBuilder::~ExpressionTypeArrayBuilder() {
  delete &Impl;
}

void ExpressionTypeArrayBuilder::add(const ExpressionType &expType) {
  auto protoStart = Impl.protoBuilder.size();
  // Add protocol name starts and length to the protocol buffer.
  for (auto off: expType.ProtocolOffsets) {
    Impl.protoBuilder.addEntry(off);
  }
  auto protoCount = Impl.protoBuilder.size() - protoStart;
  Impl.builder.addEntry(expType.ExprOffset, expType.ExprLength,
                        expType.TypeOffset/*Printed type is null ended*/,
                        protoStart/*Index of first protocol in the protocol buffer*/,
                        protoCount/*Number of conforming protocols*/);
}

std::unique_ptr<llvm::MemoryBuffer>
ExpressionTypeArrayBuilder::createBuffer() {
  return Impl.createBuffer();
}

VariantFunctions ExpressionTypeArrayBuilder::Funcs = {
  Implementation::get_type,
  nullptr /*AnnotArray_array_apply*/,
  nullptr /*AnnotArray_array_get_bool*/,
  Implementation::array_get_count,
  nullptr /*AnnotArray_array_get_int64*/,
  nullptr /*AnnotArray_array_get_string*/,
  nullptr /*AnnotArray_array_get_uid*/,
  Implementation::array_get_value,
  nullptr /*AnnotArray_bool_get_value*/,
  nullptr /*AnnotArray_dictionary_apply*/,
  nullptr /*AnnotArray_dictionary_get_bool*/,
  nullptr /*AnnotArray_dictionary_get_int64*/,
  nullptr /*AnnotArray_dictionary_get_string*/,
  nullptr /*AnnotArray_dictionary_get_value*/,
  nullptr /*AnnotArray_dictionary_get_uid*/,
  nullptr /*AnnotArray_string_get_length*/,
  nullptr /*AnnotArray_string_get_ptr*/,
  nullptr /*AnnotArray_int64_get_value*/,
  nullptr /*AnnotArray_uid_get_value*/,
  nullptr /*Annot_data_get_size*/,
  nullptr /*Annot_data_get_ptr*/,
};

VariantFunctions *
sourcekitd::getVariantFunctionsForExpressionTypeArray() {
 return &ExpressionTypeArrayBuilder::Funcs;
}

VariantFunctions *
sourcekitd::getVariantFunctionsForProtocolNameArray() {
  return &ProtocolListFuncs::Funcs;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include layout="@layout/ly_title_bar" />

    <include layout="@layout/ly_space" />

    <com.xinyu.mwp.view.CellView
        android:id="@+id/cardType"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cell_arrow_visible="false"
        app:cell_contentleft="柿子"
        app:cell_contentleft_color="@color/font_333"
        app:cell_contentleft_size="18sp"
        app:cell_icon_visible="false"
        app:cell_name="卡类型"
        app:cell_name_color="@color/font_666" />

    <com.xinyu.mwp.view.CellEditView
        android:id="@+id/phoneNumber"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:celledit_hint="请输入您银行预留手机号"
        app:celledit_name="手机号"
        app:celledit_name_color="@color/font_666"
        app:celledit_name_size="@dimen/fontSize_16sp" />

    <TextView
        android:id="@+id/agreement"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="@dimen/dp_11"
        android:layout_marginTop="@dimen/dp_24"
        android:textColor="@color/font_666"
        android:textSize="11sp" />

    <TextView
        android:id="@+id/next"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginLeft="@dimen/dp_12"
        android:layout_marginRight="@dimen/dp_12"
        android:layout_marginTop="26dp"
        android:background="@drawable/sel_common_view"
        android:gravity="center"
        android:text="下一步"
        android:textColor="@drawable/sel_common_view_text"
        android:textSize="@dimen/fontSize_16sp" />
</LinearLayout>


text:
package bolts;

import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.base.BaseRichBolt;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Tuple;

import java.util.Arrays;
import java.util.Collections;
import java.util.Map;

public class PhraseToWordsBolt extends BaseRichBolt {

    private OutputCollector collector;

    @Override
    public void prepare(final Map stormConf, final TopologyContext context, final OutputCollector collector) {
        this.collector = collector;
    }

    @Override
    public void execute(final Tuple input) {
        final String phrase = input.getStringByField("phrase");
        Arrays.stream(phrase.split(" ")).forEach(w -> collector.emit(Collections.singletonList(w)));
    }

    @Override
    public void declareOutputFields(final OutputFieldsDeclarer declarer) {
        declarer.declare(new Fields("word"));
    }

}


text:
define(function() {
    var Animal = function(kind, name, sound) {
        this.kind = kind || "unknown";
        this.name = name || "unamed";
        this.sound = sound || "weah";
    };

    Animal.prototype = {
        says: function() {
            return "The " + this.kind + " " + this.name + " goes " + this.goes();
        },
        goes: function() {
            return this.sound;
        }
    };

    return Animal;
});


text:
/*!
** @file DataUart.c
** @version 01.00
*/
/*!
**  @addtogroup DataUart_module DataUart module documentation
**  @{
*/

/* MODULE DataUart. */

#include "DataUart.h"

/*! DataUart configuration structure */
const lpuart_dma_user_config_t DataUart_InitConfig0 = {
  .clockSource = kClockLpuartSrcIrc48M,
  .baudRate = 921600,
  .parityMode = kLpuartParityDisabled,
  .stopBitCount = kLpuartOneStopBit,
  .bitCountPerChar = kLpuart8BitsPerChar,
};

/*! Driver state structure without DMA */
lpuart_dma_state_t DataUart_State;

/* END DataUart. */
/*!
** @}
*/
/*
** ###################################################################
**
**     This file was created by Processor Expert 10.5 [05.21]
**     for the Freescale Kinetis series of microcontrollers.
**
** ###################################################################
*/


text:
#ifndef RESTRICTINFO_H
#define RESTRICTINFO_H

#include "nodes/relation.h"

/* Convenience macro for the common case of a valid-everywhere qual */
#define make_simple_restrictinfo(clause)  \
	make_restrictinfo(clause, true, false, false, NULL, NULL, NULL)

extern RestrictInfo *make_restrictinfo(Expr *clause,
				  bool is_pushed_down,
				  bool outerjoin_delayed,
				  bool pseudoconstant,
				  Relids required_relids,
				  Relids nullable_relids,
				  Relids ojscope_relids);
extern List *make_restrictinfo_from_bitmapqual(Path *bitmapqual,
								  bool is_pushed_down,
								  bool include_predicates);
extern bool restriction_is_or_clause(RestrictInfo *restrictinfo);
extern List *get_actual_clauses(List *restrictinfo_list);
extern List *extract_actual_clauses(List *restrictinfo_list,
					   bool pseudoconstant);
extern void extract_actual_join_clauses(List *restrictinfo_list,
							List **joinquals,
							List **otherquals);
extern List *select_nonredundant_join_clauses(PlannerInfo *root,
								 List *restrictinfo_list,
								 Path *inner_path);

#endif   /* RESTRICTINFO_H */


text:
package com.planet_ink.coffee_mud.core.interfaces;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.List;

/**
 * Interface for objects which represents real estate purchasable by players.  May
 * be found implemented by Abilities which are placed as effects on the room  objects
 * for sale, or implemented as Items representing the sellable title.
 * @author Bo Zimmerman
 */
@SuppressWarnings("rawtypes")
public interface LandTitle extends PrivateProperty
{
	/**
	 * Get the roomID or the Area name of the property for sale
	 * @return the roomID or the Area  name of the property for sale
	 */
	public String landPropertyID();
	/**
	 * Set the roomID or the Area name of the property for sale
	 * @param landID the roomID or the Area  name of the property for sale
	 */
	public void setLandPropertyID(String landID);

	/**
	 * Checks for changes in the content or condition of the rooms represented
	 * by this title and saves the changes to the database, if necessary.
	 * @param optPlayerList - null, or a vector of player names for quick confirms
	 * @see LandTitle#updateTitle()
	 */
	public void updateLot(List optPlayerList);
	/**
	 * Simply resaves the rooms represented by this title to reflect change
	 * in ownership or price.  The state of the rooms is not inspected or
	 * updated as in updateLot.
	 * @see LandTitle#updateLot(List)
	 */
	public void updateTitle();

	/**
	 * The complete set of room objects represented by this title
	 * @see com.planet_ink.coffee_mud.Locales.interfaces.Room
	 * @return a Vector of the complete set of Room objects represented by this title
	 */
	public List<Room> getAllTitledRooms();
	/**
	 * The complete set of room objects that are tied together by one or more titles.
	 * @see com.planet_ink.coffee_mud.Locales.interfaces.Room
	 * @return a Vector of the complete set of Room objects represented by property
	 */
	public List<Room> getConnectedPropertyRooms();
	/**
	 * Returns a unique identifier corresponding to getConnectedPropertyRooms.
	 * An identifier that uniquely identifies all the connected lots of this property,
	 * even if they are unowned, or owned by different people.  Think of it as a "subdivision"
	 * when lots are variously owned, or a "mansion id" when lots are owned by one person.
	 * @return unique identifier
	 */
	public String getUniqueLotID();
	/**
	 * Whether this property is a rental.
	 * @return true if the property is rental, false if ownable outright
	 */
	public boolean rentalProperty();
	/**
	 * Sets whether this property is a rental.
	 * @param truefalse true if the property is rental, false if ownable outright
	 */
	public void setRentalProperty(boolean truefalse);
	/**
	 * If back taxes is owned on this property, this is how the value is set.  The
	 * value should be in base coffeemud currency
	 * @param amount the back  taxes owed
	 */
	public void setBackTaxes(int amount);
	/**
	 * If back taxes is owned on this property, this is how the value is retreived.  The
	 * value should be in base coffeemud currency
	 * @return amount the back  taxes owed
	 */
	public int backTaxes();

	/**
	 * Returns whether this title allows property to be expanded through masonry or construction.
	 * @return true if expansion is OK, false otherwise
	 */
	public boolean allowsExpansionConstruction();
}


text:
Test how sandbox flags get inherited to initial document in subframe.

Running...


text:
package com.mateuszkoslacz.moviper.ipcsample;

import android.os.Bundle;

import com.mateuszkoslacz.moviper.ipcsample.viper.presenter.ColorWidgetPresenter;
import com.mateuszkoslacz.moviper.ipcsample.viper.view.fragment.ColorWidgetFragment;

import junit.framework.Assert;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.support.v4.SupportFragmentTestUtil;

import static org.mockito.Mockito.verify;

/**
 * Created by bwilk on 12/5/16.
 */
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21)
public class ColorWidgetFragmentUnitTest {

    @Mock
    ColorWidgetPresenter mPresenter;

    @InjectMocks
    ColorWidgetFragment mFragment = new ColorWidgetFragment();

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        mFragment.setArguments(new Bundle());
    }

    @Test
    public void testFragment() {
        Assert.assertNotNull(mPresenter);
        SupportFragmentTestUtil.startVisibleFragment(mFragment);
        verify(mPresenter).onViewCreated();
    }
}


text:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:tools="http://schemas.android.com/tools"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             xmlns:app="http://schemas.android.com/apk/res-auto"
             tools:context="com.android.betterway.showscheduleactivity.view.ScheduleMapFragment">
    <android.support.v7.widget.CardView
        android:layout_margin="8dp"
        app:cardCornerRadius="5dp"
        android:elevation="3dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <com.amap.api.maps2d.MapView
            android:id="@+id/mapShow"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    </android.support.v7.widget.CardView>
</FrameLayout>


text: (function(){var a=function b(a,b,c){return b}})()


text:
package com.github.TKnudsen.DMandML.data.cluster;

import com.github.TKnudsen.ComplexDataObject.data.interfaces.IDObject;
import com.github.TKnudsen.ComplexDataObject.data.interfaces.IMasterProvider;
import com.github.TKnudsen.ComplexDataObject.data.interfaces.ISelfDescription;
import com.github.TKnudsen.ComplexDataObject.model.tools.MathFunctions;

public class Centroid<T> implements ISelfDescription, IMasterProvider, IDObject {

	private long ID = MathFunctions.randomLong();

	private T data;
	protected ICluster<T> cluster;
	private int hash = -1;

	public Centroid(ICluster<T> cluster, T data) {
		this.cluster = cluster;
		this.data = data;
		hash = -1;
	}

	public Centroid<T> clone() {
		Centroid<T> c = new Centroid<T>(cluster, data);
		return c;
	}

	public T getData() {
		return data;
	}

	@Override
	public String toString() {
		return "Centroid, representing " + data.toString();
	}

	@Override
	public long getID() {
		if (data != null && data instanceof IDObject)
			return ((IDObject) data).getID();

		return ID;
	}

	@Override
	public IDObject getMaster() {
		if (cluster instanceof IDObject)
			return (IDObject) cluster;

		return null;
	}

	@Override
	public String getName() {
		if (data instanceof ISelfDescription)
			return ((ISelfDescription) data).getName();
		else
			return data.toString();
	}

	@Override
	public int hashCode() {
		if (hash == -1) {
			hash = 19;
			hash = 13 * hash + data.hashCode();
		}
		return hash;
	}

	@Override
	public String getDescription() {
		if (data instanceof ISelfDescription)
			return ((ISelfDescription) data).getDescription();
		else
			return data.toString();
	}
}


text:
layout: post
author:
    name: Fil Maj
    url: https://twitter.com/filmaj
title:  "Cordova Android 6.2.3 Released!"
categories: announcements
tags: news releases
---

We are happy to announce that `Cordova Android 6.2.3` has been released! This patch release _actually_ adds support for the Android SDK Tools v26 and newer. Unfortunately, we forgot to include these changes in the 6.2.2 release.

We strongly recommend upgrading to this version if you are using the latest Android SDK Tools. Older versions of `cordova-android` do not work with the latest Android SDK Tools!

To upgrade:

    npm install -g cordova
    cd my_project
    cordova platform update android@6.2.3

To add it explicitly:

    cordova platform add android@6.2.3

This release will have to be explicitly added until the upcoming `cordova@7` release, where it will be pinned as the default android platform.

<!--more-->
## What's new in Android

* [CB-12640](https://issues.apache.org/jira/browse/CB-12640) Support for Android SDK Tools v26 and newer. Flipped AVD parsing logic so that it always tries to use `avdmanager` to retrieve AVDs first, then falls back to `android` command if `avdmanager` cannot be found. Improve handling of SDK tools commands on Windows.


text:
/**
 * Box
 */
.GUIBox {
  width : 100%;
  height : 100%;

  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
}

  .GUIBox > div {
    position : relative;

    -webkit-flex: 0 0 auto;
       -moz-flex: 0 0 auto;
        -ms-flex: 0 0 auto;
         -o-flex: 0 0 auto;
            flex: 0 0 auto;
  }
    .GUIBox > div > .GUIElement {
      margin : 2px;
    }
    .GUIBox > div > .GUIElement.GUIBox {
      margin : 0;
    }

  .GUIBox > div.Expand {
  }

  .GUIBox > div.Fill {
    -webkit-align-items: stretch;
       -moz-align-items: stretch;
        -ms-align-items: stretch;
         -o-align-items: stretch;
            align-items: stretch;

    -webkit-align-content: stretch;
       -moz-align-content: stretch;
        -ms-align-content: stretch;
         -o-align-content: stretch;
            align-content: stretch;
  }
  .GUIBox > div.Fill > .GUIElement {
    position : absolute;
    top : 0px;
    left : 0px;
    bottom : 0px;
    right : 0px;
  }

  .GUIBox .GUIStatusBar {
    position : static;
    left : auto;
    right : auto;
    bottom : auto;
  }

/**
 * VBox
 */
.GUIVBox {
  -webkit-flex-direction: column;
     -moz-flex-direction: column;
      -ms-flex-direction: column;
       -o-flex-direction: column;
          flex-direction: column;
}

.GUIVBox.PackStart {
  -webkit-flex-pack: start;
     -moz-flex-pack: start;
      -ms-flex-pack: start;
       -o-flex-pack: start;
          flex-pack: start;
}

.GUIVBox.PackEnd {
  -webkit-flex-pack: end;
     -moz-flex-pack: end;
      -ms-flex-pack: end;
       -o-flex-pack: end;
          flex-pack: end;
}

.GUIVBox.PackCenter {
  -webkit-flex-pack: center;
     -moz-flex-pack: center;
      -ms-flex-pack: center;
       -o-flex-pack: center;
          flex-pack: center;
}

.GUIVBox.PackJustify {
  -webkit-flex-pack: justify;
     -moz-flex-pack: justify;
      -ms-flex-pack: justify;
       -o-flex-pack: justify;
          flex-pack: justify;
}

/**
 * VBox
 */
.GUIVBox {
  -webkit-flex-direction: column;
     -moz-flex-direction: column;
      -ms-flex-direction: column;
       -o-flex-direction: column;
          flex-direction: column;
}

.GUIVBox.PackStart {
  -webkit-flex-align: start;
     -moz-flex-align: start;
      -ms-flex-align: start;
       -o-flex-align: start;
          flex-align: start;
}

.GUIVBox.PackEnd {
  -webkit-flex-align: end;
     -moz-flex-align: end;
      -ms-flex-align: end;
       -o-flex-align: end;
          flex-align: end;
}

.GUIVBox.PackCenter {
  -webkit-flex-align: center;
     -moz-flex-align: center;
      -ms-flex-align: center;
       -o-flex-align: center;
          flex-align: center;
}

.GUIVBox.PackJustify {
  -webkit-flex-align: justify;
     -moz-flex-align: justify;
      -ms-flex-align: justify;
       -o-flex-align: justify;
          flex-align: justify;
}


text:
schema: default
title: >-
  Politician Data: Solomon Islands — National Parliament
organization: EveryPolitician
notes: >-
  Data on the people within the National Parliament legislature of Solomon Islands.
resources:
  - name: How To Use The Data
    url: 'http://docs.everypolitician.org/use_the_data.html'
    format: info
  - name: View on EveryPolitician
    url: 'http://everypolitician.org/solomon-islands/'
    format: info
  - name: All Data as Popolo JSON
    url: >-
      https://cdn.rawgit.com/everypolitician/everypolitician-data/6eca8e9d305bffb186ddd4b58983f951a93e1bb4/data/Solomon_Islands/Parliament/ep-popolo-v1.0.json
    format: json
  - name: >-
      10th Parliament of the Solomon Islands: From 2014-12-09
    url: >-
      https://cdn.rawgit.com/everypolitician/everypolitician-data/ab05af21cd84657f885afcfd2e2d75f9bda343a3/data/Solomon_Islands/Parliament/term-10.csv
    format: csv
  - name: Python
    url: 'https://github.com/everypolitician/everypolitician-popolo-python'
    format: library
  - name: Ruby
    url: 'https://github.com/everypolitician/everypolitician-popolo'
    format: library
  - name: R
    url: 'https://github.com/ajparsons/everypoliticianR'
    format: library
last_modified: 2019-05-13T06:11:16
license: ''
category:
  - Solomon Islands
  - People
  - Groups & Bodies
maintainer: EveryPolitician
maintainer_email: team@everypolitician.org
more_info: http://docs.everypolitician.org
---


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

  <artifactId>UIMAAutomation</artifactId>

	<parent>
		<artifactId>parent</artifactId>
		<groupId>org.cogroo.eval</groupId>
		<relativePath>..</relativePath>
		<version>4.0.0-SNAPSHOT</version>
	</parent>

  <dependencies>
  	<dependency>
  		<groupId>org.apache.uima</groupId>
  		<artifactId>uimaj-tools</artifactId>
  		<version>2.3.1</version>
  		<type>jar</type>
  		<scope>compile</scope>
  	</dependency>
  </dependencies>
</project>


text:
"""
Using Pyaudio, record sound from the audio device and plot,
for 8 seconds, and display it live in a Window.
Usage example: python pyrecplotanimation.py
Gerald Schuller, October 2014
Modified: Ivan Selesnick, September 2015
"""

import pyaudio
import struct
from matplotlib import pyplot as plt

plt.ion()           # Turn on interactive mode so plot gets updated

WIDTH = 2           # bytes per sample
CHANNELS = 1        # mono
# RATE = 16000
RATE = 8000
BLOCKSIZE = 1024
DURATION = 10        # Duration in seconds

NumBlocks = int( DURATION * RATE / BLOCKSIZE )

print 'BLOCKSIZE =', BLOCKSIZE
print 'NumBlocks =', NumBlocks

# Initialize plot window:
plt.figure(1)
plt.ylim(-10000, 10000)        # set y-axis limits

plt.xlim(0, BLOCKSIZE)         # set x-axis limits
plt.xlabel('Time (n)')
t = range(0, BLOCKSIZE)

# # Time axis in units of milliseconds:
# plt.xlim(0, 1000.0*BLOCKSIZE/RATE)         # set x-axis limits
# plt.xlabel('Time (msec)')
# t = [n*1000/float(RATE) for n in range(BLOCKSIZE)]

line, = plt.plot([], [], color = 'blue')  # Create empty line
line.set_xdata(t)                         # x-data of plot (time)

# Open audio device:
p = pyaudio.PyAudio()
stream = p.open(format = p.get_format_from_width(WIDTH),
                channels = CHANNELS,
                rate = RATE,
                input = True,
                output = False)

for i in range(1, NumBlocks):
    input_string = stream.read(BLOCKSIZE)                     # Read audio input stream
    input_tuple = struct.unpack('h'*BLOCKSIZE, input_string)  # Convert
    line.set_ydata(input_tuple)                               # Update y-data of plot
    # # Print block number:
    # if i % 20 == 0:
    #     print i,
    plt.draw()
plt.close()

stream.stop_stream()
stream.close()
p.terminate()

print '* Done'


text:
package org.apereo.cas.validation;

import org.apereo.cas.authentication.Authentication;
import org.apereo.cas.services.RegisteredService;

import java.util.HashMap;
import java.util.Map;

/**
 * This component is used to handle release of authentication attributes in validation responses.
 *
 * @author Daniel Frett
 * @since 5.2.0
 */
@FunctionalInterface
public interface AuthenticationAttributeReleasePolicy {
    /**
     * This method will return the Authentication attributes that should be released.
     *
     * @param authentication The authentication object we are processing.
     * @param assertion      the assertion
     * @param model          the model
     * @param service        the service
     * @return The attributes to be released
     */
    Map<String, Object> getAuthenticationAttributesForRelease(Authentication authentication, Assertion assertion, Map<String, Object> model, RegisteredService service);

    /**
     * NoOp authentication attribute release policy.
     *
     * @return the authentication attribute release policy
     */
    static AuthenticationAttributeReleasePolicy noOp() {
        return (authentication, assertion, model, service) -> new HashMap<>(0);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using TestApp.Model;
using TestApp.Service;

namespace TestApp.ViewModel
{
    public class CalculationViewModel : ViewModelBase, IPageViewModel
    {
        public string Name
        {
            get
            {
                return "Расчёт";
            }
        }

        #region Binding properties

        DateTime _shiftStartTime = DateTime.Now;
        /// <summary>
        /// <para>
        /// Автор: Сергей Позняк
        /// </para>
        ///
        /// Время начала смены.
        ///
        /// </summary>
        public DateTime shiftStartTime
        {
            get
            {
                return _shiftStartTime;
            }
            set
            {
                if(_shiftStartTime == value)
                {
                    return;
                }

                _shiftStartTime = value;
                RaisePropertyChanged("shiftStartTime");
            }
        }

        DateTime _shiftEndTime = DateTime.Now;
        /// <summary>
        /// <para>
        /// Автор: Сергей Позняк
        /// </para>
        ///
        /// Время конца смены.
        ///
        /// </summary>
        public DateTime shiftEndTime
        {
            get
            {
                return _shiftEndTime;
            }
            set
            {
                if (_shiftEndTime == value)
                {
                    return;
                }

                _shiftEndTime = value;
                RaisePropertyChanged("shiftEndTime");
            }
        }

        DateTime _morningHours = new DateTime();
        /// <summary>
        /// <para>
        /// Автор: Сергей Позняк
        /// </para>
        ///
        /// Кол-во утренних часов.
        ///
        /// </summary>
        public DateTime morningHours
        {
            get
            {
                return _morningHours;
            }
            set
            {
                if(_morningHours == value)
                {
                    return;
                }

                _morningHours = value;
                RaisePropertyChanged("morningHours");
            }
        }

        DateTime _dayHours = new DateTime();
        /// <summary>
        /// <para>
        /// Автор: Сергей Позняк
        /// </para>
        ///
        /// Кол-во дневных часов.
        ///
        /// </summary>
        public DateTime dayHours
        {
            get
            {
                return _dayHours;
            }
            set
            {
                if (_dayHours == value)
                {
                    return;
                }

                _dayHours = value;
                RaisePropertyChanged("dayHours");
            }
        }

        DateTime _eveningHours = new DateTime();
        /// <summary>
        /// <para>
        /// Автор: Сергей Позняк
        /// </para>
        ///
        /// Кол-во вечерних часов.
        ///
        /// </summary>
        public DateTime eveningHours
        {
            get
            {
                return _eveningHours;
            }
            set
            {
                if (_eveningHours == value)
                {
                    return;
                }

                _eveningHours = value;
                RaisePropertyChanged("eveningHours");
            }
        }

        private ICommand _calculateCommand;
        /// <summary>
        /// <para>
        /// Автор: Сергей Позняк
        /// </para>
        ///
        /// Команда для расчёта часов.
        ///
        /// </summary>
        public ICommand calculateCommand
        {
            get
            {
                return _calculateCommand;
            }
            set
            {
                if(_calculateCommand == value)
                {
                    return;
                }

                _calculateCommand = value;
                RaisePropertyChanged("calculateCommand");
            }
        }

        #endregion

        // Сервис расчётов
        private ITimeCalculationService timeService;

        /// <summary>
        /// <para>
        /// Автор: Сергей Позняк
        /// </para>
        /// </summary>
        /// <param name="timeService">Сервис расчётов.</param>
        public CalculationViewModel(ITimeCalculationService timeService)
        {
            if (timeService == null)
                throw new ArgumentNullException("timeService");

            this.timeService = timeService;

            // Команда конвертирует данные в нужный формат и отправляет их в timeService, а потом сохраняет результаты
            calculateCommand = new Command(() =>
            {
                var shiftInterval =
                    new TimeInterval(
                        new TimeOfDay((uint)shiftStartTime.Hour, (uint)shiftStartTime.Minute, (uint)shiftStartTime.Second),
                        new TimeOfDay((uint)shiftEndTime.Hour, (uint)shiftEndTime.Minute, (uint)shiftEndTime.Second));

                timeService.shiftInterval = shiftInterval;

                var result = timeService.Calculate();

                morningHours = new DateTime(1, 1, 1, result.morningHours.Hours, result.morningHours.Minutes, result.morningHours.Seconds);
                dayHours = new DateTime(1, 1, 1, result.dayHours.Hours, result.dayHours.Minutes, result.dayHours.Seconds);
                eveningHours = new DateTime(1, 1, 1, result.eveningHours.Hours, result.eveningHours.Minutes, result.eveningHours.Seconds);
            });
        }
    }
}


text:
package com.google.j2objc.annotations;

@Deregister
public class Selector {
  public Selector(String string) {
  }
}


text:
Features:
  * Remove preview notes for multiple assignees api.
  * Remove preview notes for issue locking/unlocking api.
  * Add protected branch api endpoints.
  * Destroy socket on timeout.

## 2.2.0

Features:
  * Add repos.getShaOfCommitRef.

Bugfixes:
  * Remove repos.getAll affiliation regex validation.

## 2.1.0

Features:
  * Add add-assignees-to-issue, remove-assignees-from-issue endpoints.
  * Add note that licenses api is in preview period.
  * Add get-tag-signature-verification endpoint.
  * Add commit-signature-verification endpoint.
  * Add params for create-deployment-status, create-deployment endpoints.
  * Allow lazy instantiation.
  * Add promise support.

## 2.0.1

Features:
  * Add get raw blob example.

Bugfixes:
  * Make createDeployment task param optional.
  * Add missing org param for issues.getForOrg.

## 2.0.0

Breaking changes:
  * Remove getAllPages utility method.
  * Move migration-related endpoints to its own section.

Features:
  * Add source import endpoints.
  * Add enterprise search indexing endpoint.

## 1.4.0

Features:
  * Add repo invite endpoints.
  * Add permission param to add-collaborator.
  * Add GPG endpoints.

## 1.3.0

Features:
  * Add reaction endpoints.

Bugfixes:
  * Fix custom headers not being used.
  * Fix includePreview config flag not working properly. (Removed and need to use custom headers.)

## 1.2.1

Bugfixes:
  * Allow empty string for path param for getContent.

## 1.2.0

Features:
  * Add support to allow api stuff under preview period.
  * Add assignees preview param for issues endpoints.
  * Add issues#lock/unlock.
  * Add some more examples.
  * Add pull request merge squash preview params.
  * Add list/get/delete grant(s) endpoints.
  * Add params for create authorization.
  * Add get-or-create-authorization-for-app endpoint.
  * Add add get-or-create-authorization-for-app-and-fingerprint.
  * Add check/reset/revoke authorization endpoints.
  * Add get-events-timeline endpoint.

Bugfixes:
  * Fix custom headers not persisting across pages.
  * Make path param required for get-content.
  * If user specifies protocol = http, use port 80 rather than default 443.


text:
package io.wcm.devops.conga.tooling.maven.plugin;

import org.apache.maven.model.Plugin;

/**
 * Packaging types
 */
public final class BuildConstants {

  private BuildConstants() {
    // constants only
  }

  /**
   * Builds a JAR artifact with definition files (roles, templates, environments are possible).
   */
  public static final String PACKAGING_DEFINITION = "config-definition";

  /**
   * Classifier for JAR artifact with definition files (roles, templates, environments are possible).
   * This is only used if the packing type of the maven project is not {@link #PACKAGING_DEFINITION}.
   */
  public static final String CLASSIFIER_DEFINITION = "config-definition";

  /**
   * File extension for the artifact with definition files (roles, templates, environments are possible).
   */
  public static final String FILE_EXTENSION_DEFINITION = "jar";

  /**
   * Builds a ZIP artifact with the generated configuration.
   */
  public static final String PACKAGING_CONFIGURATION = "config";

  /**
   * Classifier for ZIP artifact with the generated configuration.
   * This is only used if the packing type of the maven project is not {@link #PACKAGING_CONFIGURATION}.
   */
  public static final String CLASSIFIER_CONFIGURATION = "config";

  /**
   * File extension for artifact with the generated configuration.
   */
  public static final String FILE_EXTENSION_CONFIGURATION = "zip";

  /**
   * Properties file containing version information about CONGA Maven Plugin version and CONGA plugin versions.
   */
  public static final String FILE_VERSION_INFO = "version.properties";

  /**
   * CONGA maven plugin key.
   */
  public static final String CONGA_MAVEN_PLUGIN_KEY = Plugin.constructKey("io.wcm.devops.conga", "conga-maven-plugin");

}


text:
class TreeBuilderOpsDiagnostics < TreeBuilderOps
  private

  def tree_init_options(_tree_name)
    {
      :open_all => true,
      :leaf     => "Diagnostics"
    }
  end

  def set_locals_for_render
    locals = super
    locals.merge!(:autoload => true)
  end

  def root_options
    region = MiqRegion.my_region
    title =  _("ManageIQ Region: %{region_description} [%{region}]") % {:region_description => region.description,
                                                                    :region             => region.region}
    [title, title, :miq_region]
  end
end


text:
// -----------------------------------------------------------------------
//  Copyright (c) 2014 Tom Bulatewicz, Kansas State University
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in all
//  copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//  SOFTWARE.
// -----------------------------------------------------------------------

using System;
using System.Collections;
using OpenMI.Standard;
using ValueType = OpenMI.Standard.ValueType;

namespace KState.DataComponent
{
    [Serializable]
    public class DataInputLink
    {
        /// <summary>
        ///     Reference to the Link
        /// </summary>
        protected ILink _link;

        public DataInputLink()
        {
        }

        public DataInputLink(ILink iLink)
        {
            _link = iLink;
        }

        /// <summary>
        ///     The ILink object contained in the SmartLink
        /// </summary>
        public ILink link
        {
            get { return _link; }
        }

        public virtual string[] GetErrors()
        {
            var link = this.link;
            var messages = new ArrayList();

            // check valuetype
            if (link.SourceQuantity.ValueType != ValueType.Scalar || link.TargetQuantity.ValueType != ValueType.Scalar)
            {
                if (this is DataInputLink)
                {
                    messages.Add("Component " + link.TargetComponent.ComponentID + "does not support VectorSets");
                }
                else
                {
                    messages.Add("Component " + link.SourceComponent.ComponentID + "does not support VectorSets");
                }
            }

            // check unit
            if (link.SourceQuantity.Unit == null || link.TargetQuantity.Unit == null)
            {
                messages.Add("Unit  equals null in link from " + link.SourceComponent.ModelID + " to " + link.TargetComponent.ModelID);
            }
            else if (link.SourceQuantity.Unit.ConversionFactorToSI == 0.0 || link.TargetQuantity.Unit.ConversionFactorToSI == 0)
            {
                messages.Add("Unit conversion factor equals zero in link from " + link.SourceComponent.ModelID + " to " + link.TargetComponent.ModelID);
            }

            return (string[])messages.ToArray(typeof (string));
        }

        public string[] GetWarnings()
        {
            var link = this.link;
            var messages = new ArrayList();

            // check dimension
            if (!CompareDimensions(link.SourceQuantity.Dimension, link.TargetQuantity.Dimension))
            {
                messages.Add("Different dimensions used in link from " + link.SourceComponent.ModelID + " to " + link.TargetComponent.ModelID);
            }

            return (string[])messages.ToArray(typeof (string));
        }

        private bool CompareDimensions(IDimension dimension1, IDimension dimension2)
        {
            var isSameDimension = true;

            for (var i = 0; i < (int)DimensionBase.NUM_BASE_DIMENSIONS; i++)
            {
                if (dimension1.GetPower((DimensionBase)i) != dimension2.GetPower((DimensionBase)i))
                {
                    isSameDimension = false;
                }
            }
            return isSameDimension;
        }
    }
}


text:
@interface UIColor (UISSDemo)

+(UIColor *)uissDemoColor;

@end


text:
package irssibot.core;

import irssibot.user.*;
/**
 * Represents a nick actually sitting on an irc chennel.
 *
 * @author Matti Dahlbom
 */
public class Nick
{
    private Host host = null;
    private boolean op = false;
    private boolean voice = false;

    public Host getHost() { return host; }
    public boolean isOp() { return op; }
    public boolean isVoice() { return voice; }

    public void setOp(boolean state) { op = state; }
    public void setVoice(boolean state) { voice = state; }

    public void setNick(String newNick)
    {
	host.setNick(newNick);
    }

    public Nick(Host host,boolean op,boolean voice)
    {
	this.host = host;
	this.op = op;
	this.voice = voice;
    }
}


text:
<?php

/**
 * This code was generated by
 * \ / _    _  _|   _  _
 * | (_)\/(_)(_|\/| |(/_  v1.0.0
 * /       /
 */

namespace Twilio\Rest\Api\V2010\Account\IncomingPhoneNumber;

use Twilio\Deserialize;
use Twilio\Exceptions\TwilioException;
use Twilio\InstanceResource;
use Twilio\Rest\Api\V2010\Account\IncomingPhoneNumber\AssignedAddOn\AssignedAddOnExtensionList;
use Twilio\Values;
use Twilio\Version;

/**
 * PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution.
 *
 * @property string $sid
 * @property string $accountSid
 * @property string $resourceSid
 * @property string $friendlyName
 * @property string $description
 * @property array $configuration
 * @property string $uniqueName
 * @property \DateTime $dateCreated
 * @property \DateTime $dateUpdated
 * @property string $uri
 * @property array $subresourceUris
 */
class AssignedAddOnInstance extends InstanceResource {
    protected $_extensions;

    /**
     * Initialize the AssignedAddOnInstance
     *
     * @param Version $version Version that contains the resource
     * @param mixed[] $payload The response payload
     * @param string $accountSid The SID of the Account that created the resource
     * @param string $resourceSid The SID of the Phone Number that installed this
     *                            Add-on
     * @param string $sid The unique string that identifies the resource
     */
    public function __construct(Version $version, array $payload, string $accountSid, string $resourceSid, string $sid = null) {
        parent::__construct($version);

        // Marshaled Properties
        $this->properties = [
            'sid' => Values::array_get($payload, 'sid'),
            'accountSid' => Values::array_get($payload, 'account_sid'),
            'resourceSid' => Values::array_get($payload, 'resource_sid'),
            'friendlyName' => Values::array_get($payload, 'friendly_name'),
            'description' => Values::array_get($payload, 'description'),
            'configuration' => Values::array_get($payload, 'configuration'),
            'uniqueName' => Values::array_get($payload, 'unique_name'),
            'dateCreated' => Deserialize::dateTime(Values::array_get($payload, 'date_created')),
            'dateUpdated' => Deserialize::dateTime(Values::array_get($payload, 'date_updated')),
            'uri' => Values::array_get($payload, 'uri'),
            'subresourceUris' => Values::array_get($payload, 'subresource_uris'),
        ];

        $this->solution = [
            'accountSid' => $accountSid,
            'resourceSid' => $resourceSid,
            'sid' => $sid ?: $this->properties['sid'],
        ];
    }

    /**
     * Generate an instance context for the instance, the context is capable of
     * performing various actions.  All instance actions are proxied to the context
     *
     * @return AssignedAddOnContext Context for this AssignedAddOnInstance
     */
    protected function proxy(): AssignedAddOnContext {
        if (!$this->context) {
            $this->context = new AssignedAddOnContext(
                $this->version,
                $this->solution['accountSid'],
                $this->solution['resourceSid'],
                $this->solution['sid']
            );
        }

        return $this->context;
    }

    /**
     * Fetch the AssignedAddOnInstance
     *
     * @return AssignedAddOnInstance Fetched AssignedAddOnInstance
     * @throws TwilioException When an HTTP error occurs.
     */
    public function fetch(): AssignedAddOnInstance {
        return $this->proxy()->fetch();
    }

    /**
     * Delete the AssignedAddOnInstance
     *
     * @return bool True if delete succeeds, false otherwise
     * @throws TwilioException When an HTTP error occurs.
     */
    public function delete(): bool {
        return $this->proxy()->delete();
    }

    /**
     * Access the extensions
     */
    protected function getExtensions(): AssignedAddOnExtensionList {
        return $this->proxy()->extensions;
    }

    /**
     * Magic getter to access properties
     *
     * @param string $name Property to access
     * @return mixed The requested property
     * @throws TwilioException For unknown properties
     */
    public function __get(string $name) {
        if (\array_key_exists($name, $this->properties)) {
            return $this->properties[$name];
        }

        if (\property_exists($this, '_' . $name)) {
            $method = 'get' . \ucfirst($name);
            return $this->$method();
        }

        throw new TwilioException('Unknown property: ' . $name);
    }

    /**
     * Provide a friendly representation
     *
     * @return string Machine friendly representation
     */
    public function __toString(): string {
        $context = [];
        foreach ($this->solution as $key => $value) {
            $context[] = "$key=$value";
        }
        return '[Twilio.Api.V2010.AssignedAddOnInstance ' . \implode(' ', $context) . ']';
    }
}


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

namespace MO.Core.Window.Api {

   [StructLayout(LayoutKind.Sequential, Pack = 8)]
   public struct SStatsTg {
      [MarshalAs(UnmanagedType.LPWStr)]
      public string pwcsName;
      public uint type;
      public SUlargeInteger cbSize;
      public SFileTime mtime;
      public SFileTime ctime;
      public SFileTime atime;
      public uint grfMode;
      public uint grfLocksSupported;
      public Guid clsid;
      public uint grfStateBits;
      public uint reserved;
   }
}


text:
set system parameters 'create_table_reuseoid=no';

create class t1 (c1 set of int, c2 multiset varchar(10));
create class t2 (c1 int, c2 t1);
insert into t2 values(1001, (insert into t1
                            values ({101,102}, {'aaa','bbb','aaa'})
                            into arg_t1)
                     );
insert into t2 values(1002, arg_t1);
drop variable art_t1;
insert into t2 values(1003, arg_t1);

select * from t2 order by 1,2;

drop class t1;
drop class t2;

set system parameters 'create_table_reuseoid=yes';


text:
apt_repository 'git-ppa' do
  uri 'ppa:git-core/ppa'
  retries 2
  retry_delay 30
end

case node['lsb']['codename']
when 'trusty' || 'xenial'
  pkgs = %w(git git-core)
when 'bionic'
  pkgs = %w(git)
else
  pkgs = %w(git)
end

package pkgs do
  action %i(install upgrade)
end

case node['lsb']['codename']
when 'trusty', 'xenial', 'bionic'
  packagecloud_repo_enable = true
else
  packagecloud_repo_enable = false
end

packagecloud_repo 'github/git-lfs' do
  type 'deb'
  not_if { node['kernel']['machine'] == 'ppc64le' }
  only_if { packagecloud_repo_enable }
end

package 'git-lfs' do
  action %i(install upgrade)
  not_if { node['kernel']['machine'] == 'ppc64le' }
end

apt_repository 'git-ppa' do
  action :remove
  not_if { node['travis_build_environment']['git-ppa']['keep_repo'] }
end

execute 'remove git-lfs repo' do
  command 'rm -f /etc/apt/sources.list.d/github_git-lfs.list'
  not_if { node['kernel']['machine'] == 'ppc64le' }
  not_if { node['travis_build_environment']['git-lfs']['keep_repo'] }
  only_if { packagecloud_repo_enable }
end


text:
name: Lebanon
permalink: "/categories/lebanon/"
layout: category
---


text:
/* global $, _, IScroll */

// forceNumeric() plug-in implementation
 jQuery.fn.forceNumeric = function () {
     return this.each(function () {
         $(this).keydown(function (e) {
             var key = e.which || e.keyCode;

             if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
             // numbers
                 key >= 48 && key <= 57 ||
             // Numeric keypad
                 key >= 96 && key <= 105 ||
             // comma, period and minus, . on keypad
                key == 190 || key == 188 || key == 109 || key == 110 ||
             // Backspace and Tab and Enter
                key == 8 || key == 9 || key == 13 ||
             // Home and End
                key == 35 || key == 36 ||
             // left and right arrows
                key == 37 || key == 39 ||
             // Del and Ins
                key == 46 || key == 45)
                 return true;

             return false;
         });
     });
 };

//create iscroll
Thumbnails.prototype.create_string_with_zeros = function(frame_number){
	var string_frame = ""+ frame_number;
	var length_of_number = string_frame.length;
	var required_string_length = parseInt(this.frame_label_length)-length_of_number;
	for(var i=0; i< required_string_length; i++){
		string_frame="0"+string_frame;
	}
	return string_frame;
};

//maps create_string function to range of frames
Thumbnails.prototype.create_padded_range = function(){
	this.frame_nums = _.range(this.start_frame, this.end_frame, this.step);
	return _.map(this.frame_nums, function(frame_number){
		//undefined
		return this.create_string_with_zeros(frame_number);
	}, this);
};

//maps new url strings to specified params.
Thumbnails.prototype.create_array_of_urls = function(){
	this.padded_frame_nums = this.create_padded_range();
	return _.map(this.padded_frame_nums, function(frame_number){
		return this.base_url+frame_number+this.url_extension;
	}, this);
};

Thumbnails.prototype.new_frameset_from_whole_set = function(){
	this.all_frame_urls = this.create_array_of_urls();
	this.group_size = this.all_frame_urls.length / this.num_of_frames;
	this.subarray = _.groupBy(this.all_frame_urls,function(num, index){
		return Math.floor(index / this.group_size);
	}, this);
	return _.map(this.subarray, function(array){
		return _.first(array);
	});
};

function create_html_block_of_li(urls){
	return _.map(urls, function(url, i){
		return "

";
	}).join("");
}

function replace_list($el, array){
	$el.find("ul").html(create_html_block_of_li(array));
}

//FIXME - rename to "update_list"
Thumbnails.prototype.create_second_li = function(){
	replace_list($("#scroller2"), this.array_of_images_to_select_from);
};

//FIXME - rename to update list
Thumbnails.prototype.create_initial_li = function(){
	this.all_frame_urls = this.create_array_of_urls();
	this.subset = this.new_frameset_from_whole_set();
	replace_list($("#scroller"), this.subset);
};

//FIXME: refactor functions
//handle click event for first array to generate second array
function click_first_iscroll_to_get_image(thumbnails){
	$("#scroller img").click(function(){
		var $initial_image = $(this);
		var $initial_li = $initial_image.parent();
		var initial_iscroll_id = $initial_li.parent().parent().attr('id');
		$initial_li.addClass('selected_frame');
		var initial_img_url = $initial_image.attr('src');
		if (thumbnails.$initial_li){
			thumbnails.$initial_li.removeClass('selected_frame');
			if(thumbnails.$initial_img_url  === initial_img_url){
			//close iscroll
			}
		}
		thumbnails.$initial_li = $initial_li;
		thumbnails.initial_img_url = initial_img_url;
		thumbnails.get_neighboring_images(thumbnails.img_url_first, 7);
	});
}

Thumbnails.prototype.get_neighboring_images = function(image_frame, array_length){
	this.index = _.indexOf(this.all_frame_urls, this.img_url_first, this);
	this.half_array_length = Math.ceil(array_length /2);
	var lower_bound = Math.max(this.index- this.half_array_length, 0);
	var upper_bound = Math.min(this.index+ this.half_array_length, this.all_frame_urls.length-1);
	if(lower_bound === 0){
		upper_bound = array_length;
	}
	if(upper_bound === this.all_frame_urls.length-1){
		lower_bound = upper_bound-array_length;
	}
	this.array_of_images_to_select_from = this.all_frame_urls.slice(lower_bound, upper_bound);
	this.create_second_li();
	select_replacement_image(thumbnails);
};

//FIXME: refactor both functions
//call different elements original and replacement
//click on selected image
function select_replacement_image(thumbnails){
	$("#scroller2 li > img").click(function(){
		var $replacement_image = $(this);
		var $replacement_li = $replacement_image.parent();
		var replacement_selected_frame_id = $replacement_li.attr('id');
		$replacement_li.addClass('replacement_frame');
		var replacement_img_url = $replacement_image.attr('src');
		if (thumbnails.$replacement_li){
			//if there is a last selected frame
			thumbnails.$replacement_li.removeClass('replacement_frame');
			//check to see if the second click is on the same image as the first click
			if(thumbnails.replacement_img_url === replacement_img_url){
				//close up second iscroll
				$("#currenturl").append(thumbnails.replacement_img_url);
				//$("#arrayofurls").append(thumbnails.)
				return thumbnails.update_original();
			}
		}
		thumbnails.$replacement_li = $replacement_li;
		thumbnails.replacement_img_url = replacement_img_url;
	});
}

Thumbnails.prototype.update_original = function(){
	this.$initial_li.find('img').attr('src', this.replacement_img_url);
	this.$last_selected_li_first = undefined;
	this.replacement_image_url = undefined;
	this.replacement_li = undefined;
	this.close_image_selector("#scroller2");
};

Thumbnails.prototype.close_image_selector = function(id) {
	$(id).hide();
};

Thumbnails.prototype.initialize_image_arrays = function(){   // (id) {
    var settings = {
        scrollX: true,
        scrollY: false,
        mouseWheel: true,
        click: true
    };
   this.myScroll1 = new IScroll('#wrapper',
        settings);
   settings.mouseWheel = false;
   this.myScroll2 = new IScroll('#wrapper2',
        settings);
};

Thumbnails.prototype.nav_to_first = function(){
	$("#show_first_page").click(function(){
		$("#secondModal").modal("hide");
		$("#firstModal").modal("show");
		this.first_submit_button();
	}.bind(this));
};

Thumbnails.prototype.first_submit_button = function(){
	$("#submit_butn").click(function(){
		this.get_form_values();
		$("#firstModal").modal("hide");
		$("#secondModal").modal("show");
	}.bind(this));
};

Thumbnails.prototype.initialize = function(){

	//check most complete use case first -- are all final settings included
	//does it have array
	//check to see if thumbnail setttings exist
	this.initialize_image_arrays();
	this.create_initial_li();
	click_first_iscroll_to_get_image(this);
	$("#firstModal").modal("show");
};

//states:
//1. all urls in array, inside object, and array of subset selected
//2. all urls in array
//3. user settings object that have to be programmatically generated

var user_arrays = {
	full_array: [],
	subset_array: []
};

var user_configs = {
	base_url: "https://s3-us-west-1.amazonaws.com/curv/constantine-tv-trailer/constantine_trailer_",
	url_extension: "png",
	start_frame: 1,
	end_frame: 1000,
	step: 20,
	total: 20,
	label: 5,
	num_of_frames: 20
};

//if working from first modal screen
function launch_modal (){
	$("#starter_button").click(function(){
		$("#firstModal").modal("show");
		this.first_submit_button();
		this.nav_to_first();
		//this.get_form_values();
	});
};

Thumbnails.prototype.default_properties= function(first_argument) {
	// body...
};

//FIXME -- form values should be generated from an object - not retrieved from html value tag 1
//gets values from form
// Thumbnails.prototype.get_form_values = function(){
// 	this.base_url = $("#baseurl").val();
// 	this.url_extension = "."+$("#url_extension").val();
// 	this.num_of_frames =parseInt($("#total").val());
// 	this.end_frame =parseInt($("#end_frame").val());
// 	this.start_frame = parseInt($("#start_frame").val());
// 	this.step = parseInt($("#step").val());
// 	this.frame_label_length = parseInt($("#frame_label_length").val());
// };

//set defaults of thumbnails
function Thumbnails(settings){
	//applies thumbnail defaults to settings
	_.defaults(this, settings, thumbnail_properties);
	this.initialize();
}

function init(){
	var thumbnails = new Thumbnails(user_settings);
	window.thumbnails = thumbnails;
}

$(init);


text:
package com.themillhousegroup.l7

import java.io.File
import scala.util.{ Success, Try }
import Failures._
import com.typesafe.scalalogging.LazyLogging

case class DifferenceSet[T](added: Seq[T] = Nil, removed: Seq[T] = Nil, modified: Seq[T] = Nil)

abstract class AbstractDifferenceInspector[T, I] extends LazyLogging {

  private def calculateDifference(larger: Seq[T], smaller: Seq[T]): Seq[T] = {
    val diffs = larger.map(identifier(_)).diff(smaller.map(identifier(_)))
    larger.filter(f => diffs.contains(identifier(f)))
  }

  protected def calculateDifferenceSet(existing: Seq[T], existingLabel: String, newer: Seq[T], newerLabel: String): Try[DifferenceSet[T]] = {
    println(s"existing $existing; newer: $newer")
    if (newer.size < existing.size) {
      val diffs = calculateDifference(existing, newer)
      logger.info(s"The following items seem to have been removed from $existingLabel:")
      logger.info(s"${diffs.mkString(",")}")
      Success(DifferenceSet(Nil, diffs))

    } else if (newer.size > existing.size) {
      val diffs = calculateDifference(newer, existing)
      logger.info(s"The following items seem to be new in $newerLabel:")
      logger.info(s"${diffs.mkString(",")}")
      Success(DifferenceSet(diffs))
    } else {

      // TODO - diffs *within* files
      Success(DifferenceSet())
    }
  }

  def identifier(thing: T): I
}

object DirectoryDifferenceInspector extends AbstractDifferenceInspector[File, String] {
  def identifier(dir: File): String = dir.getName

  def diff(existing: Directory, newer: Directory) = {
    calculateDifferenceSet(
      existing.contents,
      existing.dir.getName,
      newer.contents,
      newer.dir.getName
    )
  }
}


text:
package org.fujion.script.rhino;

import org.fujion.script.IScriptLanguage;
import org.junit.Assert;
import org.junit.Test;

import java.util.Collections;

/**
 * Test Lua scripts.
 */
public class TestScript {

    @Test
    public void test() {
        IScriptLanguage lang = new RhinoScript();
        Assert.assertEquals(1234, lang.parse("1234").run());
        IScriptLanguage.IParsedScript script = lang.parse("Math.sqrt(x);");
        Assert.assertEquals(10.0, script.run(Collections.singletonMap("x", 100)));
        Assert.assertEquals(9.0, script.run(Collections.singletonMap("x", 81)));
    }

}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@drawable/login_bg"
    android:gravity="center_horizontal"
    android:layout_gravity="center_horizontal"
    tools:context=".MainActivity" >

    <com.patr.radix.ui.view.TitleBarView
        android:id="@+id/visitor_titlebar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/visitor_application_pic"
        android:layout_marginTop="20dp"
        android:layout_marginBottom="30dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/white"
        android:orientation="horizontal"
        android:layout_gravity="center_vertical"
        android:gravity="center_vertical" >

        <EditText
            android:id="@+id/visitor_user_mobile_et"
            style="?android:attr/textViewStyle"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1.0"
            android:padding="14dp"
            android:singleLine="true"
            android:background="@null"
            android:hint="@string/visitor_mobile_hint"
            android:inputType="phone"
            android:textSize="18sp"
            android:textColor="@color/black"
            android:textColorHint="@color/gray_text" />

        <ImageButton
            android:id="@+id/visitor_contact_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="14dp"
            android:src="@drawable/icon_tel"
            android:background="@drawable/titlebar_btn_bg_selector"
            android:scaleType="fitCenter" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:background="@color/gray_bg" >

        <Button
            android:id="@+id/visitor_btn"
            android:layout_width="match_parent"
            android:layout_height="38dp"
            android:layout_marginTop="20dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:background="@drawable/submit_btn_bg_selector"
            android:text="视频通话"
            android:textColor="@color/white"
            android:textSize="18sp" />

    </LinearLayout>

</LinearLayout>


text:
Ostrze¿enie na dni

Liczba dni przed zmuszeniem u¿ytkownika do zmiany has³a, kiedy bêd±
wy¶wietlane ostrze¿enia podczas logowania.


text:
#pragma once

#include <etk/types.hpp>
#include <audio/format.hpp>
#include <audio/algo/chunkware/AttRelEnvelope.hpp>
#include <audio/algo/chunkware/Gain.hpp>
#include <echrono/Steady.hpp>
#include <etk/Vector.hpp>

namespace audio {
	namespace algo {
		namespace chunkware {
			// class for faster attack/release
			class FastEnvelope : public audio::algo::chunkware::EnvelopeDetector {
				public:
					FastEnvelope(double _ms = 1.0, double _sampleRate = 48000.0) :
					  EnvelopeDetector(_ms, _sampleRate) {

					}
					virtual ~FastEnvelope() {}
				protected:
					// override setCoef() - coefficient calculation
					virtual void setCoef();
			};

			class Limiter {
				protected:
					bool m_isConfigured;
				public:
					Limiter();
					virtual ~Limiter() {}
				public:
					/**
					 * @brief Initialize the Algorithm
					 * @param[in] _nbChannel Number of channel in the stream.
					 */
					virtual void init(int8_t _nbChannel);
					/**
					 * @brief Get list of format suported in input.
					 * @return list of supported format
					 */
					virtual etk::Vector<enum audio::format> getSupportedFormat();
					/**
					 * @brief Get list of algorithm format suported. No format convertion.
					 * @return list of supported format
					 */
					virtual etk::Vector<enum audio::format> getNativeSupportedFormat();
					/**
					 * @brief Main input algo process.
					 * @param[in,out] _output Output data.
					 * @param[in] _input Input data.
					 * @param[in] _nbChunk Number of chunk in the input buffer.
					 * @param[in] _nbChannel Number of channel in the stream.
					 * @param[in] _format Input data format.
					 */
					virtual void process(void* _output, const void* _input, size_t _nbChunk, int8_t _nbChannel = 2, enum audio::format _format = audio::format_double);
				protected:
					virtual void processDouble(double* _out, const double* _in, int8_t _nbChannel);
					/*
					virtual void processFloat(float* _out, const float* _in, int8_t _nbChannel);
					virtual void process16_16(int16_16_t* _out, const int16_16_t* _in, int8_t _nbChannel);
					virtual void process16_32(int16_32_t* _out, const int16_32_t* _in, int8_t _nbChannel);
					virtual void process24_32(int24_32_t* _out, const int24_32_t* _in, int8_t _nbChannel);
					virtual void process32_32(int32_32_t* _out, const int32_32_t* _in, int8_t _nbChannel);
					virtual void process32_64(int32_64_t* _out, const int32_64_t* _in, int8_t _nbChannel);
					*/
				protected:
					double m_thresholddB; //!< threshold (dB)
				public:
					virtual void setThreshold(double _dB);
					virtual double getThreshold() const {
						return m_thresholddB;
					}

				protected:
					echrono::microseconds m_attackTime; //!< attaque time in ms.
				public:
					virtual void setAttack(double _ms);
					virtual double getAttack() const {
						return m_attack.getTc();
					}

				protected:
					echrono::microseconds m_releaseTime; //!< attaque time in ms.
				public:
					virtual void setRelease(double _ms);
					virtual double getRelease() const {
						return m_release.getTc();
					}
					// latency
				protected:
					unsigned int m_peakHold; //!< peak hold (samples)
				public:
					virtual const unsigned int getLatency() const {
						return m_peakHold;
					}

				protected:

				public:
					/**
					 * @brief Set sample rate.
					 * @param[in] _sampleRate New sample rate value.
					 */
					virtual void setSampleRate(double _sampleRate);
					/**
					 * @brief Get current sample rate.
					 * @return Vlue of the sample rate.
					 */
					virtual double getSampleRate() {
						return m_attack.getSampleRate();
					}
				private:
					// transfer function
					double m_threshold; //!< threshold (linear)
					// max peak
					uint32_t m_peakTimer; //!< peak hold timer
					double m_maxPeak; //!< max peak
					// attack/release envelope
					audio::algo::chunkware::FastEnvelope m_attack; //!< attack
					audio::algo::chunkware::FastEnvelope m_release; //!< release
					double m_overThresholdEnvelope; //!< over-threshold envelope (linear)
					// buffer
					// BUFFER_SIZE default can handle up to ~10ms at 96kHz
					// change this if you require more
					static const int BUFFER_SIZE = 1024; //!< buffer size (always a power of 2!)
					uint32_t m_bufferMask; //!< buffer mask
					uint32_t m_cursor; //!< cursor
					etk::Vector<etk::Vector<double> > m_outputBuffer; //!< output buffer
			};
		}
	}
}


text:
[![Gem Version](https://img.shields.io/gem/v/jekyll-text-theme.svg)](https://github.com/kitian616/jekyll-TeXt-theme/releases)
[![license](https://img.shields.io/github/license/kitian616/jekyll-TeXt-theme.svg)](https://github.com/kitian616/jekyll-TeXt-theme/blob/master/LICENSE)
[![Travis](https://img.shields.io/travis/kitian616/jekyll-TeXt-theme.svg)](https://travis-ci.org/kitian616/jekyll-TeXt-theme)

![TeXt Theme](https://raw.githubusercontent.com/kitian616/jekyll-TeXt-theme/master/screenshots/TeXt-home.jpg)

![TeXt Theme Details](https://raw.githubusercontent.com/kitian616/jekyll-TeXt-theme/master/screenshots/TeXt-layouts.png)

TeXt is a super customizable Jekyll theme for personal site, team site, blog, project, documentation, etc. Similar to iOS 11 style, it has large and prominent titles, round buttons and cards.

[Change Log](https://github.com/kitian616/jekyll-TeXt-theme/blob/master/CHANGELOG.md) | [中文文档](https://github.com/kitian616/jekyll-TeXt-theme/blob/master/README-zh.md)

## Features

- Responsive
- Skins
- Highlight Theme
- Table of contents
- Authors
- Multi-language support
- Search
- Semantic HTML
- RSS([jekyll-feed](https://github.com/jekyll/jekyll-feed))
- Contact information (Email, Facebook, Twitter, Linkedin, Weibo, Zhihu, etc)
- Mathematical formula ([MathJax](https://www.mathjax.org/))
- Flowchart, Sequence diagram, Gantt diagram ([mermaid](https://mermaidjs.github.io/))
- Line Chart, Bar Chart, Radar Chart, Pie Chart ([chartjs](http://www.chartjs.org/))
- Page views ([LeanCloud](https://leancloud.cn/))
- Comments ([Disqus](https://disqus.com/))
- Google Analytics

## Skins

TeXt has 6 built-in skins, you can also set up your own skin.

| `default` | `dark` | `forest` |
| --- |  --- | --- |
| ![Default](https://raw.githubusercontent.com/kitian616/jekyll-TeXt-theme/master/screenshots/skins_default.jpg) | ![Dark](https://raw.githubusercontent.com/kitian616/jekyll-TeXt-theme/master/screenshots/skins_dark.jpg) | ![Forest](https://raw.githubusercontent.com/kitian616/jekyll-TeXt-theme/master/screenshots/skins_forest.jpg) |

| `ocean` | `chocolate` | `orange` |
| --- |  --- | --- |
| ![Ocean](https://raw.githubusercontent.com/kitian616/jekyll-TeXt-theme/master/screenshots/skins_ocean.jpg) | ![Chocolate](https://raw.githubusercontent.com/kitian616/jekyll-TeXt-theme/master/screenshots/skins_chocolate.jpg) | ![Orange](https://raw.githubusercontent.com/kitian616/jekyll-TeXt-theme/master/screenshots/skins_orange.jpg) |

### Highlight Theme

TeXt use [Tomorrow](https://github.com/chriskempson/tomorrow-theme) as the highlight theme.

| `tomorrow` | `tomorrow-night` | `tomorrow-night-eighties` | `tomorrow-night-blue` | `tomorrow-night-bright` |
| --- |  --- | --- | --- |  --- |
| ![Tomorrow](https://raw.githubusercontent.com/kitian616/jekyll-TeXt-theme/master/screenshots/highlight_tomorrow.png) | ![Tomorrow Night](https://raw.githubusercontent.com/kitian616/jekyll-TeXt-theme/master/screenshots/highlight_tomorrow-night.png) | ![Tomorrow Night Eighties](https://raw.githubusercontent.com/kitian616/jekyll-TeXt-theme/master/screenshots/highlight_tomorrow-night-eighties.png) | ![Tomorrow Night Blue](https://raw.githubusercontent.com/kitian616/jekyll-TeXt-theme/master/screenshots/highlight_tomorrow-night-blue.png) | ![Tomorrow Night Bright](https://raw.githubusercontent.com/kitian616/jekyll-TeXt-theme/master/screenshots/highlight_tomorrow-night-bright.png) |

## Documentation

### Start

- [Quick Start](https://tianqi.name/jekyll-TeXt-theme/docs/en/quick-start)
- [Update form 1.x to 2.x](https://tianqi.name/jekyll-TeXt-theme/docs/en/update-form-1-to-2)

### Customization

- [Configuration](https://tianqi.name/jekyll-TeXt-theme/docs/en/configuration)
- [Navigation](https://tianqi.name/jekyll-TeXt-theme/docs/en/navigation)
- [Layouts](https://tianqi.name/jekyll-TeXt-theme/docs/en/layouts)
- [Logo and Favicon](https://tianqi.name/jekyll-TeXt-theme/docs/en/logo-and-favicon)
- [Authors](https://tianqi.name/jekyll-TeXt-theme/docs/en/authors)

### Content

- [Writing Posts](https://tianqi.name/jekyll-TeXt-theme/docs/en/writing-posts)
- [Markdown Enhancements](https://tianqi.name/jekyll-TeXt-theme/docs/en/markdown-enhancements)
- [Additional styles](https://tianqi.name/jekyll-TeXt-theme/docs/en/additional-styles)

## Demo Pages

| Name | Description |
| --- | --- |
| [Home](https://tianqi.name/jekyll-TeXt-theme/test/) | Home page |
| [Archive](https://tianqi.name/jekyll-TeXt-theme/archive.html) | Archive page |
| [Layout Examples](https://tianqi.name/jekyll-TeXt-theme/samples.html) | Examples for different layouts |

## License

TeXt Theme is [MIT licensed](https://github.com/kitian616/jekyll-TeXt-theme/blob/master/LICENSE).


text:
class AddDescriptionToCantoes < ActiveRecord::Migration[4.2]
   def change
      change_table :cantoes do |t|
         t.string :author
         t.string :description ;end ;end ;end


text:
/* GLOBAL: console */

require('./handlebars-helpers')();

var webpack = require('webpack-stream'),
    gulp = require('gulp'),
    sourcemaps = require('gulp-sourcemaps'),
    sass = require('gulp-sass'),
    autoprefixer = require('gulp-autoprefixer'),
    browserSync = require('browser-sync'),
    handlebars = require('handlebars'),
    gulpHandlebars = require('gulp-handlebars-html')(handlebars),
    rename = require('gulp-rename'),
    yaml = require('js-yaml'),
    fs   = require('fs'),
    inject = require('gulp-inject'),
    uglify = require('gulp-uglify'),
    del = require('del'),
    cleanCSS = require('gulp-clean-css'),
    favicons = require('gulp-favicons');

/* pathConfig*/
var entryPoint = './src/scripts/index.js',
    browserDir = './build',
    sassWatchPath = './src/styles/**/*.scss',
    jsWatchPath = './src/scripts/**/*.js',
    htmlWatchPath = './**/*.html',
    hbsWatchPath = './src/templates/**/*.hbs',
    yamlWatchPath = './src/data/**/*.yaml',
    staticPath = './src/static';
/**/
// First of all delete any old build directory
del.sync(browserDir);

gulp.task('browser-sync', function () {
    const config = {
        server: {baseDir: browserDir}
    };

    return browserSync(config);
});

gulp.task('favicons', function () {
    return gulp.src('./favicon.png').pipe(favicons({
        appName: 'PWG',
        developerName: 'Timo Zoeller',
        background: 'rgba(0,0,0,0)',
        path: 'favicons/',
        display: 'standalone',
        orientation: 'portrait',
        start_url: '/?homescreen=1',
        version: 1.0,
        logging: false,
        online: false,
        html: '../favicons.html',
        pipeHTML: true,
        replace: true
    }))
    .pipe(gulp.dest(`${browserDir}/favicons`));
});

gulp.task('inject-favicon', ['favicons', 'hbs'], function() {
  gulp.src(`${browserDir}/index.html`)
  .pipe(inject(gulp.src([`${browserDir}/favicons.html`]), {
    starttag: '<!-- inject:head:html -->',
    transform: function(filePath, file) {
      return file.contents.toString('utf8'); // return file contents as string
    }
  }))
  .pipe(gulp.dest(browserDir));
});

gulp.task('hbs', () => {
  let data = Object.create(null);
  let stream;
  try {
      data = yaml.safeLoad(fs.readFileSync('./src/data/data.yaml', 'utf8'));
      console.log('SUCCESS: data loaded');
  } catch (e) {
      console.log('ERROR');
      console.log(e);
  }

  const options = {
      partialsDirectory : ['./src/templates/partials']
  };

  stream = gulp.src('./src/templates/index.hbs')
               .pipe(gulpHandlebars(data, options))
               .pipe(rename('index.html'))
               .pipe(gulp.dest(browserDir));
  return stream;
});

gulp.task('js', function () {
    return gulp.src(entryPoint)
               .pipe(webpack({
                    watch: false,
                    devtool: 'source-map',
                    module: {
                        loaders: [
                            { test: /\.js$/, loader: 'babel' },
                        ],
                    },
                    output: {
                        filename: 'bundle.js'
                    }
               }))
               .pipe(gulp.dest('./build/scripts'))
               .on('data', () => browserSync.reload());
});

gulp.task('sass', function () {
  return gulp.src(sassWatchPath)
    .pipe(sourcemaps.init())
    .pipe(sass().on('error', sass.logError))
    .pipe(autoprefixer({
        browsers: ['last 2 versions']
    }))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('./build/styles'))
    .pipe(browserSync.reload({stream: true}));
});

gulp.task('copyStatic', function() {
    return gulp.src(staticPath + '/**/*')
               .pipe(gulp.dest('./build/static'));
});

gulp.task('watch', function () {
    gulp.watch(jsWatchPath, ['js']);
    gulp.watch(sassWatchPath, ['sass']);
    gulp.watch([yamlWatchPath, hbsWatchPath], ['hbs']);
    gulp.watch(staticPath + '/**/*', ['copyStatic']);
    gulp.watch(htmlWatchPath, function () {
        return gulp.src('')
            .pipe(browserSync.reload({stream: true}));
    });
});

gulp.task('compress-js', ['js'], function () {
  fs.rename(`${browserDir}/scripts/bundle.js`, `${browserDir}/scripts/bundle.tmp.js`, err => err && console.log(err));
  return gulp.src(`${browserDir}/scripts/bundle.tmp.js`)
             .pipe(uglify())
             .pipe(rename('bundle.js'))
             .pipe(gulp.dest(`${browserDir}/scripts`));
});

gulp.task('compress-css', ['sass'], function () {
  fs.rename(`${browserDir}/styles/style.css`, `${browserDir}/styles/style.tmp.css`, err => err && console.log(err));
  return gulp.src(`${browserDir}/styles/style.tmp.css`)
             .pipe(cleanCSS())
             .pipe(rename('style.css'))
             .pipe(gulp.dest(`${browserDir}/styles`));
});

gulp.task('cleanup', ['compress-js', 'inject-favicon'], () =>
    del([`${browserDir}/scripts/bundle.tmp.js`, `${browserDir}/scripts/bundle.js.map`, `${browserDir}/favicons.html`, `${browserDir}/styles/style.tmp.css`])
);

gulp.task('run', ['hbs', 'js', 'sass', 'copyStatic', 'watch', 'browser-sync']);
gulp.task('build', ['hbs', 'favicons', 'inject-favicon', 'js', 'compress-js', 'sass', 'compress-css', 'copyStatic', 'cleanup']);