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

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="twitter:site" content="@kivyframework">

    <title>kivy.app — Kivy 1.10.0 ドキュメント</title>
    <link href='//fonts.googleapis.com/css?family=Source+Code+Pro:400,700' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="../../_static/fresh.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />

    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" />
    <link rel="top" title="Kivy 1.10.0 ドキュメント" href="../../index.html" />
    <link rel="up" title="kivy" href="../kivy.html" />

Guides

Garden

API Reference

PDF

Wiki

Quick search

            <form class="search" action="../../search.html" method="get">

                <input type="hidden" name="check_keywords" value="yes" />
                <input type="hidden" name="area" value="default" />
                <input type="text" class="text" name="q" />
            </form>

Getting Started(翻訳済み)

Introduction (翻訳済み)

Installation(翻訳済み)

A first App(翻訳済み)

Properties(翻訳済み)

Kv Design Language(翻訳済み)

Events(翻訳済み)

Non-widget stuff(翻訳済み)

Layouts(翻訳済み)

Drawing(翻訳済み)

Packaging(翻訳済み)

Examples(翻訳済み)

Diving in(翻訳済み)

Gallery of Examples(翻訳済み)

Gallery(翻訳済み)

3D Rotating Monkey Head(翻訳済み)

Widget animation(翻訳済み)

Suite of Application Builders(翻訳済み)

Application example using build() + return(翻訳済み)

Application built from a  .kv fil(翻訳済み)

Application from a .kv in a Template Directory(翻訳済み)

Camera Example(翻訳済み)

Bezier Example(翻訳済み)

Canvas stress(翻訳済み)

Circle Example(翻訳済み)

FBO Canvas(翻訳済み)

Line (SmoothLine) Experiment(翻訳済み)

Lines Extended Demo(翻訳済み)

Mesh test(翻訳済み)

Multitexture Example(翻訳済み)

Repeat Texture on Resize(翻訳済み)

Rotation Example(翻訳済み)

Stencil demo(翻訳済み)

Tesselate Demonstration

Texture Wrapping and Coordinates Example(翻訳済み)

Shuffled Camera Feed Puzzle(翻訳済み)

Kivy Catalog(翻訳済み)

Multistroke Recognition Database Demonstration(翻訳済み)

Basic Picture Viewer(翻訳済み)

Live Shader Editor(翻訳済み)

Showcase of Kivy Features

Touch Tracer Line Drawing Demonstration(翻訳済み)

User's Guide(翻訳済み)

Installation(翻訳済み)

Philosophy(翻訳済み)

Contributing(翻訳済み)

FAQ (翻訳済み)

Contact Us(翻訳済み)

Programming Guide(翻訳済み)

Kivy Basics(翻訳済み)

Controlling the environment(翻訳済み)

Configure Kivy(翻訳済み)

Architectural Overview(翻訳済み)

Events and Properties (翻訳済み)

Input management (翻訳済み)

Widgets(翻訳済み)

Graphics (翻訳済み)

Kv language(翻訳済み)

Integrating with other Frameworks(翻訳済み)

Packaging your application(翻訳済み)

Package licensing (翻訳済み)

Tutorials(翻訳済み)

Pong Game Tutorial(翻訳済み)

A Simple Paint App(翻訳済み)

Crash Course(翻訳済み)

API Reference

Kivy framework(翻訳済み)

Adapters

Adapter

List Item View Argument Converters

DictAdapter

ListAdapter

SelectableDataItem

SimpleListAdapter

Animation(翻訳済み)

Application (翻訳中)

Atlas

Kivy Base

Cache manager

Clock object(翻訳ずみ)

Compatibility module for Python 2.7 and > 3.3

Configuration object

Context

Core Abstraction(翻訳済み)

Audio

Camera

Clipboard(翻訳済み)

OpenGL

Image

Spelling

Text

Text Markup

Text layout

Video

Window

Kivy module for binary dependencies.

Effects

Damped scroll effect

Kinetic effect

Opacity scroll effect

Scroll effect

Event dispatcher

Factory object

Garden

Geometry utilities

Gesture recognition

Graphics(翻訳中)

CGL: standard C interface for OpenGL

Graphics compiler

Context management

Context instructions

Framebuffer

GL instructions

Canvas

OpenGL

OpenGL utilities

Scissor Instructions

Shader

Stencil instructions

SVG

Tesselator

Texture

Transformation

Input management

Motion Event Factory

Motion Event

Input Postprocessing

Calibration

Dejitter

Double Tap

Ignore list

Retain Touch

Triple Tap

Motion Event Provider

Providers

Android Joystick Input Provider

Native support for HID input from the linux kernel

Leap Motion - finger only

Native support of Wacom tablet from linuxwacom driver

Native support of MultitouchSupport framework for MacBook (MaxOSX platform)

Mouse provider implementation

Native support for Multitouch devices on Linux, using libmtdev.

Auto Create Input Provider Config Entry for Available MT Hardware (linux only).

TUIO Input Provider

Common definitions for a Windows provider

Support for WM_PEN messages (Windows platform)

Support for WM_TOUCH messages (Windows platform)

Input recorder

Motion Event Shape

Interactive launcher

Kivy Language(翻訳済み)

Builder

Parser

External libraries

DDS File library

GstPlayer

Python mtdev

OSC

NO DOCUMENTATION (module kivy.uix.recycleview)

simpleOSC 0.2

Asynchronous data loader

Logger object

Metrics

Modules

Console

Inspector

JoyCursor

Keybinding

Monitor module

Recorder module

Screen

Touchring

Web Debugger

Multistroke gesture recognizer

Network support

UrlRequest

Parser utilities

Properties

Resources management

Storage

Dictionary store

JSON store

Redis Store

Support

Tools

Packaging

Pyinstaller hooks

Widgets(翻訳済み)

Abstract View

Accordion

Action Bar

Anchor Layout

Behaviors

Button Behavior

Code Navigation Behavior

Compound Selection Behavior

Cover Behavior

Drag Behavior

Emacs Behavior

Focus Behavior

Kivy Namespaces

ToggleButton Behavior

Box Layout

Bubble

Button

Camera

Carousel(翻訳済み)

CheckBox

Code Input

Color Picker

Drop-Down List

EffectWidget

FileChooser

Float Layout(翻訳済み)

Gesture Surface

Grid Layout

Image

Label(翻訳済み)

Layout

List View

ModalView

PageLayout

Popup

Progress Bar

RecycleBoxLayout

RecycleGridLayout

RecycleLayout

RecycleView

RecycleView Data Model

RecycleView Layouts

RecycleView Views

Relative Layout

reStructuredText renderer

Sandbox

Scatter

Scatter Layout

Screen Manager(翻訳中)

ScrollView

SelectableView

Settings (翻訳中)

Slider

Spinner

Splitter

Stack Layout

Stencil View

Switch

TabbedPanel

Text Input

Toggle button

Tree View

Video

Video player

VKeyboard

Widget class

Utils

Vector

Weak Method

Weak Proxy

Table Of Contents

kivy.app のソースコード

