text:
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Spectrum.Net.Core.Session
{
    public class CommunityRole
    {
        [JsonProperty("id")]
        public UInt64 Id { get; set; }

        [JsonProperty("name")]
        public String Name { get; set; }

        // community_id
        // type
        // order
        // visible
        // description
        // color
        // permissions
        // members_count
    }
}


text:
import re
from bisect import bisect

from django.conf import settings
from django.db.models.related import RelatedObject
from django.db.models.fields.related import ManyToManyRel
from django.db.models.fields import (AutoField, SharedAutoField,
                                     FieldDoesNotExist)
from django.core.exceptions import FieldError
from django.db.models.fields.proxy import OrderWrt
from django.db.models.loading import get_models, app_cache_ready
from django.utils.translation import activate, deactivate_all, get_language, string_concat
from django.utils.encoding import force_unicode, smart_str, int32hash
from django.utils.datastructures import SortedDict

# Calculate the verbose_name by converting from InitialCaps to "lowercase with spaces".
get_verbose_name = lambda class_name: re.sub('(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))', ' \\1', class_name).lower().strip()

DEFAULT_NAMES = ('verbose_name', 'verbose_name_plural', 'db_table', 'ordering',
                'unique_together', 'permissions', 'get_latest_by',
                'order_with_respect_to', 'app_label', 'db_tablespace',
                'abstract', 'managed', 'proxy', 'auto_created',
                'db_view', 'materialized_view', 'db_view_sql', 'concrete')

