text:
Introduction
============

django-moderation is reusable application for Django framework, that allows to
moderate any model objects.

Possible use cases:

- User creates his profile, profile is not visible on site.
  It will be visible on site when moderator approves it.
- User change his profile, old profile data is visible on site.
  New data will be visible on site when moderator approves it.

Features:

- configurable admin integration(data changed in admin can be visible on
  site when moderator approves it)
- moderation queue in admin
- html differences of changes between versions of objects
- configurable email notifications
- custom model form that allows to edit changed data of object
- auto approve/reject for selected user groups or user types
- support for ImageField model fields on moderate object page
- 100% PEP8 correct code
- test coverage > 80%

Known issues
============

- m2m relations in models are not currently supported

Road map
========

For road map and issues list look at:

http://github.com/dominno/django-moderation/issues

Contributors
============

Special thanks to all persons that contributed to this project.

- jonwd7 http://github.com/jonwd7
- treyhunner http://github.com/treyhunner

Thank you for all ideas, bug fixes, patches.

Screenshots
===========

.. image:: http://dominno.pl/site_media/uploads/moderation.png
.. image:: http://dominno.pl/site_media/uploads/moderation_2.png

Requirements
============

python >= 2.4

django >= 1.2

Installation
============

Use easy_install::

    $> easy_install django-moderation

Or download source code from http://github.com/dominno/django-moderation and run
installation script::

    $> python setup.py install

Configuration
=============

1. Add to your INSTALLED_APPS in your settings.py:

    ``moderation``
2. Run command ``manage.py syncdb``
3. Register Models with moderation, put these models in module ``moderator.py`` in side of your app, ex ``myapp.moderator``::

    from moderation import moderation
    from yourapp.models import YourModel

    moderation.register(YourModel)

4. Add function ``auto_discover`` in to main urls.py::

    from moderation.helpers import auto_discover
    auto_discover()

5. If you want to enable integration with Django Admin, then register admin class with your Model::

    from django.contrib import admin
    from moderation.admin import ModerationAdmin

    class YourModelAdmin(ModerationAdmin):
        """Admin settings go here."""

    admin.site.register(YourModel, YourModelAdmin)

If admin_integration_enabled is enabled then when saving object in admin, data
will not be saved in model instance but it will be stored in moderation queue.
Also data in the change form will not display data from the original model
instance but data from the ModeratedObject instance instead.

How django-moderation works
===========================

When you change existing object or create new one, it will not be publicly
available until moderator approves it. It will be stored in ModeratedObject model.::

    your_model = YourModel(description='test')
    your_model.save()

    YourModel.objects.get(pk=your_model.pk)
    Traceback (most recent call last):
    DoesNotExist: YourModel matching query does not exist.

When you will approve object, then it will be publicly available.::

    your_model.moderated_object.approve(moderated_by=user,
                                       reason='Reason for approve')

    YourModel.objects.get(pk=1)
    <YourModel: YourModel object>

You can access changed object by calling changed_object on moderated_object:

    your_model.moderated_object.changed_object
    <YourModel: YourModel object>

This is deserialized version of object that was changed.

Now when you will change an object, old version of it will be available publicly,
new version will be saved in moderated_object::

    your_model.description = 'New description'
    your_model.save()

    your_model = YourModel.objects.get(pk=1)
    your_model.__dict__
    {'id': 1, 'description': 'test'}

    your_model.moderated_object.changed_object.__dict__
    {'id': 1, 'description': 'New description'}

    your_model.moderated_object.approve(moderated_by=user,
                                       reason='Reason for approve')

    your_model = YourModel.objects.get(pk=1)
    your_model.__dict__
    {'id': 1, 'description': 'New description'}

Moderation registration options
===============================

``moderation.register`` takes following parameters:

``model_class``
    Model class that will be registered with moderation

``moderator_class``
    Class that subclasses GenericModerator class. It Encapsulates moderation
    options for a given model. Example::

        from moderation.moderator import GenericModerator

        class UserProfileModerator(GenericModerator):
            notify_user = False
            auto_approve_for_superusers = True

        moderation.register(UserProfile, UserProfileModerator)

GenericModerator options
------------------------

``visible_until_rejected``
    By default moderation stores objects pending moderation in the ``changed_object`` field in the object's corresponding ``ModeratedObject`` instance. If ``visible_until_rejected`` is set to True, objects pending moderation will be stored in their original model as usual and the most recently approved version of the object will be stored in ``changed_object``. Default: False

``manager_names``
    List of manager names on which moderation manager will be enabled. Default: ['objects']

``moderation_manager_class``
    Default manager class that will enabled on model class managers passed in ``manager_names``. This class takes care of filtering out any objects that are not approved yet. Default: ModerationObjectsManager

``visibility_column``
    If you want a performance boost, define visibility field on your model and add option ``visibility_column = 'your_field'`` on moderator class. Field must by a BooleanField. The manager that decides which model objects should be excluded when it were rejected, will first use this option to properly display (or hide) objects that are registered with moderation. Use this option if you can define visibility column in your model and want to boost performance. By default when accessing model objects that are under moderation, one extra query is executed per object in query set to determine if object should be excluded from query set. This method benefit those who do not want to add any fields to their Models. Default: None.

``fields_exclude``
    Fields to exclude from object change list. Default: []

``auto_approve_for_superusers``
    Auto approve objects changed by superusers. Default: True

``auto_approve_for_staff``
    Auto approve objects changed by user that are staff. Default: True

``auto_approve_for_groups``
    List of user group names that will be auto approved. Default: None

``auto_reject_for_anonymous``
    Auto reject objects changed by users that are anonymous. Default: True

``auto_reject_for_groups``
    List of user group names that will be auto rejected. Default: None

``bypass_moderation_after_approval``
    When set to True, affected objects will be released from the model moderator's control upon initial approval. This is useful for models in which you want to avoid unnecessary repetition of potentially expensive auto-approve/reject logic upon each object edit. This cannot be used for models in which you would like to approve (auto or manually) each object edit, because changes are not tracked and the moderation logic is not run. If the object needs to be entered back into moderation you can set its status to "Pending" by unapproving it. Default: False

``notify_moderator``
    Defines if notification e-mails will be send to moderator. By default when user change object that is under moderation, e-mail notification is send to moderator. It will inform him that object was changed and need to be moderated. Default: True

``notify_user``
    Defines if notification e-mails will be send to user. When moderator approves or reject object changes then e-mail notification is send to user that changed this object. It will inform user if his changes were accepted or rejected and inform him why it was rejected or approved. Default: True

``subject_template_moderator``
    Subject template that will be used when sending notifications to moderators. Default: moderation/notification_subject_moderator.txt

``message_template_moderator``
    Message template that will be used when sending notifications to moderator. Default: moderation/notification_message_moderator.txt

``subject_template_user``
    Subject template that will be used when sending notifications to users. Default: moderation/notification_subject_user.txt

``message_template_user``
    Message template that will be used when sending notifications to users. Default: moderation/notification_message_user.txt

``Notes on auto moderation``
    If you want to use auto moderation in your views, then you need to save user object that has changed the object in ModeratedObject instance. You can use following helper. Example::

        moderation.register(UserProfile)

        new_profile = UserProfile()

        new_profile.save()

        from moderation.helpers import automoderate

        automoderate(new_profile, user)

``Custom auto moderation``
    If you want to define your custom logic in auto moderation, you can overwrite methods: ``is_auto_reject`` or ``is_auto_approve`` of GenericModerator class

    Example::

        class MyModelModerator(GenericModerator):

            def is_auto_reject(self, obj, user):
                # Auto reject spam
                if akismet_spam_check(obj.body):  # Check body of object for spam
                    # Body of object is spam, moderate
                    return self.reason('My custom reason: SPAM')
                super(MyModelModerator, self).is_auto_reject(obj, user)

        moderation.register(MyModel, MyModelModerator)

Default context of notification templates
-----------------------------------------

Default context:

``content_type``
    content type object of moderated object

``moderated_object``
    ModeratedObject instance

``site``
    current Site instance