'''
Application
===========

The :class:`App` class is the base for creating Kivy applications.
Think of it as your main entry point into the Kivy run loop. In most
cases, you subclass this class and make your own app. You create an
instance of your specific app class and then, when you are ready to
start the application's life cycle, you call your instance's
:meth:`App.run` method.

Creating an Application
-----------------------

Method using build() override
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

To initialize your app with a widget tree, override the :meth:`~App.build`
method in your app class and return the widget tree you constructed.

Here's an example of a very simple application that just shows a button:

.. include:: ../../examples/application/app_with_build.py
   :literal:

The file is also available in the examples folder at
:file:`kivy/examples/application/app_with_build.py`.

Here, no widget tree was constructed (or if you will, a tree with only
the root node).

Method using kv file
~~~~~~~~~~~~~~~~~~~~

You can also use the :doc:`api-kivy.lang` for creating applications. The
.kv can contain rules and root widget definitions at the same time. Here
is the same example as the Button one in a kv file.

Contents of 'test.kv':

.. include:: ../../examples/application/test.kv
   :literal:

Contents of 'main.py':

.. include:: ../../examples/application/app_with_kv.py
   :literal:

See :file:`kivy/examples/application/app_with_kv.py`.

The relationship between main.py and test.kv is explained in
:meth:`App.load_kv`.

.. _Application configuration:

Application configuration
-------------------------

Use the configuration file
~~~~~~~~~~~~~~~~~~~~~~~~~~

Your application might need its own configuration file. The
:class:`App` class handles 'ini' files automatically if you add
the section key-value pair to the :meth:`App.build_config` method using the
`config` parameter (an instance of :class:`~kivy.config.ConfigParser`)::

    class TestApp(App):
        def build_config(self, config):
            config.setdefaults('section1', {
                'key1': 'value1',
                'key2': '42'
            })

As soon as you add one section to the config, a file is created on the
disk (see :attr:`~App.get_application_config` for its location) and
named based your class name. "TestApp" will give a config file named
"test.ini" with the content::

    [section1]
    key1 = value1
    key2 = 42

The "test.ini" will be automatically loaded at runtime and you can access the
configuration in your :meth:`App.build` method::

    class TestApp(App):
        def build_config(self, config):
            config.setdefaults('section1', {
                'key1': 'value1',
                'key2': '42'
            })

        def build(self):
            config = self.config
            return Label(text='key1 is %s and key2 is %d' % (
                config.get('section1', 'key1'),
                config.getint('section1', 'key2')))

Create a settings panel
~~~~~~~~~~~~~~~~~~~~~~~

Your application can have a settings panel to let your user configure some of
your config tokens. Here is an example done in the KinectViewer example
(available in the examples directory):

    .. image:: images/app-settings.jpg
        :align: center

You can add your own panels of settings by extending
the :meth:`App.build_settings` method.
Check the :class:`~kivy.uix.settings.Settings` about how to create a panel,
because you need a JSON file / data first.

Let's take as an example the previous snippet of TestApp with custom
config. We could create a JSON like this::

    [
        { "type": "title",
          "title": "Test application" },

        { "type": "options",
          "title": "My first key",
          "desc": "Description of my first key",
          "section": "section1",
          "key": "key1",
          "options": ["value1", "value2", "another value"] },

        { "type": "numeric",
          "title": "My second key",
          "desc": "Description of my second key",
          "section": "section1",
          "key": "key2" }
    ]

Then, we can create a panel using this JSON to automatically create all the
options and link them to our :attr:`App.config` ConfigParser instance::

    class TestApp(App):
        # ...
        def build_settings(self, settings):
            jsondata = """... put the json data here ..."""
            settings.add_json_panel('Test application',
                self.config, data=jsondata)

That's all! Now you can press F1 (default keystroke) to toggle the
settings panel or press the "settings" key on your android device. You
can manually call :meth:`App.open_settings` and
:meth:`App.close_settings` if you want to handle this manually. Every
change in the panel is automatically saved in the config file.

You can also use :meth:`App.build_settings` to modify properties of
the settings panel. For instance, the default panel has a sidebar for
switching between json panels whose width defaults to 200dp. If you'd
prefer this to be narrower, you could add::

    settings.interface.menu.width = dp(100)

to your :meth:`build_settings` method.

You might want to know when a config value has been changed by the
user in order to adapt or reload your UI. You can then overload the
:meth:`on_config_change` method::

    class TestApp(App):
        # ...
        def on_config_change(self, config, section, key, value):
            if config is self.config:
                token = (section, key)
                if token == ('section1', 'key1'):
                    print('Our key1 has been changed to', value)
                elif token == ('section1', 'key2'):
                    print('Our key2 has been changed to', value)

The Kivy configuration panel is added by default to the settings
instance. If you don't want this panel, you can declare your Application as
follows::

    class TestApp(App):
        use_kivy_settings = False
        # ...

This only removes the Kivy panel but does not stop the settings instance
from appearing. If you want to prevent the settings instance from appearing
altogether, you can do this::

    class TestApp(App):
        def open_settings(self, *largs):
            pass

.. versionadded:: 1.0.7

Profiling with on_start and on_stop
-----------------------------------

It is often useful to profile python code in order to discover locations to
optimise. The standard library profilers
(http://docs.python.org/2/library/profile.html) provides multiple options for
profiling code. For profiling the entire program, the natural
approaches of using profile as a module or profile's run method does not work
with Kivy. It is however, possible to use :meth:`App.on_start` and
:meth:`App.on_stop` methods::

    import cProfile

    class MyApp(App):
        def on_start(self):
            self.profile = cProfile.Profile()
            self.profile.enable()

        def on_stop(self):
            self.profile.disable()
            self.profile.dump_stats('myapp.profile')

This will create a file called `myapp.profile` when you exit your app.

Customising layout
------------------

You can choose different settings widget layouts by setting
:attr:`App.settings_cls`. By default, this is a
:class:`~kivy.uix.settings.Settings` class which provides the pictured
sidebar layout, but you could set it to any of the other layouts
provided in :mod:`kivy.uix.settings` or create your own. See the
module documentation for :mod:`kivy.uix.settings` for more
information.

You can customise how the settings panel is displayed by
overriding :meth:`App.display_settings` which is called before
displaying the settings panel on the screen. By default, it
simply draws the panel on top of the window, but you could modify it
to (for instance) show the settings in a
:class:`~kivy.uix.popup.Popup` or add it to your app's
:class:`~kivy.uix.screenmanager.ScreenManager` if you are using
one. If you do so, you should also modify :meth:`App.close_settings`
to exit the panel appropriately. For instance, to have the settings
panel appear in a popup you can do::

    def display_settings(self, settings):
        try:
            p = self.settings_popup
        except AttributeError:
            self.settings_popup = Popup(content=settings,
                                        title='Settings',
                                        size_hint=(0.8, 0.8))
            p = self.settings_popup
        if p.content is not settings:
            p.content = settings
        p.open()

    def close_settings(self, *args):
        try:
            p = self.settings_popup
            p.dismiss()
        except AttributeError:
            pass # Settings popup doesn't exist

Finally, if you want to replace the current settings panel widget, you
can remove the internal references to it using
:meth:`App.destroy_settings`. If you have modified
:meth:`App.display_settings`, you should be careful to detect if the
settings panel has been replaced.

Pause mode
----------

.. versionadded:: 1.1.0

On tablets and phones, the user can switch at any moment to another
application. By default, your application will close and the
:meth:`App.on_stop` event will be fired.

If you support Pause mode, when switching to another application, your
application will wait indefinitely until the user
switches back to your application. There is an issue with OpenGL on Android
devices: it is not guaranteed that the OpenGL ES Context will be restored when
your app resumes. The mechanism for restoring all the OpenGL data is not yet
implemented in Kivy.

The currently implemented Pause mechanism is:

    #. Kivy checks every frame if Pause mode is activated by the Operating
       System due to the user switching to another application, a phone
       shutdown or any other reason.
    #. :meth:`App.on_pause` is called:
    #. If False is returned, then :meth:`App.on_stop` is called.
    #. If True is returned (default case), the application will sleep until
       the OS resumes our App.
    #. When the app is resumed, :meth:`App.on_resume` is called.
    #. If our app memory has been reclaimed by the OS, then nothing will be
       called.

Here is a simple example of how on_pause() should be used::

   class TestApp(App):

      def on_pause(self):
         # Here you can save data if needed
         return True

      def on_resume(self):
         # Here you can check if any data needs replacing (usually nothing)
         pass

.. warning::

    Both `on_pause` and `on_stop` must save important data because after
    `on_pause` is called, `on_resume` may not be called at all.

'''

__all__ = ('App', )

import os
from inspect import getfile
from os.path import dirname, join, exists, sep, expanduser, isfile
from kivy.config import ConfigParser
from kivy.base import runTouchApp, stopTouchApp
from kivy.compat import string_types
from kivy.factory import Factory
from kivy.logger import Logger
from kivy.event import EventDispatcher
from kivy.lang import Builder
from kivy.resources import resource_find
from kivy.utils import platform as core_platform
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty, StringProperty
from kivy.setupconfig import USE_SDL2

platform = core_platform

[ドキュメント]class App(EventDispatcher):
    ''' Application class, see module documentation for more information.

    :Events:
        `on_start`:
            Fired when the application is being started (before the
            :func:`~kivy.base.runTouchApp` call.
        `on_stop`:
            Fired when the application stops.
        `on_pause`:
            Fired when the application is paused by the OS.
        `on_resume`:
            Fired when the application is resumed from pause by the OS. Beware:
            you have no guarantee that this event will be fired after the
            `on_pause` event has been called.

    .. versionchanged:: 1.7.0
        Parameter `kv_file` added.

    .. versionchanged:: 1.8.0
        Parameters `kv_file` and `kv_directory` are now properties of App.
    '''

    title = StringProperty(None)
    '''
    Title of your application. You can set this as follows::

        class MyApp(App):
            def build(self):
                self.title = 'Hello world'

    .. versionadded:: 1.0.5

    .. versionchanged:: 1.8.0
        `title` is now a :class:`~kivy.properties.StringProperty`. Don't
        set the title in the class as previously stated in the documentation.

    .. note::

        For Kivy < 1.8.0, you can set this as follows::

            class MyApp(App):
                title = 'Custom title'

        If you want to dynamically change the title, you can do::

            from kivy.base import EventLoop
            EventLoop.window.title = 'New title'

    '''

    icon = StringProperty(None)
    '''Icon of your application.
    The icon can be located in the same directory as your main file. You can
    set this as follows::

        class MyApp(App):
            def build(self):
                self.icon = 'myicon.png'

    .. versionadded:: 1.0.5

    .. versionchanged:: 1.8.0
        `icon` is now a :class:`~kivy.properties.StringProperty`. Don't set the
        icon in the class as previously stated in the documentation.

    .. note::

        For Kivy prior to 1.8.0, you need to set this as follows::

            class MyApp(App):
                icon = 'customicon.png'

         Recommended 256x256 or 1024x1024? for GNU/Linux and Mac OSX
         32x32 for Windows7 or less. <= 256x256 for windows 8
         256x256 does work (on Windows 8 at least), but is scaled
         down and doesn't look as good as a 32x32 icon.
    '''

    use_kivy_settings = True
    '''.. versionadded:: 1.0.7

    If True, the application settings will also include the Kivy settings. If
    you don't want the user to change any kivy settings from your settings UI,
    change this to False.
    '''

    settings_cls = ObjectProperty(None)
    '''.. versionadded:: 1.8.0

    The class used to construct the settings panel and
    the instance passed to :meth:`build_config`. You should
    use either :class:`~kivy.uix.settings.Settings` or one of the provided
    subclasses with different layouts
    (:class:`~kivy.uix.settings.SettingsWithSidebar`,
    :class:`~kivy.uix.settings.SettingsWithSpinner`,
    :class:`~kivy.uix.settings.SettingsWithTabbedPanel`,
    :class:`~kivy.uix.settings.SettingsWithNoMenu`). You can also create your
    own Settings subclass. See the documentation
    of :mod:`~kivy.uix.settings.Settings` for more information.

    :attr:`~App.settings_cls` is an :class:`~kivy.properties.ObjectProperty`
    and defaults to :class:`~kivy.uix.settings.SettingsWithSpinner` which
    displays settings panels with a spinner to switch between them. If you set
    a string, the :class:`~kivy.factory.Factory` will be used to resolve the
    class.

    '''

    kv_directory = StringProperty(None)
    '''Path of the directory where application kv is stored, defaults to None

    .. versionadded:: 1.8.0

    If a kv_directory is set, it will be used to get the initial kv file. By
    default, the file is assumed to be in the same directory as the current App
    definition file.
    '''

    kv_file = StringProperty(None)
    '''Filename of the Kv file to load, defaults to None.

    .. versionadded:: 1.8.0

    If a kv_file is set, it will be loaded when the application starts. The
    loading of the "default" kv file will be prevented.
    '''

    # Return the current running App instance
    _running_app = None

    __events__ = ('on_start', 'on_stop', 'on_pause', 'on_resume')

    def __init__(self, **kwargs):
        App._running_app = self
        self._app_directory = None
        self._app_name = None
        self._app_settings = None
        self._app_window = None
        super(App, self).__init__(**kwargs)
        self.built = False

        #: Options passed to the __init__ of the App
        self.options = kwargs

        #: Returns an instance of the :class:`~kivy.config.ConfigParser` for
        #: the application configuration. You can use this to query some config
        #: tokens in the :meth:`build` method.
        self.config = None

        #: The *root* widget returned by the :meth:`build` method or by the
        #: :meth:`load_kv` method if the kv file contains a root widget.
        self.root = None

[ドキュメント]    def build(self):
        '''Initializes the application; it will be called only once.
        If this method returns a widget (tree), it will be used as the root
        widget and added to the window.

        :return:
            None or a root :class:`~kivy.uix.widget.Widget` instance
            if no self.root exists.'''

        if not self.root:
            return Widget()

