text:
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();

require_once(dirname(dirname(__FILE__)).'/edit_form.php');    // parent class definition

/**
 * Class for editing rubric grading strategy forms.
 *
 * @uses moodleform
 */
class workshop_edit_rubric_strategy_form extends workshop_edit_strategy_form {

    const MINLEVELS = 4;
    const ADDLEVELS = 2;

    /**
     * Define the elements to be displayed at the form
     *
     * Called by the parent::definition()
     *
     * @return void
     */
    protected function definition_inner(&$mform) {

        $norepeats          = $this->_customdata['norepeats'];          // number of dimensions to display
        $descriptionopts    = $this->_customdata['descriptionopts'];    // wysiwyg fields options
        $current            = $this->_customdata['current'];            // current data to be set

        $mform->addElement('hidden', 'norepeats', $norepeats);
        $mform->setType('norepeats', PARAM_INT);
        // value not to be overridden by submitted value
        $mform->setConstants(array('norepeats' => $norepeats));

        $levelgrades = array();
        for ($i = 100; $i >= 0; $i--) {
            $levelgrades[$i] = $i;
        }

        for ($i = 0; $i < $norepeats; $i++) {
            $mform->addElement('header', 'dimension'.$i, get_string('dimensionnumber', 'workshopform_rubric', $i+1));
            $mform->addElement('hidden', 'dimensionid__idx_'.$i);
            $mform->setType('dimensionid__idx_'.$i, PARAM_INT);
            $mform->addElement('editor', 'description__idx_'.$i.'_editor',
                                get_string('dimensiondescription', 'workshopform_rubric'), '', $descriptionopts);
            if (isset($current->{'numoflevels__idx_' . $i})) {
                $numoflevels = max($current->{'numoflevels__idx_' . $i} + self::ADDLEVELS, self::MINLEVELS);
            } else {
                $numoflevels = self::MINLEVELS;
            }
            $prevlevel = -1;
            for ($j = 0; $j < $numoflevels; $j++) {
                $mform->addElement('hidden', 'levelid__idx_' . $i . '__idy_' . $j);
                $mform->setType('levelid__idx_' . $i . '__idy_' . $j, PARAM_INT);
                $levelgrp = array();
                $levelgrp[] = $mform->createElement('select', 'grade__idx_'.$i.'__idy_'.$j,'', $levelgrades);
                $levelgrp[] = $mform->createElement('textarea', 'definition__idx_'.$i.'__idy_'.$j, '',  array('cols' => 60, 'rows' => 3));
                $mform->addGroup($levelgrp, 'level__idx_'.$i.'__idy_'.$j, get_string('levelgroup', 'workshopform_rubric'), array(' '), false);
                $mform->setDefault('grade__idx_'.$i.'__idy_'.$j, $prevlevel + 1);
                if (isset($current->{'grade__idx_'.$i.'__idy_'.$j})) {
                    $prevlevel = $current->{'grade__idx_'.$i.'__idy_'.$j};
                } else {
                    $prevlevel++;
                }
            }
        }

        $mform->registerNoSubmitButton('adddims');
        $mform->addElement('submit', 'adddims', get_string('addmoredimensions', 'workshopform_rubric',
                workshop_rubric_strategy::ADDDIMS));
        $mform->closeHeaderBefore('adddims');

        $mform->addElement('header', 'configheader', get_string('configuration', 'workshopform_rubric'));
        $layoutgrp = array();
        $layoutgrp[] = $mform->createElement('radio', 'config_layout', '',
                get_string('layoutlist', 'workshopform_rubric'), 'list');
        $layoutgrp[] = $mform->createElement('radio', 'config_layout', '',
                get_string('layoutgrid', 'workshopform_rubric'), 'grid');
        $mform->addGroup($layoutgrp, 'layoutgrp', get_string('layout', 'workshopform_rubric'), array('<br />'), false);
        $mform->setDefault('config_layout', 'list');
        $this->set_data($current);
    }
}


text:
using AM.Text;

using JetBrains.Annotations;

using ManagedIrbis.Pft.Infrastructure;
using ManagedIrbis.Pft.Infrastructure.Ast;
using ManagedIrbis.Pft.Infrastructure.Compiler;
using ManagedIrbis.Pft.Infrastructure.Text;

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTests.ManagedIrbis.Pft.Infrastructure.Ast
{
    [TestClass]
    public class PftSemicolonTest
    {
        private void _Execute
            (
                [NotNull] PftSemicolon node,
                [NotNull] string expected
            )
        {
            PftContext context = new PftContext(null);
            node.Execute(context);
            string actual = context.Text.DosToUnix();
            Assert.AreEqual(expected, actual);
        }

        [TestMethod]
        public void PftSemicolon_Construction_1()
        {
            PftSemicolon node = new PftSemicolon();
            Assert.IsTrue(node.ConstantExpression);
            Assert.IsTrue(node.ExtendedSyntax);
            Assert.IsFalse(node.RequiresConnection);
        }

        [TestMethod]
        public void PftSemicolon_Construction_2()
        {
            PftToken token = new PftToken(PftTokenKind.Semicolon, 1, 1, ";");
            PftSemicolon node = new PftSemicolon(token);
            Assert.IsTrue(node.ConstantExpression);
            Assert.IsTrue(node.ExtendedSyntax);
            Assert.IsFalse(node.RequiresConnection);
            Assert.AreEqual(token.Column, node.Column);
            Assert.AreEqual(token.Line, node.LineNumber);
            Assert.AreEqual(token.Text, node.Text);
        }

        [TestMethod]
        public void PftSemicolon_Compile_1()
        {
            PftCompiler compiler = new PftCompiler();
            PftProgram program = new PftProgram();
            PftSemicolon node = new PftSemicolon();
            program.Children.Add(node);
            compiler.CompileProgram(program);
        }

        [TestMethod]
        public void PftSemicolon_Execute_1()
        {
            PftSemicolon node = new PftSemicolon();
            _Execute(node, "");
        }

        [TestMethod]
        public void PftSemicolon_Optimize_1()
        {
            PftSemicolon node = new PftSemicolon();
            Assert.IsNull(node.Optimize());
        }

        [TestMethod]
        public void PftSemicolon_PrettyPrint_1()
        {
            PftPrettyPrinter printer = new PftPrettyPrinter();
            PftSemicolon node = new PftSemicolon();
            node.PrettyPrint(printer);
            Assert.AreEqual("; ", printer.ToString());
        }

        [TestMethod]
        public void PftSemicolon_ToString_1()
        {
            PftSemicolon node = new PftSemicolon();
            Assert.AreEqual(";", node.ToString());
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.lucius.kafka_streaming

import java.util
import org.apache.kafka.clients.producer.{ProducerRecord, ProducerConfig, KafkaProducer}

object KafkaWordCountProducer {
  def main(args: Array[String]) {
    if (args.length < 4) {
      //例如:centos02:9092,centos03:9092,centos04:9092 kafka-stream 2 20
      System.err.println("Usage: KafkaWordCountProducer <metadataBrokerList> <topic> " +
        "<messagesPerSec> <wordsPerMessage>")
      System.exit(1)
    }
    val Array(brokers, topic, messagesPerSec, wordsPerMessage) = args

    // Zookeeper connection properties
    val props = new util.HashMap[String, Object]()
    props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, brokers)
    props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
      "org.apache.kafka.common.serialization.StringSerializer")
    props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
      "org.apache.kafka.common.serialization.StringSerializer")

    val producer = new KafkaProducer[String, String](props)

    while(true) {
      (1 to messagesPerSec.toInt).foreach { messageNum =>
        val str = (1 to wordsPerMessage.toInt).map(x => scala.util.Random.nextInt(10).toString)
          .mkString(" ")

        val message = new ProducerRecord[String, String](topic, null, str)
        producer.send(message)
      }
      Thread.sleep(5000)
    }
  }
}


text: angular.module('winston', ['ui.router']);


text:
package view.editor.gameeditor.displays;

import api.IEntity;
import api.ILevel;
import api.ISerializable;
import javafx.collections.ObservableList;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollPane;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.VBox;
import model.entity.Level;
import view.Authoring;
import view.editor.environmenteditor.EditorEnvironment;
import view.enums.DefaultStrings;
import view.utilities.ButtonFactory;

import java.util.ResourceBundle;

public class EnvironmentDisplay extends ObjectDisplay {
    private final ObservableList<ILevel> masterEnvList;
    private final ObservableList<IEntity> masterEntList;
    private final ResourceBundle myResources;
    private final String language;
    private final Scene scene;

    public EnvironmentDisplay (String language, ObservableList<ILevel> masterEnvList, ObservableList<IEntity> masterEntList, Authoring authEnv, Scene myScene) {
        super(authEnv);
        this.masterEntList = masterEntList;
        this.masterEnvList = masterEnvList;
        this.myResources = ResourceBundle.getBundle(language);
        this.language = language;
        this.scene = myScene;
    }

    @SuppressWarnings("unchecked")
    @Override
    public ScrollPane init () {
        ScrollPane scroll = super.init();
        addListeners((ObservableList<ISerializable>) ((ObservableList<?>) masterEnvList));
        return scroll;
    }

    @Override
    protected void addNewObjects (VBox container) {
        masterEnvList.stream().forEach(e -> addEnvironmentToScroll(e, container));
    }

    private void addEnvironmentToScroll (ILevel eSystem, VBox container) {
        Button environment = ButtonFactory.makeButton(eSystem.getName(), null);
        environment.setOnMouseClicked(event -> {
            MouseButton button = event.getButton();
            if (button == MouseButton.PRIMARY) {
                createEditor(EditorEnvironment.class.getName(), language, eSystem, masterEntList, masterEnvList, scene);
            } else if (button == MouseButton.SECONDARY) {
                masterEnvList.remove(eSystem);
            }
        });
        container.getChildren().add(environment);
    }

    @Override
    public Node makeNewObject () {
        return ButtonFactory.makeButton(myResources.getString(DefaultStrings.ENVIRONMENT_EDITOR_NAME.getDefault()),
                e -> createEditor(EditorEnvironment.class.getName(), language, new Level(), masterEntList, masterEnvList, scene));
    }

}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.10.24 at 02:07:37 PM BST
//

