text:
set -e
set -x

virtualenv -p python3 .
source ./bin/activate

chmod +x data_files
chmod +x tmp

pip install tensorflow
pip install -r requirements.txt
python -m main_rllim_on_real_data
python -m main_local_dynamics_recovery

redpajama_set_name: RedPajamaGithub


text:
from ._app_configuration_management_client import AppConfigurationManagementClient
__all__ = ['AppConfigurationManagementClient']

try:
    from ._patch import patch_sdk  # type: ignore
    patch_sdk()
except ImportError:
    pass


text:
class AuthHelper(object):
    def IsUserAdmin(self, user_id):
        if int(user_id) % 2 == 0:
            return True
        else:
            return False


text:
<Alloy>
	<Window id="win">
		<Require type="widget" src="pp.sliderMenu" id="ds"/>
	</Window>
</Alloy>


text:
package techreborn.compat.jei.chemicalReactor;

import mezz.jei.api.IGuiHelper;
import mezz.jei.api.IJeiHelpers;
import mezz.jei.api.gui.IDrawableAnimated;
import mezz.jei.api.gui.IDrawableStatic;
import net.minecraft.client.Minecraft;
import reborncore.common.powerSystem.PowerSystem;
import techreborn.api.recipe.machines.ChemicalReactorRecipe;
import techreborn.client.gui.TRBuilder;
import techreborn.compat.jei.BaseRecipeWrapper;

import javax.annotation.Nonnull;

public class ChemicalReactorRecipeWrapper extends BaseRecipeWrapper<ChemicalReactorRecipe> {
	private final IDrawableAnimated progressright;
	private final IDrawableAnimated progressleft;

	public ChemicalReactorRecipeWrapper(
		@Nonnull
			IJeiHelpers jeiHelpers,
		@Nonnull
			ChemicalReactorRecipe baseRecipe) {
		super(baseRecipe);
		IGuiHelper guiHelper = jeiHelpers.getGuiHelper();
		IDrawableStatic progressrightStatic = guiHelper.createDrawable(TRBuilder.GUI_SHEET, 100, 151, 16, 10);
		IDrawableStatic progressleftStatic = guiHelper.createDrawable(TRBuilder.GUI_SHEET, 84, 161, 16, 10);

		int ticksPerCycle = baseRecipe.tickTime(); // speed up the animation

		this.progressright = guiHelper.createAnimatedDrawable(progressrightStatic, ticksPerCycle, IDrawableAnimated.StartDirection.LEFT, false);
		this.progressleft = guiHelper.createAnimatedDrawable(progressleftStatic, ticksPerCycle, IDrawableAnimated.StartDirection.RIGHT, false);
	}

	@Override
	public void drawInfo(Minecraft minecraft, int recipeWidth, int recipeHeight, int mouseX, int mouseY) {
		super.drawInfo(minecraft, recipeWidth, recipeHeight, mouseX, mouseY);
		progressright.draw(minecraft, 25, 12);
		progressleft.draw(minecraft, 75, 12);

		int y = 30;
		int lineHeight = minecraft.fontRenderer.FONT_HEIGHT;

		minecraft.fontRenderer.drawString(baseRecipe.tickTime / 20 + " seconds", (recipeWidth / 2 - minecraft.fontRenderer.getStringWidth(baseRecipe.tickTime / 20 + " seconds") / 2), y, 0x444444);
		minecraft.fontRenderer.drawString(PowerSystem.getLocaliszedPowerFormatted(baseRecipe.euPerTick * baseRecipe.tickTime), (recipeWidth / 2 - minecraft.fontRenderer.getStringWidth(PowerSystem.getLocaliszedPowerFormatted(baseRecipe.euPerTick * baseRecipe.tickTime)) / 2), y + lineHeight, 0x444444);
	}
}


text: Participación ciudadana


text:
import os
import numpy as np
from sklearn.externals import joblib
from matplotlib import pyplot as plt
import time
import util
import ipdb

def assess_threshold_and_decide(
    gradient_traj_by_time,
    curve_owner,
    state_no,
    figure_save_path,
):

    fig = plt.figure(1)
    ax = fig.add_subplot(111)

    # plot log curves of all trials
    for row_no in range(gradient_traj_by_time.shape[0]):
        trial_name = curve_owner[row_no]
        if row_no == 0:
            ax.plot(gradient_traj_by_time[row_no].tolist()[0], linestyle="dashed", color='gray', label='trials')
        else:
            ax.plot(gradient_traj_by_time[row_no].tolist()[0], linestyle="dashed", color='gray')

    min_gradient = gradient_traj_by_time.min()
    max_gradient = gradient_traj_by_time.max()
    gradient_range = max_gradient-min_gradient

    threshold = min_gradient-gradient_range/2

    title = 'state %s use threshold %s'%(state_no, threshold, )
    ax.set_title(title)

    output_dir = os.path.join(figure_save_path, 'threshold_for_deri_of_diff')

    if not os.path.isdir(output_dir):
        os.makedirs(output_dir)
    ax.axhline(y=threshold, linestyle='solid', color='red')
    fig.savefig(os.path.join(output_dir, "state %s.eps"%(state_no, )), format="eps")
    fig.savefig(os.path.join(output_dir, "state %s.png"%(state_no, )), format="png")

    plt.close(1)

    return threshold

def run(model_save_path,
    figure_save_path,
    threshold_c_value,
    trials_group_by_folder_name):

    trials_group_by_folder_name = util.make_trials_of_each_state_the_same_length(trials_group_by_folder_name)

    one_trial_data_group_by_state = trials_group_by_folder_name.itervalues().next()
    state_amount = len(one_trial_data_group_by_state)

    model_group_by_state = {}
    for state_no in range(1, state_amount+1):
        try:
            model_group_by_state[state_no] = joblib.load(model_save_path+"/model_s%s.pkl"%(state_no,))
        except IOError:
            print 'model of state %s not found'%(state_no,)
            continue

    threshold_group_by_state = {}
    mean_curve_group_by_state = {}

    for state_no in model_group_by_state:

        all_log_curves_of_this_state = []
        curve_owner = []
        for trial_name in trials_group_by_folder_name:
            curve_owner.append(trial_name)
            one_log_curve_of_this_state = []

            one_log_curve_of_this_state = util.fast_log_curve_calculation(
                trials_group_by_folder_name[trial_name][state_no],
                model_group_by_state[state_no]
            )

            all_log_curves_of_this_state.append(one_log_curve_of_this_state)

        # use np matrix to facilitate the computation of mean curve and std
        np_matrix_traj_by_time = np.matrix(all_log_curves_of_this_state)
        mean_of_log_curve = np_matrix_traj_by_time.mean(0)
        diff_traj_by_time = np_matrix_traj_by_time-mean_of_log_curve
        deri_of_diff_traj_by_time = diff_traj_by_time[:, 1:]-diff_traj_by_time[:, :-1]
        mean_curve_group_by_state[state_no] = mean_of_log_curve
        threshold_group_by_state[state_no] = assess_threshold_and_decide(
            deri_of_diff_traj_by_time,
            curve_owner,
            state_no,
            figure_save_path,
        )

    if not os.path.isdir(model_save_path):
        os.makedirs(model_save_path)

    if len(threshold_group_by_state) != 0:
        joblib.dump(threshold_group_by_state, model_save_path+"/threshold_for_deri_of_diff.pkl")
        joblib.dump(mean_curve_group_by_state, model_save_path+"/mean_curve_group_by_state.pkl")


text:
<form action="." {% if form_id %}id="{{ form_id }}"{% endif %} method="{% if method %}{{ method }}{% else %}post{% endif %}" {% if multipart %}enctype="multipart/form-data"{% endif %} class="pure-form {% if aligned %}pure-form-aligned{% else %}pure-form-stacked{% endif %}">
  {% csrf_token %}
  {% if warning %}

      {{ warning }}

  {% endif %}
  {% if form.non_field_errors %}
    {{ form.non_field_errors }}
  {% endif %}
  <fieldset>
    {% if legend %}
      <legend>{{ legend }}</legend>
    {% endif %}
    {% for field in form.visible_fields %}
      {% include 'base/_form_field.html' with field=field %}
    {% endfor %}
    {% if formset %}
      {{ formset.management_form }}
    {% endif %}
    {% for formset_form in formset %}
      <legend>
        {{ formset_legend }}
        {% if formset_add %}{{ forloop.counter|add:formset_add }}{% else %}{{ forloop.counter }}{% endif %}:
      </legend>
      {% for field in formset_form.visible_fields %}
        {% include 'base/_form_field.html' with field=field %}
      {% endfor %}
      {% for hidden in formset_form.hidden_fields %}
        {{ hidden }}
      {% endfor %}
    {% endfor %}

        <input type="submit" {% if submit_id %}id="{{ submit_id }}" {% endif %}value="{% if submit %}{{ submit }}{% else %}Submit{% endif %}" class="pure-button pure-button-primary" />

  </fieldset>
  {% for hidden in form.hidden_fields %}
    {{ hidden }}
  {% endfor %}
  {% if next %}
    <input type="hidden" name="next" value="{{ next }}" />
  {% endif %}
</form>


text:
package ru.stqa.pft.mantis.tests;

import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import ru.lanwen.verbalregex.VerbalExpression;
import ru.stqa.pft.mantis.model.MailMessage;

import java.io.IOException;
import java.util.List;

import static org.testng.Assert.assertTrue;

/**
 * Created by gren on 29.01.2017.
 */
public class ChangeMailTests extends TestBase {

  @BeforeMethod
  public void startMailServer() {
    app.mail().start();
  }

  @Test
  public void testChangeMail() throws IOException {
    String user = "user1485635023776";
    String password = "test123";
    String email = "user1485635023776@localhost.localdomain";

    app.adminHelper().changeMailUser(user);
    List<MailMessage> mailMessages = app.mail().waitForMail(1, 10000);
    String changeMailLink = findChangeMailLink(mailMessages, email);
    app.goTo().link(changeMailLink);
    app.userHelper().changePassword(changeMailLink, password);

    assertTrue(app.newSession().login(user, password));
  }

  private String findChangeMailLink(List<MailMessage> mailMessages, String email) {
    MailMessage mailMessage = mailMessages.stream().filter((m) -> m.to.equals(email)).findFirst().get();
    VerbalExpression regex = VerbalExpression.regex().find("http://").nonSpace().oneOrMore().build();
    return regex.getText(mailMessage.text);
  }

  @AfterMethod(alwaysRun = true)
  public void stopMailServer() {
    app.mail().stop();
  }

}


text:
import pytz
from django.utils.translation import ugettext_lazy as _

from horizon import exceptions
from horizon import forms
from horizon import workflows
from datetime import datetime

from openstack_dashboard import api

import logging
LOG=logging.getLogger(__name__)

class SetSingleTimingAction(workflows.Action):
    single = forms.CharField(label=_("Time"),
                           widget=forms.TextInput(attrs={'type':'datetime-local'}),
                           required=False)

    def clean(self):
        cleaned_data = super(SetSingleTimingAction, self).clean()
        single = cleaned_data.get("single", None)
        if not single:
            msg = _("Must fill time")
            self._errors['single']=self.error_class([msg])
        tz = pytz.timezone(pytz.country_timezones('cn')[0])
        now = datetime.now(tz)
        localtime = datetime(now.year, now.month,\
                              now.day, now.hour, now.minute)
        if single:
            singletime = datetime.strptime(single, "%Y-%m-%dT%H:%M")
            if singletime < localtime:
                msg = _("input time Invalid should not be less than the current time")
                self.errors['single']=self.error_class([msg])
        return cleaned_data

    class Meta:
        name = _("Set Timing")
        slug = 'single_set'
        help_text = _("The time you need to enter is not empty.")

    def __init__(self, request, context, *args, **kwargs):
        super(SetSingleTimingAction, self).__init__(request, context, *args, **kwargs)

    def handle(self, request, data):
        try:
            api.nova.update_timing_time(request, data)
            return True
        except Exception:
            exceptions.handle(request, ignore=True)
            return False