class Options(object):
    def __init__(self, meta, app_label=None):
        self.local_fields, self.local_many_to_many = [], []
        self.virtual_fields = []
        self.module_name, self.verbose_name = None, None
        self.verbose_name_plural = None
        self.db_table = ''
        self.ordering = []
        self.unique_together =  []
        self.permissions =  []
        self.object_name, self.app_label = None, app_label
        self.get_latest_by = None
        self.order_with_respect_to = None
        self.db_tablespace = settings.DEFAULT_TABLESPACE
        self.admin = None
        self.meta = meta
        self.pk = None
        self.has_auto_field, self.auto_field = False, None
        self.abstract = False
        self.managed = True
        self.proxy = False
        # For any class that is a proxy (including automatically created
        # classes for deferred object loading), proxy_for_model tells us
        # which class this model is proxying. Note that proxy_for_model
        # can create a chain of proxy models. For non-proxy models, the
        # variable is always None.
        self.proxy_for_model = None
        # For any non-abstract class, the concrete class is the model
        # in the end of the proxy_for_model chain. In particular, for
        # concrete models, the concrete_model is always the class itself.
        self.concrete_model = None
        self.parents = SortedDict()
        self.duplicate_targets = {}
        self.auto_created = False
        # is it a materialized_view base model
        self.materialized_view = False
        # is it a view
        self.db_view = False
        self.db_view_sql = None
        # is it an intermediate view in a materialized based inheritance tree
        self.intermediate = False
        # is it a concrete intermediate view (instantiable and creates a db
        # table)
        self.concrete = True
        self.leaf = False

        # To handle various inheritance situations, we need to track where
        # managers came from (concrete or abstract base classes).
        self.abstract_managers = []
        self.concrete_managers = []

        # List of all lookups defined in ForeignKey 'limit_choices_to' options
        # from *other* models. Needed for some admin checks. Internal use only.
        self.related_fkey_lookups = []

    def contribute_to_class(self, cls, name):
        from django.db import connection
        from django.db.backends.util import truncate_name

        cls._meta = self
        self.installed = re.sub('\.models$', '', cls.__module__) in settings.INSTALLED_APPS
        # First, construct the default values for these options.
        self.object_name = cls.__name__
        self.module_name = self.object_name.lower()
        self.verbose_name = get_verbose_name(self.object_name)

        # Next, apply any overridden values from 'class Meta'.
        if self.meta:
            meta_attrs = self.meta.__dict__.copy()
            for name in self.meta.__dict__:
                # Ignore any private attributes that Django doesn't care about.
                # NOTE: We can't modify a dictionary's contents while looping
                # over it, so we loop over the *original* dictionary instead.
                if name.startswith('_'):
                    del meta_attrs[name]
            for attr_name in DEFAULT_NAMES:
                if attr_name in meta_attrs:
                    setattr(self, attr_name, meta_attrs.pop(attr_name))
                elif hasattr(self.meta, attr_name):
                    setattr(self, attr_name, getattr(self.meta, attr_name))

            # unique_together can be either a tuple of tuples, or a single
            # tuple of two strings. Normalize it to a tuple of tuples, so that
            # calling code can uniformly expect that.
            ut = meta_attrs.pop('unique_together', self.unique_together)
            if ut and not isinstance(ut[0], (tuple, list)):
                ut = (ut,)
            self.unique_together = ut

            # verbose_name_plural is a special case because it uses a 's'
            # by default.
            if self.verbose_name_plural is None:
                self.verbose_name_plural = string_concat(self.verbose_name, 's')

            # Any leftover attributes must be invalid.
            if meta_attrs != {}:
                raise TypeError("'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs.keys()))
        else:
            self.verbose_name_plural = string_concat(self.verbose_name, 's')
        del self.meta

        # If the db_table wasn't provided, use the app_label + module_name.
        if not self.db_table:
            # remember that the db_table was set automatically
            self._auto_db_table = True
            self.db_table = "%s_%s" % (self.app_label, self.module_name)
            self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
        else:
            self._auto_db_table = False

    @property
    def concrete_table_name(self):
        table_name = self.db_table
        if self.intermediate:
            if self._auto_db_table:
                table_name = table_name[:-5]
            else:
                table_name += '_concrete'
        return table_name

    def _prepare(self, model):
        if self.order_with_respect_to:
            self.order_with_respect_to = self.get_field(self.order_with_respect_to)
            self.ordering = ('_order',)
            model.add_to_class('_order', OrderWrt())
        else:
            self.order_with_respect_to = None

        if self.leaf:
            self.leaf_id = int32hash('%s%s%s' % (
                self.proxy and self.app_label or '',
                self.proxy and self.object_name or '',
                self.db_table))

        if self.pk is not None:
            if self.materialized_view and not isinstance(self.pk,
                                                         SharedAutoField):
                raise FieldError('Materialized views primary key must be '\
                                'a django.db.models.field.SharedAutoField. '\
                                'Why don\'t you let django create `id` for '\
                                'you?')

            if self.leaf:
                if not isinstance(self.pk, SharedAutoField):
                    raise FieldError('Primary key must be '\
                                'a django.db.models.field.SharedAutoField. '\
                                'Why don\'t you just inherit the primary '\
                                'key from the parent materialized view?')
                vpk = self.mat_view_base.pk
                if ((self.pk.column != vpk.column) or
                    (self.pk.sequence != vpk.sequence)):
                    raise FieldError('Primary key must have the same '\
                                'column name and the same sequence as '\
                                'model\'s parent materialized view.'
                                'Why don\'t you just inherit the primary '\
                                'key from the parent materialized view?')

        else:
            if self.materialized_view:
                # the sequence name is set latter in ModelBase.__new__
                auto = SharedAutoField(verbose_name='ID', primary_key=True,
                        auto_created=True)
                model.add_to_class('id', auto)
                auto.acquired = True

            elif self.leaf:
                # create the same SharedAutoField as the mat. view
                vpk = self.mat_view_base._meta.pk
                auto = SharedAutoField(verbose_name=vpk.verbose_name,
                                       sequence = vpk.sequence,
                                       db_column = vpk.column,
                                       primary_key=True,
                                       auto_created=True)
                auto.acquired = True
                model.add_to_class(vpk.name, auto)

            elif self.parents:
                # Promote the first parent link in lieu of adding yet another
                # field.
                field = self.parents.value_for_index(0)
                # Look for a local field with the same name as the
                # first parent link. If a local field has already been
                # created, use it instead of promoting the parent
                already_created = [fld for fld in self.local_fields if fld.name == field.name]
                if already_created:
                    field = already_created[0]
                field.primary_key = True
                self.setup_pk(field)
            else:
                auto = AutoField(verbose_name='ID', primary_key=True,
                        auto_created=True)
                model.add_to_class('id', auto)

        # Determine any sets of fields that are pointing to the same targets
        # (e.g. two ForeignKeys to the same remote model). The query
        # construction code needs to know this. At the end of this,
        # self.duplicate_targets will map each duplicate field column to the
        # columns it duplicates.
        collections = {}
        for column, target in self.duplicate_targets.iteritems():
            try:
                collections[target].add(column)
            except KeyError:
                collections[target] = set([column])
        self.duplicate_targets = {}
        for elt in collections.itervalues():
            if len(elt) == 1:
                continue
            for column in elt:
                self.duplicate_targets[column] = elt.difference(set([column]))

    def register_leaf(self,leaf):
        if not self.materialized_view:
            # TODO PG: exception?
            return

        if leaf._meta.leaf_id in self.leaf_ids:
            # is there a collision in django.utils.int32hash?
            old_class = self.leaf_ids[leaf._meta.leaf_id]
            if old_class != leaf:
                class MurffyError(Exception):
                    pass
                # TODO PG: add a full how to get rid of this incredible bad
                # luck (1 out of 4 294 967 296)
                raise MurffyError('%s and %s models hashes collide. Please '\
                                    'define a random int32 in one of thoses '\
                                    'classes Meta.leaf_id.' % (old_class, leaf))
        else:
            self.leaf_ids[leaf._meta.leaf_id] = leaf
            self.leaves[leaf] = leaf._meta.leaf_id
            for base in leaf.__mro__:
                if hasattr(base,'_meta') and base._meta.intermediate:
                    # add the leaf to intermediate views
                    base._meta.leaf_ids[leaf._meta.leaf_id] = leaf
                    base._meta.leaves[leaf] = leaf._meta.leaf_id
                    if base in self.leaves and not base._meta.concrete:
                        # remove the view from leaves
                        del self.leaves[base._meta.concrete_model]
                        del self.leaf_ids[base._meta.leaf_id]

    def add_field(self, field):
        # Insert the given field in the order in which it was created, using
        # the "creation_counter" attribute of the field.
        # Move many-to-many related fields from self.fields into
        # self.many_to_many.
        if field.rel and isinstance(field.rel, ManyToManyRel):
            self.local_many_to_many.insert(bisect(self.local_many_to_many, field), field)
            if hasattr(self, '_m2m_cache'):
                del self._m2m_cache
        else:
            self.local_fields.insert(bisect(self.local_fields, field), field)
            self.setup_pk(field)
            if hasattr(self, '_field_cache'):
                del self._field_cache
                del self._field_name_cache

        if hasattr(self, '_name_map'):
            del self._name_map

    def add_virtual_field(self, field):
        self.virtual_fields.append(field)

    def setup_pk(self, field):
        if not self.pk and field.primary_key:
            self.pk = field
            field.serialize = False

    def setup_proxy(self, target):
        """
        Does the internal setup so that the current model is a proxy for
        "target".
        """
        self.pk = target._meta.pk
        self.proxy_for_model = target
        self.db_table = target._meta.db_table

    def __repr__(self):
        return '<Options for %s>' % self.object_name

    def __str__(self):
        return "%s.%s" % (smart_str(self.app_label), smart_str(self.module_name))

    def verbose_name_raw(self):
        """
        There are a few places where the untranslated verbose name is needed
        (so that we get the same value regardless of currently active
        locale).
        """
        lang = get_language()
        deactivate_all()
        raw = force_unicode(self.verbose_name)
        activate(lang)
        return raw
    verbose_name_raw = property(verbose_name_raw)

    def _fields(self):
        """
        The getter for self.fields. This returns the list of field objects
        available to this model (including through parent models).

        Callers are not permitted to modify this list, since it's a reference
        to this instance (not a copy).
        """
        try:
            self._field_name_cache
        except AttributeError:
            self._fill_fields_cache()
        return self._field_name_cache
    fields = property(_fields)

    def get_fields_with_model(self):
        """
        Returns a sequence of (field, model) pairs for all fields. The "model"
        element is None for fields on the current model. Mostly of use when
        constructing queries so that we know which model a field belongs to.
        """
        try:
            self._field_cache
        except AttributeError:
            self._fill_fields_cache()
        return self._field_cache

    def _fill_fields_cache(self):
        cache = []
        for parent in self.parents:
            for field, model in parent._meta.get_fields_with_model():
                if model:
                    cache.append((field, model))
                else:
                    cache.append((field, parent))
        cache.extend([(f, None) for f in self.local_fields])
        self._field_cache = tuple(cache)
        self._field_name_cache = [x for x, _ in cache]

    def _many_to_many(self):
        try:
            self._m2m_cache
        except AttributeError:
            self._fill_m2m_cache()
        return self._m2m_cache.keys()
    many_to_many = property(_many_to_many)

    def get_m2m_with_model(self):
        """
        The many-to-many version of get_fields_with_model().
        """
        try:
            self._m2m_cache
        except AttributeError:
            self._fill_m2m_cache()
        return self._m2m_cache.items()

    def _fill_m2m_cache(self):
        cache = SortedDict()
        for parent in self.parents:
            for field, model in parent._meta.get_m2m_with_model():
                if model:
                    cache[field] = model
                else:
                    cache[field] = parent
        for field in self.local_many_to_many:
            cache[field] = None
        self._m2m_cache = cache

    def get_field(self, name, many_to_many=True):
        """
        Returns the requested field by name. Raises FieldDoesNotExist on error.
        """
        to_search = many_to_many and (self.fields + self.many_to_many) or self.fields
        for f in to_search:
            if f.name == name:
                return f
        raise FieldDoesNotExist('%s has no field named %r' % (self.object_name, name))

    def get_field_by_name(self, name):
        """
        Returns the (field_object, model, direct, m2m), where field_object is
        the Field instance for the given name, model is the model containing
        this field (None for local fields), direct is True if the field exists
        on this model, and m2m is True for many-to-many relations. When
        'direct' is False, 'field_object' is the corresponding RelatedObject
        for this field (since the field doesn't have an instance associated
        with it).

        Uses a cache internally, so after the first access, this is very fast.
        """
        try:
            try:
                return self._name_map[name]
            except AttributeError:
                cache = self.init_name_map()
                return cache[name]
        except KeyError:
            raise FieldDoesNotExist('%s has no field named %r'
                    % (self.object_name, name))

    def get_all_field_names(self):
        """
        Returns a list of all field names that are possible for this model
        (including reverse relation names). This is used for pretty printing
        debugging output (a list of choices), so any internal-only field names
        are not included.
        """
        try:
            cache = self._name_map
        except AttributeError:
            cache = self.init_name_map()
        names = cache.keys()
        names.sort()
        # Internal-only names end with "+" (symmetrical m2m related names being
        # the main example). Trim them.
        return [val for val in names if not val.endswith('+')]

    def init_name_map(self):
        """
        Initialises the field name -> field object mapping.
        """
        cache = {}
        # We intentionally handle related m2m objects first so that symmetrical
        # m2m accessor names can be overridden, if necessary.
        for f, model in self.get_all_related_m2m_objects_with_model():
            cache[f.field.related_query_name()] = (f, model, False, True)
        for f, model in self.get_all_related_objects_with_model():
            cache[f.field.related_query_name()] = (f, model, False, False)
        for f, model in self.get_m2m_with_model():
            cache[f.name] = (f, model, True, True)
        for f, model in self.get_fields_with_model():
            cache[f.name] = (f, model, True, False)
        if app_cache_ready():
            self._name_map = cache
        return cache

    def get_add_permission(self):
        return 'add_%s' % self.object_name.lower()

    def get_change_permission(self):
        return 'change_%s' % self.object_name.lower()

    def get_delete_permission(self):
        return 'delete_%s' % self.object_name.lower()

    def get_all_related_objects(self, local_only=False, include_hidden=False,
                                include_proxy_eq=False):
        return [k for k, v in self.get_all_related_objects_with_model(
                local_only=local_only, include_hidden=include_hidden,
                include_proxy_eq=include_proxy_eq)]

    def get_all_related_objects_with_model(self, local_only=False,
                                           include_hidden=False,
                                           include_proxy_eq=False):
        """
        Returns a list of (related-object, model) pairs. Similar to
        get_fields_with_model().
        """
        try:
            self._related_objects_cache
        except AttributeError:
            self._fill_related_objects_cache()
        predicates = []
        if local_only:
            predicates.append(lambda k, v: not v)
        if not include_hidden:
            predicates.append(lambda k, v: not k.field.rel.is_hidden())
        cache = (self._related_objects_proxy_cache if include_proxy_eq
                 else self._related_objects_cache)
        return filter(lambda t: all([p(*t) for p in predicates]), cache.items())

    def _fill_related_objects_cache(self):
        cache = SortedDict()
        parent_list = self.get_parent_list()
        for parent in self.parents:
            for obj, model in parent._meta.get_all_related_objects_with_model(include_hidden=True):
                if (obj.field.creation_counter < 0 or obj.field.rel.parent_link) and obj.model not in parent_list:
                    continue
                if not model:
                    cache[obj] = parent
                else:
                    cache[obj] = model
        # Collect also objects which are in relation to some proxy child/parent of self.
        proxy_cache = cache.copy()
        for klass in get_models(include_auto_created=True, only_installed=False):
            for f in klass._meta.local_fields:
                if f.rel and not isinstance(f.rel.to, basestring):
                    if self == f.rel.to._meta:
                        cache[RelatedObject(f.rel.to, klass, f)] = None
                        proxy_cache[RelatedObject(f.rel.to, klass, f)] = None
                    elif self.concrete_model == f.rel.to._meta.concrete_model:
                        proxy_cache[RelatedObject(f.rel.to, klass, f)] = None
        self._related_objects_cache = cache
        self._related_objects_proxy_cache = proxy_cache

    def get_all_related_many_to_many_objects(self, local_only=False):
        try:
            cache = self._related_many_to_many_cache
        except AttributeError:
            cache = self._fill_related_many_to_many_cache()
        if local_only:
            return [k for k, v in cache.items() if not v]
        return cache.keys()

    def get_all_related_m2m_objects_with_model(self):
        """
        Returns a list of (related-m2m-object, model) pairs. Similar to
        get_fields_with_model().
        """
        try:
            cache = self._related_many_to_many_cache
        except AttributeError:
            cache = self._fill_related_many_to_many_cache()
        return cache.items()

    def _fill_related_many_to_many_cache(self):
        cache = SortedDict()
        parent_list = self.get_parent_list()
        for parent in self.parents:
            for obj, model in parent._meta.get_all_related_m2m_objects_with_model():
                if obj.field.creation_counter < 0 and obj.model not in parent_list:
                    continue
                if not model:
                    cache[obj] = parent
                else:
                    cache[obj] = model
        for klass in get_models(only_installed=False):
            for f in klass._meta.local_many_to_many:
                if f.rel and not isinstance(f.rel.to, basestring) and self == f.rel.to._meta:
                    cache[RelatedObject(f.rel.to, klass, f)] = None
        if app_cache_ready():
            self._related_many_to_many_cache = cache
        return cache

    def get_base_chain(self, model):
        """
        Returns a list of parent classes leading to 'model' (order from closet
        to most distant ancestor). This has to handle the case were 'model' is
        a granparent or even more distant relation.
        """
        if not self.parents:
            return
        if model in self.parents:
            return [model]
        for parent in self.parents:
            res = parent._meta.get_base_chain(model)
            if res:
                res.insert(0, parent)
                return res
        raise TypeError('%r is not an ancestor of this model'
                % model._meta.module_name)

    def get_parent_list(self):
        """
        Returns a list of all the ancestor of this model as a list. Useful for
        determining if something is an ancestor, regardless of lineage.
        """
        result = set()
        for parent in self.parents:
            result.add(parent)
            result.update(parent._meta.get_parent_list())
        return result

    def get_ancestor_link(self, ancestor):
        """
        Returns the field on the current model which points to the given
        "ancestor". This is possible an indirect link (a pointer to a parent
        model, which points, eventually, to the ancestor). Used when
        constructing table joins for model inheritance.

        Returns None if the model isn't an ancestor of this one.
        """
        if ancestor in self.parents:
            return self.parents[ancestor]
        for parent in self.parents:
            # Tries to get a link field from the immediate parent
            parent_link = parent._meta.get_ancestor_link(ancestor)
            if parent_link:
                # In case of a proxied model, the first link
                # of the chain to the ancestor is that parent
                # links
                return self.parents[parent] or parent_link

    def get_ordered_objects(self):
        "Returns a list of Options objects that are ordered with respect to this object."
        if not hasattr(self, '_ordered_objects'):
            objects = []
            # TODO
            #for klass in get_models(get_app(self.app_label)):
            #    opts = klass._meta
            #    if opts.order_with_respect_to and opts.order_with_respect_to.rel \
            #        and self == opts.order_with_respect_to.rel.to._meta:
            #        objects.append(opts)
            self._ordered_objects = objects
        return self._ordered_objects

    def pk_index(self):
        """
        Returns the index of the primary key field in the self.fields list.
        """
        return self.fields.index(self.pk)

redpajama_set_name: RedPajamaGithub


text:
//====================================================================
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
//====================================================================
public class RoadStart : FSMSingleton<RoadStart>, IFSMState<RoadFSM>
{
    //--------------------------------------
    public void Enter(RoadFSM caller)
	{
        System.GC.Collect();

        caller._isOver = false;

        if (caller._gameFsm != null && caller._gameFsm._playerFSM._eCurModeIn == PlayerFSM.ePLAYERIN.GAME)
            caller._uiCtrlInGame._panelGame._bulletCooltime.gameObject.SetActive(false);

        caller._curScrollSpeed = 0.0f;

        if(caller._gameFsm != null)
        {
            caller._uiCtrlInGame._panelGame._coin.text = caller._gameFsm._coin.ToString();
            caller._gameFsm._actMovingDist = 0f;
        }

        caller._targetScrollSpeed = GlobalData.Instance.GetCarInfo()._speed;

        GlobalData.Instance._eIngameMode = GlobalData.eINGAMEMODE.READY;

    }// public void Enter(RoadFSM caller)
     //--------------------------------------
    public void Execute(RoadFSM caller)
	{
		caller._curScrollSpeed += Time.deltaTime * caller._targetScrollSpeed * 0.2f;

		if (caller._targetScrollSpeed <= caller._curScrollSpeed)
			caller.ChangeState (RoadIdle.Instance);

	}//	public void Execute(RoadFSM caller)
	//--------------------------------------
	public void Exit(RoadFSM caller)	{ }
	//--------------------------------------
	public void Skip(RoadFSM caller)	{ }
	//--------------------------------------

}//	public class RoadStart : FSMSingleton<RoadStart>, IFSMState<RoadFSM>
//====================================================================


text:
layout: post
title:  "Breakfast at the Whitechapel Mission"
date:   2017-01-14 08:10:00
author: Sean
categories: Charity
tags: charity
cover:  "/assets/Whitechapel_station_East_London_roundel.jpg"
---

Many people find January to be a cold, dark month after all the fun of Christmas
but for London's homeless and marginalised it can be a particularly hard time of
year.

As the temperature drops volunteer services such as the [Whitechapel
Mission](https://whitechapel.org.uk/) provide vital help to many who would have
no where else to turn. Something as simple as a hot meal can make all the
difference to how someone views their day.

Baggy, Mike and Bill have been putting in time to help out with Mission's
breakfast duties serving over 300 people.

![Bill, Baggy and Mike](/assets/knights_at_the_white_chappel_mission.jpeg)

What does that entail?  Well for starters it means getting to the Mission in the
middle of the night and cooking over 600 fried eggs and, in particular,
providing tea with 5 sugars to one toothless but beaming chap.  All this and
then heading of to the day job.

Well done guys, you're doing us all proud ...and the shirts are looking pretty good
too.

If you'd like to help us help the Whitechapel Mission please sponsor us via [our
Whitechapel Mission Just Giving
page](https://www.justgiving.com/crowdfunding/companyofcyclingknights).


text:
from aiven.client.argx import UserError
from enum import Enum
from typing import Callable

import os

class ConnectionInfoError(UserError):
    def __init__(self, message: str) -> None:
        super().__init__()
        self.message = message

    def __str__(self) -> str:
        return self.message

class Store(Enum):
    overwrite = object()
    write = object()
    skip = object()

    def handle(self, getter: Callable[[], str], path: str) -> None:
        if self is Store.overwrite:
            write = True
        elif self is Store.write:
            write = not os.path.exists(path)
        elif self is Store.skip:
            write = False
        else:
            raise NotImplementedError

        if write:
            value = getter()
            with open(path, "w", encoding="utf-8") as fob:
                fob.write(value)


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Controls.WpfPropertyGrid.Attributes;
using Hawk.Core.Connectors;
using Hawk.Core.Utils.Logs;
using Hawk.Core.Utils.Plugins;
using Hawk.ETL.Interfaces;

namespace Hawk.ETL.Plugins.Generators
{
     [XFrmWork("从文本生成","每行一条数据" )]
    public class TextGE : GeneratorBase
    {
         List<string> argsList=new List<string>();

         [LocalizedDisplayName("文本")]
         [LocalizedDescription("每行一条")]
         [PropertyOrder(2)]
         [PropertyEditor("CodeEditor")]
         public string Content { get; set; }

         public TextGE()
         {
             Column = "text";
         }

         public override bool Init(IEnumerable<IFreeDocument> datas)
         {
             if (string.IsNullOrEmpty(Content))
                 return base.Init(datas);

             try
             {
                 argsList =  Content.Split( new []{"\r\n"},StringSplitOptions.None).ToList();

             }
             catch (Exception ex)
             {
                 XLogSys.Print.Error(ex.Message);

             }
             return base.Init(datas);
         }
         public override IEnumerable<FreeDocument> Generate(IFreeDocument document = null)
         {
             return argsList.Select(doc => new FreeDocument {{this.Column, doc}});
         }
    }
}


text:
{-# htermination elemIndices :: Char -> [Char] -> [Int] #-}
import List


text:
#ifndef UNIVERSAL_CHARDET_MOZILLA_ARRAYUTILS_H
#define UNIVERSAL_CHARDET_MOZILLA_ARRAYUTILS_H

namespace mozilla{
	inline size_t ArrayLength(const int16_t x[])
	{
		return (sizeof(x) / sizeof(x[0]));
	}
}

#endif


text:
require 'spec_helper'

describe TablePrint::Printable do
  before(:each) do
    Sandbox.cleanup!
  end

  describe "#default_display_methods" do
    it "returns attribute getters" do
      Sandbox.add_class("Hat")
      Sandbox.add_attributes("Hat", "brand")

      p = Sandbox::Hat.new
      TablePrint::Printable.default_display_methods(p).should == %W(brand)
    end

    it "ignores dangerous methods" do
      Sandbox.add_class("Hat")
      Sandbox.add_method("Hat", "brand!") {}

      p = Sandbox::Hat.new
      TablePrint::Printable.default_display_methods(p).should == []
    end

    it "ignores methods defined in a superclass" do
      Sandbox.add_class("Hat::Bowler")
      Sandbox.add_attributes("Hat", "brand")
      Sandbox.add_attributes("Hat::Bowler", "brim_width")

      p = Sandbox::Hat::Bowler.new
      TablePrint::Printable.default_display_methods(p).should == %W(brim_width)
    end

    it "ignores methods that require arguments" do
      Sandbox.add_class("Hat")
      Sandbox.add_attributes("Hat", "brand")
      Sandbox.add_method("Hat", "tip?") { |person| person.rapscallion? }

      p = Sandbox::Hat.new
      TablePrint::Printable.default_display_methods(p).should == %W(brand)
    end

    it "ignores methods from an included module" do
      pending "waiting for Cat to support module manipulation"
    end

    it "uses column information when available (eg, from ActiveRecord objects)"

    it "uses the members method when passed a Struct" do
      test_struct = Struct.new(:foo, :bar)
      obj = test_struct.new
      obj.foo = 1
      obj.bar = 2
      TablePrint::Printable.default_display_methods(obj).should == [:foo, :bar]
    end

  end

end


text:
namespace ExampleApp.Forms.Tables
{
    partial class BaseTable
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(BaseTable));
            this.ribbonStatusBar = new DevExpress.XtraBars.Ribbon.RibbonStatusBar();
            this.ribbon = new DevExpress.XtraBars.Ribbon.RibbonControl();
            this.applicationMenu1 = new DevExpress.XtraBars.Ribbon.ApplicationMenu(this.components);
            this.btnAdd = new DevExpress.XtraBars.BarButtonItem();
            this.btnEdit = new DevExpress.XtraBars.BarButtonItem();
            this.btnDelete = new DevExpress.XtraBars.BarButtonItem();
            this.btnRefresh = new DevExpress.XtraBars.BarButtonItem();
            this.ribbonPage1 = new DevExpress.XtraBars.Ribbon.RibbonPage();
            this.ribbonPageGroup1 = new DevExpress.XtraBars.Ribbon.RibbonPageGroup();
            this.gridControl = new DevExpress.XtraGrid.GridControl();
            this.gridView = new DevExpress.XtraGrid.Views.Grid.GridView();
            ((System.ComponentModel.ISupportInitialize)(this.ribbon)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.applicationMenu1)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.gridControl)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.gridView)).BeginInit();
            this.SuspendLayout();
            //
            // ribbonStatusBar
            //
            this.ribbonStatusBar.Location = new System.Drawing.Point(0, 578);
            this.ribbonStatusBar.Name = "ribbonStatusBar";
            this.ribbonStatusBar.Ribbon = this.ribbon;
            this.ribbonStatusBar.Size = new System.Drawing.Size(952, 31);
            //
            // ribbon
            //
            this.ribbon.ApplicationButtonDropDownControl = this.applicationMenu1;
            this.ribbon.ExpandCollapseItem.Id = 0;
            this.ribbon.Items.AddRange(new DevExpress.XtraBars.BarItem[] {
            this.ribbon.ExpandCollapseItem,
            this.btnAdd,
            this.btnEdit,
            this.btnDelete,
            this.btnRefresh});
            this.ribbon.Location = new System.Drawing.Point(0, 0);
            this.ribbon.MaxItemId = 1;
            this.ribbon.Name = "ribbon";
            this.ribbon.Pages.AddRange(new DevExpress.XtraBars.Ribbon.RibbonPage[] {
            this.ribbonPage1});
            this.ribbon.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonControlStyle.Office2010;
            this.ribbon.ShowApplicationButton = DevExpress.Utils.DefaultBoolean.False;
            this.ribbon.ShowExpandCollapseButton = DevExpress.Utils.DefaultBoolean.False;
            this.ribbon.ShowFullScreenButton = DevExpress.Utils.DefaultBoolean.False;
            this.ribbon.ShowPageHeadersMode = DevExpress.XtraBars.Ribbon.ShowPageHeadersMode.Hide;
            this.ribbon.ShowToolbarCustomizeItem = false;
            this.ribbon.Size = new System.Drawing.Size(952, 122);
            this.ribbon.StatusBar = this.ribbonStatusBar;
            this.ribbon.Toolbar.ShowCustomizeItem = false;
            //
            // applicationMenu1
            //
            this.applicationMenu1.ItemLinks.Add(this.btnAdd);
            this.applicationMenu1.ItemLinks.Add(this.btnEdit);
            this.applicationMenu1.ItemLinks.Add(this.btnDelete);
            this.applicationMenu1.ItemLinks.Add(this.btnRefresh);
            this.applicationMenu1.Name = "applicationMenu1";
            this.applicationMenu1.Ribbon = this.ribbon;
            //
            // btnAdd
            //
            this.btnAdd.Caption = "Добавить";
            this.btnAdd.Glyph = ((System.Drawing.Image)(resources.GetObject("btnAdd.Glyph")));
            this.btnAdd.Id = 1;
            this.btnAdd.LargeGlyph = ((System.Drawing.Image)(resources.GetObject("btnAdd.LargeGlyph")));
            this.btnAdd.Name = "btnAdd";
            this.btnAdd.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.Large;
            this.btnAdd.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.btnAdd_ItemClick);
            //
            // btnEdit
            //
            this.btnEdit.Caption = "Редактировать";
            this.btnEdit.Glyph = ((System.Drawing.Image)(resources.GetObject("btnEdit.Glyph")));
            this.btnEdit.Id = 2;
            this.btnEdit.LargeGlyph = ((System.Drawing.Image)(resources.GetObject("btnEdit.LargeGlyph")));
            this.btnEdit.Name = "btnEdit";
            this.btnEdit.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.Large;
            this.btnEdit.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.btnEdit_ItemClick);
            //
            // btnDelete
            //
            this.btnDelete.Caption = "Удалить";
            this.btnDelete.Glyph = ((System.Drawing.Image)(resources.GetObject("btnDelete.Glyph")));
            this.btnDelete.Id = 3;
            this.btnDelete.LargeGlyph = ((System.Drawing.Image)(resources.GetObject("btnDelete.LargeGlyph")));
            this.btnDelete.Name = "btnDelete";
            this.btnDelete.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.Large;
            this.btnDelete.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.btnDelete_ItemClick);
            //
            // btnRefresh
            //
            this.btnRefresh.Caption = "Обновить";
            this.btnRefresh.Glyph = ((System.Drawing.Image)(resources.GetObject("btnRefresh.Glyph")));
            this.btnRefresh.Id = 4;
            this.btnRefresh.LargeGlyph = ((System.Drawing.Image)(resources.GetObject("btnRefresh.LargeGlyph")));
            this.btnRefresh.Name = "btnRefresh";
            this.btnRefresh.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.Large;
            this.btnRefresh.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.btnRefresh_ItemClick);
            //
            // ribbonPage1
            //
            this.ribbonPage1.Groups.AddRange(new DevExpress.XtraBars.Ribbon.RibbonPageGroup[] {
            this.ribbonPageGroup1});
            this.ribbonPage1.Name = "ribbonPage1";
            this.ribbonPage1.Text = " ";
            //
            // ribbonPageGroup1
            //
            this.ribbonPageGroup1.ItemLinks.Add(this.btnAdd);
            this.ribbonPageGroup1.ItemLinks.Add(this.btnEdit);
            this.ribbonPageGroup1.ItemLinks.Add(this.btnDelete);
            this.ribbonPageGroup1.ItemLinks.Add(this.btnRefresh);
            this.ribbonPageGroup1.Name = "ribbonPageGroup1";
            this.ribbonPageGroup1.Text = "...";
            //
            // gridControl
            //
            this.gridControl.Dock = System.Windows.Forms.DockStyle.Fill;
            this.gridControl.Location = new System.Drawing.Point(0, 122);
            this.gridControl.MainView = this.gridView;
            this.gridControl.MenuManager = this.ribbon;
            this.gridControl.Name = "gridControl";
            this.gridControl.Size = new System.Drawing.Size(952, 456);
            this.gridControl.TabIndex = 4;
            this.gridControl.ViewCollection.AddRange(new DevExpress.XtraGrid.Views.Base.BaseView[] {
            this.gridView});
            this.gridControl.DoubleClick += new System.EventHandler(this.gridControl_DoubleClick);
            //
            // gridView
            //
            this.gridView.GridControl = this.gridControl;
            this.gridView.Name = "gridView";
            this.gridView.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.False;
            this.gridView.OptionsBehavior.AllowDeleteRows = DevExpress.Utils.DefaultBoolean.False;
            this.gridView.OptionsBehavior.Editable = false;
            this.gridView.OptionsBehavior.ReadOnly = true;
            this.gridView.OptionsView.ShowGroupExpandCollapseButtons = false;
            this.gridView.OptionsView.ShowGroupPanel = false;
            this.gridView.OptionsView.ShowIndicator = false;
            //
            // BaseTable
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(952, 609);
            this.Controls.Add(this.gridControl);
            this.Controls.Add(this.ribbonStatusBar);
            this.Controls.Add(this.ribbon);
            this.Name = "BaseTable";
            this.Ribbon = this.ribbon;
            this.RibbonVisibility = DevExpress.XtraBars.Ribbon.RibbonVisibility.Visible;
            this.ShowIcon = false;
            this.ShowInTaskbar = false;
            this.StatusBar = this.ribbonStatusBar;
            this.Text = "BaseTable";
            ((System.ComponentModel.ISupportInitialize)(this.ribbon)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.applicationMenu1)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.gridControl)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.gridView)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion
        private DevExpress.XtraBars.Ribbon.RibbonStatusBar ribbonStatusBar;
        private DevExpress.XtraBars.Ribbon.RibbonControl ribbon;
        private DevExpress.XtraBars.BarButtonItem btnAdd;
        private DevExpress.XtraBars.BarButtonItem btnEdit;
        private DevExpress.XtraBars.BarButtonItem btnDelete;
        private DevExpress.XtraBars.BarButtonItem btnRefresh;
        private DevExpress.XtraBars.Ribbon.RibbonPage ribbonPage1;
        private DevExpress.XtraBars.Ribbon.RibbonPageGroup ribbonPageGroup1;
        private DevExpress.XtraBars.Ribbon.ApplicationMenu applicationMenu1;
        protected DevExpress.XtraGrid.GridControl gridControl;
        protected DevExpress.XtraGrid.Views.Grid.GridView gridView;
        //private DevExpress.XtraBars.Ribbon.BackstageViewControl backstageViewControl1;
        //private DevExpress.XtraBars.Ribbon.BackstageViewClientControl backstageViewClientControl1;
        //private DevExpress.XtraBars.Ribbon.BackstageViewTabItem backstageViewTabItem1;
    }
}