package com.oracle.xmlns.apps.sales.opptymgmt.opportunities.opportunityservice.types;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import com.oracle.xmlns.apps.sales.opptymgmt.opportunities.opportunityservice.Opportunity;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="result" type="{http://xmlns.oracle.com/apps/sales/opptyMgmt/opportunities/opportunityService/}Opportunity" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "result"
})
@XmlRootElement(name = "findOpportunityResponse")
public class FindOpportunityResponse {

    protected List<Opportunity> result;

    /**
     * Gets the value of the result property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the result property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getResult().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link Opportunity }
     *
     *
     */
    public List<Opportunity> getResult() {
        if (result == null) {
            result = new ArrayList<Opportunity>();
        }
        return this.result;
    }

}


text:
// Used by importFixes, getEditsForFileRename, and declaration emit to synthesize import module specifiers.
/* @internal */
namespace ts.moduleSpecifiers {
    const enum RelativePreference { Relative, NonRelative, Auto }
    // See UserPreferences#importPathEnding
    const enum Ending { Minimal, Index, JsExtension }

    // Processed preferences
    interface Preferences {
        readonly relativePreference: RelativePreference;
        readonly ending: Ending;
    }

    function getPreferences({ importModuleSpecifierPreference, importModuleSpecifierEnding }: UserPreferences, compilerOptions: CompilerOptions, importingSourceFile: SourceFile): Preferences {
        return {
            relativePreference: importModuleSpecifierPreference === "relative" ? RelativePreference.Relative : importModuleSpecifierPreference === "non-relative" ? RelativePreference.NonRelative : RelativePreference.Auto,
            ending: getEnding(),
        };
        function getEnding(): Ending {
            switch (importModuleSpecifierEnding) {
                case "minimal": return Ending.Minimal;
                case "index": return Ending.Index;
                case "js": return Ending.JsExtension;
                default: return usesJsExtensionOnImports(importingSourceFile) ? Ending.JsExtension
                    : getEmitModuleResolutionKind(compilerOptions) !== ModuleResolutionKind.NodeJs ? Ending.Index : Ending.Minimal;
            }
        }
    }

    function getPreferencesForUpdate(compilerOptions: CompilerOptions, oldImportSpecifier: string): Preferences {
        return {
            relativePreference: isExternalModuleNameRelative(oldImportSpecifier) ? RelativePreference.Relative : RelativePreference.NonRelative,
            ending: hasJSFileExtension(oldImportSpecifier) ?
                Ending.JsExtension :
                getEmitModuleResolutionKind(compilerOptions) !== ModuleResolutionKind.NodeJs || endsWith(oldImportSpecifier, "index") ? Ending.Index : Ending.Minimal,
        };
    }