class SetSingleTiming(workflows.Step):
    action_class = SetSingleTimingAction
    depends_on = ("instance_id",)
    contributes = ("single")
    def contribute(self, data, context):
        if data:
            context['checkboxlist']=context.get('instance_id', None)
            context[self.workflow.slug]=self.workflow.slug
            if data.get('single', None):
                context['timing_time']=data['single']
        return context

class SingleTimingBoot(workflows.Workflow):
    slug = "timing_boot"
    name = _("Timing Boot")
    finalize_button_name = _("Save")
    success_message = _("Save instance timing boot time '%s'.")
    failure_message = _("Unable save instance timing boot time '%s'.")
    success_url = "horizon:admin:instances:index"
    default_steps = (SetSingleTiming,)

    def format_status_message(self, message):
        return message % self.context.get('timing_time', 'unknown time')

class SingleTimingShutdown(workflows.Workflow):
    slug = "timing_shutdown"
    name = _("Timing Shutdown")
    finalize_button_name = _("Save")
    success_message = _("Save instance timing shutdown time '%s'.")
    failure_message = _("Unable save instance timing showdown time '%s'.")
    success_url = "horizon:admin:instances:index"
    default_steps = (SetSingleTiming,)

    def format_status_message(self, message):
        return message % self.context.get('timing_time', 'unknown time')


text:
/*
 * JS configuration macros.
 */
#ifndef JS_VERSION
#define JS_VERSION 185
#endif

/*
 * Compile-time JS version configuration.  The JS version numbers lie on the
 * number line like so:
 *
 * 1.0     1.1     1.2     1.3     1.4     ECMAv3  1.5     1.6     1.7     1.8     ECMAv5
 *         ^                       ^
 *         |                       |
 *         basis for ECMAv1        close to ECMAv2
 *
 * where ECMAv3 stands for ECMA-262 Edition 3, and ECMAv5 stands for Edition 5.
 * See the runtime version enum JSVersion in jspubtd.h. Code in the engine can
 * therefore count on version <= JSVERSION_1_4 to mean "before the Third
 * Edition of ECMA-262" and version > JSVERSION_1_4 to mean "at or after the
 * Third Edition".
 *
 * In the (likely?) event that SpiderMonkey grows to implement JavaScript 2.0,
 * the version number to use would be near 200, or greater.
 *
 * The JS_VERSION_ECMA_3 version is the minimal configuration conforming to
 * the ECMA-262 Edition 3 specification.  Use it for minimal embeddings, where
 * you're sure you don't need any of the extensions disabled in this version.
 * In order to facilitate testing, JS_HAS_OBJ_PROTO_PROP is defined as part of
 * the JS_VERSION_ECMA_3_TEST version.
 *
 * To keep things sane in the modern age, where we need exceptions in order to
 * implement, e.g., iterators and generators, we are dropping support for all
 * versions <= 1.4.
 */
#define JS_VERSION_ECMA_3       148
#define JS_VERSION_ECMA_3_TEST  149

#if JS_VERSION == JS_VERSION_ECMA_3 ||                                        \
    JS_VERSION == JS_VERSION_ECMA_3_TEST

#define JS_HAS_STR_HTML_HELPERS 0       /* has str.anchor, str.bold, etc. */
#define JS_HAS_PERL_SUBSTR      0       /* has str.substr */
#if JS_VERSION == JS_VERSION_ECMA_3_TEST
#define JS_HAS_OBJ_PROTO_PROP   1       /* has o.__proto__ etc. */
#else
#define JS_HAS_OBJ_PROTO_PROP   0       /* has o.__proto__ etc. */
#endif
#define JS_HAS_OBJ_WATCHPOINT   0       /* has o.watch and o.unwatch */
#define JS_HAS_EVAL_THIS_SCOPE  0       /* Math.eval is same as with (Math) */
#define JS_HAS_SHARP_VARS       0       /* has #n=, #n# for object literals */
#define JS_HAS_SCRIPT_OBJECT    0       /* has (new Script("x++")).exec() */
#define JS_HAS_XDR              0       /* has XDR API and internal support */
#define JS_HAS_XDR_FREEZE_THAW  0       /* has XDR freeze/thaw script methods */
#define JS_HAS_TOSOURCE         0       /* has Object/Array toSource method */
#define JS_HAS_DEBUGGER_KEYWORD 0       /* has hook for debugger keyword */
#define JS_HAS_CATCH_GUARD      0       /* has exception handling catch guard */
#define JS_HAS_SPARSE_ARRAYS    0       /* array methods preserve empty elems */
#define JS_HAS_GETTER_SETTER    0       /* has JS2 getter/setter functions */
#define JS_HAS_UNEVAL           0       /* has uneval() top-level function */
#define JS_HAS_CONST            0       /* has JS2 const as alternative var */
#define JS_HAS_FUN_EXPR_STMT    0       /* has function expression statement */
#define JS_HAS_NO_SUCH_METHOD   0       /* has o.__noSuchMethod__ handler */
#define JS_HAS_XML_SUPPORT      0       /* has ECMAScript for XML support */
#define JS_HAS_ARRAY_EXTRAS     0       /* has indexOf and Lispy extras */
#define JS_HAS_GENERATORS       0       /* has yield in generator function */
#define JS_HAS_BLOCK_SCOPE      0       /* has block scope via let/arraycomp */
#define JS_HAS_DESTRUCTURING    0       /* has [a,b] = ... or {p:a,q:b} = ... */
#define JS_HAS_GENERATOR_EXPRS  0       /* has (expr for (lhs in iterable)) */
#define JS_HAS_EXPR_CLOSURES    0       /* has function (formals) listexpr */

#elif JS_VERSION < 150

#error "unsupported JS_VERSION"

#elif JS_VERSION == 150

#define JS_HAS_STR_HTML_HELPERS 1       /* has str.anchor, str.bold, etc. */
#define JS_HAS_PERL_SUBSTR      1       /* has str.substr */
#define JS_HAS_OBJ_PROTO_PROP   1       /* has o.__proto__ etc. */
#define JS_HAS_OBJ_WATCHPOINT   1       /* has o.watch and o.unwatch */
#define JS_HAS_EVAL_THIS_SCOPE  1       /* Math.eval is same as with (Math) */
#define JS_HAS_SHARP_VARS       1       /* has #n=, #n# for object literals */
#define JS_HAS_SCRIPT_OBJECT    1       /* has (new Script("x++")).exec() */
#define JS_HAS_XDR              1       /* has XDR API and internal support */
#define JS_HAS_XDR_FREEZE_THAW  0       /* has XDR freeze/thaw script methods */
#define JS_HAS_TOSOURCE         1       /* has Object/Array toSource method */
#define JS_HAS_DEBUGGER_KEYWORD 1       /* has hook for debugger keyword */
#define JS_HAS_CATCH_GUARD      1       /* has exception handling catch guard */
#define JS_HAS_SPARSE_ARRAYS    0       /* array methods preserve empty elems */
#define JS_HAS_GETTER_SETTER    1       /* has JS2 getter/setter functions */
#define JS_HAS_UNEVAL           1       /* has uneval() top-level function */
#define JS_HAS_CONST            1       /* has JS2 const as alternative var */
#define JS_HAS_FUN_EXPR_STMT    1       /* has function expression statement */
#define JS_HAS_NO_SUCH_METHOD   1       /* has o.__noSuchMethod__ handler */
#define JS_HAS_XML_SUPPORT      0       /* has ECMAScript for XML support */
#define JS_HAS_ARRAY_EXTRAS     0       /* has indexOf and Lispy extras */
#define JS_HAS_GENERATORS       0       /* has yield in generator function */
#define JS_HAS_BLOCK_SCOPE      0       /* has block scope via let/arraycomp */
#define JS_HAS_DESTRUCTURING    0       /* has [a,b] = ... or {p:a,q:b} = ... */
#define JS_HAS_GENERATOR_EXPRS  0       /* has (expr for (lhs in iterable)) */
#define JS_HAS_EXPR_CLOSURES    0       /* has function (formals) listexpr */

#elif JS_VERSION == 160

#define JS_HAS_STR_HTML_HELPERS 1       /* has str.anchor, str.bold, etc. */
#define JS_HAS_PERL_SUBSTR      1       /* has str.substr */
#define JS_HAS_OBJ_PROTO_PROP   1       /* has o.__proto__ etc. */
#define JS_HAS_OBJ_WATCHPOINT   1       /* has o.watch and o.unwatch */
#define JS_HAS_EVAL_THIS_SCOPE  1       /* Math.eval is same as with (Math) */
#define JS_HAS_SHARP_VARS       1       /* has #n=, #n# for object literals */
#define JS_HAS_SCRIPT_OBJECT    1       /* has (new Script("x++")).exec() */
#define JS_HAS_XDR              1       /* has XDR API and internal support */
#define JS_HAS_XDR_FREEZE_THAW  0       /* has XDR freeze/thaw script methods */
#define JS_HAS_TOSOURCE         1       /* has Object/Array toSource method */
#define JS_HAS_DEBUGGER_KEYWORD 1       /* has hook for debugger keyword */
#define JS_HAS_CATCH_GUARD      1       /* has exception handling catch guard */
#define JS_HAS_SPARSE_ARRAYS    0       /* array methods preserve empty elems */
#define JS_HAS_GETTER_SETTER    1       /* has JS2 getter/setter functions */
#define JS_HAS_UNEVAL           1       /* has uneval() top-level function */
#define JS_HAS_CONST            1       /* has JS2 const as alternative var */
#define JS_HAS_FUN_EXPR_STMT    1       /* has function expression statement */
#define JS_HAS_NO_SUCH_METHOD   1       /* has o.__noSuchMethod__ handler */
#define JS_HAS_XML_SUPPORT      1       /* has ECMAScript for XML support */
#define JS_HAS_ARRAY_EXTRAS     1       /* has indexOf and Lispy extras */
#define JS_HAS_GENERATORS       0       /* has yield in generator function */
#define JS_HAS_BLOCK_SCOPE      0       /* has block scope via let/arraycomp */
#define JS_HAS_DESTRUCTURING    0       /* has [a,b] = ... or {p:a,q:b} = ... */
#define JS_HAS_GENERATOR_EXPRS  0       /* has (expr for (lhs in iterable)) */
#define JS_HAS_EXPR_CLOSURES    0       /* has function (formals) listexpr */

#elif JS_VERSION == 170

#define JS_HAS_STR_HTML_HELPERS 1       /* has str.anchor, str.bold, etc. */
#define JS_HAS_PERL_SUBSTR      1       /* has str.substr */
#define JS_HAS_OBJ_PROTO_PROP   1       /* has o.__proto__ etc. */
#define JS_HAS_OBJ_WATCHPOINT   1       /* has o.watch and o.unwatch */
#define JS_HAS_EVAL_THIS_SCOPE  1       /* Math.eval is same as with (Math) */
#define JS_HAS_SHARP_VARS       1       /* has #n=, #n# for object literals */
#define JS_HAS_SCRIPT_OBJECT    0       /* has (new Script("x++")).exec() */
#define JS_HAS_XDR              1       /* has XDR API and internal support */
#define JS_HAS_XDR_FREEZE_THAW  0       /* has XDR freeze/thaw script methods */
#define JS_HAS_TOSOURCE         1       /* has Object/Array toSource method */
#define JS_HAS_DEBUGGER_KEYWORD 1       /* has hook for debugger keyword */
#define JS_HAS_CATCH_GUARD      1       /* has exception handling catch guard */
#define JS_HAS_SPARSE_ARRAYS    0       /* array methods preserve empty elems */
#define JS_HAS_GETTER_SETTER    1       /* has JS2 getter/setter functions */
#define JS_HAS_UNEVAL           1       /* has uneval() top-level function */
#define JS_HAS_CONST            1       /* has JS2 const as alternative var */
#define JS_HAS_FUN_EXPR_STMT    1       /* has function expression statement */
#define JS_HAS_NO_SUCH_METHOD   1       /* has o.__noSuchMethod__ handler */
#define JS_HAS_XML_SUPPORT      1       /* has ECMAScript for XML support */
#define JS_HAS_ARRAY_EXTRAS     1       /* has indexOf and Lispy extras */
#define JS_HAS_GENERATORS       1       /* has yield in generator function */
#define JS_HAS_BLOCK_SCOPE      1       /* has block scope via let/arraycomp */
#define JS_HAS_DESTRUCTURING    1       /* has [a,b] = ... or {p:a,q:b} = ... */
#define JS_HAS_GENERATOR_EXPRS  0       /* has (expr for (lhs in iterable)) */
#define JS_HAS_EXPR_CLOSURES    0       /* has function (formals) listexpr */

