text:
<?php
namespace Application\Common;

use Application\Todo\TodoListProviderInterface;
use Zend\Stdlib\InitializableInterface;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Doctrine\ORM\EntityManager;
use Zend\Paginator\Paginator;
use Zend\Paginator\Adapter\ArrayAdapter;

abstract class AbstractDumbTodoListProvider implements TodoListProviderInterface, InitializableInterface, ServiceLocatorAwareInterface {
	/**
	 * @var ServiceLocatorInterface
	 */
	protected $serviceLocator;

	/**
	 * @var array
	 */
	protected $contexDatas = array();

	/**
	 * @var array
	 */
	protected $requiredContextDataKeys = array();

	/**
	 * @var array
	 */
	protected $searchableParams = array();

	/**
	 * @var Form
	 */
	protected $searchForm;

	/**
	 * Initialize list data provider.
	 * Untuk sementara, method ini belum dapat menggunakan property yang diinject oleh initializer,
	 * misalnya service-locator. Jadi hanya digunakan misalnya untuk inisiasi search form dll.
	 */
	abstract public function init();

	/**
	 * (non-PHPdoc)
	 * @see \Application\Common\ListProviderInterface::setContextDatas()
	 */
	public function setContextDatas(array $contexDatas, $partial = true) {
		if(!$partial) {
			$this->validateContextDatas($contexDatas);
		}
		$this->contexDatas = array_merge($this->contexDatas, $contexDatas);
	}

	/**
	 * (non-PHPdoc)
	 * @see \Application\Common\Searchable::getSearchableParams()
	 */
	public function getSearchableParams() {
		return $this->searchableParams;
	}

	/**
	 * (non-PHPdoc)
	 * @see \Application\Common\Searchable::getSearchForm()
	 */
	public function getSearchForm() {
		if(!$this->searchForm) {
			throw new \RuntimeException(sprintf('Search form belum dicreate.'), 100, null);
		}
		return $this->searchForm;
	}

	/**
	 * (non-PHPdoc)
	 * @see \Application\Common\ListProviderInterface::getListData()
	 */
	public function getListData($pageNumber, $itemCountPerPage, $criterias = array()) {
		$this->validateContextDatas();

		/* @var $entityManager EntityManager */
		$entityManager = $this->serviceLocator->get('Doctrine\ORM\EntityManager');

		$paginatorAdapter = new ArrayAdapter($this->buildArrayOfObjects($entityManager));
		$paginator = new Paginator($paginatorAdapter);
		$paginator->setCurrentPageNumber($pageNumber);
		$paginator->setItemCountPerPage($itemCountPerPage);

		return $paginator;
	}

	/**
	 * @param EntityManager $entityManager
	 * @return array
	 */
	abstract protected function buildArrayOfObjects(EntityManager $entityManager);

	/**
	 * Validate contect datas yang diberikan. Apakah sesuai dengan konteks data yang diberikan atau tidak.
	 *
	 * @param unknown $contextDatas
	 * @throws \InvalidArgumentException
	 */
	protected function validateContextDatas($contextDatas = array()) {
		foreach ($this->requiredContextDataKeys as $requiredKey) {
			if(!array_key_exists($requiredKey, $this->contexDatas)) {
				throw new \InvalidArgumentException(sprintf(
					'Context-datas untuk list-provider %s yang diberikan tidak sesuai dengan konteks data yang dibutuhkan. Key context data yang diberikan [%s] sementara key yang dibutuhkan [%s]',
					get_called_class(),
					implode(', ', array_keys($this->contexDatas)),
					implode(', ', $this->requiredContextDataKeys)
				), 100, null);
			}
		}
	}

	/**
	 * (non-PHPdoc)
	 * @see \Zend\ServiceManager\ServiceLocatorAwareInterface::setServiceLocator()
	 */
	public function setServiceLocator(ServiceLocatorInterface $serviceLocator) {
		$this->serviceLocator = $serviceLocator;
	}

	/**
	 * (non-PHPdoc)
	 * @see \Zend\ServiceManager\ServiceLocatorAwareInterface::getServiceLocator()
	 */
	public function getServiceLocator() {
		return $this->serviceLocator;
	}
}


text:
<?php
namespace App\Utilities;

use App\Exceptions\FacebookRequestException;
use Facebook\Authentication\AccessToken;
use Facebook\GraphNodes\GraphEdge;
use SammyK\LaravelFacebookSdk\LaravelFacebookSdk;
use Session;

/**
 * Class responsible for authorization with Facebook.
 */
class FacebookAuthorizer
{
    /**
     * The Facebook SDK object.
     *
     * @var \SammyK\LaravelFacebookSdk\LaravelFacebookSdk;
     */
    private $fb;

    /**
     * Initializes a news instance of the FacebookAuthenticator class.
     *
     * @param \SammyK\LaravelFacebookSdk\LaravelFacebookSdk $fb Facebook SDK.
     */
    public function __construct(LaravelFacebookSdk $fb)
    {
        $this->fb = $fb;
    }

    /**
     * Checks if the user with the given ID has admin rights.
     *
     * @param integer   $userId User ID.
     *
     * @return boolean A value indicating whether the user with
     *                 the given ID is an admin.
     */
    public function isAdmin($userId)
    {
        $roles = collect($this->getUsers()->all());

        return $roles
            ->where('user', $userId)
            ->where('role', 'administrators')
            ->count() == 1;
    }

    /**
     * Gets the list of all users in the current application and their roles.
     *
     * @return GraphEdge
     */
    public function getUsers()
    {
        try {
            $appId = env('FACEBOOK_APP_ID');
            $appSecret = env('FACEBOOK_APP_SECRET');

            // Set app access token
            $token = new AccessToken("$appId|$appSecret");

            // Get roles
            $response = $this->fb->get("$appId/roles", $token);
            $users = $response->getGraphEdge();
        } catch (\Exception $e) {
            throw new FacebookRequestException();
        }

        return $users;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

For each section,
    the first and the second should be the same.
    If the third is also the same, the test is invalid.

AV

AV

AV

AV

AV

AV

A A

A A

A A

A A

A A

A A


text:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 3.2//EN">

    <title>jscalendar release notes</title>

jscalendar release notes

This release compiled at Friday,  6 Feb 2004 (21:40).

0.9.6

        "Smart" (TM :-) positioning algorithm.  The new algorithm will
        try to keep the calendar in the browser view, which is helpful
        in situations when the input field is near the bottom or the
        right edge.  This code is only tested with IE and Mozilla, but
        it should work with other browsers too.  Many thanks to Sunny Chowdhury for sponsoring
        this feature!

        Support for IE5/Win is back.  I also want to thank Janusz
        Piwowarski for keeping his eye on the CVS ;-) He reviewed my
        IE5-related changes and sent me a much cleaner patch.

        The calendar will now allow any day of week to be "the first
        day of week".  This was requested long time ago, by someone
        whose name I forgot (sorry).  The reason was that in certain
        countries weeks start on Saturday.  So I thought that instead
        of having a "mondayFirst" and a "saturdayFirst" parameter,
        :-), it's better to have a "firstDayOfWeek" parameter; now
        it's present and its meaning is: "0 for Sunday", "1 for
        Monday", "2 for Tuesday", etc.  The equivalent parameter for
        Calendar.setup is "firstDay".  The end user can also change
        it very easy: click on the day name in the calendar display.

        The above feature triggered one important change: the
        notion of "weekend" is now defined in the language file.
        Added parameters:

          Calendar._TT["WEEKEND"] = "0,6";
          Calendar._TT["DAY_FIRST"] = "Display %s first";

        "WEEKEND" specifies a string with comma-separated numbers from
        0 to 7; they define what days are marked as "weekend".  5 and
        6 mean, of course, "Sunday" and "Saturday".  Day first is the
        tooltip displayed when a day name is hovered; "%s" will get
        replaced with the day name.  Updated languages are "en" and
        "ro", which I maintain.  Please note that languages wich are
        not updated will not work.  If yours is one of them,
        please consider fixing it and sending me the fix so that I can
        include it in the distro.

        The calendar can now display days from the months adjacent to
        the currently displayed one.  This is optional, of course, and
        the parameter name is "showsOtherMonths" (or "showOthers" in
        Calendar.setup).  All theme files were updated.

        Displays "Time:" near the time selector, only if defined in
        the language file.

        Some bugs fixed in the date parsing code (which has also been
        rewritten a little bit cleaner).

        Calendar.setup will now configure the calendar to trigger the
        input fields' "onchange" event, if specified, when a date is
        selected.

        New parameter in Calendar.setup: "cache" (defaults to
        false).  If set to true then the popup calendar object
        will be "cached", meaning, it will be created only once, no
        matter how many input fields are there in the page.  Sometimes
        this is not desirable, which is why I've added this
        parameter.  Please note that it defaults to "false" (thus the
        default behavior has changed).

        Added a simple PHP wrapper.  It provides code which loads all
        the required scripts and theme file, and one function which
        creates and configures an input field for date input.  It
        takes care of creating and assigning unique ID-s for the
        calendar fields and it also creates the "Calendar.setup" code.
        Functions to create more specialized fields can be added very
        easily.  This feature was requested by the FreeMED.org project
        (thanks for donating!).