text:
from .helper import Pagination

class MongoDBAccess():
    def __init__(self, model):
        self._model = model

    def get_by_id(self, value):
        for model_object in self._model.objects(id=value):
            return model_object
        raise ValueError('{} with id "{}" does not exist.'.format(
            self._model.__name__, value))

    def get_all(self, *args, **kwargs):
        return self.query(*args, **kwargs)

    def add_or_update(self, model_object):
        return model_object.save()

    def query(self, offset=0, limit=None, order_by=None, exclude_fields=None,
              Qcombination=None, **filters):
        order_by = order_by or []
        exclude_fields = exclude_fields or []
        eop = offset + int(limit) if limit else None

        if Qcombination:
            result = self._model.objects.filter(Qcombination)
        else:
            result = self._model.objects.filter(**filters)

        if exclude_fields:
            result = result.exclude(*exclude_fields)

        result = result.order_by(*order_by)
        result = result[offset:eop]

        return result

    def delete(self, model_object):
        model_object.delete()

    def paginate(self, page=1, pagesize=9, Qcomb=None, **filters):
        pagesize = 9 if not pagesize else pagesize
        offset = (page - 1) * pagesize
        result = self.query(offset=offset, limit=pagesize, Qcombination=Qcomb,
                            **filters)
        return Pagination(result, page, pagesize, result.count())