#elif 180 <= JS_VERSION && JS_VERSION <= 185

#define JS_HAS_STR_HTML_HELPERS 1       /* has str.anchor, str.bold, etc. */
#define JS_HAS_PERL_SUBSTR      1       /* has str.substr */
#define JS_HAS_OBJ_PROTO_PROP   1       /* has o.__proto__ etc. */
#define JS_HAS_OBJ_WATCHPOINT   1       /* has o.watch and o.unwatch */
#define JS_HAS_EVAL_THIS_SCOPE  1       /* Math.eval is same as with (Math) */
#define JS_HAS_SHARP_VARS       1       /* has #n=, #n# for object literals */
#define JS_HAS_SCRIPT_OBJECT    0       /* has (new Script("x++")).exec() */
#define JS_HAS_XDR              1       /* has XDR API and internal support */
#define JS_HAS_XDR_FREEZE_THAW  0       /* has XDR freeze/thaw script methods */
#define JS_HAS_TOSOURCE         1       /* has Object/Array toSource method */
#define JS_HAS_DEBUGGER_KEYWORD 1       /* has hook for debugger keyword */
#define JS_HAS_CATCH_GUARD      1       /* has exception handling catch guard */
#define JS_HAS_SPARSE_ARRAYS    0       /* array methods preserve empty elems */
#define JS_HAS_GETTER_SETTER    1       /* has JS2 getter/setter functions */
#define JS_HAS_UNEVAL           1       /* has uneval() top-level function */
#define JS_HAS_CONST            1       /* has JS2 const as alternative var */
#define JS_HAS_FUN_EXPR_STMT    1       /* has function expression statement */
#define JS_HAS_NO_SUCH_METHOD   1       /* has o.__noSuchMethod__ handler */
#define JS_HAS_XML_SUPPORT      1       /* has ECMAScript for XML support */
#define JS_HAS_ARRAY_EXTRAS     1       /* has indexOf and Lispy extras */
#define JS_HAS_GENERATORS       1       /* has yield in generator function */
#define JS_HAS_BLOCK_SCOPE      1       /* has block scope via let/arraycomp */
#define JS_HAS_DESTRUCTURING    2       /* has [a,b] = ... or {p:a,q:b} = ... */
#define JS_HAS_GENERATOR_EXPRS  1       /* has (expr for (lhs in iterable)) */
#define JS_HAS_EXPR_CLOSURES    1       /* has function (formals) listexpr */

#else

#error "unknown JS_VERSION"

#endif

/* Features that are present in all versions. */
#define JS_HAS_RESERVED_JAVA_KEYWORDS   1
#define JS_HAS_RESERVED_ECMA_KEYWORDS   1

/* Feature-test macro for evolving destructuring support. */
#define JS_HAS_DESTRUCTURING_SHORTHAND  (JS_HAS_DESTRUCTURING == 2)


text:
package com.voxeo.moho.sip;

import javax.servlet.sip.SipServletRequest;

import com.voxeo.moho.event.CancelEvent;

/**
 * SIP specific {@link com.voxeo.moho.event.CancelEvent CancelEvent}.
 *
 * @author wchen
 *
 */
public interface SIPCancelEvent extends CancelEvent {
  /**
   * @return the SIP CANCEL request.
   */
  SipServletRequest getSipRequest();
}


text:
require 'opal-aasm'
require 'opal-rspec'
require 'jquery/jquery.js'
require 'opal-jquery'
require 'opal/jquery/rspec'
require 'react/react.js'

module ReactTestHelpers
  `var ReactTestUtils = React.addons.TestUtils`

  def renderToDocument(type, options = {})
    element = React.create_element(type, options)
    return renderElementToDocument(element)
  end

  def renderElementToDocument(element)
    instance = Native(`ReactTestUtils.renderIntoDocument(#{element.to_n})`)
    instance.class.include(React::Component::API)
    return instance
  end

  def simulateEvent(event, element, params = {})
    simulator = Native(`ReactTestUtils.Simulate`)
    element = `#{element.to_n}.getDOMNode` unless element.class == Element
    simulator[event.to_s].call(element, params)
  end

  def isElementOfType(element, type)
    `React.addons.TestUtils.isElementOfType(#{element.to_n}, #{type.cached_component_class})`
  end

  def create_element(type, options)
    component = React.create_element(type, options)
    element = `ReactTestUtils.renderIntoDocument(#{component.to_n})`
  end

  def find_dom_node(element)
    `$(React.findDOMNode(element))`
  end

  def get_component_instance(element)
    `#{element}._getOpalInstance.apply(#{element})`
  end

  def build_element(type, options)
    component = React.create_element(type, options)
    element = `ReactTestUtils.renderIntoDocument(#{component.to_n})`
    `$(React.findDOMNode(element))`
  end

  def expect_component_to_eventually(component_class, opts = {}, &block)
    # Calls block after each update of a component until it returns true.  When it does set the expectation to true.
    # Uses the after_update callback of the component_class, then instantiates an element of that class
    # The call back is only called on updates, so the call back is manually called right after the
    # element is created.
    # Because React.rb runs the callback inside the components context, we have to
    # setup a lambda to get back to correct context before executing run_async.
    # Because run_async can only be run once it is protected by clearing element once the test passes.
    element = nil
    check_block = -> () {run_async { element = nil; expect(true).to be(true) } if element and block.call(element) }
    component_class.after_update { check_block.call  }
    element = build_element component_class, opts
    check_block.call
  end

end

RSpec.configure do |config|
  config.include ReactTestHelpers
end


text:
package com.hazelcast.config;

import com.hazelcast.core.HazelcastException;

/**
 * A InvalidConfigurationException is thrown when there is an Invalid Configuration.
 * Invalid Configuration can be a wrong XML Config or logical config errors that are found
 * at real time.
 */
public class InvalidConfigurationException extends HazelcastException {

    /**
     * Creates a InvalidConfigurationException with the given message.
     *
     * @param message the message for the exception
     */
    public InvalidConfigurationException(String message) {
        super(message);
    }

    /**
     * Constructs a new runtime exception with the specified detail message and cause.
     *
     * @param message the message for the runtime exception
     * @param cause   the cause of the runtime exception
     */
    public InvalidConfigurationException(final String message, final Throwable cause) {
        super(message, cause);
    }
}


text:
class CreateMainEntryVariantForms < ActiveRecord::Migration
  def change
    create_table :main_entry_variant_forms do |t|
      t.references :main_entry, index: true
      t.integer :variant_form_id

      t.timestamps
    end
  end
end


text:
sentence = "Break the problem down into small steps, then write out those steps into pseudocode."

def word_reverser(sentence)
  word_array = []
  letter_array = []
  word_array = sentence.split(" ")
  letter_array = word_array.map do |word|
    word.split("")
  end
  return reverse_array_of_split_words(letter_array).join(" ")
end

def reverse_array_of_split_words(split_word_array)
  split_word_array.map do |word|
    # p word
    reversed_word = []
    i = word.length - 1

    while i >= 0
      reversed_word << word[i]
      i -= 1
    end

    reversed_word.join("")

  end
end

p word_reverser(sentence)

# Refactored Solution

sentence = "Break the problem down into small steps, then write out those steps into pseudocode."

def reverse_word(sentence)
  array_sentence = []
  array_sentence = sentence.split(" ")
  array_sentence.each do |x|
    x.reverse!
  end
  p array_sentence
end

reverse_word(sentence)

# Reflection


text:
Renders pane footer at the bottom of the `<Pane>`-component containing a form.

### Basic (Default) Usage

The component itself only sets up the styling of the footer and the contents (`renderStart` and `renderEnd` props) are completely up to the developer.
```js
import { Pane, PaneFooter } from '@folio/stripes/components';

const footer = (
  <PaneFooter
    renderStart={<Button>Cancel</Button>}
    renderEnd={<Button>Save</Button>}
    className={css.paneFooterClass}
    innerClassName={css.paneFooterContentClass}
  />
);

<Pane footer={footer} ... >
  Pane Content
</Pane>
```

### Advanced (Customized) Usage

The component styling and content are completely up to the developer.
```js
import { Pane, PaneFooter, Button } from '@folio/stripes/components';

const footer = (
  <PaneFooter footerClass={css.paneFooter}>
    <div className={css.paneFooterContent}>
      <Button onClick={() => {...}}>
        Cancel
      </Button>
      <Button
        buttonStyle="primary"
        type="submit"
      >
        Save
      </Button>
    </div>
  </PaneFooter>
);

<Pane footer={footer} ... >
  Pane Content
</Pane>
```

### Props
Name | type | description | default | required
--- | --- | --- | --- | ---
children | node |  |  |
className | string | Adds a className to the `PaneFooter`. Optional. |  |
innerClassName | string | Adds a className to the `PaneFooter` content. Optional. |  |
renderEnd | node |  |  |
renderStart | node |  |  |


text:
class MiddlewarePerformance < ActsAsArModel
  set_columns_hash(
    :id            => :string,
    :name          => :string,
    :resource_type => :string,
    :feed          => :string,
    :ems_ref       => :string,
    :start_time    => :datetime,
    :end_time      => :datetime
  )

  alias resource_id id
  alias resource_name name

  def self.build_results_for_report_middleware(options)
    check_if_current_class_implements_model_class

    start_time, end_time, interval = parse_time_interval(options)
    results = []

    model_class.find_each do |ms|
      begin
        raw_stats = fetch_raw_stats(ms, start_time, end_time, interval)
      rescue ::Hawkular::BaseClient::HawkularConnectionException => exception
        $log.error(exception)
        next
      end
      if raw_stats.values[0]
        parse_raw_stats_columns(raw_stats)
        raw_stats.each { |timestamp, stats| results.push(parse_row(ms, timestamp, interval, stats)) }
      end
    end
    [results, {}]
  end

  def self.check_if_current_class_implements_model_class
    raise 'You are not supposed to use MiddlewarePerformance model for reporting.' if self == MiddlewarePerformance
    raise 'You need to implement :model_class in your model. ' unless respond_to?(:model_class)
  end

  def self.parse_raw_stats_columns(raw_stats)
    columns = raw_stats.values[0].keys
    columns.each { |column| set_columns_hash(column => :float) }
  end

  def self.parse_time_interval(options)
    now = Time.now.utc
    start_time = now - options[:start_offset]
    end_time = now - options[:end_offset]
    interval = case options[:interval]
               when 'daily'   then 1.day.seconds
               when 'hourly'  then 1.hour.seconds
               when 'every minute' then 1.minute.seconds
               else end_time - start_time
               end
    [start_time, end_time, interval]
  end

  def self.fetch_raw_stats(middleware_model, start_time, end_time, interval)
    raw_stats = {}
    metrics = middleware_model.metrics_available
    metrics_ids_map, all_stats = middleware_model.collect_stats_metrics(metrics, start_time, end_time, interval)
    %w(gauge counter_rate).each do |type|
      next unless all_stats.key?(type)
      stat_data = all_stats[type]
      stat_data.each do |metric_id, buckets|
        metric_name = metrics_ids_map[metric_id]
        buckets.each do |bucket|
          timestamp = bucket['start']
          raw_stats[timestamp] = {} if raw_stats[timestamp].nil?
          %w(min avg median max samples).each do |w|
            raw_stats[timestamp]["#{metric_name}_#{w}"] = bucket[w]
          end
        end
      end
    end
    raw_stats
  end

  def self.parse_row(middleware_model, timestamp, interval, stats)
    start_time = Time.at(timestamp / 1000).utc
    row = new
    %w(id name feed ems_ref).each { |field| row[field] = middleware_model[field] }
    row[:resource_type] = middleware_model.class.name
    row[:start_time] = start_time
    row[:end_time] = start_time + interval
    stats.each { |metric_name, value| row[metric_name] = value }
    row
  end

  def to_a
    [self]
  end