Wow, there were quite some changes :-D  Enjoy it!

0.9.5

      This release's primary goal is to fix a wrong license statement which
      can be found in some files from 0.9.4.  For instance in README or
      calendar.js, the statement was that the code is distributed under the
      GNU GPL; that's because I had plans to change the license, then
      changed my mind but unfortunately I committed files so.  I am sorry
      for this inconvenience, please use the latest (0.9.5) release which is
      fully covered by LGPL.

Other changes:

        Fixed an annoying bug that prevented the calendar to display
	correctly when it was configured for an input field inside a
	scrolling area.  Many thanks to Ian Barrack (Simban.com) who pointed it up and
	donated quite some money for the Calendar project!

        All examples use UTF-8 now; the translations may not be all
        up-to-date, but I strongly suggest everyone to use
        UTF-8; other encodings are a plain mess.  So far I know for sure
        that Romanian translation will work with UTF-8 and not
        anymore with ISO-8859-2.  Other translations are probably
        usable under UTF-8, but if your preferred language isn't... ;-)
        please make it and send it to me for inclusion.

        Fixed small bug in the documentation (one footnote didn't appear
        where it should have).

        Updated translations: DE, ES, HU, IT, RO.  Thanks to everyone who
        sent translations!

0.9.4

New stuff

Supports time selection.  Yes. ;-) This work has been largely
        sponsored by Himanshukumar Shah (thank you!).  See
        the docs and example files for details on how to setup.

Easy to link 2 or more fields by using the new
        onUpdate parameter of Calendar.setup.  This
        is useful, say, to automatically set a value in a second field based
        on the value selected in the first field.  See the documentation and
        first sample in simple-1.html.

Other Calendar.setup low-level parameters, for those
        wanting to have the complete control: onSelect and
        onClose.  The handlers are called when something is
        selected in the calendar or when the calendar is closed.

The translation files can optionally include the short day names
        and the short month names.  That's because in some languages, like
        German, the short form is not the first 3 letters of the entire name
        but only the first 2.  Also in other languages short names can't be
        as easily derived from the full name by just calling substr, so this
        patch solves the problem.

Implemented a nice way to make some dates "special" (look
        different).  Specifically, the setDisabledHandler method
        was replaced with the more general setDateStatusHandler
        method (the old one is still available for backwards compatibility but
        will be removed).  More details about this in the
        documentation.  Also see simple-3.html
        for a live sample.

Date parsing and formatting engine is now rewritten and supports a
        subset of strftime format specifiers from ANSI C.  This
        makes it possible to use dates like "YYYYMMDD" (the corresponding
        format for this would be "%Y%m%d").  Details in the documentation.
        Please note that the new engine is not compatibile with older
          calendar releases!

Along with the new date parser I workarounded an unpleasant crash
        that occurred in IE when certain accented characters appeared in the
        texts.  I think German was one of the language with such problems, and
        the workaround was to use the letter without an accent.  Well, now you
        can translate to whatever you want.

"Fixes" (I mean, "horrible workarounds") for Konqueror (and
        hopefully Safari).  Unfortunately, this otherwise excellent browser
        still has some bugs that keep the calendar from working
        exactly as it should..  But they're going to be fixed,
        right? ;-)

CSS themes got pretty much modified too so if you wrote your theme
        you need to update it.  Aside for the time selector support, the CSS
        themes contain a simple hack that makes the navigation buttons show
        a little arrow in the lower-right corner which indicates that if one
        holds the mouse a menu will appear.

Translation files

The translation files need to be updated in order for the calendar to
      work properly.  Currently the only updated files are calendar-en.js
      (main file) and calendar-ro.js (well, yes, I am a Romanian ;-).

Specifically, they need the following:

Correct date format, according with the new format specifiers
        introduced in 0.9.4.  Details about the available format specifiers
        in the documentation

Short day or month names, if required.  If they can be
        derived by taking the first N letters of the full name then a simple
        Calendar._SDN_len = N or Calendar._SMN_len = N will suffice.  If N
        is 3 then nothing needs to be done as we take it for granted if no
        other option is offered ;-)

We have some new texts that shows short usage information as well
        as copyright information.

If your favorite language is not there yet, or it is but not updated
      according to the main calendar-en.js file, then please consider
      translating calendar-en.js and send the translation back to me so that
      I include it in the official distribution.

Bug status

Check SourceForge,
      I didn't keep track.  However, there were a lot of bugfixes.

0.9.3

New stuff

Opera 7 compatibility — keyboard navigation is
        still not available; text selection can't be disabled, leading to an
        ugly effect when walking through the month/year menus.

Ability to align the calendar relative to the input field (or any
        other element).  Vertical: top, center, bottom.  Horizontal: left,
        center, right.  This is established as a new parameter for
        <tt>showAtElement</tt>.

Added <tt>dateClicked</tt> property (boolean).  This can be
        inspected in the "onSelect" handler to determine if a date was
        really clicked or the user only changed month/year using the menus.
        You need to check this for "single-click" calendars and
        only close/hide the calendar if it's <tt>true</tt>.

Full documentation in HTML
        and PDF format is now available in the
        distribution archive.

New language definition files: HU, HR, PT, ZH.  Thanks those who
        submitted!

Bug status

This covers only those bugs that have been reported at SourceForge.

<tt>#703,238</tt> — fixed

<tt>#703,814</tt> — fixed

<tt>#716,777</tt> — closed (was fixed already in 0.9.2-1)

<tt>#723,335</tt> — fixed

<tt>#715,122</tt> — feature request; implemented.

<tt>#721,206</tt> — fixed (added "refresh()" function)

<tt>#721,833</tt> — fixed (bug concerning the "yy" format
        parsing)

<tt>#721,833</tt> — won't fix (we won't set the time to
        midnight; time might actually be useful when we implement support
        for time selection).

    <address>Mihai Bazon</address>

Last modified on Wed Oct 29 02:37:07 2003


text:
package com.intellij.openapi.vcs.changes.ui;

import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vcs.changes.ChangeList;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.JBIterable;
import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.function.Supplier;

public class ChangeListChangesSupplier implements Supplier<Iterable<Change>> {
  private final @NotNull List<ChangeList> myChangeLists;

  public ChangeListChangesSupplier(@NotNull List<ChangeList> changeLists) {
    myChangeLists = ContainerUtil.newUnmodifiableList(changeLists);
  }

  public ChangeListChangesSupplier(@NotNull ChangeList changeList) {
    this(ContainerUtil.immutableSingletonList(changeList));
  }

  @Override
  public Iterable<Change> get() {
    return JBIterable.from(myChangeLists).flatMap(ChangeList::getChanges);
  }
}


text:
package com.chrisrm.idea.icons.patchers;

import org.jetbrains.annotations.NotNull;

/**
 * @author Konstantin Bulenkov
 */
public class DjangoIconsPatcher extends MTIconPatcher {

  @Override
  @NotNull
  public final String getPathToAppend() {
    return "/icons/plugins/python/django";
  }

  @Override
  @NotNull
  public final String getPathToRemove() {
    return "/icons/com/jetbrains/django";
  }
}


