text:
<?php

/**
 * Sitemap model
 *
 * @method Mage_Sitemap_Model_Resource_Sitemap _getResource()
 * @method Mage_Sitemap_Model_Resource_Sitemap getResource()
 * @method string getSitemapType()
 * @method Mage_Sitemap_Model_Sitemap setSitemapType(string $value)
 * @method string getSitemapFilename()
 * @method Mage_Sitemap_Model_Sitemap setSitemapFilename(string $value)
 * @method string getSitemapPath()
 * @method Mage_Sitemap_Model_Sitemap setSitemapPath(string $value)
 * @method string getSitemapTime()
 * @method Mage_Sitemap_Model_Sitemap setSitemapTime(string $value)
 * @method int getStoreId()
 * @method Mage_Sitemap_Model_Sitemap setStoreId(int $value)
 *
 * @category    Mage
 * @package     Mage_Sitemap
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Sitemap_Model_Sitemap extends Mage_Core_Model_Abstract
{
    /**
     * Real file path
     *
     * @var string
     */
    protected $_filePath;

    /**
     * Init model
     */
    protected function _construct()
    {
        $this->_init('sitemap/sitemap');
    }

    protected function _beforeSave()
    {
        $io = new Varien_Io_File();
        $realPath = $io->getCleanPath(Mage::getBaseDir() . '/' . $this->getSitemapPath());

        /**
         * Check path is allow
         */
        if (!$io->allowedPath($realPath, Mage::getBaseDir())) {
            Mage::throwException(Mage::helper('sitemap')->__('Please define correct path'));
        }
        /**
         * Check exists and writeable path
         */
        if (!$io->fileExists($realPath, false)) {
            Mage::throwException(Mage::helper('sitemap')->__('Please create the specified folder "%s" before saving the sitemap.', Mage::helper('core')->escapeHtml($this->getSitemapPath())));
        }

        if (!$io->isWriteable($realPath)) {
            Mage::throwException(Mage::helper('sitemap')->__('Please make sure that "%s" is writable by web-server.', $this->getSitemapPath()));
        }
        /**
         * Check allow filename
         */
        if (!preg_match('#^[a-zA-Z0-9_\.]+$#', $this->getSitemapFilename())) {
            Mage::throwException(Mage::helper('sitemap')->__('Please use only letters (a-z or A-Z), numbers (0-9) or underscore (_) in the filename. No spaces or other characters are allowed.'));
        }
        if (!preg_match('#\.xml$#', $this->getSitemapFilename())) {
            $this->setSitemapFilename($this->getSitemapFilename() . '.xml');
        }

        $this->setSitemapPath(rtrim(str_replace(str_replace('\\', '/', Mage::getBaseDir()), '', $realPath), '/') . '/');

        return parent::_beforeSave();
    }

    /**
     * Return real file path
     *
     * @return string
     */
    protected function getPath()
    {
        if (is_null($this->_filePath)) {
            $this->_filePath = str_replace('//', '/', Mage::getBaseDir() .
                $this->getSitemapPath());
        }
        return $this->_filePath;
    }

    /**
     * Return full file name with path
     *
     * @return string
     */
    public function getPreparedFilename()
    {
        return $this->getPath() . $this->getSitemapFilename();
    }

    /**
     * Generate XML file
     *
     * @return Mage_Sitemap_Model_Sitemap
     */
    public function generateXml()
    {
        $io = new Varien_Io_File();
        $io->setAllowCreateFolders(true);
        $io->open(array('path' => $this->getPath()));

        if ($io->fileExists($this->getSitemapFilename()) && !$io->isWriteable($this->getSitemapFilename())) {
            Mage::throwException(Mage::helper('sitemap')->__('File "%s" cannot be saved. Please, make sure the directory "%s" is writeable by web server.', $this->getSitemapFilename(), $this->getPath()));
        }

        $io->streamOpen($this->getSitemapFilename());

        $io->streamWrite('<?xml version="1.0" encoding="UTF-8"?>' . "\n");
        $io->streamWrite('<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">');

        $storeId = $this->getStoreId();
        $date    = Mage::getSingleton('core/date')->gmtDate('Y-m-d');
        $baseUrl = Mage::app()->getStore($storeId)->getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK);

        /**
         * Generate categories sitemap
         */
        $changefreq = (string)Mage::getStoreConfig('sitemap/category/changefreq', $storeId);
        $priority   = (string)Mage::getStoreConfig('sitemap/category/priority', $storeId);
        $collection = Mage::getResourceModel('sitemap/catalog_category')->getCollection($storeId);
        $categories = new Varien_Object();
        $categories->setItems($collection);
        Mage::dispatchEvent('sitemap_categories_generating_before', array(
            'collection' => $categories
        ));
        foreach ($categories->getItems() as $item) {
            $xml = sprintf(
                '<url><loc>%s</loc><lastmod>%s</lastmod><changefreq>%s</changefreq><priority>%.1f</priority></url>',
                htmlspecialchars($baseUrl . $item->getUrl()),
                $date,
                $changefreq,
                $priority
            );
            $io->streamWrite($xml);
        }
        unset($collection);

        /**
         * Generate products sitemap
         */
        $changefreq = (string)Mage::getStoreConfig('sitemap/product/changefreq', $storeId);
        $priority   = (string)Mage::getStoreConfig('sitemap/product/priority', $storeId);
        $collection = Mage::getResourceModel('sitemap/catalog_product')->getCollection($storeId);
        $products = new Varien_Object();
        $products->setItems($collection);
        Mage::dispatchEvent('sitemap_products_generating_before', array(
            'collection' => $products
        ));
        foreach ($products->getItems() as $item) {
            $xml = sprintf(
                '<url><loc>%s</loc><lastmod>%s</lastmod><changefreq>%s</changefreq><priority>%.1f</priority></url>',
                htmlspecialchars($baseUrl . $item->getUrl()),
                $date,
                $changefreq,
                $priority
            );
            $io->streamWrite($xml);
        }
        unset($collection);

        /**
         * Generate cms pages sitemap
         */
        $changefreq = (string)Mage::getStoreConfig('sitemap/page/changefreq', $storeId);
        $priority   = (string)Mage::getStoreConfig('sitemap/page/priority', $storeId);
        $collection = Mage::getResourceModel('sitemap/cms_page')->getCollection($storeId);
        foreach ($collection as $item) {
            $xml = sprintf(
                '<url><loc>%s</loc><lastmod>%s</lastmod><changefreq>%s</changefreq><priority>%.1f</priority></url>',
                htmlspecialchars($baseUrl . $item->getUrl()),
                $date,
                $changefreq,
                $priority
            );
            $io->streamWrite($xml);
        }
        unset($collection);

        $io->streamWrite('</urlset>');
        $io->streamClose();

        $this->setSitemapTime(Mage::getSingleton('core/date')->gmtDate('Y-m-d H:i:s'));
        $this->save();

        return $this;
    }
}


text:
package com.onefishtwo.bbqtimer;

import android.view.View;
import android.widget.Checkable;

import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Matcher;

import androidx.annotation.NonNull;
import androidx.test.espresso.UiController;
import androidx.test.espresso.ViewAction;

import static androidx.test.espresso.action.ViewActions.click;
import static org.hamcrest.Matchers.any;
import static org.hamcrest.Matchers.isA;

class CustomViewActions {

    /**
     * Returns a {@code ViewAction} that waits for {@code msec} milliseconds. This should get a
     * fairly precise delay plus the usual wait-for-idle.
     *
     * @see UiController#loopMainThreadForAtLeast about looping the main thread
     * @see Espresso: Elapsed
     * time on creating and using an {@code IdlingResource} that can wait a long time. Reports
     * say Espresso polls an IdlingResource about every 5 seconds, so the timing precision is low.
     */
    @NonNull
    static ViewAction waitMsec(final long msec) {
        return new ViewAction() {
            @NonNull
            @Override
            public Matcher<View> getConstraints() {
                return any(View.class);
            }

            @NonNull
            @Override
            public String getDescription() {
                return "Wait " + msec + " msec.";
            }

            @Override
            public void perform(@NonNull UiController uiController, View view) {
                uiController.loopMainThreadForAtLeast(msec);
            }
        };
    }