end


text:
<?php

namespace JPI\SoluxBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * MembreFamilleRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class MembreFamilleRepository extends EntityRepository
{
	public function getMontantMax($id)
	{
		$lSubquery1 = $this->createQueryBuilder('b');
		$lSubquery1->select($lSubquery1->expr()->count('b.pourcentageACharge'))
			->where($lSubquery1->expr()->eq('b.famille', ':id'))
			->andWhere($lSubquery1->expr()->eq('b.parent', 1));

		$lSubquery2 = $this->createQueryBuilder('c');
		$lSubquery2->select($lSubquery2->expr()->count('c.pourcentageACharge'))
			->where($lSubquery2->expr()->eq('c.famille', ':id'))
			->andWhere($lSubquery2->expr()->eq('c.parent', 1));

		$lSubquery3 = $this->createQueryBuilder('d');
		$lSubquery3->select($lSubquery3->expr()->count('d.pourcentageACharge'))
			->where($lSubquery3->expr()->eq('d.famille', ':id'))
			->andWhere($lSubquery3->expr()->eq('d.parent', 0));

		$lSubquery4 = $this->createQueryBuilder('e');
		$lSubquery4->select($lSubquery4->expr()->count('e.pourcentageACharge'))
			->where($lSubquery4->expr()->eq('e.famille', ':id'))
			->andWhere($lSubquery4->expr()->eq('e.parent', 0));

		$lQuery = $this->_em->createQueryBuilder();
		$lQuery->select('a')->from('JPI\SoluxBundle\Entity\MontantMaxAchat', 'a')
			->where($lQuery->expr()->gte(sprintf('(%s)', $lSubquery1->getDQL()), 'a.nbMembreAdulteMin'))
			->andWhere($lQuery->expr()->lte(sprintf('(%s)', $lSubquery2->getDQL()), 'a.nbMembreAdulteMax'))
			->andWhere($lQuery->expr()->gte(sprintf('(%s)', $lSubquery3->getDQL()), 'a.nbMembreEnfantMin'))
			->andWhere($lQuery->expr()->lte(sprintf('(%s)', $lSubquery4->getDQL()), 'a.nbMembreEnfantMax'))
			->setParameter('id', $id);

		return $lQuery
			->getQuery()
			->getOneOrNullResult();
	}
}


text:
export = index;
declare function index(...args: any[]): any;


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('waffle', '0002_flag_sessions'),
    ]

    operations = [
        migrations.CreateModel(
            name='VerifiedUser',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('phone_number', models.CharField(max_length=255)),
                ('feature', models.ForeignKey(to='waffle.Flag')),
            ],
            options={
            },
            bases=(models.Model,),
        ),
    ]


text:
package net.bramp.ffmpeg.builder;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static net.bramp.ffmpeg.Preconditions.checkNotEmpty;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
import javax.annotation.CheckReturnValue;
import net.bramp.ffmpeg.FFmpegUtils;
import net.bramp.ffmpeg.probe.FFmpegProbeResult;

/**
 * Builds a ffmpeg command line
 *
 * @author bramp
 */
public class FFmpegBuilder {

  public enum Strict {
    VERY, // strictly conform to a older more strict version of the specifications or reference
    // software
    STRICT, // strictly conform to all the things in the specificiations no matter what consequences
    NORMAL, // normal
    UNOFFICIAL, // allow unofficial extensions
    EXPERIMENTAL;

    // ffmpeg command line requires these options in lower case
    @Override
    public String toString() {
      return name().toLowerCase();
    }
  }

  /** Log level options: https://ffmpeg.org/ffmpeg.html#Generic-options */
  public enum Verbosity {
    QUIET,
    PANIC,
    FATAL,
    ERROR,
    WARNING,
    INFO,
    VERBOSE,
    DEBUG;

    @Override
    public String toString() {
      return name().toLowerCase();
    }
  }

  // Global Settings
  boolean override = true;
  int pass = 0;
  String pass_directory = "";
  String pass_prefix;
  Verbosity verbosity = Verbosity.ERROR;
  URI progress;
  String user_agent;

  // Input settings
  String format;
  Long startOffset; // in millis
  boolean read_at_native_frame_rate = false;
  final List<String> inputs = new ArrayList<>();
  final Map<String, FFmpegProbeResult> inputProbes = new TreeMap<>();

  final List<String> extra_args = new ArrayList<>();

  // Output
  final List<FFmpegOutputBuilder> outputs = new ArrayList<>();

  // Filters
  String audioFilter;
  String videoFilter;
  String complexFilter;

  public FFmpegBuilder overrideOutputFiles(boolean override) {
    this.override = override;
    return this;
  }

  public boolean getOverrideOutputFiles() {
    return this.override;
  }

  public FFmpegBuilder setPass(int pass) {
    this.pass = pass;
    return this;
  }

  public FFmpegBuilder setPassDirectory(String directory) {
    this.pass_directory = checkNotNull(directory);
    return this;
  }

  public FFmpegBuilder setPassPrefix(String prefix) {
    this.pass_prefix = checkNotNull(prefix);
    return this;
  }

  public FFmpegBuilder setVerbosity(Verbosity verbosity) {
    checkNotNull(verbosity);
    this.verbosity = verbosity;
    return this;
  }

  public FFmpegBuilder setUserAgent(String userAgent) {
    this.user_agent = checkNotNull(userAgent);
    return this;
  }

  public FFmpegBuilder readAtNativeFrameRate() {
    this.read_at_native_frame_rate = true;
    return this;
  }

  public FFmpegBuilder addInput(FFmpegProbeResult result) {
    checkNotNull(result);
    String filename = checkNotNull(result.format).filename;
    inputProbes.put(filename, result);
    return addInput(filename);
  }

  public FFmpegBuilder addInput(String filename) {
    checkNotNull(filename);
    inputs.add(filename);
    return this;
  }

  protected void clearInputs() {
    inputs.clear();
    inputProbes.clear();
  }

  public FFmpegBuilder setInput(FFmpegProbeResult result) {
    clearInputs();
    return addInput(result);
  }

  public FFmpegBuilder setInput(String filename) {
    clearInputs();
    return addInput(filename);
  }

  public FFmpegBuilder setFormat(String format) {
    this.format = checkNotNull(format);
    return this;
  }

  public FFmpegBuilder setStartOffset(long duration, TimeUnit units) {
    checkNotNull(units);

    this.startOffset = units.toMillis(duration);

    return this;
  }

  public FFmpegBuilder addProgress(URI uri) {
    this.progress = checkNotNull(uri);
    return this;
  }

  /**
   * Sets the complex filter flag.
   *
   * @param filter
   * @return
   */
  public FFmpegBuilder setComplexFilter(String filter) {
    this.complexFilter = checkNotEmpty(filter, "filter must not be empty");
    return this;
  }

  /**
   * Sets the audio filter flag.
   *
   * @param filter
   * @return
   */
  public FFmpegBuilder setAudioFilter(String filter) {
    this.audioFilter = checkNotEmpty(filter, "filter must not be empty");
    return this;
  }

  /**
   * Sets the video filter flag.
   *
   * @param filter
   * @return
   */
  public FFmpegBuilder setVideoFilter(String filter) {
    this.videoFilter = checkNotEmpty(filter, "filter must not be empty");
    return this;
  }

  /**
   * Add additional ouput arguments (for flags which aren't currently supported).
   *
   * @param values The extra arguments.
   * @return this
   */
  public FFmpegBuilder addExtraArgs(String... values) {
    checkArgument(values.length > 0, "one or more values must be supplied");
    checkNotEmpty(values[0], "first extra arg may not be empty");

    for (String value : values) {
      extra_args.add(checkNotNull(value));
    }
    return this;
  }

  /**
   * Adds new output file.
   *
   * @param filename output file path
   * @return A new {@link FFmpegOutputBuilder}
   */
  public FFmpegOutputBuilder addOutput(String filename) {
    FFmpegOutputBuilder output = new FFmpegOutputBuilder(this, filename);
    outputs.add(output);
    return output;
  }

  /**
   * Adds new output file.
   *
   * @param uri output file uri typically a stream
   * @return A new {@link FFmpegOutputBuilder}
   */
  public FFmpegOutputBuilder addOutput(URI uri) {
    FFmpegOutputBuilder output = new FFmpegOutputBuilder(this, uri);
    outputs.add(output);
    return output;
  }

  /**
   * Adds an existing FFmpegOutputBuilder. This is similar to calling the other addOuput methods but
   * instead allows an existing FFmpegOutputBuilder to be used, and reused.
   *
   *

   * List<String> args = new FFmpegBuilder()
   *   .addOutput(new FFmpegOutputBuilder()
   *     .setFilename("output.flv")
   *     .setVideoCodec("flv")
   *   )
   *   .build();
   *

   *
   * @param output FFmpegOutputBuilder to add
   * @return this
   */
  public FFmpegBuilder addOutput(FFmpegOutputBuilder output) {
    outputs.add(output);
    return this;
  }

  /**
   * Create new output (to stdout)
   *
   * @return A new {@link FFmpegOutputBuilder}
   */
  public FFmpegOutputBuilder addStdoutOutput() {
    return addOutput("-");
  }

  @CheckReturnValue
  public List<String> build() {
    ImmutableList.Builder<String> args = new ImmutableList.Builder<String>();

    Preconditions.checkArgument(!inputs.isEmpty(), "At least one input must be specified");
    Preconditions.checkArgument(!outputs.isEmpty(), "At least one output must be specified");

    args.add(override ? "-y" : "-n");
    args.add("-v", this.verbosity.toString());

    if (user_agent != null) {
      args.add("-user_agent", user_agent);
    }

    if (startOffset != null) {
      args.add("-ss", FFmpegUtils.toTimecode(startOffset, TimeUnit.MILLISECONDS));
    }

    if (format != null) {
      args.add("-f", format);
    }

    if (read_at_native_frame_rate) {
      args.add("-re");
    }

    if (progress != null) {
      args.add("-progress", progress.toString());
    }

    args.addAll(extra_args);

    for (String input : inputs) {
      args.add("-i", input);
    }

    if (pass > 0) {
      args.add("-pass", Integer.toString(pass));

      if (pass_prefix != null) {
        args.add("-passlogfile", pass_directory + pass_prefix);
      }
    }

    if (!Strings.isNullOrEmpty(audioFilter)) {
      args.add("-af", audioFilter);
    }

    if (!Strings.isNullOrEmpty(videoFilter)) {
      args.add("-vf", videoFilter);
    }

    if (!Strings.isNullOrEmpty(complexFilter)) {
      args.add("-filter_complex", complexFilter);
    }

    for (FFmpegOutputBuilder output : this.outputs) {
      args.addAll(output.build(this, pass));
    }

    return args.build();
  }
}


text:
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow mw;
    mw.show();
    return a.exec();
}