[ドキュメント]    def build_config(self, config):
        '''.. versionadded:: 1.0.7

        This method is called before the application is initialized to
        construct your :class:`~kivy.config.ConfigParser` object. This
        is where you can put any default section / key / value for your
        config. If anything is set, the configuration will be
        automatically saved in the file returned by
        :meth:`get_application_config`.

        :Parameters:
            `config`: :class:`~kivy.config.ConfigParser`
                Use this to add default section / key / value items

        '''

[ドキュメント]    def build_settings(self, settings):
        '''.. versionadded:: 1.0.7

        This method is called when the user (or you) want to show the
        application settings. It is called once when the settings panel
        is first opened, after which the panel is cached. It may be
        called again if the cached settings panel is removed by
        :meth:`destroy_settings`.

        You can use this method to add settings panels and to
        customise the settings widget e.g. by changing the sidebar
        width. See the module documentation for full details.

        :Parameters:
            `settings`: :class:`~kivy.uix.settings.Settings`
                Settings instance for adding panels

        '''

[ドキュメント]    def load_kv(self, filename=None):
        '''This method is invoked the first time the app is being run if no
        widget tree has been constructed before for this app.
        This method then looks for a matching kv file in the same directory as
        the file that contains the application class.

        For example, say you have a file named main.py that contains::

            class ShowcaseApp(App):
                pass

        This method will search for a file named `showcase.kv` in
        the directory that contains main.py. The name of the kv file has to be
        the lowercase name of the class, without the 'App' postfix at the end
        if it exists.

        You can define rules and a root widget in your kv file::

            <ClassName>: # this is a rule
                ...

            ClassName: # this is a root widget
                ...

        There must be only one root widget. See the :doc:`api-kivy.lang`
        documentation for more information on how to create kv files. If your
        kv file contains a root widget, it will be used as self.root, the root
        widget for the application.

        .. note::

            This function is called from :meth:`run`, therefore, any widget
            whose styling is defined in this kv file and is created before
            :meth:`run` is called (e.g. in `__init__`), won't have its styling
            applied. Note that :meth:`build` is called after :attr:`load_kv`
            has been called.
        '''
        # Detect filename automatically if it was not specified.
        if filename:
            filename = resource_find(filename)
        else:
            try:
                default_kv_directory = dirname(getfile(self.__class__))
                if default_kv_directory == '':
                    default_kv_directory = '.'
            except TypeError:
                # if it's a builtin module.. use the current dir.
                default_kv_directory = '.'

            kv_directory = self.kv_directory or default_kv_directory
            clsname = self.__class__.__name__.lower()
            if (clsname.endswith('app') and
                    not isfile(join(kv_directory, '%s.kv' % clsname))):
                clsname = clsname[:-3]
            filename = join(kv_directory, '%s.kv' % clsname)

        # Load KV file
        Logger.debug('App: Loading kv <{0}>'.format(filename))
        rfilename = resource_find(filename)
        if rfilename is None or not exists(rfilename):
            Logger.debug('App: kv <%s> not found' % filename)
            return False
        root = Builder.load_file(rfilename)
        if root:
            self.root = root
        return True

[ドキュメント]    def get_application_name(self):
        '''Return the name of the application.
        '''
        if self.title is not None:
            return self.title
        clsname = self.__class__.__name__
        if clsname.endswith('App'):
            clsname = clsname[:-3]
        return clsname

[ドキュメント]    def get_application_icon(self):
        '''Return the icon of the application.
        '''
        if not resource_find(self.icon):
            return ''
        else:
            return resource_find(self.icon)

[ドキュメント]    def get_application_config(self, defaultpath='%(appdir)s/%(appname)s.ini'):
        '''.. versionadded:: 1.0.7

        .. versionchanged:: 1.4.0
            Customized the default path for iOS and Android platforms. Added a
            defaultpath parameter for desktop OS's (not applicable to iOS
            and Android.)

        Return the filename of your application configuration. Depending
        on the platform, the application file will be stored in
        different locations:

            - on iOS: <appdir>/Documents/.<appname>.ini
            - on Android: /sdcard/.<appname>.ini
            - otherwise: <appdir>/<appname>.ini

        When you are distributing your application on Desktops, please
        note that if the application is meant to be installed
        system-wide, the user might not have write-access to the
        application directory. If you want to store user settings, you
        should overload this method and change the default behavior to
        save the configuration file in the user directory. ::

            class TestApp(App):
                def get_application_config(self):
                    return super(TestApp, self).get_application_config(
                        '~/.%(appname)s.ini')

        Some notes:

        - The tilda '~' will be expanded to the user directory.
        - %(appdir)s will be replaced with the application :attr:`directory`
        - %(appname)s will be replaced with the application :attr:`name`
        '''

        if platform == 'android':
            defaultpath = '/sdcard/.%(appname)s.ini'
        elif platform == 'ios':
            defaultpath = '~/Documents/%(appname)s.ini'
        elif platform == 'win':
            defaultpath = defaultpath.replace('/', sep)
        return expanduser(defaultpath) % {
            'appname': self.name, 'appdir': self.directory}

    @property
    def root_window(self):
        '''.. versionadded:: 1.9.0

        Returns the root window instance used by :meth:`run`.
        '''
        return self._app_window

[ドキュメント]    def load_config(self):
        '''(internal) This function is used for returning a ConfigParser with
        the application configuration. It's doing 3 things:

            #. Creating an instance of a ConfigParser
            #. Loading the default configuration by calling
               :meth:`build_config`, then
            #. If it exists, it loads the application configuration file,
               otherwise it creates one.

        :return:
            :class:`~kivy.config.ConfigParser` instance
        '''
        try:
            config = ConfigParser.get_configparser('app')
        except KeyError:
            config = None
        if config is None:
            config = ConfigParser(name='app')
        self.config = config
        self.build_config(config)
        # if no sections are created, that's mean the user don't have
        # configuration.
        if len(config.sections()) == 0:
            return
        # ok, the user have some sections, read the default file if exist
        # or write it !
        filename = self.get_application_config()
        if filename is None:
            return config
        Logger.debug('App: Loading configuration <{0}>'.format(filename))
        if exists(filename):
            try:
                config.read(filename)
            except:
                Logger.error('App: Corrupted config file, ignored.')
                config.name = ''
                try:
                    config = ConfigParser.get_configparser('app')
                except KeyError:
                    config = None
                if config is None:
                    config = ConfigParser(name='app')
                self.config = config
                self.build_config(config)
                pass
        else:
            Logger.debug('App: First configuration, create <{0}>'.format(
                filename))
            config.filename = filename
            config.write()
        return config

    @property
    def directory(self):
        '''.. versionadded:: 1.0.7

        Return the directory where the application lives.
        '''
        if self._app_directory is None:
            try:
                self._app_directory = dirname(getfile(self.__class__))
                if self._app_directory == '':
                    self._app_directory = '.'
            except TypeError:
                # if it's a builtin module.. use the current dir.
                self._app_directory = '.'
        return self._app_directory

    @property
    def user_data_dir(self):
        '''
        .. versionadded:: 1.7.0

        Returns the path to the directory in the users file system which the
        application can use to store additional data.

        Different platforms have different conventions with regards to where
        the user can store data such as preferences, saved games and settings.
        This function implements these conventions. The <app_name> directory
        is created when the property is called, unless it already exists.

        On iOS, `~/Documents/<app_name>` is returned (which is inside the
        app's sandbox).

        On Android, `/sdcard/<app_name>` is returned.

        On Windows, `%APPDATA%/<app_name>` is returned.

        On OS X, `~/Library/Application Support/<app_name>` is returned.

        On Linux, `$XDG_CONFIG_HOME/<app_name>` is returned.
        '''
        data_dir = ""
        if platform == 'ios':
            data_dir = join('~/Documents', self.name)
        elif platform == 'android':
            data_dir = join('/sdcard', self.name)
        elif platform == 'win':
            data_dir = os.path.join(os.environ['APPDATA'], self.name)
        elif platform == 'macosx':
            data_dir = '~/Library/Application Support/{}'.format(self.name)
        else:  # _platform == 'linux' or anything else...:
            data_dir = os.environ.get('XDG_CONFIG_HOME', '~/.config')
            data_dir = join(data_dir, self.name)
        data_dir = expanduser(data_dir)
        if not exists(data_dir):
            os.mkdir(data_dir)
        return data_dir

    @property
    def name(self):
        '''.. versionadded:: 1.0.7

        Return the name of the application based on the class name.
        '''
        if self._app_name is None:
            clsname = self.__class__.__name__
            if clsname.endswith('App'):
                clsname = clsname[:-3]
            self._app_name = clsname.lower()
        return self._app_name

[ドキュメント]    def run(self):
        '''Launches the app in standalone mode.
        '''
        if not self.built:
            self.load_config()
            self.load_kv(filename=self.kv_file)
            root = self.build()
            if root:
                self.root = root
        if self.root:
            if not isinstance(self.root, Widget):
                Logger.critical('App.root must be an _instance_ of Widget')
                raise Exception('Invalid instance in App.root')
            from kivy.core.window import Window
            Window.add_widget(self.root)

        # Check if the window is already created
        from kivy.base import EventLoop
        window = EventLoop.window
        if window:
            self._app_window = window
            window.set_title(self.get_application_name())
            icon = self.get_application_icon()
            if icon:
                window.set_icon(icon)
            self._install_settings_keys(window)
        else:
            Logger.critical("Application: No window is created."
                            " Terminating application run.")
            return

        self.dispatch('on_start')
        runTouchApp()
        self.stop()

[ドキュメント]    def stop(self, *largs):
        '''Stop the application.

        If you use this method, the whole application will stop by issuing
        a call to :func:`~kivy.base.stopTouchApp`.
        '''
        self.dispatch('on_stop')
        stopTouchApp()

        # Clear the window children
        if self._app_window:
            for child in self._app_window.children:
                self._app_window.remove_widget(child)

[ドキュメント]    def on_start(self):
        '''Event handler for the `on_start` event which is fired after
        initialization (after build() has been called) but before the
        application has started running.
        '''
        pass

[ドキュメント]    def on_stop(self):
        '''Event handler for the `on_stop` event which is fired when the
        application has finished running (i.e. the window is about to be
        closed).
        '''
        pass