How to pass extra context to email notification templates
---------------------------------------------------------

Subclass GenericModerator class and overwrite ``inform_moderator`` and
``inform_user``
methods.::

    class UserProfileModerator(GenericModerator):

        def inform_moderator(self,
                         content_object,
                         extra_context=None):
            '''Send notification to moderator'''
            extra_context={'test':'test'}
            super(UserProfileModerator, self).inform_moderator(content_object,
                                                               extra_context)

        def inform_user(self, content_object, user, extra_context=None)
            '''Send notification to user when object is approved or rejected'''
            extra_context={'test':'test'}
            super(CustomModerationNotification, self).inform_user(content_object,
                                                                  user,
                                                                  extra_context)

    moderation.register(UserProfile, UserProfileModerator)

ModerationAdmin
===============

If you have defined your own ``save_model`` method in your ModelAdmin then you
must::

    # Custom save_model in MyModelAdmin
    def save_model(self, request, obj, form, change):
        # Your custom stuff
        from moderation.helpers import automoderate
        automoderate(obj, request.user)

Otherwise what you save in the admin will get moderated and automoderation will
not work.

Signals
=======

``moderation.signals.pre_moderation`` - signal send before object is approved or
rejected

Arguments sent with this signal:

``sender``
    The model class.

``instance``
    Instance of model class that is moderated

``status``
    Moderation status, 0 - rejected, 1 - approved

``moderation.signals.post_moderation`` - signal send after object is approved or
rejected

Arguments sent with this signal:

``sender``
    The model class.

``instance``
    Instance of model class that is moderated

``status``
    Moderation status, 0 - rejected, 1 - approved

Forms
=====

When creating ModelForms for models that are under moderation use
BaseModeratedObjectForm class as ModelForm class. Thanks to that form will
initialized
with data from changed_object.::

    from moderation.forms import BaseModeratedObjectForm

    class ModeratedObjectForm(BaseModeratedObjectForm):

        class Meta:
            model = MyModel

Settings
========

``DJANGO_MODERATION_MODERATORS``
    Tuple of moderators' email addresses to which notifications will be sent.

How to run django-moderation tests
==================================

1. Download source from http://github.com/dominno/django-moderation
2. Run: python bootstrap.py
3. Run buildout:

    bin/buildout

4. Run tests for Django 1.2, 1.3, 1.4::

    bin/test.sh

Continuous Integration system
=============================

Continuous Integration system for django-moderation is available at:

https://continuous.io/dominno/django-moderation/

redpajama_set_name: RedPajamaGithub


text:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

const ConstDependency = require("./dependencies/ConstDependency");

/** @typedef {import("./Compiler")} Compiler */

class UseStrictPlugin {
	/**
	 * @param {Compiler} compiler the compiler instance
	 * @returns {void}
	 */
	apply(compiler) {
		compiler.hooks.compilation.tap(
			"UseStrictPlugin",
			(compilation, { normalModuleFactory }) => {
				const handler = parser => {
					parser.hooks.program.tap("UseStrictPlugin", ast => {
						const firstNode = ast.body[0];
						if (
							firstNode &&
							firstNode.type === "ExpressionStatement" &&
							firstNode.expression.type === "Literal" &&
							firstNode.expression.value === "use strict"
						) {
							// Remove "use strict" expression. It will be added later by the renderer again.
							// This is necessary in order to not break the strict mode when webpack prepends code.
							// @see https://github.com/webpack/webpack/issues/1970
							const dep = new ConstDependency("", firstNode.range);
							dep.loc = firstNode.loc;
							parser.state.module.addPresentationalDependency(dep);
							parser.state.module.buildInfo.strict = true;
						}
					});
				};

				normalModuleFactory.hooks.parser
					.for("javascript/auto")
					.tap("UseStrictPlugin", handler);
				normalModuleFactory.hooks.parser
					.for("javascript/dynamic")
					.tap("UseStrictPlugin", handler);
				normalModuleFactory.hooks.parser
					.for("javascript/esm")
					.tap("UseStrictPlugin", handler);
			}
		);
	}
}

module.exports = UseStrictPlugin;


text:
import { Component } from '@angular/core';
import { globals } from './app.globals';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  images = globals['images'];
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
PreReplicationHook (Hazelcast Root 3.4.2 API)
</TITLE>

<META NAME="date" CONTENT="2015-03-26">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.hazelcast.replicatedmap.impl

Interface PreReplicationHook

public interface PreReplicationHook

This is an interceptor interface to hook into the current replication process. This is not meant to be public API
 and should not be used in any external application. It might also be prospect to later changes.

Method Summary

 void
preReplicateMessage(ReplicationMessage message,
                    ReplicationChannel channel)

 void
preReplicateMultiMessage(MultiReplicationMessage message,
                         ReplicationChannel channel)

Method Detail

preReplicateMessage

void preReplicateMessage(ReplicationMessage message,
                         ReplicationChannel channel)

preReplicateMultiMessage

void preReplicateMultiMessage(MultiReplicationMessage message,
                              ReplicationChannel channel)

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 2015 Hazelcast, Inc.. All Rights Reserved.


text:
% Chapter X

\chapter{Dynamic models and filtering} % Chapter title

\label{Dynamic models and filterings} % For referencing the chapter elsewhere, use

Figaro provides constructs to create dynamic probabilistic programs that describe a domain that changes over time. All the power of the language can be used in creating dynamic programs. A dynamic probabilistic program consists of two parts: (1) an initial model, which is a universe, describing the distribution over the initial state, and (2) a transition model, which is a function from a universe representing the distribution at one time point to a universe representing the distribution at the next time point. The transition model may also optionally take a static universe as an input that represents static, non--time dependent variables.

The following code shows the typical method for creating initial and transition models:

\begin{flushleft}
\texttt{val initial = Universe.createNew()
\newline val f = Flip(0.2)("f", initial)
\newline
\newline def trans(previousUniverse: Universe): Universe = \{
\newline \tab val newU = Universe.createNew()
\newline \tab val b = previousUniverse.get[Boolean]("f")
\newline \tab val f = If(b, Flip(0.8), Flip(0.3))("f", newU)
\newline \tab newU
\newline \}
}
\end{flushleft}

The first line creates a new universe for the initial model and assigns it to a variable so that we can use it later. We then define an element to appear in the initial model and give it the name "f". When a name is given explicitly to an element, you also need to specify the universe, which in this case is the initial universe.

We then define the transition model. It takes the previous universe as argument and returns a universe. The first thing it does is create a new universe, which is returned at the end of defining the transition model. It then creates an element named "f" that depends on the previous value of "f". The previous value of  "f" is the value of the element named "f" in the previous universe. Note that we can give this new element the same name as the previous element since they are part of different universes. We get at this element using \texttt{previousUniverse.get[Boolean]("f")}. Essentially, when elements in different universes at different time points have the same name, they represent the state of the same variable at different points in time. Using this procedure, we can create any manner of dependency between the previous state and the current state by referring to elements in the previous universe by reference.

There are two dynamic reasoning algorithms available in Figaro: (1) Particle filtering, and (2) factored frontier.

\subsection{Particle filtering}

To create the particle filter, use:

\begin{flushleft}
\texttt{val pf = ParticleFilter(initial, trans, numParticles)}
\end{flushleft}

where \texttt{initial} is the initial universe, trans is the transition model (a function from \texttt{Universe => Universe}), and \texttt{numParticles} is the number of particles the algorithm should produce at each time step.

One tricky aspect about using a particle filter is that the universes are produced by a function, so it is hard to get a handle on them to observe evidence. This problem is solved by the use of named evidence, so we can refer to the correct element without having a handle on the specific universe.

To tell the particle filter to create the initial set of particles from the initial model, we call the start method. The filter then waits until it is told it is time to move to the next time step. To tell the particle
filter to move forward in time and tell it the evidence at the new time point, we call the \texttt{advanceTime} method, which takes a list of \texttt{NamedEvidence} as argument. For example:

\begin{flushleft}
\texttt{pf.start()
\newline pf.advanceTime(List(NamedEvidence("f2", Observation(\textbf{true}))))
\newline pf.advanceTime(List(NamedEvidence("f2", Observation(\textbf{false}))))}
\end{flushleft}

This creates the initial particles and advances two time steps with different evidence at each time.

The query methods provided for a filtering algorithm are \texttt{currentDi\-stribution},
\texttt{currentExpectation}, and \texttt{currentProbability}. These are similar to the corresponding methods for algorithms that compute conditional probabilities for static models, except that they return the distribution, expectation, or probability at the current point in time. For example:

\begin{flushleft}
\texttt{pf.start()
\newline pf.advanceTime(List(NamedEvidence("f2", Observation(\textbf{true}))))
\newline pf.advanceTime(List(NamedEvidence("f2", Observation(\textbf{false}))))
\newline pf.currentProbability("f1", true)}
\end{flushleft}

returns the probability that the element named "f1" is true after two time steps, given that "f2" was true in the first time step and false in the second.

There are a couple of implementation notes about particle filtering that a user should be aware of. First, since particle filtering estimates probabilities of elements using many particles, it can get expensive (memory wise) to store the state estimates for every element in the model. Therefore, the states of only \emph{named} elements are tracked through time. This means that queries to filter for an element probability or expectation must be on named elements. In addition, because filtering tracks estimates through time, we want to free up memory from old universes that are no longer used. To accomplish this, when \texttt{advanceTime} is called, all named elements from the previous universe are copied as constants to a new, temporary universe. The temporary universe is then used in the transition function, allowing the real previous universe to be freed while still letting the new universe use the correct values from the old universe.

There is also a parallel version of particle filtering that uses Scala's built in parallel collections. The interface to use parallel particle filtering is similar to the original algorithm with a few exceptions. First, this version uses a model generator, which is a function that produces a universe (particle filtering is run in parallel on separate but identical universes). Second, the user must indicate the number of threads to use.

\subsection{Factored frontier}

Factored frontier is a dynamic reasoning algorithm that uses factors instead of sampling. To create an instance of factored frontier, use:

\begin{flushleft}
\texttt{val ff = FactoredFrontier(static, initial, transition, numIterations)}
\end{flushleft}

where \texttt{static} is a universe with the static variables, \texttt{initial} is the initial universe, \texttt{transition} is the transition model (a function from \texttt{(Universe, Universe) => Universe}), and \texttt{numIterations} is the number of internal BP iterations that should be performed at each time step (as BP is used internally in the algorithm). Optionally, an anytime version of BP can be used instead, where the \texttt{numIterations} is replaced by \texttt{stepTimeMillis}, a long that indicates how long to run BP at each time step.

The same restrictions and behaviors for continuous variables that apply to BP also apply to factored frontier. The interfaces for advancing time, applying evidence, and querying the model are the same for factored frontier and particle filtering. As in particle filtering, only named elements are propagated to the next time step for building the model and querying.


text:
package org.springside.examples.showcase.demos.log;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springside.modules.log.Log4jManager;

import com.google.common.collect.Lists;

@Controller
@RequestMapping("/log")
public class LogController {

	private List levels = Lists.newArrayList("", "ERROR", "WARN", "INFO");

	@Autowired
	private Log4jManager log4jManager;

	@RequestMapping(value = "/console")
	public String console(Model model) {

		createFormObject(model);

		return "log/console";
	}

	@RequestMapping(value = "/defaultsetting")
	public String updateDefaultLogger(FormObject command, Model model) {
		log4jManager.setRootLoggerLevel(command.getRootLoggerLevel());
		log4jManager.setProjectLoggerLevel(command.getProjectLoggerLevel());

		createFormObject(model);

		return "log/console";
	}

	@RequestMapping(value = "/loggersetting")
	public String updateLogger(FormObject command, Model model) {
		String loggerName = command.loggerName;
		String loggerLevel = null;
		if (StringUtils.isNotBlank(command.loggerLevel)) {
			loggerLevel = command.loggerLevel;
			log4jManager.setLoggerLevel(command.loggerName, command.loggerLevel);

		} else {
			loggerLevel = log4jManager.getLoggerLevel(command.loggerName);
		}

		FormObject newCommand = createFormObject(model);
		newCommand.loggerName = loggerName;
		newCommand.loggerLevel = loggerLevel;
		return "log/console";
	}

	private FormObject createFormObject(Model model) {
		FormObject command = new FormObject();
		command.rootLoggerLevel = log4jManager.getRootLoggerLevel();
		command.projectLoggerLevel = log4jManager.getProjectLoggerLevel();
		model.addAttribute("command", command);

		model.addAttribute("levels", levels);
		return command;
	}

	public static class FormObject {
		private String rootLoggerLevel;
		private String projectLoggerLevel;
		private String loggerName;
		private String loggerLevel;

		public String getRootLoggerLevel() {
			return rootLoggerLevel;
		}

		public String getProjectLoggerLevel() {
			return projectLoggerLevel;
		}

		public String getLoggerName() {
			return loggerName;
		}

		public String getLoggerLevel() {
			return loggerLevel;
		}

		public void setRootLoggerLevel(String rootLoggerLevel) {
			this.rootLoggerLevel = rootLoggerLevel;
		}

		public void setProjectLoggerLevel(String projectLoggerLevel) {
			this.projectLoggerLevel = projectLoggerLevel;
		}

		public void setLoggerName(String loggerName) {
			this.loggerName = loggerName;
		}

		public void setLoggerLevel(String loggerLevel) {
			this.loggerLevel = loggerLevel;
		}

	}
}


text:
<?php

namespace yolk\app\exceptions;

/**
 * 401 Unauthorised Exception
 */
class UnauthorisedException extends \yolk\app\Exception {

	public function __construct( $message = 'Unauthorised', \Exception $previous = null ) {
		parent::__construct($message, 401, $previous);
	}

}

// EOF


text:
.. Auto-generated by help-rst from "mirtk evaluate-surface-overlap -h" output

Reports label statistics given two surface meshes and a text file
listing the indices of corresponding points. The labels have to be
stored as named point data array in both datasets.


text:
BuildRequires += $(BinDir)/erlc # erlang

include ../../Library/Unix.mk

Title=		Elixir
Name=		elixir
Version=	1.0.5
Revision=	0
Site=		http://elixir-lang.org
Source=		https://github.com/elixir-lang/elixir/archive/v$(Version).tar.gz
License=        Apache License

ReadMeFile=	$(SourceDir)/README.md
LicenseFile=	$(SourceDir)/LICENSE


text:
/*
 * dragon_tbb.h
 *
 *  Created on: 2011-08-17
 *      Author: francis
 */

#ifndef DRAGON_TBB_H_
#define DRAGON_TBB_H_

#include "dragon.h"

#ifdef __cplusplus
extern "C" {
#endif
int dragon_draw_tbb(char **canvas, struct rgb *image, int width, int height, uint64_t size, int nb_thread);
int dragon_limits_tbb(limits_t *limits, uint64_t size, int nb_thread);
#ifdef __cplusplus
}
#endif

#endif /* DRAGON_TBB_H_ */


text:
<?php

namespace JavierEguiluz\Bundle\EasyAdminBundle\Tests\Controller;

use Symfony\Component\DomCrawler\Crawler;
use JavierEguiluz\Bundle\EasyAdminBundle\Tests\Fixtures\AbstractTestCase;
use JavierEguiluz\Bundle\EasyAdminBundle\Exception\NoEntitiesConfiguredException;

class ReadOnlyBackendTest extends AbstractTestCase
{
    public function setUp()
    {
        parent::setUp();

        $this->initClient(array('environment' => 'read_only_backend'));
    }

    public function testListViewContaisNoDisabledActions()
    {
        $crawler = $this->requestListView();

        $this->assertCount(0, $crawler->filter('#content-actions a.btn:contains("Add Category")'), '"new" action is disabled.');
        $this->assertCount(0, $crawler->filter('#main .table td.actions a:contains("Edit")'), '"edit" action is disabled.');
    }