text:
HTML-Blog-Page
==============

Sample & Simple Blog Page;

Mobile friendly;

[DEMO](http://ldimitrov.github.io/HTML-Blog-Page/ "HTML-Blog-Page")


text:
package com.dsi.authorization.dao;

import com.dsi.authorization.exception.CustomException;
import com.dsi.authorization.model.UserSession;
import org.hibernate.Session;

/**
 * Created by sabbir on 6/15/16.
 */
public interface UserSessionDao {

    void setSession(Session session);
    void saveUserSession(UserSession userSession) throws CustomException;
    void updateUserSession(UserSession userSession) throws CustomException;
    void deleteUserSession(UserSession userSession) throws CustomException;
    UserSession getUserSessionByUserIdAndAccessToken(String userID, String accessToken);
}


text:
namespace TAUtil.Tnt
{
    using System.IO;

    internal struct TntHeader
    {
        public const uint TntMagicNumber = 0x2000;
        public const int HeaderLength = 0x40;

        /// <summary>
        /// This is a version/file type marker of some kind.
        /// It is always 0x2000 in valid TNT files.
        /// </summary>
        public uint IdVersion;

        /// <summary>
        /// The width of the map in 16-pixel units as used for feature/height information.
        /// To get the width in 32-pixel units (the size of a tile), divide by 2.
        /// </summary>
        public uint Width;

        /// <summary>
        /// The height of the map in 16-pixel units as used for feature/height information.
        /// To get the height in 32-pixel units (the size of a tile), divide by 2.
        /// </summary>
        public uint Height;

        /// <summary>
        /// Offset from the beginning of the file to the tile indices array.
        /// This array contains unsigned shorts
        /// that are the indices in the tile array
        /// of the 32x32 pixel tile to be displayed at that point.
        /// </summary>
        public uint PtrMapData;

        /// <summary>
        /// <para>
        /// Offset from the beginning of the file to the map attributes array.
        /// This array holds the height and feature information
        /// for every 16x16 pixel square on the map.
        /// </para>
        /// <para>
        /// NB: There are 4 of these squares for each square
        /// in the tile indices array.
        /// </para>
        /// </summary>
        public uint PtrMapAttr;

        /// <summary>
        /// This is the array of tiles referenced by the tile indices array.
        /// One tile consists of unsigned char[32*32].
        /// </summary>
        public uint PtrTileGfx;

        /// <summary>
        /// The length of the array of tiles, i.e. the number of tiles.
        /// </summary>
        public uint Tiles;

        /// <summary>
        /// The length of the array of tile animations (features).
        /// i.e. the number of features.
        /// </summary>
        public uint TileAnims;

        /// <summary>
        /// <para>
        /// This is the array of features referenced by the feature indices array.
        /// Each entry is 0x84 bytes long and consists of an unsigned long
        /// that always seems to equal the index of the feature in this array
        /// and a 128-character null-terminated string
        /// that contains the name of the feature to be placed in the location
        /// as found between the square brackets "[]" in a TDF feature file.
        /// </para>
        /// <para>
        /// NB: The index seems to be totally useless.
        /// I have noticed that while Cavedog maps include them,
        /// Annihilator doesn't even bother to include them.
        /// </para>
        /// </summary>
        public uint PtrTileAnims;

        /// <summary>
        /// Any value in the heights array less than this value
        /// is deemed to be "under water"
        /// (i.e. water modifiers and effects apply).
        /// </summary>
        public uint SeaLevel;

        /// <summary>
        /// Obviously enough, this is where the minimap image is found.
        /// At the offset, the first things you find are 2 unsigned long's:
        /// the minimap's width and height (which always seem to be 252).
        /// What follows is width*height of pixel data.
        /// The difficult part about minimaps
        /// is that they are padded by 0xDD's
        /// (the standard blue used as transparent in TA).
        /// </summary>
        public uint PtrMiniMap;

        /// <summary>
        /// No-one knows what this is used for.
        /// It may have to do with multiple-of-4 or power-of-2 sizes.
        /// </summary>
        public uint Unknown1;

        /// <summary>
        /// No-one knows what this is used for.
        /// It may have to do with multiple-of-4 or power-of-2 sizes.
        /// </summary>
        public uint Pad1;

        /// <summary>
        /// No-one knows what this is used for.
        /// It may have to do with multiple-of-4 or power-of-2 sizes.
        /// </summary>
        public uint Pad2;

        /// <summary>
        /// No-one knows what this is used for.
        /// It may have to do with multiple-of-4 or power-of-2 sizes.
        /// </summary>
        public uint Pad3;

        /// <summary>
        /// No-one knows what this is used for.
        /// It may have to do with multiple-of-4 or power-of-2 sizes.
        /// </summary>
        public uint Pad4;

        public static void Read(Stream file, ref TntHeader header)
        {
            Read(new BinaryReader(file), ref header);
        }

        public static void Read(BinaryReader b, ref TntHeader header)
        {
            uint version = b.ReadUInt32();
            if (version != TntHeader.TntMagicNumber)
            {
                throw new ParseException("Input does not appear to be a valid TNT file");
            }

            header.IdVersion = version;

            header.Width = b.ReadUInt32();
            header.Height = b.ReadUInt32();
            header.PtrMapData = b.ReadUInt32();
            header.PtrMapAttr = b.ReadUInt32();
            header.PtrTileGfx = b.ReadUInt32();
            header.Tiles = b.ReadUInt32();
            header.TileAnims = b.ReadUInt32();
            header.PtrTileAnims = b.ReadUInt32();
            header.SeaLevel = b.ReadUInt32();
            header.PtrMiniMap = b.ReadUInt32();
            header.Unknown1 = b.ReadUInt32();
            header.Pad1 = b.ReadUInt32();
            header.Pad2 = b.ReadUInt32();
            header.Pad3 = b.ReadUInt32();
            header.Pad4 = b.ReadUInt32();
        }

        public void Write(BinaryWriter b)
        {
            b.Write(this.IdVersion);
            b.Write(this.Width);
            b.Write(this.Height);
            b.Write(this.PtrMapData);
            b.Write(this.PtrMapAttr);
            b.Write(this.PtrTileGfx);
            b.Write(this.Tiles);
            b.Write(this.TileAnims);
            b.Write(this.PtrTileAnims);
            b.Write(this.SeaLevel);
            b.Write(this.PtrMiniMap);
            b.Write(this.Unknown1);
            b.Write(this.Pad1);
            b.Write(this.Pad2);
            b.Write(this.Pad3);
            b.Write(this.Pad4);
        }
    }
}


text:
"use strict";

var

// required modules
express = require('express'),
consolidate = require('consolidate'),

// exstatic configuration object
conf = {
    cachePath: __dirname + '/static_cache',
    version: 'v1',
    compress: true //could be based on NODE_ENV or a force compression flag
},

// normally, require('exstatic')
exstatic = require('../../lib/AssetManager'),

// get the exstatic static asset manager
staticAssets = exstatic(conf),

// get an express application
app = express();

// register the static asset handler
staticAssets.createAssetsFromDirectory(
    '/static/:version/:dirname/:basename.:cacheId.css', // the path pattern to use
    '../stylus/assets' // a string or an array of folders of assets to be served
);

staticAssets.createAssetsFromDirectory(
    '/static/:version/:dirname/:basename.:cacheId:extname', // the path pattern to use
    [
        '../js/assets',
        '../png/assets'
    ]
);

// gzip the output
app.use(express.compress());

// use the exstatic middleware
app.use(staticAssets.middleware);

// start the server
app.listen(8080);


text:
<?php
/* SVN FILE: $Id: cache.test.php 7805 2008-10-30 17:30:26Z AD7six $ */
/**
 * Short description for file.
 *
 * Long description for file
 *
 * PHP versions 4 and 5
 *
 * CakePHP(tm) Tests <https://trac.cakephp.org/wiki/Developement/TestSuite>
 * Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
 *
 *  Licensed under The Open Group Test Suite License
 *  Redistributions of files must retain the above copyright notice.
 *
 * @filesource
 * @copyright     Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
 * @link          https://trac.cakephp.org/wiki/Developement/TestSuite CakePHP(tm) Tests
 * @package       cake.tests
 * @subpackage    cake.tests.cases.libs
 * @since         CakePHP(tm) v 1.2.0.5432
 * @version       $Revision: 7805 $
 * @modifiedby    $LastChangedBy: AD7six $
 * @lastmodified  $Date: 2008-10-30 12:30:26 -0500 (Thu, 30 Oct 2008) $
 * @license       http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
 */
if (!class_exists('Cache')) {
	require LIBS . 'cache.php';
}
/**
 * Short description for class.
 *
 * @package       cake.tests
 * @subpackage    cake.tests.cases.libs
 */
class CacheTest extends CakeTestCase {
/**
 * setUp method
 *
 * @access public
 * @return void
 */
	function setUp() {
		if (!isset($this->config)) {
			$this->config = Cache::config('default');
		}

		Cache::config('default', array('engine'=> 'File', 'path' => CACHE));
	}
/**
 * end method
 *
 * @access public
 * @return void
 */
	function end() {
		Cache::config('default', $this->config['settings']);
	}
/**
 * testConfig method
 *
 * @access public
 * @return void
 */
	function testConfig() {
		$settings = array('engine' => 'File', 'path' => TMP . 'tests', 'prefix' => 'cake_test_');
		$results = Cache::config('new', $settings);
		$this->assertEqual($results, Cache::config('new'));
	}
/**
 * testConfigChange method
 *
 * @access public
 * @return void
 */
	function testConfigChange() {
		$result = Cache::config('sessions', array('engine'=> 'File', 'path' => TMP . 'sessions'));
		$this->assertEqual($result['settings'], Cache::settings('File'));

		$result = Cache::config('tests', array('engine'=> 'File', 'path' => TMP . 'tests'));
		$this->assertEqual($result['settings'], Cache::settings('File'));
	}
/**
 * testWritingWithConfig method
 *
 * @access public
 * @return void
 */
	function testWritingWithConfig() {
		Cache::config('sessions');
		Cache::write('test_somthing', 'this is the test data', 'tests');

		$expected = array(
			'path' => TMP . 'sessions',
			'prefix' => 'cake_',
			'lock' => false,
			'serialize' => true,
			'duration' => 3600,
			'probability' => 100,
			'engine' => 'File',
			'isWindows' => DIRECTORY_SEPARATOR == '\\'
		);
		$this->assertEqual($expected, Cache::settings('File'));
	}
/**
 * testInitSettings method
 *
 * @access public
 * @return void
 */
	function testInitSettings() {
		Cache::engine('File', array('path' => TMP . 'tests'));
		$settings = Cache::settings();
		$expecting = array(
			'engine' => 'File',
			'duration'=> 3600,
			'probability' => 100,
			'path'=> TMP . 'tests',
			'prefix'=> 'cake_',
			'lock' => false,
			'serialize'=> true,
			'isWindows' => DIRECTORY_SEPARATOR == '\\'
		);
		$this->assertEqual($settings, $expecting);
	}
/**
 * testWriteEmptyValues method
 *
 * @access public
 * @return void
 */
	function testWriteEmptyValues() {
		return;
		Cache::engine('File', array('path' => TMP . 'tests'));
		Cache::write('App.falseTest', false);
		$this->assertIdentical(Cache::read('App.falseTest'), false);

		Cache::write('App.trueTest', true);
		$this->assertIdentical(Cache::read('App.trueTest'), true);

		Cache::write('App.nullTest', null);
		$this->assertIdentical(Cache::read('App.nullTest'), null);

		Cache::write('App.zeroTest', 0);
		$this->assertIdentical(Cache::read('App.zeroTest'), 0);

		Cache::write('App.zeroTest2', '0');
		$this->assertIdentical(Cache::read('App.zeroTest2'), '0');
	}
/**
 * testSet method
 *
 * @access public
 * @return void
 */
	function testSet() {
		$write = false;

		Cache::set(array('duration' => '+1 year'));
		$data = Cache::read('test_cache');
		$this->assertFalse($data);

		$data = 'this is just a simple test of the cache system';
		$write = Cache::write('test_cache', $data);

		$this->assertTrue($write);

		Cache::set(array('duration' => '+1 year'));
		$data = Cache::read('test_cache');

		$this->assertEqual($data, 'this is just a simple test of the cache system');

		Cache::delete('test_cache');

		$global = Cache::settings();
	}
}
?>


text:
<?php
/**
 * Created by PhpStorm.
 * User: Bruno
 * Date: 01/07/2017
 * Time: 19:03
 */

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

class HomeController extends Controller
{
    /**
     * @Route("/", name="accueil")
     */
    public function indexAction()
    {
        $derniereAnnonce = $this->getDoctrine()->getManager()->getRepository('AppBundle:Annonce')->findDerniereAnnonce();
        $annoncesRecentes = $this->getDoctrine()->getManager()->getRepository('AppBundle:Annonce')->findAnnoncesRecentes();
        return $this->render('Accueil/accueil.html.twig', array('annoncesRecentes' => $annoncesRecentes, 'annonceDerniere' => $derniereAnnonce));
    }
}


text:
published: true
title: Old-Time Beef Stew
layout: post
categories: [soups]
rating: 1
---
### Servings
6

### Ingredients
- 2 pounds stew beef
- 2 tablespoons vegetable oil
- 2 cups water
- 1 tablespoon Worcestershire sauce
- 1 clove garlic, peeled
- 1 or 2 bay leaves
- 1 medium onion, sliced
- 1 teaspoon salt
- 1 teaspoon sugar
- 1/2 teaspoon pepper
- 1/2 teaspoon paprika
- Dash ground allspice or ground cloves
- 3 large carrots, sliced
- 3 ribs celery, chopped
- 2 tablespoons cornstarch

### Directions
1. Brown meat in hot oil. Add water, Worcestershire
2. sauce, garlic, bay leaves, onion, salt, sugar, pepper,
3. paprika, and allspice. Cover and simmer 1 1/2 hours.
4. Remove bay leaves and garlic clove. Add carrots and
5. celery. Cover and cook 30 to 40 minutes longer. To
6. thicken gravy, remove 2 cups hot liquid. Using a
7. separate bowl, combine
8. 1/4 cup water and cornstarch until smooth. Mix
9. with a little hot liquid and return mixture to pot.
10. Stir and cook until bubbly.

### Source
http://www.foodnetwork.com/food/cda/recipe_print/0,1946,FOOD_9936_33091_RECIPE-PRINT-FULL-PAGE-FORMATTER,00.html


text:
.class public interface abstract annotation Lcom/samsung/systemui/splugins/annotations/Requires;
.super Ljava/lang/Object;
.source "Requires.java"

# interfaces
.implements Ljava/lang/annotation/Annotation;

# annotations
.annotation runtime Ljava/lang/annotation/Repeatable;
    value = Lcom/samsung/systemui/splugins/annotations/Requirements;
.end annotation

.annotation runtime Ljava/lang/annotation/Retention;
    value = .enum Ljava/lang/annotation/RetentionPolicy;->RUNTIME:Ljava/lang/annotation/RetentionPolicy;
.end annotation

# virtual methods
.method public abstract target()Ljava/lang/Class;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()",
            "Ljava/lang/Class",
            "<*>;"
        }
    .end annotation