    /** Clicks a checkbox if needed to put it into the desired state. */
    @SuppressWarnings({"SameParameterValue", "unused"})
    @NonNull
    static ViewAction setChecked(final boolean checked) {
        return new ViewAction() {
            @NonNull
            @Override
            public BaseMatcher<View> getConstraints() {
                return new BaseMatcher<>() {
                    @Override
                    public boolean matches(Object item) {
                        return isA(Checkable.class).matches(item);
                    }

                    @Override
                    public void describeMismatch(Object item, Description mismatchDescription) {}

                    @Override
                    public void describeTo(Description description) {}
                };
            }

            @NonNull
            @Override
            public String getDescription() {
                return "click if needed to check";
            }

            @Override
            public void perform(UiController uiController, View view) {
                Checkable checkableView = (Checkable) view;

                if (checkableView.isChecked() != checked) {
                    click().perform(uiController, view);
                }
            }
        };
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>

  <meta charset="utf-8">
  <title>My AngularJS App</title>
  <link rel="stylesheet" href="css/app.css"/>

view1

view2

log out

Angular seed app: v

Email: {{ user.email }}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

        <input type="text" ng-model="myFactory.hello"/>

        <input type="text" ng-model="myFactory.hello"/>


text: {% include components/brandname.html %}


text:
package es.tid.topologyModuleBase.IETFTopoModel.model;

import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-07-18T18:59:38.916+02:00")
public class NetworksSchemaSupportingNetwork   {

  private String networkRef = null;

  /**
   * References the underlay network.
   **/
  public NetworksSchemaSupportingNetwork networkRef(String networkRef) {
    this.networkRef = networkRef;
    return this;
  }

  @ApiModelProperty(value = "References the underlay network.")
  @JsonProperty("networkRef")
  public String getNetworkRef() {
    return networkRef;
  }
  public void setNetworkRef(String networkRef) {
    this.networkRef = networkRef;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    NetworksSchemaSupportingNetwork networksSchemaSupportingNetwork = (NetworksSchemaSupportingNetwork) o;
    return Objects.equals(networkRef, networksSchemaSupportingNetwork.networkRef);
  }

  @Override
  public int hashCode() {
    return Objects.hash(networkRef);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class NetworksSchemaSupportingNetwork {\n");

    sb.append("    networkRef: ").append(toIndentedString(networkRef)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private String toIndentedString(Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }
}


text:
{% extends "admin/import_export/change_list_import_export.html" %}
{% load i18n admin_urls static admin_list l10n %}

{% block extrastyle %}
  {{ block.super }}
{% endblock %}

{% block extrahead %}
{{ block.super }}

{% endblock %}

{#% block search %#}
{% block pagination %}
{{ block.super }}

Summary

            {% trans "Transaction summary" %}

            {% trans "Transfer" %}

            {% trans "Withdrawal" %}

            {% trans "Deposit" %}

            {% trans "Total" %}

    {% for row in cl.summary %}

        {{ row.name }}
        {{ row.transfer }}
        {{ row.withdrawal }}
        {{ row.deposit }}
        {{ row.total }}

    {% endfor %}

{% endblock %}


text:
<?php

/**
 * Swift Mailer PLAIN Authenticator Mechanism
 * Please read the LICENSE file
 * @author Chris Corbyn <chris@w3style.co.uk>
 * @package Swift_Authenticator
 * @license GNU Lesser General Public License
 */

require_once dirname(__FILE__) . "/../ClassLoader.php";
Swift_ClassLoader::load("Swift_Authenticator");

/**
 * Swift PLAIN Authenticator
 * This form of authentication is unbelievably insecure since everything is done plain-text
 * @package Swift_Authenticator
 * @author Chris Corbyn <chris@w3style.co.uk>
 */
class Swift_Authenticator_PLAIN extends Swift_Authenticator
{
  /**
   * Try to authenticate using the username and password
   * Returns false on failure
   * @param string The username
   * @param string The password
   * @param Swift The instance of Swift this authenticator is used in
   * @return boolean
   */
  function isAuthenticated($user, $pass, &$swift)
  {
    //The authorization string uses ascii null as a separator (See RFC 2554)
    $credentials = base64_encode($user . chr(0) . $user . chr(0) . $pass);
    Swift_ClassLoader::load("Swift_Errors");
    Swift_Errors::expect($e, "Swift_ConnectionException");
      $swift->command("AUTH PLAIN " . $credentials, 235);
    if ($e) {
      $swift->reset();
      return false;
    }
    Swift_Errors::clear("Swift_ConnectionException");
    return true;
  }
  /**
   * Return the name of the AUTH extension this is for
   * @return string
   */
  function getAuthExtensionName()
  {
    return "PLAIN";
  }
}


text:
/****************************************************************************/
/* Copyright 2005-2006, Francis Russell                                     */
/*                                                                          */
/* 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.                                           */
/*                                                                          */
/****************************************************************************/

#ifndef DESOLA_PROFILNG_BINOP_HPP
#define DESOLA_PROFILNG_BINOP_HPP

#include "Desola_profiling_fwd.hpp"
#include <map>
#include <cassert>

namespace desola
{

namespace detail
{

template<typename resultType, typename leftType, typename rightType, typename T_element>
class PBinOp : public PExprNode<resultType, T_element>
{
private:
  PExprNode<leftType, T_element>* left;
  PExprNode<rightType, T_element>* right;

public:
  bool isEqual(const PBinOp& node, const std::map<const PExpressionNode<T_element>*, const PExpressionNode<T_element>*>& mappings) const
  {
    assert(mappings.find(left) != mappings.end());
    assert(mappings.find(right) != mappings.end());

    return PExprNode<resultType, T_element>::isEqual(node, mappings) &&
	   mappings.find(left)->second == node.left &&
	   mappings.find(right)->second == node.right;
  }

  PBinOp(PExprNode<leftType, T_element>& l, PExprNode<rightType, T_element>& r) : PExprNode<resultType, T_element>(), left(&l), right(&r)
  {
  }

  inline PExprNode<leftType, T_element>& getLeft()
  {
    return *left;
  }

  inline const PExprNode<leftType, T_element>& getLeft() const
  {
    return *left;
  }

  inline PExprNode<rightType, T_element>& getRight()
  {
    return *right;
  }

  inline const PExprNode<rightType, T_element>& getRight() const
  {
    return *right;
  }
};

}

}

#endif


text:
import sys
import os
from win32com.shell import shellcon, shell

# Should be programdata files folder
ROOT_FOLDER = os.path.join(
    shell.SHGetFolderPath(0, shellcon.CSIDL_COMMON_APPDATA, None, 0), "ope")

TMP_FOLDER = os.path.join(ROOT_FOLDER, "tmp")
LOG_FOLDER = os.path.join(TMP_FOLDER, "log")
SCREEN_SHOTS_FOLDER = os.path.join(TMP_FOLDER, "screen_shots")
GIT_FOLDER = os.path.join(ROOT_FOLDER, "ope_laptop_binaries")
BINARIES_FOLDER = os.path.join(ROOT_FOLDER, "Services")
STUDENT_DATA_FOLDER = os.path.join(ROOT_FOLDER, "student_data")
LOCK_SCREEN_WIDGET_FOLDER = os.path.join(TMP_FOLDER, "lock_screen_widget")

# The base function called
CMD_FUNCTION = ""

global APP_FOLDER
APP_FOLDER = None
def get_app_folder():
    global APP_FOLDER
    ret = ""
    # Adjusted to save APP_FOLDER - issue #6 - app_folder not returning the same folder later in the app?
    if APP_FOLDER is None:
        # return the folder this app is running in.
        # Logger.info("Application: get_app_folder called...")
        if getattr(sys, 'frozen', False):
            # Running in pyinstaller bundle
            ret = sys._MEIPASS
            # Logger.info("Application: sys._MEIPASS " + sys._MEIPASS)
            # Adjust to use sys.executable to deal with issue #6 - path different if cwd done
            # ret = os.path.dirname(sys.executable)
            # Logger.info("AppPath: sys.executable " + ret)

        else:
            ret = os.path.dirname(os.path.abspath(__file__))
            # Logger.info("AppPath: __file__ " + ret)
        APP_FOLDER = ret
        # Add this folder to the os path so that resources can be found more reliably
        #text_dir = os.path.join(APP_FOLDER, "kivy\\core\\text")
        #os.environ["PATH"] = os.environ["PATH"] + ";" + ret + ";" + text_dir
        #print("-- ADJUSTING SYS PATH -- " + os.environ["PATH"])

    else:
        ret = APP_FOLDER
    return ret

get_app_folder()

def get_dict_value(source_dict, key_name, default=""):
    ret = default
    if key_name in source_dict:
        ret = source_dict[key_name]
    return ret

def pop_force_flag(only_for=None):
    # See if the -f is present in the params and remove it if it is.
    ret = False

    global CMD_FUNCTION

    # only_for - just return param if it is the root call, otherwise False
    if not only_for is None:
        if CMD_FUNCTION != only_for:
            return ret

    for i in range(len(sys.argv)):
        p = sys.argv[i]
        if p.lower() == "-f":
            #print("Found force flag!")
            ret = True
            sys.argv.remove(p)
            break

    return ret
def get_param(param_index=1, default_value="", only_for=None):
    # Get the requested parameter or default value if non existent
    ret = default_value

    global CMD_FUNCTION

    # only_for - just return param if it is the root call
    if not only_for is None:
        if CMD_FUNCTION != only_for:
            return ret

    if len(sys.argv) >=param_index + 1:
        ret = sys.argv[param_index]

    return ret

def test_params():

    force_on = pop_force_flag()
    print("Force: " + str(force_on))
    print("Params:")
    for i in range(len(sys.argv)):
        print("Param " + str(i) + "=>" + str(sys.argv[i]))
    print(len(sys.argv))
    return

if __name__ == "__main__":
    # Test the params
    test_params()


text:
namespace PS
{
	class BloodParticle : public sf::RectangleShape
	{
	public:
		BloodParticle();
		void Update(float timeStep);

		sf::Vector2f speed;
	};
}

#endif //PROJECT_SACRIFICE_BLOODPARTICLE_H


text:
<?php

/**
* Template Simple
* Simple Template class for Powerstack
*
* @author Christopher Tombleson <chris@powerstack-php.org>
* @package Powerstack
* @subpackage Core
*/

namespace Powerstack\Core;

class TemplateSimple {
    /**
    * @access private
    * @var string
    */
    private $viewsdir;

    /**
    * @access private
    * @var stdclass
    */
    private $conf;

    /**
    * Init
    * Initialize template engine
    *
    * Configuration:
    *   app/config.xml:
    *       <template>
    *           <engine>simple</engine>
    *           ...
    *       </template>
    *
    * @return bool true
    */
    function init() {
        $this->conf = config('template');
        $this->viewsdir = rtrim($this->conf->viewsdir, '/') . '/';
        return true;
    }

    /**
    * Render
    * Render a template
    *
    * Hook before_template_render, function takes the $params as an argument for
    * changing values on the fly, function must return the $params array.
    *
    * @access public
    * @param string $tpl    Template to render
    * @param array  $params A key => value array of template replacement vars. (optional, default empty array)
    * @param string $layout Layout to use. (optional, default is default layout)
    * @return string template
    */
    function render($tpl, $params=array(), $layout='default') {
        global $hooks;

        if (!file_exists($this->viewsdir . $tpl)) {
            throw new \Exception("Template: " . $tpl . ", was not found in " . $this->viewsdir);
        }

        if (!isset($params['SITENAME'])) {
            $conf = config('application');
            $params['SITENAME'] = $conf->name;
        }

        $prerender = $hooks->get('before_template_render');

        if (!empty($prerender)) {
            foreach ($prerender as $hook) {
                if (is_array($hook)) {
                    $params = call_user_func($hook, $params);
                } else {
                    $params = $hook($params);
                }
            }
        }

        $layout = file_get_contents($this->conf->layouts->{$layout}->file);
        $template = file_get_contents($this->viewsdir . $tpl);

        preg_match_all('#\{\{\s+?([a-zA-z0-9_\-]+)\s+?\}\}#', $template, $matches);

        if (!empty($matches)) {
            $count = count($matches[0]);

            for ($i = 0; $i < $count; $i++) {
                if (isset($params[$matches[1][$i]])) {
                    $template = preg_replace('#' . preg_quote($matches[0][$i]) . '#', $params[$matches[1][$i]], $template);
                }
            }
        }

        preg_match_all('#\{\{\s+?([a-zA-Z0-9_\-]+)\s+?\}\}#', $layout, $matches);

        if (!empty($matches)) {
            $count = count($matches[0]);

            for ($i = 0; $i < $count; $i++) {
                if (isset($params[$matches[1][$i]])) {
                    $layout = preg_replace('#' . preg_quote($matches[0][$i]) . '#', $params[$matches[1][$i]], $layout);
                }

                if ($matches[1][$i] == 'CONTENT') {
                    $layout = preg_replace('#' . preg_quote($matches[0][$i]) . '#', $template, $layout);
                }
            }
        }

        return $layout;
    }
}
?>


text:
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Windows.Controls;
using mzPlot;
using EngineLayer;

namespace GuiFunctions
{
    public class ParentChildScanPlotsView
    {
        public ObservableCollection<ParentChildScanPlotTemplate> Plots { get; set; }

        public ParentChildScanPlotsView()
        {
            Plots = new ObservableCollection<ParentChildScanPlotTemplate>();
        }
    }

    public class ParentChildScanPlotTemplate
    {
        public PeptideSpectrumMatchPlot Plot { get; set; }

        public string SpectrumLabel { get; set; }

        public Canvas TheCanvas { get; set; }
    }
}


text:
Ext.define('Flamingo.view.oozie.dashboard.monitoring.TimeGridDetailPopController', {
    extend: 'Ext.app.ViewController',
    alias: 'controller.timeGridDetailPopController',

    onAfterrender: function (view) {
        var refs = this.getReferences();
        var store = this.getStore('workflowActionStore');
        var url = CONSTANTS.OOZIE.WORKFLOW.JOB.DEFINITION.SELECT;

        refs.wfForm.getForm().setValues(view.inputData.getData());
        refs.detail.width = (window.innerWidth - 200) / 2;

        store.proxy.extraParams.timezoneId = getTimeZone();
        store.proxy.extraParams.jobId = view.inputData.get('id');
        store.load({
            callback: function (response) {
                if (response.length > 0) {
                    refs.actionForm.getForm().setValues(response[0].getData());

                    Ext.defer(function() {
                        refs.childgrid.getStore('childStore').load({
                            params: {
                                jobId: response[0].get('wf_job_id'),
                                timezoneId: getTimeZone(),
                                actionId: response[0].get('id')
                            }
                        });
                    }, 300);
                    refs.workflowgriddetail.getSelectionModel().select(0);
                }
            }
        });

        refs.txtDefinitionJobName.setValue(view.inputData.get('app_name'));
        refs.txtDefinitionJobId.setValue(view.inputData.get('id'));

        refs.updateBtn.setHidden(true);

        this.onDetailClick(url, view.inputData.get('id'), 'wfDefinition');
    },

    statusRenderer: function (value) {
        return statusConverter(value);
    },

    onDetailClick: function (url, jobId, reference) {
        var refs = this.getReferences();
        invokeGet(url,
            {jobId: jobId},
            function(response){
                switch (reference) {
                    case 'wfDefinition':
                        refs.definitionEditor.setValue(Ext.decode(response.responseText).map.jobDefinition);
                        break;
                    case 'wfConfiguration':
                        refs.confEditor.setValue(Ext.decode(response.responseText).map.jobConfiguration);
                        break;
                    case 'wfLog':
                        refs.logEditor.setValue(Ext.decode(response.responseText).map.jobLog);
                        break;
                    default:
                        break;
                }
            },
            function(response, opts){
                error(message.msg('common.warning'), format(message.msg('common.failure'), config['system.admin.email']));
            }
        );
    },

    onWfTabChangePop: function (tabPanel, newCard, oldCard, eOpts) {
        var refs = this.getReferences();
        var url;
        var jobName = tabPanel.up('window').inputData.get('app_name');
        var jobId = tabPanel.up('window').inputData.get('id');

        if (jobId == '') return;

        switch (newCard.reference) {
            case 'wfDefinition':
                url = CONSTANTS.OOZIE.WORKFLOW.JOB.DEFINITION.SELECT;
                refs.txtDefinitionJobName.setValue(jobName);
                refs.txtDefinitionJobId.setValue(jobId);
                break;
            case 'wfConfiguration':
                url = CONSTANTS.OOZIE.WORKFLOW.JOB.CONFIGURATION.SELECT;
                refs.txtConfJobName.setValue(jobName);
                refs.txtConfJobId.setValue(jobId);
                break;
            case 'wfLog':
                url = CONSTANTS.OOZIE.WORKFLOW.JOB.LOG.SELECT;
                refs.txtLogJobName.setValue(jobName);
                refs.txtLogJobId.setValue(jobId);
                break;
            default:
                break;
        }

        this.onDetailClick(url, jobId, newCard.reference);
    },

    onActionDetailTabChange: function (tabPanel, newCard, oldCard, eOpts) {
        var refs = this.getReferences();
        switch (newCard.reference) {
            case 'actionForm':
                break;
            case 'configuration':
                refs.configuration.setValue(refs.workflowgriddetail.getSelectionModel().getSelection()[0].get('configuration'));
                break;
            default:
                break;
        }
    },

    onActionRowDblClick: function (grid , record , tr , rowIndex , e , eOpts) {
        var refs = this.getReferences();
        refs.actionForm.getForm().setValues(record.getData());
        refs.configuration.setValue(record.get('configuration'));

        Ext.defer(function() {
            refs.childgrid.getStore('childStore').load({
                params: {
                    jobId: record.get('wf_job_id'),
                    timezoneId: getTimeZone(),
                    actionId: record.get('id')
                }
            });
        }, 300);
    },

    onConsoleURL: function () {
        var refs = this.getReferences();
        window.open(refs.actionForm.getForm().getValues().console_url);
    }
});


text:
require File.expand_path('../spec_helper', __FILE__)

describe Datajam::Datacard::MagicAttrs do
  subject do
    DummyMagicAttrs
  end

  describe ".attr_magic" do
    context "when list of names given" do
      it "registers magic attr writer for specified names" do
        subject.attr_magic :foo, :bar
        subject.new.tap do |inst|
          inst.foo "x"
          inst.foo.should == "x"
          inst.bar "y"
          inst.bar.should == "y"
        end
      end
    end

    context "when single name given" do
      it "registers magic attr writer for specified name" do
        subject.attr_magic :baz
        subject.new.tap do |inst|
          inst.baz "x"
          inst.baz.should == "x"
          inst.baz = "y"
          inst.baz.should == "y"
        end
      end
    end
  end
end


text:
title: Web UI
---

# Chronos Web UI

### Compiling Assets

**Node.js is required to build assets**

Assets are automatically compiled when running `mvn package`. If you change assets, and want them updated in your jar, you must either `rm -rf src/main/resources/assets/build` or `mvn clean`.

### Modifying Assets

To modify assets and have changes reflected on the fly, you will need to start Chronos with a specially configured YAML file. The configuration is quite simple and is documented at [dropwizard-configurable-assets-bundle](https://github.com/bazaarvoice/dropwizard-configurable-assets-bundle/blob/master/README.md).

### Build Requirements

When building and optimizing the assets, make sure you have at least 1GB of RAM available.


text:
#ifndef _C4_MEMORY_RESOURCE_HPP_
#define _C4_MEMORY_RESOURCE_HPP_

/** @file memory_resource.hpp Provides facilities to allocate typeless
 *  memory, via the memory resource model consecrated with C++17. */

/** @defgroup memory memory utilities */

/** @defgroup raw_memory_alloc Raw memory allocation
 * @ingroup memory
 */

/** @defgroup memory_resources Memory resources
 * @ingroup memory
 */

#include "c4/config.hpp"
#include "c4/error.hpp"

namespace c4 {

// need these forward decls here
struct MemoryResource;
struct MemoryResourceMalloc;
struct MemoryResourceStack;
MemoryResourceMalloc* get_memory_resource_malloc();
MemoryResourceStack* get_memory_resource_stack();
namespace detail { MemoryResource*& get_memory_resource(); }

// c-style allocation ---------------------------------------------------------

// this API provides aligned allocation functions.
// These functions forward the call to a user-modifiable function.

// aligned allocation.

/** Aligned allocation. Merely calls the current get_aalloc() function.
 * @see get_aalloc()
 * @ingroup raw_memory_alloc */
void* aalloc(size_t sz, size_t alignment);

/** Aligned free. Merely calls the current get_afree() function.
 * @see get_afree()
 * @ingroup raw_memory_alloc */
void afree(void* ptr);

/** Aligned reallocation. Merely calls the current get_arealloc() function.
 * @see get_arealloc()
 * @ingroup raw_memory_alloc */
void* arealloc(void* ptr, size_t oldsz, size_t newsz, size_t alignment);

// allocation setup facilities.

/** Function pointer type for aligned allocation
 * @see set_aalloc()
 * @ingroup raw_memory_alloc */
using aalloc_pfn   = void* (*)(size_t size, size_t alignment);

/** Function pointer type for aligned deallocation
 * @see set_afree()
 * @ingroup raw_memory_alloc */
using afree_pfn    = void  (*)(void *ptr);

/** Function pointer type for aligned reallocation
 * @see set_arealloc()
 * @ingroup raw_memory_alloc */
using arealloc_pfn = void* (*)(void *ptr, size_t oldsz, size_t newsz, size_t alignment);

// allocation function pointer setters/getters

/** Set the global aligned allocation function.
 * @see aalloc()
 * @see get_aalloc()
 * @ingroup raw_memory_alloc */
void set_aalloc  (aalloc_pfn   fn);

/** Set the global aligned deallocation function.
 * @see afree()
 * @see get_afree()
 * @ingroup raw_memory_alloc */
void set_afree   (afree_pfn    fn);

/** Set the global aligned reallocation function.
 * @see arealloc()
 * @see get_arealloc()
 * @ingroup raw_memory_alloc */
void set_arealloc(arealloc_pfn fn);

/** Get the global aligned reallocation function.
 * @see arealloc()
 * @ingroup raw_memory_alloc */
aalloc_pfn   get_aalloc();

/** Get the global aligned deallocation function.
 * @see afree()
 * @ingroup raw_memory_alloc */
afree_pfn     get_afree();

/** Get the global aligned reallocation function.
 * @see arealloc()
 * @ingroup raw_memory_alloc */
arealloc_pfn get_arealloc();

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// c++-style allocation -------------------------------------------------------

/** C++17-style memory_resource base class. See http://en.cppreference.com/w/cpp/experimental/memory_resource
 * @ingroup memory_resources */
struct MemoryResource
{
    const char *name = nullptr;
    virtual ~MemoryResource() {}

    void* allocate(size_t sz, size_t alignment=alignof(max_align_t), void *hint=nullptr)
    {
        void *mem = this->do_allocate(sz, alignment, hint);
        C4_CHECK_MSG(mem != nullptr, "could not allocate %lu bytes", sz);
        return mem;
    }

    void* reallocate(void* ptr, size_t oldsz, size_t newsz, size_t alignment=alignof(max_align_t))
    {
        void *mem = this->do_reallocate(ptr, oldsz, newsz, alignment);
        C4_CHECK_MSG(mem != nullptr, "could not reallocate from %lu to %lu bytes", oldsz, newsz);
        return mem;
    }

    void deallocate(void* ptr, size_t sz, size_t alignment = alignof(max_align_t))
    {
        this->do_deallocate(ptr, sz, alignment);
    }

protected:

    virtual void* do_allocate(size_t sz, size_t alignment, void* hint) = 0;
    virtual void* do_reallocate(void* ptr, size_t oldsz, size_t newsz, size_t alignment) = 0;
    virtual void  do_deallocate(void* ptr, size_t sz, size_t alignment) = 0;

};

/** get the current global memory resource. To avoid static initialization
 * order problems, this is implemented using a function call to ensure
 * that it is available when first used.
 * @ingroup memory_resources */
C4_ALWAYS_INLINE MemoryResource* get_memory_resource()
{
    return detail::get_memory_resource();
}

/** set the global memory resource
 * @ingroup memory_resources */
C4_ALWAYS_INLINE void set_memory_resource(MemoryResource* mr)
{
    C4_ASSERT(mr != nullptr);
    detail::get_memory_resource() = mr;
}

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
/** A c4::aalloc-based memory resource. Thread-safe if the implementation
 * called by c4::aalloc() is safe.
 * @ingroup memory_resources */
struct MemoryResourceMalloc : public MemoryResource
{

    MemoryResourceMalloc() { name = "malloc"; }
    virtual ~MemoryResourceMalloc() override {}

protected:

    virtual void* do_allocate(size_t sz, size_t alignment, void *hint) override
    {
        C4_UNUSED(hint);
        return c4::aalloc(sz, alignment);
    }

    virtual void  do_deallocate(void* ptr, size_t sz, size_t alignment) override
    {
        C4_UNUSED(sz);
        C4_UNUSED(alignment);
        c4::afree(ptr);
    }

    virtual void* do_reallocate(void* ptr, size_t oldsz, size_t newsz, size_t alignment) override
    {
        return c4::arealloc(ptr, oldsz, newsz, alignment);
    }

};

/** returns a malloc-based memory resource
 * @ingroup memory_resources */
C4_ALWAYS_INLINE MemoryResourceMalloc* get_memory_resource_malloc()
{
    static MemoryResourceMalloc mr;
    return &mr;
}

namespace detail {
C4_ALWAYS_INLINE MemoryResource* & get_memory_resource()
{
    thread_local static MemoryResource* mr = get_memory_resource_malloc();
    return mr;
}
} // namespace detail

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

namespace detail {

/** Allows a memory resource to obtain its memory from another memory resource.
 * @ingroup memory_resources */
struct DerivedMemoryResource : public MemoryResource
{
public:

    DerivedMemoryResource(MemoryResource *mr_=nullptr) : m_local(mr_ ? mr_ : get_memory_resource()) {}

private:

    MemoryResource *m_local;

protected:

    virtual void* do_allocate(size_t sz, size_t alignment, void* hint) override
    {
        return m_local->allocate(sz, alignment, hint);
    }

    virtual void* do_reallocate(void* ptr, size_t oldsz, size_t newsz, size_t alignment) override
    {
        return m_local->reallocate(ptr, oldsz, newsz, alignment);
    }

    virtual void do_deallocate(void* ptr, size_t sz, size_t alignment) override
    {
        return m_local->deallocate(ptr, sz, alignment);
    }
};

/** Provides common facilities for memory resource consisting of a single memory block
 * @ingroup memory_resources */
struct _MemoryResourceSingleChunk : public DerivedMemoryResource
{

    C4_NO_COPY_OR_MOVE(_MemoryResourceSingleChunk);

    using impl_type = DerivedMemoryResource;

public:

    _MemoryResourceSingleChunk(MemoryResource *impl=nullptr) : DerivedMemoryResource(impl) { name = "linear_malloc"; }

    /** initialize with owned memory, allocated from the given (or the global) memory resource */
    _MemoryResourceSingleChunk(size_t sz, MemoryResource *impl=nullptr) : _MemoryResourceSingleChunk(impl) { acquire(sz); }
    /** initialize with borrowed memory */
    _MemoryResourceSingleChunk(void *mem, size_t sz) : _MemoryResourceSingleChunk() { acquire(mem, sz); }

    virtual ~_MemoryResourceSingleChunk() override { release(); }

public:

    void const* mem() const { return m_mem; }

    size_t capacity() const { return m_size; }
    size_t size() const { return m_pos; }
    size_t slack() const { C4_ASSERT(m_size >= m_pos); return m_size - m_pos; }

public:

    char  *m_mem{nullptr};
    size_t m_size{0};
    size_t m_pos{0};
    bool   m_owner;

public:

    /** set the internal pointer to the beginning of the linear buffer */
    void clear() { m_pos = 0; }

    /** initialize with owned memory, allocated from the global memory resource */
    void acquire(size_t sz);
    /** initialize with borrowed memory */
    void acquire(void *mem, size_t sz);
    /** release the memory */
    void release();

};

} // namespace detail

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
/** provides a linear memory resource. Allocates incrementally from a linear
 * buffer, without ever deallocating. Deallocations are a no-op, and the
 * memory is freed only when the resource is release()d. The memory used by
 * this object can be either owned or borrowed. When borrowed, no calls to
 * malloc/free take place.
 *
 * @ingroup memory_resources */
struct MemoryResourceLinear : public detail::_MemoryResourceSingleChunk
{

    C4_NO_COPY_OR_MOVE(MemoryResourceLinear);

public:

    using detail::_MemoryResourceSingleChunk::_MemoryResourceSingleChunk;

protected:

    virtual void* do_allocate(size_t sz, size_t alignment, void *hint) override;
    virtual void  do_deallocate(void* ptr, size_t sz, size_t alignment) override;
    virtual void* do_reallocate(void* ptr, size_t oldsz, size_t newsz, size_t alignment) override;
};

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
/** provides a stack-type malloc-based memory resource.
 * @ingroup memory_resources */
struct MemoryResourceStack : public detail::_MemoryResourceSingleChunk
{

    C4_NO_COPY_OR_MOVE(MemoryResourceStack);

public:

    using detail::_MemoryResourceSingleChunk::_MemoryResourceSingleChunk;

protected:

    virtual void* do_allocate(size_t sz, size_t alignment, void *hint) override;
    virtual void  do_deallocate(void* ptr, size_t sz, size_t alignment) override;
    virtual void* do_reallocate(void* ptr, size_t oldsz, size_t newsz, size_t alignment) override;
};

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
/** provides a linear array-based memory resource.
 * @see MemoryResourceLinear
 * @ingroup memory_resources */
template<size_t N>
struct MemoryResourceLinearArr : public MemoryResourceLinear
{
    #ifdef _MSC_VER
    #pragma warning(push)
    #pragma warning(disable: 4324) // structure was padded due to alignment specifier
    #endif
    alignas(alignof(max_align_t)) char m_arr[N];
    #ifdef _MSC_VER
    #pragma warning(pop)
    #endif
    MemoryResourceLinearArr() : MemoryResourceLinear(m_arr, N) { name = "linear_arr"; }
};

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
struct AllocationCounts
{
    struct Item
    {
        ssize_t allocs;
        ssize_t size;

        void add(size_t sz)
        {
            ++allocs;
            size += static_cast<ssize_t>(sz);
        }
        void rem(size_t sz)
        {
            --allocs;
            size -= static_cast<ssize_t>(sz);
        }
        Item max(Item const& that) const
        {
            Item r(*this);
            r.allocs = r.allocs > that.allocs ? r.allocs : that.allocs;
            r.size = r.size > that.size ? r.size : that.size;
            return r;
        }
    };

    Item curr  = {0, 0};
    Item total = {0, 0};
    Item max   = {0, 0};

    void clear_counts()
    {
        curr  = {0, 0};
        total = {0, 0};
        max   = {0, 0};
    }

    void update(AllocationCounts const& that)
    {
        curr.allocs += that.curr.allocs;
        curr.size += that.curr.size;
        total.allocs += that.total.allocs;
        total.size += that.total.size;
        max.allocs += that.max.allocs;
        max.size += that.max.size;
    }

    void add_counts(void* ptr, size_t sz)
    {
        if(ptr == nullptr) return;
        curr.add(sz);
        total.add(sz);
        max = max.max(curr);
    }

    void rem_counts(void *ptr, size_t sz)
    {
        if(ptr == nullptr) return;
        curr.rem(sz);
    }

    AllocationCounts operator- (AllocationCounts const& that) const
    {
        AllocationCounts r(*this);
        r.curr.allocs -= that.curr.allocs;
        r.curr.size -= that.curr.size;
        r.total.allocs -= that.total.allocs;
        r.total.size -= that.total.size;
        r.max.allocs -= that.max.allocs;
        r.max.size -= that.max.size;
        return r;
    }

    AllocationCounts operator+ (AllocationCounts const& that) const
    {
        AllocationCounts r(*this);
        r.curr.allocs += that.curr.allocs;
        r.curr.size += that.curr.size;
        r.total.allocs += that.total.allocs;
        r.total.size += that.total.size;
        r.max.allocs += that.max.allocs;
        r.max.size += that.max.size;
        return r;
    }
};

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
/** a MemoryResource which latches onto another MemoryResource
 * and counts allocations and sizes.
 * @ingroup memory_resources */
class MemoryResourceCounts : public MemoryResource
{
public:

    MemoryResourceCounts() : m_resource(get_memory_resource())
    {
        C4_ASSERT(m_resource != this);
        name = "MemoryResourceCounts";
    }
    MemoryResourceCounts(MemoryResource *res) : m_resource(res)
    {
        C4_ASSERT(m_resource != this);
        name = "MemoryResourceCounts";
    }

    MemoryResource *resource() { return m_resource; }
    AllocationCounts const& counts() const { return m_counts; }

protected:

    MemoryResource *m_resource;
    AllocationCounts m_counts;

protected:

    virtual void* do_allocate(size_t sz, size_t alignment, void * /*hint*/) override
    {
        void *ptr = m_resource->allocate(sz, alignment);
        m_counts.add_counts(ptr, sz);
        return ptr;
    }

    virtual void  do_deallocate(void* ptr, size_t sz, size_t alignment) override
    {
        m_counts.rem_counts(ptr, sz);
        m_resource->deallocate(ptr, sz, alignment);
    }

    virtual void* do_reallocate(void* ptr, size_t oldsz, size_t newsz, size_t alignment) override
    {
        m_counts.rem_counts(ptr, oldsz);
        void* nptr = m_resource->reallocate(ptr, oldsz, newsz, alignment);
        m_counts.add_counts(nptr, newsz);
        return nptr;
    }

};

//-----------------------------------------------------------------------------
/** RAII class which binds a memory resource with a scope duration.
 * @ingroup memory_resources */
struct ScopedMemoryResource
{
    MemoryResource *m_original;

    ScopedMemoryResource(MemoryResource *r)
    :
        m_original(get_memory_resource())
    {
        set_memory_resource(r);
    }

    ~ScopedMemoryResource()
    {
        set_memory_resource(m_original);
    }
};

//-----------------------------------------------------------------------------
/** RAII class which counts allocations and frees inside a scope. Can
 * optionally set also the memory resource to be used.
 * @ingroup memory_resources */
struct ScopedMemoryResourceCounts
{
    MemoryResourceCounts mr;

    ScopedMemoryResourceCounts() : mr()
    {
        set_memory_resource(&mr);
    }
    ScopedMemoryResourceCounts(MemoryResource *m) : mr(m)
    {
        set_memory_resource(&mr);
    }
    ~ScopedMemoryResourceCounts()
    {
        set_memory_resource(mr.resource());
    }
};

} // namespace c4

#endif /* _C4_MEMORY_RESOURCE_HPP_ */


text:
package com.mongodb.client.model.search;

import com.mongodb.annotations.Beta;
import com.mongodb.annotations.Evolving;
import org.bson.BsonDocument;
import org.bson.BsonType;
import org.bson.BsonValue;
import org.bson.Document;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.conversions.Bson;

import java.time.Instant;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import static com.mongodb.assertions.Assertions.assertTrue;
import static com.mongodb.assertions.Assertions.isTrue;
import static com.mongodb.assertions.Assertions.isTrueArgument;
import static com.mongodb.internal.client.model.Util.sizeAtLeast;
import static java.lang.String.format;
import static com.mongodb.assertions.Assertions.notNull;

/**
 * A facet definition for {@link FacetSearchCollector}.
 *
 * @mongodb.atlas.manual atlas-search/facet/#facet-definition Facet definition
 * @since 4.7
 */
@Evolving
@Beta({Beta.Reason.CLIENT, Beta.Reason.SERVER})
public interface SearchFacet extends Bson {
    /**
     * Returns a {@link SearchFacet} that allows narrowing down search results based on the most frequent
     * BSON {@link BsonType#STRING String} values of the specified field.
     *
     * @param name The facet name.
     * @param path The field to facet on.
     * @return The requested {@link SearchFacet}.
     * @mongodb.atlas.manual atlas-search/facet/#string-facets String facet definition
     */
    static StringSearchFacet stringFacet(final String name, final FieldSearchPath path) {
        return new SearchConstructibleBsonElement(notNull("name", name),
                new Document("type", "string")
                        .append("path", notNull("path", path).toValue()));
    }

    /**
     * Returns a {@link SearchFacet} that allows determining the frequency of
     * BSON {@link BsonType#INT32 32-bit integer} / {@link BsonType#INT64 64-bit integer} / {@link BsonType#DOUBLE Double} values
     * in the search results by breaking the results into separate ranges.
     *
     * @param name The facet name.
     * @param path The path to facet on.
     * @param boundaries Bucket boundaries in ascending order. Must contain at least two boundaries.
     * @return The requested {@link SearchFacet}.
     * @mongodb.atlas.manual atlas-search/facet/#numeric-facets Numeric facet definition
     */
    static NumberSearchFacet numberFacet(final String name, final FieldSearchPath path, final Iterable<? extends Number> boundaries) {
        isTrueArgument("boundaries must contain at least 2 elements", sizeAtLeast(boundaries, 2));
        return new SearchConstructibleBsonElement(notNull("name", name),
                new Document("type", "number")
                        .append("path", notNull("path", path).toValue())
                        .append("boundaries", notNull("boundaries", boundaries)));
    }

    /**
     * Returns a {@link SearchFacet} that allows determining the frequency of BSON {@link BsonType#DATE_TIME Date} values
     * in the search results by breaking the results into separate ranges.
     *
     * @param name The facet name.
     * @param path The path to facet on.
     * @param boundaries Bucket boundaries in ascending order. Must contain at least two boundaries.
     * @return The requested {@link SearchFacet}.
     * @mongodb.atlas.manual atlas-search/facet/#date-facets Date facet definition
     * @see org.bson.codecs.jsr310.InstantCodec
     */
    static DateSearchFacet dateFacet(final String name, final FieldSearchPath path, final Iterable<Instant> boundaries) {
        isTrueArgument("boundaries must contain at least 2 elements", sizeAtLeast(boundaries, 2));
        return new SearchConstructibleBsonElement(notNull("name", name),
                new Document("type", "date")
                        .append("path", notNull("path", path).toValue())
                        .append("boundaries", notNull("boundaries", boundaries)));
    }

    /**
     * Creates a {@link SearchFacet} from a {@link Bson} in situations when there is no builder method that better satisfies your needs.
     * This method cannot be used to validate the syntax.
     *

     * Example

     * The following code creates two functionally equivalent {@link SearchFacet}s,
     * though they may not be {@linkplain Object#equals(Object) equal}.
     *
{@code
     *  SearchFacet facet1 = SearchFacet.stringFacet("facetName",
     *          SearchPath.fieldPath("fieldName"));
     *  SearchFacet facet2 = SearchFacet.of(new Document("facetName", new Document("type", "string")
     *          .append("path", SearchPath.fieldPath("fieldName").toValue())));
     * }

     *
     * @param facet A {@link Bson} representing the required {@link SearchFacet}.
     * @return The requested {@link SearchFacet}.
     */
    static SearchFacet of(final Bson facet) {
        return new SearchConstructibleBsonElement(notNull("facet", facet));
    }

    /**
     * Combines {@link SearchFacet}s into a {@link Bson}.
     *

     * This method may be useful when using {@link SearchCollector#of(Bson)}.

     *
     * @param facets The non-empty facet definitions to combine.
     * @return A {@link Bson} representing combined {@code facets}.
     */
    static Bson combineToBson(final Iterable<? extends SearchFacet> facets) {
        notNull("facets", facets);
        isTrueArgument("facets must not be empty", sizeAtLeast(facets, 1));
        return new Bson() {
            @Override
            public <TDocument> BsonDocument toBsonDocument(final Class<TDocument> documentClass, final CodecRegistry codecRegistry) {
                Set<String> names = new HashSet<>();
                BsonDocument result = new BsonDocument();
                for (final SearchFacet facet : facets) {
                    BsonDocument doc = facet.toBsonDocument(documentClass, codecRegistry);
                    assertTrue(doc.size() == 1);
                    Map.Entry<String, BsonValue> entry = doc.entrySet().iterator().next();
                    String name = entry.getKey();
                    isTrue(format("facet names must be unique. '%s' is used at least twice in %s", names, facets), names.add(name));
                    result.append(name, entry.getValue());
                }
                return result;
            }

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


text:
class Profile;

namespace browser_sync {

class ThemeDataTypeController : public syncer::AsyncDirectoryTypeController {
 public:
  // |dump_stack| is called when an unrecoverable error occurs.
  ThemeDataTypeController(const base::Closure& dump_stack,
                          syncer::SyncClient* sync_client,
                          Profile* profile);
  ~ThemeDataTypeController() override;

 private:
  // AsyncDirectoryTypeController implementation.
  bool StartModels() override;

  Profile* const profile_;
  DISALLOW_COPY_AND_ASSIGN(ThemeDataTypeController);
};

}  // namespace browser_sync

#endif  // CHROME_BROWSER_SYNC_GLUE_THEME_DATA_TYPE_CONTROLLER_H_


text:
<?php

namespace Application\Helper;

use Zend\View\Helper\AbstractHelper;
use Application\Components\Translate;

class TranslateHelper extends AbstractHelper
{

    public function __invoke ($text = "", $params = array())
    {
        return Translate::t($text, $params);
    }
}


text:
require 'minitest_helper'

class ResultTest < Minitest::Test
  def test_can_create_with_deafults
    assert Multiconnect::Connection::Result.new
  end

  def test_result_responds_to_success?
    assert Multiconnect::Connection::Result.new(status: :success).success?
    refute Multiconnect::Connection::Result.new.success?
  end

  def test_result_responds_to_using_fallback?
    result = Multiconnect::Connection::Result.new(connection: PrimaryConnection)
    assert result.using_fallback?(PrimaryConnection)
    refute result.using_fallback?(SecondaryConnection)
  end

  def test_result_delegates_method_missing_to_the_data
    assert_equal 2, Multiconnect::Connection::Result.new(data: [1, 2, 3])[1]
  end

  def test_result_responds_to_data
    assert_equal [1, 2, 3], Multiconnect::Connection::Result.new(data: [1, 2, 3]).data
  end
end


text:
package org.eclipse.php.internal.core.ast.nodes;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.eclipse.php.internal.core.PHPVersion;
import org.eclipse.php.internal.core.ast.match.ASTMatcher;
import org.eclipse.php.internal.core.ast.visitor.Visitor;

/**
 * Represents namespace declaration:
 *
 *
e.g.
 *
 *

 * namespace MyNamespace;
 *namespace MyProject\Sub\Level;
 */
public class NamespaceDeclaration extends Statement {

	private NamespaceName name;
	private Block body;
	private boolean bracketed = true;

	/**
	 * The "namespace" structural property of this node type.
	 */
	public static final ChildPropertyDescriptor NAME_PROPERTY = new ChildPropertyDescriptor(
			NamespaceDeclaration.class,
			"name", NamespaceName.class, OPTIONAL, NO_CYCLE_RISK); //$NON-NLS-1$

	public static final ChildPropertyDescriptor BODY_PROPERTY = new ChildPropertyDescriptor(
			NamespaceDeclaration.class,
			"body", Block.class, OPTIONAL, CYCLE_RISK); //$NON-NLS-1$

	public static final SimplePropertyDescriptor BRACKETED_PROPERTY = new SimplePropertyDescriptor(
			NamespaceDeclaration.class, "bracketed", Boolean.class, MANDATORY); //$NON-NLS-1$

	/**
	 * A list of property descriptors (element type:
	 * {@link StructuralPropertyDescriptor}), or null if uninitialized.
	 */
	private static final List<StructuralPropertyDescriptor> PROPERTY_DESCRIPTORS;
	static {
		List<StructuralPropertyDescriptor> properyList = new ArrayList<StructuralPropertyDescriptor>(
				2);
		properyList.add(NAME_PROPERTY);
		properyList.add(BODY_PROPERTY);
		properyList.add(BRACKETED_PROPERTY);
		PROPERTY_DESCRIPTORS = Collections.unmodifiableList(properyList);
	}

	public NamespaceDeclaration(AST ast) {
		super(ast);
	}

	public NamespaceDeclaration(int start, int end, AST ast,
			NamespaceName name, Block body, boolean bracketed) {
		super(start, end, ast);

		if (!bracketed && name == null) {
			throw new IllegalArgumentException(
					"Namespace name must not be null in an un-bracketed statement"); //$NON-NLS-1$
		}

		this.bracketed = bracketed;

		if (body == null) {
			body = new Block(end + 1, end + 1, ast, new ArrayList(), false);
		}
		body.setParent(this, BODY_PROPERTY);

		if (name != null) {
			name.setParent(this, NAME_PROPERTY);
		}

		this.name = name;
		this.body = body;
	}

	/**
	 * Returns whether this namespace declaration has a bracketed syntax
	 *
	 * @return
	 */
	public boolean isBracketed() {
		return bracketed;
	}

	public void setBracketed(boolean bracketed) {
		preValueChange(BRACKETED_PROPERTY);
		this.bracketed = bracketed;
		postValueChange(BRACKETED_PROPERTY);
	}

	public void addStatement(Statement statement) {
		Block body = getBody();
		body.statements().add(statement);

		int statementEnd = statement.getEnd();
		int bodyStart = body.getStart();
		body.setSourceRange(bodyStart, statementEnd - bodyStart + 1);

		int namespaceStart = getStart();
		setSourceRange(namespaceStart, statementEnd - namespaceStart);
	}

	/**
	 * The body component of this namespace declaration node
	 *
	 * @return body component of this namespace declaration node
	 */
	public Block getBody() {
		return body;
	}

	/**
	 * Sets the name of this parameter
	 *
	 * @param name
	 *            of this type declaration.
	 * @exception IllegalArgumentException
	 *                if:
	 *

	 *
the node belongs to a different AST

	 *
the node already has a parent

	 *
a cycle in would be created

	 *

	 */
	public void setBody(Block block) {
		// an Assignment may occur inside a Expression - must check cycles
		ASTNode oldChild = this.body;
		preReplaceChild(oldChild, block, BODY_PROPERTY);
		this.body = block;
		postReplaceChild(oldChild, block, BODY_PROPERTY);
	}

	/**
	 * The name component of this namespace declaration node
	 *
	 * @return name component of this namespace declaration node
	 */
	public NamespaceName getName() {
		return name;
	}

	/**
	 * Sets the name of this parameter
	 *
	 * @param name
	 *            of this type declaration.
	 * @exception IllegalArgumentException
	 *                if:
	 *

	 *
the node belongs to a different AST

	 *
the node already has a parent

	 *
a cycle in would be created

	 *

	 */
	public void setName(NamespaceName name) {
		// an Assignment may occur inside a Expression - must check cycles
		ASTNode oldChild = this.name;
		preReplaceChild(oldChild, name, NAME_PROPERTY);
		this.name = name;
		postReplaceChild(oldChild, name, NAME_PROPERTY);
	}

	public void childrenAccept(Visitor visitor) {
		NamespaceName name = getName();
		if (name != null) {
			name.accept(visitor);
		}
		Block body = getBody();
		body.accept(visitor);
	}

	public void traverseTopDown(Visitor visitor) {
		accept(visitor);
		NamespaceName name = getName();
		if (name != null) {
			name.accept(visitor);
		}
		Block body = getBody();
		body.accept(visitor);
	}

	public void traverseBottomUp(Visitor visitor) {
		NamespaceName name = getName();
		if (name != null) {
			name.accept(visitor);
		}
		Block body = getBody();
		body.accept(visitor);
		accept(visitor);
	}

	public void toString(StringBuffer buffer, String tab) {
		buffer.append(tab).append("<NamespaceDeclaration"); //$NON-NLS-1$
		appendInterval(buffer);
		buffer.append(" isBracketed='").append(bracketed).append("'>\n"); //$NON-NLS-1$ //$NON-NLS-2$

		NamespaceName name = getName();
		if (name != null) {
			name.toString(buffer, TAB + tab);
			buffer.append("\n"); //$NON-NLS-1$
		}

		Block body = getBody();
		body.toString(buffer, TAB + tab);
		buffer.append("\n"); //$NON-NLS-1$

		buffer.append(tab).append("</NamespaceDeclaration>"); //$NON-NLS-1$
	}

	public void accept0(Visitor visitor) {
		final boolean visit = visitor.visit(this);
		if (visit) {
			childrenAccept(visitor);
		}
		visitor.endVisit(this);
	}

	public int getType() {
		return ASTNode.NAMESPACE;
	}

	/*
	 * (omit javadoc for this method) Method declared on ASTNode.
	 */
	public boolean subtreeMatch(ASTMatcher matcher, Object other) {
		// dispatch to correct overloaded match method
		return matcher.match(this, other);
	}

	/*
	 * (omit javadoc for this method) Method declared on ASTNode.
	 */
	ASTNode clone0(AST target) {
		final NamespaceName name = ASTNode.copySubtree(target, getName());
		final Block body = ASTNode.copySubtree(target, getBody());
		final boolean bracketed = isBracketed();
		final NamespaceDeclaration result = new NamespaceDeclaration(this
				.getStart(), this.getEnd(), target, name, body, bracketed);
		return result;
	}

	@Override
	List<StructuralPropertyDescriptor> internalStructuralPropertiesForType(
			PHPVersion apiLevel) {
		return PROPERTY_DESCRIPTORS;
	}

	boolean internalGetSetBooleanProperty(SimplePropertyDescriptor property,
			boolean get, boolean value) {
		if (property == BRACKETED_PROPERTY) {
			if (get) {
				return isBracketed();
			} else {
				setBracketed(value);
				return false;
			}
		}
		return super.internalGetSetBooleanProperty(property, get, value);
	}

	final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property,
			boolean get, ASTNode child) {
		if (property == BODY_PROPERTY) {
			if (get) {
				return getBody();
			} else {
				setBody((Block) child);
				return null;
			}
		}
		if (property == NAME_PROPERTY) {
			if (get) {
				return getName();
			} else {
				setName((NamespaceName) child);
				return null;
			}
		}
		// allow default implementation to flag the error
		return super.internalGetSetChildProperty(property, get, child);
	}
}


text:
package com.paxport.json.ser;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.math.BigDecimal;

/**
 * Serialize Money correctly
 */
public class MoneySerializer extends JsonSerializer<BigDecimal> {
    @Override
    public void serialize(BigDecimal value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        jgen.writeString(format(value));
    }

    private static BigDecimal round(BigDecimal amount){
        return amount.setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    private static String format(BigDecimal amount){
        return round(amount).toPlainString();
    }
}


text:
<?php

/*
 * This file is part of PHP CS Fixer.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *     Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace PhpCsFixer\Fixer\Phpdoc;

use PhpCsFixer\AbstractFixer;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\DocBlock\Line;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Tokens;

/**
 * @author Graham Campbell <graham@alt-three.com>
 */
final class PhpdocSummaryFixer extends AbstractFixer implements WhitespacesAwareFixerInterface
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, Tokens $tokens)
    {
        foreach ($tokens as $token) {
            if (!$token->isGivenKind(T_DOC_COMMENT)) {
                continue;
            }

            $doc = new DocBlock($token->getContent());
            $end = $this->findShortDescriptionEnd($doc->getLines());

            if (null !== $end) {
                $line = $doc->getLine($end);
                $content = rtrim($line->getContent());

                if (!$this->isCorrectlyFormatted($content)) {
                    $line->setContent($content.'.'.$this->whitespacesConfig->getLineEnding());
                    $token->setContent($doc->getContent());
                }
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getDefinition()
    {
        return new FixerDefinition(
            'Phpdocs summary should end in either a full stop, exclamation mark, or question mark.',
            array(new CodeSample('<?php
/**
 * Foo function is great
 */
function foo () {}
'))
        );
    }

    /**
     * {@inheritdoc}
     */
    public function isCandidate(Tokens $tokens)
    {
        return $tokens->isTokenKindFound(T_DOC_COMMENT);
    }

    /**
     * Find the line number of the line containing the end of the short
     * description, if present.
     *
     * @param Line[] $lines
     *
     * @return int|null
     */
    private function findShortDescriptionEnd(array $lines)
    {
        $reachedContent = false;

        foreach ($lines as $index => $line) {
            // we went past a description, then hit a tag or blank line, so
            // the last line of the description must be the one before this one
            if ($reachedContent && ($line->containsATag() || !$line->containsUsefulContent())) {
                return $index - 1;
            }

            // no short description was found
            if ($line->containsATag()) {
                return null;
            }

            // we've reached content, but need to check the next lines too
            // in case the short description is multi-line
            if ($line->containsUsefulContent()) {
                $reachedContent = true;
            }
        }
    }

    /**
     * Is the last line of the short description correctly formatted?
     *
     * @param string $content
     *
     * @return bool
     */
    private function isCorrectlyFormatted($content)
    {
        if (false !== strpos(strtolower($content), '{@inheritdoc}')) {
            return true;
        }

        return $content !== rtrim($content, '.。!?¡¿!?');
    }
}


text:
package cz.jiripinkas.example.layout;

import com.vaadin.ui.MenuBar;
import com.vaadin.ui.UI;

import cz.jiripinkas.example.MyVaadinUI;

public class Menu extends MenuBar {

	public Menu() {
		setWidth("100%");
		MenuItem mainItem = addItem("Main", null);
		mainItem.addItem("Home", new MenuBar.Command() {
			@Override
			public void menuSelected(MenuItem selectedItem) {
				UI.getCurrent().getNavigator().navigateTo(MyVaadinUI.HOME_VIEW);
			}
		});
		mainItem.addItem("Items", new MenuBar.Command() {
			@Override
			public void menuSelected(MenuItem selectedItem) {
				UI.getCurrent().getNavigator().navigateTo(MyVaadinUI.ITEMS_VIEW);
			}
		});
		mainItem.addItem("Add item", new MenuBar.Command() {
			@Override
			public void menuSelected(MenuItem selectedItem) {
				UI.getCurrent().getNavigator().navigateTo(MyVaadinUI.ITEM_FORM_VIEW);
			}
		});
		mainItem.addItem("Basket", new MenuBar.Command() {
			@Override
			public void menuSelected(MenuItem selectedItem) {
				UI.getCurrent().getNavigator().navigateTo(MyVaadinUI.BASKET_VIEW);
			}
		});
		mainItem.addItem("User orders", new MenuBar.Command() {
			@Override
			public void menuSelected(MenuItem selectedItem) {
				UI.getCurrent().getNavigator().navigateTo(MyVaadinUI.USER_ORDERS_VIEW);
			}
		});
	}
}


text:
Presentations
=============

These are some of the presentations and guest lectures that I've given, organized by topic and date.


text: from . import dashboard, settings, tools, profile


text:
package org.gradle.jvm.toolchain.internal.install;

import org.gradle.api.provider.Provider;
import org.gradle.api.provider.ProviderFactory;
import org.gradle.internal.deprecation.DeprecationLogger;
import org.gradle.internal.jvm.inspection.JvmVendor;
import org.gradle.jvm.toolchain.JavaLanguageVersion;
import org.gradle.jvm.toolchain.JavaToolchainDownload;
import org.gradle.jvm.toolchain.JavaToolchainRequest;
import org.gradle.jvm.toolchain.JavaToolchainSpec;
import org.gradle.jvm.toolchain.JvmImplementation;
import org.gradle.jvm.toolchain.internal.DefaultJvmVendorSpec;
import org.gradle.platform.BuildPlatform;

import javax.inject.Inject;
import java.net.URI;
import java.util.Optional;

public class AdoptOpenJdkRemoteBinary {

    private static final String DEFAULT_ADOPTOPENJDK_ROOT_URL = "https://api.adoptopenjdk.net/";
    private static final String DEFAULT_ADOPTIUM_ROOT_URL = "https://api.adoptium.net/";

    private final Provider<String> adoptOpenJdkRootUrl;
    private final Provider<String> adoptiumRootUrl;

    @Inject
    public AdoptOpenJdkRemoteBinary(ProviderFactory providerFactory) {
        this.adoptOpenJdkRootUrl = providerFactory.gradleProperty("org.gradle.jvm.toolchain.install.adoptopenjdk.baseUri");
        this.adoptiumRootUrl = providerFactory.gradleProperty("org.gradle.jvm.toolchain.install.adoptium.baseUri");
    }

    public Optional<JavaToolchainDownload> resolve(JavaToolchainRequest request) {
        JavaToolchainSpec spec = request.getJavaToolchainSpec();
        if (canProvide(spec)) {
            return Optional.of(JavaToolchainDownload.fromUri(constructUri(spec, request.getBuildPlatform())));
        } else {
            return Optional.empty();
        }
    }

    private boolean canProvide(JavaToolchainSpec spec) {
        final boolean matchesLanguageVersion = determineLanguageVersion(spec).canCompileOrRun(8);
        boolean matchesVendor = matchesVendor(spec);
        return matchesLanguageVersion && matchesVendor;
    }

    private boolean matchesVendor(JavaToolchainSpec spec) {
        final DefaultJvmVendorSpec vendorSpec = (DefaultJvmVendorSpec) spec.getVendor().get();
        if (vendorSpec == DefaultJvmVendorSpec.any()) {
            return true;
        }

        if (vendorSpec.test(JvmVendor.KnownJvmVendor.ADOPTOPENJDK.asJvmVendor())) {
            DeprecationLogger.deprecateBehaviour("Due to changes in AdoptOpenJDK download endpoint, downloading a JDK with an explicit vendor of AdoptOpenJDK should be replaced with a spec without a vendor or using Eclipse Temurin / IBM Semeru.")
                    .willBeRemovedInGradle8().withUpgradeGuideSection(7, "adoptopenjdk_download").nagUser();
            return true;
        }

        if (vendorSpec.test(JvmVendor.KnownJvmVendor.ADOPTIUM.asJvmVendor()) && !isJ9ExplicitlyRequested(spec)) {
            return true;
        }

        return vendorSpec.test(JvmVendor.KnownJvmVendor.IBM_SEMERU.asJvmVendor());
    }

    private URI constructUri(JavaToolchainSpec spec, BuildPlatform platform) {
        return URI.create(determineServerBaseUri(spec) +
                "v3/binary/latest/" + determineLanguageVersion(spec) +
                "/" +
                determineReleaseState() +
                "/" +
                determineOs(platform) +
                "/" +
                determineArch(platform) +
                "/jdk/" +
                determineImplementation(spec) +
                "/normal/" +
                determineOrganization(spec));
    }

    private static String determineImplementation(JavaToolchainSpec spec) {
        return isJ9Requested(spec) ? "openj9" : "hotspot";
    }

    private static JavaLanguageVersion determineLanguageVersion(JavaToolchainSpec spec) {
        return spec.getLanguageVersion().get();
    }

    private String determineArch(BuildPlatform platform) {
        switch (platform.getArchitecture()) {
            case X86:
                return "x32";
            case X86_64:
                return "x64";
            case AARCH64:
                return "aarch64";
            default:
                return "unknown";
        }
    }

    private String determineOs(BuildPlatform platform) {
        switch (platform.getOperatingSystem()) {
            case LINUX:
                return "linux";
            case WINDOWS:
                return "windows";
            case MAC_OS:
                return "mac";
            case SOLARIS:
                return "solaris";
            default:
                return "unknown";
        }
    }

    private static String determineReleaseState() {
        return "ga";
    }

    private String determineServerBaseUri(JavaToolchainSpec spec) {
        String baseUri = adoptiumHasIt(spec) ? adoptiumRootUrl.getOrElse(DEFAULT_ADOPTIUM_ROOT_URL) :
                adoptOpenJdkRootUrl.getOrElse(DEFAULT_ADOPTOPENJDK_ROOT_URL);

        if (!baseUri.endsWith("/")) {
            baseUri += "/";
        }
        return baseUri;
    }

    private static String determineOrganization(JavaToolchainSpec spec) {
        return adoptiumHasIt(spec) ? "eclipse" : "adoptopenjdk";
    }

    private static boolean adoptiumHasIt(JavaToolchainSpec spec) { //TODO: also consider if ADOPTIUM was explicitly requested as the VENDOR?
        if (isJ9Requested(spec)) {
            return false;
        }

        int version = determineLanguageVersion(spec).asInt();
        return version == 8 || version == 11 || version >= 16; // https://api.adoptium.net/v3/info/available_releases
    }

    private static boolean isJ9Requested(JavaToolchainSpec spec) {
        if (isJ9ExplicitlyRequested(spec)) {
            return true;
        }
        return isJ9RequestedViaVendor(spec);
    }

    private static boolean isJ9ExplicitlyRequested(JavaToolchainSpec spec) {
        return spec.getImplementation().get() == JvmImplementation.J9;
    }

    private static boolean isJ9RequestedViaVendor(JavaToolchainSpec spec) {
        DefaultJvmVendorSpec vendorSpec = (DefaultJvmVendorSpec) spec.getVendor().get();
        return vendorSpec != DefaultJvmVendorSpec.any() && vendorSpec.test(JvmVendor.KnownJvmVendor.IBM_SEMERU.asJvmVendor());
    }

}


text:
require 'lotus/utils/class'
require 'lotus/utils/kernel'
require 'lotus/utils/string'
require 'lotus/routes'
require 'lotus/routing/default'
require 'lotus/action/session'
require 'lotus/config/security'
require 'lotus/action/routing_helpers'

module Lotus
  # Load an application
  #
  # @since 0.1.0
  # @api private
  class Loader

    STRICT_TRANSPORT_SECURITY_HEADER = 'Strict-Transport-Security'.freeze
    STRICT_TRANSPORT_SECURITY_DEFAULT_VALUE = 'max-age=31536000'.freeze

    def initialize(application)
      @application   = application
      @configuration = @application.configuration

      @mutex = Mutex.new
    end

    def load!
      @mutex.synchronize do
        load_configuration!
        configure_frameworks!
        load_configuration_load_paths!
        load_rack!
        load_frameworks!
      end
    end

    private
    attr_reader :application, :configuration

    def load_configuration!
      configuration.load!(application_module)
    end

    def configure_frameworks!
      _configure_model_framework! if defined?(Lotus::Model)
      _configure_controller_framework!
      _configure_view_framework!
      _configure_logger!
    end

    def _configure_controller_framework!
      config = configuration
      unless namespace.const_defined?('Controller')
        controller = Lotus::Controller.duplicate(namespace) do
          handle_exceptions config.handle_exceptions
          default_request_format config.default_request_format
          default_response_format config.default_response_format
          default_headers({
            Lotus::Config::Security::X_FRAME_OPTIONS_HEADER         => config.security.x_frame_options,
            Lotus::Config::Security::CONTENT_SECURITY_POLICY_HEADER => config.security.content_security_policy
          })
          default_headers.merge!(STRICT_TRANSPORT_SECURITY_HEADER => STRICT_TRANSPORT_SECURITY_DEFAULT_VALUE) if config.force_ssl

          if config.cookies.enabled?
            require 'lotus/action/cookies'
            prepare { include Lotus::Action::Cookies }
            cookies config.cookies.default_options
          end

          if config.sessions.enabled?
            prepare do
              include Lotus::Action::Session
              include Lotus::Action::CSRFProtection
            end
          end

          prepare { include Lotus::Action::RoutingHelpers }

          config.controller.__apply(self)
        end

        namespace.const_set('Controller', controller)
      end
    end

    def _configure_view_framework!
      config = configuration
      unless namespace.const_defined?('View')
        view = Lotus::View.duplicate(namespace) do
          root   config.templates
          layout config.layout

          config.view.__apply(self)
        end

        namespace.const_set('View', view)
      end
    end

    def _configure_model_framework!
      config = configuration
      if _lotus_model_loaded? && !application_module.const_defined?('Model')
        model = Lotus::Model.duplicate(application_module) do
          adapter(config.adapter)  if config.adapter
          mapping(&config.mapping) if config.mapping

          config.model.__apply(self)
        end

        application_module.const_set('Model', model)
      end
    end

    def _configure_logger!
      unless application_module.const_defined?('Logger', false)
        if configuration.logger.nil?
          configuration.logger Lotus::Logger.new(application_module.to_s)
        end
        application_module.const_set('Logger', configuration.logger)
      end
    end

    def load_frameworks!
      _load_view_framework!
      _load_model_framework!
    end

    def _load_view_framework!
      namespace.module_eval %{
        #{ namespace }::View.load!
      }
    end

    def _load_model_framework!
      return unless _load_model_framework?

      application_module.module_eval %{
        #{ application_module }::Model.load!
      }
    end

    def _load_model_framework?
      if _lotus_model_loaded? && application_module.const_defined?('Model')
        model = application_module.const_get('Model')
        model.configuration.adapter
      end
    end

    def _lotus_model_loaded?
      defined?(Lotus::Model)
    end

    def _lotus_mailer_loaded?
      defined?(Lotus::Mailer)
    end

    def load_configuration_load_paths!
      configuration.load_paths.load!(configuration.root)
    end

    def load_rack!
      _assign_routes_to_application_module!

      return if application.is_a?(Class)
      _assign_rendering_policy!
      _assign_rack_routes!
      _load_rack_middleware!
    end

    def _assign_rendering_policy!
      application.renderer = RenderingPolicy.new(configuration)
    end

    def _assign_rack_routes!
      application.routes = application_routes
    end

    def _load_rack_middleware!
      configuration.middleware.load!(application, namespace)
    end

    def _assign_routes_to_application_module!
      unless application_module.const_defined?('Routes')
        routes = Lotus::Routes.new(application_routes)
        application_module.const_set('Routes', routes)
      end
    end

    def application_module
      @application_module ||= Utils::Class.load!(
        Utils::String.new(application.name).namespace
      )
    end

    def application_routes
      resolver    = Lotus::Routing::EndpointResolver.new(pattern: configuration.controller_pattern, namespace: namespace)
      default_app = Lotus::Routing::Default.new
      Lotus::Router.new(
        parsers:     configuration.body_parsers,
        resolver:    resolver,
        default_app: default_app,
        scheme:      configuration.scheme,
        host:        configuration.host,
        port:        configuration.port,
        prefix:      configuration.path_prefix,
        force_ssl:   configuration.force_ssl,
        &configuration.routes
      )
    end

    def namespace
      configuration.namespace || application_module
    end
  end
end


text:
package org.apache.flink.streaming.api.windowing.windows;

import org.apache.flink.annotation.PublicEvolving;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.core.memory.DataInputView;
import org.apache.flink.core.memory.DataOutputView;

import java.io.IOException;

@PublicEvolving
public class GlobalWindow extends Window {

	private static GlobalWindow INSTANCE = new GlobalWindow();

	private GlobalWindow() { }

	public static GlobalWindow get() {
		return INSTANCE;
	}

	@Override
	public long maxTimestamp() {
		return Long.MAX_VALUE;
	}

	@Override
	public boolean equals(Object o) {
		return this == o || !(o == null || getClass() != o.getClass());
	}

	@Override
	public int hashCode() {
		return 0;
	}

	@Override
	public String toString() {
		return "GlobalWindow";
	}

	public static class Serializer extends TypeSerializer<GlobalWindow> {
		private static final long serialVersionUID = 1L;

		@Override
		public boolean isImmutableType() {
			return true;
		}

		@Override
		public TypeSerializer<GlobalWindow> duplicate() {
			return this;
		}

		@Override
		public GlobalWindow createInstance() {
			return GlobalWindow.INSTANCE;
		}

		@Override
		public GlobalWindow copy(GlobalWindow from) {
			return from;
		}

		@Override
		public GlobalWindow copy(GlobalWindow from, GlobalWindow reuse) {
			return from;
		}

		@Override
		public int getLength() {
			return 0;
		}

		@Override
		public void serialize(GlobalWindow record, DataOutputView target) throws IOException {
			target.writeByte(0);
		}

		@Override
		public GlobalWindow deserialize(DataInputView source) throws IOException {
			source.readByte();
			return GlobalWindow.INSTANCE;
		}

		@Override
		public GlobalWindow deserialize(GlobalWindow reuse,
				DataInputView source) throws IOException {
			source.readByte();
			return GlobalWindow.INSTANCE;
		}

		@Override
		public void copy(DataInputView source, DataOutputView target) throws IOException {
			source.readByte();
			target.writeByte(0);
		}

		@Override
		public boolean equals(Object obj) {
			return obj instanceof Serializer;
		}

		@Override
		public boolean canEqual(Object obj) {
			return obj instanceof Serializer;
		}

		@Override
		public int hashCode() {
			return 0;
		}
	}
}


text:
/**
 * Created by a on 7/4/2016.
 */

var mongoose = require('mongoose');
var logger = require('dvp-common/LogHandler/CommonLogHandler.js').logger;
var TimeEntry = require('dvp-mongomodels/model/TimeEntry').TimeEntry;
var Ticket = require('dvp-mongomodels/model/Ticket').Ticket;
var SLA = require('dvp-mongomodels/model/SLA').SLA;
var messageFormatter = require('dvp-common/CommonMessageGenerator/ClientMessageJsonFormatter.js');

function CreateSLA(req, res){
    logger.info("DVP-LiteTicket.CreateSLA Internal method ");

    var company = parseInt(req.user.company);
    var tenant = parseInt(req.user.tenant);
    var jsonString;

    var data = SLA({
        title: req.body.title,
        description: req.body.description,
        priority: req.body.priority,
        company: company,
        tenant: tenant,
        filter: req.body.filter,
        matrix: req.body.matrix,
        created_at: Date.now(),
        updated_at: Date.now()
    });

    data.save(function(err, sla){
        if (err) {
            jsonString = messageFormatter.FormatMessage(err, "SLA create failed", false, undefined);
        }
        else {
            jsonString = messageFormatter.FormatMessage(undefined, "SLA saved successfully", true, sla);
        }
        res.end(jsonString);
    });
}

function GetSLA(req, res){
    logger.info("DVP-LiteTicket.GetSLA Internal method ");

    var company = parseInt(req.user.company);
    var tenant = parseInt(req.user.tenant);
    var jsonString;

    SLA.findOne({_id: req.params.id, company: company, tenant: tenant}, function (err, sla) {
        if (err) {
            jsonString = messageFormatter.FormatMessage(err, "Get SLA Failed", false, undefined);
            res.end(jsonString);
        } else {
            jsonString = messageFormatter.FormatMessage(err, "Get SLA Success", true, sla);
            res.end(jsonString);
        }
    });
}

function GetSLAs(req, res){
    logger.info("DVP-LiteTicket.GetSLAs Internal method ");

    var company = parseInt(req.user.company);
    var tenant = parseInt(req.user.tenant);
    var jsonString;

    SLA.find({company: company, tenant: tenant}, function (err, sla) {
        if (err) {
            jsonString = messageFormatter.FormatMessage(err, "Get GetSLAs Failed", false, undefined);
            res.end(jsonString);
        } else {
            jsonString = messageFormatter.FormatMessage(err, "Get GetSLAs Success", true, sla);
            res.end(jsonString);
        }
    });
}

function UpdateSLA(req, res){
    logger.info("DVP-LiteTicket.UpdateSLA Internal method ");

    var company = parseInt(req.user.company);
    var tenant = parseInt(req.user.tenant);
    var jsonString;

    SLA.findOne({_id: req.params.id, company: company, tenant: tenant}, function(err, sla){
        if(err){
            jsonString = messageFormatter.FormatMessage(err, "Get GetSLA Failed", false, undefined);
            res.end(jsonString);
        }else{
            if(sla){
                sla.description = req.body.description;
                sla.priority = req.body.priority;
                sla.filter = req.body.filter;
                sla.matrix = req.body.matrix;
                sla.updated_at = Date.now();

                sla.update(sla, function (err, newSla) {
                    if (err) {
                        jsonString = messageFormatter.FormatMessage(err, "Fail Update SLA", false, undefined);
                    }
                    else {
                        if (newSla) {
                            jsonString = messageFormatter.FormatMessage(undefined, "SLA Update Successfully", true, newSla);
                        }
                        else {
                            jsonString = messageFormatter.FormatMessage(undefined, "Invalid SLA Id.", false, newSla);
                        }
                    }
                    res.end(jsonString);
                });
            }else{
                jsonString = messageFormatter.FormatMessage(err, "No SLA Found", false, undefined);
                res.end(jsonString);
            }
        }
    });
}

function DeleteSLA(req, res){
    logger.info("DVP-LiteTicket.DeleteSLA Internal method ");

    var company = parseInt(req.user.company);
    var tenant = parseInt(req.user.tenant);
    var jsonString;

    SLA.findOne({_id: req.params.id, company: company, tenant: tenant}, function (err, sla) {
        if (err) {
            jsonString = messageFormatter.FormatMessage(err, "Get SLA Failed", false, undefined);
            res.end(jsonString);
        } else {
            if (sla) {
                sla.remove(function (err) {
                    if (err) {
                        jsonString = messageFormatter.FormatMessage(err, "Delete SLA Failed", false, undefined);
                    } else {
                        jsonString = messageFormatter.FormatMessage(undefined, "SLA successfully deleted", true, undefined);
                    }
                    res.end(jsonString);
                });
            } else {
                jsonString = messageFormatter.FormatMessage(undefined, "Delete SLA Failed, SLA object is null", false, undefined);
                res.end(jsonString);
            }
        }
    });
}

function AddMatrix(req, res){
    logger.info("DVP-LiteTicket.AddMatrix Internal method ");

    var company = parseInt(req.user.company);
    var tenant = parseInt(req.user.tenant);
    var jsonString;

    SLA.findOneAndUpdate({_id: req.params.id,company: company, tenant: tenant}, { $addToSet :{
        matrix : {
            priority: req.body.priority,
            criteria: req.body.criteria,
            target: req.body.target,
            threshold:  req.body.threshold,
            on_fail:  req.body.on_fail,
            on_threshold:  req.body.on_threshold
        }}}, function (err, matrices) {
        if (err) {
            jsonString = messageFormatter.FormatMessage(err, "Add Matrix Failed", false, undefined);
        } else {
            jsonString = messageFormatter.FormatMessage(undefined, "Add Matrix Successful", true, matrices);
        }
        res.end(jsonString);
    });
}

function DeleteMatrix(req, res){
    logger.info("DVP-LiteTicket.DeleteMatrix Internal method ");

    var company = parseInt(req.user.company);
    var tenant = parseInt(req.user.tenant);
    var jsonString;

    SLA.findOneAndUpdate({_id: req.params.id,company: company, tenant: tenant}, { $pull :{
        matrix : {
            _id: req.params.matrixid
        }}}, function (err, matrices) {
        if (err) {
            jsonString = messageFormatter.FormatMessage(err, "Delete Matrix Failed", false, undefined);
        } else {
            jsonString = messageFormatter.FormatMessage(undefined, "Delete Matrix Successful", true, matrices);
        }
        res.end(jsonString);
    });
}

function AddFilterAll(req, res){
    logger.info("DVP-LiteTicket.AddFilterAll Internal method ");

    var company = parseInt(req.user.company);
    var tenant = parseInt(req.user.tenant);
    var jsonString;

    SLA.findOne({_id: req.params.id,company: company, tenant: tenant}, function (err, sla) {
        var allFiler = {field: req.body.field, operator: req.body.operator, value: req.body.value};
        if(sla.filter.all && Array.isArray(sla.filter.all)) {
            sla.filter.all.push(allFiler);
        }else{
            sla.filter.all = [allFiler];
        }
        sla.update(sla, function (err, newSla) {
            if (err) {
                jsonString = messageFormatter.FormatMessage(err, "Add Filter All Failed", false, undefined);
            } else {
                jsonString = messageFormatter.FormatMessage(undefined, "Add Filter All Successful", true, newSla);
            }
            res.end(jsonString);
        });
    });
}

function RemoveFilterAll(req, res){
    logger.info("DVP-LiteTicket.RemoveFilterAll Internal method ");

    var company = parseInt(req.user.company);
    var tenant = parseInt(req.user.tenant);
    var jsonString;

    SLA.findOne({_id: req.params.id,company: company, tenant: tenant}, function (err, sla) {
        for(var i = 0; i < sla.filter.all.length; i++){
            if(sla.filter.all[i].id == req.params.filterid) {
                sla.filter.all.splice(i, 1);
                break;
            }
        }
        sla.update(sla, function (err, newSla) {
            if (err) {
                jsonString = messageFormatter.FormatMessage(err, "Delete Filter All Failed", false, undefined);
            } else {
                jsonString = messageFormatter.FormatMessage(undefined, "Delete Filter All Successful", true, newSla);
            }
            res.end(jsonString);
        });
    });
}

function GetFiltersAll(req, res){
    logger.info("DVP-LiteTicket.GetFiltersAll Internal method ");

    var company = parseInt(req.user.company);
    var tenant = parseInt(req.user.tenant);
    var jsonString;

    SLA.findOne({_id: req.params.id,company: company, tenant: tenant}, function (err, sla) {
        if (err) {
            jsonString = messageFormatter.FormatMessage(err, "Get FiltersAll Failed", false, undefined);
        } else {
            jsonString = messageFormatter.FormatMessage(undefined, "Get FiltersAll Successful", true, sla.filter.all);
        }
        res.end(jsonString);
    });
}

function AddFilterAny(req, res){
    logger.info("DVP-LiteTicket.AddFilterAny Internal method ");

    var company = parseInt(req.user.company);
    var tenant = parseInt(req.user.tenant);
    var jsonString;

    SLA.findOne({_id: req.params.id,company: company, tenant: tenant}, function (err, sla) {
        var anyFiler = {field: req.body.field, operator: req.body.operator, value: req.body.value};
        if(sla.filter.any && Array.isArray(sla.filter.any)) {
            sla.filter.any.push(anyFiler);
        }else{
            sla.filter.any = [anyFiler];
        }
        sla.update(sla, function (err, newSla) {
            if (err) {
                jsonString = messageFormatter.FormatMessage(err, "Add Filter Any Failed", false, undefined);
            } else {
                jsonString = messageFormatter.FormatMessage(undefined, "Add Filter Any Successful", true, newSla);
            }
            res.end(jsonString);
        });
    });
}

function RemoveFilterAny(req, res){
    logger.info("DVP-LiteTicket.RemoveFilterAny Internal method ");

    var company = parseInt(req.user.company);
    var tenant = parseInt(req.user.tenant);
    var jsonString;

    SLA.findOne({_id: req.params.id,company: company, tenant: tenant}, function (err, sla) {
        for(var i = 0; i < sla.filter.any.length; i++){
            if(sla.filter.any[i].id == req.params.filterid) {
                sla.filter.any.splice(i, 1);
                break;
            }
        }
        sla.update(sla, function (err, newSla) {
            if (err) {
                jsonString = messageFormatter.FormatMessage(err, "Delete Filter Any Failed", false, undefined);
            } else {
                jsonString = messageFormatter.FormatMessage(undefined, "Delete Filter Any Successful", true, newSla);
            }
            res.end(jsonString);
        });
    });
}

function GetFiltersAny(req, res){
    logger.info("DVP-LiteTicket.GetFiltersAny Internal method ");

    var company = parseInt(req.user.company);
    var tenant = parseInt(req.user.tenant);
    var jsonString;

    SLA.findOne({_id: req.params.id,company: company, tenant: tenant}, function (err, sla) {
        if (err) {
            jsonString = messageFormatter.FormatMessage(err, "Get Filters Any Failed", false, undefined);
        } else {
            jsonString = messageFormatter.FormatMessage(undefined, "Get Filters Any Successful", true, sla.filter.any);
        }
        res.end(jsonString);
    });
}

function GetMatrices(req, res){
    logger.info("DVP-LiteTicket.GetMatrices Internal method ");

    var company = parseInt(req.user.company);
    var tenant = parseInt(req.user.tenant);
    var jsonString;

    SLA.findOne({_id: req.params.id,company: company, tenant: tenant}, function (err, sla) {
        if (err) {
            jsonString = messageFormatter.FormatMessage(err, "Get Matrices Failed", false, undefined);
        } else {
            jsonString = messageFormatter.FormatMessage(undefined, "Get Matrices Successful", true, sla.matrix);
        }
        res.end(jsonString);
    });
}

module.exports.CreateSLA =CreateSLA;
module.exports.GetSLA =GetSLA;
module.exports.GetSLAs =GetSLAs;
module.exports.UpdateSLA = UpdateSLA;
module.exports.DeleteSLA = DeleteSLA;
module.exports.AddMatrix = AddMatrix;
module.exports.DeleteMatrix = DeleteMatrix;
module.exports.AddFilterAll = AddFilterAll;
module.exports.RemoveFilterAll = RemoveFilterAll;
module.exports.AddFilterAny = AddFilterAny;
module.exports.RemoveFilterAny = RemoveFilterAny;
module.exports.GetMatrices = GetMatrices;
module.exports.GetFiltersAll =GetFiltersAll;
module.exports.GetFiltersAny =GetFiltersAny;