    public function testSearchViewContaisNoDisabledActions()
    {
        $crawler = $this->requestSearchView();

        $this->assertCount(0, $crawler->filter('#content-actions a.btn:contains("Add Category")'), '"new" action is disabled.');
        $this->assertCount(0, $crawler->filter('#main .table td.actions a:contains("Edit")'), '"edit" action is disabled.');
    }

    public function testShowViewContaisNoDisabledActions()
    {
        $crawler = $this->requestShowView();

        $this->assertCount(0, $crawler->filter('#form-actions a.btn:contains("Edit")'), '"edit" action is disabled.');
        $this->assertCount(0, $crawler->filter('#form-actions button:contains("Delete")'), '"delete" action is disabled.');
    }

    public function testEditActionIsDisabled()
    {
        $this->requestEditView();

        $this->assertEquals(500, $this->client->getResponse()->getStatusCode());
        $this->assertContains('ERROR: the requested 'edit' action is not allowed for the 'Category' entity.', $this->client->getResponse()->getContent());
    }

    public function testNewActionIsDisabled()
    {
        $this->requestNewView();

        $this->assertEquals(500, $this->client->getResponse()->getStatusCode());
        $this->assertContains('ERROR: the requested 'new' action is not allowed for the 'Category' entity.', $this->client->getResponse()->getContent());
    }

    /**
     * @return Crawler
     */
    private function requestListView()
    {
        return $this->getBackendPage(array(
            'action' => 'list',
            'entity' => 'Category',
        ));
    }

    /**
     * @return Crawler
     */
    private function requestShowView()
    {
        return $this->getBackendPage(array(
            'action' => 'show',
            'entity' => 'Category',
            'id' => '200',
        ));
    }

    /**
     * @return Crawler
     */
    private function requestEditView()
    {
        return $this->getBackendPage(array(
            'action' => 'edit',
            'entity' => 'Category',
            'id' => '200',
        ));
    }

    /**
     * @return Crawler
     */
    private function requestNewView()
    {
        return $this->getBackendPage(array(
            'action' => 'new',
            'entity' => 'Category',
        ));
    }

    /**
     * @return Crawler
     */
    private function requestSearchView()
    {
        return $this->getBackendPage(array(
            'action' => 'search',
            'entity' => 'Category',
            'query' => 'cat',
        ));
    }
}


text:
#ifndef STATE_HPP
#define STATE_HPP

#include "StateIdentifiers.hpp"
#include "../StreamManager.hpp"
#include "../StationsDatabase.hpp"
#include "../StatusBar.hpp"
#include "../TextLocalizer.hpp"
#include "../Subject.hpp"

class StationPlayer;
class Config;

namespace nana {
class menubar;
class form;
}  // namespace nana

class StatesManager;
class RadioBrowserRequester;

class State : public Subject {
   public:
    virtual ~State() = default;

    /**
     * \brief Context represents a structure containing references to items use
     * throughout all states
     */
    struct Context {
        Context(nana::form& window, nana::menubar& menubar, StationPlayer& station_player,
                StationsDatabase& stations_database, StatusBar& status, TextLocalizer& localizer,
                Config& config, RadioBrowserRequester& requester) noexcept;
        nana::form& window_;
        nana::menubar& menubar_;
        StationPlayer& station_player_;
        StationsDatabase& stations_database_;
        StatusBar& status_;
        TextLocalizer& localizer_;
        Config& config_;
        RadioBrowserRequester& requester_;
    };
    State(StatesManager& state_manager, Context& context);
    virtual void change_visibility(bool visible) = 0;

   protected:
    void switch_state(States::ID id) const;
    Context& context_;

   private:
    StatesManager& manager_;
};

#endif


text:
package org.colorcoding.ibas.bobas.rules.common;

import java.util.Map;

import org.colorcoding.ibas.bobas.core.IPropertyInfo;
import org.colorcoding.ibas.bobas.i18n.i18n;
import org.colorcoding.ibas.bobas.rules.BusinessRule;
import org.colorcoding.ibas.bobas.rules.BusinessRuleContext;

/**
 * 业务规则-要求值检查
 *
 * @author Niuren.Zhu
 *
 */
public class BusinessRuleRequired extends BusinessRule {

    /**
     * 构造
     *
     * @param propertyInfo
     *            要求值的属性
     * @param propertyInfos
     *            要求值的属性数组
     */
    public BusinessRuleRequired(IPropertyInfo<?> propertyInfo, IPropertyInfo<?>... propertyInfos) {
        // 要输入的参数
        this.getInputProperties().add(propertyInfo);
        if (propertyInfos != null) {
            for (IPropertyInfo<?> item : propertyInfos) {
                this.getInputProperties().add(item);
            }
        }
    }

    @Override
    protected String getName() {
        return i18n.prop("msg_bobas_business_rule_required");
    }

    @Override
    protected void execute(BusinessRuleContext context) throws Exception {
        for (Map.Entry<IPropertyInfo<?>, Object> entry : context.getInputPropertyValues().entrySet()) {
            if (entry.getValue() == null) {
                throw new Exception(i18n.prop("msg_bobas_business_rule_required_error", entry.getKey().getName()));
            }
        }
    }

}


text:
module ActiveRecord
  module AttributeMethods
    module Serialization
      extend ActiveSupport::Concern

      included do
        # Returns a hash of all the attributes that have been specified for
        # serialization as keys and their class restriction as values.
        class_attribute :serialized_attributes, instance_accessor: false
        self.serialized_attributes = {}
      end

      module ClassMethods
        ##
        # :method: serialized_attributes
        #
        # Returns a hash of all the attributes that have been specified for
        # serialization as keys and their class restriction as values.

        # If you have an attribute that needs to be saved to the database as an
        # object, and retrieved as the same object, then specify the name of that
        # attribute using this method and it will be handled automatically. The
        # serialization is done through YAML. If +class_name+ is specified, the
        # serialized object must be of that class on retrieval or
        # <tt>SerializationTypeMismatch</tt> will be raised.
        #
        # A notable side effect of serialized attributes is that the model will
        # be updated on every save, even if it is not dirty.
        #
        # ==== Parameters
        #
        # * +attr_name+ - The field name that should be serialized.
        # * +class_name_or_coder+ - Optional, a coder object, which responds to `.load` / `.dump`
        #   or a class name that the object type should be equal to.
        #
        # ==== Example
        #
        #   # Serialize a preferences attribute.
        #   class User < ActiveRecord::Base
        #     serialize :preferences
        #   end
        #
        #   # Serialize preferences using JSON as coder.
        #   class User < ActiveRecord::Base
        #     serialize :preferences, JSON
        #   end
        #
        #   # Serialize preferences as Hash using YAML coder.
        #   class User < ActiveRecord::Base
        #     serialize :preferences, Hash
        #   end
        def serialize(attr_name, class_name_or_coder = Object)
          include Behavior

          coder = if [:load, :dump].all? { |x| class_name_or_coder.respond_to?(x) }
                    class_name_or_coder
                  else
                    Coders::YAMLColumn.new(class_name_or_coder)
                  end

          # merge new serialized attribute and create new hash to ensure that each class in inheritance hierarchy
          # has its own hash of own serialized attributes
          self.serialized_attributes = serialized_attributes.merge(attr_name.to_s => coder)
        end
      end

      class Type # :nodoc:
        def initialize(column)
          @column = column
        end

        def type_cast(value)
          if value.state == :serialized
            value.unserialized_value @column.type_cast value.value
          else
            value.unserialized_value
          end
        end

        def type
          @column.type
        end

        def accessor
          ActiveRecord::Store::IndifferentHashAccessor
        end
      end

      class Attribute < Struct.new(:coder, :value, :state) # :nodoc:
        def unserialized_value(v = value)
          state == :serialized ? unserialize(v) : value
        end

        def serialized_value
          state == :unserialized ? serialize : value
        end

        def unserialize(v)
          self.state = :unserialized
          self.value = coder.load(v)
        end

        def serialize
          self.state = :serialized
          self.value = coder.dump(value)
        end
      end

      # This is only added to the model when serialize is called, which
      # ensures we do not make things slower when serialization is not used.
      module Behavior # :nodoc:
        extend ActiveSupport::Concern

        module ClassMethods # :nodoc:
          def initialize_attributes(attributes, options = {})
            serialized = (options.delete(:serialized) { true }) ? :serialized : :unserialized
            super(attributes, options)

            serialized_attributes.each do |key, coder|
              if attributes.key?(key)
                attributes[key] = Attribute.new(coder, attributes[key], serialized)
              end
            end

            attributes
          end
        end

        def should_record_timestamps?
          super || (self.record_timestamps && (attributes.keys & self.class.serialized_attributes.keys).present?)
        end

        def keys_for_partial_write
          super | (attributes.keys & self.class.serialized_attributes.keys)
        end

        def type_cast_attribute_for_write(column, value)
          if column && coder = self.class.serialized_attributes[column.name]
            Attribute.new(coder, value, :unserialized)
          else
            super
          end
        end

        def raw_type_cast_attribute_for_write(column, value)
          if column && coder = self.class.serialized_attributes[column.name]
            Attribute.new(coder, value, :serialized)
          else
            super
          end
        end

        def _field_changed?(attr, old, value)
          if self.class.serialized_attributes.include?(attr)
            old != value
          else
            super
          end
        end

        def read_attribute_before_type_cast(attr_name)
          if self.class.serialized_attributes.include?(attr_name)
            super.unserialized_value
          else
            super
          end
        end

        def attributes_before_type_cast
          super.dup.tap do |attributes|
            self.class.serialized_attributes.each_key do |key|
              if attributes.key?(key)
                attributes[key] = attributes[key].unserialized_value
              end
            end
          end
        end

        def typecasted_attribute_value(name)
          if self.class.serialized_attributes.include?(name)
            @attributes[name].serialized_value
          else
            super
          end
        end

        def attributes_for_coder
          attribute_names.each_with_object({}) do |name, attrs|
            attrs[name] = if self.class.serialized_attributes.include?(name)
                            @attributes[name].serialized_value
                          else
                            read_attribute(name)
                          end
          end
        end
      end
    end
  end