.end method

.method public abstract version()I
.end method


text:
. $PSScriptRoot\Administrator.ps1
. $PSScriptRoot\Bitwise.ps1
. $PSScriptRoot\Command.ps1
. $PSScriptRoot\Directory.ps1
. $PSScriptRoot\Hash.ps1
. $PSScriptRoot\HttpProxyWindows.ps1

function Backup-Item {
	param (
		[Parameter(Mandatory)]
		[string]
		$Path,

		[string]
		$Destination,

		[ValidateSet('LastWriteTime', 'Now')]
		$Date = 'Now',

		[ValidateSet('yyMMdd', 'yyMMddHHmmss')]
		[string]
		$DateFormat = 'yyMMdd',

		[switch]
		$Archive
	)

	if (!(Test-Path $Path)) {
		Write-Warning "Backup failed: '$Path' does not exist."
		return
	}

	$dst = if ($Destination) {
		$Destination
	} else {
		$item = Get-Item $Path

		$datetime = switch ($Date) {
			LastWriteTime { $item.LastWriteTime }
			Now { Get-Date }
		}

		"{0}-{1:$DateFormat}{2}" -f @(
			$item.BaseName, $datetime, $item.Extension
		)
	}

	if ($Archive) {
		Compress-Archive $Path "$dst.zip"
	} else {
		Copy-Item $Path $dst -Container -Recurse
	}
}