[ドキュメント]    def on_pause(self):
        '''Event handler called when Pause mode is requested. You should
        return True if your app can go into Pause mode, otherwise
        return False and your application will be stopped.

        You cannot control when the application is going to go into this mode.
        It's determined by the Operating System and mostly used for mobile
        devices (android/ios) and for resizing.

        The default return value is True.

        .. versionadded:: 1.1.0
        .. versionchanged:: 1.10.0
            The default return value is now True.
        '''
        return True

[ドキュメント]    def on_resume(self):
        '''Event handler called when your application is resuming from
        the Pause mode.

        .. versionadded:: 1.1.0

        .. warning::

            When resuming, the OpenGL Context might have been damaged / freed.
            This is where you can reconstruct some of your OpenGL state
            e.g. FBO content.
        '''
        pass

    @staticmethod

[ドキュメント]    def get_running_app():
        '''Return the currently running application instance.

        .. versionadded:: 1.1.0
        '''
        return App._running_app

[ドキュメント]    def on_config_change(self, config, section, key, value):
        '''Event handler fired when a configuration token has been changed by
        the settings page.
        '''
        pass

[ドキュメント]    def open_settings(self, *largs):
        '''Open the application settings panel. It will be created the very
        first time, or recreated if the previously cached panel has been
        removed by :meth:`destroy_settings`. The settings panel will be
        displayed with the
        :meth:`display_settings` method, which by default adds the
        settings panel to the Window attached to your application. You
        should override that method if you want to display the
        settings panel differently.

        :return:
            True if the settings has been opened.

        '''
        if self._app_settings is None:
            self._app_settings = self.create_settings()
        displayed = self.display_settings(self._app_settings)
        if displayed:
            return True
        return False

[ドキュメント]    def display_settings(self, settings):
        '''.. versionadded:: 1.8.0

        Display the settings panel. By default, the panel is drawn directly
        on top of the window. You can define other behaviour by overriding
        this method, such as adding it to a ScreenManager or Popup.

        You should return True if the display is successful, otherwise False.

        :Parameters:
            `settings`: :class:`~kivy.uix.settings.Settings`
                You can modify this object in order to modify the settings
                display.

        '''
        win = self._app_window
        if not win:
            raise Exception('No windows are set on the application, you cannot'
                            ' open settings yet.')
        if settings not in win.children:
            win.add_widget(settings)
            return True
        return False

[ドキュメント]    def close_settings(self, *largs):
        '''Close the previously opened settings panel.

        :return:
            True if the settings has been closed.
        '''
        win = self._app_window
        settings = self._app_settings
        if win is None or settings is None:
            return
        if settings in win.children:
            win.remove_widget(settings)
            return True
        return False

[ドキュメント]    def create_settings(self):
        '''Create the settings panel. This method will normally
        be called only one time per
        application life-time and the result is cached internally,
        but it may be called again if the cached panel is removed
        by :meth:`destroy_settings`.

        By default, it will build a settings panel according to
        :attr:`settings_cls`, call :meth:`build_settings`, add a Kivy panel if
        :attr:`use_kivy_settings` is True, and bind to
        on_close/on_config_change.

        If you want to plug your own way of doing settings, without the Kivy
        panel or close/config change events, this is the method you want to
        overload.

        .. versionadded:: 1.8.0
        '''
        if self.settings_cls is None:
            from kivy.uix.settings import SettingsWithSpinner
            self.settings_cls = SettingsWithSpinner
        elif isinstance(self.settings_cls, string_types):
            self.settings_cls = Factory.get(self.settings_cls)
        s = self.settings_cls()
        self.build_settings(s)
        if self.use_kivy_settings:
            s.add_kivy_panel()
        s.bind(on_close=self.close_settings,
               on_config_change=self._on_config_change)
        return s

[ドキュメント]    def destroy_settings(self):
        '''.. versionadded:: 1.8.0

        Dereferences the current settings panel if one
        exists. This means that when :meth:`App.open_settings` is next
        run, a new panel will be created and displayed. It doesn't
        affect any of the contents of the panel, but lets you (for
        instance) refresh the settings panel layout if you have
        changed the settings widget in response to a screen size
        change.

        If you have modified :meth:`~App.open_settings` or
        :meth:`~App.display_settings`, you should be careful to
        correctly detect if the previous settings widget has been
        destroyed.

        '''
        if self._app_settings is not None:
            self._app_settings = None

    #
    # privates
    #

    def _on_config_change(self, *largs):
        self.on_config_change(*largs[1:])

    def _install_settings_keys(self, window):
        window.bind(on_keyboard=self._on_keyboard_settings)

    def _on_keyboard_settings(self, window, *largs):
        key = largs[0]
        setting_key = 282  # F1

        # android hack, if settings key is pygame K_MENU
        if platform == 'android' and not USE_SDL2:
            import pygame
            setting_key = pygame.K_MENU

        if key == setting_key:
            # toggle settings panel
            if not self.open_settings():
                self.close_settings()
            return True
        if key == 27:
            return self.close_settings()

    def on_title(self, instance, title):
        if self._app_window:
            self._app_window.set_title(title)

    def on_icon(self, instance, icon):
        if self._app_window:
            self._app_window.set_icon(self.get_application_icon())


text:
package org.zalando.nakadi.service;

import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.zalando.nakadi.config.NakadiSettings;
import org.zalando.nakadi.domain.Feature;
import org.zalando.nakadi.domain.Permission;
import org.zalando.nakadi.domain.ResourceAuthorization;
import org.zalando.nakadi.domain.ResourceAuthorizationAttribute;
import org.zalando.nakadi.plugin.api.authz.AuthorizationAttribute;
import org.zalando.nakadi.plugin.api.authz.AuthorizationService;
import org.zalando.nakadi.repository.db.AuthorizationDbRepository;

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

import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.internal.verification.VerificationModeFactory.times;

public class AdminServiceTest {

    final List<Permission> defaultAdminPermissions;
    final AuthorizationAttribute user1 = new ResourceAuthorizationAttribute("user", "user1");
    final AuthorizationAttribute user2 = new ResourceAuthorizationAttribute("user", "user2");
    final AuthorizationAttribute service2 = new ResourceAuthorizationAttribute("service", "service2");
    final List<AuthorizationAttribute> newAttrs = Arrays.asList(user1, user2, service2);
    final Permission permAdminUser1 = new Permission("org/zalando/nakadi", AuthorizationService.Operation.ADMIN,
            new ResourceAuthorizationAttribute("user", "user1"));
    final Permission permAdminService1 = new Permission("org/zalando/nakadi", AuthorizationService.Operation.ADMIN,
            new ResourceAuthorizationAttribute("service", "service1"));
    final Permission permAdminService2 = new Permission("org/zalando/nakadi", AuthorizationService.Operation.ADMIN,
            new ResourceAuthorizationAttribute("service", "service2"));
    final Permission permReadUser1 = new Permission("org/zalando/nakadi", AuthorizationService.Operation.READ,
            new ResourceAuthorizationAttribute("user", "user1"));
    final Permission permReadService1 = new Permission("org/zalando/nakadi", AuthorizationService.Operation.READ,
            new ResourceAuthorizationAttribute("service", "service1"));
    final Permission permReadService2 = new Permission("org/zalando/nakadi", AuthorizationService.Operation.READ,
            new ResourceAuthorizationAttribute("service", "service2"));
    final Permission permWriteUser1 = new Permission("org/zalando/nakadi", AuthorizationService.Operation.WRITE,
            new ResourceAuthorizationAttribute("user", "user1"));
    final Permission permWriteService1 = new Permission("org/zalando/nakadi", AuthorizationService.Operation.WRITE,
            new ResourceAuthorizationAttribute("service", "service1"));
    final Permission permWriteService2 = new Permission("org/zalando/nakadi", AuthorizationService.Operation.WRITE,
            new ResourceAuthorizationAttribute("service", "service2"));
    final ResourceAuthorization newAuthz = new ResourceAuthorization(newAttrs, newAttrs, newAttrs);
    final AuthorizationAttribute defaultAdmin = new ResourceAuthorizationAttribute("service", "org/zalando/nakadi");
    private final AuthorizationDbRepository authorizationDbRepository;
    private final AdminService adminService;
    private final AuthorizationService authorizationService;
    private final NakadiSettings nakadiSettings;
    private final List<Permission> adminList;
    private final FeatureToggleService featureToggleService;

    public AdminServiceTest() {
        this.authorizationDbRepository = mock(AuthorizationDbRepository.class);
        this.authorizationService = mock(AuthorizationService.class);
        this.nakadiSettings = mock(NakadiSettings.class);
        this.featureToggleService = mock(FeatureToggleService.class);
        this.adminService = new AdminService(authorizationDbRepository, authorizationService,
                featureToggleService, nakadiSettings);
        this.adminList = new ArrayList<>(Arrays.asList(permAdminUser1, permAdminService1,
                permAdminService2, permReadUser1, permReadService1, permReadService2, permWriteUser1,
                permWriteService1, permWriteService2));
        this.defaultAdminPermissions = new ArrayList<>();
        for (final AuthorizationService.Operation operation : AuthorizationService.Operation.values()) {
            defaultAdminPermissions.add(new Permission("org/zalando/nakadi", operation, defaultAdmin));
        }
        doNothing().when(authorizationService).isAuthorizationForResourceValid(any());
        when(featureToggleService.isFeatureEnabled(Feature.DISABLE_DB_WRITE_OPERATIONS))
                .thenReturn(false);
    }

    @Test
    public void whenUpdateAdminsThenOk() {
        when(authorizationDbRepository.listAdmins()).thenReturn(adminList);
        adminService.updateAdmins(newAuthz.toPermissionsList("org/zalando/nakadi"));
    }

    @Test
    public void whenUpdateThenDefaultAdminIsNotAddedToDB() {
        when(nakadiSettings.getDefaultAdmin()).thenReturn(defaultAdmin);
        when(authorizationDbRepository.listAdmins()).thenReturn(adminList);

        final List<Permission> newList = new ArrayList<>(adminList);
        newList.addAll(defaultAdminPermissions);
        adminService.updateAdmins(newList);
        verify(authorizationDbRepository, times(0)).createPermission(any());
        verify(authorizationDbRepository, times(0)).deletePermission(any());
    }

    @Test
    public void whenUpdateThenDefaultAdminIsNotDeletedFromDB() {
        when(nakadiSettings.getDefaultAdmin()).thenReturn(defaultAdmin);
        when(authorizationDbRepository.listAdmins()).thenReturn(adminList);

        adminService.updateAdmins(adminList);
        verify(authorizationDbRepository, times(0)).createPermission(any());
        verify(authorizationDbRepository, times(0)).deletePermission(any());
    }