end


text:
FOUNDATION_EXPORT
    IOSObjectArray *JreEmulationMainArguments(int argc, const char *argv[]) {
  IOSClass *stringType = [IOSClass classWithClass:[NSString class]];
  if (argc <= 1) {
    return [IOSObjectArray arrayWithType:stringType count:0];
  }
  IOSObjectArray *args = [[IOSObjectArray alloc] initWithLength:argc - 1
                                                           type:stringType];
#if ! __has_feature(objc_arc)
  [args autorelease];
#endif
  for (int i = 1; i < argc; i++) {
    NSString *arg =
        [NSString stringWithCString:argv[i]
                           encoding:[NSString defaultCStringEncoding]];
    [args replaceObjectAtIndex:i - 1 withObject:arg];
  }
  return args;
}


text:
package org.apache.felix.gogo.command;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;

import org.apache.felix.service.command.CommandSession;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;

public class Util
{

    static final String CWD = "_cwd";

    public static String getBundleName(Bundle bundle)
    {
        if (bundle != null)
        {
            String name = (String) bundle.getHeaders().get(Constants.BUNDLE_NAME);
            return (name == null)
                ? "Bundle " + Long.toString(bundle.getBundleId())
                : name + " (" + Long.toString(bundle.getBundleId()) + ")";
        }
        return "[STALE BUNDLE]";
    }
    private final static StringBuffer m_sb = new StringBuffer();

    public static String getUnderlineString(int len)
    {
        synchronized (m_sb)
        {
            m_sb.delete(0, m_sb.length());
            for (int i = 0; i < len; i++)
            {
                m_sb.append('-');
            }
            return m_sb.toString();
        }
    }

    public static String getValueString(Object obj)
    {
        synchronized (m_sb)
        {
            if (obj instanceof String)
            {
                return (String) obj;
            }
            else if (obj instanceof String[])
            {
                String[] array = (String[]) obj;
                m_sb.delete(0, m_sb.length());
                for (int i = 0; i < array.length; i++)
                {
                    if (i != 0)
                    {
                        m_sb.append(", ");
                    }
                    m_sb.append(array[i].toString());
                }
                return m_sb.toString();
            }
            else if (obj instanceof Boolean)
            {
                return ((Boolean) obj).toString();
            }
            else if (obj instanceof Long)
            {
                return ((Long) obj).toString();
            }
            else if (obj instanceof Integer)
            {
                return ((Integer) obj).toString();
            }
            else if (obj instanceof Short)
            {
                return ((Short) obj).toString();
            }
            else if (obj instanceof Double)
            {
                return ((Double) obj).toString();
            }
            else if (obj instanceof Float)
            {
                return ((Float) obj).toString();
            }
            else if (obj == null)
            {
                return "null";
            }
            else
            {
                return obj.toString();
            }
        }
    }

    public static <T> T getService(
        BundleContext bc, Class<T> clazz, List<ServiceReference<?>> refs)
    {
        @SuppressWarnings("unchecked")
        ServiceReference<T> ref = (ServiceReference<T>) bc.getServiceReference(clazz.getName());
        if (ref == null)
        {
            return null;
        }
        T t = (T) bc.getService(ref);
        if (t != null)
        {
            refs.add(ref);
        }
        return t;
    }

    public static void ungetServices(BundleContext bc, List<ServiceReference<?>> refs)
    {
        while (refs.size() > 0)
        {
            bc.ungetService(refs.remove(0));
        }
    }

    public static void downloadSource(
        PrintStream out, PrintStream err,
        URL srcURL, File localDir, boolean extract)
    {
        // Get the file name from the URL.
        String fileName = (srcURL.getFile().lastIndexOf('/') > 0)
            ? srcURL.getFile().substring(srcURL.getFile().lastIndexOf('/') + 1)
            : srcURL.getFile();

        try
        {
            out.println("Connecting...");

            if (!localDir.exists())
            {
                err.println("Destination directory does not exist.");
            }
            File file = new File(localDir, fileName);

            OutputStream os = new FileOutputStream(file);
            URLConnection conn = srcURL.openConnection();
            Util.setProxyAuth(conn);
            int total = conn.getContentLength();
            InputStream is = conn.getInputStream();

            if (total > 0)
            {
                out.println("Downloading " + fileName
                    + " ( " + total + " bytes ).");
            }
            else
            {
                out.println("Downloading " + fileName + ".");
            }
            byte[] buffer = new byte[4096];
            for (int len = is.read(buffer); len > 0; len = is.read(buffer))
            {
                os.write(buffer, 0, len);
            }

            os.close();
            is.close();

            if (extract)
            {
                is = new FileInputStream(file);
                JarInputStream jis = new JarInputStream(is);
                out.println("Extracting...");
                unjar(jis, localDir);
                jis.close();
                file.delete();
            }
        }
        catch (Exception ex)
        {
            err.println(ex);
        }
    }

    public static void unjar(JarInputStream jis, File dir)
        throws IOException
    {
        // Reusable buffer.
        byte[] buffer = new byte[4096];

        // Loop through JAR entries.
        for (JarEntry je = jis.getNextJarEntry();
             je != null;
             je = jis.getNextJarEntry())
        {
            if (je.getName().startsWith("/"))
            {
                throw new IOException("JAR resource cannot contain absolute paths.");
            }

            File target = new File(dir, je.getName());

            // Check to see if the JAR entry is a directory.
            if (je.isDirectory())
            {
                if (!target.exists())
                {
                    if (!target.mkdirs())
                    {
                        throw new IOException("Unable to create target directory: "
                            + target);
                    }
                }
                // Just continue since directories do not have content to copy.
                continue;
            }

            int lastIndex = je.getName().lastIndexOf('/');
            String name = (lastIndex >= 0) ?
                je.getName().substring(lastIndex + 1) : je.getName();
            String destination = (lastIndex >= 0) ?
                je.getName().substring(0, lastIndex) : "";

            // JAR files use '/', so convert it to platform separator.
            destination = destination.replace('/', File.separatorChar);
            copy(jis, dir, name, destination, buffer);
        }
    }