function New-Junction {
	param (
		[Parameter(Mandatory, Position = 0)]
		[Alias('Target')]
		[string]
		$Value,

		[string]
		$Path = '.',

		[string]
		$Name = (Split-Path $Value -Leaf)
	)

	New-Item -Path $Path -Name $Name -Value $Value -ItemType Junction
}

function New-SymbolicLink {
	param (
		[Parameter(Mandatory, Position = 0)]
		[Alias('Target')]
		[string]
		$Value,

		[string]
		$Path = '.',

		[string]
		$Name = (Split-Path $Value -Leaf)
	)

	New-Item -Path $Path -Name $Name -Value $Value -ItemType SymbolicLink
}

function New-GodMode([string]$Name = 'GodMode') {
	New-Item -Path "$Name.{ED7BA470-8E54-465E-825C-99712043E01C}" -ItemType Directory
}

function Get-Accelerator([string]$Name = '*') {
	$accelerators = [powershell].Assembly.GetType('System.Management.Automation.TypeAccelerators')::Get
	$accelerators.GetEnumerator() | Where-Object Key -Like $Name | Sort-Object -Property Key
}

function Get-Assembly {
	param (
		[SupportsWildcards]
		[string]
		$ManifestModule = '*'
	)

	[System.AppDomain]::CurrentDomain.GetAssemblies() |
	? ManifestModule -Like $ManifestModule |
	Sort-Object Location
}