    @Test
    public void whenAddNewAdminCallCreatePermission() {
        when(nakadiSettings.getDefaultAdmin()).thenReturn(defaultAdmin);
        when(authorizationDbRepository.listAdmins()).thenReturn(adminList);
        doNothing().when(authorizationDbRepository).update(any(), any());

        final ArgumentCaptor<List> addCaptor = ArgumentCaptor.forClass(List.class);
        final ArgumentCaptor<List> deleteCaptor = ArgumentCaptor.forClass(List.class);

        final List<Permission> newList = new ArrayList<>(adminList);
        newList.add(new Permission("org/zalando/nakadi", AuthorizationService.Operation.READ,
                new ResourceAuthorizationAttribute("user", "user42")));

        adminService.updateAdmins(newList);

        verify(authorizationDbRepository).update(addCaptor.capture(), deleteCaptor.capture());
        assertEquals(1, addCaptor.getValue().size());
        assertEquals(0, deleteCaptor.getValue().size());
    }

    @Test
    public void whenDeleteAdminCallDeletePermission() {
        when(nakadiSettings.getDefaultAdmin()).thenReturn(defaultAdmin);
        when(authorizationDbRepository.listAdmins()).thenReturn(adminList);
        doNothing().when(authorizationDbRepository).update(any(), any());

        final ArgumentCaptor<List> addCaptor = ArgumentCaptor.forClass(List.class);
        final ArgumentCaptor<List> deleteCaptor = ArgumentCaptor.forClass(List.class);

        final List<Permission> newList = new ArrayList<>(adminList);
        newList.remove(permReadUser1);

        adminService.updateAdmins(newList);

        verify(authorizationDbRepository).update(addCaptor.capture(), deleteCaptor.capture());
        assertEquals(0, addCaptor.getValue().size());
        assertEquals(1, deleteCaptor.getValue().size());
    }
}

redpajama_set_name: RedPajamaGithub


text:
import { create } from '@storybook/theming/create';

export default create({
  base: 'light',

  /*colorPrimary: 'hotpink',
  colorSecondary: 'deepskyblue',

  // UI
  appBg: 'white',
  appContentBg: 'silver',
  appBorderColor: 'grey',
  appBorderRadius: 4,
*/
  // Typography
  fontBase: '"Open Sans", sans-serif',
  fontCode: 'monospace',

  // Text colors
  textColor: '#031c2d',
  headerCommon: { color: 'red' },
  brandUrl: null,
  /*textInverseColor: 'rgba(255,255,255,0.9)',

  // Toolbar default and active colors
  barTextColor: 'silver',
  barSelectedColor: 'black',
  barBg: 'hotpink',

  // Form colors
  inputBg: 'white',
  inputBorder: 'silver',
  inputTextColor: 'black',
  inputBorderRadius: 4,

  brandTitle: 'My custom storybook',
  brandUrl: 'https://example.com',
  brandImage: 'https://placehold.it/350x150',*/
});


text:
function [O] = TriOverlap(area)
%UNTITLED3 Summary of this function goes here
%   Detailed explanation goes here
O=[2,1,1;1,2,1;1,1,2]*area/24;
end


text:
<?php
/**
 * Created by PhpStorm.
 * User: KevinSup
 * Date: 01/02/2016
 * Time: 09:16
 */

namespace Joli\BlogBundle\Controller;

use Joli\BlogBundle\Entity\Post;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;

class ProposeController extends Controller
{
    /**
     * @Template("JoliBlogBundle:propose:propose.html.twig")
     */
    public function proposeAction(Request $request)
    {
        $message = "Veuillez remplir le formulaire pour poster un article";
        $post = new Post();
        $form = $this->createFormBuilder($post)
            ->add('title', 'text')
            ->add('body', 'text')
            ->add('slug', 'text')
            ->add('published', 'checkbox', array(
                'required' => false,
            ))
            ->add('save', 'submit', array('label' => 'Create post'))
            ->getForm();

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($post);
            $em->flush();
            $message = "L'article à été posté avec succès";
        } elseif ($form->isSubmitted() && !$form->isValid()) {
            $message = "Veuillez remplir le formulaire correctement";
        }
        return array(
            'form' => $form->createView(),
            'message' => $message
        );
    }
}


text:
package org.jpox.samples.valuegeneration;

import java.io.Serializable;

/**
 * Test case for the "max" generator.
 *
 * @version $Revision: 1.1 $
 */
public class MaxGeneratorItem
{
    private int identifier; // Generated field

    protected String name=null;

    protected MaxGeneratorItem()
    {
    }

    public MaxGeneratorItem(String name)
    {
        this.name   = name;
    }

    public int getIdentifier()
    {
        return identifier;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public String toString()
    {
        return "MaxPoidItem : " + name;
    }

    public static class Oid implements Serializable
    {
        public int identifier;

        public Oid()
        {
        }

        public Oid(String s)
        {
            this.identifier = Integer.valueOf(s).intValue();
        }

        public String toString()
        {
            return "" + identifier;
        }

        public int hashCode()
        {
            return identifier;
        }

        public boolean equals(Object other)
        {
            if (other != null && (other instanceof Oid))
            {
                Oid k = (Oid)other;
                return k.identifier == this.identifier;
            }
            return false;
        }
    }
}


text: Simple simulations for comparing error metrics between distributions


text:
__version__ = "0.9"

import Tkinter

# weight/slant
NORMAL = "normal"
ROMAN = "roman"
BOLD   = "bold"
ITALIC = "italic"

def nametofont(name):
    """Given the name of a tk named font, returns a Font representation.
    """
    return Font(name=name, exists=True)

class Font:

    """Represents a named font.

    Constructor options are:

    font -- font specifier (name, system font, or (family, size, style)-tuple)
    name -- name to use for this font configuration (defaults to a unique name)
    exists -- does a named font by this name already exist?
       Creates a new named font if False, points to the existing font if True.
       Raises _Tkinter.TclError if the assertion is false.

       the following are ignored if font is specified:

    family -- font 'family', e.g. Courier, Times, Helvetica
    size -- font size in points
    weight -- font thickness: NORMAL, BOLD
    slant -- font slant: ROMAN, ITALIC
    underline -- font underlining: false (0), true (1)
    overstrike -- font strikeout: false (0), true (1)

    """

    def _set(self, kw):
        options = []
        for k, v in kw.items():
            options.append("-"+k)
            options.append(str(v))
        return tuple(options)

    def _get(self, args):
        options = []
        for k in args:
            options.append("-"+k)
        return tuple(options)

    def _mkdict(self, args):
        options = {}
        for i in range(0, len(args), 2):
            options[args[i][1:]] = args[i+1]
        return options

    def __init__(self, root=None, font=None, name=None, exists=False, **options):
        if not root:
            root = Tkinter._default_root
        if font:
            # get actual settings corresponding to the given font
            font = root.tk.splitlist(root.tk.call("font", "actual", font))
        else:
            font = self._set(options)
        if not name:
            name = "font" + str(id(self))
        self.name = name

        if exists:
            self.delete_font = False
            # confirm font exists
            if self.name not in root.tk.call("font", "names"):
                raise Tkinter._tkinter.TclError, "named font %s does not already exist" % (self.name,)
            # if font config info supplied, apply it
            if font:
                root.tk.call("font", "configure", self.name, *font)
        else:
            # create new font (raises TclError if the font exists)
            root.tk.call("font", "create", self.name, *font)
            self.delete_font = True
        # backlinks!
        self._root  = root
        self._split = root.tk.splitlist
        self._call  = root.tk.call

    def __str__(self):
        return self.name

    def __eq__(self, other):
        return self.name == other.name and isinstance(other, Font)

    def __getitem__(self, key):
        return self.cget(key)

    def __setitem__(self, key, value):
        self.configure(**{key: value})

    def __del__(self):
        try:
            if self.delete_font:
                self._call("font", "delete", self.name)
        except (KeyboardInterrupt, SystemExit):
            raise
        except Exception:
            pass

    def copy(self):
        "Return a distinct copy of the current font"
        return Font(self._root, **self.actual())

    def actual(self, option=None):
        "Return actual font attributes"
        if option:
            return self._call("font", "actual", self.name, "-"+option)
        else:
            return self._mkdict(
                self._split(self._call("font", "actual", self.name))
                )

    def cget(self, option):
        "Get font attribute"
        return self._call("font", "config", self.name, "-"+option)

    def config(self, **options):
        "Modify font attributes"
        if options:
            self._call("font", "config", self.name,
                  *self._set(options))
        else:
            return self._mkdict(
                self._split(self._call("font", "config", self.name))
                )

    configure = config

    def measure(self, text):
        "Return text width"
        return int(self._call("font", "measure", self.name, text))

    def metrics(self, *options):
        """Return font metrics.

        For best performance, create a dummy widget
        using this font before calling this method."""

        if options:
            return int(
                self._call("font", "metrics", self.name, self._get(options))
                )
        else:
            res = self._split(self._call("font", "metrics", self.name))
            options = {}
            for i in range(0, len(res), 2):
                options[res[i][1:]] = int(res[i+1])
            return options

def families(root=None):
    "Get font families (as a tuple)"
    if not root:
        root = Tkinter._default_root
    return root.tk.splitlist(root.tk.call("font", "families"))

def names(root=None):
    "Get names of defined fonts (as a tuple)"
    if not root:
        root = Tkinter._default_root
    return root.tk.splitlist(root.tk.call("font", "names"))

# --------------------------------------------------------------------
# test stuff

if __name__ == "__main__":

    root = Tkinter.Tk()

    # create a font
    f = Font(family="times", size=30, weight=NORMAL)

    print f.actual()
    print f.actual("family")
    print f.actual("weight")

    print f.config()
    print f.cget("family")
    print f.cget("weight")

    print names()

    print f.measure("hello"), f.metrics("linespace")

    print f.metrics()

    f = Font(font=("Courier", 20, "bold"))
    print f.measure("hello"), f.metrics("linespace")

    w = Tkinter.Label(root, text="Hello, world", font=f)
    w.pack()

    w = Tkinter.Button(root, text="Quit!", command=root.destroy)
    w.pack()

    fb = Font(font=w["font"]).copy()
    fb.config(weight=BOLD)

    w.config(font=fb)

