text:
<?php

namespace CKSource\CKFinder\Exception;

use CKSource\CKFinder\Error;

/**
 * Invalid request exception class
 *
 * @copyright 2015 CKSource - Frederico Knabben
 */
class InvalidRequestException extends CKFinderException
{
    /**
     * Constructor
     *
     * @param string     $message    exception message
     * @param array      $parameters parameters passed for translation
     * @param \Exception $previous   previous exception
     */
    public function __construct($message = 'Invalid request', $parameters = array(), \Exception $previous = null)
    {
        parent::__construct($message, Error::INVALID_REQUEST, $parameters, $previous);
    }
}


text:
The `predefined_device` objects contain entries for all device types currently on the system. This is the content of the `PdDv` object class in ODM.

# base flag of <predefined_device> : string

Returns the base flag of the specified predefined device object.

# bus extender flag of <predefined_device> : string

Returns the bus extender flag of the specified predefined device object.

# catalog filename of <predefined_device> : string

Returns the catalog filename of the specified predefined device object.

# change method of <predefined_device> : string

Returns the change method of the specified predefined device object.

# change status flag of <predefined_device> : string

Returns the change status flag of the specified predefined device object.

# class of <predefined_device> : string

Returns the class of the specified predefined device object.

# configure method of <predefined_device> : string

Returns the configure method of the specified predefined device object.

# define method of <predefined_device> : string

Returns the define method of the specified predefined device object.

# detectable flag of <predefined_device> : string

Returns the detectable flag of the specified predefined device object.

# device driver name of <predefined_device> : string

Returns the device driver name of the specified predefined device object.

# fru flag of <predefined_device> : string

Returns the fru flag of the specified predefined device object.

# id of <predefined_device> : string

Returns the id of the specified predefined device object.

# inventory only flag of <predefined_device> : string

Returns the inventory only flag of the specified predefined device object.

# led value of <predefined_device> : string

Returns the led value of the specified predefined device object.

# msg number of <predefined_device> : string

Returns the msg number of the specified predefined device object.

# prefix name of <predefined_device> : string

Returns the prefix name of the specified predefined device object.

# set number of <predefined_device> : string

Returns the set number of the specified predefined device object.

# start method of <predefined_device> : string

Returns the start method of the specified predefined device object.

# stop method of <predefined_device> : string

Returns the stop method of the specified predefined device object.

# subclass of <predefined_device> : string

Returns the subclass of the specified predefined device object.

# type of <predefined_device> : string

Returns the type of the specified predefined device object.

# unconfigure method of <predefined_device> : string

Returns the unconfigure method of the specified predefined device object.

# undefine method of <predefined_device> : string

Returns the undefine method of the specified predefined device object.

# unique type of <predefined_device> : string

Returns the unique type of the specified predefined device object.

# vpd flag of <predefined_device> : string

Returns the vpd flag of the specified predefined device object.

# <predefined_device> as string : string

Returns a string representation of a predefined device object in the format "uniquetype class".

redpajama_set_name: RedPajamaGithub


text:
@interface KHTenViewController : KHBaseViewController

@property (nonatomic,copy) NSString *area;

@property (nonatomic,copy) NSString *port;
@end


text:
package org.purview.qtui

import com.trolltech.qt.core.QDir
import com.trolltech.qt.core.Qt
import com.trolltech.qt.gui.QAction
import com.trolltech.qt.gui.QApplication
import com.trolltech.qt.gui.QFileDialog
import com.trolltech.qt.gui.QIcon
import com.trolltech.qt.gui.QMainWindow
import com.trolltech.qt.gui.QMenu
import com.trolltech.qt.gui.QMenuBar
import com.trolltech.qt.gui.QMessageBox
import com.trolltech.qt.gui.QPixmap
import com.trolltech.qt.gui.QTabWidget
import com.trolltech.qt.gui.QToolBar
import java.io.File
import javax.imageio.ImageIO
import org.purview.core.analysis.Analyser
import org.purview.core.data.ImageMatrix
import org.purview.core.session.SessionUtils
import org.purview.qtui.meta.ImageSession

object MainWindow extends QMainWindow {
  if(objectName.isEmpty)
    setObjectName("MainWindow")

  setWindowTitle("Purview 1.2")
  setWindowIcon(QIcon.fromTheme("purview", new QIcon("classpath:icons/purview.png")))
  setMinimumSize(800, 600)

  addDockWidget(Qt.DockWidgetArea.BottomDockWidgetArea, AnalysisView)
  AnalysisView.hide()
  addDockWidget(Qt.DockWidgetArea.LeftDockWidgetArea, ResultsView)
  ResultsView.hide()
  addDockWidget(Qt.DockWidgetArea.BottomDockWidgetArea, LogView)
  LogView.hide()

  //A simple helper method for modifying something when it's constructed
  private def construct[A](what: A)(constructionBody: A => Any) = {
    constructionBody(what)
    what
  }

  private val shallowAnalysers = SessionUtils.createAnalyserInstances[ImageMatrix]

  private val tabWidget = new QTabWidget(this) {
    currentChanged.connect(this, "changeSession(int)")
    tabCloseRequested.connect(this, "closeTab(int)")
    tabCloseRequested.connect(MainWindow.this, "updateToolbar()")
    setDocumentMode(true)
    setTabsClosable(true)

    private def changeSession(sessionNr: Int) = {
      val ana = Option(currentWidget.asInstanceOf[ImageSessionWidget]) flatMap {_.imageSession.analysis}
      AnalysisView.analysis = ana
      ResultsView.analysis = ana
      updateToolbar()
    }

    def closeTab(tab: Int) = {
      widget(tab).close()
      removeTab(tab)
    }
  }

  private val openImageAction = new QAction(this) {
    setText("&Open Image...")
    setShortcut("Ctrl+N")
    setIcon(QIcon.fromTheme("folder-image", new QIcon("classpath:icons/folder-image.png")))
    triggered.connect(this, "selectImage()")

    private def selectImage() = {
      val filename = QFileDialog.getOpenFileName(MainWindow.this, "Open image", QDir.homePath,
                                                 new QFileDialog.Filter(ImageIO.getReaderFileSuffixes.mkString("Image files (*.", " *.", ")")))
      val sessionWidget = new ImageSessionWidget(new ImageSession(new File(filename)))
      tabWidget.addTab(sessionWidget, QIcon.fromTheme("image-x-generic", new QIcon("classpath:icons/image-x-generic.png")), sessionWidget.windowTitle)
      updateToolbar()
    }
  }

  private val saveReportAction = new QAction(this) {
    setText("Save report image...")
    setShortcut("Ctrl+S")
    setIcon(QIcon.fromTheme("document-save-all", new QIcon("classpath:icons/document-save-all.png")))
    triggered.connect(this, "saveImages()")

    def saveImages() = {
      val file = QFileDialog.getSaveFileName(MainWindow.this, "Save SVG", QDir.homePath, new QFileDialog.Filter("SVG files (*.svg)"))
      Option(tabWidget.currentWidget.asInstanceOf[ImageSessionWidget]).foreach(_.saveImageTo(file))
    }
  }

  private val exitAction = new QAction(this) {
    setText("&Quit Purview")
    setShortcut("Ctrl+Q")
    setIcon(QIcon.fromTheme("dialog-error", new QIcon("classpath:icons/dialog-error.png")))
    triggered.connect(QApplication.instance(), "quit()")
  }

  private val showAnalysisAction = new QAction(this) {
    setText("&Analysis window")
    setShortcut("Ctrl+A")
    setIcon(AnalysisView.windowIcon)
    setCheckable(true)
    setChecked(false)
    toggled.connect(AnalysisView, "setVisible(boolean)")
    AnalysisView.visibilityChanged.connect(this: QAction /*!!*/, "setChecked(boolean)")
  }

  private val showResultsAction = new QAction(this) {
    setText("&Results window")
    setShortcut("Ctrl+R")
    setIcon(ResultsView.windowIcon)
    setCheckable(true)
    setChecked(false)
    toggled.connect(ResultsView, "setVisible(boolean)")
    ResultsView.visibilityChanged.connect(this: QAction /*!!*/, "setChecked(boolean)")
  }

  private val showLogAction = new QAction(this) {
    setText("&Log window")
    setShortcut("Ctrl+L")
    setIcon(LogView.windowIcon)
    setCheckable(true)
    setChecked(false)
    toggled.connect(LogView, "setVisible(boolean)")
    LogView.visibilityChanged.connect(this: QAction /*!!*/, "setChecked(boolean)")
  }

  private val aboutAction = new QAction(this) {
    setText("&About Purview...")
    setIcon(QIcon.fromTheme("dialog-information", new QIcon("classpath:icons/dialog-information.png")))
    setShortcut("F1")
    triggered.connect(this, "showAboutDialog()")
    private def showAboutDialog() = QMessageBox.about(MainWindow.this, "About Purview", MainWindowTemplates.aboutText)
  }

  private val aboutQtAction = new QAction(this) {
    setText("About &Qt...")
    setIcon(QIcon.fromTheme("qt", new QIcon("classpath:icons/qt.png")))
    triggered.connect(this, "showAboutQtDialog()")
    private def showAboutQtDialog() = QMessageBox.aboutQt(MainWindow.this)
  }

  private val analyseAction = new QAction(this) {
    setText("Analyse &image")
    setIcon(QIcon.fromTheme("system-run", new QIcon("classpath:icons/system-run.png")))
    setShortcut("Ctrl+A")
    setEnabled(false)
    triggered.connect(this, "analyse()")
    private def analyse() = {
      AnalysisView.show()
      val imgWidget = tabWidget.currentWidget.asInstanceOf[ImageSessionWidget]
      imgWidget.analyse()
      imgWidget.imageSession.analysis.foreach(_.finished.connect(this, "refreshResultsView()"))
      AnalysisView.analysis = imgWidget.imageSession.analysis
      updateToolbar()
    }
    private def refreshResultsView() = {
      ResultsView.show()
      val imgWidget = Option(tabWidget.currentWidget.asInstanceOf[ImageSessionWidget])
      ResultsView.analysis = imgWidget.flatMap(_.imageSession.analysis)
      ResultsView.analysis.foreach {a =>
        a.finished.disconnect(this)
      }
    }
  }

  private val configureAnalysersAction = new QAction(this) {
    setText("&Configure analysers...")
    setIcon(QIcon.fromTheme("configure", new QIcon("classpath:icons/configure.png")))
    setShortcut("Ctrl+C")
    setEnabled(false)
    triggered.connect(this, "configureAnalysers()")
    private def configureAnalysers() = tabWidget.currentWidget.asInstanceOf[ImageSessionWidget].configureAnalysers()
  }

  private val zoomInAction = new QAction(this) {
    setText("Zoom &in")
    setShortcut("Ctrl++")
    setIcon(QIcon.fromTheme("zoom-in", new QIcon("classpath:icons/zoom-in.png")))
    setEnabled(false)
    triggered.connect(this, "zoomIn()")
    def zoomIn() = tabWidget.currentWidget.asInstanceOf[ImageSessionWidget].scale(1.25, 1.25)
  }