function Edit-Hosts { saps notepad.exe $env:SystemRoot\System32\drivers\etc\hosts -Verb RunAs }
function Edit-Profile {
	param (
		[ValidateSet('AllUsersAllHosts', 'AllUsersCurrentHost', 'CurrentUserAllHosts', 'CurrentUserCurrentHost', 'Private')]
		[string]
		$Name = 'CurrentUserAllHosts'
	)

	if ($Name -eq 'Private') {
		if (!(Test-Path $PROFILEDIR.Private)) { New-Item $PROFILEDIR.Private -ItemType Directory }
		code "$($PROFILEDIR.Private)\profile.ps1"
	} else {
		code $PROFILE."$Name"
	}
}
function Edit-SshConfig { code $HOME\.ssh\config }

function Export-PwshProxyClixml {
	param (
		[Parameter(Mandatory)]
		[uri]
		$Proxy,

		[pscredential]
		$ProxyCredential = (Get-Credential -UserName $env:USERNAME),

		[string]
		$Path = (Join-Path (Split-Path $PROFILE) PwshProxy.xml)
	)

	$pwshProxy = [pscustomobject]@{
		Proxy           = $Proxy
		ProxyCredential = $ProxyCredential
	}

	Export-Clixml -Path $Path -InputObject $pwshProxy
}

function Get-Constructor {
	param (
		[Parameter(Mandatory, ValueFromPipeline)]
		[type]
		$Type
	)

	foreach ($c in $Type.GetConstructors()) {
		[string[]]$paramStrings = $c.GetParameters() | % {
			'[{0}]${1}' -f ($_.ParameterType.FullName, $_.Name)
		}

		'{0}({1})' -f $c.DeclaringType.Name, ($paramStrings -join ', ')
	}
}

function Compare-PSObjectProperties {
	param (
		$ReferenceObject,
		$DifferenceObject
	)

	$referenceProperties = $ReferenceObject.psobject.Properties
	$differenceProperties = $DifferenceObject.psobject.Properties
	$names = $referenceProperties.Name + $differenceProperties.Name | Sort-Object -Unique
	foreach ($n in $names) {
		$result = Compare-Object $ReferenceObject $DifferenceObject -Property $n -ErrorAction Ignore
		if ($result) {
			[PSCustomObject]@{
				Property   = $n
				Reference  = $result | Where-Object SideIndicator -EQ '<=' | ForEach-Object $n
				Difference = $result | Where-Object SideIndicator -EQ '=>' | ForEach-Object $n
			}
		}
	}
}

function Save-WebResource {
	param (
		[uri]
		$Uri,

		[string]
		$OutFile = (Join-Path $DOWNLOADS ((Split-Path $Uri -Leaf) -replace "[$([System.IO.Path]::GetInvalidFileNameChars())]"))
	)

	(Test-Path $OutFile) -or (Invoke-WebRequest $Uri -OutFile $OutFile -Verbose) > $null
	Get-Item $OutFile
}

function New-ModuleItem {
	param (
		[Parameter(Mandatory)]
		[string]
		$Name
	)

	if (Test-Path $Name) {
		Write-Warning "$Name already exists."
		return
	}

	New-Item -Path (Join-Path $Name "$Name.psm1") -Force

	$param = @{
		Path                 = Join-Path $Name "$Name.psd1"
		RootModule           = "$Name.psm1"
		CompatiblePSEditions = 'Core'
		Author               = 'Matt Gucci'
		LicenseUri           = 'https://github.com/matt9ucci/{0}/blob/master/LICENSE' -f $Name
		ProjectUri           = 'https://github.com/matt9ucci/{0}' -f $Name
		ReleaseNotes         = 'Initial release'
	}
	New-ModuleManifest @param
	$withoutComment = Get-Content $param.Path | % {
		if (($line = ($_ -replace '#.*').Trim())) {
			$line
		}
	}
	Set-Content $param.Path $withoutComment
}

function New-ModuleManifestFromModule {
	param (
		[string]
		$Name
	)

	[psmoduleinfo]$m = Import-Module $Name -PassThru
	$template = @"
@{

RootModule           = '$($m.Name)'
ModuleVersion        = $("'0.0.0.{0}'" -f (Get-Date -Format 'yyMMdd'))
CompatiblePSEditions = 'Core'
Author               = 'Matt Gucci'
Copyright            = '(c) Matt Gucci. All rights reserved.'
PowerShellVersion    = '6.0'

FunctionsToExport = @(
	$(($m.ExportedFunctions.Keys | % { "'{0}'" -f $_ }) -join "`n`t")
)
CmdletsToExport = @(
	$(($m.ExportedCmdlets.Keys | % { "'{0}'" -f $_ }) -join "`n`t")
)
VariablesToExport = @(
	$(($m.ExportedVariables.Keys | % { "'{0}'" -f $_ }) -join "`n`t")
)
AliasesToExport = @(
	$(($m.ExportedAliases.Keys | % { "'{0}'" -f $_ }) -join "`n`t")
)

}
"@

	New-Item -Path ($m.Path -replace 'psm1$', 'psd1') -Value $template
}

function Show-SpecialFolder {
	param (
		[System.Environment+SpecialFolder]
		$Name
	)

	Invoke-Item ([System.Environment]::GetFolderPath($Name))
}

function Search-MicrosoftDocs {
	param (
		[string[]]
		$Word
	)

	$search = $word -join '+'
	saps "https://docs.microsoft.com/en-us/search/index?search=$search"
}

function New-PrivateProfile {
	New-Item "$($PROFILEDIR.Private)\profile.ps1" -Force
}

Set-Alias msdocs Search-MicrosoftDocs

function ConvertTo-PlainText {
	[Alias('ToPlainText')]
	param (
		[Parameter(Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)]
		[securestring]
		$SecureString
	)
	[System.Net.NetworkCredential]::new('', $SecureString).Password
}

function ToHash {
	param (
		[string[]]$Path,
		[ValidateSet('MD5', 'SHA1', 'SHA256', 'SHA384', 'SHA512')]
		[string]$Algorithm = 'SHA256'
	)
	$fh = Get-FileHash @PSBoundParameters
	Set-Clipboard $fh.hash
	$fh
}

filter FromStream {
	[System.IO.StreamReader]::new($_).ReadToEnd()
}

filter ToHex([switch]$Upper) {
	if ($Upper) {
		[System.Convert]::ToString($_, 16).ToUpper()
	} else {
		[System.Convert]::ToString($_, 16)
	}
}

filter FromHex {
	[System.Convert]::ToInt64($_, 16)
}

filter ToBit([UInt32]$ZeroPadding = 8) {
	[System.Convert]::ToString($_, 2).PadLeft($ZeroPadding, '0')
}