    Tkinter.mainloop()


text:
________________________

## MBEPickerController - Text Picker

A custom view component that presents a `UIPickerView` with a simple list of options,
along with a toolbar for Select/Cancel and an optional faded backdrop view.

## MBEPickerController - Date/Time/DateTime Picker

A custom view component that presents a `UIDatePicker` with a toolbar for Select/Cancel.

## Usage

Usage is easy:

Add the dependency to your `Podfile`:

```ruby
platform :ios
pod 'MBEPickerController'
...
```

Run `pod install` to install the dependencies.

Next, import the header file wherever you want to use the picker:

```objc
#import <MBEPickerController/MBEPickerController.h>
```

Finally, present the picker when necessary (say on a button touch handler):

```objc

- (IBAction)openPicker:(id)sender {
    if (!self.isBeingPresented || !self.isBeingDismissed) {

        // Create Custom Picker Instance
        MBEPickerController *pickerController = [[MBEPickerController alloc] initWithNibName:@"MBEPickerController" bundle:nil];

        // Account for iOS 8 & Under
        if ([UIDevice currentDevice].systemVersion.floatValue <= 7.1)
            self.modalPresentationStyle = UIModalPresentationCurrentContext;
        else
            pickerController.modalPresentationStyle = UIModalPresentationCustom;

        // Set Picker Title if present
        [pickerController setPickerTitle:@"Test Title"];

        // Set 'Yes' for Date Picker
        if (segControl.selectedSegmentIndex == 0)
            [pickerController setPickerTypeState:PickerTypeText];
        else if (segControl.selectedSegmentIndex == 1)
            [pickerController setPickerTypeState:PickerTypeDate];
        else if (segControl.selectedSegmentIndex == 2)
            [pickerController setPickerTypeState:PickerTypeTime];
        else
            [pickerController setPickerTypeState:PickerTypeDateTime];

        // Set Array Options
        [pickerController setPickerOptions:categories];

        // Set Picker Text if present
        [pickerController setText:@"Test 2"];

        // Set Picker Date if present
        [pickerController setDate:[NSDate date]];
        //[pickerController setDate:[NSDate dateWithTimeIntervalSince1970:[NSDate date].timeIntervalSince1970 - (86400 * 2)]];

        if (segControl.selectedSegmentIndex == 0) {
            // Block to return Text Selection
            pickerController.select =  ^(NSString *selection) {
                if (selection != nil) {
                    if (selection.length > 0) {
                        NSLog(@"text :: pos :: %i :: %@", 0, selection);
                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Selection" message:[NSString stringWithFormat:@"Selected: '%@'", selection] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                        [alert show];
                    }
                }
            };
        }
        else {
            // Block to return Date/Time Selection
            pickerController.selectDate =  ^(NSDate *selectedDate) {
                if (selectedDate != nil) {
                    if (selectedDate.description.length > 0) {
                        NSLog(@"date :: pos :: %i :: %@", 0, selectedDate.description);
                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Selection" message:[NSString stringWithFormat:@"Selected: '%@'", selectedDate.description] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                        [alert show];
                    }
                }
            };
        }

        // Present Custom Pickers
        [self presentViewController:pickerController animated:YES completion:nil];
    }
}
```


text:
<?php
namespace Procure\Domain\QuotationRequest;

use Application\Domain\Shared\AbstractDTO;
use Application\Domain\Shared\Assembler\GenericObjectAssembler;
use Procure\Domain\QuotationRequest\Definition\QrRowDefinition;

/**
 *
 * @author Nguyen Mau Tri - ngmautri@gmail.com
 *
 */
class QRRowSnapshotAssembler
{

    public static function updateAllFieldsFromArray(AbstractDTO $snapShot, $data)
    {
        return GenericObjectAssembler::updateAllFieldsFromArray($snapShot, $data);
    }

    public static function updateIncludedFieldsFromArray(AbstractDTO $snapShot, $data, $fields)
    {
        return GenericObjectAssembler::updateIncludedFieldsFromArray($snapShot, $data, $fields);
    }

    public static function updateDefaultIncludedFieldsFromArray(AbstractDTO $snapShot, $data)
    {
        return GenericObjectAssembler::updateIncludedFieldsFromArray($snapShot, $data, QrRowDefinition::$defaultIncludedFields);
    }

    public static function updateExcludedFieldsFromArray(AbstractDTO $snapShot, $data, $fields)
    {
        return GenericObjectAssembler::updateExcludedFieldsFromArray($snapShot, $data, $fields);
    }

    public static function updateDefaultExcludedFieldsFromArray(AbstractDTO $snapShot, $data)
    {
        return GenericObjectAssembler::updateIncludedFieldsFromArray($snapShot, $data, QrRowDefinition::$defaultExcludedFields);
    }

    // from Object
    // =============================
    public static function updateAllFieldsFrom(AbstractDTO $snapShot, $data)
    {
        return GenericObjectAssembler::updateAllFieldsFrom($snapShot, $data);
    }

    public static function updateIncludedFieldsFrom(AbstractDTO $snapShot, $data, $fields)
    {
        return GenericObjectAssembler::updateIncludedFieldsFromArray($snapShot, $data, $fields);
    }

    public static function updateDefaultFieldsFrom(AbstractDTO $snapShot, $data)
    {
        return GenericObjectAssembler::updateIncludedFieldsFrom($snapShot, $data, QrRowDefinition::$defaultIncludedFields);
    }

    public static function updateExcludedFieldsFrom(AbstractDTO $snapShot, $data, $fields)
    {
        return GenericObjectAssembler::updateExcludedFieldsFromArray($snapShot, $data, $fields);
    }

    public static function updateDefaultExcludedFieldsFrom(AbstractDTO $snapShot, $data)
    {
        return GenericObjectAssembler::updateExcludedFieldsFrom($snapShot, $data, QrRowDefinition::$defaultExcludedFields);
    }

    public static function createFromQueryHit($hit)
    {
        if ($hit == null) {
            return;
        }

        $snapshort = new QRRowSnapshot();
        $reflectionClass = new \ReflectionClass($snapshort);
        $itemProperites = $reflectionClass->getProperties();
        foreach ($itemProperites as $property) {
            $property->setAccessible(true);
            $propertyName = $property->getName();

            if ($hit->__isset($propertyName)) {
                $snapshort->$propertyName = $hit->$propertyName;
            }
        }

        $snapshort->id = $hit->rowId; // important
        if ($hit->__isset("itemId")) {
            $snapshort->item = $hit->itemId; // important
        }

        return $snapshort;
    }
}


text:
package com.reactnativenavigation.views;

import android.view.MotionEvent;

import com.reactnativenavigation.BaseTest;
import com.reactnativenavigation.mocks.SimpleOverlay;
import com.reactnativenavigation.parse.params.Bool;
import com.reactnativenavigation.views.touch.OverlayTouchDelegate;

import org.junit.Test;
import org.mockito.Mockito;

import static org.assertj.core.api.Java6Assertions.assertThat;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

public class TouchDelegateTest extends BaseTest {
    private OverlayTouchDelegate uut;
    private final int x = 10;
    private final int y = 10;
    private final MotionEvent downEvent = MotionEvent.obtain(0, 0, MotionEvent.ACTION_DOWN, x, y, 0);
    private final MotionEvent upEvent = MotionEvent.obtain(0, 0, MotionEvent.ACTION_UP, x, y, 0);
    private SimpleOverlay reactView;
    private ComponentLayout component;

    @Override
    public void beforeEach() {
        super.beforeEach();
        reactView = spy(new SimpleOverlay(newActivity()));
        component = Mockito.mock(ComponentLayout.class);
        uut = spy(new OverlayTouchDelegate(component, reactView));
    }

    @Test
    public void downEventIsHandled() {
        uut.setInterceptTouchOutside(new Bool(true));
        uut.onInterceptTouchEvent(downEvent);
        verify(uut, times(1)).handleDown(downEvent);
    }

    @Test
    public void onlyDownEventIsHandled() {
        uut.setInterceptTouchOutside(new Bool(true));
        uut.onInterceptTouchEvent(upEvent);
        verify(uut, times(0)).handleDown(upEvent);
    }

    @Test
    public void nonDownEventsDontIntercept() {
        uut.setInterceptTouchOutside(new Bool(true));
        assertThat(uut.onInterceptTouchEvent(upEvent)).isFalse();
    }