  private val zoomOutAction = new QAction(this) {
    setText("Zoom &out")
    setShortcut("Ctrl+-")
    setIcon(QIcon.fromTheme("zoom-out", new QIcon("classpath:icons/zoom-out.png")))
    setEnabled(false)
    triggered.connect(this, "zoomOut()")
    private def zoomOut() = tabWidget.currentWidget.asInstanceOf[ImageSessionWidget].scale(0.8, 0.8)
  }

  private val zoomOrigAction = new QAction(this) {
    setText("O&riginal size")
    setShortcut("Ctrl+0")
    setIcon(QIcon.fromTheme("zoom-original", new QIcon("classpath:icons/zoom-original.png")))
    setEnabled(false)
    triggered.connect(this, "zoomOrig()")
    private def zoomOrig() = tabWidget.currentWidget.asInstanceOf[ImageSessionWidget].resetTransform()
  }

  private val analyserActions = for(analyser <- shallowAnalysers) yield
    new QAction(this) {
      setIcon(analyser.iconResource.map(x => new QIcon("classpath:" + x)) getOrElse QIcon.fromTheme("system-run", new QIcon("classpath:icons/system-run.png")))
      setText("About \"" + analyser.name + "\"...")
      setToolTip(analyser.description)
      setData(analyser)
      triggered.connect(this, "analyserInfoClicked()")
      private def analyserInfoClicked() = {
        val buttons = new QMessageBox.StandardButtons(QMessageBox.StandardButton.Ok)
        val messageBox = new QMessageBox(QMessageBox.Icon.NoIcon, "About \"" + analyser.name + "\"",
                                         MainWindowTemplates.aboutAnalyserText(analyser), buttons, MainWindow.this)
        val pixmap = new QPixmap("classpath:" + (analyser.iconResource getOrElse "icons/system-run.png"))
        val scaledPixmap = pixmap.scaled(64, 64,
                                         Qt.AspectRatioMode.KeepAspectRatio,
                                         Qt.TransformationMode.SmoothTransformation)
        messageBox.setIconPixmap(scaledPixmap)
        messageBox.exec()
      }
    }

  private val menuFile = new QMenu(this) {
    setTitle("&File")
    addAction(openImageAction)
    addAction(saveReportAction)
    addAction(analyseAction)
    addAction(configureAnalysersAction)
    addSeparator()
    addAction(exitAction)
  }

  private val menuWindow = new QMenu(this) {
    setTitle("&Window")
    addAction(showAnalysisAction)
    addAction(showResultsAction)
    addAction(showLogAction)
    addSeparator()
    addAction(zoomInAction)
    addAction(zoomOutAction)
    addAction(zoomOrigAction)
  }

  private val menuHelp = new QMenu(this) {
    setTitle("&Help")
    analyserActions.foreach(addAction)
    addSeparator()
    addAction(aboutAction)
    addAction(aboutQtAction)
  }

  private val mainToolBar = new QToolBar(this) {
    setWindowTitle("&Main toolbar")
    setFloatable(true)
    setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon)
    addAction(openImageAction)
  }

  private val analysisToolBar = new QToolBar(this) {
    setWindowTitle("A&nalysis toolbar")
    setFloatable(true)
    setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon)
    addAction(analyseAction)
    addAction(configureAnalysersAction)
  }

  private val interactToolBar = new QToolBar(this) {
    setWindowTitle("Interact tool&bar")
    setFloatable(true)
    setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon)
    addAction(zoomInAction)
    addAction(zoomOutAction)
    addSeparator()
    addAction(zoomOrigAction)
  }

  private val menu = new QMenuBar(this) {
    setWindowTitle("Menu bar")
    addMenu(menuFile)
    addMenu(menuWindow)
    addMenu(menuHelp)
  }

  addToolBar(mainToolBar)
  addToolBar(analysisToolBar)
  addToolBar(interactToolBar)

  setCentralWidget(tabWidget)
  setMenuBar(menu)

  protected def updateToolbar() {
    val enabled = (tabWidget.currentIndex > -1)
    val imgWidget = Option(tabWidget.currentWidget.asInstanceOf[ImageSessionWidget])
    analyseAction.setEnabled(imgWidget flatMap (_.imageSession.analysis) match {
        case Some(analysis) => analysis.results.isDefined
        case None => enabled
      })
    configureAnalysersAction.setEnabled(enabled)
    zoomInAction.setEnabled(enabled)
    zoomOutAction.setEnabled(enabled)
    zoomOrigAction.setEnabled(enabled)
  }
}

object MainWindowTemplates {
  val aboutText = {

About Purview

        Purview is an automated image forensics tool, used for detecting digital image forgeries.

        For more information, access to the source code and information
        about the project in general, please see
        http://github.com/dflemstr/purview

        Purview is available under the Apache 2.0 license.
        Please visit
        http://www.apache.org/licenses/
        for more information.

        Copyright © 2010 David Flemström and Moritz Roth

  }.toString