    export function updateModuleSpecifier(
        compilerOptions: CompilerOptions,
        importingSourceFileName: Path,
        toFileName: string,
        host: ModuleSpecifierResolutionHost,
        files: readonly SourceFile[],
        redirectTargetsMap: RedirectTargetsMap,
        oldImportSpecifier: string,
    ): string | undefined {
        const res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferencesForUpdate(compilerOptions, oldImportSpecifier));
        if (res === oldImportSpecifier) return undefined;
        return res;
    }

    // Note: importingSourceFile is just for usesJsExtensionOnImports
    export function getModuleSpecifier(
        compilerOptions: CompilerOptions,
        importingSourceFile: SourceFile,
        importingSourceFileName: Path,
        toFileName: string,
        host: ModuleSpecifierResolutionHost,
        files: readonly SourceFile[],
        preferences: UserPreferences = {},
        redirectTargetsMap: RedirectTargetsMap,
    ): string {
        return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile));
    }

    export function getNodeModulesPackageName(
        compilerOptions: CompilerOptions,
        importingSourceFileName: Path,
        nodeModulesFileName: string,
        host: ModuleSpecifierResolutionHost,
        files: readonly SourceFile[],
        redirectTargetsMap: RedirectTargetsMap,
    ): string | undefined {
        const info = getInfo(importingSourceFileName, host);
        const modulePaths = getAllModulePaths(files, importingSourceFileName, nodeModulesFileName, info.getCanonicalFileName, host, redirectTargetsMap);
        return firstDefined(modulePaths,
            moduleFileName => tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions, /*packageNameOnly*/ true));
    }

    function getModuleSpecifierWorker(
        compilerOptions: CompilerOptions,
        importingSourceFileName: Path,
        toFileName: string,
        host: ModuleSpecifierResolutionHost,
        files: readonly SourceFile[],
        redirectTargetsMap: RedirectTargetsMap,
        preferences: Preferences
    ): string {
        const info = getInfo(importingSourceFileName, host);
        const modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap);
        return firstDefined(modulePaths, moduleFileName => tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions)) ||
            getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences);
    }

    /** Returns an import for each symlink and for the realpath. */
    export function getModuleSpecifiers(
        moduleSymbol: Symbol,
        compilerOptions: CompilerOptions,
        importingSourceFile: SourceFile,
        host: ModuleSpecifierResolutionHost,
        files: readonly SourceFile[],
        userPreferences: UserPreferences,
        redirectTargetsMap: RedirectTargetsMap,
    ): readonly string[] {
        const ambient = tryGetModuleNameFromAmbientModule(moduleSymbol);
        if (ambient) return [ambient];

        const info = getInfo(importingSourceFile.path, host);
        const moduleSourceFile = getSourceFileOfNode(moduleSymbol.valueDeclaration || getNonAugmentationDeclaration(moduleSymbol));
        const modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.originalFileName, info.getCanonicalFileName, host, redirectTargetsMap);

        const preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile);
        const global = mapDefined(modulePaths, moduleFileName => tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions));
        return global.length ? global : modulePaths.map(moduleFileName => getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences));
    }

    interface Info {
        readonly getCanonicalFileName: GetCanonicalFileName;
        readonly sourceDirectory: Path;
    }
    // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path
    function getInfo(importingSourceFileName: Path, host: ModuleSpecifierResolutionHost): Info {
        const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true);
        const sourceDirectory = getDirectoryPath(importingSourceFileName);
        return { getCanonicalFileName, sourceDirectory };
    }

    function getLocalModuleSpecifier(moduleFileName: string, { getCanonicalFileName, sourceDirectory }: Info, compilerOptions: CompilerOptions, { ending, relativePreference }: Preferences): string {
        const { baseUrl, paths, rootDirs } = compilerOptions;

        const relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) ||
            removeExtensionAndIndexPostFix(ensurePathIsNonModuleName(getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions);
        if (!baseUrl || relativePreference === RelativePreference.Relative) {
            return relativePath;
        }

        const relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName);
        if (!relativeToBaseUrl) {
            return relativePath;
        }

        const importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions);
        const fromPaths = paths && tryGetModuleNameFromPaths(removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths);
        const nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths;

        if (relativePreference === RelativePreference.NonRelative) {
            return nonRelative;
        }

        if (relativePreference !== RelativePreference.Auto) Debug.assertNever(relativePreference);

        // Prefer a relative import over a baseUrl import if it has fewer components.
        return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative;
    }

    export function countPathComponents(path: string): number {
        let count = 0;
        for (let i = startsWith(path, "./") ? 2 : 0; i < path.length; i++) {
            if (path.charCodeAt(i) === CharacterCodes.slash) count++;
        }
        return count;
    }

    function usesJsExtensionOnImports({ imports }: SourceFile): boolean {
        return firstDefined(imports, ({ text }) => pathIsRelative(text) ? hasJSFileExtension(text) : undefined) || false;
    }

    function numberOfDirectorySeparators(str: string) {
        const match = str.match(/\//g);
        return match ? match.length : 0;
    }

    function comparePathsByNumberOfDirectorySeparators(a: string, b: string) {
        return compareValues(
            numberOfDirectorySeparators(a),
            numberOfDirectorySeparators(b)
        );
    }

    /**
     * Looks for existing imports that use symlinks to this module.
     * Symlinks will be returned first so they are preferred over the real path.
     */
    function getAllModulePaths(files: readonly SourceFile[], importingFileName: string, importedFileName: string, getCanonicalFileName: GetCanonicalFileName, host: ModuleSpecifierResolutionHost, redirectTargetsMap: RedirectTargetsMap): readonly string[] {
        const redirects = redirectTargetsMap.get(importedFileName);
        const importedFileNames = redirects ? [...redirects, importedFileName] : [importedFileName];
        const cwd = host.getCurrentDirectory ? host.getCurrentDirectory() : "";
        const targets = importedFileNames.map(f => getNormalizedAbsolutePath(f, cwd));
        const links = host.getProbableSymlinks
            ? host.getProbableSymlinks(files)
            : discoverProbableSymlinks(files, getCanonicalFileName, cwd);

        const result: string[] = [];
        const compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? compareStringsCaseSensitive : compareStringsCaseInsensitive;
        links.forEach((resolved, path) => {
            if (startsWithDirectory(importingFileName, resolved, getCanonicalFileName)) {
                return; // Don't want to a package to globally import from itself
            }

            const target = find(targets, t => compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === Comparison.EqualTo);
            if (target === undefined) return;

            const relative = getRelativePathFromDirectory(resolved, target, getCanonicalFileName);
            const option = resolvePath(path, relative);
            if (!host.fileExists || host.fileExists(option)) {
                result.push(option);
            }
        });
        result.push(...targets);
        if (result.length < 2) return result;

        // Sort by paths closest to importing file Name directory
        const allFileNames = arrayToMap(result, identity, getCanonicalFileName);
        const sortedPaths: string[] = [];
        for (
            let directory = getDirectoryPath(toPath(importingFileName, cwd, getCanonicalFileName));
            allFileNames.size !== 0;
        ) {
            const directoryStart = ensureTrailingDirectorySeparator(directory);
            let pathsInDirectory: string[] | undefined;
            allFileNames.forEach((canonicalFileName, fileName) => {
                if (startsWith(canonicalFileName, directoryStart)) {
                    (pathsInDirectory || (pathsInDirectory = [])).push(fileName);
                    allFileNames.delete(fileName);
                }
            });
            if (pathsInDirectory) {
                if (pathsInDirectory.length > 1) {
                    pathsInDirectory.sort(comparePathsByNumberOfDirectorySeparators);
                }
                sortedPaths.push(...pathsInDirectory);
            }
            const newDirectory = getDirectoryPath(directory);
            if (newDirectory === directory) break;
            directory = newDirectory;
        }
        if (allFileNames.size) {
            const remainingPaths = arrayFrom(allFileNames.values());
            if (remainingPaths.length > 1) remainingPaths.sort(comparePathsByNumberOfDirectorySeparators);
            sortedPaths.push(...remainingPaths);
        }
        return sortedPaths;
    }

    function tryGetModuleNameFromAmbientModule(moduleSymbol: Symbol): string | undefined {
        const decl = find(moduleSymbol.declarations,
            d => isNonGlobalAmbientModule(d) && (!isExternalModuleAugmentation(d) || !isExternalModuleNameRelative(getTextOfIdentifierOrLiteral(d.name)))
        ) as (ModuleDeclaration & { name: StringLiteral }) | undefined;
        if (decl) {
            return decl.name.text;
        }
    }

    function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex: string, relativeToBaseUrl: string, paths: MapLike<readonly string[]>): string | undefined {
        for (const key in paths) {
            for (const patternText of paths[key]) {
                const pattern = removeFileExtension(normalizePath(patternText));
                const indexOfStar = pattern.indexOf("*");
                if (indexOfStar !== -1) {
                    const prefix = pattern.substr(0, indexOfStar);
                    const suffix = pattern.substr(indexOfStar + 1);
                    if (relativeToBaseUrl.length >= prefix.length + suffix.length &&
                        startsWith(relativeToBaseUrl, prefix) &&
                        endsWith(relativeToBaseUrl, suffix) ||
                        !suffix && relativeToBaseUrl === removeTrailingDirectorySeparator(prefix)) {
                        const matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length);
                        return key.replace("*", matchedStar);
                    }
                }
                else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) {
                    return key;
                }
            }
        }
    }

    function tryGetModuleNameFromRootDirs(rootDirs: readonly string[], moduleFileName: string, sourceDirectory: string, getCanonicalFileName: (file: string) => string, ending: Ending, compilerOptions: CompilerOptions): string | undefined {
        const normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName);
        if (normalizedTargetPath === undefined) {
            return undefined;
        }

        const normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName);
        const relativePath = normalizedSourcePath !== undefined ? ensurePathIsNonModuleName(getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath;
        return getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.NodeJs
            ? removeExtensionAndIndexPostFix(relativePath, ending, compilerOptions)
            : removeFileExtension(relativePath);
    }

    function tryGetModuleNameAsNodeModule(moduleFileName: string, { getCanonicalFileName, sourceDirectory }: Info, host: ModuleSpecifierResolutionHost, options: CompilerOptions, packageNameOnly?: boolean): string | undefined {
        if (!host.fileExists || !host.readFile) {
            return undefined;
        }
        const parts: NodeModulePathParts = getNodeModulePathParts(moduleFileName)!;
        if (!parts) {
            return undefined;
        }

        let packageJsonContent: any | undefined;
        const packageRootPath = moduleFileName.substring(0, parts.packageRootIndex);
        if (!packageNameOnly) {
            const packageJsonPath = combinePaths(packageRootPath, "package.json");
            packageJsonContent = host.fileExists(packageJsonPath)
                ? JSON.parse(host.readFile(packageJsonPath)!)
                : undefined;
            const versionPaths = packageJsonContent && packageJsonContent.typesVersions
                ? getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions)
                : undefined;
            if (versionPaths) {
                const subModuleName = moduleFileName.slice(parts.packageRootIndex + 1);
                const fromPaths = tryGetModuleNameFromPaths(
                    removeFileExtension(subModuleName),
                    removeExtensionAndIndexPostFix(subModuleName, Ending.Minimal, options),
                    versionPaths.paths
                );
                if (fromPaths !== undefined) {
                    moduleFileName = combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths);
                }
            }
        }

        // Simplify the full file path to something that can be resolved by Node.

        // If the module could be imported by a directory name, use that directory's name
        const moduleSpecifier = packageNameOnly ? moduleFileName : getDirectoryOrExtensionlessFileName(moduleFileName);
        const globalTypingsCacheLocation = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation();
        // Get a path that's relative to node_modules or the importing file's path
        // if node_modules folder is in this folder or any of its parent folders, no need to keep it.
        const pathToTopLevelNodeModules = getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex));
        if (!(startsWith(sourceDirectory, pathToTopLevelNodeModules) || globalTypingsCacheLocation && startsWith(getCanonicalFileName(globalTypingsCacheLocation), pathToTopLevelNodeModules))) {
            return undefined;
        }

        // If the module was found in @types, get the actual Node package name
        const nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1);
        const packageName = getPackageNameFromTypesPackageName(nodeModulesDirectoryName);
        // For classic resolution, only allow importing from node_modules/@types, not other node_modules
        return getEmitModuleResolutionKind(options) !== ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName;

        function getDirectoryOrExtensionlessFileName(path: string): string {
            // If the file is the main module, it can be imported by the package name
            if (packageJsonContent) {
                const mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main;
                if (isString(mainFileRelative)) {
                    const mainExportFile = toPath(mainFileRelative, packageRootPath, getCanonicalFileName);
                    if (removeFileExtension(mainExportFile) === removeFileExtension(getCanonicalFileName(path))) {
                        return packageRootPath;
                    }
                }
            }

            // We still have a file name - remove the extension
            const fullModulePathWithoutExtension = removeFileExtension(path);

            // If the file is /index, it can be imported by its directory name
            // IFF there is not _also_ a file by the same name
            if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index" && !tryGetAnyFileFromPath(host, fullModulePathWithoutExtension.substring(0, parts.fileNameIndex))) {
                return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex);
            }

            return fullModulePathWithoutExtension;
        }
    }

    function tryGetAnyFileFromPath(host: ModuleSpecifierResolutionHost, path: string) {
        if (!host.fileExists) return;
        // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory
        const extensions = getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: ScriptKind.JSON }]);
        for (const e of extensions) {
            const fullPath = path + e;
            if (host.fileExists(fullPath)) {
                return fullPath;
            }
        }
    }

    interface NodeModulePathParts {
        readonly topLevelNodeModulesIndex: number;
        readonly topLevelPackageNameIndex: number;
        readonly packageRootIndex: number;
        readonly fileNameIndex: number;
    }
    function getNodeModulePathParts(fullPath: string): NodeModulePathParts | undefined {
        // If fullPath can't be valid module file within node_modules, returns undefined.
        // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js
        // Returns indices:                       ^            ^                                                      ^             ^

        let topLevelNodeModulesIndex = 0;
        let topLevelPackageNameIndex = 0;
        let packageRootIndex = 0;
        let fileNameIndex = 0;

        const enum States {
            BeforeNodeModules,
            NodeModules,
            Scope,
            PackageContent
        }

        let partStart = 0;
        let partEnd = 0;
        let state = States.BeforeNodeModules;

        while (partEnd >= 0) {
            partStart = partEnd;
            partEnd = fullPath.indexOf("/", partStart + 1);
            switch (state) {
                case States.BeforeNodeModules:
                    if (fullPath.indexOf(nodeModulesPathPart, partStart) === partStart) {
                        topLevelNodeModulesIndex = partStart;
                        topLevelPackageNameIndex = partEnd;
                        state = States.NodeModules;
                    }
                    break;
                case States.NodeModules:
                case States.Scope:
                    if (state === States.NodeModules && fullPath.charAt(partStart + 1) === "@") {
                        state = States.Scope;
                    }
                    else {
                        packageRootIndex = partEnd;
                        state = States.PackageContent;
                    }
                    break;
                case States.PackageContent:
                    if (fullPath.indexOf(nodeModulesPathPart, partStart) === partStart) {
                        state = States.NodeModules;
                    }
                    else {
                        state = States.PackageContent;
                    }
                    break;
            }
        }

        fileNameIndex = partStart;

        return state > States.NodeModules ? { topLevelNodeModulesIndex, topLevelPackageNameIndex, packageRootIndex, fileNameIndex } : undefined;
    }

    function getPathRelativeToRootDirs(path: string, rootDirs: readonly string[], getCanonicalFileName: GetCanonicalFileName): string | undefined {
        return firstDefined(rootDirs, rootDir => {
            const relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName)!; // TODO: GH#18217
            return isPathRelativeToParent(relativePath) ? undefined : relativePath;
        });
    }

    function removeExtensionAndIndexPostFix(fileName: string, ending: Ending, options: CompilerOptions): string {
        if (fileExtensionIs(fileName, Extension.Json)) return fileName;
        const noExtension = removeFileExtension(fileName);
        switch (ending) {
            case Ending.Minimal:
                return removeSuffix(noExtension, "/index");
            case Ending.Index:
                return noExtension;
            case Ending.JsExtension:
                return noExtension + getJSExtensionForFile(fileName, options);
            default:
                return Debug.assertNever(ending);
        }
    }

    function getJSExtensionForFile(fileName: string, options: CompilerOptions): Extension {
        const ext = extensionFromPath(fileName);
        switch (ext) {
            case Extension.Ts:
            case Extension.Dts:
                return Extension.Js;
            case Extension.Tsx:
                return options.jsx === JsxEmit.Preserve ? Extension.Jsx : Extension.Js;
            case Extension.Js:
            case Extension.Jsx:
            case Extension.Json:
                return ext;
            case Extension.TsBuildInfo:
                return Debug.fail(`Extension ${Extension.TsBuildInfo} is unsupported:: FileName:: ${fileName}`);
            default:
                return Debug.assertNever(ext);
        }
    }

    function getRelativePathIfInDirectory(path: string, directoryPath: string, getCanonicalFileName: GetCanonicalFileName): string | undefined {
        const relativePath = getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
        return isRootedDiskPath(relativePath) ? undefined : relativePath;
    }

    function isPathRelativeToParent(path: string): boolean {
        return startsWith(path, "..");
    }
}


text:
using System;

namespace Api.Exceptions
{
    [Serializable]
    public class NotFoundException : ApiException
    {
        public NotFoundException(string title, string message) : base(title, message)
        {
        }
    }
}


text:
package net.imagej.ops.features.haralick;