text:
import { ArtworkImageBrowser_artwork } from "v2/__generated__/ArtworkImageBrowser_artwork.graphql"
import { ArtworkImageBrowserQuery } from "v2/__generated__/ArtworkImageBrowserQuery.graphql"
import { SystemContext } from "v2/System"
import { renderWithLoadProgress } from "v2/System/Relay/renderWithLoadProgress"
import { SystemQueryRenderer as QueryRenderer } from "v2/System/Relay/SystemQueryRenderer"
import React, { useContext, useState } from "react"
import { createFragmentContainer, graphql } from "react-relay"
import { ArtworkActionsFragmentContainer as ArtworkActions } from "./ArtworkActions"
import { ArtworkImageBrowser } from "./ArtworkImageBrowser"
import { Box, Spacer } from "@artsy/palette"
import { ContextModule } from "@artsy/cohesion"

export interface ImageBrowserProps {
  artwork: ArtworkImageBrowser_artwork
}

export const ArtworkImageBrowserContainer: React.FC<ImageBrowserProps> = ({
  artwork,
}) => {
  const { images, image_alt } = artwork

  // Rather than lift state up to reset the carousel to the first slide, just
  // re-render it to reset the state.
  const [key, setKey] = useState(0)
  const handleSelectDefaultSlide = () => {
    return setKey(prevKey => prevKey + 1)
  }

  if ((images ?? []).length === 0) {
    return null
  }

  return (
    <Box data-test={ContextModule.artworkImage}>
      <ArtworkImageBrowser key={key} images={images} imageAlt={image_alt} />

      <Spacer mt={2} />

      <ArtworkActions
        artwork={artwork}
        selectDefaultSlide={handleSelectDefaultSlide}
      />
    </Box>
  )
}

export const ArtworkImageBrowserFragmentContainer = createFragmentContainer<
  ImageBrowserProps
>(ArtworkImageBrowserContainer, {
  artwork: graphql`
    fragment ArtworkImageBrowser_artwork on Artwork {
      image_alt: formattedMetadata
      ...ArtworkActions_artwork
      images {
        internalID
        uri: url(version: ["large"])
        placeholder: resized(width: 30, height: 30, version: "small") {
          url
        }
        aspectRatio: aspectRatio
        is_zoomable: isZoomable
        is_default: isDefault
        deepZoom: deepZoom {
          Image {
            xmlns
            Url
            Format
            TileSize
            Overlap
            Size {
              Width
              Height
            }
          }
        }
      }
    }
  `,
})

export const ArtworkImageBrowserQueryRenderer = ({
  artworkID,
}: {
  artworkID: string
}) => {
  const { relayEnvironment } = useContext(SystemContext)

  return (
    <QueryRenderer<ArtworkImageBrowserQuery>
      environment={relayEnvironment}
      variables={{ artworkID }}
      query={graphql`
        query ArtworkImageBrowserQuery($artworkID: String!) {
          artwork(id: $artworkID) {
            ...ArtworkImageBrowser_artwork
          }
        }
      `}
      render={renderWithLoadProgress(ArtworkImageBrowserFragmentContainer)}
    />
  )
}


text:
[![Build Status][ico-travis]][link-travis]
[![StyleCI][ico-styleci]][link-styleci]
[![ScrutinizerCI][ico-scrutinizer]][link-scrutinizer]
[![Latest Version on Packagist][ico-version]][link-packagist]
[![Software License][ico-license]](LICENSE.md)

## Requirements

This package requires PHP 7.2 or higher.

## Installation

You can install the package via composer:

``` bash
$ composer require argentcrusade/support
```

## Documentation

## Change log

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

## Testing

``` bash
$ vendor/bin/phpunit
```

## Contributing

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

## Security

If you discover any security related issues, please email zurbaev@gmail.com instead of using the issue tracker.

## License

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

[ico-version]: https://poser.pugx.org/argentcrusade/support/version?format=flat
[ico-license]: https://poser.pugx.org/argentcrusade/support/license?format=flat
[ico-travis]: https://api.travis-ci.org/argentcrusade/support.svg?branch=master
[ico-styleci]: https://styleci.io/repos/107431752/shield?branch=master&style=flat
[ico-scrutinizer]: https://scrutinizer-ci.com/g/argentcrusade/support/badges/quality-score.png?b=master

[link-packagist]: https://packagist.org/packages/argentcrusade/support
[link-travis]: https://travis-ci.org/argentcrusade/support
[link-styleci]: https://styleci.io/repos/107431752
[link-scrutinizer]: https://scrutinizer-ci.com/g/argentcrusade/support/
[link-author]: https://github.com/tzurbaev


text:
<!DOCTYPE html>

    <title>CodeFlower Source code visualization</title>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
    <link type="text/css" rel="stylesheet" href="bootstrap/dist/css/bootstrap.min.css"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href='http://fonts.googleapis.com/css?family=Rosario:400,700' rel='stylesheet' type='text/css'>
    <link type="text/css" rel="stylesheet" href="CodeFlower/stylesheets/style.css"/>

CodeFlower Source code visualization

This experiment visualizes source repositories using an interactive tree. Each disc represents a file, with a radius proportional to the number of lines of code (loc). All rendering is done client-side, in JavaScript. Try hovering on nodes to see the loc number, clicking on directory nodes to fold them, dragging nodes to rearrange the layout, and changing project to see different tree structures. Built with d3.js. Inspired by Code Swarm and Gource.