  def aboutAnalyserText(analyser: Analyser[ImageMatrix]) = {

        Name:
        {analyser.name}

        Description:
        {analyser.description}

      {
        analyser.author.map {auth =>

            Author:
            {auth}

        } getOrElse ""
      }
      {
        analyser.version.map {ver =>

            Version:
            {ver}

        } getOrElse ""
      }

  }.toString
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project-private xmlns="http://www.netbeans.org/ns/project-private/1">
    <editor-bookmarks xmlns="http://www.netbeans.org/ns/editor-bookmarks/2" lastBookmarkId="0"/>
    <open-files xmlns="http://www.netbeans.org/ns/projectui-open-files/2">
        <group>
            <file>file:/F:/Java-workspace/СУ%20-%20УП%20Java/28.03.2016/Домашно/ComputeMinPerimeter/src/computeminperimeter/ComputeMinPerimeter.java</file>
        </group>
    </open-files>
</project-private>


text:
"""Add missing constraints for threats

Revision ID: 62f26762d0a
Revises: 2837682ad516
Create Date: 2015-11-12 16:10:29.579969

"""

from alembic import op
# from ggrc.migrations.utils.resolve_duplicates import resolve_duplicates
# from ggrc_risks.models import Threat

# revision identifiers, used by Alembic.
revision = '62f26762d0a'
down_revision = '2837682ad516'

def upgrade():
  # resolve_duplicates(Threat, 'slug')
  op.create_unique_constraint('uq_threats', 'threats', ['slug'])

def downgrade():
  op.drop_constraint('uq_threats', 'threats', 'unique')


text:
/**
 * Created by Oliver(AnounFX™) on 8/01/2017.
 */
exports.run = async (bot, message) => {
    let stats = await bot.getStats();
    stats.lizard++;
    bot.saveStats(stats);
    await bot.snekfetch.get(`https://discordbots.org/api/bots/334186716770598912/votes?onlyids=1`)
        .set('Authorization', bot.config.dblkey)
        .then(rsp => {
            if (!rsp.body.includes(message.author.id)) return message.reply(`hmmmm, you must upvote at https://discordbots.org/bot/${bot.user.id}`);
    bot.snekfetch.get('https://nekos.life/api/lizard')
    .then(r => message.channel.send({
        embed: {
            color: bot.getRandomColor(),
            author: {
                name: "Lizard \\o/",
                icon_url: bot.user.avatarURL
            },
            image: {
                url: r.body.url
            }
        }
    }).catch(e => console.warn('wew tf happened here ' + e)));
        });

};


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;
var DocumentRole = {
  relatedConcepts: [{
    module: 'ARIA',
    concept: {
      name: 'document'
    }
  }],
  type: 'structure'
};
var _default = DocumentRole;
exports["default"] = _default;


text:
Lomse incorporates source code from third parties:

- [agg](#agg)
- [pugixml](#pugixml)
- [MiniZip](#minizip)
- [utfcpp](#utfcpp)

When building the library it links with other libraries:

- [zlib](#zlib)
- [libpng](#libpng)
- [FreeType](#freetype2)
- [UnitTest++](#unittest)
- [fontconfig](#fontconfig) (only for Unix platforms)

Details about these third party materials follow.

## Source code from third parties

### agg
The Anti-Grain Geometry software (AGG version 2.4) developed by Maxim Shemanarev, is an open source, free 2D vector graphics library. It produces pixel images in memory from vectorial data, supports anti-aliasing and has a very high performance. It is platform independent, very flexible and extensible, with a lightweight design and has very good reliability and stability.

**Source**:
- https://sourceforge.net/projects/agg/
- https://github.com/ghaerr/agg-2.6/tree/master/agg-src

**License**: Anti-Grain Geometry Public License

```
Anti-Grain Geometry - Version 2.4
Copyright (C) 2002-2005 Maxim Shemanarev (McSeem)

Permission to copy, use, modify, sell and distribute this software
is granted provided this copyright notice appears in all copies.
This software is provided "as is" without express or implied
warranty, and with no claim as to its suitability for any purpose.
```

### pugixml
It is a light-weight, simple and fast XML parser for C++ with XPath support. The library is extremely portable and easy to integrate and use. It is maintained by Arseny Kapoulkine.

**Source**:
- https://github.com/zeux/pugixml
- http://pugixml.org

**License**: MIT License

```
Copyright (c) 2006-2022 Arseny Kapoulkine

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.
```

### MiniZip
It is an interface to the Zlib library for extracting files from a .zip archive. MiniZip is copyright (c) by Gilles Vollant and Mathias Svensson and is free to use, even in commercial applications.

**Source**:
- https://github.com/madler/zlib/tree/master/contrib/minizip
- https://www.winimage.com/zLibDll/minizip.html

**License**: ZLib License

```
  Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler

  This software is provided 'as-is', without any express or implied
  warranty.  In no event will the authors be held liable for any damages
  arising from the use of this software.

  Permission is granted to anyone to use this software for any purpose,
  including commercial applications, and to alter it and redistribute it
  freely, subject to the following restrictions:

  1. The origin of this software must not be misrepresented; you must not
     claim that you wrote the original software. If you use this software
     in a product, an acknowledgment in the product documentation would be
     appreciated but is not required.
  2. Altered source versions must be plainly marked as such, and must not be
     misrepresented as being the original software.
  3. This notice may not be removed or altered from any source distribution.

  Jean-loup Gailly        Mark Adler
  jloup@gzip.org          madler@alumni.caltech.edu
```

### utfcpp
It is a simple, portable and lightweigt C++ library for easy handling of UTF-8 encoded strings. It relies on std::string for strings and provides lots of utility functions for iterating through UTF-8 encoded strings, converting between UTF-8 and UTF-16/UTF-32, and detecting invalid UTF-8 sequencesetc. It is just header files. Utfcpp is Copyright 2006 Nemanja Trifunovic.

**Source**: https://github.com/nemtrif/utfcpp

**License**: Boost Software License 1.0

```
Boost Software License - Version 1.0 - August 17th, 2003

Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:

The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.

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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
```

## Libraries that will be linked when building

### libpng
It is the official Portable Network Graphics (PNG) reference library. It is a platform-independent library that contains C functions for handling PNG images.

**Source**:
- https://github.com/glennrp/libpng
- https://sourceforge.net/projects/libpng/files/
- http://www.libpng.org/pub/png/libpng.html

**License**: PNG Reference Library License version 2

```
PNG Reference Library License version 2
---------------------------------------

 * Copyright (c) 1995-2019 The PNG Reference Library Authors.
 * Copyright (c) 2018-2019 Cosmin Truta.
 * Copyright (c) 2000-2002, 2004, 2006-2018 Glenn Randers-Pehrson.
 * Copyright (c) 1996-1997 Andreas Dilger.
 * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.

The software is supplied "as is", without warranty of any kind,
express or implied, including, without limitation, the warranties
of merchantability, fitness for a particular purpose, title, and
non-infringement.  In no event shall the Copyright owners, or
anyone distributing the software, be liable for any damages or
other liability, whether in contract, tort or otherwise, arising
from, out of, or in connection with the software, or the use or
other dealings in the software, even if advised of the possibility
of such damage.

Permission is hereby granted to use, copy, modify, and distribute
this software, or portions hereof, for any purpose, without fee,
subject to the following restrictions:

 1. The origin of this software must not be misrepresented; you
    must not claim that you wrote the original software.  If you
    use this software in a product, an acknowledgment in the product
    documentation would be appreciated, but is not required.

 2. Altered source versions must be plainly marked as such, and must
    not be misrepresented as being the original software.

 3. This Copyright notice may not be removed or altered from any
    source or altered source distribution.
```

### Zlib
It is a general purpose compression/decompression library, written by Jean-Loup Gailly and Mark Adler. It supports the algorithm used in the ZIP archive format and it is used by Lomse to decode ZIP files. Zlib is also required by libpng.

**Source**:
- https://github.com/madler/zlib
- http://www.zlib.net/

**License**: ZLib License

```
  Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler

  This software is provided 'as-is', without any express or implied
  warranty.  In no event will the authors be held liable for any damages
  arising from the use of this software.

  Permission is granted to anyone to use this software for any purpose,
  including commercial applications, and to alter it and redistribute it
  freely, subject to the following restrictions:

  1. The origin of this software must not be misrepresented; you must not
     claim that you wrote the original software. If you use this software
     in a product, an acknowledgment in the product documentation would be
     appreciated but is not required.
  2. Altered source versions must be plainly marked as such, and must not be
     misrepresented as being the original software.
  3. This notice may not be removed or altered from any source distribution.

  Jean-loup Gailly        Mark Adler
  jloup@gzip.org          madler@alumni.caltech.edu
```

### UnitTest++
UnitTest++ is a lightweight unit testing framework for C++, designed to do test-driven development on a wide variety of platforms. Lomse uses UnitTest++ for library development.

**Source**: https://github.com/unittest-cpp/unittest-cpp

**License**: MIT License

```
Copyright (c) 2006 Noel Llopis and Charles Nicholson

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.
```

### fontconfig
It is a free library designed to provide configuration, enumeration and substitution of fonts to other programs. Fontconfig was originally written and maintained by Keith Packard, and is currently maintained by Behdad Esfahbod.

**Source**:
- https://gitlab.freedesktop.org/fontconfig/fontconfig
- https://www.freedesktop.org/wiki/Software/fontconfig/

**License**: Fontconfig License

```
Copyright © 2000,2001,2002,2003,2004,2006,2007 Keith Packard
Copyright © 2005 Patrick Lam
Copyright © 2007 Dwayne Bailey and Translate.org.za
Copyright © 2009 Roozbeh Pournader
Copyright © 2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019,2020 Red Hat, Inc.
Copyright © 2008 Danilo Šegan
Copyright © 2012 Google, Inc.

Permission to use, copy, modify, distribute, and sell this software and its
documentation for any purpose is hereby granted without fee, provided that
the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation, and that the name of the author(s) not be used in
advertising or publicity pertaining to distribution of the software without
specific, written prior permission.  The authors make no
representations about the suitability of this software for any purpose.  It
is provided "as is" without express or implied warranty.

THE AUTHOR(S) DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY SPECIAL, INDIRECT OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
```

### FreeType2
It is a free open source font engine, designed to be small, efficient, highly customizable and portable, while capable of producing high-quality output (glyph images). It was developed by David Turner, Robert Wilhelm, and Werner Lemberg. FreeType is copyright (c) 1996-2002 The FreeType Project.

**Source**:
- https://gitlab.freedesktop.org/freetype/freetype
- https://freetype.org/

**License**: FreeType License (BSD-like license)

```
                    The FreeType Project LICENSE
                    ----------------------------

                            2006-Jan-27

                    Copyright 1996-2002, 2006 by
          David Turner, Robert Wilhelm, and Werner Lemberg

Introduction
============

  The FreeType  Project is distributed in  several archive packages;
  some of them may contain, in addition to the FreeType font engine,
  various tools and  contributions which rely on, or  relate to, the
  FreeType Project.

  This  license applies  to all  files found  in such  packages, and
  which do not  fall under their own explicit  license.  The license
  affects  thus  the  FreeType   font  engine,  the  test  programs,
  documentation and makefiles, at the very least.

  This  license   was  inspired  by  the  BSD,   Artistic,  and  IJG
  (Independent JPEG  Group) licenses, which  all encourage inclusion
  and  use of  free  software in  commercial  and freeware  products
  alike.  As a consequence, its main points are that:

    o We don't promise that this software works. However, we will be
      interested in any kind of bug reports. (`as is' distribution)

    o You can  use this software for whatever you  want, in parts or
      full form, without having to pay us. (`royalty-free' usage)

    o You may not pretend that  you wrote this software.  If you use
      it, or  only parts of it,  in a program,  you must acknowledge
      somewhere  in  your  documentation  that  you  have  used  the
      FreeType code. (`credits')

  We  specifically  permit  and  encourage  the  inclusion  of  this
  software, with  or without modifications,  in commercial products.
  We  disclaim  all warranties  covering  The  FreeType Project  and
  assume no liability related to The FreeType Project.

  Finally,  many  people  asked  us  for  a  preferred  form  for  a
  credit/disclaimer to use in compliance with this license.  We thus
  encourage you to use the following text:

   """
    Portions of this software are copyright © <year> The FreeType
    Project (www.freetype.org).  All rights reserved.
   """

  Please replace <year> with the value from the FreeType version you
  actually use.

Legal Terms
===========

0. Definitions
--------------

  Throughout this license,  the terms `package', `FreeType Project',
  and  `FreeType  archive' refer  to  the  set  of files  originally
  distributed  by the  authors  (David Turner,  Robert Wilhelm,  and
  Werner Lemberg) as the `FreeType Project', be they named as alpha,
  beta or final release.

  `You' refers to  the licensee, or person using  the project, where
  `using' is a generic term including compiling the project's source
  code as  well as linking it  to form a  `program' or `executable'.
  This  program is  referred to  as  `a program  using the  FreeType
  engine'.

  This  license applies  to all  files distributed  in  the original
  FreeType  Project,   including  all  source   code,  binaries  and
  documentation,  unless  otherwise  stated   in  the  file  in  its
  original, unmodified form as  distributed in the original archive.
  If you are  unsure whether or not a particular  file is covered by
  this license, you must contact us to verify this.

  The FreeType  Project is copyright (C) 1996-2000  by David Turner,
  Robert Wilhelm, and Werner Lemberg.  All rights reserved except as
  specified below.

1. No Warranty
--------------

  THE FREETYPE PROJECT  IS PROVIDED `AS IS' WITHOUT  WARRANTY OF ANY
  KIND, EITHER  EXPRESS OR IMPLIED,  INCLUDING, BUT NOT  LIMITED TO,
  WARRANTIES  OF  MERCHANTABILITY   AND  FITNESS  FOR  A  PARTICULAR
  PURPOSE.  IN NO EVENT WILL ANY OF THE AUTHORS OR COPYRIGHT HOLDERS
  BE LIABLE  FOR ANY DAMAGES CAUSED  BY THE USE OR  THE INABILITY TO
  USE, OF THE FREETYPE PROJECT.

2. Redistribution
-----------------

  This  license  grants  a  worldwide, royalty-free,  perpetual  and
  irrevocable right  and license to use,  execute, perform, compile,
  display,  copy,   create  derivative  works   of,  distribute  and
  sublicense the  FreeType Project (in  both source and  object code
  forms)  and  derivative works  thereof  for  any  purpose; and  to
  authorize others  to exercise  some or all  of the  rights granted
  herein, subject to the following conditions:

    o Redistribution of  source code  must retain this  license file
      (`FTL.TXT') unaltered; any  additions, deletions or changes to
      the original  files must be clearly  indicated in accompanying
      documentation.   The  copyright   notices  of  the  unaltered,
      original  files must  be  preserved in  all  copies of  source
      files.

    o Redistribution in binary form must provide a  disclaimer  that
      states  that  the software is based in part of the work of the
      FreeType Team,  in  the  distribution  documentation.  We also
      encourage you to put an URL to the FreeType web page  in  your
      documentation, though this isn't mandatory.

  These conditions  apply to any  software derived from or  based on
  the FreeType Project,  not just the unmodified files.   If you use
  our work, you  must acknowledge us.  However, no  fee need be paid
  to us.

3. Advertising
--------------

  Neither the  FreeType authors and  contributors nor you  shall use
  the name of the  other for commercial, advertising, or promotional
  purposes without specific prior written permission.

  We suggest,  but do not require, that  you use one or  more of the
  following phrases to refer  to this software in your documentation
  or advertising  materials: `FreeType Project',  `FreeType Engine',
  `FreeType library', or `FreeType Distribution'.

  As  you have  not signed  this license,  you are  not  required to
  accept  it.   However,  as  the FreeType  Project  is  copyrighted
  material, only  this license, or  another one contracted  with the
  authors, grants you  the right to use, distribute,  and modify it.
  Therefore,  by  using,  distributing,  or modifying  the  FreeType
  Project, you indicate that you understand and accept all the terms
  of this license.

4. Contacts
-----------

  There are two mailing lists related to FreeType:

    o freetype@nongnu.org

      Discusses general use and applications of FreeType, as well as
      future and  wanted additions to the  library and distribution.
      If  you are looking  for support,  start in  this list  if you
      haven't found anything to help you in the documentation.

    o freetype-devel@nongnu.org

      Discusses bugs,  as well  as engine internals,  design issues,
      specific licenses, porting, etc.

  Our home page can be found at

    http://www.freetype.org

--- end of FTL.TXT ---
```


text:
package com.kotcrab.vis.editor.module.scene.system.inflater;

import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.kotcrab.vis.editor.util.gdx.DummyMusic;
import com.kotcrab.vis.runtime.component.AssetReference;
import com.kotcrab.vis.runtime.component.VisMusic;
import com.kotcrab.vis.runtime.component.proto.ProtoVisMusic;
import com.kotcrab.vis.runtime.system.inflater.InflaterSystem;

/** @author Kotcrab */
public class EditorMusicInflater extends InflaterSystem {
	private ComponentMapper<VisMusic> musicCm;
	private ComponentMapper<ProtoVisMusic> protoCm;

	public EditorMusicInflater () {
		super(Aspect.all(ProtoVisMusic.class, AssetReference.class));
	}

	@Override
	protected void inserted (int entityId) {
		ProtoVisMusic protoVisMusic = protoCm.get(entityId);

		VisMusic music = musicCm.create(entityId);
		music.music = new DummyMusic();
		protoVisMusic.fill(music);

		protoCm.remove(entityId);
	}
}


text:
/*	$NetBSD: ntfs_subr.h,v 1.8 1999/10/10 14:48:37 jdolecek Exp $	*/

/*-
 * Copyright (c) 1998, 1999 Semen Ustimenko
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * $FreeBSD: releng/9.3/sys/fs/ntfs/ntfs_subr.h 230197 2012-01-16 05:22:18Z kevlo $
 */

#define	VA_LOADED		0x0001
#define	VA_PRELOADED		0x0002

struct ntvattr {
	LIST_ENTRY(ntvattr) 	va_list;

	u_int32_t		va_vflag;
	struct vnode	       *va_vp;
	struct ntnode 	       *va_ip;

	u_int32_t		va_flag;
	u_int32_t		va_type;
	u_int8_t		va_namelen;
	char			va_name[NTFS_MAXATTRNAME];

	u_int32_t		va_compression;
	u_int32_t		va_compressalg;
	u_int64_t		va_datalen;
	u_int64_t		va_allocated;
	cn_t	 		va_vcnstart;
	cn_t	 		va_vcnend;
	u_int16_t		va_index;
	union {
		struct {
			cn_t *		cn;
			cn_t *		cl;
			u_long		cnt;
		} vrun;
		caddr_t		datap;
		struct attr_name *name;
		struct attr_indexroot *iroot;
		struct attr_indexalloc *ialloc;
	} va_d;
};
#define	va_vruncn	va_d.vrun.cn
#define va_vruncl	va_d.vrun.cl
#define va_vruncnt	va_d.vrun.cnt
#define va_datap	va_d.datap
#define va_a_name	va_d.name
#define va_a_iroot	va_d.iroot
#define va_a_ialloc	va_d.ialloc

struct componentname;
struct fnode;
struct uio;

int ntfs_procfixups( struct ntfsmount *, u_int32_t, caddr_t, size_t );
int ntfs_parserun( cn_t *, cn_t *, u_int8_t *, u_long, u_long *);
int ntfs_runtocn( cn_t *, struct ntfsmount *, u_int8_t *, u_long, cn_t);
int ntfs_readntvattr_plain( struct ntfsmount *, struct ntnode *, struct ntvattr *, off_t, size_t, void *,size_t *, struct uio *);
int ntfs_readattr_plain( struct ntfsmount *, struct ntnode *, u_int32_t, char *, off_t, size_t, void *,size_t *, struct uio *);
int ntfs_readattr( struct ntfsmount *, struct ntnode *, u_int32_t, char *, off_t, size_t, void *, struct uio *);
int ntfs_filesize( struct ntfsmount *, struct fnode *, u_int64_t *, u_int64_t *);
int ntfs_times( struct ntfsmount *, struct ntnode *, ntfs_times_t *);
struct timespec	ntfs_nttimetounix( u_int64_t );
int ntfs_ntreaddir( struct ntfsmount *, struct fnode *, u_int32_t, struct attr_indexentry **);
int ntfs_runtovrun( cn_t **, cn_t **, u_long *, u_int8_t *);
int ntfs_attrtontvattr( struct ntfsmount *, struct ntvattr **, struct attr * );
void ntfs_freentvattr( struct ntvattr * );
int ntfs_loadntvattrs( struct ntfsmount *, struct vnode *, caddr_t, struct ntvattr **);
struct ntvattr * ntfs_findntvattr( struct ntfsmount *, struct ntnode *, u_int32_t, cn_t );
int ntfs_ntlookupfile(struct ntfsmount *, struct vnode *, struct componentname *, struct vnode **);
int ntfs_isnamepermitted(struct ntfsmount *, struct attr_indexentry * );
int ntfs_ntvattrrele(struct ntvattr * );
int ntfs_ntvattrget(struct ntfsmount *, struct ntnode *, u_int32_t, const char *, cn_t , struct ntvattr **);
int ntfs_ntlookup(struct ntfsmount *, ino_t, struct ntnode **);
int ntfs_ntget(struct ntnode *);
void ntfs_ntref(struct ntnode *);
void ntfs_ntrele(struct ntnode *);
void ntfs_ntput(struct ntnode *);
int ntfs_loadntnode( struct ntfsmount *, struct ntnode * );
int ntfs_writentvattr_plain(struct ntfsmount *, struct ntnode *, struct ntvattr *, off_t, size_t, void *, size_t *, struct uio *);
int ntfs_writeattr_plain(struct ntfsmount *, struct ntnode *, u_int32_t, char *, off_t, size_t, void *, size_t *, struct uio *);
void ntfs_toupper_init(void);
void ntfs_toupper_destroy(void);
int ntfs_toupper_use(struct mount *, struct ntfsmount *);
void ntfs_toupper_unuse(void);
int ntfs_fget(struct ntfsmount *, struct ntnode *, int, char *, struct fnode **);
void ntfs_frele(struct fnode *);

int ntfs_u28_init(struct ntfsmount *ntmp, wchar *u2w, char *cs_local, char *cs_ntfs);
int ntfs_u28_uninit(struct ntfsmount *ntmp);
int ntfs_82u_init(struct ntfsmount *ntmp, char *cs_local, char *cs_ntfs);
int ntfs_82u_uninit(struct ntfsmount *ntmp);
char * ntfs_u28(char *outbuf, struct ntfsmount *ntmp, wchar wc);
wchar ntfs_82u(struct ntfsmount *ntmp, const char *c, int *len);
#define NTFS_U28(ch)		ntfs_u28(tmpbuf, ntmp, (ch))
#define NTFS_82U(ch, len)	ntfs_82u(ntmp, (ch), len)
#define	NTFS_UASTRCMP(ustr, ustrlen, astr, astrlen)	\
	ntfs_uastrcmp(ntmp, (ustr), (ustrlen), (astr), (astrlen))
#define	NTFS_UASTRICMP(ustr, ustrlen, astr, astrlen)	\
	ntfs_uastricmp(ntmp, (ustr), (ustrlen), (astr), (astrlen))


text:
{% extends 'base.html' %}

{% load i18n static %}
{% load widget_tweaks %}
{% load staticfiles %}

{% block title %}
  <title>Fix My Django! Sign up</title>
{% endblock title %}

{% block content %}

Sing up

        {% if form.errors and not form.non_field_errors %}

          {% if form.errors.items|length == 1 %}{% trans "Please correct the error below." %}{% else %}{% trans "Please correct the errors below." %}{% endif %}

         {% endif %}

         {% if form.non_field_errors %}
          {% for error in form.non_field_errors %}

              {{ error }}

          {% endfor %}
        {% endif %}
        <form action="{{ app_path }}" method="post" id="login-form">

              {% csrf_token %}

                Email
                {{ form.email|add_class:'form-control'}}

                First name
                {{ form.first_name|add_class:'form-control'}}

                Last name
                {{ form.last_name|add_class:'form-control'}}

                Password
                {{ form.password|add_class:'form-control'}}
                <input type="hidden" name="next" value="{{ next }}" />

              <button class="btn btn-success pull-right" type="submit">{% trans 'Sign up' %}</button>

        </form>

{% endblock %}


text:
/***************************************************************************
--[[#js.plated_plugin.import

A way of importing chunks from another page.

This module only exposes one function, which is used to create
the actual module with bound state data.

	plated_plugin_import = require("./plated_plugin_import.js").create(opts,plated)

This is called automatically when the plated module is created and the
returned plugin functions are added to the plugin call stack. Note that
all of these modules are bound together and operate as a group with
shared data.

]]*/

/***************************************************************************
--[[#html.plated_plugin.import

	#^importedchunk import=dir/dir
	...

The content if this chunk is unimportant as it will be replaced by the
chunk referenced from another file via the import=dir flag.

]]*/

//var fs = require('fs');
var util=require('util');
var JSON5=require('json5');
var JSON_stringify = require('json-stable-stringify');

var ls=function(a) { console.log(util.inspect(a,{depth:null})); }

// wrap so we can contain multiple environments without borking
exports.create=function(opts,plated){

	var timestr=function(){ return new Date().toISOString().replace(/^.+T/, "").replace(/\..+/, ""); }

	var plated_plugin_import={};

	plated_plugin_import.config={};

/***************************************************************************
--[[#js.plated_plugin.import.process_file

	chunks = plated_plugin_import.process_file(chunks)

Tweak a single file of chunks, only chunks found in this file will be
available.

]]*/
	plated_plugin_import.process_file=function(chunks){

// process import flag

		for( n in chunks )
		{
			var flags=chunks._flags && chunks._flags[n]
			if(flags && flags.import) // special import
			{
				var dirname=flags.import
				var dirchunks=plated.dirs[dirname] || plated.files[dirname]
				if( dirname && dirchunks )
				{
					chunks[n]=dirchunks
					console.log(timestr()+" IMPORTING from "+dirname+" into #^"+n)
				}
			}
		}
		return chunks;
	};

	return plated_plugin_import;
};


text:
from bisect import bisect

import numpy as np
from scipy.interpolate import interp2d
import matplotlib.pyplot as plt
import matplotlib.patheffects as pe

from vaspy.iter import XdatCar, AniFile
from traj import get_trajectories

orders = [2, 6, 10, 14, 18, 22, 26, 30, 34]
max_x = 0.7
max_y = 0.7
grid_resolution = 60
interp_resolution = 100

def locate(x, y, position):
    i, j = position
    return bisect(x, i)-1, bisect(y, j)-1

if __name__ == "__main__":
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_aspect("equal")

    # Merge all positions.
    trajs = get_trajectories()
    positions = np.concatenate(trajs)

    # Get limits.
    all_data = np.concatenate((positions[:, 0], positions[:, 1]))
    left, right = np.min(all_data), np.max(all_data)

    z = np.zeros([grid_resolution, grid_resolution])
    x = np.linspace(left, right, grid_resolution)
    y = np.linspace(left, right, grid_resolution)
    for xi, yi, zi in positions:
        m, n = locate(x, y, [xi, yi])
        z[m, n] += 1

    # interpolation.
    interp_func = interp2d(x, y, z, kind="linear")

    newx = np.linspace(left, right, interp_resolution)
    newy = np.linspace(left, right, interp_resolution)
    newz = interp_func(newx, newy)

#    z /= len(positions)
#    x, y = np.meshgrid(x, y)

    CS = plt.contourf(newx, newy, newz, 30, cmap=plt.cm.coolwarm)

    plt.show()


text:
//Using SDL and standard IO
#include <SDL2/SDL.h>
#include <stdio.h>

//Screen dimension constants
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;

//Starts up SDL and creates window
bool init();

//Loads media
bool loadMedia();

//Frees media and shuts down SDL
void close();

//The window we'll be rendering to
SDL_Window* gWindow = NULL;

//The surface contained by the window
SDL_Surface* gScreenSurface = NULL;

//The image we will load and show on the screen
SDL_Surface* gHelloWorld = NULL;

bool init()
{
    //Initialization flag
    bool success = true;

    //Initialize SDL
    if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
    {
        printf( "SDL could not initialize! SDL_Error: %s\n", SDL_GetError() );
        success = false;
    }
    else
    {
        //Create window
        gWindow = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
        if( gWindow == NULL )
        {
            printf( "Window could not be created! SDL_Error: %s\n", SDL_GetError() );
            success = false;
        }
        else
        {
            //Get window surface
            gScreenSurface = SDL_GetWindowSurface( gWindow );
        }
    }

    return success;
}

bool loadMedia()
{
    //Loading success flag
    bool success = true;

    //Load splash image
    gHelloWorld = SDL_LoadBMP( "hello_world.bmp" );
    if( gHelloWorld == NULL )
    {
        printf( "Unable to load image %s! SDL Error: %s\n", "hello_world.bmp", SDL_GetError() );
        success = false;
    }

    return success;
}

void close()
{
    //Deallocate surface
    SDL_FreeSurface( gHelloWorld );
    gHelloWorld = NULL;

    //Destroy window
    SDL_DestroyWindow( gWindow );
    gWindow = NULL;

    //Quit SDL subsystems
    SDL_Quit();
}

int main( int argc, char* args[] )
{
    //Start up SDL and create window
    if( !init() )
    {
        printf( "Failed to initialize!\n" );
    }
    else
    {
        //Load media
        if( !loadMedia() )
        {
            printf( "Failed to load media!\n" );
        }
        else
        {
            //Apply the image
            SDL_BlitSurface( gHelloWorld, NULL, gScreenSurface, NULL );

            //Update the surface
            SDL_UpdateWindowSurface( gWindow );

            //Wait two seconds
            SDL_Delay( 2000 );
        }
    }

    //Free resources and close SDL
    close();

    return 0;
}


text:
import argparse
import os
import pysam
from collections import OrderedDict
from datetime import datetime

from pynnotator import settings

toolname = 'merge'

class Merge(object):
    def __init__(self, vcffile=None):

        self.vcffile = vcffile

        self.filename = os.path.splitext(os.path.basename(str(vcffile)))[0]

        self.header = open('%s/scripts/header.vcf' % (settings.BASE_DIR)).readlines()

        # create folder merge if it doesn't exists
        if not os.path.exists('merge'):
            os.makedirs('merge')
        # enter inside folder
        os.chdir('merge')

        self.annotation_files = OrderedDict()

        pysam.tabix_index('../snpeff/snpeff.output.vcf', preset='vcf')

        self.annotation_files['snpeff'] = {
            'info': 'EFF',
            'file': pysam.Tabixfile('../snpeff/snpeff.output.vcf.gz', 'r', encoding="utf-8")
        }

        pysam.tabix_index('../vep/vep.output.sorted.vcf', preset='vcf')

        self.annotation_files['vep'] = {
            'info': 'CSQ',
            'file': pysam.Tabixfile('../vep/vep.output.sorted.vcf.gz', 'r', encoding="utf-8")
        }

        pysam.tabix_index('../snpsift/snpsift.final.vcf', preset='vcf')

        self.annotation_files['vartype'] = {
            'info': 'VARTYPE,SNP,MNP,INS,DEL,MIXED,HOM,HET',
            'file': pysam.Tabixfile('../snpsift/snpsift.final.vcf.gz', 'r', encoding="utf-8")
        }

        self.dbsnp = pysam.Tabixfile(settings.dbsnp, 'r', encoding="utf-8")

    def run(self):
        tstart = datetime.now()
        print(tstart, 'Starting merge: ', self.vcffile)

        self.merge()

        tend = datetime.now()
        annotation_time = tend - tstart
        print(tend, 'Finished merge, it took: ', annotation_time)

        # merge VCF Files with VariantAnnotator

    def merge(self):

        BASE_DIR = os.getcwd()

        # get headers from files
        headers = []
        for annotation in self.annotation_files:
            # print(annotation, self.annotation_files[annotation])
            info = self.annotation_files[annotation]['info'].split(',')
            # print(info)
            ann_vcf_file = self.annotation_files[annotation]['file']

        output = open('annotation.final.vcf', 'w')
        input_vcf = open(self.vcffile)
        for line in input_vcf:
            if line.startswith('#'):
                if line.startswith('#CHROM'):
                    # write extra header
                    # for tag in headers:
                    #     # print(tag)
                    #     output.writelines(tag + '\n')
                    output.writelines(self.header)
                    output.writelines(line)
                else:
                    output.writelines(line)
            else:
                # here annotation comes!
                variant = line.split('\t')
                variant[0] = variant[0].replace('chr', '')
                index = '%s-%s' % (variant[0], variant[1])
                # print(variant)
                annotations = []
                for annotation in self.annotation_files:
                    info = self.annotation_files[annotation]['info'].split(',')
                    # print(info)
                    ann_vcf_file = self.annotation_files[annotation]['file']
                    try:
                        records = ann_vcf_file.fetch(variant[0], int(variant[1]) - 1, int(variant[1]))
                    except:
                        records = []
                    for record in records:

                        ann = record.split('\t')
                        # print(ann)
                        new_info = ann[7].split(';')

                        if annotation == 'pynnotator':
                            for tag in new_info:
                                string = tag.split('=')[0].split('.')[0]
                                if string in self.pynnotator_tags:
                                    annotations.append(tag)
                        else:
                            # print(info)
                            for tag in new_info:
                                string = tag.split('=')[0]
                                if string in info:
                                    annotations.append(tag)
                                    # print(annotations)

                new_info = variant[7] + ';' + ";".join(annotations)
                # print(new_info)
                variant[7] = new_info

                # now dbsnp

                try:
                    records = self.dbsnp.fetch(variant[0], int(variant[1]) - 1, int(variant[1]))
                except:
                    records = []
                rsids = []
                for record in records:
                    # print(record, variant)
                    row = record.split('\t')
                    rsid = row[2]

                    check_flag = False
                    if variant[3] == row[3]:
                        alts = variant[4].split(',')
                        alts_row = row[4].split(',')
                        # compare ALT
                        for alt in alts:
                            if alt in alts_row:
                                check_flag = True
                    if check_flag:
                        rsids.append(rsid)

                if len(rsids) > 0:
                    variant[2] = ",".join(rsids)

                new_line = "\t".join(variant)
                output.writelines(new_line)
                # index()
        output.close()

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='MERGE all VCF Files from previous methods.')
    parser.add_argument('-i', dest='vcffile', required=True, metavar='example.vcf', help='a VCF file to be annotated')

    args = parser.parse_args()

    merge = Merge(args.vcffile)
    merge.run()


text:
package payment

import (
	"database/sql"
	"database/sql/driver"
	"encoding/json"
	"fmt"
	"time"

	"code.google.com/p/godec/dec"
	"github.com/fritzpay/paymentd/pkg/decimal"
)

type PaymentTransactionStatus string

// Scan implements the Scanner interface for sql
func (s *PaymentTransactionStatus) Scan(v interface{}) error {
	switch src := v.(type) {
	case []byte:
		*s = PaymentTransactionStatus(string(src))
		return nil
	case nil:
		*s = PaymentStatusNone
		return nil
	}
	str, ok := v.(string)
	if !ok {
		return fmt.Errorf("cannot scan %T into %T", v, s)
	}
	*s = PaymentTransactionStatus(str)
	return nil
}

// Value implements the Valuer interface for sql
func (s PaymentTransactionStatus) Value() (driver.Value, error) {
	return driver.Value(s.String()), nil
}

func (s PaymentTransactionStatus) Valid() bool {
	return string(s) != ""
}

func (s PaymentTransactionStatus) String() string {
	return string(s)
}

const (
	PaymentStatusNone           PaymentTransactionStatus = "uninitialized"
	PaymentStatusOpen                                    = "open"
	PaymentStatusPending                                 = "pending"
	PaymentStatusPaid                                    = "paid"
	PaymentStatusSettled                                 = "settled"
	PaymentStatusAuthorized                              = "authorized"
	PaymentStatusError                                   = "error"
	PaymentStatusCancelled                               = "cancelled"
	PaymentStatusFailed                                  = "failed"
	PaymentStatusChargeback                              = "chargeback"
	PaymentStatusRefunded                                = "refunded"
	PaymentStatusRefundReversed                          = "refund-reversed"
)

// PaymentTransaction represents a transaction on a payment
//
// A transaction is any event/status change on a payment
//
// The transactions represents the ledger on a payment
type PaymentTransaction struct {
	Payment *Payment

	Timestamp time.Time
	Amount    int64
	Subunits  int8
	Currency  string
	Status    PaymentTransactionStatus
	Comment   sql.NullString
}

func (p *PaymentTransaction) Decimal() *decimal.Decimal {
	d := dec.NewDecInt64(p.Amount)
	sc := dec.Scale(int32(p.Subunits))
	d.SetScale(sc)
	return &decimal.Decimal{Dec: *d}
}

// Balance represents a balance which totals the ledger by currency
type Balance map[string]*decimal.Decimal

func (b Balance) FlatMap() map[string]string {
	flat := make(map[string]string)
	for curr, dec := range b {
		flat[curr] = dec.String()
	}
	return flat
}

func (b Balance) MarshalJSON() ([]byte, error) {
	return json.Marshal(b.FlatMap())
}

func (b *Balance) UnmarshalJSON(p []byte) error {
	m := make(map[string]string)
	err := json.Unmarshal(p, &m)
	if err != nil {
		return err
	}
	bal := make(map[string]*decimal.Decimal)
	for k, v := range m {
		dec := dec.NewDecInt64(0)
		_, ok := dec.SetString(v)
		if !ok {
			return fmt.Errorf("error decoding decimal %s", v)
		}
		bal[k] = &decimal.Decimal{Dec: *dec}
	}
	*b = Balance(bal)
	return nil
}

type PaymentTransactionList []*PaymentTransaction

func (p PaymentTransactionList) Balance() Balance {
	b := make(map[string]*decimal.Decimal)
	for _, tx := range p {
		am := tx.Decimal()
		if _, ok := b[tx.Currency]; ok {
			b[tx.Currency].Add(&b[tx.Currency].Dec, &am.Dec)
		} else {
			b[tx.Currency] = am
		}
	}
	return b
}


text:
/* Copied wholesale from hadoop-common 0.23.1
package org.apache.hadoop.fs;
*/
package org.apache.bookkeeper.util;

import static com.google.common.base.Charsets.UTF_8;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

/**
 * Class for creating hardlinks.
 * Supports Unix/Linux, WinXP/2003/Vista via Cygwin, and Mac OS X.
 *
 *
The HardLink class was formerly a static inner class of FSUtil,
 * and the methods provided were blatantly non-thread-safe.
 * To enable volume-parallel Update snapshots, we now provide static
 * threadsafe methods that allocate new buffer string arrays
 * upon each call.  We also provide an API to hardlink all files in a
 * directory with a single command, which is up to 128 times more
 * efficient - and minimizes the impact of the extra buffer creations.
 */
public class HardLink {

  /**
   * OS Types.
   */
  public enum OSType {
    OS_TYPE_UNIX,
    OS_TYPE_WINXP,
    OS_TYPE_SOLARIS,
    OS_TYPE_MAC
  }

  public static final OSType OS_TYPE;
  private static HardLinkCommandGetter getHardLinkCommand;

  public final LinkStats linkStats; //not static

  //initialize the command "getters" statically, so can use their
  //methods without instantiating the HardLink object
  static {
    OS_TYPE = getOSType();
    if (OS_TYPE == OSType.OS_TYPE_WINXP) {
      // Windows
      getHardLinkCommand = new HardLinkCGWin();
    } else {
      // Unix
      getHardLinkCommand = new HardLinkCGUnix();
      //override getLinkCountCommand for the particular Unix variant
      //Linux is already set as the default - {"stat","-c%h", null}
      if (OS_TYPE == OSType.OS_TYPE_MAC) {
        String[] linkCountCmdTemplate = {"stat", "-f%l", null};
        HardLinkCGUnix.setLinkCountCmdTemplate(linkCountCmdTemplate);
      } else if (OS_TYPE == OSType.OS_TYPE_SOLARIS) {
        String[] linkCountCmdTemplate = {"ls", "-l", null};
        HardLinkCGUnix.setLinkCountCmdTemplate(linkCountCmdTemplate);
      }
    }
  }

  public HardLink() {
    linkStats = new LinkStats();
  }

  private static OSType getOSType() {
    String osName = System.getProperty("os.name");
    if (osName.contains("Windows") && (osName.contains("XP")
            || osName.contains("2003")
            || osName.contains("Vista")
            || osName.contains("Windows_7")
            || osName.contains("Windows 7")
            || osName.contains("Windows7"))) {
      return OSType.OS_TYPE_WINXP;
    } else if (osName.contains("SunOS")
            || osName.contains("Solaris")) {
       return OSType.OS_TYPE_SOLARIS;
    } else if (osName.contains("Mac")) {
       return OSType.OS_TYPE_MAC;
    } else {
      return OSType.OS_TYPE_UNIX;
    }
  }

  /**
   * This abstract class bridges the OS-dependent implementations of the
   * needed functionality for creating hardlinks and querying link counts.
   * The particular implementation class is chosen during
   * static initialization phase of the HardLink class.
   * The "getter" methods construct shell command strings for various purposes.
   */
  private abstract static class HardLinkCommandGetter {

    /**
     * Get the command string needed to hardlink a bunch of files from
     * a single source directory into a target directory.  The source directory
     * is not specified here, but the command will be executed using the source
     * directory as the "current working directory" of the shell invocation.
     *
     * @param fileBaseNames - array of path-less file names, relative
     *            to the source directory
     * @param linkDir - target directory where the hardlinks will be put
     * @return - an array of Strings suitable for use as a single shell command
     *            with {@code Runtime.exec()}
     * @throws IOException - if any of the file or path names misbehave
     */
    abstract String[] linkMult(String[] fileBaseNames, File linkDir)
                          throws IOException;

    /**
     * Get the command string needed to hardlink a single file.
     */
    abstract String[] linkOne(File file, File linkName) throws IOException;

    /**
     * Get the command string to query the hardlink count of a file.
     */
    abstract String[] linkCount(File file) throws IOException;

    /**
     * Calculate the total string length of the shell command
     * resulting from execution of linkMult, plus the length of the
     * source directory name (which will also be provided to the shell).
     *
     * @param fileDir - source directory, parent of fileBaseNames
     * @param fileBaseNames - array of path-less file names, relative
     *            to the source directory
     * @param linkDir - target directory where the hardlinks will be put
     * @return - total data length (must not exceed maxAllowedCmdArgLength)
     * @throws IOException
     */
    abstract int getLinkMultArgLength(
                     File fileDir, String[] fileBaseNames, File linkDir)
                     throws IOException;

    /**
     * Get the maximum allowed string length of a shell command on this OS,
     * which is just the documented minimum guaranteed supported command
     * length - aprx. 32KB for Unix, and 8KB for Windows.
     */
    abstract int getMaxAllowedCmdArgLength();
  }

  /**
   * Implementation of HardLinkCommandGetter class for Unix.
   */
  static class HardLinkCGUnix extends HardLinkCommandGetter {
    private static String[] hardLinkCommand = {"ln", null, null};
    private static String[] hardLinkMultPrefix = {"ln"};
    private static String[] hardLinkMultSuffix = {null};
    private static String[] getLinkCountCommand = {"stat", "-c%h", null};
    //Unix guarantees at least 32K bytes cmd length.
    //Subtract another 64b to allow for Java 'exec' overhead
    private static final int maxAllowedCmdArgLength = 32 * 1024 - 65;

    private static synchronized
    void setLinkCountCmdTemplate(String[] template) {
      //May update this for specific unix variants,
      //after static initialization phase
      getLinkCountCommand = template;
    }

    /*
     * @see org.apache.hadoop.fs.HardLink.HardLinkCommandGetter#linkOne(java.io.File, java.io.File)
     */
    @Override
    String[] linkOne(File file, File linkName)
    throws IOException {
      String[] buf = new String[hardLinkCommand.length];
      System.arraycopy(hardLinkCommand, 0, buf, 0, hardLinkCommand.length);
      //unix wants argument order: "ln <existing> <new>"
      buf[1] = makeShellPath(file);
      buf[2] = makeShellPath(linkName);
      return buf;
    }

    /*
     * @see org.apache.hadoop.fs.HardLink.HardLinkCommandGetter#linkMult(java.lang.String[], java.io.File)
     */
    @Override
    String[] linkMult(String[] fileBaseNames, File linkDir)
    throws IOException {
      String[] buf = new String[fileBaseNames.length
                                + hardLinkMultPrefix.length
                                + hardLinkMultSuffix.length];
      int mark = 0;
      System.arraycopy(hardLinkMultPrefix, 0, buf, mark,
                       hardLinkMultPrefix.length);
      mark += hardLinkMultPrefix.length;
      System.arraycopy(fileBaseNames, 0, buf, mark, fileBaseNames.length);
      mark += fileBaseNames.length;
      buf[mark] = makeShellPath(linkDir);
      return buf;
    }

    /*
     * @see org.apache.hadoop.fs.HardLink.HardLinkCommandGetter#linkCount(java.io.File)
     */
    @Override
    String[] linkCount(File file)
    throws IOException {
      String[] buf = new String[getLinkCountCommand.length];
      System.arraycopy(getLinkCountCommand, 0, buf, 0,
                       getLinkCountCommand.length);
      buf[getLinkCountCommand.length - 1] = makeShellPath(file);
      return buf;
    }

    /*
     * @see org.apache.hadoop.fs.HardLink.HardLinkCommandGetter#getLinkMultArgLength(File, String[], File)
     */
    @Override
    int getLinkMultArgLength(File fileDir, String[] fileBaseNames, File linkDir)
    throws IOException{
      int sum = 0;
      for (String x : fileBaseNames) {
        // add 1 to account for terminal null or delimiter space
        sum += 1 + ((x == null) ? 0 : x.length());
      }
      sum += 2 + makeShellPath(fileDir).length()
             + makeShellPath(linkDir).length();
      //add the fixed overhead of the hardLinkMult prefix and suffix
      sum += 3; //length("ln") + 1
      return sum;
    }

    /*
     * @see org.apache.hadoop.fs.HardLink.HardLinkCommandGetter#getMaxAllowedCmdArgLength()
     */
    @Override
    int getMaxAllowedCmdArgLength() {
      return maxAllowedCmdArgLength;
    }
  }

  /**
   * Implementation of HardLinkCommandGetter class for Windows.
   *
   *
Note that the linkCount shell command for Windows is actually
   * a Cygwin shell command, and depends on ${cygwin}/bin
   * being in the Windows PATH environment variable, so
   * stat.exe can be found.
   */
  static class HardLinkCGWin extends HardLinkCommandGetter {
    //The Windows command getter impl class and its member fields are
    //package-private ("default") access instead of "private" to assist
    //unit testing (sort of) on non-Win servers

    static String[] hardLinkCommand = {
                        "fsutil", "hardlink", "create", null, null};
    static String[] hardLinkMultPrefix = {
                        "cmd", "/q", "/c", "for", "%f", "in", "("};
    static String   hardLinkMultDir = "\\%f";
    static String[] hardLinkMultSuffix = {
                        ")", "do", "fsutil", "hardlink", "create", null,
                        "%f", "1>NUL"};
    static String[] getLinkCountCommand = {"stat", "-c%h", null};
    //Windows guarantees only 8K - 1 bytes cmd length.
    //Subtract another 64b to allow for Java 'exec' overhead
    private static final int maxAllowedCmdArgLength = 8 * 1024 - 65;

    /*
     * @see org.apache.hadoop.fs.HardLink.HardLinkCommandGetter#linkOne(java.io.File, java.io.File)
     */
    @Override
    String[] linkOne(File file, File linkName)
    throws IOException {
      String[] buf = new String[hardLinkCommand.length];
      System.arraycopy(hardLinkCommand, 0, buf, 0, hardLinkCommand.length);
      //windows wants argument order: "create <new> <existing>"
      buf[4] = file.getCanonicalPath();
      buf[3] = linkName.getCanonicalPath();
      return buf;
    }

    /*
     * @see org.apache.hadoop.fs.HardLink.HardLinkCommandGetter#linkMult(java.lang.String[], java.io.File)
     */
    @Override
    String[] linkMult(String[] fileBaseNames, File linkDir)
    throws IOException {
      String[] buf = new String[fileBaseNames.length
                                + hardLinkMultPrefix.length
                                + hardLinkMultSuffix.length];
      String td = linkDir.getCanonicalPath() + hardLinkMultDir;
      int mark = 0;
      System.arraycopy(hardLinkMultPrefix, 0, buf, mark,
                       hardLinkMultPrefix.length);
      mark += hardLinkMultPrefix.length;
      System.arraycopy(fileBaseNames, 0, buf, mark, fileBaseNames.length);
      mark += fileBaseNames.length;
      System.arraycopy(hardLinkMultSuffix, 0, buf, mark,
                       hardLinkMultSuffix.length);
      mark += hardLinkMultSuffix.length;
      buf[mark - 3] = td;
      return buf;
    }

    /*
     * @see org.apache.hadoop.fs.HardLink.HardLinkCommandGetter#linkCount(java.io.File)
     */
    @Override
    String[] linkCount(File file)
    throws IOException {
      String[] buf = new String[getLinkCountCommand.length];
      System.arraycopy(getLinkCountCommand, 0, buf, 0,
                       getLinkCountCommand.length);
      //The linkCount command is actually a Cygwin shell command,
      //not a Windows shell command, so we should use "makeShellPath()"
      //instead of "getCanonicalPath()".  However, that causes another
      //shell exec to "cygpath.exe", and "stat.exe" actually can handle
      //DOS-style paths (it just prints a couple hundred bytes of warning
      //to stderr), so we use the more efficient "getCanonicalPath()".
      buf[getLinkCountCommand.length - 1] = file.getCanonicalPath();
      return buf;
    }

    /*
     * @see org.apache.hadoop.fs.HardLink.HardLinkCommandGetter#getLinkMultArgLength(File, String[], File)
     */
    @Override
    int getLinkMultArgLength(File fileDir, String[] fileBaseNames, File linkDir)
    throws IOException {
      int sum = 0;
      for (String x : fileBaseNames) {
        // add 1 to account for terminal null or delimiter space
        sum += 1 + ((x == null) ? 0 : x.length());
      }
      sum += 2 + fileDir.getCanonicalPath().length() + linkDir.getCanonicalPath().length();
      //add the fixed overhead of the hardLinkMult command
      //(prefix, suffix, and Dir suffix)
      sum += ("cmd.exe /q /c for %f in ( ) do "
              + "fsutil hardlink create \\%f %f 1>NUL ").length();
      return sum;
    }

    /*
     * @see org.apache.hadoop.fs.HardLink.HardLinkCommandGetter#getMaxAllowedCmdArgLength()
     */
    @Override
    int getMaxAllowedCmdArgLength() {
      return maxAllowedCmdArgLength;
    }
  }

  /**
   * Calculate the nominal length of all contributors to the total
   * commandstring length, including fixed overhead of the OS-dependent
   * command.  It's protected rather than private, to assist unit testing,
   * but real clients are not expected to need it -- see the way
   * createHardLinkMult() uses it internally so the user doesn't need to worry
   * about it.
   *
   * @param fileDir - source directory, parent of fileBaseNames
   * @param fileBaseNames - array of path-less file names, relative
   *            to the source directory
   * @param linkDir - target directory where the hardlinks will be put
   * @return - total data length (must not exceed maxAllowedCmdArgLength)
   * @throws IOException
   */
  protected static int getLinkMultArgLength(
          File fileDir, String[] fileBaseNames, File linkDir)
  throws IOException {
    return getHardLinkCommand.getLinkMultArgLength(fileDir,
          fileBaseNames, linkDir);
  }

  /**
   * Return this private value for use by unit tests.
   * Shell commands are not allowed to have a total string length
   * exceeding this size.
   */
  protected static int getMaxAllowedCmdArgLength() {
    return getHardLinkCommand.getMaxAllowedCmdArgLength();
  }

  /*
   * ****************************************************
   * Complexity is above.  User-visible functionality is below
   * ****************************************************
   */

  /**
   * Creates a hardlink.
   * @param file - existing source file
   * @param linkName - desired target link file
   */
  public static void createHardLink(File file, File linkName)
  throws IOException {
    if (file == null) {
      throw new IOException(
          "invalid arguments to createHardLink: source file is null");
    }
    if (linkName == null) {
      throw new IOException(
          "invalid arguments to createHardLink: link name is null");
    }
    // construct and execute shell command
    String[] hardLinkCommand = getHardLinkCommand.linkOne(file, linkName);
    Process process = Runtime.getRuntime().exec(hardLinkCommand);
    try {
      if (process.waitFor() != 0) {
        String errMsg = new BufferedReader(new InputStreamReader(
                                                   process.getInputStream(), UTF_8)).readLine();
        if (errMsg == null) {
            errMsg = "";
        }
        String inpMsg = new BufferedReader(new InputStreamReader(
                                                   process.getErrorStream(), UTF_8)).readLine();
        if (inpMsg == null) {
            inpMsg = "";
        }
        throw new IOException(errMsg + inpMsg);
      }
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
      throw new IOException(e);
    } finally {
      process.destroy();
    }
  }

  /**
   * Creates hardlinks from multiple existing files within one parent
   * directory, into one target directory.
   * @param parentDir - directory containing source files
   * @param fileBaseNames - list of path-less file names, as returned by
   *                        parentDir.list()
   * @param linkDir - where the hardlinks should be put.  It must already exist.
   *
   * If the list of files is too long (overflows maxAllowedCmdArgLength),
   * we will automatically split it into multiple invocations of the
   * underlying method.
   */
  public static void createHardLinkMult(File parentDir, String[] fileBaseNames,
      File linkDir) throws IOException {
    //This is the public method all non-test clients are expected to use.
    //Normal case - allow up to maxAllowedCmdArgLength characters in the cmd
    createHardLinkMult(parentDir, fileBaseNames, linkDir,
                       getHardLinkCommand.getMaxAllowedCmdArgLength());
  }

  /*
   * Implements {@link createHardLinkMult} with added variable  "maxLength",
   * to ease unit testing of the auto-splitting feature for long lists.
   * Likewise why it returns "callCount", the number of sub-arrays that
   * the file list had to be split into.
   * Non-test clients are expected to call the public method instead.
   */
  protected static int createHardLinkMult(File parentDir,
      String[] fileBaseNames, File linkDir, int maxLength)
  throws IOException {
    if (parentDir == null) {
      throw new IOException(
          "invalid arguments to createHardLinkMult: parent directory is null");
    }
    if (linkDir == null) {
      throw new IOException(
          "invalid arguments to createHardLinkMult: link directory is null");
    }
    if (fileBaseNames == null) {
      throw new IOException(
          "invalid arguments to createHardLinkMult: "
          + "filename list can be empty but not null");
    }
    if (fileBaseNames.length == 0) {
      //the OS cmds can't handle empty list of filenames,
      //but it's legal, so just return.
      return 0;
    }
    if (!linkDir.exists()) {
      throw new FileNotFoundException(linkDir + " not found.");
    }

    //if the list is too long, split into multiple invocations
    int callCount = 0;
    if (getLinkMultArgLength(parentDir, fileBaseNames, linkDir) > maxLength
          && fileBaseNames.length > 1) {
      String[] list1 = Arrays.copyOf(fileBaseNames, fileBaseNames.length / 2);
      callCount += createHardLinkMult(parentDir, list1, linkDir, maxLength);
      String[] list2 = Arrays.copyOfRange(fileBaseNames, fileBaseNames.length / 2,
          fileBaseNames.length);
      callCount += createHardLinkMult(parentDir, list2, linkDir, maxLength);
      return callCount;
    } else {
      callCount = 1;
    }

    // construct and execute shell command
    String[] hardLinkCommand = getHardLinkCommand.linkMult(fileBaseNames,
        linkDir);
    Process process = Runtime.getRuntime().exec(hardLinkCommand, null,
        parentDir);
    try {
      if (process.waitFor() != 0) {
        String errMsg = new BufferedReader(new InputStreamReader(
                                                   process.getInputStream(), UTF_8)).readLine();
        if (errMsg == null) {
            errMsg = "";
        }
        String inpMsg = new BufferedReader(new InputStreamReader(
                                                   process.getErrorStream(), UTF_8)).readLine();
        if (inpMsg == null) {
            inpMsg = "";
        }
        throw new IOException(errMsg + inpMsg);
      }
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
      throw new IOException(e);
    } finally {
      process.destroy();
    }
    return callCount;
  }

   /**
   * Retrieves the number of links to the specified file.
   */
  public static int getLinkCount(File fileName) throws IOException {
    if (fileName == null) {
      throw new IOException(
          "invalid argument to getLinkCount: file name is null");
    }
    if (!fileName.exists()) {
      throw new FileNotFoundException(fileName + " not found.");
    }

    // construct and execute shell command
    String[] cmd = getHardLinkCommand.linkCount(fileName);
    String inpMsg = null;
    String errMsg = null;
    int exitValue = -1;
    BufferedReader in = null;
    BufferedReader err = null;

    Process process = Runtime.getRuntime().exec(cmd);
    try {
      exitValue = process.waitFor();
      in = new BufferedReader(new InputStreamReader(
                                      process.getInputStream(), UTF_8));
      inpMsg = in.readLine();
      err = new BufferedReader(new InputStreamReader(
                                       process.getErrorStream(), UTF_8));
      errMsg = err.readLine();
      if (inpMsg == null || exitValue != 0) {
        throw createIOException(fileName, inpMsg, errMsg, exitValue, null);
      }
      if (OS_TYPE == OSType.OS_TYPE_SOLARIS) {
        String[] result = inpMsg.split("\\s+");
        return Integer.parseInt(result[1]);
      } else {
        return Integer.parseInt(inpMsg);
      }
    } catch (NumberFormatException e) {
      throw createIOException(fileName, inpMsg, errMsg, exitValue, e);
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
      throw createIOException(fileName, inpMsg, errMsg, exitValue, e);
    } finally {
      process.destroy();
      if (in != null) {
          in.close();
      }
      if (err != null) {
          err.close();
      }
    }
  }

  /* Create an IOException for failing to get link count. */
  private static IOException createIOException(File f, String message,
      String error, int exitvalue, Exception cause) {

    final String winErrMsg = "; Windows errors in getLinkCount are often due "
         + "to Cygwin misconfiguration";

    final String s = "Failed to get link count on file " + f
        + ": message=" + message
        + "; error=" + error
        + ((OS_TYPE == OSType.OS_TYPE_WINXP) ? winErrMsg : "")
        + "; exit value=" + exitvalue;
    return (cause == null) ? new IOException(s) : new IOException(s, cause);
  }

  /**
   * HardLink statistics counters and methods.
   * Not multi-thread safe, obviously.
   * Init is called during HardLink instantiation, above.
   *
   *
These are intended for use by knowledgeable clients, not internally,
   * because many of the internal methods are static and can't update these
   * per-instance counters.
   */
  public static class LinkStats {
    public int countDirs = 0;
    public int countSingleLinks = 0;
    public int countMultLinks = 0;
    public int countFilesMultLinks = 0;
    public int countEmptyDirs = 0;
    public int countPhysicalFileCopies = 0;

    public void clear() {
      countDirs = 0;
      countSingleLinks = 0;
      countMultLinks = 0;
      countFilesMultLinks = 0;
      countEmptyDirs = 0;
      countPhysicalFileCopies = 0;
    }

    public String report() {
      return "HardLinkStats: " + countDirs + " Directories, including "
      + countEmptyDirs + " Empty Directories, "
      + countSingleLinks
      + " single Link operations, " + countMultLinks
      + " multi-Link operations, linking " + countFilesMultLinks
      + " files, total " + (countSingleLinks + countFilesMultLinks)
      + " linkable files.  Also physically copied "
      + countPhysicalFileCopies + " other files.";
    }
  }

  /**
   * Convert a os-native filename to a path that works for the shell.
   * @param file The file to convert
   * @return The unix pathname
   * @throws IOException on windows, there can be problems with the subprocess
   */
  public static String makeShellPath(File file) throws IOException {
    String filename = file.getCanonicalPath();
    if (System.getProperty("os.name").startsWith("Windows")) {
      BufferedReader r = null;
      try {
        ProcessBuilder pb = new ProcessBuilder("cygpath", "-u", filename);
        Process p = pb.start();
        int err = p.waitFor();
        if (err != 0) {
            throw new IOException("Couldn't resolve path "
                                  + filename + "(" + err + ")");
        }
        r = new BufferedReader(new InputStreamReader(p.getInputStream(), UTF_8));
        return r.readLine();
      } catch (InterruptedException ie) {
        Thread.currentThread().interrupt();
        throw new IOException("Couldn't resolve path " + filename, ie);
      } finally {
        if (r != null) {
          r.close();
        }
      }
    } else {
      return filename;
    }
  }
}


text:
#include <vector>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cstdio>
#include <ctime>
#include <cmath>

//#define SEQAN_DEBUG
//#define SEQAN_TEST
//#define SEQAN_NOSRAN //suppress srand

#include <seqan/sequence.h>
#include <seqan/chaining.h>

using namespace seqan;
using namespace std;

//////////////////////////////////////////////////////////////////////////////

template< typename TContainer >
void
_generateRandomFrags(TContainer & dest,
					 int num,
					 int min,
					 int max,
					 int minwidth,
					 int maxwidth,
					 int dim )
{
	typedef typename Value< TContainer >::Type FragType;
	typename Key< FragType >::Type * left_pos;
	typename Key< FragType >::Type * right_pos;
	reserve( dest, num );
	double d_dim = static_cast< double >( dim );
	for( int i = 0; i < num; ++i )
	{

		double width_sum = 0;
		left_pos = new typename Key< FragType >::Type[ dim ];
		right_pos = new typename Key< FragType >::Type[ dim ];
		for( int d = 0; d < dim; ++d )
		{
			left_pos[ d ] = ( rand() % ( max - min ) ) + min;
			int width = ( rand() % ( maxwidth - minwidth ) )+ minwidth;
			width_sum += width;
			right_pos[ d ] = left_pos[ d ] + width;

		}
		FragType frag( left_pos, right_pos, dim, static_cast< typename Weight< FragType >::Type >(exp(log(width_sum)/d_dim)) * 100 );

		delete[] left_pos;
		delete[] right_pos;

		appendValue( dest, frag );
	}
}

//////////////////////////////////////////////////////////////////////////////
//helper function

template <typename TChain, typename TScoring>
void _showChain(TChain & ch,
				TScoring scoring)
{
	typedef typename Iterator<TChain>::Type TIterator;
	typedef typename Value<TChain>::Type TFragment;

	TIterator it = begin(ch);
	TIterator it_end = end(ch);
	unsigned int dim = dimension(*it); //chain must not be empty!
	while (it < it_end)
	{
		TFragment & frag = *it;
		printf("%4i: ", weight(frag));
		cout << "(";
		for (unsigned int i = 0; i < dim; ++i)
		{
			printf("%2i", leftPosition(frag, i));
			if (i < (dim-1)) cout << ", ";
		}
		cout << ")(";
		for (unsigned int i = 0; i < dim; ++i)
		{
			printf("%2i", rightPosition(frag, i));
			if (i < (dim-1)) cout << ", ";
		}
		cout << ")\n";

		++it;
		if (it == it_end) break;

		printf("%4i\n", scoreChainGap(scoring, frag, *it));
	}
}

//////////////////////////////////////////////////////////////////////////////

template <typename TScoring>
void testChainer(int count,
				 int dim,
				 TScoring scoring)
{
	String< Seed<int, MultiSeed> > fragments;
	reserve(fragments, count);

	_generateRandomFrags(fragments, count, 1, 3 * count, 10, 20, dim);
//_showChain(fragments, scoring);

	String< Seed<int, MultiSeed> > ch;
	reserve(ch, count+2);

	//build chain
	int chain_score = globalChaining(fragments, ch, scoring);

    //std::cout << chain_score << "\n";
//_showChain(ch, scoring);

	//verify validity of chain
    SEQAN_ASSERT_GT(length(ch), 0u);
	int sum = weight(ch[0]);
	for (unsigned int i = 1; i < length(ch); ++i)
	{
		SEQAN_ASSERT(_chainGenericChainable(ch[i-1], ch[i]));
		sum += scoreChainGap(scoring, ch[i-1], ch[i]) + weight(ch[i]);
	}
	//verify score of chain
	SEQAN_ASSERT_EQ(sum, chain_score);

	//build generic chain
	int chain_score2 = globalChaining(fragments, ch, scoring, GenericChaining());
    //std::cout << chain_score2 << "\n";
//_showChain(ch, scoring);

	//verify validity of generic chain
    SEQAN_ASSERT_GT(length(ch), 0u);
	sum = weight(ch[0]);
	for (unsigned int i = 1; i < length(ch); ++i) {
            SEQAN_ASSERT(_chainGenericChainable(ch[i-1], ch[i]));
            sum += scoreChainGap(scoring, ch[i-1], ch[i]) + weight(ch[i]);
	}
	//verify score of generic chain
	SEQAN_ASSERT_EQ(sum, chain_score2);

	//compare results of two chaining algorithms
	SEQAN_ASSERT_EQ(chain_score2, chain_score);
}

//////////////////////////////////////////////////////////////////////////////

SEQAN_DEFINE_TEST(test_chaining_test_chainer_zero_score) {
    testChainer(1000, 2, Score<int, Zero>());
}

SEQAN_DEFINE_TEST(test_chaining_test_chainer_manhattan_score) {
    testChainer(1000, 2, Score<int, Manhattan>());
}

SEQAN_DEFINE_TEST(test_chaining_test_chainer_chain_sop_score) {
    testChainer(1000, 2, Score<int, ChainSoP>());
}

SEQAN_BEGIN_TESTSUITE(test_chaining) {
    SEQAN_CALL_TEST(test_chaining_test_chainer_zero_score);
    SEQAN_CALL_TEST(test_chaining_test_chainer_manhattan_score);
//    SEQAN_CALL_TEST(test_chaining_test_chainer_chain_sop_score);

    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/chain_base.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/chain_generic.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/chain_meta_fragment.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/chain_point.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/chain_wrapper_point.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/fragment.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/geom_distribution.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/range_max_tree.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/range_tree.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/rmt_base.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/rmt_common_algos.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/rmt_compl_algos.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/rmt_def_algos.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/rmt_skip_base_element.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/rmt_skip_element.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/rt_base.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/rt_common_algos.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/rt_impl.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/rt_skip_base_element.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/rt_skip_element.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/rt_sl_base.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/rt_sl_compl_algos.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/rt_sl_def_algos.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/rt_sl_impl.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/score_chain.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/score_chain_sop.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/score_manhattan.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/score_zero.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/skip_base_element.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/skip_element.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/skip_list.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/skip_list_base.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/skip_list_dynamic.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/skip_list_impl.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/skip_list_iterator.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/skip_list_type.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/skip_pool_alloc.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/tree_chain.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/tree_chain_sop.h");
    SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/chaining/tree_chain_utils.h");
}
SEQAN_END_TESTSUITE


text:
<?php

namespace Cookbook\CoreBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class FriendType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name');
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Cookbook\CoreBundle\Entity\Friend',
        ));
    }

    public function getName()
    {
        return 'friend';
    }
}


text:
<?php

use yii\db\Schema;
use yii\db\Migration;

class m151110_105002_create_orders_history_table extends Migration
{
    public function up()
    {
        // TODO: create table
    }

    public function down()
    {
        $this->dropTable('{{%orders_history}}');
    }

    /*
    // Use safeUp/safeDown to run migration code within a transaction
    public function safeUp()
    {
    }

    public function safeDown()
    {
    }
    */
}


text:
from mcfw.rpc import arguments, returns

from authentication import get_browser_language
from framework.errors.plugins import PluginNotFoundException
from framework.i18n_utils import get_available_languages, DEFAULT_LANGUAGE
from framework.plugin_loader import get_auth_plugin
from framework.to.authentication import SetLanguageTO

@returns(SetLanguageTO)
@arguments(data=SetLanguageTO)
def set_user_language(data):
    language = data.language
    available_languages = get_available_languages()
    if language not in available_languages:
        language = get_browser_language()
        if language not in available_languages:
            language = DEFAULT_LANGUAGE
    get_auth_plugin().set_user_language(language)
    return SetLanguageTO(language)

def get_user_language():
    try:
        auth_plugin = get_auth_plugin()
        language = auth_plugin.get_user_language()
    except PluginNotFoundException:
        language = None
    return language or get_browser_language() or DEFAULT_LANGUAGE


text:
Puppet::Type.newtype(:keystone_tenant) do

  desc <<-EOT
    This type can be used to manage
    keystone tenants.

    This is assumed to be running on the same node
    as your keystone API server.
  EOT

  ensurable

  newparam(:name, :namevar => true) do
    newvalues(/\w+/)
  end

  newproperty(:enabled) do
    newvalues(/(t|T)rue/, /(f|F)alse/)
    defaultto('True')
    munge do |value|
      value.to_s.capitalize
    end
  end

  newproperty(:description)

  newproperty(:id) do
    validate do |v|
      raise(Puppet::Error, 'This is a read only property')
    end
  end

  # we should not do anything until the keystone service is started
  autorequire(:service) do
    ['keystone']
  end

end


text:
"""Generate a README.md file for Modis"""

from modis.tools import help, config

def add_md(text, s, level=0):
    """Appends text to a markdown.

    Args:
        text (str): The old text.
        s (str): The text to append.
        level (int): The markdown level of the appended text.

    Returns:
        text (str): The updated text
    """

    if level > 0:
        if text != "":
            text += "\n"
        text += "#" * level
        text += " "

    text += s + "\n"

    if level > 0:
        text += "\n"

    return text

moduledoc = ""

# Get module
module_name = input("Module name: ")

# Get help data
datapacks = help.get_formatted(module_name, "!")
if datapacks:
    moduledoc = add_md(moduledoc, module_name, 1)
    for d in datapacks:
        moduledoc = add_md(moduledoc, d[0], 2)
        moduledoc = add_md(moduledoc, d[1])

    print(moduledoc)
    newreadme_path = "{}/../{}.md".format(config.ROOT_DIR, module_name)
    with open(newreadme_path, 'w') as file:
        file.write(moduledoc)


text:
AddToCalendar — free customizable JavaScript widget "Add to Calendar" for event page. It allows users to easily schedule the event in their calendar.

The widget uses fast (HTTP/2) and secure (SSL A+ grade from SSL Labs) server of https://addtocalendar.com service. By default the widget adds small link to the service on the bottom of event and you can ask support@addtocalendar.com for changes.

Install from Bower
================
```
$ npm install -g bower
$ bower install addtocalendar
```

Install from NPM
================
```
$ npm install addtocalendar
```