text:
Globus Auth / OAuth2
--------------------

Globus offers Authentication and Authorization services through an OAuth2
service, Globus Auth.

Globus Auth acts as an Authorization Server, and allows users to authenticate
with, and link together, identities from a wide range of Identity Providers.

Although the :class:`AuthClient <globus_sdk.AuthClient>` class documentation
covers normal interactions with Globus Auth, the OAuth2 flows are significantly
more complex.

This section documents the supported types of authentication and how to carry
them out, as well as providing some necessary background on various OAuth2
elements.

.. rubric:: Credentials are for Users and also for Applications

It is very important that our goal in OAuth2 is not to get credentials for an
application on its own, but rather for the application as a *client* to Globus
which is acting *on behalf of a user*.

Therefore, if you are writing an application called **foo**, and a user
**bar@example.com** is using **foo**, the credentials produced belong to the
combination of **foo** and **bar@example.com**.
The resulting credentials represent the rights and permission for **foo** to
perform actions for **bar@example.com** on systems authenticated via Globus.

.. rubric:: OAuth2 Documentation

.. toctree::
   :maxdepth: 1

   oauth/flows
   oauth/resource_servers


text:
from django.conf import settings
from django.contrib.auth.models import AbstractUser
from django.db.models.signals import post_save
from django.dispatch import receiver

from rest_framework.authtoken.models import Token

class User(AbstractUser):
    pass

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    if created:
        Token.objects.create(user=instance)

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>Freeling</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

Module Freeling

Functions

    obtenerInfoEtiquetadoFreeling
    obtenerOracionesEtiquetadasFreeling
    obtenerSalidaFreeling

    sacarTildes

    salidaProceso

Variables

    __package__

    base_cmd_freeling

[hide private]


text:
package cars.infra.response;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;

/**
 * Car rental provider
 * Created by claudio on 07/07/17.
 */
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class Provider {

  @JsonProperty("company_code")
  String companyCode;

  @JsonProperty("company_name")
  String companyName;

}


text:
from licant.modules import submodule
from licant.cxx_modules import application
import licant

from licant.scripter import scriptq
scriptq.execute("../../gxx.g.py")

application("target",
	sources = ["main.c"],
	include_paths = ["../.."],
	include_modules = [
		("gxx", "posix"),
		("gxx.dprint", "stdout")
	]
)

licant.ex(default="target")


text:
layout: post
author: "Greg Wilson"
title: "A 'Joel Test' for Grassroots Programming Groups"
date: 2014-11-04
time: "07:00:00"
category: ["Teaching"]
---

  Back during the first dot-com bubble,
  Joel Spolsky wrote an article titled
  "The Joel Test: 12 Steps to Better Code"
  that listed 12 questions you can ask to estimate the maturity of a software development team:

Do you use source control?

Can you make a build in one step?

Do you make daily builds?

Do you have a bug database?

Do you fix bugs before writing new code?

Do you have an up-to-date schedule?

Do you have a spec?

Do programmers have quiet working conditions?

Do you use the best tools money can buy?

Do you have testers?

Do new candidates write code during their interview?

Do you do hallway usability testing?

  It was completely unscientific,
  but it was also very useful and influential
  (and was in fact one of the inspirations for our
  "Best Practices for Scientific Computing"
  paper).
  In that spirit,
  I would like to present something similar for estimating the maturity of
  a grassroots "learn to program" project like ours.
  In place of the original test's 12 questions,
  I have 16:

    How Mature Is Your Training Program?

Are all of your lessons searchable?

Does each lesson solve a problem your learners believe they have?

Are you teaching principles that will still be relevant in five years?

Do your instructors regularly update your lessons in a publicly-accessible version control repository?

Do your instructors record and share their pedagogical content knowledge?

Is there a coherent narrative running through all your lessons?

Are lessons presented in short, digestible pieces with clear objectives at the start and practice exercises at the end?

Do you code live when teaching?

Do your setup instructions work for most learners, and do instructors know how to fix things when they don't?

Do you check learners' current knowledge and skills before teaching?

Do you have real-time feedback in your classroom?

Do you check what learners got out of the workshop weeks or months later?

Do you have a standard for conduct that everyone is familiar with and that is actually enforced?

Do you recruit potential new instructors from your workshops?

Do you teach your instructors how to teach?

Do you provide explicit next steps for learners?

  The thing about this quiz is that it's easy to give a quick yes or no to each question.
  (You can even give yourself half marks if your score would otherwise be uncomfortably low,
  which is what I do below for Software Carpentry.)
  I think any score over 50% is pretty good;
  I also think that a lot of software skills programs fall well below that,
  regardless of whether they are grassroots groups,
  corporate training,
  or traditional academic courses.

1. Are all of your lessons searchable?

      Search engines can't read the text embedded in images, videos, and Flash animations,
      and users can't copy and paste such text,
      so anything presented that way is essentially invisible to the web.
      PDFs are also often difficult,
      especially if what they contain is graphically rich.
      In order to help learners find what they need when they need it,
      in their own order and on their own time,
      lessons should be stored in a web-friendly format like HTML.

      Software Carpentry's score: 1.
      (Note that our Version 4 lessons would only get 0.5 on this,
      because most of the example code is only present in the PNG images exported from PowerPoint,
      and not in the accompanying narration.)

2. Does each lesson solve a problem your learners believe they have?

      People learn best when they're intrinsically motivated,
      and intrinsic motivation is more likely when they can see
      how the things they are learning will help them do things
      they currently want to do.

      Software Carpentry's score: 1.

3. Are you teaching deep ideas that will still be relevant in five years?

      Specific tools come and go, but deeper principles remain.
      More importantly,
      without an understanding of the principles embodied in particular tools and techniques,
      learners will be reduced to cargo cult programming:
      they won't be able to fix things that go wrong,
      and they're unlikely to be able to extrapolate from what they know
      to come up with new solutions to their specific problems.

      And yes,
      this goal is in direct tension with the preceding one.
      Learners want specific, concrete skills to meet next Thursday's deadline;
      we want them to understand the "why" behind those skills.
      I think Software Carpentry's curriculum does a good job of smuggling big ideas into lessons
      by showing learners specific tools (e.g., pipes in the shell)
      and then explicitly saying what those tools are examples of.

      Software Carpentry's score: 1.

4. Do your instructors regularly update your lessons in a publicly-accessible version control repository?

      I now believe that getting people to collaborate openly on lessons
      in the way they collaborate on Wikipedia articles and open source software
      may well be Software Carpentry's greatest long-term contribution.
      More prosaically,
      if instructors (and learners, and passers-by) aren't able to update lessons easily,
      your training is critically dependent on a small number of authors,
      and will probably wither when real life drags those authors (or that single author) away.

      Software Carpentry's score: 1.

5. Do your instructors record and share their pedagogical content knowledge?

      Pedagogical content knowledge (PCK) is what lies between
      the domain-specific knowledge that's being taught
      and the general principles of good educational practice.
      It's the examples that illustrate ideas particularly well,
      how long lessons take,
      the instructors' collective understanding of what's likely to go wrong in those lessons and how to fix it,
      and so on—in short,
      the collective wisdom of a specific teaching community.

      Software Carpentry's score: 0.
      (Our instructor's guide only captures a fraction of what we know, and isn't updated regularly.)