    @Test
    public void nonDownEventsInvokeSuperImplementation() {
        uut.setInterceptTouchOutside(new Bool(true));
        uut.onInterceptTouchEvent(upEvent);
        verify(component).superOnInterceptTouchEvent(upEvent);
    }
}


text:
'use strict';

goog.provide('tachyfont.Reporter');

goog.require('goog.log');
goog.require('goog.userAgent');
goog.require('tachyfont.Logger');

/**
 * Singleton reporter.
 *
 * @param {string} url The base URL to send reports to.
 * @constructor
 */
tachyfont.Reporter = function(url) {

  /** @private {string} */
  this.url_ = url;

  /** @private {!Object<string, (number|string)>} */
  this.items_ = {};
};

/**
 * TachyFont start time.
 *
 * This is as close to the user start time as possible. This is useful for
 * reporting how long after start time activities happened.
 *
 * @private {number} The milliseconds since midnight, January 1, 1970
 */
tachyfont.Reporter.startTime_ = goog.now();

/**
 * TachyFont singleton object.
 *
 * @private {tachyfont.Reporter}
 */
tachyfont.Reporter.instance_ = null;

/**
 * Indicated is the reporter has been intialized.
 * @return {boolean} Whether the reporter has been initialized.
 */
tachyfont.Reporter.isReady = function() {
  return tachyfont.Reporter.instance_ != null;
};

/**
 * Get the reporter instance.
 * @return {tachyfont.Reporter}
 */
tachyfont.Reporter.getInstance = function() {
  return tachyfont.Reporter.instance_;
};

/**
 * Set the reporter instance.
 * @param {tachyfont.Reporter} instance The reporter instance
 */
tachyfont.Reporter.setInstance = function(instance) {
  tachyfont.Reporter.instance_ = instance;
};

/**
 * Initialize the reporter singleton.
 * @param {string} url The base URL to send reports to.
 */
tachyfont.Reporter.initReporter = function(url) {
  if (tachyfont.Reporter.instance_ == null) {
    tachyfont.Reporter.instance_ = new tachyfont.Reporter(url);
  }
};

/**
 * Reset the reporter singleton.
 */
tachyfont.Reporter.reset = function() {
  tachyfont.Reporter.instance_ = null;
};

/**
 * Add the time an item happened.
 *
 * @param {string} name The name of the item.
 */
tachyfont.Reporter.addItemTime = function(name) {
  var deltaTime = goog.now() - tachyfont.Reporter.startTime_;
  tachyfont.Reporter.addItem(name, deltaTime);
};

/**
 * Add an item to report.
 *
 * @param {string} name The name of the item.
 * @param {string|number} value The value of the item.
 */
tachyfont.Reporter.addItem = function(name, value) {
  if (typeof value == 'number') {
    value = Math.round(value);
  }
  tachyfont.Reporter.instance_.items_[name] = value;
};

/**
 * Send an error report.
 *
 * @param {string} errNum The error number.
 * @param {string} id Identifying information.
 * @param {*} errInfo The error information.
 */
tachyfont.Reporter.reportError = function(errNum, id, errInfo) {
  // Move any pre-existing items aside.
  var preexistingItems = tachyfont.Reporter.instance_.items_;
  tachyfont.Reporter.instance_.items_ = {};
  var name = errNum + '.' + id;
  var msg = '';

  // Get the error message out of the error object.
  if (typeof errInfo == 'string') {
    msg += errInfo;
  } else if (typeof errInfo == 'object') {
    if (errInfo['message']) {
      msg += errInfo['message'];
    }
    if (errInfo['name']) {
      if (msg) {
        msg += ', ';
      }
      msg += errInfo['name'] + ', ';
    }
    if (errInfo['url']) {
      if (msg) {
        msg += ', ';
      }
      msg += errInfo['url'] + ', ';
    }
    if (errInfo['lineNumber']) {
      if (msg) {
        msg += ', ';
      }
      msg += errInfo['lineNumber'] + ', ';
    }
  }
  tachyfont.Reporter.addItem(name, msg);
  if (goog.DEBUG) {
    var keys = Object.keys(tachyfont.Reporter.instance_.items_);
    keys.sort();
    for (var i = 0; i < keys.length; i++) {
      name = keys[i];
      goog.log.error(tachyfont.Logger.logger, '    ' + name + ': ' +
          tachyfont.Reporter.instance_.items_[name]);
    }
    // debugger; // Enable this when debugging the reporter.
  }
  tachyfont.Reporter.sendReport();

  // Restore any pre-existing items.
  tachyfont.Reporter.instance_.items_ = preexistingItems;

};

/**
 * Send the report.
 *
 * @param {boolean=} opt_okIfNoItems Do not complain if not items.
 */
tachyfont.Reporter.sendReport = function(opt_okIfNoItems) {
  var keys = Object.keys(tachyfont.Reporter.instance_.items_);
  keys.sort();
  if (keys.length == 0) {
    if (goog.DEBUG) {
      if (!opt_okIfNoItems) {
        goog.log.warning(tachyfont.Logger.logger, 'sendReport: no items');
      }
    }
    return;
  }

  var baseUrl = tachyfont.Reporter.instance_.url_ + '/gen_204?id=tf&';
  var length = baseUrl.length;
  var items = [];
  var item = 'm=' + (goog.userAgent.MOBILE ? '1' : '0');
  length += item.length;
  items.push(item);
  if (goog.DEBUG) {
    goog.log.info(tachyfont.Logger.logger, 'report items:');
  }
  for (var i = 0; i < keys.length; i++) {
    var name = keys[i];
    var value = encodeURIComponent(
        (tachyfont.Reporter.instance_.items_[name]).toString());
    delete tachyfont.Reporter.instance_.items_[name];
    item = encodeURIComponent(name) + '=' + value;
    if (length + item.length > 2000) {
      tachyfont.Reporter.sendGen204_(baseUrl, items);
      length = baseUrl.length;
      items = [];
    }
    length += item.length;
    items.push(item);
    if (goog.DEBUG) {
      goog.log.info(tachyfont.Logger.logger, '    ' + item);
    }
  }
  tachyfont.Reporter.sendGen204_(baseUrl, items);
};

/**
 * Send the gen_204.
 *
 * @param {string} baseUrl The url to send the GET to.
 * @param {Array<string>} params The URL parameters.
 * @private
 */
tachyfont.Reporter.sendGen204_ = function(baseUrl, params) {
  var reportUrl = baseUrl + params.join('&');
  var image = new Image();
  image.onload = image.onerror = tachyfont.Reporter.cleanUpFunc_(image);
  image.src = reportUrl;
};

/**
 * Clear references off the Image so it can be garbage collected.
 * @private
 * @param {!Image} image The image to clean up.
 * @return {!function()} Function that cleans up the image.
 */
tachyfont.Reporter.cleanUpFunc_ = function(image) {
  return function() {
    image.onload = image.onerror = null;
  };
};


text:
import { checkUpdate } from "../CheckUpdate";

describe("CheckUpdates", () => {
  it("should compare semvers", async () => {
    jest.mock("node-fetch", async () => {
      const release = {
        name: "v1.4.0",
      };
      return {
        json: () => Promise.resolve(release),
      };
    });

    const hasNewUpdate = await checkUpdate();
    expect(hasNewUpdate).toBe(true);
  });
});


text:
// Electron shell bootstrap script

"use strict";

var app = require('app');  // Module to control application life.
var BrowserWindow = require('browser-window');  // Module to create native browser window.
var ipc = require('electron').ipcMain;
var dialog = require('dialog');
var fs = require('fs');

// Report crashes to our server.
// const crashReporter = require('electron').crashReporter;
// crashReporter.start({
//   productName: 'Nubomedia Graph Editor',
//   companyName: 'Nubomedia Consortium',
//   submitURL: 'https://your-domain.com/url-to-submit',
//   autoSubmit: true
// });

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is GCed.
var mainWindow = null;

// Quit when all windows are closed.
app.on('window-all-closed', function() {
    app.quit();
});

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', function() {
  // Create the browser window.
  mainWindow = new BrowserWindow({minWidth: 400, minHeight: 400, icon: __dirname + '/images/nubomedia-logo.png'});

  // and load the index.html of the app.
  mainWindow.loadURL('file://' + __dirname + '/index.html');

  // -------------------
  // Custom commands
  // -------------------
  ipc.on('selectOpenProject', function(event, arg) {
    console.log('selectOpenProject: ', arg);
    var paths = dialog.showOpenDialog(mainWindow, {
      title:"Open Project",
      filters: [{ name: 'Project files', extensions: ['ngeprj'] },
                { name: 'All Files', extensions: ['*'] }],
      defaultPath: ".",
      properties: ['openFile']
    });
    event.returnValue = paths?paths[0]:null; // Protect from 'undefined' causing Electron error
  });

  ipc.on('selectSaveProject', function(event, arg) {
    console.log('selectSaveProject: ', arg);
    var path = dialog.showSaveDialog(mainWindow, {
      title:"Save Project as...",
      defaultPath: "./" + arg.replace(/ /g,"_") + ".ngeprj",
      filters: [{ name: 'Project files', extensions: ['ngeprj'] },
                { name: 'All Files', extensions: ['*'] }]
    });
    event.returnValue = path?path:null; // Protect from 'undefined' causing Electron error
  });

  ipc.on('readJSONFile', function(event, arg) {
    console.log('readJSONFile: ', arg);
    try {
      let v = fs.readFileSync(arg, "utf8");
      console.log("read: ", v);
      let d = JSON.parse(v);
      event.returnValue = d || {};
    } catch (e) {
      console.log('ERROR: ', e);
      event.returnValue = null;
    }
  });

  ipc.on('writeJSONFile', function(event, arg) {
    console.log('writeJSONFile: ', arg);
    try {
      fs.writeFileSync(arg.filename, JSON.stringify(arg.obj));
      event.returnValue = true;
    } catch (e) {
      console.log('ERROR: ', e);
      event.returnValue = false;
    }
  });

  // Open the devtools.
  //mainWindow.openDevTools();

  // Emitted when the window is closed.
  mainWindow.on('closed', function() {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null;
  });
});


text:
/**
 * Created by Kristof on 16/10/2015.
 */