    public static void copy(
        InputStream is, File dir, String destName, String destDir, byte[] buffer)
        throws IOException
    {
        if (destDir == null)
        {
            destDir = "";
        }

        // Make sure the target directory exists and
        // that is actually a directory.
        File targetDir = new File(dir, destDir);
        if (!targetDir.exists())
        {
            if (!targetDir.mkdirs())
            {
                throw new IOException("Unable to create target directory: "
                    + targetDir);
            }
        }
        else if (!targetDir.isDirectory())
        {
            throw new IOException("Target is not a directory: "
                + targetDir);
        }

        BufferedOutputStream bos = new BufferedOutputStream(
            new FileOutputStream(new File(targetDir, destName)));
        int count = 0;
        while ((count = is.read(buffer)) > 0)
        {
            bos.write(buffer, 0, count);
        }
        bos.close();
    }

    public static void setProxyAuth(URLConnection conn) throws IOException
    {
        // Support for http proxy authentication
        String auth = System.getProperty("http.proxyAuth");
        if ((auth != null) && (auth.length() > 0))
        {
            if ("http".equals(conn.getURL().getProtocol())
                || "https".equals(conn.getURL().getProtocol()))
            {
                String base64 = Base64Encoder.base64Encode(auth);
                conn.setRequestProperty("Proxy-Authorization", "Basic " + base64);
            }
        }
    }

    public static InputStream openURL(final URL url) throws IOException
    {
        // Do it the manual way to have a chance to
        // set request properties as proxy auth (EW).
        return openURL(url.openConnection());
    }

    public static InputStream openURL(final URLConnection conn) throws IOException
    {
        // Do it the manual way to have a chance to
        // set request properties as proxy auth (EW).
        setProxyAuth(conn);
        return conn.getInputStream();
    }

    public static List<String> parseSubstring(String value)
    {
        List<String> pieces = new ArrayList<String>();
        StringBuffer ss = new StringBuffer();
        // int kind = SIMPLE; // assume until proven otherwise
        boolean wasStar = false; // indicates last piece was a star
        boolean leftstar = false; // track if the initial piece is a star
        boolean rightstar = false; // track if the final piece is a star

        int idx = 0;

        // We assume (sub)strings can contain leading and trailing blanks
        boolean escaped = false;
loop:   for (;;)
        {
            if (idx >= value.length())
            {
                if (wasStar)
                {
                    // insert last piece as "" to handle trailing star
                    rightstar = true;
                }
                else
                {
                    pieces.add(ss.toString());
                    // accumulate the last piece
                    // note that in the case of
                    // (cn=); this might be
                    // the string "" (!=null)
                }
                ss.setLength(0);
                break loop;
            }

            // Read the next character and account for escapes.
            char c = value.charAt(idx++);
            if (!escaped && ((c == '(') || (c == ')')))
            {
                throw new IllegalArgumentException(
                    "Illegal value: " + value);
            }
            else if (!escaped && (c == '*'))
            {
                if (wasStar)
                {
                    // encountered two successive stars;
                    // I assume this is illegal
                    throw new IllegalArgumentException("Invalid filter string: " + value);
                }
                if (ss.length() > 0)
                {
                    pieces.add(ss.toString()); // accumulate the pieces
                    // between '*' occurrences
                }
                ss.setLength(0);
                // if this is a leading star, then track it
                if (pieces.isEmpty())
                {
                    leftstar = true;
                }
                wasStar = true;
            }
            else if (!escaped && (c == '\\'))
            {
                escaped = true;
            }
            else
            {
                escaped = false;
                wasStar = false;
                ss.append(c);
            }
        }
        if (leftstar || rightstar || pieces.size() > 1)
        {
            // insert leading and/or trailing "" to anchor ends
            if (rightstar)
            {
                pieces.add("");
            }
            if (leftstar)
            {
                pieces.add(0, "");
            }
        }
        return pieces;
    }

    public static String unparseSubstring(List<String> pieces)
    {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < pieces.size(); i++)
        {
            if (i > 0)
            {
                sb.append("*");
            }
            sb.append(pieces.get(i));
        }
        return sb.toString();
    }

    public static boolean compareSubstring(List<String> pieces, String s)
    {
        // Walk the pieces to match the string
        // There are implicit stars between each piece,
        // and the first and last pieces might be "" to anchor the match.
        // assert (pieces.length > 1)
        // minimal case is <string>*<string>

        boolean result = true;
        int len = pieces.size();

        // Special case, if there is only one piece, then
        // we must perform an equality test.
        if (len == 1)
        {
            return s.equals(pieces.get(0));
        }

        // Otherwise, check whether the pieces match
        // the specified string.

        int index = 0;

loop:   for (int i = 0; i < len; i++)
        {
            String piece = pieces.get(i);

            // If this is the first piece, then make sure the
            // string starts with it.
            if (i == 0)
            {
                if (!s.startsWith(piece))
                {
                    result = false;
                    break loop;
                }
            }

            // If this is the last piece, then make sure the
            // string ends with it.
            if (i == len - 1)
            {
                if (s.endsWith(piece))
                {
                    result = true;
                }
                else
                {
                    result = false;
                }
                break loop;
            }

            // If this is neither the first or last piece, then
            // make sure the string contains it.
            if ((i > 0) && (i < (len - 1)))
            {
                index = s.indexOf(piece, index);
                if (index < 0)
                {
                    result = false;
                    break loop;
                }
            }

            // Move string index beyond the matching piece.
            index += piece.length();
        }

        return result;
    }

    /**
     * Intepret a string as a URI relative to the current working directory.
     * @param session the session (where the CWD is stored)
     * @param relativeUri the input URI
     * @return the resulting URI as a string
     * @throws IOException
     */
    public static String resolveUri(CommandSession session, String relativeUri) throws IOException
    {
        File cwd = (File) session.get(CWD);
        if (cwd == null)
        {
            cwd = new File("").getCanonicalFile();
            session.put(CWD, cwd);
        }
        if ((relativeUri == null) || (relativeUri.length() == 0))
        {
            return relativeUri;
        }

        URI curUri = cwd.toURI();
        URI newUri = curUri.resolve(relativeUri);
        return newUri.toString();
    }
}


text:
from pandas import read_csv
from pandas import set_option
import matplotlib.pyplot as plt, mpld3
from Interface import plotmgr, utility
import simplejson as json
import jsonpickle

def loaddata(name, filename, columns=None):
    filepath = "./data/" + name + "/dataset/" + filename

    if not columns is None:
        df = read_csv(filepath, columns=columns)
    else:
        df = read_csv(filepath)

    return df

def data_columns(name, filename):
    df = loaddata(name, filename)
    result = list(df)

    return result

def basic_info(name, filename, columns=None, count = 5):
    df = loaddata(name, filename, columns)
    result = {}
    h = df.head(count)
    result["peek"] = h.to_html()
    result["stats"] = df.describe().to_html()
    result["shape"] = df.shape
    result["dtypes"] = json.loads(df.dtypes.to_json())
    result["attr_corr"] = df.corr(method='pearson').to_html()
    result["skew"] = json.loads(df.skew().to_json())

    return result