6. Is there a coherent narrative running through each lesson?

      Humans are story-telling animals:
      we listen more closely,
      and learn better,
      when we're presented with a plot rather than a mere collection of facts.
      Good lessons should therefore contain a story that builds toward a useful conclusion.

      Software Carpentry's score: 0.
      (Unlike Data Carpentry, we don't use a running example throughout our lessons.)

7. Are lessons presented in short, digestible pieces with clear objectives at the start and formative assessment exercises at the end?

      This question is basically asking, "Are the lessons well designed?"

      Software Carpentry's score: 0.5.
      (Our lessons are short and digestible, but our objectives are muddled and the practice exercises are uneven.)

8. Do you code live when teaching?

      We've all had the misfortune to watch an instructor whip through slides faster than the audience could possibly follow.
      Live coding helps prevent that,
      but it also allows instructors to go off the beaten track and follow learners' questions in unexpected directions.
      More importantly,
      it allows learners to see instructors diagnose and fix mistakes
      (something which is rarely if ever shown in static slides).
      And most importantly of all,
      seeing instructors make mistakes gives learners permission to make mistakes of their own:
      if the teacher is fouling this up,
      it must OK for the newbie to as well.

      Software Carpentry's score: 1.

9. Do your setup instructions work for most learners, and do instructors know how to fix things when they don't?

      "I can't even get started" is perhaps the biggest demotivator a class faces.

      Software Carpentry's score: 0.5.
      (We get full marks for instructions, but only part marks for instructors knowing how to debug things that go wrong.)

10. Do you check learners' current knowledge and skills before teaching?

      This question is similar to the previous one, but on a different timescale:
      rather than feedback in real time as you're teaching,
      do you gather feedback before the class starts
      so that you can tune your content and pace to your actual learners?
      Laying out pre-requisites doesn't achieve this:
      people will mis-estimate their own knowledge,
      or sign up for something far too simple or far too advanced
      just because it's the only training on offer.

      Software Carpentry's score: 1.

11. Do you have real-time feedback in your classroom?

      Watching recorded videos is actually a pretty poor way for novices to learn.
      The only reason most people don't realize it is that
      many of the live lectures they've attended aren't any better.
      The whole point of a live performance is that the performer
      (in this case, the teacher)
      can respond to her audience,
      but in order for her to do that,
      there must be some way for her to get feedback while she's teaching.

      Software Carpentry's score: 1.
      (Sticky notes and Etherpad for the win!)

12. Do you check what learners got out of the workshop weeks or months later?

      Asking people immediately after a class what they learned doesn't tell you what's going to stick,
      and there's no point teaching things that don't
      (if only because there's always something else you could try to teach instead).
      A good training course also gathers long-term feedback to tune the way it's teaching,
      particularly if different instructors or different offerings approach a topic in different ways.

      Software Carpentry's score: 0.
      (Our lack of long-term post-workshop assessment is our biggest failing.)

13. Do you have a standard for conduct that everyone is familiar with and that is actually enforced?

      Isaiah Berlin famously distinguished between negative liberty (the absence of constraints)
      and positive liberty (the possession of the power and resources needed to fulfill one's desires).
      Similarly,
      there's a different between negative openness
      (the absence of a rule saying "you can't take part in this")
      and positive openness
      (a sincere effort to make everyone feel welcome and help them take part).
      A code of conduct isn't
      the only way to achieve the latter—Hacker School has
      their User's Manual,
      and Ascend has its class agreement—but
      there has to be something in place
      if you truly want all kinds of learners.

      Software Carpentry's score: 1.

14. Do you continually recruit new instructors?

      Everybody gets tired eventually,
      or is sidetracked by other events in their lives.
      In order for your training program to last longer than one person's heroic efforts,
      the instructor pool must steadily be replenished.

      Software Carpentry's score: 1.
      (Most of our instructors are alumni of past workshops.)

15. Do you teach your instructors how to teach?

      People can teach themselves how to program;
      projects like Software Carpentry exist because it's easier to learn with guidance.
      Similarly,
      people can learn how to teach on their own,
      but it's easier (and faster, and more reliable) if someone is there
      to point the way.
      Having some kind of training for instructors also helps ensure that
      they're all singing from the same songbook,
      i.e.,
      that there's some level of agreement on what and how they're going to teach,
      and therefore fewer collisions between approach and direction in class.

      But to ensure positive openness,
      instructor training must go beyond the lessons.
      Instructors need to know that they shouldn't take over the keyboard when working with novices,
      that they have to actively give everyone a chance to speak,
      to respect learners' cultural norms
      (swearing, for example, is almost unnoticed now by some people, but still quite offensive to others),
      and not to belittle the difficulties learners face by saying things like,
      "Oh, that's easy, you just..."

      Software Carpentry's score: 1.

16. Do you provide explicit next steps for learners?

      The end of class shouldn't be the end of learning.
      Instructors should tell learners where to go to find out more,
      and should connect them with everything from mailing lists and bulletin boards
      to networking events,
      potential employers,
      and internships.

      Software Carpentry's score: 0.
      (Some instructors may point learners at other resources or other classes,
      but we don't do anything systematically.)

  Our total score is 11 out of 15.
  That's a 'B' at most schools,
  so while I think we're doing well,
  we clearly also have room to improve.
  Once the Software Carpentry Foundation is properly launched,
  I hope to turn our attention to the places where we fall short.

  The real aim of this rubric,
  though,
  is to help us compare what we're doing to other efforts
  so that we can learn from them and vice versa.
  This list is obviously biased toward Software Carpentry,
  so if there are things you do that you think are valuable,
  but which don't show up in the questions above,
  please let us know.
  Equally,
  if there are questions that you think shouldn't be included
  because they're too specific to our model and audience,
  or not actually important to helping volunteers deliver high-quality training,
  please let us know that too.


text:
import collections
import itertools
import operator
import Queue
from util import *

set_ = frozenset

class InconsistencyError(Exception):
    """raise when a game state is logically inconsistent."""
    pass

"""represents the board geometry for traditional minesweeper, where the board
has fixed dimensions and fixed total # of mines.

total_cells -- total # of cells on board; all cells contained in rules + all
    'uncharted' cells
total_mines: total # of mines contained within all cells
"""
MineCount = collections.namedtuple('MineCount', ['total_cells', 'total_mines'])

def solve(rules, mine_prevalence, other_tag=None):
    """solve a minesweeper board.

    take in a minesweeper board and return the solution as a dict mapping each
    cell to its probability of being a mine.

    rules -- a set of 'Rule' describing the board
    mine_prevalence -- an object describing the total expected mines on the
        board. a MineCount indicates traditional minesweeper (fixed board
        dimensions with a total # of mines); a float indicates a fixed
        probability that any unknown cell is a mine (total # of mines will
        vary for given board dimensions, in a binomial distribution)
    other_tag -- tag used to represent all 'other' cells (all cells not
        mentioned in a rule) in the solution output
    """
    rules, all_cells = condense_supercells(rules)
    rules = reduce_rules(rules)

    determined = set(r for r in rules if r.is_trivial())
    rules -= determined

    ruleset = permute_and_interfere(rules)
    fronts = ruleset.split_fronts()

    trivial_fronts = set(f for f in fronts if f.is_trivial())
    determined |= set(f.trivial_rule() for f in trivial_fronts)
    fronts -= trivial_fronts

    stats = set(enumerate_front(f) for f in fronts)
    stats.update(r.tally() for r in determined)
    cell_probs = cell_probabilities(stats, mine_prevalence, all_cells)
    return dict(expand_cells(cell_probs, other_tag))

class Rule(ImmutableMixin):
    """basic representation of an axiom from a minesweeper game: N mines
    contained within a set of M cells.

    only used during the very early stages of the algorithm; quickly converted
    to 'Rule_'

    num_mines -- # of mines
    cells -- list of cells; each 'cell' is a unique, identifying tag that
        represents that cell (string, int, any hashable)
    """

    def __init__(self, num_mines, cells):
        self.num_mines = num_mines
        self.cells = set_(cells)

    def condensed(self, rule_supercells_map):
        """condense supercells and convert to a 'Rule_'

        rule_supercells_map -- pre-computed supercell mapping
        """
        return Rule_(
            self.num_mines,
            rule_supercells_map.get(self, set_()), # default to handle degenerate rules
            len(self.cells)
        )

    def _canonical(self):
        return (self.num_mines, self.cells)

    def __repr__(self):
        return 'Rule(num_mines=%d, cells=%s)' % (self.num_mines, sorted(list(self.cells)))

class Rule_(ImmutableMixin):
    """analogue of 'Rule', but containing supercells (sets of 'ordinary' cells
    that only ever appear together).

    this is the common rule form used throughout most of the algorithm

    num_mines -- total # of mines
    num_cells -- total # of base cells
    cells_ -- set of supercells; each supercell a set of base cells
    """

    def __init__(self, num_mines, cells_, num_cells=None):
        self.num_mines = num_mines
        self.cells_ = cells_
        self.num_cells = num_cells if num_cells is not None else sum(len(cell_) for cell_ in cells_)

        if self.num_mines < 0 or self.num_mines > self.num_cells:
            raise InconsistencyError('rule with negative mines / more mines than cells')

    def decompose(self):
        """if rule is completely full or empty of mines, split into sub-rules
        for each supercell"""
        if self.num_mines == 0 or self.num_mines == self.num_cells:
            for cell_ in self.cells_:
                size = len(cell_)
                yield Rule_(size if self.num_mines > 0 else 0, set_([cell_]), size)
            # degenerate rules (no cells) disappear here
        else:
            yield self

    def subtract(self, subrule):
        """if another rule is a sub-rule of this one, return a new rule
        covering only the difference"""
        return Rule_(self.num_mines - subrule.num_mines,
                     self.cells_ - subrule.cells_,
                     self.num_cells - subrule.num_cells)

    def permute(self):
        """generate all possible mine permutations of this rule"""
        for p in permute(self.num_mines, list(self.cells_)):
            yield p

    def is_subrule_of(self, parent):
        """return if this rule is a sub-rule of 'parent'

        'sub-rule' means this rule's cells are a subset of the parent rules'
        cells. equivalent rules are subrules of each other.
        """
        return self.cells_.issubset(parent.cells_)

    def is_trivial(self):
        """return whether this rule is trivial, i.e., has only one permutation"""
        return len(self.cells_) == 1

    def tally(self):
        """build a FrontTally from this *trivial* rule only"""
        return FrontTally.from_rule(self)

    def _canonical(self):
        return (self.num_mines, self.cells_)

    def __repr__(self):
        return 'Rule_(num_mines=%d, num_cells=%d, cells_=%s)' % (self.num_mines, self.num_cells,
            sorted([sorted(list(cell_)) for cell_ in self.cells_]))

    @staticmethod
    def mk(num_mines, cells_):
        """helper method for creation

        num_mines -- total # of mines
        cells_ -- list of cells and supercells, where a supercell is a list of
            ordinary cells, e.g., ['A', ['B', 'C'], 'D']
        """
        cells_ = [listify(cell_) for cell_ in cells_]
        return Rule_(num_mines, set_(set_(cell_) for cell_ in cells_))

def condense_supercells(rules):
    """condense supercells by finding sets of ordinary cells that only ever
    appear together. returns a set of 'Rule_' corresponding to the original
    ruleset.

    rules -- original set of 'Rule' to analyze

    note that ALL cells are converted to supercells for ease of processing
    later, even if that cell does not group with any others. the result would
    be a singleton supercell
    """

    # for each cell, list of rules that cell appears in
    cell_rules_map = map_reduce(rules, lambda rule: [(cell, rule) for cell in rule.cells], set_)
    # for each 'list of rules appearing in', list of cells that share that ruleset (these cells
    # thus only ever appear together in the same rules)
    rules_supercell_map = map_reduce(cell_rules_map.iteritems(), lambda (cell, rules): [(rules, cell)], set_)
    # for each original rule, list of 'supercells' appearing in that rule
    rule_supercells_map = map_reduce(rules_supercell_map.iteritems(), lambda (rules, cell_): [(rule, cell_) for rule in rules], set_)

    return ([rule.condensed(rule_supercells_map) for rule in rules], rules_supercell_map.values())

def reduce_rules(rules):
    """reduce ruleset using logical deduction"""
    rr = RuleReducer()
    rr.add_rules(rules)
    return rr.reduce_all()

class Reduceable(ImmutableMixin):
    """during the logical deduction phase, if all rules are nodes in a graph,
    this represents a directed edge in that graph indicating 'superrule' can
    be reduced by 'subrule'"""

    def __init__(self, superrule, subrule):
        self.superrule = superrule
        self.subrule = subrule

    def metric(self):
        """calculate the attractiveness of this reduction

        favor reductions that involve bigger rules, and amongst same-sized
        rules, those that yield # mines towards the extremes -- such rules
        have fewer permutations
        """

        num_reduced_cells = self.superrule.num_cells - self.subrule.num_cells
        num_reduced_mines = self.superrule.num_mines - self.subrule.num_mines
        return (self.superrule.num_cells, self.subrule.num_cells,
                abs(num_reduced_mines - .5 * num_reduced_cells))

    def reduce(self):
        """perform the reduction"""
        return self.superrule.subtract(self.subrule)

    def contains(self, rule):
        return rule in (self.superrule, self.subrule)

    def contained_within(self, rules):
        return all(r in rules for r in (self.superrule, self.subrule))

    def _canonical(self):
        return (self.superrule, self.subrule)

    def __repr__(self):
        return 'Reduceable(superrule=%s, subrule=%s)' % (self.superrule, self.subrule)

class CellRulesMap(object):
    """a utility class mapping cells to the rules they appear in"""

    def __init__(self, rules=[]):
        # a mapping: cell -> list of rules cell appears in
        self.map = collections.defaultdict(set)
        self.rules = set()
        self.add_rules(rules)

    def add_rules(self, rules):
        for rule in rules:
            self.add_rule(rule)

    def add_rule(self, rule):
        self.rules.add(rule)
        for cell_ in rule.cells_:
            self.map[cell_].add(rule)

    def remove_rule(self, rule):
        self.rules.remove(rule)
        for cell_ in rule.cells_:
            self.map[cell_].remove(rule)

    def overlapping_rules(self, rule):
        """return set of rules that overlap 'rule', i.e., have at least one
        cell in common"""
        return reduce(operator.or_, (self.map[cell_] for cell_ in rule.cells_), set()) - set([rule])

    def interference_edges(self):
        """return pairs of all rules that overlap each other; each pair is
        represented twice ((a, b) and (b, a)) to support processing of
        relationships that are not symmetric"""
        def _interference_edges():
            for rule in self.rules:
                for rule_ov in self.overlapping_rules(rule):
                    yield (rule, rule_ov)
        return set(_interference_edges())

    def partition(self):
        """partition the ruleset into disjoint sub-rulesets of related rules.

        that is, all rules in a sub-ruleset are related to each other in some
        way through some number of overlaps, and no rules from separate
        sub-rulesets overlap each other. returns a set of partitions, each a
        set of rules.
        """
        related_rules = dict((rule, self.overlapping_rules(rule)) for rule in self.rules)
        partitions = set()
        while related_rules:
            start = peek(related_rules)
            partition = graph_traverse(related_rules, start)
            partitions.add(set_(partition))
            for rule in partition:
                del related_rules[rule]
        return partitions

    def cells_(self):
        """return all cells contained in ruleset"""
        return set_(self.map.keys())

class RuleReducer(object):
    """manager object that performs the 'logical deduction' phase of
    the solver; maintains a set of active rules, tracks which rules
    overlap with other rules, and iteratively reduces them until no
    further reductions are possible"""

    def __init__(self):
        # current list of rules
        self.active_rules = set()
        # reverse lookup for rules containing a given cell
        self.cell_rules_map = CellRulesMap()
        # current list of all possible reductions
        self.candidate_reductions = Queue.PriorityQueue()

    def add_rules(self, rules):
        """add a set of rules to the ruleset"""
        for rule in rules:
            self.add_rule(rule)

    def add_rule(self, rule):
        """add a new rule to the active ruleset"""
        for base_rule in rule.decompose():
            self.add_base_rule(base_rule)

    def add_base_rule(self, rule):
        """helper for adding a rule"""
        self.active_rules.add(rule)
        self.cell_rules_map.add_rule(rule)
        self.update_reduceables(rule)

    def add_reduceable(self, reduc):
        # priority queue priorities are lowest first
        prio = tuple(-k for k in reduc.metric())
        self.candidate_reductions.put((prio, reduc))

    def update_reduceables(self, rule):
        """update the index of which rules are reduceable from others"""
        rules_ov = self.cell_rules_map.overlapping_rules(rule)
        for rule_ov in rules_ov:
            if rule_ov.is_subrule_of(rule):
                # catches if rules are equivalent
                self.add_reduceable(Reduceable(rule, rule_ov))
            elif rule.is_subrule_of(rule_ov):
                self.add_reduceable(Reduceable(rule_ov, rule))

    def remove_rule(self, rule):
        """remove a rule from the active ruleset/index, presumably because it
        was reduced"""
        self.active_rules.remove(rule)
        self.cell_rules_map.remove_rule(rule)
        # we can't remove the inner contents of candidate_reductions queue; items
        # are checked for validity when they're popped

    def pop_best_reduction(self):
        """get the highest-value reduction to perform next"""
        while not self.candidate_reductions.empty():
            reduction = self.candidate_reductions.get()[1]
            if not reduction.contained_within(self.active_rules):
                continue
            return reduction
        return None

    def reduce(self, reduction):
        """perform a reduction"""
        reduced_rule = reduction.reduce()
        self.remove_rule(reduction.superrule)
        self.add_rule(reduced_rule)

    def reduce_all(self):
        """run the manager"""
        while True:
            reduction = self.pop_best_reduction()
            if not reduction:
                break
            self.reduce(reduction)
        return self.active_rules

class Permutation(ImmutableMixin):
    """a single permutation of N mines among a set of (super)cells"""

    def __init__(self, mapping):
        """mapping -- a mapping: supercell -> # of mines therein

        cell set is determined implicitly from mapping, so all cells in set
        must have an entry, even if they have 0 mines"""
        self.mapping = dict(mapping)

    def subset(self, subcells):
        """return a sub-permutation containing only the cells in 'subcells'"""
        return Permutation((cell, self.mapping[cell]) for cell in subcells)

    def compatible(self, permu):
        """return whether this permutation is consistent with 'permu', meaning
        the cells they have in common have matching numbers of mines assigned"""
        overlap = self.cells() & permu.cells()
        return self.subset(overlap) == permu.subset(overlap)

    def combine(self, permu):
        """return a new permutation by combining this permutation with
        'permu'
        the permutations must be compatible!"""
        assert all(permu.mapping[k] == v for k, v in self.mapping.iteritems() if k in permu.mapping)
        mapping = dict(self.mapping)
        mapping.update(permu.mapping)
        return Permutation(mapping)

    def k(self):
        """return total # mines in this permutation"""
        return sum(self.mapping.values())

    def cells(self):
        """return set of cells in this permutation"""
        return set(self.mapping)

    def multiplicity(self):
        """count the # of permutations this permutation would correspond to if
        each supercell were broken up into singleton cells.

        e.g., N mines in a supercell of M cells has (M choose N) actual
        configurations
        """
        return product(choose(len(cell_), k) for cell_, k in self.mapping.iteritems())

    def _canonical(self):
        return tuple(sorted(self.mapping.iteritems(), key=lambda (k, v): hash(k)))

    def __repr__(self):
        cell_counts = sorted([(sorted(list(cell)), count) for cell, count in self.mapping.iteritems()])
        cell_frags = ['%s:%d' % (','.join(str(c) for c in cell), count) for cell, count in cell_counts]
        return '{%s}' % ' '.join(cell_frags)

def permute(count, cells, permu=None):
    """generate all permutations of 'count' mines among 'cells'

    permu -- the sub-permutation in progress, when called as a recursive
        helper function. not actually a Permutation object, but a set of
        (key, value) pairs
    """

    def permu_add(*k):
        return permu.union(k)

    if permu is None:
        permu = set()

    if count == 0:
        yield Permutation(permu_add(*[(cell, 0) for cell in cells]))
    else:
        remaining_size = sum(len(cell) for cell in cells)
        if remaining_size == count:
            yield Permutation(permu_add(*[(cell, len(cell)) for cell in cells]))
        elif remaining_size >= count:
            cell = cells[0]
            for multiplicity in range(min(count, len(cell)), -1, -1):
                for p in permute(count - multiplicity, cells[1:], permu_add((cell, multiplicity))):
                    yield p

class PermutationSet(object):
    """a set of permutations of the same cell set and total # of mines

    may be the full set of possible permutations, or a subset as particular
    permutations are removed due to outside conflicts

    constrained -- False if the set is the full set of possible permutations;
        True if the set has since been reduced; accurate ONLY IF the
        PermutationSet was created with the full set of possibles
    """

    def __init__(self, cells_, k, permus):
        """
        cells_ -- set of supercells
        k -- # of mines
        permus -- set of 'Permutation's thereof; all permutations must share
            the same cell set and # of mines! (corresponding to 'cells_' and
            'k')
        """
        self.cells_ = cells_
        self.k = k
        self.permus = permus
        self.constrained = False

    def _immutable(self):
        """helper function for comparison in unit tests"""
        return (self.cells_, self.k, set_(self.permus))

    @staticmethod
    def from_rule(rule):
        """build from all possible permutations of the given rule"""
        return PermutationSet(rule.cells_, rule.num_mines, set(rule.permute()))

    def to_rule(self):
        """back-construct a Rule_ from this set

        note that the set generated from self.to_rule().from_rule() may not
        match this set, as it cannot account for permutations removed from
        this set due to conflicts"""
        return Rule_(self.k, self.cells_)

    def __iter__(self):
        """return an iterator over the set of permutations"""
        return self.permus.__iter__()

    def __contains__(self, p):
        """membership test for permutation"""
        return p in self.permus

    def remove(self, permu):
        """remove a permutation from the set, such as if that permutation
        conflicts with another rule"""
        self.permus.remove(permu)
        self.constrained = True

    def empty(self):
        """return whether the set is empty"""
        return not self.permus

    def compatible(self, permu):
        """return a new PermutationSet containing only the Permutations that
        are compatible with the given Permutation 'permu'"""
        return PermutationSet(self.cells_, self.k, set(p for p in self.permus if p.compatible(permu)))

    def subset(self, cell_subset):
        """return a new PermutationSet consisting of the sub-setted
        permutations from this set"""
        permu_subset = set(p.subset(cell_subset) for p in self.permus)
        k_sub = set(p.k() for p in permu_subset)
        if len(k_sub) > 1:
            # subset is not valid because permutations differ in # of mines
            raise ValueError()
        return PermutationSet(cell_subset, k_sub.pop(), permu_subset)

    def decompose(self):
        """see _decompose(); optimizes if set has not been constrained because
        full permu-sets decompose to themselves"""
        return self._decompose() if self.constrained else [self]

    def _decompose(self, k_floor=1):
        """determine if the permutation set is the cartesian product of N
        smaller permutation sets; return the decomposition if so

        this set may be constrained, in which case at least one subset of the
        decomposition (if one exists) will also be constrained
        """
        for _k in range(k_floor, int(.5 * len(self.cells_)) + 1):
            for cell_subset in (set_(c) for c in itertools.combinations(self.cells_, _k)):
                try:
                    permu_subset, permu_remainder = self.split(cell_subset)
                except ValueError:
                    continue

                # lo, a cartesian divisor!
                divisors = [permu_subset]
                divisors.extend(permu_remainder._decompose(_k))
                return divisors

        return [self]

    def split(self, cell_subset):
        """helper function for decompose(). given a subset of cells, return
        the two permutation sets for the subset and the set of remaining
        cells, provided cell_subset is a valid decomposor; raise exception if
        not"""
        cell_remainder = self.cells_ - cell_subset
        permu_subset = self.subset(cell_subset)
        # exception thrown if subset cannot be a cartesian divisor; i.e., set
        # of permutations could not have originated from single 'choose'
        # operation

        # get the remaining permutation sets for each sub-permutation
        permu_remainders = set(map_reduce(self.permus,
            emitfunc=lambda p: [(p.subset(cell_subset), p)],
            reducefunc=lambda pv: set_(p.subset(cell_remainder) for p in pv)
        ).values())
        if len(permu_remainders) > 1:
            # remaining subsets are not identical for each sub-permutation; not
            # a cartesian divisor
            raise ValueError()
        permu_remainders = permu_remainders.pop()

        return (permu_subset, PermutationSet(cell_remainder, self.k - permu_subset.k, permu_remainders))

    def __repr__(self):
        return str(list(self.permus))

class PermutedRuleset(object):
    """a set of rules and the available permutations for each, eliminating
    permutations which are mutually-inconsistent across the ruleset"""

    def __init__(self, rules, permu_map=None):
        """
        rules -- ruleset
        permu_map -- if creating a subset of another PermutedRuleset, will be
            the permu_map of the parent; for a new PermutedRuleset, will be
            computed automatically
        """
        self.rules = rules
        self.cell_rules_map = CellRulesMap(rules)
        self.cells_ = self.cell_rules_map.cells_()

        def rule_permuset(r):
            return PermutationSet.from_rule(r) if permu_map is None else permu_map[r]
        # a mapping: rule -> PermutationSet for that rule
        self.permu_map = dict((rule, rule_permuset(rule)) for rule in rules)

    def cross_eliminate(self):
        """determine what permutations are possible for each rule, taking
        into account the constraints of all overlapping rules. eliminate
        impossible permutations"""

        interferences = self.cell_rules_map.interference_edges()

        # we can't simply iterate through 'interferences', as eliminating a
        # permutation in a rule may in turn invalidate permutations in other
        # overlapping rules that have already been processed, thus causing a
        # cascade effect
        while interferences:
            r, r_ov = interferences.pop()
            changed = False
            for permu in list(self.permu_map[r]): #copy iterable so we can modify original
                if self.permu_map[r_ov].compatible(permu).empty():
                    # this permutation has no compatible permutation in the overlapping
                    # rule. thus, it can never occur
                    self.permu_map[r].remove(permu)
                    changed = True

            if self.permu_map[r].empty():
                # no possible configurations for this rule remain
                raise InconsistencyError('rule is constrained such that it has no valid mine permutations')
            elif changed:
                # other rules overlapping with this one must be recalculated
                for r_other in self.cell_rules_map.overlapping_rules(r):
                    interferences.add((r_other, r))

    def rereduce(self):
        """after computing the possible permutations of the rules, analyze and
        decompose rules into sub-rules, if possible. this can eliminate
        dependencies among the initial set of rules, and thus potentially
        split what would have been one rule-front into several.

        this is analagous to the previous 'reduce_rules' step, but with more
        advanced logical analysis -- exploiting information gleaned from the
        permutation phase
        """

        """
        postulates that i'm pretty certain about, but can't quite prove
        *) among all cartesian decompositions from all rules, none will be reduceable with another
           (decomp'ed rules may have duplicates, though)
        *) cartesian decomposition will have effectively re-reduced all rules in the set, even non-
           decomp'ed rules; there will be no possible reductions between a decomp'ed rule and an
           original rule
        *) re-permuting amongst the de-comped ruleset will produce the same permutation sets
        """

        superseded_rules = set()
        decompositions = {}
        for rule, permu_set in self.permu_map.iteritems():
            decomp = permu_set.decompose()
            if len(decomp) > 1:
                superseded_rules.add(rule)
                # collapse duplicate decompositions by keying by cell set
                decompositions.update((dc.cells_, dc) for dc in decomp)

        for rule in superseded_rules:
            self.remove_rule(rule)
        for permu_set in decompositions.values():
            self.add_permu_set(permu_set)

    def remove_rule(self, rule):
        self.rules.remove(rule)
        self.cell_rules_map.remove_rule(rule)
        del self.permu_map[rule]

    def add_permu_set(self, permu_set):
        """add a 'decomposed' rule to the ruleset"""
        rule = permu_set.to_rule()
        self.rules.add(rule)
        self.cell_rules_map.add_rule(rule)
        self.permu_map[rule] = permu_set

    def filter(self, rule_subset):
        """return a PermutedRuleset built from this one containing only a
        subset of rules"""
        return PermutedRuleset(rule_subset, self.permu_map)

    def split_fronts(self):
        """split the ruleset into combinatorially-independent 'fronts'"""
        return set(self.filter(rule_subset) for rule_subset in self.cell_rules_map.partition())

    def is_trivial(self):
        """return whether this ruleset is trivial, i.e., contains only one rule"""
        return len(self.rules) == 1

    def trivial_rule(self):
        """return the singleton rule of this *trivial* ruleset"""
        assert self.is_trivial()
        singleton = peek(self.rules)

        # postulate: any singleton rule must also be trivial
        assert singleton.is_trivial()

        return singleton

    def enumerate(self):
        """enumerate all possible mine configurations for this ruleset"""
        for mineconfig in EnumerationState(self).enumerate():
            yield mineconfig

    def __repr__(self):
        import pprint
        return 'PermutedRuleset(\n %s)' % pprint.pformat(self.permu_map)

def permute_and_interfere(rules):
    """process the set of rules and analyze the relationships and constraints
    among them"""
    ruleset = PermutedRuleset(rules)
    ruleset.cross_eliminate()
    ruleset.rereduce()
    return ruleset

class EnumerationState(object):
    """a helper object to enumerate through all possible mine configurations of
    a ruleset"""

    def __init__(self, ruleset=None):
        """
        ruleset -- None when cloning an existing state
        """
        if ruleset is None:
            # 'naked' object for cloning
            return

        # set of Permutations -- one per rule -- that have been 'fixed' for
        # the current configuration-in-progress
        self.fixed = set()
        # subset of ruleset whose permutations are still 'open'
        self.free = dict((rule, set(permu_set)) for rule, permu_set in ruleset.permu_map.iteritems())

        # helper function (closure)
        self.overlapping_rules = lambda rule: ruleset.cell_rules_map.overlapping_rules(rule)
        # index for constraining overlapping permutations
        # mapping: (permutation, overlapping rule) -> PermutationSet of valid permutations for overlapping rule
        self.compatible_rule_index = self.build_compatibility_index(ruleset.permu_map)

    def clone(self):
        """clone this state"""
        state = EnumerationState()
        state.fixed = set(self.fixed)
        state.free = dict((rule, set(permu_set)) for rule, permu_set in self.free.iteritems())
        state.overlapping_rules = self.overlapping_rules
        state.compatible_rule_index = self.compatible_rule_index
        return state

    def build_compatibility_index(self, rspm):
        """build the constraint index"""
        index = {}
        for rule, permu_set in rspm.iteritems():
            for permu in permu_set:
                for rule_ov in self.overlapping_rules(rule):
                    index[(permu, rule_ov)] = rspm[rule_ov].compatible(permu)
        return index

    def is_complete(self):
        """return whether all rules have been 'fixed', i.e., the configuration
        is complete"""
        return not self.free

    def __iter__(self):
        """pick an 'open' rule at random and 'fix' each possible permutation
        for that rule. in this manner, when done recursively, all valid
        combinations are enumerated"""
        rule = peek(self.free)
        for permu in self.free[rule]:
            try:
                yield self.propogate(rule, permu)
            except ValueError:
                # conflict detected; dead end
                pass

    def propogate(self, rule, permu):
        """'fix' a permutation for a given rule"""
        state = self.clone()
        state._propogate(rule, permu)
        return state

    def _propogate(self, rule, permu):
        """'fix' a rule permutation and constrain the available permutations
        of all overlapping rules"""
        self.fixed.add(permu)
        del self.free[rule]

        # constrain overlapping rules
        cascades = []
        affected_rules = filter(lambda r: r in self.free, self.overlapping_rules(rule))
        for related_rule in affected_rules:
            # PermutationSet of the related rule, constrained _only by_ the rule/permutation just fixed
            allowed_permus = self.compatible_rule_index[(permu, related_rule)]
            # further constrain the related rule with this new set -- is now properly constrained by
            # all fixed rules
            self.free[related_rule] &= set(allowed_permus)

            linked_permus = self.free[related_rule]
            if len(linked_permus) == 0:
                # conflict
                raise ValueError()
            elif len(linked_permus) == 1:
                # only one possiblity; constrain further
                cascades.append((related_rule, peek(linked_permus)))

        # cascade if any other rules are now fully constrained
        for related_rule, constrained_permu in cascades:
            if related_rule in self.free: # may have already been constrained by prior recurisve call
                self._propogate(related_rule, constrained_permu)

    def mine_config(self):
        """convert the set of fixed permutations into a single Permutation
        encompassing the mine configuration for the entire ruleset"""
        return reduce(lambda a, b: a.combine(b), self.fixed)

    def enumerate(self):
        """recursively generate all possible mine configurations for the ruleset"""
        if self.is_complete():
            yield self.mine_config()
        else:
            for next_state in self:
                for mineconfig in next_state.enumerate():
                    yield mineconfig

class FrontTally(object):
    """tabulation of per-cell mine frequencies"""

    def __init__(self, data=None):
        # mapping: # of mines in configuration -> sub-tally of configurations with that # of mines
        self.subtallies = collections.defaultdict(FrontSubtally) if data is None else data

    def tally(self, front):
        """tally all possible configurations for a front (ruleset)

        note that the tallies for different total # of mines must be
        maintained separately, as these will be given different statistical
        weights later on
        """

        for config in front.enumerate():
            self.subtallies[config.k()].add(config)

        if not self.subtallies:
            # front has no possible configurations
            raise InconsistencyError('mine front has no possible configurations')

        self.finalize()

    def finalize(self):
        """finalize all sub-tallies (convert running totals to
        probabilities/expected values)"""
        for subtally in self.subtallies.values():
            subtally.finalize()

    def min_mines(self):
        """minimum # of mines found among all configurations"""
        return min(self.subtallies)

    def max_mines(self):
        """maximum # of mines found among all configurations"""
        return max(self.subtallies)

    def is_static(self):
        """whether all configurations have the same # of mines (simplifies
        statistical weighting later)"""
        return len(self.subtallies) == 1

    def __iter__(self):
        return self.subtallies.iteritems()

    def normalize(self):
        """normalize sub-tally totals into relative weights such that
        sub-totals remain proportional to each other, and the grand total
        across all sub-tallies is 1."""
        total = sum(subtally.total for subtally in self.subtallies.values())
        for subtally in self.subtallies.values():
            subtally.total /= float(total)
            subtally.normalized = True

    def collapse(self):
        """calculate the per-cell expected mine values, summed/weighted across
        all sub-tallies"""
        self.normalize()
        collapsed = map_reduce(self.subtallies.values(), lambda subtally: subtally.collapse(), sum)
        for entry in collapsed.iteritems():
            yield entry

    def scale_weights(self, scalefunc):
        """scale each sub-tally's weight/total according to 'scalefunc'

        scalefunc -- function: num_mines -> factor by which to scale the sub-tally for 'num_mines'
        """
        for num_mines, subtally in self:
            subtally.total *= scalefunc(num_mines)

    def update_weights(self, weights):
        """update each sub-tally's weight/total

        weights -- mapping: num_mines -> new weight of the sub-tally for 'num_mines'
        """
        for num_mines, subtally in self:
            subtally.total = weights.get(num_mines, 0.)

    @staticmethod
    def from_rule(rule):
        """tally a trivial rule"""
        assert rule.is_trivial()
        return FrontTally({rule.num_mines: FrontSubtally.mk(choose(rule.num_cells, rule.num_mines), {peek(rule.cells_): rule.num_mines})})

    @staticmethod
    def for_other(num_uncharted_cells, mine_totals):
        """create a meta-tally representing the mine distribution of all
        'other' cells

        num_uncharted_cells -- # of 'other' cells
        mine_totals -- a mapping suitable for update_weights(): # mines in 'other' region -> relative likelihood
        """

        metacell = UnchartedCell(num_uncharted_cells)
        return FrontTally(dict((num_mines, FrontSubtally.mk(k, {metacell: num_mines})) for num_mines, k in mine_totals.iteritems()))

    def __repr__(self):
        return str(dict(self.subtallies))

class FrontSubtally(object):
    """sub-tabulation of per-cell mine frequencies"""

    def __init__(self):
        # 'weight' of this sub-tally among the others in the FrontTally. initially
        # will be a raw count of the configurations in this sub-tally, but later
        # will be skewed due to weighting and normalizing factors
        self.total = 0
        # per-cell mine counts (pre-finalizing) / mine prevalence (post-finalizing)
        # mapping: supercell -> total # of mines in cell summed across all configurations (pre-finalize)
        #                    -> expected # of mines in cell (post-finalize)
        self.tally = collections.defaultdict(lambda: 0)

        self.finalized = False
        self.normalized = False

    def add(self, config):
        """add a configuration to the tally"""
        mult = config.multiplicity() # weight by multiplicity
        self.total += mult
        for cell_, n in config.mapping.iteritems():
            self.tally[cell_] += n * mult

    def finalize(self):
        """after all configurations have been summed, compute relative
        prevalence from totals"""
        self.tally = dict((cell_, n / float(self.total)) for cell_, n in self.tally.iteritems())
        self.finalized = True

    def collapse(self):
        """helper function for FrontTally.collapse(); emit all cell expected
        mine values weighted by this sub-tally's weight"""
        for cell_, expected_mines in self.tally.iteritems():
            yield (cell_, self.total * expected_mines)

    @staticmethod
    def mk(total, tally):
        """build a sub-tally manually

        tally data must already be finalized"""
        o = FrontSubtally()
        o.total = total
        o.tally = tally
        o.finalized = True
        return o

    def __repr__(self):
        return str((self.total, dict(self.tally)))

def enumerate_front(front):
    """enumerate and tabulate all mine configurations for the given front

    return a tally where: sub-totals are split out by total # of mines in
    configuration, and each sub-tally contains: a total count of matching
    configurations, and expected # of mines in each cell
    """
    tally = FrontTally()
    tally.tally(front)
    return tally

def cell_probabilities(tallies, mine_prevalence, all_cells):
    """generate the final expected values for all cells in all fronts

    tallies -- set of 'FrontTally's
    mine_prevalence -- description of # or frequency of mines in board
        (from solve())
    all_cells -- a set of all supercells from all rules

    generates a stream of tuples: (cell, # mines / cell) for all cells
    """

    weight_subtallies(tallies, mine_prevalence, all_cells)
    # concatenate and emit the cell solutions from all fronts
    return itertools.chain(*(tally.collapse() for tally in tallies))

def weight_subtallies(tallies, mine_prevalence, all_cells):
    """analyze all FrontTallys as a whole and weight the likelihood of each
    sub-tally using probability analysis"""

    # True: traditional minesweeper -- fixed total # of mines
    # False: fixed overall probability of mine; total # of mines varies per game
    discrete_mode = isinstance(mine_prevalence, MineCount)

    if discrete_mode:
        num_uncharted_cells = check_count_consistency(tallies, mine_prevalence, all_cells)

    # tallies with only one sub-tally don't need weighting
    dyn_tallies = set(tally for tally in tallies if not tally.is_static())

    if discrete_mode:
        num_static_mines = sum(tally.max_mines() for tally in (tallies - dyn_tallies))
        at_large_mines = mine_prevalence.total_mines - num_static_mines

        tally_uncharted = combine_fronts(dyn_tallies, num_uncharted_cells, at_large_mines)
    else:
        tally_uncharted = weight_nondiscrete(dyn_tallies, mine_prevalence)
    tallies.add(tally_uncharted)

def weight_nondiscrete(dyn_tallies, mine_prevalence):
    """weight the relative likelihood of each sub-tally in a 'fixed mine
    probability / variable # of mines'-style game

    in this scenario, all fronts are completely independent; no front affects
    the likelihoods for any other front
    """
    for tally in dyn_tallies:
        relative_likelihood = lambda num_mines: nondiscrete_relative_likelihood(mine_prevalence, num_mines, tally.min_mines())
        tally.scale_weights(relative_likelihood)

    # regurgitate the fixed mine probability as the p for 'other' cells. kind of
    # redundant but saves the client a step. (note that since we don't count total
    # # cells in this mode, this is not a guarantee that any given game state has
    # 'other' cells)
    return FixedProbTally(mine_prevalence)

def check_count_consistency(tallies, mine_prevalence, all_cells):
    """ensure the min/max mines required across all fronts is compatible with
    the total # of mines and remaining space available on the board

    in the process, compute and return the remaining available space (# of
    'other' cells not referenced in any rule)
    """

    min_possible_mines, max_possible_mines = possible_mine_limits(tallies)
    num_uncharted_cells = mine_prevalence.total_cells - sum(len(cell_) for cell_ in all_cells)

    if min_possible_mines > mine_prevalence.total_mines:
        raise InconsistencyError('minimum possible number of mines is more than supplied mine count')
    if mine_prevalence.total_mines > max_possible_mines + num_uncharted_cells:
        # the max # of mines that can fit on the board is less than the total # specified
        raise InconsistencyError('maximum possible number of mines on board is less than supplied mine count')

    return num_uncharted_cells

def combine_fronts(tallies, num_uncharted_cells, at_large_mines):
    """assign relative weights to all sub-tallies in all fronts. because the
    total # of mines is fixed, we must do a combinatorial analysis to
    compute the likelihood of each front containing each possible # of mines.
    in the process, compute the mine count likelihood for the 'other' cells,
    not a part of any front, and return a meta-front encapsulating them.
    """

    min_tallied_mines, max_tallied_mines = possible_mine_limits(tallies)
    min_other_mines = max(at_large_mines - max_tallied_mines, 0)
    # technically, min_tallied_mines known to be <= at_large_mines due to check_count_consistency()
    max_other_mines = min(max(at_large_mines - min_tallied_mines, 0), num_uncharted_cells)
    def relative_likelihood(num_free_mines):
        return discrete_relative_likelihood(num_uncharted_cells, num_free_mines, max_other_mines)

    class FrontPerMineTotals(object):
        """object that tracks, for a constituent front, how many configurations for each # of mines
        in the front"""
        def __init__(self, totals):
            """totals: mapping of # mines -> # configurations"""
            self.totals = totals

        @staticmethod
        def singleton(num_mines, total):
            return FrontPerMineTotals({num_mines: total})

        @property
        def total_count(self):
            """returns total # of configurations across all possible # of mines"""
            return sum(self.totals.values())

        def multiply(self, n):
            """multiply all the configuration counts by a fixed factor"""
            return FrontPerMineTotals(dict((num_mines, n * count) for num_mines, count in self))

        @staticmethod
        def sum(front_totals):
            """compute an aggregate sum of several mappings"""
            return FrontPerMineTotals(map_reduce(front_totals, lambda ft: ft, sum))

        def __iter__(self):
            return self.totals.iteritems()

        def __repr__(self):
            return str(self.totals)

    class AllFrontsPerMineTotals(object):
        """object that tracks, for a given # of mines in the CombinedFront, the FrontPerMineTotals objects
        corresponding to each constituent front"""
        def __init__(self, front_totals):
            """front_totals: a list of FrontPerMineTotals objects"""
            self.front_totals = front_totals

        @property
        def total_count(self):
            """total number of configurations for the given total # of mines in the combined front"""
            if self.front_totals:
                # the count should match for each constituent front
                return self.front_totals[0].total_count
            else:
                # null case
                return 1

        @staticmethod
        def null():
            return AllFrontsPerMineTotals([])

        @staticmethod
        def singleton(num_mines, total):
            return AllFrontsPerMineTotals([FrontPerMineTotals.singleton(num_mines, total)])

        def join_with(self, new):
            """merge two AllFrontsPerMineTotals objects, joining into a single list and performing
            necessary cross-multiplication"""
            return AllFrontsPerMineTotals([f.multiply(new.total_count) for f in self.front_totals] +
                                          [f.multiply(self.total_count) for f in new.front_totals])

        @staticmethod
        def sum(frontsets):
            """sum a list of AllFrontsPerMineTotals objects on a per-constituent front basis"""
            return AllFrontsPerMineTotals(map(FrontPerMineTotals.sum, zip(*frontsets)))

        def __iter__(self):
            return iter(self.front_totals)

        def __repr__(self):
            return str((self.total_count, self.front_totals))

    class CombinedFront(object):
        """a representation of a combinatorial fusing of multiple fronts/tallies. essentially, track:
        for total # of mines in the combined front -> for each constituent front -> count of total # of
        configurations for each # of mines in the constituent front"""

        def __init__(self, total_mines_to_front_totals):
            """total_mines_to_front_totals: a mapping of total # of mines in the combined front to
            a AllFrontsPerMineTotals object"""
            self.totals = total_mines_to_front_totals

        @property
        def min_max_mines(self):
            """return (min, max) # of mines in the front"""
            return tuple(f(self.totals.keys()) for f in (min, max))

        @staticmethod
        def null():
            """create an 'empty' combined front"""
            return CombinedFront({0: AllFrontsPerMineTotals.null()})

        @staticmethod
        def from_counts_per_num_mines(mines_with_count):
            """build a starter combined front using known counts for each # of mines"""
            return CombinedFront(dict((num_mines, AllFrontsPerMineTotals.singleton(num_mines, total)) for num_mines, total in mines_with_count))

        @staticmethod
        def from_tally(tally):
            """build a starter combined front from a front tally"""
            return CombinedFront.from_counts_per_num_mines((num_mines, subtally.total) for num_mines, subtally in tally)

        @staticmethod
        def for_other(min_mines, max_mines):
            """build a starter combined front to represent the 'uncharted cells' region"""
            return CombinedFront.from_counts_per_num_mines((n, relative_likelihood(n)) for n in xrange(min_mines, max_mines + 1))

        def join_with(self, new, min_remaining_mines, max_remaining_mines):
            """combine two combined fronts. min/max remaining mines represent the total remaining mines available
            in all fronts yet to be combined (excluding 'new'). this helps avoid computing combinations whose # mines
            can never add up to the requisite # of board mines. this is also how we converge to a single total # of
            mines upon combining all fronts"""
            def cross_entry(((a_num_mines, a_fronts), (b_num_mines, b_fronts))):
                combined_mines = a_num_mines + b_num_mines
                min_mines_at_end = combined_mines + min_remaining_mines
                max_mines_at_end = combined_mines + max_remaining_mines
                if min_mines_at_end > at_large_mines or max_mines_at_end < at_large_mines:
                    return None
                return (combined_mines, a_fronts.join_with(b_fronts))
            cross_entries = filter(None, map(cross_entry, itertools.product(self, new)))
            new_totals = map_reduce(cross_entries, lambda kv: [kv], AllFrontsPerMineTotals.sum)
            return CombinedFront(new_totals)

        def collapse(self):
            """once all fronts combined, unwrap objects and return the underlying counts corresponding to each front"""
            assert len(self.totals) == 1
            return [e.totals for e in self.totals.popitem()[1].front_totals]

        def __iter__(self):
            return self.totals.iteritems()

        def __repr__(self):
            return str(self.totals)

    tallies = list(tallies) # we need guaranteed iteration order
    all_fronts = map(CombinedFront.from_tally, tallies) + [CombinedFront.for_other(min_other_mines, max_other_mines)]
    min_remaining_mines, max_remaining_mines = map(sum, zip(*(f.min_max_mines for f in all_fronts)))
    combined = CombinedFront.null()
    for f in all_fronts:
        # note that it's only safe to use min/max mines in this way before the front has been combined/modified
        front_min, front_max = f.min_max_mines
        min_remaining_mines -= front_min
        max_remaining_mines -= front_max
        combined = combined.join_with(f, min_remaining_mines, max_remaining_mines)
    front_totals = combined.collapse()
    uncharted_total = front_totals[-1]
    front_totals = front_totals[:-1]

    # upate tallies with adjusted weights
    for tally, front_total in zip(tallies, front_totals):
        tally.update_weights(front_total)

    return FrontTally.for_other(num_uncharted_cells, uncharted_total)

def possible_mine_limits(tallies):
    """return the total minimum and maximum possible # of mines across all
    tallied fronts

    returns (min, max)"""
    return (sum(f(tally) for tally in tallies) for f in (lambda tally: tally.min_mines(), lambda tally: tally.max_mines()))

def nondiscrete_relative_likelihood(p, k, k0):
    """given binomial probability (p,k,n) => p^k*(1-p)^(n-k),
    return binom_prob(p,k,n) / binom_prob(p,k0,n)

    note that n isn't actually needed! this is because we're calculating a
    per-configuration weight, and in a true binomial distribution we'd then
    multiply by (n choose k) configurations; however, we've effectively done
    that already with the enumeration/tallying phase
    """

    if p < 0. or p > 1.:
        raise ValueError('p must be [0., 1.]')

    return float((p / (1 - p))**(k - k0))

def discrete_relative_likelihood(n, k, k0):
    """return 'n choose k' / 'n choose k0'"""
    if any(x < 0 or x > n for x in (k, k0)):
        raise ValueError('k, k0 must be [0, n]')

    return float(fact_div(k0, k) * fact_div(n - k0, n - k))

class UnchartedCell(ImmutableMixin):
    """a meta-cell object that represents all the 'other' cells on the board
    that aren't explicitly mentioned in a rule. see expand_cells()"""

    def __init__(self, size=1):
        """
        size -- # of 'other' cells
        """
        self.size = size

    def __len__(self):
        return self.size

    def __iter__(self):
        """only appear once in the solution, regardless of size. however,
        don't appear at all if in fact there are no 'other' cells"""
        if self.size > 0:
            yield None

    def _canonical(self):
        return (self.size,)

class FixedProbTally(ImmutableMixin):
    """a meta-tally to represent when all 'other' cells are uncounted and
    assumed to have a fixed mine probability"""
    def __init__(self, p):
        self.p = p

    def collapse(self):
        yield (UnchartedCell(), self.p)

    def _canonical(self):
        return (self.p,)

def expand_cells(cell_probs, other_tag):
    """back-convert the expected values for all supercells into per-cell
    probabilities for each original cell"""
    for cell_, p in cell_probs:
        for cell in cell_:
            yield (cell if cell is not None else other_tag, p / len(cell_))


text:
#region LICENSE
// Source Code licensed under MS-PL.
// Derived from: MVC Foolproof Validation (http://foolproof.codeplex.com/)
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HermaFx.DataAnnotations
{
	public class MaxElementsIfNotAttribute : MaxElementsIfAttribute
	{
		public MaxElementsIfNotAttribute(uint elements, string dependentProperty, object dependentValue) : base(elements, dependentProperty, Operator.NotEqualTo, dependentValue) { }
	}
}


text:
package com.harlie.radiotheater.radiomysterytheater.utils;

import android.content.Context;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.RatingBar;
import android.widget.TextView;

import com.harlie.radiotheater.radiomysterytheater.BaseActivity;
import com.harlie.radiotheater.radiomysterytheater.EpisodeListActivity;
import com.harlie.radiotheater.radiomysterytheater.R;
import com.harlie.radiotheater.radiomysterytheater.RadioTheaterApplication;
import com.harlie.radiotheater.radiomysterytheater.data_helper.EpisodeRecyclerViewItem;

public class EpisodeViewHolder extends RecyclerView.ViewHolder {
    private final static String TAG = "LEE: <" + EpisodeViewHolder.class.getSimpleName() + ">";

    public final View mView;
    public final TextView mEpisodeNumber;
    public final TextView mEpisodeAirdate;
    public final TextView mEpisodeTitle;
    public final TextView mEpisodeDescription;
    public final RatingBar mEpisodeRating;

    public EpisodeRecyclerViewItem mItem;

    public final int mTextTitleColor;
    public final int mTextDescriptionColor;
    public final int mTitleBackgroundColor;
    public final int mDescriptionBackgroundColor;

    public EpisodeViewHolder(View itemView) {
        super(itemView);
        Context context = RadioTheaterApplication.getRadioTheaterApplicationContext();
        mView = itemView;
        this.mEpisodeNumber = (TextView) itemView.findViewById(R.id.episode_number) ;
        this.mEpisodeAirdate = (TextView) itemView.findViewById(R.id.episode_airdate) ;
        this.mEpisodeTitle = (TextView) itemView.findViewById(R.id.episode_title) ;
        this.mEpisodeDescription = (TextView) itemView.findViewById(R.id.episode_description) ;
        this.mEpisodeRating = (RatingBar) itemView.findViewById(R.id.episode_rating);
        this.mTextTitleColor = ResourceHelper.getThemeColor(context, R.color.primary_text, 0x212121);
        this.mTitleBackgroundColor = ResourceHelper.getThemeColor(context, R.color.primary_light, 0xd1c4e9);
        this.mTextDescriptionColor = ResourceHelper.getThemeColor(context, R.color.secondary_text, 0x727272);
        this.mDescriptionBackgroundColor = ResourceHelper.getThemeColor(context, R.color.light_grey, 0xbdbdbd);
    }

    public void setNormalColors() {
        if (mItem != null) {
            if (mView != null && mItem.isHeard()) {
                int color;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                    color = mView.getResources().getColor(R.color.primary_light, null);
                }
                else {
                    //noinspection deprecation
                    color = mView.getResources().getColor(R.color.primary_light);
                }
                mView.setBackgroundColor(color);
            }
            if (mEpisodeTitle != null && mItem.isDownloaded()) {
                int color;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                    color = mView != null ? mView.getResources().getColor(R.color.list_episode_title_color, null) : 0;
                }
                else {
                    //noinspection deprecation
                    color = mView != null ? mView.getResources().getColor(R.color.list_episode_title_color) : 0;
                }
                mEpisodeTitle.setTextColor(color);
            }
        }
    }

    public void setSpecialColors() {
        if (mItem != null) {
            if (mView != null && mItem.isHeard()) {
                int color;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                    color = mView.getResources().getColor(R.color.grey, null);
                }
                else {
                    //noinspection deprecation
                    color = mView.getResources().getColor(R.color.grey);
                }
                mView.setBackgroundColor(color);
            }
            if (mEpisodeTitle != null && mItem.isDownloaded()) {
                int color;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                    color = mView != null ? mView.getResources().getColor(R.color.green, null) : 0;
                }
                else {
                    //noinspection deprecation
                    color = mView != null ? mView.getResources().getColor(R.color.green) : 0;
                }
                mEpisodeTitle.setTextColor(color);
            }
        }
    }

    static final int LIST_SCALE_AMT = 3;
    public void setFontTypeAndSizes(BaseActivity activity) {
        //LogHelper.v(TAG, "setFontTypeAndSizes");
        FontPreferences fontPreferences = new FontPreferences(activity);
        String fontname = fontPreferences.getFontName();
        String fontsize = fontPreferences.getFontSize();
        LogHelper.v(TAG, "--> USING FONT NAME="+fontname+", SIZE="+fontsize);
        activity.getTheme().applyStyle(fontPreferences.getFontStyle().getResId(), true);

        int[] attrs = {R.attr.font_small, R.attr.font_medium, R.attr.font_large, R.attr.font_xlarge}; // The attributes to retrieve
        TypedArray ta = activity.obtainStyledAttributes(fontPreferences.getFontStyle().getResId(), attrs);
        //noinspection ResourceType
        float titleTextSize, descriptionTextSize, airdateTextSize, episodeNumberTextSize;
        if (! EpisodeListActivity.isTwoPane()
                || activity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
        {
            titleTextSize = getTextSize(ta, 2) + LIST_SCALE_AMT + 5;
            descriptionTextSize = getTextSize(ta, 1) + LIST_SCALE_AMT + 3;
            airdateTextSize = getTextSize(ta, 1) + LIST_SCALE_AMT + 1;
            episodeNumberTextSize = getTextSize(ta, 1) + LIST_SCALE_AMT + 1;
        }
        else {
            titleTextSize = getTextSize(ta, 1) + LIST_SCALE_AMT + 4;
            descriptionTextSize = getTextSize(ta, 0) + LIST_SCALE_AMT + 2;
            airdateTextSize = getTextSize(ta, 0) + LIST_SCALE_AMT;
            episodeNumberTextSize = getTextSize(ta, 0) + LIST_SCALE_AMT;
        }

        LogHelper.v(TAG, "=========> titleTextSize="+titleTextSize+", descriptionTextSize="+descriptionTextSize+"," +
                " airdateTextSize="+airdateTextSize+", episodeNumberTextSize="+episodeNumberTextSize);

        ta.recycle();

        if (mEpisodeTitle != null) {
            mEpisodeTitle.setTextSize(titleTextSize);
        }
        if (mEpisodeDescription != null) {
            mEpisodeDescription.setTextSize(descriptionTextSize);
        }
        if (mEpisodeAirdate != null) {
            mEpisodeAirdate.setTextSize(airdateTextSize);
        }
        if (mEpisodeNumber != null) {
            mEpisodeNumber.setTextSize(episodeNumberTextSize);
        }
    }

    private float getTextSize(TypedArray ta, int index) {
        float textSize = 0;
        String str;//noinspection ResourceType
        str = ta.getString(index);
        if (str != null) {
            textSize = Float.valueOf(str.substring(0, str.length() - 2)); // discard the "sp" part of the style item
        }
        return textSize;
    }

    @Override
    public String toString() {
        return super.toString() + " '" + mEpisodeTitle + ": " + mEpisodeDescription.getText() + "'";
    }

}


text: <kolobok-main-screen></kolobok-main-screen>


text:
using System.ComponentModel;

namespace Connect.BL
{
    public class MainPageModel : INotifyPropertyChanged
    {
        #region Members

        private bool _canConnect;
        private string _serverAddress;
        private ushort? _serverPort;
        private ConnectionState _connectionState = ConnectionState.Disconnected;
        #endregion

        #region Properties

        public ConnectionState ConnectionState
        {
            get { return _connectionState; }
            set
            {
                if (_connectionState == value)
                    return;

                _connectionState = value;
                OnPropertyChanged("ConnectionState");
                OnPropertyChanged("CanConnect");
                OnPropertyChanged("CanDisconnect");
            }
        }

        public bool CanConnect
        {
            get { return ConnectionState == ConnectionState.Disconnected; }
        }

        public bool CanDisconnect
        {
            get { return ConnectionState == ConnectionState.Connected; }
        }

        public string ServerAddress
        {
            get { return _serverAddress; }
            set
            {
                if (_serverAddress == value)
                    return;

                _serverAddress = value;

                OnPropertyChanged("ServerAddress");
            }
        }

        public ushort? ServerPort
        {
            get { return _serverPort; }
            set
            {
                if (_serverPort == value)
                    return;

                _serverPort = value;

                OnPropertyChanged("ServerPort");
            }
        }

        #endregion

        #region INotifyPropertyChanged

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        #endregion
    }
}


text:
require "rails_helper"

module MnoEnterprise
  RSpec.describe OrgInvitesController, type: :routing do
    routes { MnoEnterprise::Engine.routes }

    it "routes to #show" do
      expect(get("/org_invites/1")).to route_to("mno_enterprise/org_invites#show", id: '1')
    end

  end
end


text:
/*

This css is custom for:
- a full page image cover
- a white text on the middle
- a green button for contact us.
- a sticky footer

Greatly inspired by slack.com and sticky footer by bootstrap.
Most of the css of the landing page is directly taken from boostrap.

by @Adrien_Brunet

*/

/* Sticky footer styles
----------------------------------------------------------------------------- */

html {
  position: relative;
  min-height: 100%;
  font-size: 17px;
}

body {
  /* Margin bottom by footer height */
  margin-bottom: 150px;
}

.footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  /* Set the fixed height of the footer here */
  height: 150px;
  margin-top:110px;
  z-index: 10;
}