filter FromBit {
	[System.Convert]::ToInt64($_, 2)
}

filter Tax {
	$result = @(
		[pscustomobject]@{ Rate = 8; Tax = $_ * 0.08 }
		[pscustomobject]@{ Rate = 10; Tax = $_ * 0.10 }
	)

	$result | ft

	'Price: {0}, Diff: {1}' -f $_, ($result[1].Tax - $result[0].Tax)
}

filter Factorial {
	if ($_ -le 1) {
		1
	} else {
		$tmp = $_ * ($_ - 1 | Factorial)
		Write-Debug ('{0, 8} {1, -1}' -f $_, $tmp)
		$tmp
	}
}

function Get-ZipArchiveEntry {
	[OutputType([System.IO.Compression.ZipArchiveEntry])]
	param (
		[Parameter(Mandatory)]
		[string]
		$Path
	)

	[System.IO.Compression.ZipArchive]$zipArchive = [System.IO.Compression.ZipFile]::OpenRead((Resolve-Path $Path))
	$zipArchive.Entries
	$zipArchive.Dispose()
}

function Set-HistoryToClipboard {
	[Alias('shycb')]
	param (
		[ValidateRange(0, [int]::MaxValue)]
		[int]
		$Last
	)

	$histories = Get-History
	if ($Last) {
		$histories = $histories | select -Last $Last
	}
	$histories | % CommandLine | Set-Clipboard
}

function Out-SortedJson {
	param (
		[string]
		$Path
	)

	$result = [ordered]@{}
	Get-Content $Path | ConvertFrom-Json -OutVariable original | Get-Member -MemberType NoteProperty | Sort-Object Name | % {
		$result[$_.Name] = $original.$($_.Name)
	}
	[pscustomobject]$result | ConvertTo-Json
}

function Set-Prompt {
	param (
		[scriptblock]
		$Definition
	)

	$value = if ($Definition) {
		$Definition.ToString()
	} else {
		pwsh -NoProfile -Command '(Get-Item Function:prompt).Definition' | Out-String
	}
	Set-Item -Path Function:prompt -Value $value
}

function New-CommandJunction {
	param (
		[Parameter(Mandatory)]
		[string]
		$Path,

		[string]
		$Name = (Split-Path $Path -Leaf)
	)

	New-Item -ItemType Junction -Path $HOME\Commands\$Name -Value $Path
}

filter FromBase64 {
	param (
		[System.Text.Encoding]
		$Encoding = [System.Text.Encoding]::UTF8
	)
	$Encoding.GetString([System.Convert]::FromBase64String($_))
}

filter FromBase64ToUtf8 {
	[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($_))
}

filter FromUrlEncodedString {
	[System.Web.HttpUtility]::UrlDecode($_)
}

filter ToNarrowJaJp {
	[Microsoft.VisualBasic.Strings]::StrConv($_, [Microsoft.VisualBasic.VbStrConv]::Narrow, (Get-Culture -Name ja-JP).LCID)
}

function Show-WindowsSetting {
	param (
		[ArgumentCompleter({
				param ($commandName, $parameterName, $wordToComplete)
				$windowsSetting = @{
					'Notification Area Icons' = { 'explorer', 'shell:::{05d7b0f4-2121-4eff-bf6b-ed3f69b894d9}' }
				}
				$windowsSetting.Keys | ? { $_ -match $wordToComplete.Trim("'") } | % { "'{0}'" -f $_ }
			})]
		[string]
		$Name
	)

	$params = $windowsSetting.$Name.Invoke()
	Start-Process @params
}

<#
.LINK
	https://docs.github.com/en/rest/reference/licenses#get-all-commonly-used-licenses
#>
function Get-LicenseFromGithub {
	param (
		[ValidateSet('apache-2.0', 'mit', 'mpl-2.0')]
		[string]
		$Key
	)

	$params = @{
		Uri = 'https://api.github.com/licenses' + $(if ($Key) { "/$Key" } else { '' })
	}
	Invoke-RestMethod @params
}

<#
.LINK
	https://docs.github.com/en/rest/reference/licenses#get-a-license
#>
function New-LicenseFile {
	param (
		[ValidateSet('agpl-3.0', 'apache-2.0', 'bsd-2-clause', 'bsd-3-clause', 'bsl-1.0', 'cc0-1.0', 'epl-2.0', 'gpl-2.0', 'gpl-3.0', 'lgpl-2.1', 'mit', 'mpl-2.0', 'unlicense')]
		[Parameter(Mandatory)]
		[string]
		$Key,

		[switch]
		$Commit
	)

	$response = Get-LicenseFromGithub $Key

	$licenseText = $response.body
	if ($key -eq 'mit') {
		$licenseText = $licenseText -replace '\[year\]', [datetime]::Today.Year
		$licenseText = $licenseText -replace '\[fullname\]', 'Masatoshi Higuchi'
	}

	$params = @{
		Path  = 'LICENSE'
		Value = $licenseText
	}
	Set-Content @params -NoNewline

	$response | Select-Object name, description, implementation | Format-List

	if ($Commit) {
		git add $params.Path
		git commit -m 'New LICENSE'
	}
}

function New-ReadmeFile {
	param (
		[switch]
		$Commit
	)

	$params = @{
		Path  = 'README.md'
		Value = "# $(Split-Path (Get-Location) -Leaf)"
	}
	Set-Content @params

	if ($Commit) {
		git add $params.Path
		git commit -m 'New README'
	}
}

function Format-Json {
	param (
		[Parameter(Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)]
		[string[]]
		$Path,

		[System.Text.Encoding]
		$Encoding = [System.Text.Encoding]::UTF8,

		[int]
		$Depth = 100,

		[ValidateSet('jq', 'PowerShell')]
		[string]
		$Formatter = 'PowerShell'
	)

	foreach ($jsonPath in $Path) {
		$json = Get-Content $jsonPath -Encoding $Encoding
		switch ($Formatter) {
			PowerShell {
				(ConvertFrom-Json -InputObject $json | ConvertTo-Json -Depth $Depth) -split '\n' | % {
					$_ -replace '\s\s', "`t"
				}
			}
			jq {
				$json | jq --tab .
			}
		}
	}
}

function Get-ComputerWindowsInfo {
	Get-ComputerInfo | select *Windows*
}

function Get-TypeHierarchy {
	param (
		[Parameter(Mandatory, ValueFromPipeline)]
		[type]
		$Type
	)

	if (($baseType = $Type.BaseType)) {
		Get-TypeHierarchy $baseType
	}
	$Type
}

function Set-BytesString {
	param (
		[Parameter(Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)]
		[string]
		$BytesString,

		[Parameter(Mandatory, Position = 1, ValueFromPipeline, ValueFromPipelineByPropertyName)]
		[string]
		$Path
	)

	[byte[]]$bytes = foreach ($byteString in ($BytesString -split ' ')) {
		try {
			[System.Convert]::ToByte($byteString, 16)
		} catch {
			throw "$byteString"
		}
	}

	Set-Content -Path $Path -Value $bytes -AsByteStream
}


text:
package com.rgi.view;

import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.ButtonGroup;
import javax.swing.JTree;

import org.openstreetmap.gui.jmapviewer.JMapViewer;
import org.openstreetmap.gui.jmapviewer.TileStoreLoader;

import com.rgi.store.tiles.TileStoreException;
import com.rgi.store.tiles.TileStoreReader;

//This is a work in progress do not rely on this code
@SuppressWarnings("javadoc")
public class RadioButtonTree extends JTree
{
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    ButtonGroup mainGroup;
    private final JMapViewer map;
    private final List<TileStoreRadioButton> buttonList = new ArrayList<>();

    public RadioButtonTree(final List<TileStoreReader> stores, final JMapViewer map)
    {
        this.map = map;
        this.mainGroup = new ButtonGroup();
        this.addGroup(stores);
    }

    public void addLayer(final TileStoreReader store)
    {
        final TileStoreRadioButton button = new TileStoreRadioButton(store);
        this.mainGroup.add(button);
        button.addActionListener(this.createActionListener());
        this.buttonList.add(button);
    }

    public void addGroup(final List<TileStoreReader> tileStores)
    {
        tileStores.stream().forEach(store -> {
                                                final TileStoreRadioButton button = new TileStoreRadioButton(store);
                                                this.mainGroup.add(button);
                                                this.buttonList.add(button);

                                                button.addActionListener(this.createActionListener());
                                             });

    }

    public ButtonGroup getGroup()
    {
        return this.mainGroup;
    }

    public ActionListener createActionListener()
    {
        return e ->
        {
            final Object source = e.getSource();
            if(source.getClass().equals(TileStoreRadioButton.class))
            {
                final TileStoreRadioButton button = (TileStoreRadioButton) source;

                button.getTileStore();

                if(button.isSelected())
                {
                    //view tiles
                    try
                    {
                        RadioButtonTree.this.map.setTileLoader(new TileStoreLoader(button.getTileStore(), RadioButtonTree.this.map));
                    }
                    catch (final TileStoreException e1)
                    {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                }
                else
                {
                    //tile disappear

                }
            }

        };
    }

}