Step 1: Paste a Git URL

          Git URL
          <input type="text" class="form-control" name="repo" placeholder="https://github.com/SMU-CS-and-Math-Society/GitFlower.git">

            <button class="btn btn-default" type="button" id="submit-repo-btn">Go!</button>

        <form class="form-inline">
          <fieldset>
          Example projects from GitHub:
          <select id="project">
            <option value="CodeFlower/data/uptime.json">fzaninotto / uptime</option>
            <option value="CodeFlower/data/faker.json">fzaninotto / faker</option>
            <option value="CodeFlower/data/jquery.json">jquery / jquery</option>
            <option value="CodeFlower/data/twig.json">fabpot / twig</option>
            <option value="CodeFlower/data/lichess.json">ornicar / lila</option>
            <option value="CodeFlower/data/propel2.json">propelorm / Propel2</option>
            <option value="CodeFlower/data/doctrine2.json">doctrine / doctrine2</option>
            <option value="CodeFlower/data/wordpress.json">WordPress / WordPress</option>
            <option value="CodeFlower/data/rails.json">rails / rails</option>
            <option value="CodeFlower/data/symfony.json">symfony / symfony (WARNING: will make your computer scream)</option>
            <option value="CodeFlower/data/zf2.json">zendframework / zf2 (WARNING: will make your computer scream
          </select>
          </fieldset>
        </form>

Step 2: Done

Purpose

Did you ever dive into an existing project and wish you could have a bird's eye view of the whole code?

Did you ever have to refactor a large application and wish you knew where to start?

Did you ever look for a visualization that would help you communicate visually with your teammates about a repository?

CodeFlowers tries to answer these needs. Also, it tries to make code look beautiful, but that's another story.

Usage

To create a CodeFlower, include the CodeFlower.js file together with d3.js, just like in this page. Create a new CodeFlower instance using a CSS selector (of the div where the flower should be inserted), and the width and height of the desired visualization. Then, bind JSON data to the flower using CodeFlower.update(), and you're done.

var myFlower = new CodeFlower("#visualization", 300, 200);
myflower.update(jsonData);

Input data format

The jsonData format taken as input to update() is extremely simple. It's a JavaScript object representing a file tree structure. Each node must have a name (the file or directory name), leaf nodes must have a size (the number of lines of code or the file), and directory nodes must have a children property containing an array of nodes. As an example, here is the input for the currently displayed CodeFlower. You can modify it at will and click the update button to see the effect of your changes on the CodeFlower.

        <form id="jsonInput">
        <fieldset>
          <textarea id="jsonData"></textarea>

            <button type="submit" class="btn btn-primary btn-large">Update</button>

        </fieldset>
        </form>

Generating JSON for a project

It's easy to generate loc metrics for any project, whatever the language. You can use wc, but this method requires cleaning the output and counts comments and blanks together with actual lines of code. Alternatively, you can use cloc (http://cloc.sourceforge.net/), which is open-source and makes the difference between real source code and comments. Here are three examples using GitHub as a source.

# Using curl and cloc (fast, accurate)
$ curl https://nodeload.github.com/symfony/symfony/tar.gz/master | tar xvz
$ cloc symfony-master --csv --by-file --report-file=symfony.cloc

# Using git clone and cloc (slow, accurate)
$ git clone git://github.com/symfony/symfony.git
$ cloc symfony --csv --by-file --report-file=symfony.cloc

# Using git clone and wc (slow, inaccurate)
$ git clone git://github.com/symfony/symfony.git
$ cd symfony
$ git ls-files | xargs wc -l > symfony.wc

Once you have a loc metrics file, paste its content below and click on the convert button. This will update the CodeFlower and the JSON textarea, to let you save data for your own CodeFlowers.

        <form id="jsonConverter">
        <fieldset>
          <select name="origin">
            <option value="cloc" selected>Origin: cloc</option>
            <option value="ws">Origin: wc</option>
          </select>
          <textarea id="metricsData"></textarea>

            <button type="submit" class="btn btn-primary btn-large">Convert</button>

        </fieldset>
        </form>

Sharing your CodeFlowers

The best way to share your CodeFlowers is to use GitHub Pages, just like this very page. So just fork the fzaninotto/CodeFlower repository, add your own JSON data under the data directory, update the options of the dropdown list in the index.html file accordingly, commit the code, and push to the gh-pages branch. GitHub will publish the result for you.

Licence

All this work is open-source, published by François Zaninotto under the MIT license. That means that nothing prevents you from growing as many CodeFlowers as you want!

Tip: If you like the CodeFlower, you may also like another visualization I made with d3.js called DependencyWheel.


text:
import functools
from tornado.escape import url_escape
from tornado.httpclient import AsyncHTTPClient
from tornado.testing import AsyncHTTPTestCase, AsyncTestCase, LogTrapTestCase
from tornado.util import b
from tornado.web import Application, RequestHandler, asynchronous

from tornado import gen

class GenTest(AsyncTestCase):
    def run_gen(self, f):
        f()
        self.wait()

    def delay_callback(self, iterations, callback, arg):
        """Runs callback(arg) after a number of IOLoop iterations."""
        if iterations == 0:
            callback(arg)
        else:
            self.io_loop.add_callback(functools.partial(
                    self.delay_callback, iterations - 1, callback, arg))

    def test_no_yield(self):
        @gen.engine
        def f():
            self.stop()
        self.run_gen(f)

    def test_inline_cb(self):
        @gen.engine
        def f():
            (yield gen.Callback("k1"))()
            res = yield gen.Wait("k1")
            assert res is None
            self.stop()
        self.run_gen(f)

    def test_ioloop_cb(self):
        @gen.engine
        def f():
            self.io_loop.add_callback((yield gen.Callback("k1")))
            yield gen.Wait("k1")
            self.stop()
        self.run_gen(f)

    def test_exception_phase1(self):
        @gen.engine
        def f():
            1/0
        self.assertRaises(ZeroDivisionError, self.run_gen, f)

    def test_exception_phase2(self):
        @gen.engine
        def f():
            self.io_loop.add_callback((yield gen.Callback("k1")))
            yield gen.Wait("k1")
            1/0
        self.assertRaises(ZeroDivisionError, self.run_gen, f)

    def test_with_arg(self):
        @gen.engine
        def f():
            (yield gen.Callback("k1"))(42)
            res = yield gen.Wait("k1")
            self.assertEqual(42, res)
            self.stop()
        self.run_gen(f)

    def test_key_reuse(self):
        @gen.engine
        def f():
            yield gen.Callback("k1")
            yield gen.Callback("k1")
            self.stop()
        self.assertRaises(gen.KeyReuseError, self.run_gen, f)

    def test_key_mismatch(self):
        @gen.engine
        def f():
            yield gen.Callback("k1")
            yield gen.Wait("k2")
            self.stop()
        self.assertRaises(gen.UnknownKeyError, self.run_gen, f)

    def test_leaked_callback(self):
        @gen.engine
        def f():
            yield gen.Callback("k1")
            self.stop()
        self.assertRaises(gen.LeakedCallbackError, self.run_gen, f)

    def test_parallel_callback(self):
        @gen.engine
        def f():
            for k in range(3):
                self.io_loop.add_callback((yield gen.Callback(k)))
            yield gen.Wait(1)
            self.io_loop.add_callback((yield gen.Callback(3)))
            yield gen.Wait(0)
            yield gen.Wait(3)
            yield gen.Wait(2)
            self.stop()
        self.run_gen(f)

    def test_bogus_yield(self):
        @gen.engine
        def f():
            yield 42
        self.assertRaises(gen.BadYieldError, self.run_gen, f)

    def test_reuse(self):
        @gen.engine
        def f():
            self.io_loop.add_callback((yield gen.Callback(0)))
            yield gen.Wait(0)
            self.stop()
        self.run_gen(f)
        self.run_gen(f)

    def test_task(self):
        @gen.engine
        def f():
            yield gen.Task(self.io_loop.add_callback)
            self.stop()
        self.run_gen(f)

    def test_wait_all(self):
        @gen.engine
        def f():
            (yield gen.Callback("k1"))("v1")
            (yield gen.Callback("k2"))("v2")
            results = yield gen.WaitAll(["k1", "k2"])
            self.assertEqual(results, ["v1", "v2"])
            self.stop()
        self.run_gen(f)

    def test_exception_in_yield(self):
        @gen.engine
        def f():
            try:
                yield gen.Wait("k1")
                raise "did not get expected exception"
            except gen.UnknownKeyError:
                pass
            self.stop()
        self.run_gen(f)

    def test_resume_after_exception_in_yield(self):
        @gen.engine
        def f():
            try:
                yield gen.Wait("k1")
                raise "did not get expected exception"
            except gen.UnknownKeyError:
                pass
            (yield gen.Callback("k2"))("v2")
            self.assertEqual((yield gen.Wait("k2")), "v2")
            self.stop()
        self.run_gen(f)

    def test_orphaned_callback(self):
        @gen.engine
        def f():
            self.orphaned_callback = yield gen.Callback(1)
        try:
            self.run_gen(f)
            raise "did not get expected exception"
        except gen.LeakedCallbackError:
            pass
        self.orphaned_callback()

    def test_multi(self):
        @gen.engine
        def f():
            (yield gen.Callback("k1"))("v1")
            (yield gen.Callback("k2"))("v2")
            results = yield [gen.Wait("k1"), gen.Wait("k2")]
            self.assertEqual(results, ["v1", "v2"])
            self.stop()
        self.run_gen(f)

    def test_multi_delayed(self):
        @gen.engine
        def f():
            # callbacks run at different times
            responses = yield [
                gen.Task(self.delay_callback, 3, arg="v1"),
                gen.Task(self.delay_callback, 1, arg="v2"),
                ]
            self.assertEqual(responses, ["v1", "v2"])
            self.stop()
        self.run_gen(f)

    def test_arguments(self):
        @gen.engine
        def f():
            (yield gen.Callback("noargs"))()
            self.assertEqual((yield gen.Wait("noargs")), None)
            (yield gen.Callback("1arg"))(42)
            self.assertEqual((yield gen.Wait("1arg")), 42)

            (yield gen.Callback("kwargs"))(value=42)
            result = yield gen.Wait("kwargs")
            self.assertTrue(isinstance(result, gen.Arguments))
            self.assertEqual(((), dict(value=42)), result)
            self.assertEqual(dict(value=42), result.kwargs)

            (yield gen.Callback("2args"))(42, 43)
            result = yield gen.Wait("2args")
            self.assertTrue(isinstance(result, gen.Arguments))
            self.assertEqual(((42, 43), {}), result)
            self.assertEqual((42, 43), result.args)

            def task_func(callback):
                callback(None, error="foo")
            result = yield gen.Task(task_func)
            self.assertTrue(isinstance(result, gen.Arguments))
            self.assertEqual(((None,), dict(error="foo")), result)

            self.stop()
        self.run_gen(f)

class GenSequenceHandler(RequestHandler):
    @asynchronous
    @gen.engine
    def get(self):
        self.io_loop = self.request.connection.stream.io_loop
        self.io_loop.add_callback((yield gen.Callback("k1")))
        yield gen.Wait("k1")
        self.write("1")
        self.io_loop.add_callback((yield gen.Callback("k2")))
        yield gen.Wait("k2")
        self.write("2")
        # reuse an old key
        self.io_loop.add_callback((yield gen.Callback("k1")))
        yield gen.Wait("k1")
        self.finish("3")

class GenTaskHandler(RequestHandler):
    @asynchronous
    @gen.engine
    def get(self):
        io_loop = self.request.connection.stream.io_loop
        client = AsyncHTTPClient(io_loop=io_loop)
        response = yield gen.Task(client.fetch, self.get_argument('url'))
        response.rethrow()
        self.finish(b("got response: ") + response.body)

class GenWebTest(AsyncHTTPTestCase, LogTrapTestCase):
    def get_app(self):
        return Application([
                ('/sequence', GenSequenceHandler),
                ('/task', GenTaskHandler),
                ])

    def test_sequence_handler(self):
        response = self.fetch('/sequence')
        self.assertEqual(response.body, b("123"))

    def test_task_handler(self):
        response = self.fetch('/task?url=%s' % url_escape(self.get_url('/sequence')))
        self.assertEqual(response.body, b("got response: 123"))


text:
<?php
namespace Grid\Embed\Model\Parser\Oembed;

use Zork\Factory\FactoryAbstract;

/**
 * Oembed content type adapter factory
 *
 * @author Kristof Matos <kristof.matos@megaweb.hu>
 */
class ContentFactory extends FactoryAbstract
{

}


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

    <groupId>com.exemple</groupId>
    <artifactId>teste</artifactId>
    <version>0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>mongocom-examples-vraptor3</name>

    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>br.com.caelum</groupId>
            <artifactId>vraptor</artifactId>
            <version>3.5.3</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>com.arquivolivre</groupId>
            <artifactId>mongocom</artifactId>
            <version>0.3-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>6.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>sonatype-nexus-snapshots</id>
            <name>Sonatype Nexus Snapshots</name>
            <url>https://oss.sonatype.org/content/repositories/snapshots</url>
            <releases>
                <enabled>false</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <compilerArguments>
                        <endorseddirs>${endorsed.dir}</endorseddirs>
                    </compilerArguments>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.1.1</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.1</version>
                <executions>
                    <execution>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${endorsed.dir}</outputDirectory>
                            <silent>true</silent>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>javax</groupId>
                                    <artifactId>javaee-endorsed-api</artifactId>
                                    <version>6.0</version>
                                    <type>jar</type>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>


text:
const Connection = require("./src/DB/Connection"),
  Repository = require("./src/ORM/BaseRepository"),
  Entity = require("./src/ORM/Entity"),
  Expression = require("./src/ORM/Builder/Query/Expression");

module.exports = {
  Connection: Connection,
  ORM: {
    Repository: Repository,
    Entity: Entity,
    Query: {
      Expression: Expression
    }
  }
};


text:
/**
 * Created by xubt on 10/14/16.
 */

kanbanApp.directive('cardTagsSmall', function() {
    return {
        restrict: 'E',
        templateUrl: 'component/card/tags/partials/tags-small.html',
        replace: true,
        controller: ['$scope', 'boardsService', 'tagsService', 'cardTagsService', function($scope, boardsService, tagsService, cardTagsService) {
            $scope.tags = $scope.card.tagsNode === undefined ? [] : $scope.card.tagsNode.cardTags;
        }]
    };
});


text:
NS_ASSUME_NONNULL_BEGIN

@interface Monologue (CoreDataProperties)

+ (NSFetchRequest<Monologue *> *)fetchRequest;

@property (nullable, nonatomic, copy) NSString *age;
@property (nullable, nonatomic, copy) NSString *author;
@property (nullable, nonatomic, copy) NSNumber *favorite;
@property (nullable, nonatomic, copy) NSString *gender;
@property (nullable, nonatomic, copy) NSString *length;
@property (nullable, nonatomic, copy) NSString *notes;
@property (nullable, nonatomic, copy) NSString *period;
@property (nullable, nonatomic, copy) NSString *tags;
@property (nullable, nonatomic, copy) NSString *text;
@property (nullable, nonatomic, copy) NSString *title;
@property (nullable, nonatomic, copy) NSString *tone;

@end

NS_ASSUME_NONNULL_END


text:
from datetime import datetime
from datetime import time as dtime
from dateutil import parser
import os
import threading

import zopkio.runtime as runtime

def start_threads_and_join(commands):
  threads = [threading.Thread(target=command) for command in commands]
  for thread in threads:
    thread.start()
  for thread in threads:
    thread.join()

def get_log_for_test(test_name, log_path, dt_format):
  """
  Gets the portion of the log file relevant to the test (i.e lies between the start and end times of the test).
  It is assumed that every line in the log file starts with a datetime following dtformat.
  :param test_name: the test name
  :param log_path: the absolute path to the log file
  :param dt_format: the format of the datetime in the log file. This could simply be an example datetime because
                   only the word count matters
  """
  word_count = len(dt_format.split())

  start_time = datetime.fromtimestamp(runtime.get_active_test_start_time(test_name))
  end_time = datetime.fromtimestamp(runtime.get_active_test_end_time(test_name))

  start_pos = _search_log_for_datetime(log_path, start_time, word_count)
  end_pos = _search_log_for_datetime(log_path, end_time, word_count, reverse=True)

  with open(log_path, 'r') as log:
    log.seek(start_pos)
    return log.read(end_pos - start_pos)

def _search_log_for_datetime(log_path, dt, word_count, reverse=False):
  """
  Find the start position of the line containing the datetime nearest to dt.
  :param log_path: the absolute path to the log file
  :param dt: the datetime to be searched
  :param word_count: the number of "words" that represents the datetime in the log
  :param reverse: if False, finds the line with the largest datetime less than dt
                  if True, finds the line with the smallest datetime larger than dt
  """
  ONE_KILOBYTE = 1024
  with open(log_path, 'r') as log:
    lbound = 0
    ubound = os.path.getsize(log_path)

    # the algorithm does not guarantee that one of lbound or ubound is changed in each iteration
    # we use search_area to keep track of the block size (ubound - lbound) to see if it changes.
    # It is initialized to 0 in order to declare it before use (note 0 is an impossible case)
    search_area = 0
    while ubound > lbound:
      # Doing a linear search when the size gets small to avoid the issue of keeping track of the previous line.
      if ubound - lbound < ONE_KILOBYTE:
        return _linear_search_log_for_time(log_path, dt, word_count, lbound, ubound, reverse)
      mid = (lbound + ubound) / 2
      log.seek(mid)
      log.readline()  # skip to the end of the line, we will process the next one

      # some lines may not begin with a valid datetime (e.g exception messages that spans multiple lines)
      # hence, we loop until we find a line with a valid datetime
      is_valid_dt = False
      while not is_valid_dt:
        if log.tell() == ubound:
          # we have reached the end of the search block.
          # This should rarely happen unless there is a really long line in the log.
          # Do a linear search because we cannot make further progress
          return _linear_search_log_for_time(log_path, dt, word_count, lbound, ubound, reverse)
        line_start = log.tell()
        line = log.readline()
        timestr = ' '.join(line.split()[:word_count])
        try:
          log_dt = parser.parse(timestr)  # TODO(tlan) exception management
          # if the parse does not work the default time returned is dtime(0, 0, 0)
          # we ignore this time so it is not included in the calculation
          # if a test starts or ends with this time, this will return a superset of the relevant log lines of the tests
          # There may be a chance this affects validation; but the chance is low enough that it is acceptable
          if log_dt.time() != dtime(0, 0, 0):
            is_valid_dt = True
        except:
          is_valid_dt = False

      # the following conditional block updates the bounds. The line that was just process is kept within the bounds,
      # because it still may be the line that we are looking for.
      if log_dt > dt:
        ubound = log.tell()
      elif log_dt < dt:
        lbound = line_start
      else:
        # here we have found a matching time, but we must continue searching
        # because there may be multiple lines with matching times!
        if not reverse:
          ubound = log.tell()
        else:
          lbound = line_start

      #  perform linear search when further progress cannot be made.
      if ubound - lbound == search_area:
        return _linear_search_log_for_time(log_path, dt, word_count, lbound, ubound, reverse)
      search_area = ubound - lbound

def _linear_search_log_for_time(log_path, dt, word_count, lbound, ubound, reverse=False):
  """
  Find the start position of the line containing the datetime nearest to dt.
  :param log_path: the absolute path to the log file
  :param dt: the datetime to be searched
  :param word_count: the number of "words" that represents the datetime in the log
  :param lbound: the byte offset to the start of the block to be searched
  :param ubound: the byte offset to the end of the block to be searched
  :param reverse: if False, finds the line with the largest datetime less than dt
                  if True, finds the line with the smallest datetime larger than dt
  """
  with open(log_path, 'r') as log:
    log.seek(lbound)

    # The following are true at the beginning of each iteration:
    #   - line_start points to the beginning of the line of the datetime we are currently processing
    #   - prev_line_start points the beginning of the previous line (except for the first iteration)
    prev_line_start = lbound
    line_start = log.tell()
    while log.tell() < ubound:
      is_valid_dt = False

      # some lines may not begin with a valid datetime (e.g exception messages that spans multiple lines)
      # hence, we loop until we find a line with a valid datetime
      while not is_valid_dt:
        line = log.readline()
        timestr = ' '.join(line.split()[:word_count])
        try:
          log_dt = parser.parse(timestr)
          is_valid_dt = True
        except:
          is_valid_dt = False
          if log.tell() == ubound:
            if not reverse:
              return prev_line_start
            else:
              return log.tell()

      if not reverse:
        if log_dt >= dt:
          return prev_line_start
        else:
          prev_line_start = line_start
          line_start = log.tell()
          if line_start == ubound:
            # reached the end of block, return the last line
            return prev_line_start
      else:
        if log_dt > dt:
          return log.tell()
        else:
          if log.tell() == ubound:
            # reached the end of block, return the last line
            return log.tell()
          else:
            line_start = log.tell()


text:
/**
 * tests/db/model/sample/timeout.js
 */
'use strict';
const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
const expect = chai.expect;
const tu = require('../../../testUtils');
const u = require('./utils');
const Sample = tu.db.Sample;
const Aspect = tu.db.Aspect;
const Subject = tu.db.Subject;
const Op = require('sequelize').Op;

describe('tests/db/model/sample/timeout.js >', () => {
  let updatedAt;
  const defaultForStatus = 'Timeout';
  const twentyFourhours = 24;
  const hundredDays = 100;
  const tenSeconds = 10;
  const fiveMinutes = 5;

  afterEach(u.forceDelete);

  beforeEach((done) => {
    Aspect.create({
      isPublished: true,
      name: `${tu.namePrefix}OneSecond`,
      timeout: '1s',
      valueType: 'NUMERIC',
      criticalRange: [0, 0],
      warningRange: [1, 1],
      infoRange: [2, 2],
      okRange: [3, 3],
    })
    .then(() => Aspect.create({
      isPublished: true,
      name: `${tu.namePrefix}TwoMinutes`,
      timeout: '2m',
      valueType: 'NUMERIC',
      criticalRange: [0, 0],
      warningRange: [1, 1],
      infoRange: [2, 2],
      okRange: [3, 3],
    }))
    .then(() => Aspect.create({
      isPublished: true,
      name: `${tu.namePrefix}ThreeHours`,
      timeout: '3H',
      valueType: 'NUMERIC',
      criticalRange: [0, 0],
      warningRange: [1, 1],
      infoRange: [2, 2],
      okRange: [3, 3],
    }))
    .then(() => Aspect.create({
      isPublished: true,
      name: `${tu.namePrefix}NinetyDays`,
      timeout: '90D',
      valueType: 'NUMERIC',
      criticalRange: [0, 0],
      warningRange: [1, 1],
      infoRange: [2, 2],
      okRange: [3, 3],
    }))
    .then(() => Subject.create({
      isPublished: true,
      name: `${tu.namePrefix}Subject`,
    }))
    .then(() => Sample.bulkUpsertByName([
      { name: `${tu.namePrefix}Subject|${tu.namePrefix}OneSecond`, value: 1 },
      { name: `${tu.namePrefix}Subject|${tu.namePrefix}TwoMinutes`, value: 1 },
      { name: `${tu.namePrefix}Subject|${tu.namePrefix}ThreeHours`, value: 2 },
      { name: `${tu.namePrefix}Subject|${tu.namePrefix}NinetyDays`, value: 3 },
    ]))
    .then(() => Sample.findAll({
      attributes: ['name', 'updatedAt'],
      where: {
        name: {
          [Op.iLike]: `${tu.namePrefix}Subject|%`,
        },
      },
    })
    .each((s) => {
      updatedAt = s.updatedAt;
    }))
    .then(() => done())
    .catch(done);
  });

  it('simulate 100 days in the future', (done) => {
    const mockUpdatedAt = updatedAt;
    mockUpdatedAt.setHours(updatedAt.getHours() +
      (twentyFourhours * hundredDays));
    Sample.doTimeout(mockUpdatedAt)
    .then((res) => {
      expect(res).to.contain({ numberEvaluated: 4, numberTimedOut: 4 });
      expect(res.timedOutSamples.length).to.equal(res.numberTimedOut);
    })
    .then(() => Sample.findAll({
      where: {
        name: {
          [Op.iLike]: `${tu.namePrefix}Subject|%`,
        },
      },
    })
    .each((s) => {
      expect(s.status).to.equal(defaultForStatus);
    }))
    .then(() => done())
    .catch(done);
  });

  it('simulate 1 day in the future', (done) => {
    const mockUpdatedAt = updatedAt;
    mockUpdatedAt.setHours(updatedAt.getHours() + twentyFourhours);
    Sample.doTimeout(mockUpdatedAt)
    .then((res) => {
      expect(res).to.contain({ numberEvaluated: 4, numberTimedOut: 3 });
      expect(res.timedOutSamples.length).to.equal(res.numberTimedOut);
    })
    .then(() => Sample.findAll({
      where: {
        name: {
          [Op.iLike]: `${tu.namePrefix}Subject|%`,
        },
      },
    })
    .each((s) => {
      switch (s.name) {
        case `${tu.namePrefix}Subject|${tu.namePrefix}OneSecond`:
          expect(s.status).to.equal(defaultForStatus);
          break;
        case `${tu.namePrefix}Subject|${tu.namePrefix}TwoMinutes`:
          expect(s.status).to.equal(defaultForStatus);
          break;
        case `${tu.namePrefix}Subject|${tu.namePrefix}ThreeHours`:
          expect(s.status).to.equal(defaultForStatus);
          break;
        case `${tu.namePrefix}Subject|${tu.namePrefix}NinetyDays`:
          expect(s.status).to.not.equal(defaultForStatus);
          break;
      }
    }))
    .then(() => done())
    .catch(done);
  });

  it('simulate 5 minutes in the future', (done) => {
    const mockUpdatedAt = updatedAt;
    mockUpdatedAt.setMinutes(updatedAt.getMinutes() + fiveMinutes);
    Sample.doTimeout(mockUpdatedAt)
    .then((res) => {
      expect(res).to.contain({ numberEvaluated: 4, numberTimedOut: 2 });
      expect(res.timedOutSamples.length).to.equal(res.numberTimedOut);
    })
    .then(() => Sample.findAll({
      where: {
        name: {
          [Op.iLike]: `${tu.namePrefix}Subject|%`,
        },
      },
    })
    .each((s) => {
      switch (s.name) {
        case `${tu.namePrefix}Subject|${tu.namePrefix}OneSecond`:
          expect(s.status).to.equal(defaultForStatus);
          break;
        case `${tu.namePrefix}Subject|${tu.namePrefix}TwoMinutes`:
          expect(s.status).to.equal(defaultForStatus);
          break;
        case `${tu.namePrefix}Subject|${tu.namePrefix}ThreeHours`:
          expect(s.status).to.not.equal(null);
          break;
        case `${tu.namePrefix}Subject|${tu.namePrefix}NinetyDays`:
          expect(s.status).to.not.equal(null);
          break;
      }
    }))
    .then(() => done())
    .catch(done);
  });

  it('simulate 10 seconds in the past', (done) => {
    const mockUpdatedAt = updatedAt;
    mockUpdatedAt.setSeconds(updatedAt.getSeconds() - tenSeconds);
    Sample.doTimeout(mockUpdatedAt)
    .then((res) => {
      expect(res).to.contain({ numberEvaluated: 4, numberTimedOut: 0 });
      expect(res.timedOutSamples.length).to.equal(res.numberTimedOut);
    })
    .then(() => Sample.findAll({
      where: {
        name: {
          [Op.iLike]: `${tu.namePrefix}Subject|%`,
        },
      },
    })
    .each((s) => {
      switch (s.name) {
        case `${tu.namePrefix}Subject|${tu.namePrefix}OneSecond`:
          expect(s.status).to.not.equal(null);
          break;
        case `${tu.namePrefix}Subject|${tu.namePrefix}TwoMinutes`:
          expect(s.status).to.not.equal(null);
          break;
        case `${tu.namePrefix}Subject|${tu.namePrefix}ThreeHours`:
          expect(s.status).to.not.equal(null);
          break;
        case `${tu.namePrefix}Subject|${tu.namePrefix}NinetyDays`:
          expect(s.status).to.not.equal(null);
          break;
      }
    }))
    .then(() => done())
    .catch(done);
  });

  it('checktimeout scope should only return required fields' +
      'from sample model', (done) => {
    Sample.scope('checkTimeout').findOne()
    .then((samp) => {
      expect(samp.id).to.not.equal(undefined);
      expect(samp.value).to.not.equal(undefined);
      expect(samp.updatedAt).to.not.equal(undefined);
      expect(samp.name).to.not.equal(undefined);
      expect(samp.aspectId).to.not.equal(undefined);
      expect(samp.subjectId).to.not.equal(undefined);
      expect(samp.relatedLinks).to.not.equal(undefined);
      expect(samp.aspect.name).to.not.equal(undefined);
      expect(samp.aspect.tags).to.not.equal(undefined);

      /*
       * the following sample fields should not be fetched in the
       * checktimeout query
       */
      expect(samp.previousStatus).to.equal(undefined);
      expect(samp.messageBody).to.equal(undefined);
      expect(samp.messageCode).to.equal(undefined);
      expect(samp.status).to.equal(undefined);
      expect(samp.createdAt).to.equal(undefined);
    })
    .then(() => done())
    .catch(done);
  });
});


text:
Haar Cascade Inverter
=====================

Script to invert an OpenCV Haar cascade. For example, when passed a cascade
file that would normally detect human faces in an image, it will instead
generate an image of a human face.

See [this blog post](http://matthewearl.github.io/2016/01/14/inverse-haar/) for
an overview of how the code works.


text:
package com.koch.ambeth.persistence.h2;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.sql.Statement;
import java.util.List;
import java.util.Set;

import javax.persistence.OptimisticLockException;
import javax.persistence.PersistenceException;

import org.h2.Driver;

import com.koch.ambeth.ioc.annotation.Autowired;
import com.koch.ambeth.ioc.config.Property;
import com.koch.ambeth.persistence.IColumnEntry;
import com.koch.ambeth.persistence.SelectPosition;
import com.koch.ambeth.persistence.api.sql.ISqlBuilder;
import com.koch.ambeth.persistence.jdbc.AbstractConnectionDialect;
import com.koch.ambeth.persistence.jdbc.ColumnEntry;
import com.koch.ambeth.persistence.jdbc.JdbcUtil;
import com.koch.ambeth.persistence.jdbc.config.PersistenceJdbcConfigurationConstants;
import com.koch.ambeth.util.collections.ArrayList;
import com.koch.ambeth.util.collections.EmptyMap;
import com.koch.ambeth.util.collections.HashMap;
import com.koch.ambeth.util.collections.HashSet;
import com.koch.ambeth.util.collections.ILinkedMap;
import com.koch.ambeth.util.collections.IList;
import com.koch.ambeth.util.collections.IMap;
import com.koch.ambeth.util.exception.RuntimeExceptionUtil;

public class H2Dialect extends AbstractConnectionDialect {
	public static int getOptimisticLockErrorCode() {
		return 10001;
	}

	@Autowired
	protected ISqlBuilder sqlBuilder;

	@Property(name = PersistenceJdbcConfigurationConstants.DatabaseProtocol)
	protected String protocol;

	@Override
	protected Class<?> getDriverType() {
		return Driver.class;
	}

	@Override
	protected ConnectionKeyValue preProcessConnectionIntern(Connection connection,
			String[] schemaNames, boolean forcePreProcessing) throws SQLException {
		Statement stm = null;
		ResultSet rs = null;
		try {
			stm = connection.createStatement();
			stm.execute("SET MULTI_THREADED 1");

			if ("jdbc:h2:mem".equals(protocol)) {
				stm.execute("SET DB_CLOSE_DELAY -1");
			}
			stm.execute("CREATE SCHEMA IF NOT EXISTS \"" + schemaNames[0] + "\"");
			stm.execute("SET SCHEMA \"" + schemaNames[0] + "\"");

			rs = stm.executeQuery("SELECT alias_name FROM INFORMATION_SCHEMA.FUNCTION_ALIASES");
			HashSet<String> functionAliases = new HashSet<>();
			while (rs.next()) {
				functionAliases.add(rs.getString("alias_name"));
			}
			rs.close();
			createAliasIfNecessary("TO_TIMESTAMP", Functions.class.getName() + ".toTimestamp",
					functionAliases, stm);

			stm = connection.createStatement();
			ArrayList<String> disableSql = new ArrayList<>();
			ArrayList<String> enableSql = new ArrayList<>();
			for (String tableName : getAllFullqualifiedTableNames(connection, schemaNames)) {
				disableSql.add("ALTER TABLE " + tableName + " SET REFERENTIAL_INTEGRITY FALSE");
				enableSql.add("ALTER TABLE " + tableName + " SET REFERENTIAL_INTEGRITY TRUE CHECK");
			}
			return new ConnectionKeyValue(disableSql.toArray(String.class),
					enableSql.toArray(String.class));
		}
		catch (Exception e) {
			throw RuntimeExceptionUtil.mask(e);
		}
		finally {
			JdbcUtil.close(stm, rs);
		}
	}

	protected void createAliasIfNecessary(String aliasName, String functionName,
			Set<String> functionAliases, Statement stm) throws SQLException {
		if (functionAliases.contains(aliasName)) {
			return;
		}
		stm.execute("CREATE ALIAS \"" + toDefaultCase(aliasName) + "\" FOR \"" + functionName + "\"");
	}

	@Override
	public IList<IMap<String, String>> getExportedKeys(Connection connection, String[] schemaNames)
			throws SQLException {
		Statement stm = null;
		ResultSet rs = null;
		try {
			ArrayList<IMap<String, String>> allForeignKeys = new ArrayList<>();
			// rs = connection.getMetaData().getExportedKeys(null, null, null);
			stm = connection.createStatement();
			// rs = stm.executeQuery("SELECT * FROM INFORMATION_SCHEMA.CONSTRAINTS WHERE
			// constraint_type='REFERENTIAL'");
			rs = stm.executeQuery("SELECT * FROM INFORMATION_SCHEMA.CROSS_REFERENCES");
			// printResultSet(rs);
			while (rs.next()) {
				HashMap<String, String> foreignKey = new HashMap<>();

				foreignKey.put("OWNER", schemaNames[0]);
				foreignKey.put("CONSTRAINT_NAME", rs.getString("FK_NAME"));
				foreignKey.put("FKTABLE_NAME", rs.getString("FKTABLE_NAME"));
				foreignKey.put("FKCOLUMN_NAME", rs.getString("FKCOLUMN_NAME"));
				foreignKey.put("PKTABLE_NAME", rs.getString("PKTABLE_NAME"));
				foreignKey.put("PKCOLUMN_NAME", rs.getString("PKCOLUMN_NAME"));

				allForeignKeys.add(foreignKey);
			}
			return allForeignKeys;
		}
		finally {
			JdbcUtil.close(stm, rs);
		}
	}

	@Override
	public ILinkedMap<String, IList<String>> getFulltextIndexes(Connection connection,
			String schemaName) throws SQLException {
		return EmptyMap.emptyMap();
	}

	@Override
	public boolean isSystemTable(String tableName) {
		return false;
	}

	@Override
	public void releaseSavepoint(Savepoint savepoint, Connection connection) throws SQLException {
		throw new UnsupportedOperationException();
	}

	@Override
	public int getResourceBusyErrorCode() {
		throw new UnsupportedOperationException();
	}

	@Override
	public PersistenceException createPersistenceException(SQLException e, String relatedSql) {
		int errorCode = e.getErrorCode();
		if (errorCode == getOptimisticLockErrorCode()) {
			OptimisticLockException ex = new OptimisticLockException(relatedSql, e);
			ex.setStackTrace(RuntimeExceptionUtil.EMPTY_STACK_TRACE);
			return ex;
		}
		return null;
	}

	@Override
	public ResultSet getIndexInfo(Connection connection, String schemaName, String tableName,
			boolean unique) throws SQLException {
		return connection.getMetaData().getIndexInfo(null, schemaName, tableName, unique, true);
	}

	@Override
	public Class<?> getComponentTypeByFieldTypeName(String additionalFieldInfo) {
		// H2 does not support arrays so there is never a component type
		return null;
	}

	@Override
	public String getFieldTypeNameByComponentType(Class<?> componentType) {
		throw new UnsupportedOperationException();
	}

	@Override
	public List<String> getAllFullqualifiedSequences(Connection connection, String... schemaNames)
			throws SQLException {
		if (schemaNames.length == 0) {
			schemaNames = this.schemaNames;
		}
		return queryDefault(connection, "full_name",
				"SELECT sequence_schema || '.' || sequence_name AS full_name FROM INFORMATION_SCHEMA.SEQUENCES WHERE sequence_schema IN (?)",
				(Object) schemaNames);
	}

	@Override
	public List<String> getAllFullqualifiedTableNames(Connection connection, String... schemaNames)
			throws SQLException {
		if (schemaNames.length == 0) {
			schemaNames = this.schemaNames;
		}
		return queryDefault(connection, "full_name",
				"SELECT table_schema || '.' || table_name AS full_name FROM INFORMATION_SCHEMA.TABLES WHERE table_type='TABLE' AND table_schema IN (?)",
				(Object) schemaNames);
	}

	@Override
	public List<String> getAllFullqualifiedViews(Connection connection, String... schemaNames)
			throws SQLException {
		if (schemaNames.length == 0) {
			schemaNames = this.schemaNames;
		}
		PreparedStatement pstm = null;
		ResultSet rs = null;
		try {
			pstm = connection.prepareStatement(
					"SELECT table_schema, table_name FROM INFORMATION_SCHEMA.VIEWS WHERE table_schema IN (?)");
			pstm.setObject(1, schemaNames);
			rs = pstm.executeQuery();
			ArrayList<String> viewNames = new ArrayList<>();
			while (rs.next()) {
				String tableSchema = rs.getString("table_schema");
				String tableName = rs.getString("table_name");
				viewNames.add(tableSchema + "." + tableName);
			}
			return viewNames;
		}
		finally {
			JdbcUtil.close(pstm, rs);
		}
	}

	@Override
	public IList<IColumnEntry> getAllFieldsOfTable(Connection connection, String fqTableName)
			throws SQLException {
		String[] names = sqlBuilder.getSchemaAndTableName(fqTableName);
		ResultSet tableColumnsRS = connection.getMetaData().getColumns(null, names[0], names[1], null);
		try {
			ArrayList<IColumnEntry> columns = new ArrayList<>();
			while (tableColumnsRS.next()) {
				String fieldName = tableColumnsRS.getString("COLUMN_NAME");
				int columnIndex = tableColumnsRS.getInt("ORDINAL_POSITION");
				int typeIndex = tableColumnsRS.getInt("DATA_TYPE");

				String typeName = tableColumnsRS.getString("TYPE_NAME");

				String isNullable = tableColumnsRS.getString("IS_NULLABLE");
				boolean nullable = "YES".equalsIgnoreCase(isNullable);

				int scale = tableColumnsRS.getInt("COLUMN_SIZE");
				int digits = tableColumnsRS.getInt("DECIMAL_DIGITS");
				int radix = tableColumnsRS.getInt("NUM_PREC_RADIX");

				Class<?> javaType = JdbcUtil.getJavaTypeFromJdbcType(typeIndex, scale, digits);

				ColumnEntry entry = new ColumnEntry(fieldName, columnIndex, javaType, typeName, nullable,
						radix, true);
				columns.add(entry);
			}
			return columns;
		}
		finally {
			JdbcUtil.close(tableColumnsRS);
		}
	}

	@Override
	protected String buildDeferrableForeignKeyConstraintsSelectSQL(String[] schemaNames) {
		return null;
	}

	@Override
	protected void handleRow(String schemaName, String tableName, String constraintName,
			ArrayList<String> disableConstraintsSQL, ArrayList<String> enableConstraintsSQL) {
		throw new UnsupportedOperationException();
	}

	@Override
	public String prepareCommand(String sqlCommand) {
		sqlCommand = prepareCommandIntern(sqlCommand, " NUMBER *\\( *1 *, *0 *\\)", " BOOLEAN");
		sqlCommand = prepareCommandIntern(sqlCommand, " NUMBER *\\( *3 *, *0 *\\)", " INT");
		sqlCommand = prepareCommandIntern(sqlCommand, " NUMBER *\\( *5 *, *0 *\\)", " INT");
		sqlCommand = prepareCommandIntern(sqlCommand, " NUMBER *\\( *9 *, *0 *\\)", " INT");
		sqlCommand = prepareCommandIntern(sqlCommand, " NUMBER *\\( *10 *, *0 *\\)", " LONG");
		sqlCommand = prepareCommandIntern(sqlCommand, " NUMBER *\\( *12 *, *0 *\\)", " LONG");
		sqlCommand = prepareCommandIntern(sqlCommand, " NUMBER *\\( *18 *, *0 *\\)", " BIGINT");
		sqlCommand = prepareCommandIntern(sqlCommand, " NUMBER *\\( *\\* *, *0 *\\)", " BIGINT");
		sqlCommand = prepareCommandIntern(sqlCommand, " NUMBER", " DOUBLE");
		sqlCommand = prepareCommandIntern(sqlCommand, "VARCHAR2 *\\( *(\\d+) *BYTE *\\)",
				"VARCHAR($1)");
		sqlCommand = prepareCommandIntern(sqlCommand, "VARCHAR2 *\\( *(\\d+) *CHAR *\\)",
				"VARCHAR($1)");
		sqlCommand = prepareCommandIntern(sqlCommand, " DEFERRABLE *INITIALLY *(?:DEFERRED|IMMEDIATE)",
				"");
		sqlCommand = prepareCommandIntern(sqlCommand, " NOORDER", "");
		sqlCommand = prepareCommandIntern(sqlCommand, " USING +INDEX", "");
		sqlCommand = prepareCommandIntern(sqlCommand, "MAXVALUE *9{19,} ",
				"MAXVALUE 999999999999999999 ");
		sqlCommand = prepareCommandIntern(sqlCommand, "DBMS_RANDOM\\.VALUE", "RAND()");
		sqlCommand = prepareCommandIntern(sqlCommand, "to_timestamp\\(", "TO_TIMESTAMP(");
		return sqlCommand;
	}

	@Override
	public SelectPosition getLimitPosition() {
		return SelectPosition.AFTER_WHERE;
	}
}


text:
import { Template } from 'meteor/templating';
import { Tasks } from '../api/tasks.js';
import './task.html';

Template.task.events({
	'click .toggle-checked'() {
		// Set the checked property to the opposite of its current value
		Tasks.update(this._id, {
			$set: { checked: ! this.checked },
		});
	},
	'click .delete'() {
		Tasks.remove(this._id);
	},
})