.footer .footer-dark {
  height: 150px;
  bottom: 0px;
  padding: 40px 0px 40px 0px;
  background-color: #2C2D30;
}

.same_color_than_footer {
  background-color: #2C2D30;
}

footer .content {
  position: absolute;
  bottom: 0px;
  width: 100%;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  padding: 40px 0px 40px 0px;
  z-index: 10;
}

footer li {
  list-style-type: none;
}

footer li a {
  color: #AAA !important;
}

.trick-css {
  position: relative;
  height:150px;
}

.gradient {
  z-index: 9;
  position: absolute;
  bottom: 0;
  width: 100%;
  /* Set the fixed height of the footer here */
  height: 260px;
  background: transparent linear-gradient(to bottom, rgba(44, 45, 48, 0) 0px, #2C2D30 45%) repeat scroll 0% 0%;
}

/* Logo and background
----------------------------------------------------------------------------- */

.full-pype {
  background: url('/static/img/nasa-background.jpg') no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  background-size: cover;
  -o-background-size: cover;
}

.full-westlife {
  background: url('/static/img/westlife-background2.jpg') no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  background-size: cover;
  -o-background-size: cover;
}

.full {
  background: url('/static/img/teky-background.jpg') no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  background-size: cover;
  -o-background-size: cover;
}

.full-meteospace {
  background: url('/static/img/meteospace-background.jpg') no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  background-size: cover;
  -o-background-size: cover;
}

.logo {
  height: 60px;
}

/* Text in the middle
----------------------------------------------------------------------------- */

a {
  color: white !important;
}

.presentation-landing-page {
  z-index: 11;
  margin-top: 250px;
  color: white !important;
  background-color: transparent !important;
  text-align: center;
}

.presentation-landing-page h1 {
  font-size: 3.4rem;
}

.presentation-description h3 {
  font-size: 1.3rem;
}

.landing-green-button {
  background: #56B68B none repeat scroll 0%;
  padding: 5px 25px 10px 25px;
}

.nobackground {
  background: transparent none repeat scroll 0%;
}

nav.top ul {
  list-style-type: none;
  margin: 0 20px 0 0;
  padding: 0;
  float: right;
  line-height: 70px;
}

nav.top ul li {
  display: inline-block;
}

nav.top ul a {
  color: #FFF;
  text-decoration: none;
  display: inline-block;
  font-size: 15px;
  font-weight: 700;
  margin-left: 9px;
  position: relative;
  cursor: pointer;
  line-height: 1em;
  padding: 8px 10px 9px;
  border-radius: 5px;
  opacity: .8;
}

nav.top ul a:hover {
  opacity: 1;
  background: rgba(0, 0, 0, .1);
  box-shadow: inset 0 1px 2px rgba(0, 0, 0, .05);
}

.presentation-text {
  background-color: rgba(0, 0, 0, 0.8);
  margin: 50px;
  min-height: 600px;
  border-radius: 15px;
  box-shadow: 0 15px 20px rgba(0, 0, 0, 0.9);
  padding: 15px;
  color: #CCC;
}

.presentation-text form {
  color: #000;
}

.presentation-text h3 {
  color: #FFF;
  text-align: center;
}

.presentation-text ul {
  list-style-type: none;
}

.presentation-text .presentation-institution {
  margin-bottom: 30px;
}

.presentation-text .presentation-institution h4 a {
  color: #FFF;
  text-decoration: none;
  font-size: 15px;
  font-weight: 700;
  cursor: pointer;
}

.presentation-text .presentation-institution p, .presentation-text .presentation-institution ul {
  list-style-type: initial;
  color: #CCC;
}

.acknowledgement-notice {
  background-color: rgba(0, 0, 0, 0.8);
  margin: 50px;
  border-radius: 15px;
  box-shadow: 0 15px 20px rgba(0, 0, 0, 0.9);
  padding: 15px;
}

.shadow-black {
  text-shadow: 2px 2px 4px #000, 5px 5px 10px #444;
}


text:
#ifndef _mrpt_scanmatching_H
#define _mrpt_scanmatching_H

#include <mrpt/scanmatching/scan_matching.h>

#endif


text:
package org.apache.isis.core.metamodel.facets.object.callbacks;

/**
 * Represents the mechanism to inform the object that it about to be deleted.
 *
 * <p>
 * In the standard Apache Isis Programming Model, this is represented by a
 * <tt>deleting</tt> method.
 *
 * @see RemovedCallbackFacet
 */

public interface RemovingCallbackFacet extends CallbackFacet {

}


text:
bool DeltaInvertedIndex::CmpDeltaId(const pair<int,int>& delta_id_and_object_id_1, const pair<int,int>& delta_id_and_object_id_2)
{
	return delta_id_and_object_id_1.first == delta_id_and_object_id_2.first ?
		delta_id_and_object_id_1.second < delta_id_and_object_id_2.second : delta_id_and_object_id_1.first < delta_id_and_object_id_2.first;
}

void DeltaInvertedIndex::AddDeltaObjectList(int token, vector<pair<int,int> >& delta_id_and_object_id_vec)
{
	if (delta_id_and_object_id_vec.size() == 0) return;
	assert(token_to_delta_object_list.count(token) == 0);

	sort(delta_id_and_object_id_vec.begin(), delta_id_and_object_id_vec.end(), CmpDeltaId);

	// for saving index space
	int delta_id_number = 0;
	int previous_delta_id = delta_id_and_object_id_vec[0].first;
	vector<int> object_id_number_vec;
	int object_id_number = 1;
	for (uint i=1; i<delta_id_and_object_id_vec.size(); ++i)
	{
		if (delta_id_and_object_id_vec[i].first != previous_delta_id)
		{
			object_id_number_vec.push_back(object_id_number);
			previous_delta_id = delta_id_and_object_id_vec[i].first;
			delta_id_number++;
			object_id_number = 1;
		}
		else
			object_id_number++;
	}
	delta_id_number++;
	object_id_number_vec.push_back(object_id_number);

	vector<DeltaObjectList> delta_object_list_vec(delta_id_number);
	int delta_id_first_pos = 0;
	for (uint i=0; i<object_id_number_vec.size(); ++i)
	{
		delta_object_list_vec[i].delta_id = delta_id_and_object_id_vec[delta_id_first_pos].first;
		delta_object_list_vec[i].list.reserve(object_id_number_vec[i]);
		for (int k=0; k<object_id_number_vec[i]; ++k)
		{
			int object_id = delta_id_and_object_id_vec[delta_id_first_pos+k].second;
			delta_object_list_vec[i].list.push_back(object_id);
		}
		delta_id_first_pos += object_id_number_vec[i];
	}
	token_to_delta_object_list.insert(HashMap<int,vector<DeltaObjectList> >::value_type(token, delta_object_list_vec));
}


text:
package net.bytebuddy.description.annotation;

import net.bytebuddy.test.utility.ObjectPropertyAssertion;
import org.junit.Test;

import java.lang.annotation.Annotation;

public class AnnotationDescriptionBuilderTest {

    private static final String FOO = "foo", BAR = "bar", QUX = "qux", BAZ = "baz";

    @Test(expected = IllegalArgumentException.class)
    public void testNonMatchingEnumerationValue() throws Exception {
        AnnotationDescription.Builder.forType(Foo.class).define(FOO, FooBar.FIRST);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testNonMatchingAnnotationValue() throws Exception {
        AnnotationDescription.Builder.forType(Qux.class).define(FOO, new QuxBaz.Instance());
    }

    @Test(expected = IllegalArgumentException.class)
    @SuppressWarnings("unchecked")
    public void testNonMatchingEnumerationArrayValue() throws Exception {
        AnnotationDescription.Builder.forType(Foo.class).defineEnumerationArray(BAR, (Class) Bar.class, Bar.FIRST, FooBar.SECOND);
    }

    @Test(expected = IllegalArgumentException.class)
    @SuppressWarnings("unchecked")
    public void testNonMatchingAnnotationArrayValue() throws Exception {
        AnnotationDescription.Builder.forType(Foo.class).defineAnnotationArray(BAZ, (Class) Qux.class, new Qux.Instance(), new QuxBaz.Instance());
    }

    @Test(expected = IllegalArgumentException.class)
    @SuppressWarnings("unchecked")
    public void testNonAnnotationType() throws Exception {
        AnnotationDescription.Builder.forType((Class) Object.class);
    }

    @Test(expected = IllegalStateException.class)
    public void testIncompleteAnnotation() throws Exception {
        AnnotationDescription.Builder.forType(Foo.class).make();
    }

    @Test(expected = IllegalArgumentException.class)
    public void testUnknownProperty() throws Exception {
        AnnotationDescription.Builder.forType(Foo.class).define(FOO + BAR, FOO);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testIllegalProperty() throws Exception {
        AnnotationDescription.Builder.forType(Foo.class).define(FOO, FOO);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testDuplicateProperty() throws Exception {
        AnnotationDescription.Builder.forType(Foo.class).define(BAZ, FOO).define(BAZ, FOO);
    }

    @Test
    public void testObjectProperties() throws Exception {
        ObjectPropertyAssertion.of(AnnotationDescription.Builder.class).apply();
    }

    public enum Bar {
        FIRST,
        SECOND
    }

    public enum FooBar {
        FIRST,
        SECOND
    }

    public @interface Foo {

        Bar foo();

        Bar[] bar();

        Qux qux();

        String baz();
    }

    public @interface Qux {

        class Instance implements Qux {

            @Override
            public Class<? extends Annotation> annotationType() {
                return Qux.class;
            }
        }
    }

    public @interface QuxBaz {

        class Instance implements QuxBaz {

            @Override
            public Class<? extends Annotation> annotationType() {
                return QuxBaz.class;
            }
        }
    }
}


text:
{% extends "main.html" %}

{% block content %}
{# {% include "header.html" %} #}

        Show All Restaurants

Login with OAuth 2.0

<button>

          <fb:login-button scope="public_profile,email" onlogin="sendTokenToServer();">
Login with Facebook

</fb:login-button>

        </button>

{% endblock content %}


text:
package org.kie.workbench.common.stunner.core.client.canvas.command;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.workbench.common.stunner.core.graph.Node;
import org.kie.workbench.common.stunner.core.graph.content.Bounds;
import org.kie.workbench.common.stunner.core.graph.content.view.Point2D;
import org.kie.workbench.common.stunner.core.graph.content.view.View;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.Silent.class)
public class UpdateElementPositionCommandTest extends AbstractCanvasCommandTest {

    @Mock
    private Node candidate;
    @Mock
    private View<?> content;

    private UpdateElementPositionCommand tested;

    @Before
    @SuppressWarnings("unchecked")
    public void setUp() throws Exception {
        super.setUp();
        when(candidate.getUUID()).thenReturn("uuid1");
        when(candidate.getContent()).thenReturn(content);
        when(content.getBounds()).thenReturn(Bounds.create(3d, 27d, 50d, 50d));
        this.tested = new UpdateElementPositionCommand(candidate,
                                                       new Point2D(100d, 200d));
    }

    @Test
    public void testGetGraphCommand() {
        final org.kie.workbench.common.stunner.core.graph.command.impl.UpdateElementPositionCommand graphCommand =
                (org.kie.workbench.common.stunner.core.graph.command.impl.UpdateElementPositionCommand) tested.newGraphCommand(canvasHandler);
        assertNotNull(graphCommand);
        assertEquals(candidate,
                     graphCommand.getNode());
        assertEquals(100d,
                     graphCommand.getLocation().getX(),
                     0);
        assertEquals(200d,
                     graphCommand.getLocation().getY(),
                     0);
        assertEquals(3d,
                     graphCommand.getPreviousLocation().getX(),
                     0);
        assertEquals(27d,
                     graphCommand.getPreviousLocation().getY(),
                     0);
    }

    @Test
    public void testGetCanvasCommand() {
        final UpdateCanvasElementPositionCommand canvasCommand =
                (UpdateCanvasElementPositionCommand) tested.newCanvasCommand(canvasHandler);
        assertNotNull(canvasCommand);
        assertEquals(candidate,
                     canvasCommand.getElement());
    }
}


text:
package scalariform.lexer

object Tokens {

  val PACKAGE = TokenType("PACKAGE")
  val STAR = TokenType("STAR")
  val WHILE = TokenType("WHILE")
  val CASE = TokenType("CASE")
  val NEW = TokenType("NEW")
  val DO = TokenType("DO")
  val EQUALS = TokenType("EQUALS")
  val SUBTYPE = TokenType("SUBTYPE")
  val EOF = TokenType("EOF")
  val SEALED = TokenType("SEALED")
  val TYPE = TokenType("TYPE")
  val LBRACKET = TokenType("LBRACKET")
  val FINAL = TokenType("FINAL")
  val RPAREN = TokenType("RPAREN")
  val IMPORT = TokenType("IMPORT")
  val STRING_LITERAL = TokenType("STRING_LITERAL")
  val STRING_PART = TokenType("STRING_PART")
  val FLOATING_POINT_LITERAL = TokenType("FLOATING_POINT_LITERAL")
  val EXCLAMATION = TokenType("EXCLAMATION")
  val NEWLINES = TokenType("NEWLINES")
  val THIS = TokenType("THIS")
  val RETURN = TokenType("RETURN")
  val VAL = TokenType("VAL")
  val VAR = TokenType("VAR")
  val SUPER = TokenType("SUPER")
  val RBRACE = TokenType("RBRACE")
  val LINE_COMMENT = TokenType("LINE_COMMENT")
  val PRIVATE = TokenType("PRIVATE")
  val NULL = TokenType("NULL")
  val ELSE = TokenType("ELSE")
  val CHARACTER_LITERAL = TokenType("CHARACTER_LITERAL")
  val MATCH = TokenType("MATCH")
  val TRY = TokenType("TRY")
  val WS = TokenType("WS")
  val SUPERTYPE = TokenType("SUPERTYPE")
  val INTEGER_LITERAL = TokenType("INTEGER_LITERAL")
  val OP = TokenType("OP")
  val USCORE = TokenType("USCORE")
  val LOWER = TokenType("LOWER")
  val CATCH = TokenType("CATCH")
  val FALSE = TokenType("FALSE")
  val VARID = TokenType("VARID")
  val THROW = TokenType("THROW")
  val UPPER = TokenType("UPPER")
  val PROTECTED = TokenType("PROTECTED")
  val CLASS = TokenType("CLASS")
  val DEF = TokenType("DEF")
  val LBRACE = TokenType("LBRACE")
  val FOR = TokenType("FOR")
  val LARROW = TokenType("LARROW")
  val ABSTRACT = TokenType("ABSTRACT")
  val LPAREN = TokenType("LPAREN")
  val IF = TokenType("IF")
  val AT = TokenType("AT")
  val MULTILINE_COMMENT = TokenType("MULTILINE_COMMENT")
  val SYMBOL_LITERAL = TokenType("SYMBOL_LITERAL")
  val OBJECT = TokenType("OBJECT")
  val COMMA = TokenType("COMMA")
  val YIELD = TokenType("YIELD")
  val TILDE = TokenType("TILDE")
  val PLUS = TokenType("PLUS")
  val PIPE = TokenType("PIPE")
  val VIEWBOUND = TokenType("VIEWBOUND")
  val RBRACKET = TokenType("RBRACKET")
  val DOT = TokenType("DOT")
  val WITH = TokenType("WITH")
  val IMPLICIT = TokenType("IMPLICIT")
  val LAZY = TokenType("LAZY")
  val TRAIT = TokenType("TRAIT")
  val HASH = TokenType("HASH")
  val FORSOME = TokenType("FORSOME")
  val MINUS = TokenType("MINUS")
  val TRUE = TokenType("TRUE")
  val SEMI = TokenType("SEMI")
  val COLON = TokenType("COLON")
  val OTHERID = TokenType("OTHERID")
  val NEWLINE = TokenType("NEWLINE")
  val FINALLY = TokenType("FINALLY")
  val OVERRIDE = TokenType("OVERRIDE")
  val ARROW = TokenType("ARROW")
  val EXTENDS = TokenType("EXTENDS")
  val INTERPOLATION_ID = TokenType("INTERPOLATION_ID")
  val XML_START_OPEN = TokenType("XML_START_OPEN", isXml = true)
  val XML_EMPTY_CLOSE = TokenType("XML_EMPTY_CLOSE", isXml = true)
  val XML_TAG_CLOSE = TokenType("XML_TAG_CLOSE", isXml = true)
  val XML_END_OPEN = TokenType("XML_END_OPEN", isXml = true)
  val XML_WHITESPACE = TokenType("XML_WHITESPACE", isXml = true)
  val XML_ATTR_EQ = TokenType("XML_ATTR_EQ", isXml = true)
  val XML_ATTR_VALUE = TokenType("XML_ATTR_VALUE", isXml = true)
  val XML_NAME = TokenType("XML_NAME", isXml = true)
  val XML_PCDATA = TokenType("XML_PCDATA", isXml = true)
  val XML_COMMENT = TokenType("XML_COMMENT", isXml = true)
  val XML_CDATA = TokenType("XML_CDATA", isXml = true)
  val XML_UNPARSED = TokenType("XML_UNPARSED", isXml = true)
  val XML_PROCESSING_INSTRUCTION = TokenType("XML_PROCESSING_INSTRUCTION", isXml = true)

  val KEYWORDS: Set[TokenType] = Set(
    ABSTRACT, CASE, CATCH, CLASS, DEF,
    DO, ELSE, EXTENDS, FINAL,
    FINALLY, FOR, FORSOME, IF, IMPLICIT,
    IMPORT, LAZY, MATCH, NEW,
    OBJECT, OVERRIDE, PACKAGE, PRIVATE, PROTECTED,
    RETURN, SEALED, SUPER, THIS,
    THROW, TRAIT, TRY, TYPE,
    VAL, VAR, WHILE, WITH, YIELD
  )

  val COMMENTS: Set[TokenType] = Set(LINE_COMMENT, MULTILINE_COMMENT, XML_COMMENT)

  val IDS: Set[TokenType] = Set(VARID, PLUS, MINUS, STAR, PIPE, TILDE, EXCLAMATION)

  val LITERALS: Set[TokenType] = Set(
    CHARACTER_LITERAL, INTEGER_LITERAL, FLOATING_POINT_LITERAL, STRING_LITERAL,
    STRING_PART, SYMBOL_LITERAL, TRUE, FALSE, NULL
  )

}