import net.imagej.ops.Ops;
import net.imglib2.IterableInterval;
import net.imglib2.type.numeric.RealType;
import net.imglib2.type.numeric.real.DoubleType;

import org.scijava.plugin.Plugin;

/**
 *
 * Implementation of Entropy Haralick Feature Definition: -( sum_{i=1}^q
 * sum_{j=1}^q c(i,j) log(c(i,j)) )
 *
 * @author Andreas Graumann (University of Konstanz)
 * @author Christian Dietz (University of Konstanz)
 * @author Tim-Oliver Buchholz (University of Konstanz)
 */
@Plugin(type = Ops.Haralick.Entropy.class, label = "Haralick: Entropy")
public class DefaultEntropy<T extends RealType<T>> extends
		AbstractHaralickFeature<T> implements Ops.Haralick.Entropy {

	// Avoid log 0
	private static final double EPSILON = Double.MIN_NORMAL;

	@Override
	public void compute(final IterableInterval<T> input, final DoubleType output) {
		final double[][] matrix = getCooccurrenceMatrix(input);
		double res = 0;

		final int nrGrayLevels = matrix.length;

		for (int i = 0; i < nrGrayLevels; i++) {
			for (int j = 0; j < nrGrayLevels; j++) {
				res += matrix[i][j] * Math.log(matrix[i][j] + EPSILON);
			}
		}

		output.set(-res);
	}
}


text: <!DOCTYPE potato SYSTEMtaco "ddd">Hello


text:
Setup
=====
This folder contains help guidelines and scripts to help with installing Xilinx ISE

### Windows

Follow [Install_Win.pdf](Install_Win.pdf)

### Linux

Follow [Install_Linux.pdf](Install_Linux.pdf)

If you need to install for other boards. Recomend checking out below.

Other Boards:

**Spartan**: Download and compile the xilinx libusb-drivers with `git clone git://git.zerfleddert.de/usb-driver && cd usb-driver && make`. After you compile add `export LD_PRELOAD=/$libusb_path/libusb-driver.so` to the setting64.sh or the script your using. Make sure you set the $libusb_path to the location where you have the usb-driver located.