def plot(name, filename, method, options=None):
    df = loaddata(name, filename)
    d = []
    if method == "factor":
        utility.validateParam(options, "x")
        utility.validateParam(options, "y")
        d = plotmgr.Axis_FactorPlot(df, options["x"], options["y"], utility.getVal(options, "hue")
                                    , utility.getVal(options, "row"), utility.getVal(options, "col")
                                    , utility.getVal(options, "kind", "point"))
    elif method == "lm":
        utility.validateParam(options, "x")
        utility.validateParam(options, "y")
        d = plotmgr.Axis_LMPlot(df, options["x"], options["y"], utility.getVal(options, "hue"))
    elif method == "pair":
        d = plotmgr.Axis_PairPlot(df, utility.getVal(options, "vars"), utility.getVal(options, "hue"))
    elif method == "joint":
        utility.validateParam(options, "x")
        utility.validateParam(options, "y")
        d = plotmgr.Axis_JointPlot(df, options["x"], options["y"], utility.getVal(options, "kind", "scatter"))
    elif method == "strip":
        utility.validateParam(options, "x")
        d = plotmgr.Cat_StripPlot(df, options["x"], utility.getVal(options, "y"),
                                utility.getVal(options, "hue"), utility.getVal(options, "jitter", False))
    elif method == "swarm":
        utility.validateParam(options, "x")
        d = plotmgr.Cat_SwarmPlot(df, options["x"], utility.getVal(options, "y"), utility.getVal(options, "hue"))
    elif method == "box":
        utility.validateParam(options, "x")
        d = plotmgr.Cat_BoxPlot(df, options["x"], utility.getVal(options, "y"), utility.getVal(options, "hue"))
    elif method == "violin":
        utility.validateParam(options, "x")
        d = plotmgr.Cat_ViolinPlot(df, options["x"], utility.getVal(options, "y"), utility.getVal(options, "hue"))
    elif method == "lv":
        utility.validateParam(options, "x")
        d = plotmgr.Cat_LVPlot(df, options["x"], utility.getVal(options, "y"), utility.getVal(options, "hue"))
    elif method == "point":
        utility.validateParam(options, "x")
        d = plotmgr.Cat_LVPlot(df, options["x"], utility.getVal(options, "y"), utility.getVal(options, "hue"))
    elif method == "bar":
        utility.validateParam(options, "x")
        d = plotmgr.Cat_BarPlot(df, options["x"], utility.getVal(options, "y"), utility.getVal(options, "hue"))
    elif method == "count":
        utility.validateParam(options, "x")
        d = plotmgr.Cat_CountPlot(df, options["x"], utility.getVal(options, "y"), utility.getVal(options, "hue"))
    elif method == "reg":
        utility.validateParam(options, "x")
        utility.validateParam(options, "y")
        d = plotmgr.Reg_RegPlot(df, options["x"], utility.getVal(options, "y"))
    elif method == "kde":
        utility.validateParam(options, "x")
        utility.validateParam(options, "y")
        d = plotmgr.Reg_RegPlot(df, options["x"], utility.getVal(options, "y"))
    elif method == "rug":
        utility.validateParam(options, "x")
        d = plotmgr.Reg_RugPlot(df, options["x"])
    return d


text:
require 'spec_helper'

describe Puppet::Parser::Functions.function(:resources_deep_merge) do
  let(:scope) { PuppetlabsSpec::PuppetInternals.scope }

  it "should exist" do
    expect(Puppet::Parser::Functions.function("resources_deep_merge")).to eq("function_resources_deep_merge")
  end

  it "should raise an ArgumentError if there is less than 1 arguments" do
    expect { scope.function_resources_deep_merge([]) }.to( raise_error(ArgumentError))
  end

  it "should not compile when 1 argument is passed" do
    my_hash={'one' => 1}
    expect { scope.function_resources_deep_merge([my_hash]) }.to( raise_error(ArgumentError))
  end

  it 'should require all parameters are hashes' do
    expect { scope.function_resources_deep_merge([{}, '2']) }.to( raise_error(ArgumentError))
  end

  describe 'when calling resources_deep_merge on a resource and a defaults hash' do
    it 'should be able to deep_merge a resource hash and a defaults hash' do
      resources = {
        'one' => {
          'attributes' => {
            'user' => '1',
            'pass' => '1'
          }
        },
        'two' => {
          'attributes' => {
            'user' => '2',
            'pass' => '2'
          }
        }
      }
      defaults = {
        'ensure' => 'present',
        'attributes' => {
          'type' => 'psql'
        }
      }
      result = scope.function_resources_deep_merge([resources, defaults])
      expect(result['one']).to eq({'ensure' => 'present', 'attributes' => {'type'=>'psql', 'user' => '1', 'pass' => '1'}})
      expect(result['two']).to eq({'ensure' => 'present', 'attributes' => {'type'=>'psql', 'user' => '2', 'pass' => '2'}})
    end
  end

end


text:
<?php

namespace PDepend\Source\Language\PHP;

use PDepend\AbstractTest;

/**
 * Test case for the {@link \PDepend\Source\Language\PHP\PHPParserGeneric} class.
 *
 * @copyright 2008-2013 Manuel Pichler. All rights reserved.
 * @license http://www.opensource.org/licenses/bsd-license.php BSD License
 * @since     2.1.0
 *
 * @covers \PDepend\Source\Language\PHP\AbstractPHPParser
 * @covers \PDepend\Source\Language\PHP\PHPParserGeneric
 * @group unittest
 * @link https://github.com/pdepend/pdepend/issues/180
 */
class PHPParserGenericVersion56Test extends AbstractTest
{
    /**
     * testShiftLeftInConstantInitializer
     *
     * @return void
     */
    public function testShiftLeftInConstantInitializer()
    {
        $class = $this->getFirstClassForTestCase();
        $const = $class->getChild(0);

        $this->assertInstanceOf('PDepend\\Source\\AST\\ASTConstantDefinition', $const);
    }

    /**
     * testShiftRightInConstantInitializer
     *
     * @return void
     */
    public function testShiftRightInConstantInitializer()
    {
        $class = $this->getFirstClassForTestCase();
        $const = $class->getChild(0);

        $this->assertInstanceOf('PDepend\\Source\\AST\\ASTConstantDefinition', $const);
    }

    /**
     * testShiftLeftInConstantInitializer
     *
     * @return void
     */
    public function testMultipleShiftLeftInConstantInitializer()
    {
        $class = $this->getFirstClassForTestCase();
        $const = $class->getChild(0);

        $this->assertInstanceOf('PDepend\\Source\\AST\\ASTConstantDefinition', $const);
    }

    /**
     * testShiftRightInConstantInitializer
     *
     * @return void
     */
    public function testMultipleShiftRightInConstantInitializer()
    {
        $class = $this->getFirstClassForTestCase();
        $const = $class->getChild(0);

        $this->assertInstanceOf('PDepend\\Source\\AST\\ASTConstantDefinition', $const);
    }
}


text:
FROM golang:1.11 as build

ADD . /go/src/github.com/google/trillian
WORKDIR /go/src/github.com/google/trillian

ARG GOFLAGS=""
RUN go get ./server/trillian_log_signer ./scripts/licenses
RUN licenses save ./server/trillian_log_signer --save_path /THIRD_PARTY_NOTICES

FROM gcr.io/distroless/base

COPY --from=build /go/bin/trillian_log_signer /
COPY --from=build /THIRD_PARTY_NOTICES /THIRD_PARTY_NOTICES

ENTRYPOINT ["/trillian_log_signer"]


text:
<?xml version="1.0" encoding="utf-8"?>
<menu
  xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:id="@id/action_goto_resource" android:title="" app:showAsAction="always" />
</menu>


text:
package com.google.inject.internal.aop;

import static java.lang.reflect.Modifier.PUBLIC;
import static java.lang.reflect.Modifier.STATIC;
import static org.objectweb.asm.Opcodes.ACONST_NULL;
import static org.objectweb.asm.Opcodes.ARETURN;
import static org.objectweb.asm.Opcodes.F_SAME;
import static org.objectweb.asm.Opcodes.ILOAD;

import java.lang.invoke.MethodHandle;
import java.lang.reflect.Constructor;
import java.lang.reflect.Executable;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.NavigableMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.ToIntFunction;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Type;

/**
 * Support code for generating enhancer/fast-class glue.
 *
 *
Each glue class has a trampoline that accepts an index, context object, and argument array:
 *
 *

 * public static Object GUICE$TRAMPOLINE(int index, Object context, Object[] args) {
 *   switch (index) {
 *     case 0: {
 *       return ...;
 *     }
 *     case 1: {
 *       return ...;
 *     }
 *   }
 *   return null;
 * }
 *

 *
 * Each indexed statement in the trampoline invokes a constructor or method, returning the result.
 * The expected context object depends on the statement; it could be the invocation target, some
 * additional constructor context, or it may be unused. Arguments are unpacked from the array onto
 * the call stack, unboxing or casting them as necessary. Primitive results are autoboxed before
 * being returned.
 *
 *
Where possible the trampoline is converted into a lookup {@link Function} mapping an integer
 * to an invoker function, each invoker represented as a {@link BiFunction} that accepts a context
 * object plus argument array and returns the result. These functional interfaces are used to avoid
 * introducing a dependency from the glue class to Guice specific types. This means the glue class
 * can be loaded anywhere that can see the host class, it doesn't need access to Guice's own {@link
 * ClassLoader}. (In other words it removes any need for bridge {@link ClassLoader}s.)
 *
 * @author mcculls@gmail.com (Stuart McCulloch)
 */