text:
Support better provision user experience for APBs by giving additional metadata about APB parameters.

## Problem Description
Currently, APB parameters are shown in random order and without any kind of grouping.  the OpenServiceBroker API utilizes json-schema data format and does not include any UI metadata.  As such, the UI cannot customize the experience and users are confronted with a bad experience which gets worse as the number of parameters increases.

## Implementation Details

### APB changes
APBs will allow an author to implement parameter order, grouping, and form field type.
* Ordering will honor the order of parameters used in the apb.yml
* Grouping will require the addition of a parameter field `display_group`.  This is an arbitrary string value but can be left empty to signify that the form input is at the top level and not grouped.  If it matches other `display_group` string from a parameter immediately before or after the parameter in question, they would be grouped together.
* UI field types will require the addition of a parameter field `display_type`.  Default (empty) will use the default form input based on the json-schema.

```yaml
name: hello-world-db-apb
# ...snip...
plans:
  - name: default
    # ...snip...
    parameters:                           # respects order of parameters
      - name: postgresql_database         # first parameter on form
        title: PostgreSQL Database Name
        type: string
        required: True
        default: admin
      - name: postgresql_user             # second parameter
        title: PostgreSQL User
        type: string
        required: True
        default: admin
        display_group: User Information   # same group as password
      - name: postgresql_password         # third parameter
        title: PostgreSQL Password
        type: string
        required: True
        default: admin
        display_type: password            # password type displayed in UI as ****
        display_group: User Information   # same group as user
```
Documentation for the additional fields should be added to the appropriate documentation for APBs in the [ansible-playbook-bundle](https://github.com/fusor/ansible-playbook-bundle) project.

### API changes
The agreed upon request format with the OpenShift UI team matches the [form definition](https://github.com/json-schema-form/angular-schema-form/blob/development/docs/index.md#form-definitions) used on the front end UI.  This will be specific to OpenShift but there is no standard agreed upon and this would cause the least changes in the UI code with maximum flexibility.  In order to minimize impact and not make changes to the OpenServiceBroker API, the data will be contained in the plan metadata.  Since parameters are tied to the method, the json structure in metadata containing the form definition will mirror the json structure containing the schema.

```json
[
  {
    "name": "hello-world-db-apb-latest",
    "metadata": {},
    "plans": [
      {
        "id": "default",
        "name": "default",
        "metadata": {
          "schemas": {
            "service_instance": {
              "create": {
                "form_definition": [
                  "postgresql_database",
                  {
                    "type": "section",
                    "items": [
                      "postgresql_user",
                      {
                        "key": "postgresql_password",
                        "type": "password"
                      }
                    ]
                  }
                ]
              },
              "update": {}
            },
            "service_binding": {
              "create": "... same as service_instance.create"
            }
          }
        },
        "schemas": {
          "service_instance": {
            "create": {
              "parameters": {
                "$schema": "http://json-schema.org/draft-04/schema",
                "additionalProperties": false,
                "properties": {
                  "postgresql_database": {
                    "default": "admin",
                    "title": "PostgreSQL Database Name",
                    "type": "string"
                  },
                  "postgresql_password": {
                    "default": "admin",
                    "title": "PostgreSQL Password",
                    "type": "string"
                  },
                  "postgresql_user": {
                    "default": "admin",
                    "title": "PostgreSQL User",
                    "type": "string"
                  }
                },
                "required": [
                  "postgresql_database",
                  "postgresql_user",
                  "postgresql_password"
                ],
                "type": "object"
              }
            },
            "update": {}
          },
          "service_binding": {
            "create": "... same as service_instance.create"
          }
        }
      }
    ]
  }
]

```
Currently the impact would be change the metadata and is additive with no breaking changes.  The broker code would modify how the metadata is set [here](https://github.com/openshift/ansible-service-broker/blob/master/pkg/broker/util.go#L36) and introducing a new function to append the UI metadata.

## Notes
* This will require changes to [origin-web-catalog](https://github.com/openshift/origin-web-catalog) to read, validate, and use the form definition.  Currently we are only planning on supporting only fieldset/sections for grouping, types, and honoring the order from the form definition.


text:
import WebGLManager from './WebGLManager';

/**
 * @class
 * @extends PIXI.WebGLManager
 * @memberof PIXI
 */
export default class StencilManager extends WebGLManager
{
    /**
     * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for.
     */
    constructor(renderer)
    {
        super(renderer);
        this.stencilMaskStack = null;
    }

    /**
     * Changes the mask stack that is used by this manager.
     *
     * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack
     */
    setMaskStack(stencilMaskStack)
    {
        this.stencilMaskStack = stencilMaskStack;

        const gl = this.renderer.gl;

        if (stencilMaskStack.length === 0)
        {
            gl.disable(gl.STENCIL_TEST);
        }
        else
        {
            gl.enable(gl.STENCIL_TEST);
        }
    }

    /**
     * Applies the Mask and adds it to the current stencil stack. @alvin
     *
     * @param {PIXI.Graphics} graphics - The mask
     */
    pushStencil(graphics)
    {
        this.renderer.setObjectRenderer(this.renderer.plugins.graphics);

        this.renderer._activeRenderTarget.attachStencilBuffer();

        const gl = this.renderer.gl;
        const prevMaskCount = this.stencilMaskStack.length;

        if (prevMaskCount === 0)
        {
            gl.enable(gl.STENCIL_TEST);
        }

        this.stencilMaskStack.push(graphics);

        // Increment the reference stencil value where the new mask overlaps with the old ones.
        gl.colorMask(false, false, false, false);
        gl.stencilFunc(gl.EQUAL, prevMaskCount, this._getBitwiseMask());
        gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR);
        this.renderer.plugins.graphics.render(graphics);

        this._useCurrent();
    }

    /**
     * Removes the last mask from the stencil stack. @alvin
     */
    popStencil()
    {
        this.renderer.setObjectRenderer(this.renderer.plugins.graphics);

        const gl = this.renderer.gl;
        const graphics = this.stencilMaskStack.pop();

        if (this.stencilMaskStack.length === 0)
        {
            // the stack is empty!
            gl.disable(gl.STENCIL_TEST);
            gl.clear(gl.STENCIL_BUFFER_BIT);
            gl.clearStencil(0);
        }
        else
        {
            // Decrement the reference stencil value where the popped mask overlaps with the other ones
            gl.colorMask(false, false, false, false);
            gl.stencilOp(gl.KEEP, gl.KEEP, gl.DECR);
            this.renderer.plugins.graphics.render(graphics);

            this._useCurrent();
        }
    }

    /**
     * Setup renderer to use the current stencil data.
     */
    _useCurrent()
    {
        const gl = this.renderer.gl;

        gl.colorMask(true, true, true, true);
        gl.stencilFunc(gl.EQUAL, this.stencilMaskStack.length, this._getBitwiseMask());
        gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
    }

    /**
     * Fill 1s equal to the number of acitve stencil masks.
     *
     * @return {number} The bitwise mask.
     */
    _getBitwiseMask()
    {
        return (1 << this.stencilMaskStack.length) - 1;
    }

    /**
     * Destroys the mask stack.
     *
     */
    destroy()
    {
        WebGLManager.prototype.destroy.call(this);

        this.stencilMaskStack.stencilStack = null;
    }
}


text:
- Support processed CSS

## 0.1.0

- Initial release


text:
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------

#include "core/strings/stringFunctions.h"
#include "util/tempAlloc.h"
#include "console/console.h"
#include "core/stringTable.h"

//-----------------------------------------------------------------------------

StringTableEntry Platform::getTemporaryDirectory()
{
   StringTableEntry path = osGetTemporaryDirectory();

   if(! Platform::isDirectory(path))
      path = Platform::getCurrentDirectory();

   return path;
}

ConsoleFunction(getTemporaryDirectory, const char *, 1, 1, "()"
				"@brief Returns the OS temporary directory, \"C:/Users/Mich/AppData/Local/Temp\" for example\n\n"
				"@note This can be useful to adhering to OS standards and practices, "
				"but not really used in Torque 3D right now.\n"
				"@note Be very careful when getting into OS level File I/O."
				"@return String containing path to OS temp directory\n"
				"@note This is legacy function brought over from TGB, and does not appear "
				"to have much use. Possibly deprecate?\n"
				"@ingroup FileSystem\n"
				"@internal")
{
   return Platform::getTemporaryDirectory();
}

StringTableEntry Platform::getTemporaryFileName()
{
   char buf[512];
   StringTableEntry path = Platform::getTemporaryDirectory();

   dSprintf(buf, sizeof(buf), "%s/tgb.%08x.%02x.tmp", path, Platform::getRealMilliseconds(), U32(Platform::getRandom() * 255));

   // [tom, 9/7/2006] This shouldn't be needed, but just in case
   if(Platform::isFile(buf))
      return Platform::getTemporaryFileName();

   return StringTable->insert(buf);
}

ConsoleFunction(getTemporaryFileName, const char *, 1, 1, "()"
				"@brief Creates a name and extension for a potential temporary file\n\n"
				"This does not create the actual file. It simply creates a random name "
				"for a file that does not exist.\n\n"
				"@note This is legacy function brought over from TGB, and does not appear "
				"to have much use. Possibly deprecate?\n"
				"@ingroup FileSystem\n"
				"@internal")
{
   return Platform::getTemporaryFileName();
}

//-----------------------------------------------------------------------------

static StringTableEntry sgMainCSDir = NULL;

StringTableEntry Platform::getMainDotCsDir()
{
   if(sgMainCSDir == NULL)
      sgMainCSDir = Platform::getExecutablePath();

   return sgMainCSDir;
}

void Platform::setMainDotCsDir(const char *dir)
{
   sgMainCSDir = StringTable->insert(dir);
}

//-----------------------------------------------------------------------------

typedef Vector<char*> CharVector;
static CharVector gPlatformDirectoryExcludeList( __FILE__, __LINE__ );

void Platform::addExcludedDirectory(const char *pDir)
{
   gPlatformDirectoryExcludeList.push_back(dStrdup(pDir));
}

void Platform::clearExcludedDirectories()
{
   while(gPlatformDirectoryExcludeList.size())
   {
      dFree(gPlatformDirectoryExcludeList.last());
      gPlatformDirectoryExcludeList.pop_back();
   }
}

bool Platform::isExcludedDirectory(const char *pDir)
{
   for(CharVector::iterator i=gPlatformDirectoryExcludeList.begin(); i!=gPlatformDirectoryExcludeList.end(); i++)
      if(!dStrcmp(pDir, *i))
         return true;

   return false;
}

//-----------------------------------------------------------------------------

inline void catPath(char *dst, const char *src, U32 len)
{
   if(*dst != '/')
   {
      ++dst; --len;
      *dst = '/';
   }

   ++dst; --len;

   dStrncpy(dst, src, len);
   dst[len - 1] = 0;
}

// converts the posix root path "/" to "c:/" for win32
// FIXME: this is not ideal. the c: drive is not guaranteed to exist.
#if defined(TORQUE_OS_WIN32)
static inline void _resolveLeadingSlash(char* buf, U32 size)
{
   if(buf[0] != '/')
      return;

   AssertFatal(dStrlen(buf) + 2 < size, "Expanded path would be too long");
   dMemmove(buf + 2, buf, dStrlen(buf));
   buf[0] = 'c';
   buf[1] = ':';
}
#endif

static void makeCleanPathInPlace( char* path )
{
   U32 pathDepth = 0;
   char* fromPtr = path;
   char* toPtr = path;

   bool isAbsolute = false;
   if( *fromPtr == '/' )
   {
      fromPtr ++;
      toPtr ++;
      isAbsolute = true;
   }
   else if( fromPtr[ 0 ] != '\0' && fromPtr[ 1 ] == ':' )
   {
      toPtr += 3;
      fromPtr += 3;
      isAbsolute = true;
   }

   while( *fromPtr )
   {
      if( fromPtr[ 0 ] == '.' && fromPtr[ 1 ] == '.' && fromPtr[ 2 ] == '/' )
      {
         // Back up from '../'

         if( pathDepth > 0 )
         {
            pathDepth --;
            toPtr -= 2;
            while( toPtr >= path && *toPtr != '/' )
               toPtr --;
            toPtr ++;
         }
         else if( !isAbsolute )
         {
            dMemcpy( toPtr, fromPtr, 3 );
            toPtr += 3;
         }

         fromPtr += 3;
      }
      else if( fromPtr[ 0 ] == '.' && fromPtr[ 1 ] == '/' )
      {
         // Ignore.
         fromPtr += 2;
      }
      else
      {
         if( fromPtr[ 0 ] == '/' )
            pathDepth ++;

         *toPtr ++ = *fromPtr ++;
      }
   }

   *toPtr = '\0';
}

char * Platform::makeFullPathName(const char *path, char *buffer, U32 size, const char *cwd /* = NULL */)
{
   char bspath[1024];
   dStrncpy(bspath, path, sizeof(bspath));
   bspath[sizeof(bspath)-1] = 0;

   for(S32 i = 0;i < dStrlen(bspath);++i)
   {
      if(bspath[i] == '\\')
         bspath[i] = '/';
   }

   if(Platform::isFullPath(bspath))
   {
      // Already a full path
      #if defined(TORQUE_OS_WIN32)
         _resolveLeadingSlash(bspath, sizeof(bspath));
      #endif
      dStrncpy(buffer, bspath, size);
      buffer[size-1] = 0;
      return buffer;
   }

   // [rene, 05/05/2008] Based on overall file handling in Torque, it does not seem to make
   //    that much sense to me to base things off the current working directory here.

   if(cwd == NULL)
      cwd = Con::isCurrentScriptToolScript() ? Platform::getMainDotCsDir() : Platform::getCurrentDirectory();

   dStrncpy(buffer, cwd, size);
   buffer[size-1] = 0;

   const char* defaultDir = Con::getVariable("defaultGame");

   char *ptr = bspath;
   char *slash = NULL;
   char *endptr = buffer + dStrlen(buffer) - 1;

   do
   {
      slash = dStrchr(ptr, '/');
      if(slash)
      {
         *slash = 0;

         // Directory

         if(dStrcmp(ptr, "..") == 0)
         {
            // Parent
            endptr = dStrrchr(buffer, '/');
            if (endptr)
               *endptr-- = 0;
         }
         else if(dStrcmp(ptr, ".") == 0)
         {
            // Current dir
         }
         else if(dStrcmp(ptr, "~") == 0)
         {
            catPath(endptr, defaultDir, size - (endptr - buffer));
            endptr += dStrlen(endptr) - 1;
         }
         else if(endptr)
         {
            catPath(endptr, ptr, size - (endptr - buffer));
            endptr += dStrlen(endptr) - 1;
         }

         ptr = slash + 1;
      }
      else if(endptr)
      {
         // File

         catPath(endptr, ptr, size - (endptr - buffer));
         endptr += dStrlen(endptr) - 1;
      }

   } while(slash);

   return buffer;
}

bool Platform::isFullPath(const char *path)
{
   // Quick way out
   if(path[0] == '/' || path[1] == ':')
      return true;

   return false;
}

//-----------------------------------------------------------------------------

/// Return "fileName" stripped of its extension.  Only extensions contained
/// in "validExtensions" will be stripped from the filename.
///
/// @note Extensions in "validExtension" should include the dot.
String Platform::stripExtension( String fileName, Vector< String >& validExtensions )
{
   // See if we have a valid extension to strip off
   String ext;
   S32 dotPos = fileName.find( '.', 0, String::Right );
   if( dotPos != String::NPos )
      ext = fileName.substr( dotPos );

   U32 numValidExt = validExtensions.size();
   if( ext.isNotEmpty() && numValidExt )
   {
      bool validExt = false;
      for( U32 i = 0; i < numValidExt; i++ )
      {
         if( ext.equal( validExtensions[ i ], String::NoCase ) )
         {
            validExt = true;
            break;
         }
      }

      if( !validExt )
         ext = String::EmptyString;
   }

   if( ext.isEmpty() )
      return fileName;
   else
      return fileName.substr( 0, fileName.length() - ext.length() );
}

//-----------------------------------------------------------------------------
// TODO: wow really shouldn't be adding everything to the string table, use the string class!
StringTableEntry Platform::makeRelativePathName(const char *path, const char *to)
{
   // Make sure 'to' is a proper absolute path terminated with a forward slash.

   char buffer[ 2048 ];
   if( !to )
   {
      dSprintf( buffer, sizeof( buffer ), "%s/", Platform::getMainDotCsDir() );
      to = buffer;
   }
   else if( !Platform::isFullPath( to ) )
   {
      dSprintf( buffer, sizeof( buffer ), "%s/%s/", Platform::getMainDotCsDir(), to );
      makeCleanPathInPlace( buffer );
      to = buffer;
   }
   else if( to[ dStrlen( to ) - 1 ] != '/' )
   {
      U32 length = getMin( (U32)dStrlen( to ), sizeof( buffer ) - 2 );
      dMemcpy( buffer, to, length );
      buffer[ length ] = '/';
      buffer[ length + 1 ] = '\0';
      to = buffer;
   }

   // If 'path' isn't absolute, make it now.  Let's us use a single
   // absolute/absolute merge path from here on.

   char buffer2[ 1024 ];
   if( !Platform::isFullPath( path ) )
   {
      dSprintf( buffer2, sizeof( buffer2 ), "%s/%s", Platform::getMainDotCsDir(), path );
      makeCleanPathInPlace( buffer2 );
      path = buffer2;
   }

   // First, find the common prefix and see where 'path' branches off from 'to'.

   const char *pathPtr, *toPtr, *branch = path;
   for(pathPtr = path, toPtr = to;*pathPtr && *toPtr && dTolower(*pathPtr) == dTolower(*toPtr);++pathPtr, ++toPtr)
   {
      if(*pathPtr == '/')
         branch = pathPtr;
   }

   // If there's no common part, the two paths are on different drives and
   // there's nothing we can do.

   if( pathPtr == path )
      return StringTable->insert( path );

   // If 'path' and 'to' are identical (minus trailing slash or so), we can just return './'.

   else if((*pathPtr == 0 || (*pathPtr == '/' && *(pathPtr + 1) == 0)) &&
      (*toPtr == 0 || (*toPtr == '/' && *(toPtr + 1) == 0)))
   {
      char* bufPtr = buffer;
      *bufPtr ++ = '.';

      if(*pathPtr == '/' || *(pathPtr - 1) == '/')
         *bufPtr++ = '/';

      *bufPtr = 0;
      return StringTable->insert(buffer);
   }

   // If 'to' is a proper prefix of 'path', the remainder of 'path' is our relative path.

   else if( *toPtr == '\0' && toPtr[ -1 ] == '/' )
      return StringTable->insert( pathPtr );

   // Otherwise have to step up the remaining directories in 'to' and then
   // append the remainder of 'path'.

   else
   {
      if((*pathPtr == 0 && *toPtr == '/') || (*toPtr == '/' && *pathPtr == 0))
         branch = pathPtr;

      // Allocate a new temp so we aren't prone to buffer overruns.

      TempAlloc< char > temp( dStrlen( toPtr ) + dStrlen( branch ) + 1 );
      char* bufPtr = temp;

      // Figure out parent dirs

      for(toPtr = to + (branch - path);*toPtr;++toPtr)
      {
         if(*toPtr == '/' && *(toPtr + 1) != 0)
         {
            *bufPtr++ = '.';
            *bufPtr++ = '.';
            *bufPtr++ = '/';
         }
      }
      *bufPtr = 0;

      // Copy the rest
      if(*branch)
         dStrcpy(bufPtr, branch + 1);
      else
         *--bufPtr = 0;

      return StringTable->insert( temp );
   }
}

//-----------------------------------------------------------------------------

static StringTableEntry tryStripBasePath(const char *path, const char *base)
{
   U32 len = dStrlen(base);
   if(dStrnicmp(path, base, len) == 0)
   {
      if(*(path + len) == '/') ++len;
      return StringTable->insert(path + len, true);
   }
   return NULL;
}

StringTableEntry Platform::stripBasePath(const char *path)
{
   if(path == NULL)
      return NULL;

   StringTableEntry str = tryStripBasePath(path, Platform::getMainDotCsDir());

   if(str != NULL )
      return str;

   str = tryStripBasePath(path, Platform::getCurrentDirectory());
   if(str != NULL )
      return str;

   str = tryStripBasePath(path, Platform::getPrefsPath());
   if(str != NULL )
      return str;

   return path;
}

//-----------------------------------------------------------------------------

StringTableEntry Platform::getPrefsPath(const char *file /* = NULL */)
{
#ifndef TORQUE2D_TOOLS_FIXME
   return StringTable->insert(file ? file : "");
#else
   char buf[1024];
   const char *company = Con::getVariable("$Game::CompanyName");
   if(company == NULL || *company == 0)
      company = "GarageGames";

   const char *appName = Con::getVariable("$Game::GameName");
   if(appName == NULL || *appName == 0)
      appName = TORQUE_APP_NAME;

   if(file)
   {
      if(dStrstr(file, ".."))
      {
         Con::errorf("getPrefsPath - filename cannot be relative");
         return NULL;
      }

      dSprintf(buf, sizeof(buf), "%s/%s/%s/%s", Platform::getUserDataDirectory(), company, appName, file);
   }
   else
      dSprintf(buf, sizeof(buf), "%s/%s/%s", Platform::getUserDataDirectory(), company, appName);

   return StringTable->insert(buf, true);
#endif
}

//-----------------------------------------------------------------------------

ConsoleFunction(getUserDataDirectory, const char*, 1, 1, "getUserDataDirectory()")
{
   return Platform::getUserDataDirectory();
}

ConsoleFunction(getUserHomeDirectory, const char*, 1, 1, "getUserHomeDirectory()")
{
   return Platform::getUserHomeDirectory();
}


text:
/* eslint-disable no-unused-vars */
/**
 * Copyright 2018 The AMP HTML Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {Deferred} from '../../../src/utils/promise';
import {Layout, isLayoutSizeDefined} from '../../../src/layout';
import {Services} from '../../../src/services';
import {VideoAttributes, VideoEvents} from '../../../src/video-interface';

import {dev, userAssert} from '../../../src/log';
import {
  fullscreenEnter,
  fullscreenExit,
  isFullscreenElement,
  removeElement,
} from '../../../src/dom';
import {getData, listen} from '../../../src/event-helper';
import {getIframe} from '../../../src/3p-frame';
import {installVideoManagerForDoc} from '../../../src/service/video-manager-impl';

const TAG = 'amp-viqeo-player';

/**
 * @implements {../../../src/video-interface.VideoInterface}
 */
class AmpViqeoPlayer extends AMP.BaseElement {
  /** @param {!AmpElement} element */
  constructor(element) {
    super(element);

    /** @private {?HTMLIFrameElement} */
    this.iframe_ = null;

    /** @private {?Promise} */
    this.playerReadyPromise_ = null;

    /** @private {?Function} */
    this.playerReadyResolver_ = null;

    /** @private {?number} */
    this.volume_ = null;

    /** @private {?Function} */
    this.unlistenMessage_ = null;

    /** @private {?Object} */
    this.viqeoPlayer_ = null;

    /** @private {boolean} */
    this.hasAutoplay_ = false;

    /** @private {string} */
    this.videoId_ = '';
  }

  /**
   * @param {boolean=} opt_onLayout
   * @override
   */
  preconnectCallback(opt_onLayout) {
    this.preconnect.url('https://api.viqeo.tv', opt_onLayout);
    this.preconnect.url('https://cdn.viqeo.tv', opt_onLayout);
  }

  /**
   * @param {!Layout} layout
   * @return {boolean}
   * @override
   */
  isLayoutSupported(layout) {
    return isLayoutSizeDefined(layout);
  }

  /** @override */
  buildCallback() {
    this.videoId_ = userAssert(
      this.element.getAttribute('data-videoid'),
      'The data-videoid attribute is required for <amp-viqeo-player> %s',
      this.element
    );

    userAssert(
      this.element.getAttribute('data-profileid'),
      'The data-profileid attribute is required for <amp-viqeo-player> %s',
      this.element
    );

    this.hasAutoplay_ = this.element.hasAttribute(VideoAttributes.AUTOPLAY);

    const deferred = new Deferred();
    this.playerReadyPromise_ = deferred.promise;
    this.playerReadyResolver_ = deferred.resolve;

    installVideoManagerForDoc(this.element);
    Services.videoManagerForDoc(this.element).register(this);
  }

  /** @override */
  layoutCallback() {
    const iframe = getIframe(
      this.win,
      this.element,
      'viqeoplayer',
      {
        'autoplay': this.hasAutoplay_,
      },
      {
        allowFullscreen: true,
      }
    );

    // required to display the user gesture in the iframe
    iframe.setAttribute('allow', 'autoplay');

    this.unlistenMessage_ = listen(
      this.win,
      'message',
      this.handleViqeoMessages_.bind(this)
    );

    return this.mutateElement(() => {
      this.element.appendChild(iframe);
      this.iframe_ = iframe;
      this.applyFillContent(iframe);
    }).then(() => {
      return this.playerReadyPromise_;
    });
  }

  /**
   * @param {!Event|{data: !JsonObject}} event
   * @return {?JsonObject|string|undefined}
   * @private
   * */
  handleViqeoMessages_(event) {
    const eventData = getData(event);
    if (
      !eventData ||
      event.source !== (this.iframe_ && this.iframe_.contentWindow) ||
      eventData['source'] !== 'ViqeoPlayer'
    ) {
      return;
    }

    const action = eventData['action'];
    if (action === 'ready') {
      this.element.dispatchCustomEvent(VideoEvents.LOAD);
      this.playerReadyResolver_(this.iframe_);
    } else if (action === 'play') {
      this.element.dispatchCustomEvent(VideoEvents.PLAYING);
    } else if (action === 'pause') {
      this.element.dispatchCustomEvent(VideoEvents.PAUSE);
    } else if (action === 'mute') {
      this.element.dispatchCustomEvent(VideoEvents.MUTED);
    } else if (action === 'unmute') {
      this.element.dispatchCustomEvent(VideoEvents.UNMUTED);
    } else if (action === 'volume') {
      this.volume_ = parseFloat(eventData['value']);
      if (this.volume_ === 0) {
        this.element.dispatchCustomEvent(VideoEvents.MUTED);
      } else {
        this.element.dispatchCustomEvent(VideoEvents.UNMUTED);
      }
    }
  }

  /** @override */
  unlayoutCallback() {
    if (this.iframe_) {
      removeElement(this.iframe_);
      this.iframe_ = null;
    }
    if (this.unlistenMessage_) {
      this.unlistenMessage_();
    }

    const deferred = new Deferred();
    this.playerReadyPromise_ = deferred.promise;
    this.playerReadyResolver_ = deferred.resolve;
    return true; // Call layoutCallback again.
  }

  /** @override */
  createPlaceholderCallback() {
    const placeholder = this.element.ownerDocument.createElement('amp-img');
    this.propagateAttributes(['aria-label'], placeholder);
    if (placeholder.hasAttribute('aria-label')) {
      placeholder.setAttribute(
        'alt',
        'Loading video - ' + placeholder.getAttribute('aria-label')
      );
    } else {
      placeholder.setAttribute('alt', 'Loading video');
    }
    placeholder.setAttribute(
      'src',
      `https://cdn.viqeo.tv/preview/${encodeURIComponent(this.videoId_)}.jpg`
    );
    placeholder.setAttribute('layout', 'fill');
    placeholder.setAttribute('placeholder', '');
    placeholder.setAttribute('referrerpolicy', 'origin');
    this.applyFillContent(placeholder);
    return placeholder;
  }

  /** @override */
  supportsPlatform() {
    return true;
  }

  /** @override */
  isInteractive() {
    return true;
  }

  /** @override */
  play() {
    this.sendCommand_('play');
  }

  /** @override */
  pause() {
    this.sendCommand_('pause');
  }

  /** @override */
  mute() {
    this.sendCommand_('mute');
  }

  /** @override */
  unmute() {
    this.sendCommand_('unmute');
  }

  /** @override */
  showControls() {
    // Not supported.
  }

  /** @override */
  hideControls() {
    // Not supported.
  }

  /**
   * @override
   */
  fullscreenEnter() {
    if (!this.iframe_) {
      return;
    }
    fullscreenEnter(dev().assertElement(this.iframe_));
  }

  /**
   * @override
   */
  fullscreenExit() {
    if (!this.iframe_) {
      return;
    }
    fullscreenExit(dev().assertElement(this.iframe_));
  }

  /** @override */
  isFullscreen() {
    if (!this.iframe_) {
      return false;
    }
    return isFullscreenElement(dev().assertElement(this.iframe_));
  }

  /** @override */
  getMetadata() {
    // Not implemented
  }

  /** @override */
  preimplementsMediaSessionAPI() {
    return false;
  }

  /** @override */
  preimplementsAutoFullscreen() {
    return false;
  }

  /** @override */
  getCurrentTime() {
    if (!this.viqeoPlayer_) {
      return 0;
    }
    return this.viqeoPlayer_.getCurrentTime();
  }

  /** @override */
  getDuration() {
    if (!this.viqeoPlayer_) {
      return 1;
    }
    return this.viqeoPlayer_.getDuration();
  }

  /** @override */
  getPlayedRanges() {
    // Not supported.
    return [];
  }

  /**
   * Sends a command to the player
   * @param {string|JsonObject} command
   * @private
   */
  sendCommand_(command) {
    if (!this.iframe_) {
      return;
    }
    const {contentWindow} = this.iframe_;
    if (!contentWindow) {
      return;
    }

    if (typeof command === 'string') {
      command = /** @type {JsonObject} */ ({
        action: command,
      });
    }
    contentWindow./*OK*/ postMessage(command, '*');
  }

  /** @override */
  seekTo(unusedTimeSeconds) {
    this.user().error(TAG, '`seekTo` not supported.');
  }
}

AMP.extension(TAG, '0.1', AMP => {
  AMP.registerElement(TAG, AmpViqeoPlayer);
});

export default AmpViqeoPlayer;


text:
'use strict';

var ensureDbjsObject = require('dbjs/valid-dbjs-object')
  , toArray          = require('es5-ext/array/to-array')
  , resolve          = require('path').resolve
  , uploadsPath      = require('mano').uploadsPath;

module.exports = function (/*file, ..., fileN*/) {
	return toArray(arguments).filter(function (file) {
		ensureDbjsObject(file);

		return Boolean(file.name && file.path);
	}).map(function (file) {
		return { filename: file.name, path: resolve(uploadsPath, file.path) };
	});
};


text:
from django import template
from django.conf import settings
from django.contrib import admin
from django.contrib.auth.forms import UserCreationForm, UserChangeForm, AdminPasswordChangeForm
from django.contrib.auth.models import User, Group
from django.core.exceptions import PermissionDenied
from django.http import HttpResponseRedirect, Http404
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.utils.html import escape
from django.utils.translation import ugettext, ugettext_lazy as _

class GroupAdmin(admin.ModelAdmin):
    search_fields = ('name',)
    ordering = ('name',)
    filter_horizontal = ('permissions',)

class UserAdmin(admin.ModelAdmin):
    fieldsets = (
        (None, {'fields': ('username', 'password')}),
        (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
        (_('Permissions'), {'fields': ('is_staff', 'is_active', 'is_superuser', 'user_permissions')}),
        (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
        (_('Groups'), {'fields': ('groups',)}),
    )
    form = UserChangeForm
    add_form = UserCreationForm
    change_password_form = AdminPasswordChangeForm
    list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff')
    list_filter = ('is_staff', 'is_superuser', 'is_active')
    search_fields = ('username', 'first_name', 'last_name', 'email')
    ordering = ('username',)
    filter_horizontal = ('user_permissions',)

    def __call__(self, request, url):
        # this should not be here, but must be due to the way __call__ routes
        # in ModelAdmin.
        if url is None:
            return self.changelist_view(request)
        if url.endswith('password'):
            return self.user_change_password(request, url.split('/')[0])
        return super(UserAdmin, self).__call__(request, url)

    def get_urls(self):
        from django.conf.urls.defaults import patterns
        return patterns('',
            (r'^(\d+)/password/$', self.admin_site.admin_view(self.user_change_password))
        ) + super(UserAdmin, self).get_urls()

    def add_view(self, request):
        # It's an error for a user to have add permission but NOT change
        # permission for users. If we allowed such users to add users, they
        # could create superusers, which would mean they would essentially have
        # the permission to change users. To avoid the problem entirely, we
        # disallow users from adding users if they don't have change
        # permission.
        if not self.has_change_permission(request):
            if self.has_add_permission(request) and settings.DEBUG:
                # Raise Http404 in debug mode so that the user gets a helpful
                # error message.
                raise Http404('Your user does not have the "Change user" permission. In order to add users, Django requires that your user account have both the "Add user" and "Change user" permissions set.')
            raise PermissionDenied
        if request.method == 'POST':
            form = self.add_form(request.POST)
            if form.is_valid():
                new_user = form.save()
                msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': 'user', 'obj': new_user}
                self.log_addition(request, new_user)
                if "_addanother" in request.POST:
                    request.user.message_set.create(message=msg)
                    return HttpResponseRedirect(request.path)
                elif '_popup' in request.REQUEST:
                    return self.response_add(request, new_user)
                else:
                    request.user.message_set.create(message=msg + ' ' + ugettext("You may edit it again below."))
                    return HttpResponseRedirect('../%s/' % new_user.id)
        else:
            form = self.add_form()
        return render_to_response('admin/auth/user/add_form.html', {
            'title': _('Add user'),
            'form': form,
            'is_popup': '_popup' in request.REQUEST,
            'add': True,
            'change': False,
            'has_add_permission': True,
            'has_delete_permission': False,
            'has_change_permission': True,
            'has_file_field': False,
            'has_absolute_url': False,
            'auto_populated_fields': (),
            'opts': self.model._meta,
            'save_as': False,
            'username_help_text': self.model._meta.get_field('username').help_text,
            'root_path': self.admin_site.root_path,
            'app_label': self.model._meta.app_label,
        }, context_instance=template.RequestContext(request))

    def user_change_password(self, request, id):
        if not self.has_change_permission(request):
            raise PermissionDenied
        user = get_object_or_404(self.model, pk=id)
        if request.method == 'POST':
            form = self.change_password_form(user, request.POST)
            if form.is_valid():
                new_user = form.save()
                msg = ugettext('Password changed successfully.')
                request.user.message_set.create(message=msg)
                return HttpResponseRedirect('..')
        else:
            form = self.change_password_form(user)
        return render_to_response('admin/auth/user/change_password.html', {
            'title': _('Change password: %s') % escape(user.username),
            'form': form,
            'is_popup': '_popup' in request.REQUEST,
            'add': True,
            'change': False,
            'has_delete_permission': False,
            'has_change_permission': True,
            'has_absolute_url': False,
            'opts': self.model._meta,
            'original': user,
            'save_as': False,
            'show_save': True,
            'root_path': self.admin_site.root_path,
        }, context_instance=RequestContext(request))

admin.site.register(Group, GroupAdmin)
admin.site.register(User, UserAdmin)


text:
class Post < ActiveRecord::Base
  belongs_to :contributor
  validates :title, presence: true, length: { minimum: 5 }
  validates :content, presence: true, length: { minimum: 20 }
end


text:
/**
 * @file
 * Definitions of DPDK version numbers
 */

#ifndef _RTE_VERSION_H_
#define _RTE_VERSION_H_

#ifdef __cplusplus
extern "C" {
#endif

#include <string.h>
#include <stdio.h>
#include <rte_compat.h>

/**
 * Macro to compute a version number usable for comparisons
 */
#define RTE_VERSION_NUM(a,b,c,d) ((a) << 24 | (b) << 16 | (c) << 8 | (d))

/**
 * All version numbers in one to compare with RTE_VERSION_NUM()
 */
#define RTE_VERSION RTE_VERSION_NUM( \
			RTE_VER_YEAR, \
			RTE_VER_MONTH, \
			RTE_VER_MINOR, \
			RTE_VER_RELEASE)

/**
 * Function to return DPDK version prefix string
 */
__rte_experimental
const char *rte_version_prefix(void);

/**
 * Function to return DPDK version year
 */
__rte_experimental
unsigned int rte_version_year(void);

/**
 * Function to return DPDK version month
 */
__rte_experimental
unsigned int rte_version_month(void);

/**
 * Function to return DPDK minor version number
 */
__rte_experimental
unsigned int rte_version_minor(void);

/**
 * Function to return DPDK version suffix for any release candidates
 */
__rte_experimental
const char *rte_version_suffix(void);

/**
 * Function to return DPDK version release candidate value
 */
__rte_experimental
unsigned int rte_version_release(void);

/**
 * Function returning version string
 * @return
 *     DPDK version string
 */
const char *rte_version(void);

#ifdef __cplusplus
}
#endif

#endif /* RTE_VERSION_H */


text:
using openxc::util::log::debug;
using openxc::signals::getCanBuses;
using openxc::signals::getCanBusCount;
using openxc::can::lookupBus;

namespace can = openxc::can;
namespace interface = openxc::interface;

bool openxc::commands::handleCan(openxc_VehicleMessage* message,
        openxc::interface::InterfaceDescriptor* sourceInterfaceDescriptor) {
    bool status = true;
    if(message->type == openxc_VehicleMessage_Type_CAN) {
        openxc_CanMessage* canMessage = &message->can_message;
        CanBus* matchingBus = NULL;
        if(canMessage->bus >= 0) {
            matchingBus = lookupBus(canMessage->bus, getCanBuses(), getCanBusCount());
	}
        if((matchingBus == NULL) && (canMessage->bus == 0) && (getCanBusCount() > 0)) {	// Could not find a bus of 0 so use 1st one if one not asked for
            matchingBus = &getCanBuses()[0];
            debug("No bus specified for write, using the first active: %d", matchingBus->address);
        }
        if(!sourceInterfaceDescriptor->allowRawWrites) {
            debug("Direct CAN message writes not allowed from %s interface",
                    interface::descriptorToString(sourceInterfaceDescriptor));
            status = false;
        } else if(matchingBus == NULL) {
            debug("No matching active bus for requested address: %d",
                    canMessage->bus);
            status = false;
        } else if(matchingBus->rawWritable) {
            uint8_t size = canMessage->data.size;
            CanMessageFormat format;

            if(canMessage->frame_format != openxc_CanMessage_FrameFormat_UNUSED) {
                format = canMessage->frame_format ==
                        openxc_CanMessage_FrameFormat_STANDARD ?
                            CanMessageFormat::STANDARD :
                            CanMessageFormat::EXTENDED;
            } else {
                format = canMessage->id > 2047 ?
                    CanMessageFormat::EXTENDED : CanMessageFormat::STANDARD;
            }

            CanMessage message = {
                id: canMessage->id,
                format: format
            };
            memcpy(message.data, canMessage->data.bytes, size);
            message.length = size;
            can::write::enqueueMessage(matchingBus, &message);
        } else {
            debug("Raw CAN writes not allowed for bus %d", matchingBus->address);
            status = false;
        }
    }
    return status;
}

bool openxc::commands::validateCan(openxc_VehicleMessage* message) {
    bool valid = true;
    if(message->type == openxc_VehicleMessage_Type_CAN) {
        openxc_CanMessage* canMessage = &message->can_message;
        if(canMessage->id == 0) {
            valid = false;
            debug("Write request is malformed, missing id");
        }

        if (canMessage->frame_format == openxc_CanMessage_FrameFormat_STANDARD &&
                canMessage->id > 0xff) {
            valid = false;
            debug("ID in raw write request (0x%02x) is too large "
                    "for explicit standard frame format", canMessage->id);
        }
    } else {
        valid = false;
    }
    return valid;
}


text:
$(document).ready(function() {
    $('.button-collapse').sideNav({
        menuWidth: 300, // Default is 240
        edge: 'left', // Choose the horizontal origin
        closeOnClick: true // Closes side-nav on <a> clicks, useful for Angular/Meteor
    });

    $('.collapsible').collapsible({
      accordion : false // A setting that changes the collapsible behavior to expandable instead of the default accordion style
    });
    // $('select').material_select();
    // $('.collapsible').collapsible({
    //   accordion : false // A setting that changes the collapsible behavior to expandable instead of the default accordion style
    // });
});


text:
/*
 * 1.0 code.
 */

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.TextArea;
import java.awt.GridLayout;

public class LamePrintThread extends Applet {

    TextArea display = new TextArea(1, 80);

    public void init() {
        //Create the text area and make it uneditable.
    	display = new TextArea(1, 80);
        display.setEditable(false);

	//Set the layout manager so that the text area
	//will be as wide as possible.
        setLayout(new GridLayout(1,0));

	//Add the text area to the applet.
        add(display);
        validate();

        addItem("init: " + threadInfo(Thread.currentThread()));
    }

    public void start() {
        addItem("start: " + threadInfo(Thread.currentThread()));
    }

    public void stop() {
        addItem("stop: " + threadInfo(Thread.currentThread()));
    }

    public void destroy() {
        addItem("destroy: " + threadInfo(Thread.currentThread()));
    }

    String threadInfo(Thread t) {
        return "thread=" + t.getName() + ", "
               + "thread group=" + t.getThreadGroup().getName();
    }

    void addItem(String newWord) {
        System.out.println(newWord);
        display.appendText(newWord + "\n");
        display.repaint();
    }

    //DO NOT IMPLEMENT update() and paint()!  Netscape Navigator 2.0
    //for Windows crashes if you do.
}


text:
# define READTABLE_REP_SIZE 128

struct dispmacro_param;

typedef lisp (*reader_macro_function)(lisp, Char);
typedef lisp (*reader_dispmacro_function)(lisp, Char, dispmacro_param &);

enum standard_char_type
{
  SCT_ILLEGAL,
  SCT_WHITESPACE,
  SCT_CONSTITUENT,
  SCT_SINGLE_ESCAPE,
  SCT_MULTIPLE_ESCAPE,
  SCT_TERM_MACRO,
  SCT_NON_TERM_MACRO
};

enum readtable_case
{
  RTC_UPCASE,
  RTC_DOWNCASE,
  RTC_PRESERVE,
  RTC_INVERT,
};

struct disptab_rep
{
  lisp lfunc;
  reader_dispmacro_function cfunc;
};

struct readtab_rep
{
  standard_char_type type;
  lisp lfunc;
  reader_macro_function cfunc;
  disptab_rep *disp;
};

class lreadtable: public lisp_object
{
public:
  readtab_rep *rep;
  readtable_case rcase;
  ~lreadtable ();
};

# define readtablep(X) typep ((X), Treadtable)

inline void
check_readtable (lisp x)
{
  check_type (x, Treadtable, Qreadtable);
}

inline readtab_rep *&
xreadtable_rep (lisp x)
{
  assert (readtablep (x));
  return ((lreadtable *)x)->rep;
}

inline readtable_case &
xreadtable_case (lisp x)
{
  assert (readtablep (x));
  return ((lreadtable *)x)->rcase;
}

# define _stdchar_type(rep, c) ((rep)[(c)].type)
# define _stdchar_type_p(rep, type, c) (_stdchar_type ((rep), (c)) == (type))

static inline standard_char_type
stdchar_type (const readtab_rep *rep, Char c)
{
  return ascii_char_p (c) ? _stdchar_type (rep, c) : SCT_CONSTITUENT;
}

static inline int
stdchar_type_p (const readtab_rep *rep, standard_char_type type, Char c)
{
  return ascii_char_p (c) && _stdchar_type_p (rep, type, c);
}

# define stdchar_illegal_p(rep, c) \
  stdchar_type_p ((rep), SCT_ILLEGAL, (c))
# define stdchar_whitespace_p(rep, c) \
  stdchar_type_p ((rep), SCT_WHITESPACE, (c))
# define stdchar_constituent_p(rep, c) \
  stdchar_type_p ((rep), SCT_CONSTITUENT, (c))
# define stdchar_single_escape_p(rep, c) \
  stdchar_type_p ((rep), SCT_SINGLE_ESCAPE, (c))
# define stdchar_multiple_escape_p(rep, c) \
  stdchar_type_p ((rep), SCT_MULTIPLE_ESCAPE, (c))
# define stdchar_terminating_macro_p(rep, c) \
  stdchar_type_p ((rep), SCT_TERM_MACRO, (c))
# define stdchar_non_terminating_macro_p(rep, c) \
  stdchar_type_p ((rep), SCT_NON_TERM_MACRO, (c))

lisp current_readtable ();
reader_dispmacro_function get_reader_dispmacro_function (lisp);
reader_macro_function get_reader_macro_function (lisp);

#endif


text:
require 'httparty'
require 'byebug'

class TVDB
  include HTTParty

  base_uri 'https://api.thetvdb.com/'

  attr_reader :token

  def token
    @token ||= begin
      results = self.class.post("/login", headers: headers, body: login_body.to_json)
      results.parsed_response.fetch("token")
    end
  end

  def get_episodes_by_id(id)
    self.class.get("/series/#{id}/episodes", headers: authorization)
  end

  private

    def headers
      { 'Content-Type' => 'application/json' }
    end

    def login_body
      {
        apikey: ENV["TVDB_APIKEY"],
        username: ENV["TVDB_USERNAME"],
        userkey: ENV["TVDB_USERKEY"]
      }
    end

    def authorization
      { 'Authorization': 'Bearer ' + token }
    end
end


text:
@implementation SKNode (ChildrenClean)

- (void)cleanUpChildrenAndRemove
{
  for (SKNode *child in self.children) {
    [child cleanUpChildrenAndRemove];
  }
  [self removeAllActions];
  [self removeFromParent];
}

@end


text:
* Improvement: Tests for expired items without must-revalidate #20
* Improvement: Support for including Vary headers in cache keys #21
* Improvement: Test for the can_cache option #23
* Bugfix: Not adding timezone to dates #24
* Improvement: Add $defaultTtl to CacheStorage constructor #25
* Bugfix: Error caches responses for without vary headers #26
* Bugfix: stale-if-header not being added to max-age #27
* Bugfix: max-age and freshness confusing zero and null #28
* Bugfix: Use date() method to fix missing GMT #29
* Improvement: Tests for stale-if-error behaviour #30
* Improvement: Delete cache entries on both 404 and 410 responses #33
* Refactoring: Minor ValidationSubscriber.php cleanup #35
* Refactoring: Minor ValidationSubscriber.php cleanup #35
* Improvement: Extend caching ttl considerations #56
* Improvement: Add purge method #57
* Improvement: Integration test for the calculation of the "resident_time" #60
* Improvement: Support for PHP 7.0 & 7.1 #73

## 0.1.0 - 2014-10-29

* Initial release.