describe("Objectstore - Count", function () {

    it("Counting data - Count all", function (done) {
        var expect = 1, ct = 0;
        var key = 1;

        initionalSituationObjectStoreWithKeyPathAndMultipleDataNoAutoIncrement(function () {
            var request = indexedDB.open(dbName);
            request.onsuccess = function(e){
                try{
                    var transaction = e.target.result.transaction([objectStoreName], "readwrite");
                    var objectstore = transaction.objectStore(objectStoreName);

                    try{
                        var countRequest = objectstore.count();
                        countRequest.onsuccess = function (e){
                            assert.equal(e.target.result, 10, "Count");
                            ct++;
                        };
                        countRequest.onerror = function (e){
                            assert.ok(false, "Count error");
                        };
                    }
                    catch (ex){
                        assert.ok(false, "Count error");
                    }

                    transaction.oncomplete = function (e){
                        equal(ct, expect, "Expected test count");
                        e.target.db.close();
                        done();
                    };
                    transaction.onabort = function (err){
                        assert.equal(err.error.name, "AbortError", "AbortError");
                        e.target.result.close();
                        done();
                    };
                    transaction.onerror = function (){
                        assert.ok(false, "Transaction error");
                        e.target.result.close();
                        done();
                    };
                }
                catch (ex) {
                    assert.ok(false, "Transaction error");
                    e.target.result.close();
                    done();
                }
            };
            request.onerror = function(){
                assert.ok(false, "Database error");
                done();
            };
        }, done, assert);
    });
    it("Counting data - key range lowerBound exclusieve", function (done) {
        var expect = 1, ct = 0;

        initionalSituationObjectStoreWithKeyPathAndMultipleDataNoAutoIncrement(function () {
            var request = indexedDB.open(dbName);
            request.onsuccess = function(e){
                try{
                    var transaction = e.target.result.transaction([objectStoreName], "readwrite");
                    var objectstore = transaction.objectStore(objectStoreName);

                    try{
                        var countRequest = objectstore.count(KeyRange.lowerBound(5, true));
                        countRequest.onsuccess = function (e){
                            assert.deepEqual(e.target.result, 5, "Count");
                            ct++;
                        };
                        countRequest.onerror = function (e){
                            assert.ok(false, "Count error");
                        };
                    }
                    catch (ex){
                        assert.ok(false, "Count error");
                    }

                    transaction.oncomplete = function (e){
                        equal(ct, expect, "Expected test count");
                        e.target.db.close();
                        done();
                    };
                    transaction.onabort = function (err){
                        assert.equal(err.error.name, "AbortError", "AbortError");
                        e.target.result.close();
                        done();
                    };
                    transaction.onerror = function (){
                        assert.ok(false, "Transaction error");
                        e.target.result.close();
                        done();
                    };
                }
                catch (ex) {
                    assert.ok(false, "Transaction error");
                    e.target.result.close();
                    done();
                }
            };
            request.onerror = function(){
                assert.ok(false, "Database error");
                done();
            };
        }, done, assert);
    });
    it("Counting data - key range lowerBound inclusieve", function (done) {
        var expect = 1, ct = 0;

        initionalSituationObjectStoreWithKeyPathAndMultipleDataNoAutoIncrement(function () {
            var request = indexedDB.open(dbName);
            request.onsuccess = function(e){
                try{
                    var transaction = e.target.result.transaction([objectStoreName], "readwrite");
                    var objectstore = transaction.objectStore(objectStoreName);

                    try{
                        var countRequest = objectstore.count(KeyRange.lowerBound(5));
                        countRequest.onsuccess = function (e){
                            assert.deepEqual(e.target.result, 6, "Count");
                            ct++;
                        };
                        countRequest.onerror = function (e){
                            assert.ok(false, "Count error");
                        };
                    }
                    catch (ex){
                        assert.ok(false, "Count error");
                    }

                    transaction.oncomplete = function (e){
                        equal(ct, expect, "Expected test count");
                        e.target.db.close();
                        done();
                    };
                    transaction.onabort = function (err){
                        assert.equal(err.error.name, "AbortError", "AbortError");
                        e.target.result.close();
                        done();
                    };
                    transaction.onerror = function (){
                        assert.ok(false, "Transaction error");
                        e.target.result.close();
                        done();
                    };
                }
                catch (ex) {
                    assert.ok(false, "Transaction error");
                    e.target.result.close();
                    done();
                }
            };
            request.onerror = function(){
                assert.ok(false, "Database error");
                done();
            };
        }, done, assert);
    });
    it("Counting data - key range upperBound exclusieve", function (done) {
        var expect = 1, ct = 0;

        initionalSituationObjectStoreWithKeyPathAndMultipleDataNoAutoIncrement(function () {
            var request = indexedDB.open(dbName);
            request.onsuccess = function(e){
                try{
                    var transaction = e.target.result.transaction([objectStoreName], "readwrite");
                    var objectstore = transaction.objectStore(objectStoreName);

                    try{
                        var countRequest = objectstore.count(KeyRange.upperBound(5, true));
                        countRequest.onsuccess = function (e){
                            assert.deepEqual(e.target.result, 4, "Count");
                            ct++;
                        };
                        countRequest.onerror = function (e){
                            assert.ok(false, "Count error");
                        };
                    }
                    catch (ex){
                        assert.ok(false, "Count error");
                    }

                    transaction.oncomplete = function (e){
                        equal(ct, expect, "Expected test count");
                        e.target.db.close();
                        done();
                    };
                    transaction.onabort = function (err){
                        assert.equal(err.error.name, "AbortError", "AbortError");
                        e.target.result.close();
                        done();
                    };
                    transaction.onerror = function (){
                        assert.ok(false, "Transaction error");
                        e.target.result.close();
                        done();
                    };
                }
                catch (ex) {
                    assert.ok(false, "Transaction error");
                    e.target.result.close();
                    done();
                }
            };
            request.onerror = function(){
                assert.ok(false, "Database error");
                done();
            };
        }, done, assert);
    });
    it("Counting data - key range upperBound inclusieve", function (done) {
        var expect = 1, ct = 0;

        initionalSituationObjectStoreWithKeyPathAndMultipleDataNoAutoIncrement(function () {
            var request = indexedDB.open(dbName);
            request.onsuccess = function(e){
                try{
                    var transaction = e.target.result.transaction([objectStoreName], "readwrite");
                    var objectstore = transaction.objectStore(objectStoreName);

                    try{
                        var countRequest = objectstore.count(KeyRange.upperBound(5, false));
                        countRequest.onsuccess = function (e){
                            assert.deepEqual(e.target.result, 5, "Count");
                            ct++;
                        };
                        countRequest.onerror = function (e){
                            assert.ok(false, "Count error");
                        };
                    }
                    catch (ex){
                        assert.ok(false, "Count error");
                    }

                    transaction.oncomplete = function (e){
                        equal(ct, expect, "Expected test count");
                        e.target.db.close();
                        done();
                    };
                    transaction.onabort = function (err){
                        assert.equal(err.error.name, "AbortError", "AbortError");
                        e.target.result.close();
                        done();
                    };
                    transaction.onerror = function (){
                        assert.ok(false, "Transaction error");
                        e.target.result.close();
                        done();
                    };
                }
                catch (ex) {
                    assert.ok(false, "Transaction error");
                    e.target.result.close();
                    done();
                }
            };
            request.onerror = function(){
                assert.ok(false, "Database error");
                done();
            };
        }, done, assert);
    });
    it("Counting data - key range only", function (done) {
        var expect = 1, ct = 0;

        initionalSituationObjectStoreWithKeyPathAndMultipleDataNoAutoIncrement(function () {
            var request = indexedDB.open(dbName);
            request.onsuccess = function(e){
                try{
                    var transaction = e.target.result.transaction([objectStoreName], "readwrite");
                    var objectstore = transaction.objectStore(objectStoreName);

                    try{
                        var countRequest = objectstore.count(KeyRange.only(1));
                        countRequest.onsuccess = function (e){
                            assert.deepEqual(e.target.result, 1, "Count");
                            ct++;
                        };
                        countRequest.onerror = function (e){
                            assert.ok(false, "Count error");
                        };
                    }
                    catch (ex){
                        assert.ok(false, "Count error");
                    }

                    transaction.oncomplete = function (e){
                        equal(ct, expect, "Expected test count");
                        e.target.db.close();
                        done();
                    };
                    transaction.onabort = function (err){
                        assert.equal(err.error.name, "AbortError", "AbortError");
                        e.target.result.close();
                        done();
                    };
                    transaction.onerror = function (){
                        assert.ok(false, "Transaction error");
                        e.target.result.close();
                        done();
                    };
                }
                catch (ex) {
                    assert.ok(false, "Transaction error");
                    e.target.result.close();
                    done();
                }
            };
            request.onerror = function(){
                assert.ok(false, "Database error");
                done();
            };
        }, done, assert);
    });
    it("Counting data - key range between", function (done) {
        var expect = 1, ct = 0;

        initionalSituationObjectStoreWithKeyPathAndMultipleDataNoAutoIncrement(function () {
            var request = indexedDB.open(dbName);
            request.onsuccess = function(e){
                try{
                    var transaction = e.target.result.transaction([objectStoreName], "readwrite");
                    var objectstore = transaction.objectStore(objectStoreName);

                    try{
                        var countRequest = objectstore.count(KeyRange.bound(1,5, false, false));
                        countRequest.onsuccess = function (e){
                            assert.deepEqual(e.target.result, 5, "Count");
                            ct++;
                        };
                        countRequest.onerror = function (e){
                            assert.ok(false, "Count error");
                        };
                    }
                    catch (ex){
                        assert.ok(false, "Count error");
                    }

                    transaction.oncomplete = function (e){
                        equal(ct, expect, "Expected test count");
                        e.target.db.close();
                        done();
                    };
                    transaction.onabort = function (err){
                        assert.equal(err.error.name, "AbortError", "AbortError");
                        e.target.result.close();
                        done();
                    };
                    transaction.onerror = function (){
                        assert.ok(false, "Transaction error");
                        e.target.result.close();
                        done();
                    };
                }
                catch (ex) {
                    assert.ok(false, "Transaction error");
                    e.target.result.close();
                    done();
                }
            };
            request.onerror = function(){
                assert.ok(false, "Database error");
                done();
            };
        }, done, assert);
    });
    it("Counting data - non key range", function (done) {
        var expect = 1, ct = 0;
        var key = 1;

        initionalSituationObjectStoreWithKeyPathAndMultipleDataNoAutoIncrement(function () {
            var request = indexedDB.open(dbName);
            request.onsuccess = function(e){
                try{
                    var transaction = e.target.result.transaction([objectStoreName], "readwrite");
                    var objectstore = transaction.objectStore(objectStoreName);

                    try{
                        var countRequest = objectstore.count(2);
                        countRequest.onsuccess = function (e){
                            assert.equal(e.target.result, 1, "Count");
                            ct++;
                        };
                        countRequest.onerror = function (e){
                            assert.ok(false, "Count error");
                        };
                    }
                    catch (ex){
                        assert.ok(false, "Count error");
                    }

                    transaction.oncomplete = function (e){
                        equal(ct, expect, "Expected test count");
                        e.target.db.close();
                        done();
                    };
                    transaction.onabort = function (err){
                        assert.equal(err.error.name, "AbortError", "AbortError");
                        e.target.result.close();
                        done();
                    };
                    transaction.onerror = function (){
                        assert.ok(false, "Transaction error");
                        e.target.result.close();
                        done();
                    };
                }
                catch (ex) {
                    assert.ok(false, "Transaction error");
                    e.target.result.close();
                    done();
                }
            };
            request.onerror = function(){
                assert.ok(false, "Database error");
                done();
            };
        }, done, assert);
    });
    it("Retrieving data - key invalid", function (done) {
        var expect = 1, ct = 0;
        var key = 1;

        initionalSituationObjectStoreNoAutoIncrement(function () {
            var request = indexedDB.open(dbName);
            request.onsuccess = function(e){
                try{
                    var transaction = e.target.result.transaction([objectStoreName], "readwrite");
                    var objectstore = transaction.objectStore(objectStoreName);

                    try{
                        var countRequest = objectstore.count(function(){});
                        countRequest.onsuccess = function (e){
                            assert.ok(false, "Data counted");
                        };
                        countRequest.onerror = function (e){
                            assert.ok(false, "Count error");
                        };
                    }
                    catch (ex){
                        assert.equal(ex.name, "DataError", ex.name);
                        ct++;
                    }

                    transaction.oncomplete = function (e){
                        equal(ct, expect, "Expected test count");
                        e.target.db.close();
                        done();
                    };
                    transaction.onabort = function (err){
                        assert.equal(err.error.name, "AbortError", "AbortError");
                        e.target.result.close();
                        done();
                    };
                    transaction.onerror = function (){
                        assert.ok(false, "Transaction error");
                        e.target.result.close();
                        done();
                    };
                }
                catch (ex) {
                    assert.ok(false, "Transaction error");
                    e.target.result.close();
                    done();
                }
            };
            request.onerror = function(){
                assert.ok(false, "Database error");
                done();
            };
        }, done, assert);
    });
});