Referances:
* [Platform Cable USB - Frequently Asked Questions (FAQs)](http://www.xilinx.com/support/answers/20429.html)
* [XILINX JTAG tools on Linux without proprietary kernel modules](http://rmdir.de/~michael/xilinx/)
* [Xilinx JTAG Linux](http://www.george-smart.co.uk/wiki/Xilinx_JTAG_Linux)

### Macintosh

Mac is currently not supported.
Recomend following the Linux setup if you are determined.


text:
const {getDefaultConfig} = require('metro-config');
module.exports = (async () => {
  const defaultConfig = await getDefaultConfig();
  const {assetExts, sourceExts} = defaultConfig.resolver;
  return {
    transformer: {
      getTransformOptions: async () => ({
        transform: {
          experimentalImportSupport: false,
          inlineRequires: false,
        },
      }),
    },
    resolver: {
      // Add bin to assetExts
      assetExts: [...assetExts, 'bin'],
      sourceExts: ['js', 'json', 'ts', 'tsx', 'jsx'],
    }
  };
})();


text:
[Back to DS](../../README.md)

# Example scenario using Major League Baseball game logs

## Overview
For this DS example, we configure and load Major League Baseball [1871-2018 Game Logs](https://www.retrosheet.org/gamelogs/gl1871_2018.zip) which were sourced from [Retrosheet](https://www.retrosheet.org/gamelogs/index.html).

## Quick start

This sequence of commands will create a new bucket, deploy the ingestion function attaching to the new bucket, then deploy the configuration and data files for the game logs example. It displays the number of records that were ingested, then deletes the bucket.

```
BUCKET=$(head -1 /dev/random | md5)
gsutil mb gs://${BUCKET}
cd bq-datashare-toolkit/ingestion/function
npm run deploy -- --trigger-bucket=gs://${BUCKET}
cd ../../examples/mlb/config/ingestion
gsutil cp game_logs.schema.json gs://${BUCKET}/cds/
gsutil cp game_logs.transform.sql gs://${BUCKET}/cds/
cd ../../data
gsutil cp mlb.game_logs.csv.gz gs://${BUCKET}
sleep 60 # wait for ingestion
echo "SELECT COUNT(*) AS entry_count FROM mlb.game_logs" | bq --quiet --format=json --headless query

# [{"entry_count":"171907"}]

# clean up bucket
gsutil rm -r -f gs://${BUCKET}

```

The output from these commands would resemble:

```
host:Code thisuser$ BUCKET=$(head -1 /dev/random | md5)
host:Code thisuser$ gsutil mb gs://${BUCKET}
Creating gs://713573366abd762a58fce9752b55b610/...
host:Code thisuser$ cd bq-datashare-toolkit/ingestion/bin
host:bin thisuser$ ./deploy.sh --trigger-bucket=gs://${BUCKET}
cloudfunctions.googleapis.com api is enabled
Bucket name: gs://713573366abd762a58fce9752b55b610
Bucket region: us
Main region: us
Function region: us-central1
Deploying function (may take a while - up to 2 minutes)...done.
availableMemoryMb: 256
entryPoint: processEvent
eventTrigger:
  eventType: google.storage.object.finalize
  failurePolicy: {}
  resource: projects/_/buckets/713573366abd762a58fce9752b55b610
  service: storage.googleapis.com
labels:
  deployment-tool: cli-gcloud
name: projects/thisuser-cloud-sandbox/locations/us-central1/functions/processUpload
runtime: nodejs10
serviceAccountEmail: thisuser-cloud-sandbox@appspot.gserviceaccount.com
sourceUploadUrl: https://storage.googleapis.com/gcf-upload-us-central1-081d71f7-3b71-4e31-bbb2-8668bf287101/bbcb0441-0571-4dbc-920a-5772b9c34e85.zip?GoogleAccessId=service-283242825526@gcf-admin-robot.iam.gserviceaccount.com&Expires=1572371537&Signature=dZLp9YyRa2y40pTFuz0%2BEgWR0oUKAC9CYFzFy2rfwyKpobnyo17RivMnXgkFhyw4izwHTdUy%2FSfg4jYXIjM6kt6GCGX%2FuTz2F4Mp0sNifUEZ5WueNGsVdHQ%2BWDuKAkiUd%2FrHfAxNWm3UrU%2BuR0MSZg2%2Baaz9hh5AzFEAGu9ixhm4rc3G5LNDp4kud8QCVz57Dtl5F7ZZSX3RRzVCPAkP7Fq7%2BYZLLsENDrEz4%2B04FDLiuPXddvkU9XpLZAahWlWKZL8T4Y6wJPhKuQHqY8RLR9jU1Vfkbp93%2BcMXcOPtue6eXOmVVKVhRYalXsoLUMTu2qutKgVkbTN8MBczKT9K2g%3D%3D
status: ACTIVE
timeout: 540s
updateTime: '2019-10-29T17:22:49Z'
versionId: '21'
host:bin thisuser$ cd ../../examples/mlb/config/ingestion
host:ingestion thisuser$ gsutil cp game_logs.schema.json gs://${BUCKET}/cds/
Copying file://game_logs.schema.json [Content-Type=application/json]...
/ [1 files][ 21.4 KiB/ 21.4 KiB]
Operation completed over 1 objects/21.4 KiB.
host:ingestion thisuser$ gsutil cp game_logs.transform.sql gs://${BUCKET}/cds/
Copying file://game_logs.transform.sql [Content-Type=application/x-sql]...
/ [1 files][  158.0 B/  158.0 B]
Operation completed over 1 objects/158.0 B.
host:ingestion thisuser$ cd ../../data
host:data thisuser$ gsutil cp mlb.game_logs.csv.gz gs://${BUCKET}
Copying file://mlb.game_logs.csv.gz [Content-Type=text/csv]...
\ [1 files][ 19.5 MiB/ 19.5 MiB]   25.1 MiB/s
Operation completed over 1 objects/19.5 MiB.
host:data thisuser$ sleep 60 # wait for ingestion
host:data thisuser$ echo "SELECT COUNT(*) AS entry_count FROM mlb.game_logs" | bq --quiet --format=json --headless query
[{"entry_count":"171907""}]
host:data thisuser$
host:data thisuser$ # ^^^ [{"entry_count":"171907"}]
host:data thisuser$
host:data thisuser$ # clean up bucket
host:data thisuser$ gsutil rm -r -f gs://${BUCKET}
Removing gs://713573366abd762a58fce9752b55b610/mlb.game_logs.csv.gz#1572369785409249...
Removing gs://713573366abd762a58fce9752b55b610/cds/game_logs.schema.json#1572369771326950...
Removing gs://713573366abd762a58fce9752b55b610/cds/game_logs.transform.sql#1572369772972359...
/ [3 objects]
Operation completed over 3 objects.
Removing gs://713573366abd762a58fce9752b55b610/...
```

## Ingestion
- [Teams](./data/mlb.teams.txt) - Raw data for ballparks available at [Retrosheet](https://www.retrosheet.org/TeamIDs.htm).
    - For the Teams data, it's already in a format that is ready to consume. We do not require any custom transformations, so in this case we do **_not_** need to create a specific `teams.transform.sql` file.
- [Ballparks](./data/mlb.ballpark.txt) - Raw data for ballparks available at [Retrosheet](https://www.retrosheet.org/parkcode.txt).
    - For the Ballparks data, it's also already in a format that is ready to consume. However, in this case we want to update the column header names that we use to represent the data within BigQuery. [`ballpark.transform.sql`](./config/ingestion/ballpark.transform.sql) is the file that specifies the transformation to rename the column headers for the consumable table.
- 1871-2018 Game Logs - Raw data for 1871-2018 Game Logs available at [Retrosheet](https://www.retrosheet.org/gamelogs/index.html).
    - The Game Logs data is a little more complex. In this case you first create a schema definition file which will be used to create a staging BigQuery table - [`game_logs.schema.json`](./config/ingestion/game_logs.schema.json). Next you create a transformation file to transform the data into a more queryable format - [`game_logs.transform.sql`](./config/ingestion/game_logs.transform.sql). The transformation for this case performss the following:
        1. The provided format for the `date` column is a date string in the format `yyyyMMdd`. If we load the data as is without a transformation, BigQuery will use [schema auto-detection](https://cloud.google.com/bigquery/docs/schema-detect) to generate each column's respective data type. In the case of this column, it would recognize an integer. So, in order to make the data easier to work with, we write logic to parse the string and cast it to a [`DATE`](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#date-type) data type. Additionally, we're renaming the column from `date` to `game_date`.
        ```
        CAST(CONCAT(SUBSTR(date, 0, 4), '-', SUBSTR(date, 5, 2), '-', SUBSTR(date), 7, 2)) AS DATE) AS game_date
        ```
        2. Include all of the available columns in the file, with the exception of `date`, for which you applied the custom transformation above.
        ```
         * EXCEPT(date)
        ```
        3. To apply row-level data entitlements, you can also create a `label` key which will be used to filter rows by user. The label key that you generate for the game logs data is the a copncatenation of the visitor team name and the home team name. For row-level access labels, you can specify multiple labels within the same column by delimiting them. In this case you are configuring the columns to be delimited with a single pipe (`|`).

        ```
        CONCAT(v_name, '|', h_name) AS label
        ```

## Directories
The following directories are included in the example:
- [config](./config)
    - [ingestion](./config/ingestion) - Contains the ingestion configuration files.
- [data](./data) - Contains a raw, compressed data archive and license file used for the example.

## License
The license for [Retrosheet](https://www.retrosheet.org) data is available [here](https://www.retrosheet.org/notice.txt), or can be found locally in this repository [here](./data/RETROSHEET_LICENSE.txt).


text:
#!/usr/bin/env bash
#
#

zkname=$1
ledgersPath=$2
numBookies=$3
waitInterval=$4

while (( $(zk-shell --run-once "ls ${ledgersPath}/available" ${zkname} | grep -v "readonly" | wc -l) < $numBookies )); do echo "waiting bookies ..."; sleep $waitInterval; done


text:
package volume

import (
	"fmt"
	"strings"

	"github.com/containerum/chkit/pkg/context"
	"github.com/containerum/chkit/pkg/model"
	"github.com/containerum/chkit/pkg/model/volume"
	"github.com/containerum/chkit/pkg/porta"
	"github.com/containerum/chkit/pkg/util/ferr"
	"github.com/ninedraft/boxofstuff/strset"
	"github.com/octago/sflags/gen/gpflag"
	"github.com/spf13/cobra"
)

var aliases = []string{"volumes", "vol"}

func Get(ctx *context.Context) *cobra.Command {
	var flags struct {
		porta.Exporter
		Names bool `desc:"print only names"`
	}
	var command = &cobra.Command{
		Use:     "volume",
		Aliases: aliases,
		Short:   "get volume info",
		Example: "chkit get volume [$VOLUME_NAME...] [-o yaml] [--file $VOLUME_DATA_FILE]",
		Run: func(cmd *cobra.Command, args []string) {
			var logger = ctx.Log.Command("get volumes")
			logger.Debugf("START")
			defer logger.Debugf("END")
			logger.StructFields(flags)
			var renderable model.Renderer
			if len(args) == 1 {
				vol, err := ctx.Client.GetVolume(ctx.GetNamespace().ID, args[0])
				logger.Debugf("getting volume %q from namespace %q", args[0], ctx.GetNamespace())
				if err != nil {
					logger.WithError(err).Errorf("unable to get volume %q from namespace %q", args[0], ctx.GetNamespace())
					ferr.Println(err)
					ctx.Exit(1)
				}
				if flags.Names {
					logger.Debugf("printing name")
					fmt.Println(vol.OwnerAndName())
					return
				}
			} else {
				logger.Debugf("getting volume list from namespace %q", ctx.GetNamespace())
				list, err := ctx.Client.GetVolumeList(ctx.GetNamespace().ID)
				if err != nil {
					logger.WithError(err).Errorf("unable to get volume list")
					ferr.Println(err)
					ctx.Exit(1)
				}
				if len(args) > 0 {
					logger.Debugf("filtering volume list by names %v", args)
					var volumeSet = strset.NewSet(args)
					list = list.Filter(func(volume volume.Volume) bool {
						return volumeSet.Have(volume.Name) || volumeSet.Have(volume.OwnerAndName())
					})
				}
				if flags.Names {
					logger.Debugf("printing names")
					fmt.Println(strings.Join(list.OwnersAndNames(), "\n"))
					return
				}
				renderable = list
			}
			logger.Debugf("exporting data")
			if err := flags.Export(renderable); err != nil {
				ferr.Println(err)
				ctx.Exit(1)
			}
		},
	}
	if err := gpflag.ParseTo(&flags, command.PersistentFlags()); err != nil {
		panic(err)
	}
	return command
}


text:
/* eslint no-dupe-keys: 0, no-mixed-operators: 0 */
import React from 'react'
import ReactDOM from 'react-dom'
import { RefreshControl, ListView } from 'antd-mobile';

const data = [
  {
    img: 'https://zos.alipayobjects.com/rmsportal/dKbkpPXKfvZzWCM.png',
    title: 'Meet hotel',
    des: '不是所有的兼职汪都需要风吹日晒',
  },
  {
    img: 'https://zos.alipayobjects.com/rmsportal/XmwCzSeJiqpkuMB.png',
    title: 'McDonald\'s invites you',
    des: '不是所有的兼职汪都需要风吹日晒',
  },
  {
    img: 'https://zos.alipayobjects.com/rmsportal/hfVtzEhPzTUewPm.png',
    title: 'Eat the week',
    des: '不是所有的兼职汪都需要风吹日晒',
  },
];
let index = data.length - 1;

let pageIndex = 0;

class TestList extends React.Component {
  constructor(props) {
    super(props);
    const dataSource = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row1 !== row2,
    });

    this.initData = [];
    for (let i = 0; i < 20; i++) {
      this.initData.push(`r${i}`);
    }
    this.state = {
      dataSource: dataSource.cloneWithRows(this.initData),
      refreshing: false,
      height: document.documentElement.clientHeight,
    };
  }
  // If you use redux, the data maybe at props, you need use `componentWillReceiveProps`
  // componentWillReceiveProps(nextProps) {
  //   if (nextProps.dataSource !== this.props.dataSource) {
  //     this.setState({
  //       dataSource: this.state.dataSource.cloneWithRows(nextProps.dataSource),
  //     });
  //   }
  // }
  componentDidMount() {
    this.manuallyRefresh = true;
    setTimeout(() => this.setState({ refreshing: true }), 10);

    // Set the appropriate height
    setTimeout(() => this.setState({
      height: this.state.height - ReactDOM.findDOMNode(this.lv).offsetTop,
    }), 0);

    // handle https://github.com/ant-design/ant-design-mobile/issues/1588
    this.lv.getInnerViewNode().addEventListener('touchstart', this.ts = (e) => {
      this.tsPageY = e.touches[0].pageY;
    });
    this.lv.getInnerViewNode().addEventListener('touchmove', this.tm = (e) => {
      this.tmPageY = e.touches[0].pageY;
      if (this.tmPageY > this.tsPageY && this.st <= 0 && document.body.scrollTop > 0) {
        console.log('start pull to refresh');
        this.domScroller.options.preventDefaultOnTouchMove = false;
      } else {
        this.domScroller.options.preventDefaultOnTouchMove = undefined;
      }
    });
  }
  componentWillUnmount() {
    this.lv.getInnerViewNode().removeEventListener('touchstart', this.ts);
    this.lv.getInnerViewNode().removeEventListener('touchmove', this.tm);
  }
  onScroll = (e) => {
    this.st = e.scroller.getValues().top;
    this.domScroller = e;
  }
  onRefresh = () => {
    console.log('onRefresh');
    if (!this.manuallyRefresh) {
      this.setState({ refreshing: true });
    } else {
      this.manuallyRefresh = false;
    }
    setTimeout(() => {
      this.initData = [`ref${pageIndex++}`, ...this.initData];
      this.setState({
        dataSource: this.state.dataSource.cloneWithRows(this.initData),
        refreshing: false,
      });
    }, 1000);
  };
  lv = null
  render() {
    const separator = (sectionID, rowID) => (
      <div
        key={`${sectionID}-${rowID}`}
        style={{
          backgroundColor: '#F5F5F9',
          height: 8,
          borderTop: '1px solid #ECECED',
          borderBottom: '1px solid #ECECED',
        }}
      />
    );
    const row = (rowData, sectionID, rowID) => {
      console.log(rowID);
      if (index < 0) {
        index = data.length - 1;
      }
      const obj = data[index--];
      return (

            {obj.title}

{obj.des}-{rowData}

35元/任务

      );
    };
    return (
      <ListView
        ref={(el) => { this.lv = el }}
        dataSource={this.state.dataSource}
        renderRow={row}
        renderSeparator={separator}
        initialListSize={5}
        pageSize={5}
        scrollRenderAheadDistance={200}
        scrollEventThrottle={20}
        style={{
          height: this.state.height,
          border: '1px solid #ddd',
          margin: '0.1rem 0',
        }}
        scrollerOptions={{ scrollbars: true }}
        refreshControl={<RefreshControl
          refreshing={this.state.refreshing}
          onRefresh={this.onRefresh}
        />}
        onScroll={this.onScroll}
      />
    );
  }
}

export default TestList


text:
// Type definitions for fluxible-addons-react 0.2
// Project: https://github.com/yahoo/fluxible#readme
// Definitions by: xbim <https://github.com/xbim>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
/// <reference types="node" />
import * as React from 'react';
import BaseStore = require('fluxible/addons/BaseStore');
import { ComponentContext } from "fluxible";

/**
 * Registers change listeners and retrieves state from stores using the `getStateFromStores`
 * method
 * @param Component component to pass state as props to.
 * @param stores List of stores to listen for changes
 * @param getStateFromStores function that receives all stores and should return
 *      the full state object. Receives `stores` hash and component `props` as arguments
 * @param customContextTypes additional `contextTypes` that could be accessed from your `getStateFromStores`
 *      function
 * @returns React.Component
 */
export function connectToStores(
 Component: typeof React.Component,
 stores: Array<typeof BaseStore> | string[],
 getStateFromStores: (context: ComponentContext, props: any) => any,
 customContextTypes?: any): typeof React.Component;

/**
 * Provides context prop to all children as React context
 * @param  component to wrap
 * @param customContextTypes Custom contextTypes to add
 * @returns React.Component
 */
export function provideContext(Component: typeof React.Component, customContextTypes?: any): typeof React.Component;


text:
package com.greghaskins.bankocr.ui;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintStream;

interface Application {

    void run(final BufferedReader inputStream, final PrintStream outputStream) throws IOException;

}


text:
echo "[MeteorCLI - universal] Resetting project"
meteor reset
echo "[MeteorCLI - universal] Installing npm dependencies"
npm ci
exit_code=$?; if [ ${exit_code} -gt 0 ]; then exit ${exit_code}; fi
echo "[MeteorCLI - universal] Installing meteor dependencies"
meteor update --all-packages --allow-incompatible-update
exit_code=$?; if [ ${exit_code} -gt 0 ]; then exit ${exit_code}; fi
echo "[MeteorCLI - universal] Testing JIT"
npm run test:ci
exit_code=$?; if [ ${exit_code} -gt 0 ]; then exit ${exit_code}; fi
echo "[MeteorCLI - universal] Testing AOT"
AOT=1 meteor build ./.meteor/build-aot
exit_code=$?; if [ ${exit_code} -gt 0 ]; then exit ${exit_code}; fi
echo "[MeteorCLI - universal] AOT w/ Rollup"
AOT=1 ROLLUP=1 meteor build ./.meteor/build-aot-rollup
exit_code=$?; if [ ${exit_code} -gt 0 ]; then exit ${exit_code}; fi


text:
/* eslint no-unused-vars: 0 */

const { format } = require('../');
const { combine, timestamp, label } = format;

const ignorePrivate = format((info, opts) => {
  if (info.private) { return false; }
  return info;
})();

console.dir(ignorePrivate.transform({
  level: 'error',
  message: 'Public error to share'
}));

console.dir(ignorePrivate.transform({
  level: 'error',
  private: true,
  message: 'This is super secret - hide it.'
}));

const willNeverThrow = format.combine(
  format(info => { return false; })(), // Ignores everything
  format(info => { throw new Error('Never reached'); })()
);

console.dir(willNeverThrow.transform({
  level: 'info',
  message: 'wow such testing'
}));


text:
using Microsoft.Web.XmlTransform;
using System;
using System.Web;
using System.Xml;
using umbraco.cms.businesslogic.packager.standardPackageActions;
using umbraco.interfaces;
using Umbraco.Core.Logging;

namespace Our.Umbraco.LocalizedEditorModels.Web.PackageActions
{
    /// <summary>
    /// Package Action which supports the use of .xdt files during Umbraco Package installation (not required when installed by NuGet.)
    ///
    /// Modified version of Tim Geyssens' https://github.com/TimGeyssens/UmbracoPageNotFoundManager/blob/e4861c2a298c977842c73dd1683a297f4d7b3198/PageNotFoundManager/Umbraco/Installer/PackageActions.cs
    /// </summary>
    public class TransformConfigPackageAction : IPackageAction
    {
        public string Alias()
        {
            return "LEM.TransformConfig";
        }

        private bool Transform(string packageName, XmlNode xmlData, bool uninstall = false)
        {
            try
            {
                var configFileAttributeValue = xmlData.Attributes.GetNamedItem("file").Value;
                var configFileAbsoluteVirtualPath = VirtualPathUtility.ToAbsolute(configFileAttributeValue);

                var fileEnd = "install.xdt";
                if (uninstall)
                {
                    fileEnd = string.Format("un{0}", fileEnd);
                }

                var xdtfileAttributeValue = string.Format("{0}.{1}", xmlData.Attributes.GetNamedItem("xdtfile").Value, fileEnd);
                var xdtFileAbsoluteVirtualPath = VirtualPathUtility.ToAbsolute(xdtfileAttributeValue);

                using (var xmlDoc = new XmlTransformableDocument())
                {
                    var xmlMappedFilePath = HttpContext.Current.Server.MapPath(configFileAbsoluteVirtualPath);
                    var xdtMappedFilePath = HttpContext.Current.Server.MapPath(xdtFileAbsoluteVirtualPath);
                    xmlDoc.PreserveWhitespace = true;
                    xmlDoc.Load(xmlMappedFilePath);

                    using (var xmlTrans = new XmlTransformation(xdtMappedFilePath))
                    {
                        LogHelper.Info<TransformConfigPackageAction>("Applying XDT File ({0}) to XML File ({1}).", () => new[] { xdtMappedFilePath, xmlMappedFilePath });

                        if (xmlTrans.Apply(xmlDoc))
                        {
                            xmlDoc.Save(xmlMappedFilePath);
                            LogHelper.Info<TransformConfigPackageAction>("Successfully Applied XDT File ({0}) to XML File ({1}).", () => new[] { xdtMappedFilePath, xmlMappedFilePath });
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error<TransformConfigPackageAction>("Unable to perform package action.", ex);
                return false;
            }

            return true;
        }

        public bool Execute(string packageName, XmlNode xmlData)
        {
            return Transform(packageName, xmlData);
        }

        public XmlNode SampleXml()
        {
            var str = "<Action runat=\"install\" undo=\"true\" alias=\"LEM.TransformConfig\" file=\"~/web.config\" xdtfile=\"~/app_plugins/demo/web.config\"></Action>";
            return helper.parseStringToXmlNode(str);
        }

        public bool Undo(string packageName, XmlNode xmlData)
        {
            return Transform(packageName, xmlData, true);
        }
    }
}


text:
<?=View::factory('templates/topslider')->render()?>

//{pagetitle}

						{main_content_template}

							[#Product? &view=`main_root_products` &type=`main` &showProduct=`false`#]
							<? /*$categories = Product::factory('', array('view' => 'main_root_products', 'showProduct' => false, 'type' => 'main')); ?>
							<? $categories->render();*/ ?>

						Сервисы

Калькулятор

									блаблаблабла

								Подробнее

Сертификация

									блаблаблабла

								Подробнее

Доставка

									блаблаблабла

								Подробнее

						//Последний коментарий

									блаблаблабалб алабалблаблаблабалбалабалблаблаб лабалбалабалблабл!блаблаблабалб алабалблаблаблабалбалабалблаблаб лабалбалабалблабл

								Еще отзывы

Владимир Путин

ФГУП ПРесса "российская газета"

					<?=View::factory('templates/services_blocks')->render()?>


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>glm::gtc Namespace Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>

Main Page

Modules

Namespaces

Classes

Files

Namespace List

Namespace Members

glm

gtc

Namespaces

glm::gtc Namespace Reference

G-Truc Creation stable extensions.
More...

Namespaces

namespace  	half_float

namespace  	matrix_access

namespace  	matrix_integer

namespace  	matrix_inverse

namespace  	matrix_transform

namespace  	quaternion

namespace  	swizzle

namespace  	type_precision

namespace  	type_ptr

Detailed Description

G-Truc Creation stable extensions.

<address class="footer">Generated by

 1.7.4 </address>


text:
package com.navercorp.pinpoint.plugin.hystrix.interceptor;

import com.navercorp.pinpoint.bootstrap.context.MethodDescriptor;
import com.navercorp.pinpoint.bootstrap.context.TraceContext;
import com.navercorp.pinpoint.plugin.hystrix.HystrixPluginConstants;

/**
 * @author HyunGil Jeong
 */
public class ExecutionObservableCallInterceptor extends HystrixObservableCallInterceptor {

    public ExecutionObservableCallInterceptor(TraceContext traceContext, MethodDescriptor methodDescriptor) {
        super(traceContext, methodDescriptor);
    }

    @Override
    protected String getExecutionType() {
        return HystrixPluginConstants.EXECUTION_TYPE_EXECUTION;
    }
}


text:
<option value=<%= selectOptions.user.get('id') %>>Meg</option>
<% if (selectOptions.admin === true) { %>
  <option value="alle">Alle</option>
<% } %>
<optgroup value="groups" label="DNT-grupper">
  <% _.each(selectOptions.groups, function(element) { %>
    <option value=<%= element.object_id %>><%= element.navn %></option>
  <% }); %>
</optgroup>
<optgroup value="groups" label="Innholdspartnere">
  <% if (selectOptions.admin === true) { %>
    <% _.each(selectOptions.externalGroups, function(element) { %>
      <option value=<%= element._id %>><%= element.navn %></option>
    <% }); %>
  <% } else { %>
    <% _.each(selectOptions.userExternalGroups, function(element) { %>
      <option value=<%= element._id %>><%= element.navn %></option>
    <% }); %>
  <% } %>
</optgroup>


text:
var request = require('superagent');
var url = require('url');
var app = require('../');

module.exports = validate;

function validate(req, res, next) {
  var method = 'HEAD';
  var timeout = 8000;
  var redirects = 5;
  var agent = request.agent();
  if (/^http/.test(req.query.url) === false) req.query.url = 'http://' + req.query.url
  res.set('Queried-URL', req.query.url);
  agent.head(req.query.url).timeout(timeout).end(onResponse);
  function onResponse(err, response) {
    if (((response || {}).header || {}).location) {
      if (!redirects) return res.sendStatus(500);
      redirects--;
      var query = url.parse(req.query.url)
      res.set('Queried-URL', response.header.location);
      return agent.head(response.header.location).timeout(timeout).end(onResponse);
    }
    if (err && err.status === 405 && method === 'HEAD') {
      method = 'GET';
      return agent.get(req.query.url).timeout(timeout).end(onResponse);
    }
    if (err && err.status) return res.sendStatus(err.status)
    if (err) return res.sendStatus(500)
    res.sendStatus(response.status)
  }
}

function getPath(protocol, host, path) {
  return app.pathFor('api:validate', {
    $query: {
      url: protocol + '//' + host + path
    }
  })
}


text:
package main

import (
	"bytes"
	"encoding/json"
	"strings"
	"sync"
	"testing"

	"github.com/kataras/golog"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/httptest"
)

func TestJSONLogger(t *testing.T) {
	iters := 500

	out := new(bytes.Buffer)

	app := iris.New()
	app.Logger().SetTimeFormat("")     // disable timestamps.
	app.Logger().SetStacktraceLimit(1) // limit debug stacktrace to 1, show only the first caller.
	app.Logger().SetOutput(out)

	app.Logger().Handle(func(l *golog.Log) bool {
		enc := json.NewEncoder(l.Logger.Printer) // you can change the output to a file as well.
		err := enc.Encode(l)
		return err == nil
	})

	app.Get("/ping", ping)

	const expectedLogStr = `{"level":"debug","message":"Request path: /ping","fields":{"request_id":null},"stacktrace":[{"function":"json-logger/ping","source":"/home/runner/work/iris/iris/_examples/logging/json-logger/main.go:78"}]}` // gh actions-specific.
	e := httptest.New(t, app, httptest.LogLevel("debug"))
	wg := new(sync.WaitGroup)
	wg.Add(iters)
	for i := 0; i < iters; i++ {
		go func() {
			e.GET("/ping").Expect().Status(httptest.StatusOK).Body().Equal("pong")
			wg.Done()
		}()
	}

	wg.Wait()
	expected := ""
	for i := 0; i < iters; i++ {
		expected += expectedLogStr + "\n"
	}

	got := out.String()
	got = got[strings.Index(got, "{"):] // take only the json we care and after.
	if expected != got {
		if !strings.HasSuffix(got, expected) {
			// C:/mygopath vs /home/travis vs any file system,
			// pure check but it does the job.
			t.Fatalf("expected:\n%s\nbut got:\n%s", expected, got)
		}
	}
}


text:
/**
 * @file   CudaUtil.h
 * @author Giuseppe Coviello <giuseppe.coviello@uniparthenope.it>
 * @date   Sun Oct 11 17:16:48 2009
 *
 * @brief
 *
 *
 */

#ifndef _CUDAUTIL_H
#define	_CUDAUTIL_H

#include <iostream>
#include <cstdlib>

#include <fatBinaryCtl.h>
#include <fatbinary.h>
#include <texture_types.h>
#include "__cudaFatFormat.h"

#include "Buffer.h"

//#define DEBUG

/**
 * CudaUtil contains facility functions used by gVirtuS. These functions
 * includes the ones for marshalling and unmarshalling pointers and "CUDA fat
 * binaries".
 */
class CudaUtil {
public:
    CudaUtil();
    CudaUtil(const CudaUtil& orig);
    virtual ~CudaUtil();
    static const size_t MarshaledDevicePointerSize = sizeof(void *) * 2 + 3;
    static const size_t MarshaledHostPointerSize = sizeof(void *) * 2 + 3;
    static char * MarshalHostPointer(const void* ptr);
    static void MarshalHostPointer(const void * ptr, char * marshal);
    static char * MarshalDevicePointer(const void *devPtr);
    static void MarshalDevicePointer(const void *devPtr, char * marshal);
    static inline void * UnmarshalPointer(const char *marshal) {
        return (void *) strtoul(marshal, NULL, 16);
    }
    template <class T> static inline pointer_t MarshalPointer(const T ptr) {
        return static_cast<pointer_t>(ptr);
    }
    static Buffer * MarshalFatCudaBinary(__cudaFatCudaBinary * bin, Buffer * marshal = NULL);
    static Buffer * MarshalFatCudaBinary(__fatBinC_Wrapper_t * bin, Buffer * marshal = NULL);
    static __cudaFatCudaBinary * UnmarshalFatCudaBinary(Buffer * marshal);
    static __fatBinC_Wrapper_t * UnmarshalFatCudaBinaryV2(Buffer * marshal);
    static void DumpFatCudaBinary(__cudaFatCudaBinary * bin, std::ostream & out);
    static Buffer * MarshalTextureDescForArguments(const cudaTextureDesc* tex,
      Buffer * marshal);
    static cudaTextureDesc * UnmarshalTextureDesc(Buffer * marshal);

    /**
     * CudaVar is a data structure used for storing information about shared
     * variables.
     */
    struct CudaVar {
        char fatCubinHandle[MarshaledHostPointerSize];
        char hostVar[MarshaledDevicePointerSize];
        char deviceAddress[255];
        char deviceName[255];
        int ext;
        int size;
        int constant;
        int global;
    };
private:
};

static const char *_cudaGetErrorEnum(cudaError_t error)
{
    switch (error)
    {
        case cudaSuccess:
            return "cudaSuccess";

        case cudaErrorMissingConfiguration:
            return "cudaErrorMissingConfiguration";

        case cudaErrorMemoryAllocation:
            return "cudaErrorMemoryAllocation";

        case cudaErrorInitializationError:
            return "cudaErrorInitializationError";

        case cudaErrorLaunchFailure:
            return "cudaErrorLaunchFailure";

        case cudaErrorPriorLaunchFailure:
            return "cudaErrorPriorLaunchFailure";

        case cudaErrorLaunchTimeout:
            return "cudaErrorLaunchTimeout";

        case cudaErrorLaunchOutOfResources:
            return "cudaErrorLaunchOutOfResources";

        case cudaErrorInvalidDeviceFunction:
            return "cudaErrorInvalidDeviceFunction";

        case cudaErrorInvalidConfiguration:
            return "cudaErrorInvalidConfiguration";

        case cudaErrorInvalidDevice:
            return "cudaErrorInvalidDevice";

        case cudaErrorInvalidValue:
            return "cudaErrorInvalidValue";

        case cudaErrorInvalidPitchValue:
            return "cudaErrorInvalidPitchValue";

        case cudaErrorInvalidSymbol:
            return "cudaErrorInvalidSymbol";

        case cudaErrorMapBufferObjectFailed:
            return "cudaErrorMapBufferObjectFailed";

        case cudaErrorUnmapBufferObjectFailed:
            return "cudaErrorUnmapBufferObjectFailed";

        case cudaErrorInvalidHostPointer:
            return "cudaErrorInvalidHostPointer";

        case cudaErrorInvalidDevicePointer:
            return "cudaErrorInvalidDevicePointer";

        case cudaErrorInvalidTexture:
            return "cudaErrorInvalidTexture";

        case cudaErrorInvalidTextureBinding:
            return "cudaErrorInvalidTextureBinding";

        case cudaErrorInvalidChannelDescriptor:
            return "cudaErrorInvalidChannelDescriptor";

        case cudaErrorInvalidMemcpyDirection:
            return "cudaErrorInvalidMemcpyDirection";

        case cudaErrorAddressOfConstant:
            return "cudaErrorAddressOfConstant";

        case cudaErrorTextureFetchFailed:
            return "cudaErrorTextureFetchFailed";

        case cudaErrorTextureNotBound:
            return "cudaErrorTextureNotBound";

        case cudaErrorSynchronizationError:
            return "cudaErrorSynchronizationError";

        case cudaErrorInvalidFilterSetting:
            return "cudaErrorInvalidFilterSetting";

        case cudaErrorInvalidNormSetting:
            return "cudaErrorInvalidNormSetting";
        case cudaErrorMixedDeviceExecution:
            return "cudaErrorMixedDeviceExecution";

        case cudaErrorCudartUnloading:
            return "cudaErrorCudartUnloading";

        case cudaErrorUnknown:
            return "cudaErrorUnknown";

        case cudaErrorNotYetImplemented:
            return "cudaErrorNotYetImplemented";

        case cudaErrorMemoryValueTooLarge:
            return "cudaErrorMemoryValueTooLarge";

        case cudaErrorInvalidResourceHandle:
            return "cudaErrorInvalidResourceHandle";

        case cudaErrorNotReady:
            return "cudaErrorNotReady";

        case cudaErrorInsufficientDriver:
            return "cudaErrorInsufficientDriver";

        case cudaErrorSetOnActiveProcess:
            return "cudaErrorSetOnActiveProcess";

        case cudaErrorInvalidSurface:
            return "cudaErrorInvalidSurface";

        case cudaErrorNoDevice:
            return "cudaErrorNoDevice";

        case cudaErrorECCUncorrectable:
            return "cudaErrorECCUncorrectable";

        case cudaErrorSharedObjectSymbolNotFound:
            return "cudaErrorSharedObjectSymbolNotFound";

        case cudaErrorSharedObjectInitFailed:
            return "cudaErrorSharedObjectInitFailed";

        case cudaErrorUnsupportedLimit:
            return "cudaErrorUnsupportedLimit";

        case cudaErrorDuplicateVariableName:
            return "cudaErrorDuplicateVariableName";

        case cudaErrorDuplicateTextureName:
            return "cudaErrorDuplicateTextureName";

        case cudaErrorDuplicateSurfaceName:
            return "cudaErrorDuplicateSurfaceName";

        case cudaErrorDevicesUnavailable:
            return "cudaErrorDevicesUnavailable";

        case cudaErrorInvalidKernelImage:
            return "cudaErrorInvalidKernelImage";

        case cudaErrorNoKernelImageForDevice:
            return "cudaErrorNoKernelImageForDevice";

        case cudaErrorIncompatibleDriverContext:
            return "cudaErrorIncompatibleDriverContext";

        case cudaErrorPeerAccessAlreadyEnabled:
            return "cudaErrorPeerAccessAlreadyEnabled";

        case cudaErrorPeerAccessNotEnabled:
            return "cudaErrorPeerAccessNotEnabled";

        case cudaErrorDeviceAlreadyInUse:
            return "cudaErrorDeviceAlreadyInUse";

        case cudaErrorProfilerDisabled:
            return "cudaErrorProfilerDisabled";

        case cudaErrorProfilerNotInitialized:
            return "cudaErrorProfilerNotInitialized";

        case cudaErrorProfilerAlreadyStarted:
            return "cudaErrorProfilerAlreadyStarted";

        case cudaErrorProfilerAlreadyStopped:
            return "cudaErrorProfilerAlreadyStopped";

        /* Since CUDA 4.0*/
        case cudaErrorAssert:
            return "cudaErrorAssert";

        case cudaErrorTooManyPeers:
            return "cudaErrorTooManyPeers";

        case cudaErrorHostMemoryAlreadyRegistered:
            return "cudaErrorHostMemoryAlreadyRegistered";

        case cudaErrorHostMemoryNotRegistered:
            return "cudaErrorHostMemoryNotRegistered";

        /* Since CUDA 5.0 */
        case cudaErrorOperatingSystem:
            return "cudaErrorOperatingSystem";

        case cudaErrorPeerAccessUnsupported:
            return "cudaErrorPeerAccessUnsupported";

        case cudaErrorLaunchMaxDepthExceeded:
            return "cudaErrorLaunchMaxDepthExceeded";

        case cudaErrorLaunchFileScopedTex:
            return "cudaErrorLaunchFileScopedTex";

        case cudaErrorLaunchFileScopedSurf:
            return "cudaErrorLaunchFileScopedSurf";

        case cudaErrorSyncDepthExceeded:
            return "cudaErrorSyncDepthExceeded";

        case cudaErrorLaunchPendingCountExceeded:
            return "cudaErrorLaunchPendingCountExceeded";

        case cudaErrorNotPermitted:
            return "cudaErrorNotPermitted";

        case cudaErrorNotSupported:
            return "cudaErrorNotSupported";

        /* Since CUDA 6.0 */
        case cudaErrorHardwareStackError:
            return "cudaErrorHardwareStackError";

        case cudaErrorIllegalInstruction:
            return "cudaErrorIllegalInstruction";

        case cudaErrorMisalignedAddress:
            return "cudaErrorMisalignedAddress";

        case cudaErrorInvalidAddressSpace:
            return "cudaErrorInvalidAddressSpace";

        case cudaErrorInvalidPc:
            return "cudaErrorInvalidPc";

        case cudaErrorIllegalAddress:
            return "cudaErrorIllegalAddress";

        /* Since CUDA 6.5*/
        case cudaErrorInvalidPtx:
            return "cudaErrorInvalidPtx";

        case cudaErrorInvalidGraphicsContext:
            return "cudaErrorInvalidGraphicsContext";

        case cudaErrorStartupFailure:
            return "cudaErrorStartupFailure";

        case cudaErrorApiFailureBase:
            return "cudaErrorApiFailureBase";
    }

    return "<unknown>";
}

#endif	/* _CUDAUTIL_H */


text:
<?xml version="1.0" encoding="UTF-8"?>

<Widget w="800" h="600">

    <!-- Buttons -->
    <VBox w="800" childPadding="10" padding="10">
        <Button w="300" skin:Paint-border="1" skin:Paint-color="0xaaaaaa" text="'Click here to set \'child.left = 30\''" autoHeight="true" on-click=" #child.left = 30; "/>
        <Button w="300" skin:Paint-border="1" skin:Paint-color="0xaaaaaa" text="'Click here to set \'child.leftPt = 30\''" autoHeight="true" on-click=" #child.leftPt = 30; " />
        <Button w="300" skin:Paint-border="1" skin:Paint-color="0xaaaaaa" text="'Click here to set \'child.right = 30\''" autoHeight="true" on-click=" #child.right = 30; " />
        <Button w="300" skin:Paint-border="1" skin:Paint-color="0xaaaaaa" text="'Click here to set \'child.rightPt = 30\''" autoHeight="true" on-click=" #child.rightPt = 30; " />
        <Button w="300" skin:Paint-border="1" skin:Paint-color="0xaaaaaa" text="'Click here to set \'child.top = 30\''" autoHeight="true" on-click=" #child.top = 30; " />
        <Button w="300" skin:Paint-border="1" skin:Paint-color="0xaaaaaa" text="'Click here to set \'child.topPt = 30\''" autoHeight="true" on-click=" #child.topPt = 30; " />
        <Button w="300" skin:Paint-border="1" skin:Paint-color="0xaaaaaa" text="'Click here to set \'child.bottom = 30\''" autoHeight="true" on-click=" #child.bottom = 30; " />
        <Button w="300" skin:Paint-border="1" skin:Paint-color="0xaaaaaa" text="'Click here to set \'child.bottomPt = 30\''" autoHeight="true" on-click=" #child.bottomPt = 30; " />
    </VBox>

    <!-- parent -->
    <Widget bottom="10" left="50" h="300" w="700" skin:Paint-border="1" skin:Paint-color="0x005500">
        <!-- child -->
        <Widget leftPt="50" topPt="50" id="'child'" w="50" h="50" skin:Paint-border="1" skin:Paint-color="0x550000" />
    </Widget>
</Widget>


text:
layout: post
published: true
title: Something new about changelogs
---

Lately I realized a thing which made me sad: changelog formats are far from standardized.

I stumbled upon this thought while thinking about a way to have `bundle
outdated` to print out a kind of changelog excerpt to help me get an idea
on whether I had to update a gem or skip the latest version for this time.

The first step to achive this would be to have a kind of changelog parser to
extract machine readable data. So I started to look around for a
changelog parser. I hardly found something, which somehow surprised me.

## The official CHANGELOG format

I wasn't able to find an **official spec** for changelogs. I found instead
a [page hosted on gnu.org](http://www.gnu.org/prep/standards/html_node/Style-of-Change-Logs.html)
which lists few advices on how to create a changelog file. It's venerably
old. It describes few rules expecially suited for programs written it C
language.

It lacks of several directions I was expecting to find. For instance it doesn't
say anything about version numbers. It's all about dates of changes.

## Different formats and conventions

I decided to have a deeper look at several popular OSS projects to see how they
behave. I was expecting to find a changelog of any format in the root
directory of the project. I was almost never the case.

### The Linux Kernel

The linux kernel does not have a changelog file in the root directory. There's
a Documentation folder, [with a "Changes" file
inside](https://git.kernel.org/cgit/linux/kernel/git/stable/linux-stable.git/tree/Documentation/Changes?id=refs/tags/v3.13.9).  It's a documentation
file, not a changelog strictly speaking, so it does not track changes in specific versions.
Other changelog files are present in specific component folders.

### Ruby on Rails

There's not a changelog in the main folder, but [several "CHANGELOG.md"](https://github.com/rails/rails)
files inside each component folder. It's a markdown file, with no version numbers
and no dates.

### WordPress

[No changelog at all.](http://core.svn.wordpress.org/trunk/)

### Django

[No changelog.](https://github.com/django/django)

### Rubygems.org

An [History.txt file][2] with version numbers and no dates.

## What about libraries?

Since I'm a Ruby guy, let's have a look at some popular Rubygem:

### Sidekiq

Sidekiq has a [Changes.md](https://github.com/mperham/sidekiq/blob/master/Changes.md)
file which has version number and a bullet list item for each change. No dates.
It has code examples.

### Nokogiri

Has a [Changelog.rdoc](https://github.com/sparklemotion/nokogiri/blob/master/CHANGELOG.rdoc)
file with version and dates as headings, and bullet lists for features and bugfixes.

### Devise

Has a
[CHANGELOG.md](https://github.com/plataformatec/devise/blob/master/CHANGELOG.md)
with version numbers and changes in a bullet list, just like Sidekiq.

## Do I need a changelog?

There are times in which it doesn't make sense to write a changelog.
A small team working on a private project may not find any benefit
in writing a changelog. But if you work on an opensource project, expecially
on a library, you should definitely have one.

Dependencies on a project tend to become difficult to manage also because you
don't have a clear view of what changed.
[Semantic versioning][1] helps us a lot
to quickly understand if it's safe update a component or not.

Is it a bugfix?
You should update ASAP. Is it a minor change? It's safe to update and you
should, because you want to stay close to the edge, right?
Is it a major change? You should take the risk to update because the world is moving on.
_But it's not always that easy._

Even if it's a bugfix, I want to know what changed. And
because every time I run a `bundle outdated` it's always a long list showing
up, I would have a quick summary.

Many times, even minor version changes are too easily applied. If a change is
backward compatible you shuold still **ask yourself if that change is something
you would benefit of**. Most of the times it's a new feature introduced, which
you may not need. Moreover a backward compatible change may introduce a bug.

Developers are often caught by a kind of **up-to-date fever**. I think part of
it is due to the fact that it's hard to have a clear view of your
**outofdateness**.

## Why a shared format is important

Going back to the inital thought which led to all this typing, a shared
standard for changelogs would make it possible to have machines do something
interesting with those files.

[Bundler][3] is one of the many dependency management which may benefit of a
parsable format. Even an online service would be possibile with little effort,
to send you a weekly digest of the changelogs of your project's dependencies.

## Modern requirements for a changelog

Let's have a look at what the specs for a modern changelog should be.

### Version numbers

The most important thing a changelog should tell is the version number the
changes refer to. Listing dates is much less important.

### Markdown

Having a look at what most projects are doing, I think any kind of
text friendly markup language is a desirable feature.
TXT is great, but the world is on the web and
with a tiny markdown effort we can make web pages much more pleasant to read.

Markdown would also make possible to have automated syntax highlight for code
samples and all the stuff we already know and appreciate. This should be optional though.

### List of changes

Those should be listed from the most recent to the oldest. Each item should
start with an item list marker (this may change depending on the makrup
language adopted). Each item should be composed of at least a short summary.

Optionally, a change may have a longer description of the change, links, code
example or any other thing a developer may want to add.

### Authors

This is far less important than the previous three. I would hardly make a
decision on whether a change is something I would apply or not based on who
did that. That should be something you dig into the CVS when interested in.
This one too should be optional.

### Dates

I don't know what to do with dates in a changelog. Again, they may have a
meaning, but what I'm trying to come up with is a format which includes the
basic facts a developer may need to decide if a change is worth upgrading or
not. I don't think anybody would take this decision based on a date. I
consider the date to be optional too.

It's worth nothing that if you like to put dates in a changelog, you may want
to put the dates on change items *and* on version numbers. If you are a date
maniac, you'd probably want to know how many time passed since the last change
and the version release.

### Example

I think something like this should would go as a standard changelog:

    # Acme Products

    ## 2.1.2 (2002-03-10)

    * Added a button to fire missles

      You shuold used this only if in danger. Don't fire for offense. Ever.

      Author: Fabrizio Regini <freegenie@gmail.com>

    * Added breakes

    * Fix a bug in cosmic ray controller

Which in markdown translates into this:

![formatted changelog example](/images/formatted-changelog-example.png)

## Conclusion

I think that having a shared format for Changelogs is a little bit an
**utopia**. But the possibility to have your changes show up nicely
into one of the many dependency management softwares out there may be a huge
stimulus for developers to agree on something.

**What do you think?**

[1]: http://semver.org/ "Semver.org"
[2]: https://github.com/rubygems/rubygems/blob/master/History.txt
[3]: http://bundler.io/