abstract class AbstractGlueGenerator {

  protected static final String GENERATED_SOURCE = "<generated>";

  protected static final String TRAMPOLINE_NAME = "GUICE$TRAMPOLINE";

  /**
   * The trampoline method takes an index, along with a context object and an array of argument
   * objects, and invokes the appropriate constructor/method returning the result as an object.
   */
  protected static final String TRAMPOLINE_DESCRIPTOR =
      "(ILjava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;";

  protected final Class<?> hostClass;

  protected final String hostName;

  protected final String proxyName;

  private static final AtomicInteger COUNTER = new AtomicInteger();

  protected AbstractGlueGenerator(Class<?> hostClass, String marker) {
    this.hostClass = hostClass;
    this.hostName = Type.getInternalName(hostClass);
    this.proxyName = proxyName(hostName, marker, hashCode());
  }

  /** Generates a unique name based on the original class name and marker. */
  private static String proxyName(String hostName, String marker, int hash) {
    int id = ((hash & 0x000FFFFF) | (COUNTER.getAndIncrement() << 20));
    String proxyName = hostName + marker + id;
    if (proxyName.startsWith("java/") && !ClassDefining.hasPackageAccess()) {
      proxyName = '$' + proxyName; // can't define java.* glue in same package
    }
    return proxyName;
  }

  /** Generates the enhancer/fast-class and returns a mapping from signature to invoker. */
  public final Function<String, BiFunction<Object, Object[], Object>> glue(
      NavigableMap<String, Executable> glueMap) {
    final MethodHandle invokerTable;
    try {
      byte[] bytecode = generateGlue(glueMap.values());
      Class<?> glueClass = ClassDefining.define(hostClass, bytecode);
      invokerTable = lookupInvokerTable(glueClass);
    } catch (Throwable e) {
      throw new GlueException("Problem generating " + proxyName, e);
    }

    // build optimized index for these signatures and bind it to the generated invokers
    ToIntFunction<String> signatureTable = ImmutableStringTrie.buildTrie(glueMap.keySet());
    return bindSignaturesToInvokers(signatureTable, invokerTable);
  }

  /** Generates enhancer/fast-class bytecode for the given constructors/methods. */
  protected abstract byte[] generateGlue(Collection<Executable> members);

  /** Lookup the invoker table; this may be represented by a function or a trampoline. */
  protected abstract MethodHandle lookupInvokerTable(Class<?> glueClass) throws Throwable;

  /** Combines the signature and invoker tables into a mapping from signature to invoker. */
  private static Function<String, BiFunction<Object, Object[], Object>> bindSignaturesToInvokers(
      ToIntFunction<String> signatureTable, MethodHandle invokerTable) {

    // single-argument method; the table must be a function from integer index to invoker function
    if (invokerTable.type().parameterCount() == 1) {
      return signature -> {
        try {
          // pass this signature's index into the table function to retrieve the invoker
          return (BiFunction<Object, Object[], Object>)
              invokerTable.invokeExact(signatureTable.applyAsInt(signature));
        } catch (Throwable e) {
          throw asIfUnchecked(e);
        }
      };
    }

    // otherwise must be a trampoline method that takes the index and invoker arguments all at once
    return signature -> {
      // bind the index as soon as we have the signature...
      int index = signatureTable.applyAsInt(signature);
      return (instance, arguments) -> {
        try {
          // ...but delay calling trampoline until invocation time when we have the other arguments
          return invokerTable.invokeExact(index, instance, arguments);
        } catch (Throwable e) {
          throw asIfUnchecked(e);
        }
      };
    };
  }

  /** Generics trick to get compiler to treat given exception as if unchecked (as JVM does). */
  @SuppressWarnings("unchecked")
  private static <E extends Throwable> RuntimeException asIfUnchecked(Throwable e) throws E {
    throw (E) e;
  }

  /**
   * Generate trampoline that takes an index, along with a context object and array of argument
   * objects, and invokes the appropriate constructor/method returning the result as an object.
   */
  protected final void generateTrampoline(ClassWriter cw, Collection<Executable> members) {
    MethodVisitor mv =
        cw.visitMethod(PUBLIC | STATIC, TRAMPOLINE_NAME, TRAMPOLINE_DESCRIPTOR, null, null);
    mv.visitCode();

    Label[] labels = new Label[members.size()];
    Arrays.setAll(labels, i -> new Label());
    Label defaultLabel = new Label();

    mv.visitVarInsn(ILOAD, 0);
    mv.visitTableSwitchInsn(0, labels.length - 1, defaultLabel, labels);

    int labelIndex = 0;
    for (Executable member : members) {
      mv.visitLabel(labels[labelIndex++]);
      mv.visitFrame(F_SAME, 0, null, 0, null);
      if (member instanceof Constructor<?>) {
        generateConstructorInvoker(mv, (Constructor<?>) member);
      } else {
        generateMethodInvoker(mv, (Method) member);
      }
      mv.visitInsn(ARETURN);
    }

    mv.visitLabel(defaultLabel);
    mv.visitFrame(F_SAME, 0, null, 0, null);
    mv.visitInsn(ACONST_NULL);
    mv.visitInsn(ARETURN);

    mv.visitMaxs(0, 0);
    mv.visitEnd();
  }

  /** Generate invoker that takes a context and an argument array and calls the constructor. */
  protected abstract void generateConstructorInvoker(MethodVisitor mv, Constructor<?> constructor);

  /** Generate invoker that takes an instance and an argument array and calls the method. */
  protected abstract void generateMethodInvoker(MethodVisitor mv, Method method);
}


text:
import { Component } from '@angular/core';

@Component({
  template: `

Roles Missing

      It appears that you are missing the proper roles. Please contact your administrator to rectify the
      situation.

  `
})
export class RolesMissingComponent {
}


text:
<?php

namespace MongoDB\Tests\Collection\CrudSpec;

/**
 * CRUD spec functional tests for deleteOne().
 *
 * @see https://github.com/mongodb/specifications/tree/master/source/crud/tests
 */
class DeleteOneFunctionalTest extends FunctionalTestCase
{
    public function setUp()
    {
        parent::setUp();

        $this->createFixtures(3);
    }

    public function testDeleteOneWhenManyDocumentsMatch()
    {
        $filter = array('_id' => array('$gt' => 1));

        $result = $this->collection->deleteOne($filter);
        $this->assertSame(1, $result->getDeletedCount());

        $expected = array(
            array('_id' => 1, 'x' => 11),
            array('_id' => 3, 'x' => 33),
        );

        $this->assertSame($expected, $this->collection->find()->toArray());
    }

    public function testDeleteOneWhenOneDocumentMatches()
    {
        $filter = array('_id' => 2);

        $result = $this->collection->deleteOne($filter);
        $this->assertSame(1, $result->getDeletedCount());

        $expected = array(
            array('_id' => 1, 'x' => 11),
            array('_id' => 3, 'x' => 33),
        );

        $this->assertSame($expected, $this->collection->find()->toArray());
    }

    public function testDeleteOneWhenNoDocumentsMatch()
    {
        $filter = array('_id' => 4);

        $result = $this->collection->deleteOne($filter);
        $this->assertSame(0, $result->getDeletedCount());

        $expected = array(
            array('_id' => 1, 'x' => 11),
            array('_id' => 2, 'x' => 22),
            array('_id' => 3, 'x' => 33),
        );

        $this->assertSame($expected, $this->collection->find()->toArray());
    }
}