text:
from collections import OrderedDict
from textwrap import dedent
import re

import sublime
from sublime_plugin import TextCommand

from . import util
from ..core.runtime import enqueue_on_worker
from ..core.settings import GitSavvySettings
from ..core.utils import focus_view

MYPY = False
if MYPY:
    from typing import Dict, Optional

interfaces = {}  # type: Dict[sublime.ViewId, Interface]
edit_views = {}
subclasses = []

EDIT_DEFAULT_HELP_TEXT = "## To finalize your edit, press {super_key}+Enter.  To cancel, close the view.\n"

class Interface():
    interface_type = ""
    syntax_file = ""

    template = ""

    _initialized = False

    def __new__(cls, repo_path=None, **kwargs):
        """
        Search for intended interface in active window - if found, bring it
        to focus and return it instead of creating a new interface.
        """
        if repo_path is not None:
            window = sublime.active_window()
            for view in window.views():
                vset = view.settings()
                if (
                    vset.get("git_savvy.interface") == cls.interface_type
                    and vset.get("git_savvy.repo_path") == repo_path
                ):
                    focus_view(view)
                    try:
                        return interfaces[view.id()]
                    except KeyError:
                        return cls(view=view)  # surprise! we recurse

        return super().__new__(cls)

    def __init__(self, repo_path=None, view=None):
        if self._initialized:
            return
        self._initialized = True

        self.regions = {}

        subclass_attrs = (getattr(self, attr) for attr in vars(self.__class__).keys())

        self.partials = {
            attr.key: attr
            for attr in subclass_attrs
            if callable(attr) and hasattr(attr, "key")
        }

        for attr in vars(self.__class__).keys():
            if attr.startswith("template"):
                setattr(self, attr, dedent(getattr(self, attr)))

        if view:
            self.view = view
        else:
            self.create_view(repo_path)
            sublime.set_timeout_async(self.on_new_dashboard, 0)

        interfaces[self.view.id()] = self
        self.on_create()

    def create_view(self, repo_path):
        window = sublime.active_window()
        self.view = window.new_file()

        self.view.settings().set("git_savvy.repo_path", repo_path)
        self.view.settings().set("git_savvy.{}_view".format(self.interface_type), True)
        self.view.settings().set("git_savvy.tabbable", True)
        self.view.settings().set("git_savvy.interface", self.interface_type)
        self.view.settings().set("git_savvy.help_hidden", GitSavvySettings().get("hide_help_menu"))
        self.view.set_syntax_file(self.syntax_file)
        self.view.set_scratch(True)
        self.view.set_read_only(True)
        util.view.disable_other_plugins(self.view)
        self.after_view_creation(self.view)

        # Set title as late as possible, otherwise e.g. `result_file_regex` will not apply
        # after the initial activate. (It applies after the second activation of the view,
        # shall we say a sublime nuance.)
        self.view.set_name(self.title())

        self.render()
        focus_view(self.view)

        return self.view

    def title(self):
        # type: () -> str
        raise NotImplementedError

    def after_view_creation(self, view):
        """
        Hook template method called after the view has been created.
        Can be used to further manipulate the view and store state on it.
        """
        pass

    def on_new_dashboard(self):
        """
        Hook template method called after the first render.
        """
        pass

    def on_create(self):
        """
        Hook template method called after a new interface object has been created.
        """
        pass

    def on_close(self):
        """
        Hook template method called after a view has been closed.
        """
        pass

    def pre_render(self):
        pass

    def reset_cursor(self):
        pass

    def render(self, nuke_cursors=False):
        self.clear_regions()
        self.pre_render()
        rendered = self._render_template()
        self.view.run_command("gs_new_content_and_regions", {
            "content": rendered,
            "regions": self.regions,
            "nuke_cursors": nuke_cursors
        })
        if nuke_cursors:
            self.reset_cursor()

    def _render_template(self):
        """
        Generate new content for the view given the interface template
        and partial content.  As partial content is added to the rendered
        template, add regions to `self.regions` with the key, start, and
        end of each partial.
        """
        rendered = self.template

        keyed_content = self.get_keyed_content()
        for key, new_content in keyed_content.items():
            new_content_len = len(new_content)
            pattern = re.compile(r"\{(<+ )?" + key + r"\}")

            match = pattern.search(rendered)
            while match:
                start, end = match.span()
                backspace_group = match.groups()[0]
                backspaces = backspace_group.count("<") if backspace_group else 0
                start -= backspaces

                rendered = rendered[:start] + new_content + rendered[end:]

                self.adjust(start, end - start, new_content_len)
                if new_content_len:
                    self.regions[key] = [start, start + new_content_len]

                match = pattern.search(rendered)

        return rendered

    def adjust(self, idx, orig_len, new_len):
        """
        When interpolating template variables, update region ranges for previously-evaluated
        variables, that are situated later on in the output/template string.
        """
        shift = new_len - orig_len
        for key, region in self.regions.items():
            if region[0] > idx:
                region[0] += shift
                region[1] += shift
            elif region[1] > idx or region[0] == idx:
                region[1] += shift

    def get_keyed_content(self):
        keyed_content = OrderedDict(
            (key, render_fn())
            for key, render_fn in self.partials.items()
        )

        for key in keyed_content:
            output = keyed_content[key]
            if isinstance(output, tuple):
                sub_template, complex_partials = output
                keyed_content[key] = sub_template

                for render_fn in complex_partials:
                    keyed_content[render_fn.key] = render_fn()

        return keyed_content

    def update(self, key, content):
        self.view.run_command("gs_update_region", {
            "key": "git_savvy_interface." + key,
            "content": content
        })

    def clear_regions(self):
        for key in self.regions.keys():
            self.view.erase_regions("git_savvy_interface." + key)
        self.regions = {}

    def get_view_regions(self, key):
        return self.view.get_regions("git_savvy_interface." + key)

    def get_selection_line(self):
        selections = self.view.sel()
        if not selections or len(selections) > 1:
            self.view.window().status_message("Please make a selection.")
            return None

        selection = selections[0]
        return selection, util.view.get_lines_from_regions(self.view, [selection])[0]

    def get_selection_lines_in_region(self, region):
        return util.view.get_lines_from_regions(
            self.view,
            self.view.sel(),
            valid_ranges=self.get_view_regions(region)
        )

def partial(key):
    def decorator(fn):
        fn.key = key
        return fn
    return decorator

class GsNewContentAndRegionsCommand(TextCommand):

    def run(self, edit, content, regions, nuke_cursors=False):
        selections = self.view.sel()

        if selections and not nuke_cursors:
            cursors_row_col = [self.view.rowcol(cursor.a) for cursor in selections]
        else:
            cursors_row_col = [(0, 0)]

        selections.clear()

        is_read_only = self.view.is_read_only()
        self.view.set_read_only(False)
        self.view.replace(edit, sublime.Region(0, self.view.size()), content)
        self.view.set_read_only(is_read_only)

        for row, col in cursors_row_col:
            pt = self.view.text_point(row, col)
            selections.add(sublime.Region(pt, pt))

        for key, region_range in regions.items():
            a, b = region_range
            self.view.add_regions("git_savvy_interface." + key, [sublime.Region(a, b)])

        if self.view.settings().get("git_savvy.interface"):
            self.view.run_command("gs_handle_vintageous")
            self.view.run_command("gs_handle_arrow_keys")

class GsUpdateRegionCommand(TextCommand):

    def run(self, edit, key, content):
        is_read_only = self.view.is_read_only()
        self.view.set_read_only(False)
        for region in self.view.get_regions(key):
            self.view.replace(edit, region, content)
        self.view.set_read_only(is_read_only)

def register_listeners(InterfaceClass):
    subclasses.append(InterfaceClass)

def get_interface(view_id):
    # type: (sublime.ViewId) -> Optional[Interface]
    return interfaces.get(view_id, None)

class GsInterfaceCloseCommand(TextCommand):

    """
    Clean up references to interfaces for closed views.
    """

    def run(self, edit):
        view_id = self.view.id()
        interface = get_interface(view_id)
        if interface:
            interface.on_close()
            enqueue_on_worker(lambda: interfaces.pop(view_id))

class GsInterfaceRefreshCommand(TextCommand):

    """
    Re-render GitSavvy interface view.
    """

    def run(self, edit, nuke_cursors=False):
        enqueue_on_worker(self.run_async, nuke_cursors)

    def run_async(self, nuke_cursors):
        # type: (bool) -> None
        interface_type = self.view.settings().get("git_savvy.interface")
        for cls in subclasses:
            if cls.interface_type == interface_type:
                vid = self.view.id()
                interface = interfaces.get(vid, None)
                if not interface:
                    interface = interfaces[vid] = cls(view=self.view)
                interface.render(nuke_cursors=nuke_cursors)  # type: ignore[union-attr]
                break

class GsInterfaceToggleHelpCommand(TextCommand):

    """
    Toggle GitSavvy help.
    """

    def run(self, edit):
        interface_type = self.view.settings().get("git_savvy.interface")
        for InterfaceSubclass in subclasses:
            if InterfaceSubclass.interface_type == interface_type:
                current_help = bool(self.view.settings().get("git_savvy.help_hidden"))
                self.view.settings().set("git_savvy.help_hidden", not current_help)
                self.view.run_command("gs_interface_refresh")

class GsInterfaceTogglePopupHelpCommand(TextCommand):

    """
    Toggle GitSavvy popup help.
    """

    def run(self, edit, view_name, popup_max_width=800, popup_max_height=900):
        css = sublime.load_resource("Packages/GitSavvy/popups/style.css")
        html = (
            sublime.load_resource("Packages/GitSavvy/popups/" + view_name + ".html")
            .format(css=css, super_key=util.super_key)
        )
        visible_region = self.view.visible_region()
        self.view.show_popup(html, 0, visible_region.begin(), popup_max_width, popup_max_height)

class EditView():

    def __init__(self, content, on_done, repo_path, help_text=None, window=None):
        self.window = window or sublime.active_window()
        self.view = self.window.new_file()

        self.view.set_scratch(True)
        self.view.set_read_only(False)
        self.view.set_name("EDIT")
        self.view.set_syntax_file("Packages/GitSavvy/syntax/make_commit.sublime-syntax")
        self.view.settings().set("git_savvy.edit_view", True)
        self.view.settings().set("git_savvy.repo_path", repo_path)

        self.on_done = on_done
        self.render(content, help_text)

        edit_views[self.view.id()] = self

    def render(self, starting_content, help_text):
        regions = {}

        starting_content += "\n\n"

        regions["content"] = (0, len(starting_content))
        content = starting_content + (help_text or EDIT_DEFAULT_HELP_TEXT).format(super_key=util.super_key)
        regions["help"] = (len(starting_content), len(content))

        self.view.run_command("gs_new_content_and_regions", {
            "content": content,
            "regions": regions,
            "nuke_cursors": True
        })

class GsEditViewCompleteCommand(TextCommand):

    """
    Invoke callback with edit view content.
    """

    def run(self, edit):
        sublime.set_timeout_async(self.run_async, 0)

    def run_async(self):
        edit_view = edit_views.get(self.view.id(), None)
        if not edit_view:
            sublime.error_message("Unable to complete edit.  Please try again.")
            return

        help_region = self.view.get_regions("git_savvy_interface.help")[0]
        content_before = self.view.substr(sublime.Region(0, help_region.begin()))
        content_after = self.view.substr(sublime.Region(help_region.end(), self.view.size() - 1))
        content = (content_before + content_after).strip()

        self.view.close()
        edit_view.on_done(content)

class GsEditViewCloseCommand(TextCommand):

    """
    Clean up references to closed edit views.
    """

    def run(self, edit):
        sublime.set_timeout_async(self.run_async, 0)

    def run_async(self):
        view_id = self.view.id()
        if view_id in edit_views:
            del edit_views[view_id]


text:
(function( $, ko ) {

	var binding = {

		'after': [ 'attr', 'value' ],

		'defaults': {},

		'extensions': {},

		'init': function( element, valueAccessor, allBindings, viewModel, bindingContext ) {
			if ( !ko.isWriteableObservable( valueAccessor() ) ) {
				throw 'valueAccessor must be writeable and observable';
			}

			// Get custom configuration object from the 'wysiwygConfig' binding, more settings here... http://www.tinymce.com/wiki.php/Configuration
			var options = allBindings.has( 'wysiwygConfig' ) ? allBindings.get( 'wysiwygConfig' ) : null,

				// Get any extensions that have been enabled for this instance.
				ext = allBindings.has( 'wysiwygExtensions' ) ? allBindings.get( 'wysiwygExtensions' ) : [],

				settings = configure( binding['defaults'], ext, options, arguments );

			// Ensure the valueAccessor's value has been applied to the underlying element, before instanciating the tinymce plugin
			$( element ).text( valueAccessor()() );

			// Defer TinyMCE instantiation
			setTimeout( function() {
				$( element ).tinymce( settings );
			}, 0 );

			// To prevent a memory leak, ensure that the underlying element's disposal destroys it's associated editor.
			ko.utils['domNodeDisposal'].addDisposeCallback( element, function() {
				$( element ).tinymce().remove();
			});

			return { controlsDescendantBindings: true };
		},

		'update': function( element, valueAccessor, allBindings, viewModel, bindingContext ) {
			var tinymce = $( element ).tinymce(),
				value = valueAccessor()();

			if ( tinymce ) {
				if ( tinymce.getContent() !== value ) {
					tinymce.setContent( value );
					tinymce.execCommand( 'keyup' );
				}
			} else {
				$( element ).text( valueAccessor()() );
			}
		}

	};

	var configure = function( defaults, extensions, options, args ) {

		// Apply global configuration over TinyMCE defaults
		var config = $.extend( true, {}, defaults );

		if ( options ) {
			// Concatenate element specific configuration
			ko.utils.objectForEach( options, function( property ) {
				if ( Object.prototype.toString.call( options[property] ) === '[object Array]' ) {
					if ( !config[property] ) {
						config[property] = [];
					}
					options[property] = ko.utils.arrayGetDistinctValues( config[property].concat( options[property] ) );
				}
			});

			$.extend( true, config, options );
		}

		// Ensure paste functionality
		if ( !config['plugins'] ) {
			config['plugins'] = [ 'paste' ];
		} else if ( $.inArray( 'paste', config['plugins'] ) === -1 ) {
			config['plugins'].push( 'paste' );
		}

		// Define change handler
		var applyChange = function( editor ) {
			// Ensure the valueAccessor state to achieve a realtime responsive UI.
			editor.on( 'change keyup nodechange', function( e ) {
				// Update the valueAccessor
				args[1]()( editor.getContent() );

				// Run all applied extensions
				for ( var name in extensions ) {
					if ( extensions.hasOwnProperty( name ) ) {
						binding['extensions'][extensions[name]]( editor, e, args[2], args[4] );
					}
				}
			});
		};

		if ( typeof( config['setup'] ) === 'function' ) {
			var setup = config['setup'];

			// Concatenate setup functionality with the change handler
			config['setup'] = function( editor ) {
				setup( editor );
				applyChange( editor );
			};
		} else {
			// Apply change handler
			config['setup'] = applyChange;
		}

		return config;
	};

	// Export the binding
	ko.bindingHandlers['wysiwyg'] = binding;

})( jQuery, ko );

redpajama_set_name: RedPajamaGithub


text:
<?php
// the path to the module. the probably shouldn't be changed unless you rename the zip_install folder(s)
define('zip_install_path', my_pligg_base . '/modules/zip_install/');

// the path to the module. the probably shouldn't be changed unless you rename the module_store folder(s)
if(!defined('lang_loc')){
	// determine if we're in root or another folder like admin
	$pos = strrpos($_SERVER["SCRIPT_NAME"], "/");
	$path = substr($_SERVER["SCRIPT_NAME"], 0, $pos);
	if ($path == "/"){$path = "";}
	if($path != my_pligg_base){
		define('lang_loc', '..');
	} else {
		define('lang_loc', '.');
	}
}

define('zip_install_lang_conf', lang_loc . '/modules/zip_install/lang.conf');
define('zip_install_pligg_lang_conf', lang_loc . "/languages/lang_" . pligg_language . ".conf");

define('zip_install_tpl_path', '../modules/zip_install/templates/');
define('zip_install_lib_path', '../modules/zip_install/lib/');

   $path = getcwd();
   if (preg_match("/\/modules/i", "$path"))
	   $abspath = str_replace('/modules',"",$path);
   else
	   $abspath = str_replace('\modules',"",$path);

define('zip_install_absolute_path', $abspath."/");

// don't touch anything past this line.
if(isset($main_smarty) && is_object($main_smarty)){
   $main_smarty->assign('zip_install_path', zip_install_path);
   $main_smarty->assign('zip_install_lang_conf', zip_install_lang_conf);
   $main_smarty->assign('zip_install_pligg_lang_conf', zip_install_pligg_lang_conf);
   $main_smarty->assign('zip_install_tpl_path', zip_install_tpl_path);
   $main_smarty->assign('zip_install_lib_path', zip_install_lib_path);
}

?>


text:
//
//  SFLogger.h
//  SalesforceCommonUtils
//
//  Copyright (c) 2012 salesforce.com. All rights reserved.
//

#import <Foundation/Foundation.h>

typedef enum SFLogLevel {
	SFLogLevelDebug,
	SFLogLevelInfo,
	SFLogLevelWarning,
	SFLogLevelError,
} SFLogLevel;

typedef void (^SFLogBlock) (NSString *msg);

#define SFLogAssert(_cond, _desc, ...) \
do { \
if (!(_cond)) { \
[SFLogger logAssertionFailureInMethod:_cmd object:(self) file:[NSString stringWithUTF8String:__FILE__] lineNumber:__LINE__ description:(_desc), ##__VA_ARGS__]; \
} \
} while (0) \

/*!
 Allows your class to log messages specific to that class.
 You should be able to use this 99% of the time.
 */
@interface NSObject (SFLogging)
/**
 * Logs a message with the given level.
 * @param level The minimum log level to log at.
 * @param msg The message to log.
 */
-(void)log:(SFLogLevel)level msg:(NSString *)msg;

/**
 * Logs a formatted message with the given log level and format parameters.
 * @param level The minimum log level to log at.
 * @param msg The format message, and optional arguments to expand in the format.
 * @param ... The arguments to the message format string.
 */
-(void)log:(SFLogLevel)level format:(NSString *)msg, ...;

@end

/*!
 Generic logging utility: logs to both console and persistent file.
 */
@interface SFLogger : NSObject {
	SFLogLevel		logLevel;
}

/**
 * The current log level of the app.
 */
+ (SFLogLevel)logLevel;

/** Turn on and off for logging to a file
 @param logToFile Yes to log to file. Set to NO will turn off logging to file and also remove existing logging file
 */
+ (void)logToFile:(BOOL)logToFile;

/**
 * Sets the log level of the app.
 * @param newLevel The new log level to configure.
 */
+ (void)setLogLevel:(SFLogLevel)newLevel;

/** Get access to the content of the application log file.
 */
+ (NSString *)logFileContents;

/**
 * Logs at the Class level.  Should only be used if you don't have an NSObject instance to
 * log from.
 * @param cls The class associated with the log event.
 * @param level The level to log at.
 * @param msg The message to log.
 */
+ (void)log:(Class)cls level:(SFLogLevel)level msg:(NSString *)msg;

/**
 * Logs an assertion failure to a file.
 * @param method The method where the assertion failure occurred.
 * @param obj The object where the assertion failure occurred.
 * @param file The file to log to.
 * @param line The line number of the failure.
 * @param desc The formatted description to log.
 * @param ... The format arguments of the description.
 */
+ (void)logAssertionFailureInMethod:(SEL)method object:(id)obj file:(NSString *)file lineNumber:(NSUInteger)line description:(NSString *)desc, ...;

/**
 * Logs a formatted message with the given log level and format parameters.
 * @param cls The class associated with the log event.
 * @param level The minimum log level to log at.
 * @param msg The format message, and optional arguments to expand in the format.
 * @param ... The arguments to the message format string.
 */
+ (void)log:(Class)cls level:(SFLogLevel)level format:(NSString *)msg, ...;

/*!
 Sets the log level based on the user preferences.
 */
+ (void)applyLogLevelFromPreferences;

/**
 Use this method to enable the recording of the assertion instead of aborting the
 program when an assertion is triggered. This is usually used by the
 unit tests.
 @param enabled Whether or not to enable assertion recording.
 */
+ (void)setRecordAssertionEnabled:(BOOL)enabled;

/**
 Returns YES if an assertion was recorded and clear the flag.
 @return YES if an assertion was recorded, NO otherwise.
 */
+ (BOOL)assertionRecordedAndClear;

@end


text:
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { MdDialog } from '@angular/material';

import { DialogDismantlingOrderListComponent } from '../../../shared/dialog-dismantling-order-list/dialog-dismantling-order-list.component';

@Component({
  selector: 'app-dismantling-progressing',
  templateUrl: './dismantling-progressing.component.html',
  styleUrls: ['./dismantling-progressing.component.scss']
})
export class DismantlingProgressingComponent implements OnInit {
  @Input() data;
  @Input() filterCache;
  @Input() btity;
  @Input() orderType;
  filteredData;
  filterValueChangesRxx = new BehaviorSubject({dismantlingStarted: 1});
  optionsArr = [];
  title: string;
  dataProps = [ // dismantlingOrderWeek
    {title: '本周', name: 'thisWeek'},
    {title: '上周', name: 'lastWeek'},
    {title: '更早', name: 'evenEarlier'},
    {title: '合计', name: 'total'},
  ];

  basedOnDismantlingStarted = {
    '1': {
      sumPredicate: curr => {return true; },
    },
    '2': {
      sumPredicate: curr => {return curr['started']; },
    },
    '3': {
      sumPredicate: curr => {return !curr['started']; },
    },
  };

  constructor(
    public dialog: MdDialog,
  ) { }

  ngOnInit() {
    switch (this.orderType) {
      case 'dot1':
        this.title = '正常'; break;
      case 'dot3':
        this.title = '前期'; break;
    }
    const filterCache = this.filterCache['DismantlingProgressingComponent'];
    if (filterCache && filterCache['dismantlingStarted']) {
      this.filterValueChangesRxx.next({dismantlingStarted: filterCache['dismantlingStarted']});
    }
    this.filterValueChangesRxx.subscribe(v => {
      this.filteredData = this.calculateFilteredData(v.dismantlingStarted);
      filterCache ?
        filterCache['dismantlingStarted'] = v.dismantlingStarted :
        this.filterCache['DismantlingProgressingComponent'] = {dismantlingStarted: v.dismantlingStarted}
      // console.log(this.filteredData);
    });

    this.optionsArr = [
      {
        title: 'dismantlingStarted',
        placeholder: '拆解已开始',
        initValue: filterCache ?
          (filterCache['dismantlingStarted'] ? filterCache['dismantlingStarted'] : 1)
          : 1,
        options: [
          {value: 1, viewValue: '全部'},
          {value: 2, viewValue: '是'},
          {value: 3, viewValue: '否'},
        ]
      }
    ];
  }

  calculateFilteredData(dismantlingStarted) {
    return this.data.reduce((acc, curr) => {
      if (curr.orderType === this.orderType) {
        const vehicleTypeIdsForMotocycle = this.btity['types']['vehicleTypeIdsForMotocycle'];
        const currType = vehicleTypeIdsForMotocycle.indexOf(curr['vehicleType']) > -1
          ? '摩托车' : '非摩托车';
        const obj = Object.assign({}, acc[currType]);
        for (const item of this.dataProps) {
          const name = item.name;  // name is week

          if (this.basedOnDismantlingStarted[dismantlingStarted].sumPredicate(curr)) {
            obj[name] = (acc[currType] ? (acc[currType][name] ? acc[currType][name] : 0) : 0) + curr[name];
          }
        }
        acc[currType] = Object.assign({}, obj);
      }
      return acc;
    }, {});
  }

  queryList(dismantlingOrderWeek, vehicleType?) {
    const dismantlingStarted = (this.filterValueChangesRxx.getValue()).dismantlingStarted;
    const searchQuery = {
      completed: false,
      orderType: this.orderType
    };
    if (dismantlingStarted > 1) {
      searchQuery['dismantlingStarted'] = dismantlingStarted === 2 ? true : false;
    }
    searchQuery['dismantlingOrderWeek'] = dismantlingOrderWeek;

    if (vehicleType) {
      searchQuery['vehicleType'] = vehicleType;
      // vehicleType here could be '2' or 'z', backend will deal with 'z'
    }
    // console.log(searchQuery);
    const dialogRef = this.dialog.open(DialogDismantlingOrderListComponent, {
      width: '80%',
      data: {
        searchQuery,
        source: '未完成拆解计划',
        dismantlingOrderWeek: (this.dataProps.find(dp => dp.name === dismantlingOrderWeek)).title,
        vehicleType
      }
    });

  }

}


text:
package executor

import (
	"context"
	"errors"
	"fmt"
	"sync"
	"testing"
	"time"

	"github.com/influxdata/flux"
	"github.com/influxdata/influxdb"
	icontext "github.com/influxdata/influxdb/context"
	"github.com/influxdata/influxdb/inmem"
	"github.com/influxdata/influxdb/kit/prom"
	"github.com/influxdata/influxdb/kit/prom/promtest"
	"github.com/influxdata/influxdb/kv"
	"github.com/influxdata/influxdb/query"
	"github.com/influxdata/influxdb/task/backend/scheduler"
	"go.uber.org/zap/zaptest"
)

type tes struct {
	svc     *fakeQueryService
	ex      *TaskExecutor
	metrics *ExecutorMetrics
	i       *kv.Service
	tc      testCreds
}

func taskExecutorSystem(t *testing.T) tes {
	aqs := newFakeQueryService()
	qs := query.QueryServiceBridge{
		AsyncQueryService: aqs,
	}

	i := kv.NewService(inmem.NewKVStore())

	ex, metrics := NewExecutor(zaptest.NewLogger(t), qs, i, i, i)
	return tes{
		svc:     aqs,
		ex:      ex,
		metrics: metrics,
		i:       i,
		tc:      createCreds(t, i),
	}
}

func TestTaskExecutor(t *testing.T) {
	t.Run("QuerySuccess", testQuerySuccess)
	t.Run("QueryFailure", testQueryFailure)
	t.Run("ManualRun", testManualRun)
	t.Run("ResumeRun", testResumingRun)
	t.Run("WorkerLimit", testWorkerLimit)
	t.Run("LimitFunc", testLimitFunc)
	t.Run("Metrics", testMetrics)
	t.Run("IteratorFailure", testIteratorFailure)
}

func testQuerySuccess(t *testing.T) {
	t.Parallel()
	tes := taskExecutorSystem(t)

	script := fmt.Sprintf(fmtTestScript, t.Name())
	ctx := icontext.SetAuthorizer(context.Background(), tes.tc.Auth)
	task, err := tes.i.CreateTask(ctx, influxdb.TaskCreate{OrganizationID: tes.tc.OrgID, OwnerID: tes.tc.Auth.GetUserID(), Flux: script})
	if err != nil {
		t.Fatal(err)
	}

	promise, err := tes.ex.Execute(ctx, scheduler.ID(task.ID), time.Unix(123, 0))
	if err != nil {
		t.Fatal(err)
	}
	promiseID := influxdb.ID(promise.ID())

	run, err := tes.i.FindRunByID(context.Background(), task.ID, promiseID)
	if err != nil {
		t.Fatal(err)
	}

	if run.ID != promiseID {
		t.Fatal("promise and run dont match")
	}

	tes.svc.WaitForQueryLive(t, script)
	tes.svc.SucceedQuery(script)

	<-promise.Done()

	if got := promise.Error(); got != nil {
		t.Fatal(got)
	}
}

func testQueryFailure(t *testing.T) {
	t.Parallel()
	tes := taskExecutorSystem(t)

	script := fmt.Sprintf(fmtTestScript, t.Name())
	ctx := icontext.SetAuthorizer(context.Background(), tes.tc.Auth)
	task, err := tes.i.CreateTask(ctx, influxdb.TaskCreate{OrganizationID: tes.tc.OrgID, OwnerID: tes.tc.Auth.GetUserID(), Flux: script})
	if err != nil {
		t.Fatal(err)
	}

	promise, err := tes.ex.Execute(ctx, scheduler.ID(task.ID), time.Unix(123, 0))
	if err != nil {
		t.Fatal(err)
	}
	promiseID := influxdb.ID(promise.ID())

	run, err := tes.i.FindRunByID(context.Background(), task.ID, promiseID)
	if err != nil {
		t.Fatal(err)
	}

	if run.ID != promiseID {
		t.Fatal("promise and run dont match")
	}

	tes.svc.WaitForQueryLive(t, script)
	tes.svc.FailQuery(script, errors.New("blargyblargblarg"))

	<-promise.Done()

	if got := promise.Error(); got == nil {
		t.Fatal("got no error when I should have")
	}
}

func testManualRun(t *testing.T) {
	t.Parallel()
	tes := taskExecutorSystem(t)

	script := fmt.Sprintf(fmtTestScript, t.Name())
	ctx := icontext.SetAuthorizer(context.Background(), tes.tc.Auth)
	task, err := tes.i.CreateTask(ctx, influxdb.TaskCreate{OrganizationID: tes.tc.OrgID, OwnerID: tes.tc.Auth.GetUserID(), Flux: script})
	if err != nil {
		t.Fatal(err)
	}

	manualRun, err := tes.i.ForceRun(ctx, task.ID, 123)
	if err != nil {
		t.Fatal(err)
	}

	mr, err := tes.i.ManualRuns(ctx, task.ID)
	if err != nil {
		t.Fatal(err)
	}

	if len(mr) != 1 {
		t.Fatal("manual run not created by force run")
	}

	promise, err := tes.ex.Execute(ctx, scheduler.ID(task.ID), time.Unix(123, 0))
	if err != nil {
		t.Fatal(err)
	}
	promiseID := influxdb.ID(promise.ID())

	run, err := tes.i.FindRunByID(context.Background(), task.ID, promiseID)
	if err != nil {
		t.Fatal(err)
	}

	if run.ID != promiseID || manualRun.ID != promiseID {
		t.Fatal("promise and run and manual run dont match")
	}

	tes.svc.WaitForQueryLive(t, script)
	tes.svc.SucceedQuery(script)

	if got := promise.Error(); got != nil {
		t.Fatal(got)
	}
}

func testResumingRun(t *testing.T) {
	t.Parallel()
	tes := taskExecutorSystem(t)

	script := fmt.Sprintf(fmtTestScript, t.Name())
	ctx := icontext.SetAuthorizer(context.Background(), tes.tc.Auth)
	task, err := tes.i.CreateTask(ctx, influxdb.TaskCreate{OrganizationID: tes.tc.OrgID, OwnerID: tes.tc.Auth.GetUserID(), Flux: script})
	if err != nil {
		t.Fatal(err)
	}

	stalledRun, err := tes.i.CreateRun(ctx, task.ID, time.Unix(123, 0))
	if err != nil {
		t.Fatal(err)
	}

	promise, err := tes.ex.Execute(ctx, scheduler.ID(task.ID), time.Unix(123, 0))
	if err != nil {
		t.Fatal(err)
	}
	promiseID := influxdb.ID(promise.ID())

	// ensure that it doesn't recreate a promise
	promise2, err := tes.ex.Execute(ctx, scheduler.ID(task.ID), time.Unix(123, 0))
	if err != nil {
		t.Fatal(err)
	}

	if promise2 != promise {
		t.Fatal("executing a current promise for a task that is already running created a new promise")
	}

	run, err := tes.i.FindRunByID(context.Background(), task.ID, promiseID)
	if err != nil {
		t.Fatal(err)
	}

	if run.ID != promiseID || stalledRun.ID != promiseID {
		t.Fatal("promise and run and manual run dont match")
	}

	tes.svc.WaitForQueryLive(t, script)
	tes.svc.SucceedQuery(script)

	if got := promise.Error(); got != nil {
		t.Fatal(got)
	}
}

func testWorkerLimit(t *testing.T) {
	t.Parallel()
	tes := taskExecutorSystem(t)

	script := fmt.Sprintf(fmtTestScript, t.Name())
	ctx := icontext.SetAuthorizer(context.Background(), tes.tc.Auth)
	task, err := tes.i.CreateTask(ctx, influxdb.TaskCreate{OrganizationID: tes.tc.OrgID, OwnerID: tes.tc.Auth.GetUserID(), Flux: script})
	if err != nil {
		t.Fatal(err)
	}

	promise, err := tes.ex.Execute(ctx, scheduler.ID(task.ID), time.Unix(123, 0))
	if err != nil {
		t.Fatal(err)
	}

	if len(tes.ex.workerLimit) != 1 {
		t.Fatal("expected a worker to be started")
	}

	tes.svc.WaitForQueryLive(t, script)
	tes.svc.FailQuery(script, errors.New("blargyblargblarg"))

	<-promise.Done()

	if got := promise.Error(); got == nil {
		t.Fatal("got no error when I should have")
	}
}

func testLimitFunc(t *testing.T) {
	t.Parallel()
	tes := taskExecutorSystem(t)

	script := fmt.Sprintf(fmtTestScript, t.Name())
	ctx := icontext.SetAuthorizer(context.Background(), tes.tc.Auth)
	task, err := tes.i.CreateTask(ctx, influxdb.TaskCreate{OrganizationID: tes.tc.OrgID, OwnerID: tes.tc.Auth.GetUserID(), Flux: script})
	if err != nil {
		t.Fatal(err)
	}
	forcedErr := errors.New("forced")
	forcedQueryErr := influxdb.ErrQueryError(forcedErr)
	tes.svc.FailNextQuery(forcedErr)

	count := 0
	tes.ex.SetLimitFunc(func(*influxdb.Run) error {
		count++
		if count < 2 {
			return errors.New("not there yet")
		}
		return nil
	})

	promise, err := tes.ex.Execute(ctx, scheduler.ID(task.ID), time.Unix(123, 0))
	if err != nil {
		t.Fatal(err)
	}

	<-promise.Done()

	if got := promise.Error(); got.Error() != forcedQueryErr.Error() {
		t.Fatal("failed to get failure from forced error")
	}

	if count != 2 {
		t.Fatalf("failed to call limitFunc enough times: %d", count)
	}
}

func testMetrics(t *testing.T) {
	t.Parallel()
	tes := taskExecutorSystem(t)
	metrics := tes.metrics
	reg := prom.NewRegistry()
	reg.MustRegister(metrics.PrometheusCollectors()...)

	mg := promtest.MustGather(t, reg)
	m := promtest.MustFindMetric(t, mg, "task_executor_total_runs_active", nil)
	if got := *m.Gauge.Value; got != 0 {
		t.Fatalf("expected 0 total runs active, got %v", got)
	}

	script := fmt.Sprintf(fmtTestScript, t.Name())
	ctx := icontext.SetAuthorizer(context.Background(), tes.tc.Auth)
	task, err := tes.i.CreateTask(ctx, influxdb.TaskCreate{OrganizationID: tes.tc.OrgID, OwnerID: tes.tc.Auth.GetUserID(), Flux: script})
	if err != nil {
		t.Fatal(err)
	}

	promise, err := tes.ex.Execute(ctx, scheduler.ID(task.ID), time.Unix(123, 0))
	if err != nil {
		t.Fatal(err)
	}
	promiseID := influxdb.ID(promise.ID())

	run, err := tes.i.FindRunByID(context.Background(), task.ID, promiseID)
	if err != nil {
		t.Fatal(err)
	}

	if run.ID != promiseID {
		t.Fatal("promise and run dont match")
	}

	tes.svc.WaitForQueryLive(t, script)

	mg = promtest.MustGather(t, reg)
	m = promtest.MustFindMetric(t, mg, "task_executor_total_runs_active", nil)
	if got := *m.Gauge.Value; got != 1 {
		t.Fatalf("expected 1 total runs active, got %v", got)
	}

	tes.svc.SucceedQuery(script)
	<-promise.Done()

	mg = promtest.MustGather(t, reg)

	m = promtest.MustFindMetric(t, mg, "task_executor_total_runs_complete", map[string]string{"status": "success"})
	if got := *m.Counter.Value; got != 1 {
		t.Fatalf("expected 1 active runs, got %v", got)
	}
	m = promtest.MustFindMetric(t, mg, "task_executor_total_runs_active", nil)
	if got := *m.Gauge.Value; got != 0 {
		t.Fatalf("expected 0 total runs active, got %v", got)
	}

	if got := promise.Error(); got != nil {
		t.Fatal(got)
	}

	// manual runs metrics
	mt, err := tes.i.CreateTask(ctx, influxdb.TaskCreate{OrganizationID: tes.tc.OrgID, OwnerID: tes.tc.Auth.GetUserID(), Flux: script})
	if err != nil {
		t.Fatal(err)
	}

	scheduledFor := int64(123)

	_, err = tes.i.ForceRun(ctx, mt.ID, scheduledFor)
	if err != nil {
		t.Fatal(err)
	}

	scheduledForTime := time.Unix(scheduledFor, 0).UTC()

	tes.ex.Execute(ctx, scheduler.ID(mt.ID), scheduledForTime)

	mg = promtest.MustGather(t, reg)

	m = promtest.MustFindMetric(t, mg, "task_executor_manual_runs_counter", map[string]string{"taskID": string(mt.ID)})
	if got := *m.Counter.Value; got != 1 {
		t.Fatalf("expected 1 manual run, got %v", got)
	}

}

func testIteratorFailure(t *testing.T) {
	t.Parallel()
	tes := taskExecutorSystem(t)

	// replace iterator exhaust function with one which errors
	tes.ex.workerPool = sync.Pool{New: func() interface{} {
		return &worker{tes.ex, func(flux.Result) error {
			return errors.New("something went wrong exhausting iterator")
		}}
	}}

	script := fmt.Sprintf(fmtTestScript, t.Name())
	ctx := icontext.SetAuthorizer(context.Background(), tes.tc.Auth)
	task, err := tes.i.CreateTask(ctx, influxdb.TaskCreate{OrganizationID: tes.tc.OrgID, OwnerID: tes.tc.Auth.GetUserID(), Flux: script})
	if err != nil {
		t.Fatal(err)
	}

	promise, err := tes.ex.Execute(ctx, scheduler.ID(task.ID), time.Unix(123, 0))
	if err != nil {
		t.Fatal(err)
	}
	promiseID := influxdb.ID(promise.ID())

	run, err := tes.i.FindRunByID(context.Background(), task.ID, promiseID)
	if err != nil {
		t.Fatal(err)
	}

	if run.ID != promiseID {
		t.Fatal("promise and run dont match")
	}

	tes.svc.WaitForQueryLive(t, script)
	tes.svc.SucceedQuery(script)

	<-promise.Done()

	if got := promise.Error(); got == nil {
		t.Fatal("got no error when I should have")
	}
}


text:
> Bootstrap V4 CSS provides several classes that control the sizing of elements, of which some of
> these have been translated into props on components.

## Component `size` prop

Various components allow for an optional size (via the `size` prop). Below are the sizes supported
via the default Bootstrap V4 CSS.

Available Sizes:

- `sm` small
- `lg` large

When no size is specified, this results in normal sized appearance (usually referred to as `md`).

These size values will be translated into the appropriate Bootstrap CSS class, depending on the
component used on, such as `.btn-<size>` for buttons, `.modal-<size>` for modal,
`.form-control-<size>` for form elements, `.pagination-<size>` for pagination buttons, etc.

## Breakpoint sizes

Bootstrap V4 also includes viewport breakpoint sizes: `xs`, `sm`, `md`, `lg`, and `xl`. which refer
to the width of the user's view port.

For details on breakpoint sizes, please check the [Layout and Grid](/docs/layout/) documentation.

## Sizing utility classes

Easily make an element as wide or as tall (relative to its parent) with the width and height
utilities classes.

Width and height utilities are generated from the `$sizes` Sass map in Bootstrap's
`_variables.scss`. Includes support for `25%`, `50%`, `75%`, and `100%` by default. Modify those
values as you need to generate different utilities here.

**Widths:**

```html
<div class="text-center">
  <div class="w-25 p-3 mb-1 bg-secondary">Width 25%</div>
  <div class="w-50 p-3 mb-1 bg-secondary">Width 50%</div>
  <div class="w-75 p-3 mb-1 bg-secondary">Width 75%</div>
  <div class="w-100 p-3 bg-secondary">Width 100%</div>
</div>

<!-- widths.vue -->
```

**Heights:**

```html
<div style="height: 100px; background-color: rgba(255,0,0,0.1);">
  <div class="h-25 d-inline-block" style="width: 120px; background-color: rgba(0,0,255,.1)">
    Height 25%
  </div>
  <div class="h-50 d-inline-block" style="width: 120px; background-color: rgba(0,0,255,.1)">
    Height 50%
  </div>
  <div class="h-75 d-inline-block" style="width: 120px; background-color: rgba(0,0,255,.1)">
    Height 75%
  </div>
  <div class="h-100 d-inline-block" style="width: 120px; background-color: rgba(0,0,255,.1)">
    Height 100%
  </div>
</div>

<!-- heights.vue -->
```

**Max width and height:**

You can also use `mw-100` (`max-width: 100%;`) and `mh-100` (`max-height: 100%;`) utilities as
needed.

## Additional resources

Refer to [Bootstrap V4](https://getbootstrap.com/) official documentation site for more information.


text:
namespace System.Net
{
    internal sealed class InternalException : Exception
    {
        private readonly object _unexpectedValue;

        internal InternalException()
        {
            NetEventSource.Fail(this, "InternalException thrown.");
        }

        internal InternalException(object unexpectedValue)
        {
            _unexpectedValue = unexpectedValue;
            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Fail(this, $"InternalException thrown for unexpected value: {unexpectedValue}");
            }
        }

        public override string Message => _unexpectedValue != null ?
            base.Message + " " + _unexpectedValue :
            base.Message;
    }
}


text:
import { Injectable, OnDestroy } from '@angular/core';

import { Observable } from 'rxjs/Observable';
import { of }         from 'rxjs/observable/of';
import { delay }      from 'rxjs/operators';

export class Crisis {
  constructor(public id: number, public name: string) { }
}

const CRISES: Crisis[] = [
  new Crisis(1, 'Dragon Burning Cities'),
  new Crisis(2, 'Sky Rains Great White Sharks'),
  new Crisis(3, 'Giant Asteroid Heading For Earth'),
  new Crisis(4, 'Procrastinators Meeting Delayed Again'),
];

const FETCH_LATENCY = 500;

/** Simulate a data service that retrieves crises from a server */
@Injectable()
export class CrisisService implements OnDestroy {
  constructor() { console.log('CrisisService instance created.'); }
  ngOnDestroy() { console.log('CrisisService instance destroyed.'); }

  getCrises(): Observable<Crisis[]> {
    return of(CRISES).pipe(delay(FETCH_LATENCY));
  }

  getCrisis(id: number | string): Observable<Crisis> {
    return of(CRISES.find(crisis => crisis.id === +id))
      .pipe(delay(FETCH_LATENCY));
  }
}


text:
<resources>
    <string name="app_name">KotlinDaggerApp</string>
</resources>


text:
MACRO(PARSE_ARGUMENTS prefix arg_names option_names)
  SET(DEFAULT_ARGS)
  FOREACH(arg_name ${arg_names})
    SET(${prefix}_${arg_name})
  ENDFOREACH(arg_name)
  FOREACH(option ${option_names})
    SET(${prefix}_${option} FALSE)
  ENDFOREACH(option)

  SET(current_arg_name DEFAULT_ARGS)
  SET(current_arg_list)
  FOREACH(arg ${ARGN})
    SET(larg_names ${arg_names})
    LIST(FIND larg_names "${arg}" is_arg_name)
    IF (is_arg_name GREATER -1)
      SET(${prefix}_${current_arg_name} ${current_arg_list})
      SET(current_arg_name ${arg})
      SET(current_arg_list)
    ELSE (is_arg_name GREATER -1)
      SET(loption_names ${option_names})
      LIST(FIND loption_names "${arg}" is_option)
      IF (is_option GREATER -1)
	     SET(${prefix}_${arg} TRUE)
      ELSE (is_option GREATER -1)
	     SET(current_arg_list ${current_arg_list} ${arg})
      ENDIF (is_option GREATER -1)
    ENDIF (is_arg_name GREATER -1)
  ENDFOREACH(arg)
  SET(${prefix}_${current_arg_name} ${current_arg_list})
ENDMACRO(PARSE_ARGUMENTS)

# Generates a string containing space separated elements of a list
macro(separate_by_spaces _VAR_ _LIST_)
	list(GET ${_LIST_} 0 LIST_START)
	set(LIST_REST ${${_LIST_}})
	list(REMOVE_AT LIST_REST 0)
	set(${_VAR_} "${LIST_START}")
	foreach(I ${LIST_REST})
		set(${_VAR_} "${${_VAR_}} ${I}")
	endforeach(I)
endmacro(separate_by_spaces)

# Adds a subdirectory, then pulls its include_directories and sets
# them in the current directory scope.
macro(add_subdirectory_with_includes _DIR_NAME_)
	add_subdirectory(${_DIR_NAME_})
	get_directory_property(TMP DIRECTORY ${_DIR_NAME_} INCLUDE_DIRECTORIES)
	include_directories(${TMP})
endmacro(add_subdirectory_with_includes)


text:
package org.aries.client.jms;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.jms.JMSException;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aries.Handler;
import org.aries.message.Message;
import org.aries.service.AbstractServiceProxy;
import org.aries.service.ServiceProxy;

public class JMSServiceProxy extends AbstractServiceProxy implements ServiceProxy {

	private static Log log = LogFactory.getLog(JMSServiceProxy.class);

	private JMSEndpointContext endpointContext;

	public JMSServiceProxy(JMSEndpointContext endpointContext) {
		this.endpointContext = endpointContext;
	}

	public void initialize() throws JMSException {
    	endpointContext.initialize();
	}

	public void dispatch(Message message) {
		try {
			javax.jms.Message jmsMessage = endpointContext.toJMSMessage(message);
			endpointContext.getProducer().send(jmsMessage);

		} catch (JMSException e) {
            log.error("****** Exception: "+ExceptionUtils.getRootCauseMessage(e));
            log.debug("", e);
			//TODO drill down and get the actual cause
			//TODO throw instead a UserDefined fault
			throw new RuntimeException(e);

		} catch (RuntimeException e) {
            log.error("****** Exception: "+ExceptionUtils.getRootCauseMessage(e));
            log.debug("", e);
			//assuming for now e is acceptable for propagation
			//(i.e. not like an SQLException etc...)
			//TODO drill down and get the actual cause
			//TODO throw instead a UserDefined fault
			throw e;

		} catch (Throwable e) {
            log.error("****** Exception: "+ExceptionUtils.getRootCauseMessage(e));
			//assuming for now e is acceptable for propagation
			//(i.e. not like an SQLException etc...)
			//TODO drill down and get the actual cause
			//TODO throw instead a UserDefined fault
            log.debug("", e);
			throw new RuntimeException(e);
		}
	}

	public Future<Message> invoke(final Message request, Handler<Message> handler) {
		ExecutorService executor = createExecutor("aries.jms", "JMSServiceProxy", 1);
		Callable<Message> callable = new Callable<Message>() {
			public Message call() {
				try {
					javax.jms.Message jmsRequest = endpointContext.toJMSMessage(request);
					endpointContext.getProducer().send(jmsRequest);

					javax.jms.Message jmsResponse = endpointContext.getConsumer().receive(2000);
					Message response = endpointContext.fromJMSMessage(jmsResponse);
					return response;

				} catch (Exception e) {
		            log.error("****** Exception: "+ExceptionUtils.getRootCauseMessage(e));
					log.debug("", e);
					return null;
				}
			}
		};

//		AsyncHandler<Message> asyncHandler = new AsyncHandler<Message>() {
//			public void handleResponse(Response<Message> response) {
//				Message message = response.get();
//				BankLoanQuoteResponse bankLoanQuoteResponse = message.getPart("response");
//				boolean accepted = getLoanQuoteHandler.accept(bankLoanQuoteResponse);
//				if (accepted) {
//
//				}
//			}
//		};

		FutureTask<Message> future = new AsyncResponse<Message>(callable, handler);
		executor.execute(future);
		return future;
	}

	public Message invoke(Message request) {
		//request.addPart("ARIESServiceName", service);
		//request.addPart("ARIESMethodName", method);

		try {
			javax.jms.Message jmsRequest = endpointContext.toJMSMessage(request);
			javax.jms.Message jmsResponse = endpointContext.getInvoker().invoke(jmsRequest);
			Message response = endpointContext.fromJMSMessage(jmsResponse);
			return response;

		} catch (JMSException e) {
            log.error("****** Exception: "+ExceptionUtils.getRootCauseMessage(e));
            log.debug("", e);
			//TODO drill down and get the actual cause
			//TODO throw instead a UserDefined fault
			throw new RuntimeException(e);

		} catch (RuntimeException e) {
            log.error("****** Exception: "+ExceptionUtils.getRootCauseMessage(e));
            log.debug("", e);
			//assuming for now e is acceptable for propagation
			//(i.e. not like an SQLException etc...)
			//TODO drill down and get the actual cause
			//TODO throw instead a UserDefined fault
			throw e;

		} catch (Throwable e) {
            log.error("****** Exception: "+ExceptionUtils.getRootCauseMessage(e));
			//assuming for now e is acceptable for propagation
			//(i.e. not like an SQLException etc...)
			//TODO drill down and get the actual cause
			//TODO throw instead a UserDefined fault
            log.debug("", e);
			throw new RuntimeException(e);
		}
	}

	public Message receive(long timeout) {
		//Assert.notNull(incomingDestination, "JMS incoming-destination must be specified");

		try {
			//attempt to receive message
			javax.jms.Message jmsMessage = endpointContext.getConsumer().receive(timeout);
			if (jmsMessage == null)
				return null;

			//process received message
			Message response = endpointContext.fromJMSMessage(jmsMessage);
			return response;

		} catch (JMSException e) {
            log.error("****** Exception: "+ExceptionUtils.getRootCauseMessage(e));
            log.debug("", e);
			//TODO drill down and get the actual cause
			//TODO throw instead a UserDefined fault
			throw new RuntimeException(e);

		} catch (RuntimeException e) {
            log.error("****** Exception: "+ExceptionUtils.getRootCauseMessage(e));
            log.debug("", e);
			//assuming for now e is acceptable for propagation
			//(i.e. not like an SQLException etc...)
			//TODO drill down and get the actual cause
			//TODO throw instead a UserDefined fault
			throw e;

		} catch (Throwable e) {
            log.error("****** Exception: "+ExceptionUtils.getRootCauseMessage(e));
			//assuming for now e is acceptable for propagation
			//(i.e. not like an SQLException etc...)
			//TODO drill down and get the actual cause
			//TODO throw instead a UserDefined fault
            log.debug("", e);
			throw new RuntimeException(e);
		}
	}

	protected ExecutorService createExecutor() {
		return createExecutor("aries.jms", "JMSServiceProxy", 1);
	}

	//TODO use keep alive var.
	protected ExecutorService createExecutor(String group, String name, int poolSize) {
		SynchronousQueue<Runnable> workQueue = new SynchronousQueue<Runnable>();
		ThreadPoolExecutor executor = createThreadPoolExecutor(workQueue, group, name, poolSize);
		executor.prestartAllCoreThreads();
		return executor;
	}

	protected ThreadPoolExecutor createThreadPoolExecutor(BlockingQueue<Runnable> workQueue, final String group, final String name, int poolSize) {
		final ThreadGroup threadGroup = new ThreadGroup(group);
		ThreadPoolExecutor executor = new ThreadPoolExecutor(1, poolSize, 1, TimeUnit.MINUTES, workQueue, new ThreadFactory() {
			private int counter = 0;
			public Thread newThread(Runnable runnable) {
				Thread thread = new Thread(threadGroup, runnable);
				thread.setName(group+name+"."+counter);
				//TODO check do we need this?
				//thread.setDaemon(true);
				counter++;
				return thread;
			}
		});
		return executor;
	}

}


text:
using System;
using System.Linq;
using System.Collections.Generic;
using VioletGrass.ProjectModel.Issues;
using System.Threading.Tasks;

namespace VioletGrass.ProjectModel.Storage
{
    /// <summary>
    /// In memory project storage.
    /// </summary>
    /// <remarks>This implemenation is not thread safe. We avoided using System.Collections.Concurrent here due to additionally dependency.</remarks>
    public class InMemoryStorage : IProjectStorage
    {
        private IDictionary<string, Owner> _owners = new Dictionary<string, Owner>();
        private IDictionary<string, List<Issue>> _issueCollections = new Dictionary<string, List<Issue>>();

        /// <summary>
        /// Loads the issue collection as specified with the owner/project.
        /// </summary>
        /// <param name="ownerName">The name of the owner.</param>
        /// <param name="projectName">The name of the project.</param>
        /// <param name="issueId">The issueId.</param>
        /// <returns>The list of all issues. Returns a empty collection if project is not found.</returns>
        public Task<Issue> GetIssueAsync(string ownerName, string projectName, string issueId)
        {
            Issue result = null;
            List<Issue> issues = null;

            var projectFullName = Project.CreateFullName(ownerName, projectName);

            if (_issueCollections.TryGetValue(projectFullName, out issues))
            {
                result = issues.FirstOrDefault(i => i.Id == issueId);
            }

            return Task.FromResult(result);
        }

        /// <summary>
        /// Loads the owner including all projects below.
        /// </summary>
        /// <param name="ownerName">The name of the owner.</param>
        /// <returns>The owner including all projects.</returns>
        public Task<Owner> GetOwnerWithProjectsAsync(string ownerName)
        {
            Owner result = null;

            _owners.TryGetValue(ownerName, out result);

            return Task.FromResult(result);
        }

        /// <summary>
        /// Saves an issue collection.
        /// </summary>
        /// <param name="ownerName">The name of the owner.</param>
        /// <param name="projectName">The name of the project.</param>
        /// <param name="issue">The issue collection to save.</param>
        public Task SaveIssue(string ownerName, string projectName, Issue issue)
        {
            if (issue == null)
            {
                throw new ArgumentNullException(nameof(issue));
            }

            var projectFullName = Project.CreateFullName(ownerName, projectName);

            if (_issueCollections.ContainsKey(projectFullName))
            {
                var collection = _issueCollections[projectFullName];

                collection.RemoveAll(i => i.Id == issue.Id);
                collection.Add(issue);
            }
            else
            {
                _issueCollections.Add(projectFullName, new List<Issue>() { issue });
            }

            return Task.CompletedTask;
        }

        /// <summary>
        /// Saves a modified owner.
        /// </summary>
        /// <param name="owner">The owner to save.</param>
        public Task SaveOwner(Owner owner)
        {
            if (owner == null)
            {
                throw new ArgumentNullException(nameof(owner));
            }

            var ownerName = owner.Name;

            if (_owners.ContainsKey(ownerName))
            {
                _owners[ownerName] = owner;
            }
            else
            {
                _owners.Add(ownerName, owner);
            }

            return Task.CompletedTask;
        }
    }
}


text:
using System;
using FluentNHibernate.Mapping;

namespace Logic.Customers
{
    public class CustomerMap : ClassMap<Customer>
    {
        public CustomerMap()
        {
            Id(x => x.Id);

            Map(x => x.Name).CustomType<string>().Access.CamelCaseField(Prefix.Underscore);
            Map(x => x.Email).CustomType<string>().Access.CamelCaseField(Prefix.Underscore);
            Map(x => x.MoneySpent).CustomType<decimal>().Access.CamelCaseField(Prefix.Underscore);

            Component(x => x.Status, y =>
            {
                y.Map(x => x.Type, "Status").CustomType<int>();
                y.Map(x => x.ExpirationDate, "StatusExpirationDate").CustomType<DateTime?>()
                    .Access.CamelCaseField(Prefix.Underscore)
                    .Nullable();
            });

            HasMany(x => x.PurchasedMovies).Access.CamelCaseField(Prefix.Underscore); ;
        }
    }
}


text:
# Table of Contents
- [Develop all-the-things() with a dev-ci-cd pipeline](#develop-all-the-things-with-a-dev-ci-cd-pipeline)
    - [Problem](#problem)
    - [Solution](#solution)
    - [Overview](#overview)
        - [CI/CD in Openshift](#cicd-in-openshift)
        - [Jenkins Pipeline](#jenkins-pipeline)
        - [Openshift Pipelines](#openshift-pipelines)
    - [Components](#components)
    - [Setup](#setup)
        - [Prerequisites](#prerequisites)
        - [Install](#install)
            - [Launch Openshift Cluster](#launch-openshift-cluster)
            - [Deploy Jenkins](#deploy-jenkins)
            - [Deploy Local Git Server](#deploy-local-git-server)
            - [Add your project to start development](#add-your-project-to-start-development)
                - [Clone a public repository](#clone-a-public-repository)
                - [Add a remote for your git server](#add-a-remote-for-your-git-server)
                - [Add Jenkinsfile to root of repo](#add-jenkinsfile-to-root-of-repo)
                - [Make changes and commit and push the code to the git server](#make-changes-and-commit-and-push-the-code-to-the-git-server)
    - [Talks and Videos](#talks-and-videos)
        - [#devconfcz Presentation and Video](#devconfcz-presentation-and-video)
        - [Demo Video](#demo-video)

# Develop all-the-things() with a dev-ci-cd pipeline

## Problem

How do we enable developers on a project to be more efficient and produce higher quality code into production environments and not overburden them with a CI/CD process?

Often developers want to develop code and continuously test it and produce an end component, application, module, etc.  In these cases more often than not when the component or application is built and tested in a developer's environment it behaves differently than in a stage or production environment.  How do we allow developers to make changes faster without compromising quality.

## Solution

If a developer can develop, build, test, and continuously integrate a component as it would be in production in their own development environment before it even goes into a pull request or even worse checked in to the code base it help identify issues sooner and closer to the changes and the person making the changes.

Openshift has put an excellent PaaS and CI/CD pipeline combination together that can be be run in a developer's environment to Build->Test->Integrate->Test->Deliver->Deploy to environments. (ex. Stage and Production)

A developer can take their code and easily move it through a CI/CD Pipeline on Openshift which is a Platform as a Service (PaaS). Openshift combined with Jenkins and Jenkins pipeline to develop code from their local sandbox, git repositories, docker hub, etc.

## Overview

### CI/CD in Openshift

* Webhook triggers for builds
* Build my application image when my code changes
* ImageChangeTriggers for builds
* Build my application image when my base image changes
* Post-build test hooks
* Test my application image before I push it to a registry
* ImageChangeTriggers for deployments
* Redeploy my application when my image changes (e.g. after a build)

### Jenkins Pipeline

Developers can store their tests and CI/CD pipelines with their source code and this can be automatically loaded into the Jenkins Master container instance.  So as changes are made to code and tests it can also be made to the pipeline itself and tested.  This all can be run from within the developer's desktop to be used as an identical setup of what runs in production

* Groovy syntax for running arbitrarily complex workflows
* Many plugins offer a DSL
* Pipeline is defined in a Jenkinsfile
* Jenkinsfile lives with source code on developers local code or in scm

### Openshift Pipelines

* New Pipeline BuildConfig strategy type
* Jenkins master and slave images
* Synchronization logic between Jenkins and OpenShift
* Web console for viewing Pipelines
* Auto-provisioning of Jenkins as needed

## Components

* Openshift Cluster
* Router, Registry, HA Proxy,  etc
* Pipelines
* Apps
* Jenkins Example
* Master and slave images
git server

## Setup

### Prerequisites

* oc
* oc cluster
* oc-cluster-wrapper

### Install

#### Launch Openshift Cluster

Add the below line to /etc/sysconfig/docker and restart docker
````
INSECURE_REGISTRY='--insecure-registry 172.30.0.0/16'
````
Install oc and oc-cluster-wrapper and set the path

````
$ sudo iptables -F
$ oc cluster up
$ oc login
$ Username: developer
$ Password: developer
````

#### Deploy Jenkins

Deploy a new project and Jenkins ephemeral or persistent master

````
$ oc new-project
$ oc new-app jenkins-persistent
````

Otherwise:

````
$ oc new-app jenkins-ephemeral
````

Find route to Jenkins service

````
$ oc get route
````

Loading the Sample App Configuration

If you decide to load the sample app that will appear as a job in Jenkins to test

````
$ oc new-app -f https://raw.githubusercontent.com/openshift/origin/master/examples/jenkins/application-template.json
````

#### Deploy Local Git Server

````
$ oc create -f https://raw.githubusercontent.com/openshift/origin/master/examples/gitserver/gitserver-ephemeral.yaml
$ oc policy add-role-to-user edit -z git
$ GITSERVER=http://$(oc get route git -o template --template '{{.spec.host}}')
$ echo $GITSERVER
$ git config --global credential.$GITSERVER.helper \
'!f() { echo "username=$(oc whoami)"; echo "password=$(oc whoami -t)"; }; f'
````

#### Add your project to start development

##### Clone a public repository

````
$ git clone https://github.com/arilivigni/linch-pin.git
````

##### Add a remote for your git server

````
$ cd linch-pin
$ git remote add openshift $GITSERVER/linch-pin.git
````

##### Add Jenkinsfile to root of repo

ex. Jenkinsfile

````
node('linch-pin-slave') {
    stage ('build') {
        dir('linch-pin') {
            git url: 'http://git:8080/linch-pin.git'
            sh '''
                virtualenv $WORKSPACE/lp-test-venv
                source $WORKSPACE/lp-test-venv/bin/activate
                ./install.sh
           '''
        }
    }
    stage ('test') {
        sh '''
            source $WORKSPACE/lp-test-venv/bin/activate
            pip install nosexcover pylint pycrypto flake8 pep8
            iconv -f utf8 -t ascii $WORKSPACE/linch-pin/requirements.txt >> $WORKSPACE/linch-pin/requirements.txt
            chmod -x $WORKSPACE/linch-pin/tests/*.py
            nosetests --verbosity=3 --with-xunit $WORKSPACE/linch-pin/tests/test_linchpin_creds.py
        '''
        archiveArtifacts '*.xml,**/*.md'
        junit 'nosetests.xml'
    }
}
````

##### Make changes and commit and push the code to the git server

````
$ git push openshift master
````

## Talks and Videos

### [#devconfcz Presentation and Video](https://youtu.be/EZwufSsDPDQ?list=PLeU5HlemqUTZo02zSUVp6DWkoJvDJuxUY)

### [Demo Video](https://www.youtube.com/watch?v=EZwufSsDPDQ)


text:
<?php

declare(strict_types=1);

namespace whatwedo\CrudBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use whatwedo\CrudBundle\Extension\ExtensionInterface;
use whatwedo\CrudBundle\Manager\DefinitionManager;
use whatwedo\CrudBundle\Resource\DefinitionResource;

class DefinitionPass implements CompilerPassInterface
{
    /**
     * this will initialize all Definitions.
     */
    public function process(ContainerBuilder $container): void
    {
        if (! $container->has(DefinitionManager::class)) {
            return;
        }

        /*
         * Load Definition Extensions
         */
        foreach (array_keys($container->findTaggedServiceIds('whatwedo_crud.extension')) as $id) {
            $crudExtension = $container->getDefinition($id);

            // all extensions must implement ExtensionInExtensionInterfaceterface
            if (! is_subclass_of($crudExtension->getClass(), ExtensionInterface::class)) {
                throw new \UnexpectedValueException(sprintf('Extensions tagged with whatwedo_crud.extension must implement %s - %s given.', ExtensionInterface::class, $crudExtension->getClass()));
            }

            // remove extensions from container if their requirements (other bundles) are not fulfilled
            if (! call_user_func([$crudExtension->getClass(), 'isEnabled'], [$container->getParameter('kernel.bundles')])) {
                $container->removeDefinition($id);
            }
        }

        /*
         * Load definitions
         */
        foreach ($container->findTaggedServiceIds('whatwedo_crud.definition') as $id => $tags) {
            $crudDefinition = $container->getDefinition($id);

            if ($crudDefinition->isAbstract()) {
                continue;
            }

            $crudDefinition->addMethodCall('setTemplates', [$container->getParameter('whatwedo_crud.config.templates')]);

            // add available extensions to all Definitions
            foreach (array_keys($container->findTaggedServiceIds('whatwedo_crud.extension')) as $idExtension) {
                $crudDefinition->addMethodCall('addExtension', [new Reference($idExtension)]);
            }

            // create a resource so that the cache is loaded new as soon as a definition is updated
            $container->addResource(new DefinitionResource($id));
        }
    }
}


text:
package com.maxleap.las.sdk;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.SimpleTimeZone;

/**
 *
 * @author sneaky
 * @since 3.0.0
 */
public class DateUtils {
  private static final DateFormat dateFormat;

  static {
    DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    format.setTimeZone(new SimpleTimeZone(0, "GMT"));
    dateFormat = format;
  }

  public static String encodeDate(Date date) {
    return dateFormat.format(date);
  }

  public synchronized static Date parseDate(String dateString) {
    try {
      return dateFormat.parse(dateString);
    } catch (Exception e) {
      return null;
    }
  }
}


text:
<?php

class Rootd_Tinymce_Block_Loader_Codemirror
    extends Rootd_Tinymce_Block_Loader_Abstract
{

    protected $_plugins = array();

    /**
     * Configure base data.
     *
     * @return void
     */
    protected function _construct()
    {
        $this->addData(
            array(
                'base_css_url'  => $this->getConfigUrl('tinymce/codemirror/base_css'),
                'base_js_url'   => $this->getConfigUrl('tinymce/codemirror/base_js'),
                'mode_js_url'   => $this->getConfigUrl('tinymce/codemirror/mode_js'),
                'loader_js_url' => $this->getConfigUrl('tinymce/codemirror/loader_js'),
            )
        );

        $this->_initPlugins();
    }

    /**
     * Add configured plugins.
     *
     * @return Rootd_Tinymce_Block_Loader_Codemirror
     */
    protected function _initPlugins()
    {
        $plugins = explode(',', Mage::getStoreConfig('tinymce/codemirror/plugins'));

        foreach ($plugins as $plugin) {
            $this->addPlugin($plugin);
        }

        return $this;
    }

    /**
     * Add a CodeMirror plugin.
     *
     * @param string $path An absolute or relative path to the plugin.
     *
     * @return Rootd_Tinymce_Block_Loader_Codemirror
     */
    public function addPlugin($path)
    {
        $this->_plugins[] = $this->resolveUrl($path);

        return $this;
    }

    /**
     * Generate JavaScript HTML for all registered plugins.
     *
     * @return string
     */
    public function getPluginJsHtml()
    {
        $html = '';

        foreach ($this->_plugins as $plugin) {
            $html .= $this->getJsHtml($plugin) . "\n";
        }

        return $html;
    }

}


text:
namespace CryptoNote {
class ISerializer;

typedef std::pair<Crypto::PublicKey, size_t> TransactionOutputId;
}

namespace std {

template<>
struct hash<CryptoNote::TransactionOutputId> {
  size_t operator()(const CryptoNote::TransactionOutputId &_v) const {
    return hash<Crypto::PublicKey>()(_v.first) ^ _v.second;
  }
};

}

namespace CryptoNote {

struct UnconfirmedTransferDetails {

  UnconfirmedTransferDetails() :
    amount(0), sentTime(0), transactionId(WALLET_LEGACY_INVALID_TRANSACTION_ID) {}

  CryptoNote::Transaction tx;
  uint64_t amount;
  uint64_t outsAmount;
  time_t sentTime;
  TransactionId transactionId;
  std::vector<TransactionOutputId> usedOutputs;
};

class WalletUnconfirmedTransactions
{
public:

  explicit WalletUnconfirmedTransactions(uint64_t uncofirmedTransactionsLiveTime);

  bool serialize(CryptoNote::ISerializer& s);

  bool findTransactionId(const Crypto::Hash& hash, TransactionId& id);
  void erase(const Crypto::Hash& hash);
  void add(const CryptoNote::Transaction& tx, TransactionId transactionId,
    uint64_t amount, const std::list<TransactionOutputInformation>& usedOutputs);
  void updateTransactionId(const Crypto::Hash& hash, TransactionId id);

  uint64_t countUnconfirmedOutsAmount() const;
  uint64_t countUnconfirmedTransactionsAmount() const;
  bool isUsed(const TransactionOutputInformation& out) const;
  void reset();

  std::vector<TransactionId> deleteOutdatedTransactions();

private:

  void collectUsedOutputs();
  void deleteUsedOutputs(const std::vector<TransactionOutputId>& usedOutputs);

  typedef std::unordered_map<Crypto::Hash, UnconfirmedTransferDetails, boost::hash<Crypto::Hash>> UnconfirmedTxsContainer;
  typedef std::unordered_set<TransactionOutputId> UsedOutputsContainer;

  UnconfirmedTxsContainer m_unconfirmedTxs;
  UsedOutputsContainer m_usedOutputs;
  uint64_t m_uncofirmedTransactionsLiveTime;
};

} // namespace CryptoNote


text:
/*
 *  Host Resources MIB - disk device group interface - hr_disk.h
 *
 */
#ifndef _MIBGROUP_HRDISK_H
#define _MIBGROUP_HRDISK_H

extern void     init_hr_disk(void);
extern void     Init_HR_Disk(void);
extern int      Get_Next_HR_Disk(void);
extern int      Get_Next_HR_Disk_Partition(char *, int);
extern FindVarMethod var_hrdisk;

#endif                          /* _MIBGROUP_HRDISK_H */


text:
from __future__ import absolute_import
from envisage.ui.workbench.workbench_plugin import *


text:
package mac.winter.entity;

public class UserEntity {

	String userId;

	String userName;

	String password;

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}


text:
package org.teavm.common;

/**
 *
 * @author Alexey Andreev
 */
public interface GraphNodeFilter {
    boolean match(int node);
}


text:
def get_value():
    """current core temperature is %d degrees celsius"""
    try:
        f = open("/sys/class/thermal/thermal_zone0/temp")
        val = int(f.read().strip())
        f.close()
        return val/1000
    except:
        return -1


text:
package com.intellij.webSymbols.webTypes.gen;

import com.fasterxml.jackson.databind.JsonNode;
import com.sun.codemodel.JClassContainer;
import com.sun.codemodel.JType;
import org.jsonschema2pojo.Schema;
import org.jsonschema2pojo.rules.TypeRule;

public class WebTypesTypeRule extends TypeRule {

  private final WebTypesRuleFactory myRuleFactory;

  protected WebTypesTypeRule(WebTypesRuleFactory ruleFactory) {
    super(ruleFactory);
    myRuleFactory = ruleFactory;
  }

  @Override
  public JType apply(String nodeName,
                     JsonNode node,
                     JsonNode parent,
                     JClassContainer jClassContainer,
                     Schema schema) {
    JType result = myRuleFactory.getOneOfRule().apply(nodeName, node, parent, jClassContainer.getPackage(), schema);
    if (result != null) {
      return result;
    }
    return super.apply(nodeName, node, parent, jClassContainer, schema);
  }

}


text:
/**
 *

 * Util classes to create a new search problem. Use {@link es.usc.citius.hipster.model.problem.ProblemBuilder}
 * to define a search problem required to instantiate a new algorithm with {@link es.usc.citius.hipster.algorithm.Hipster}
 * class. Example:
 *

 *

 *     {@code
 *     Hipster.SearchProblem p =
 *          ProblemBuilder.create()
 *              .initialState(initialState)
 *              .defineProblemWithExplicitActions()
 *                  .useActionFunction(af)
 *                  .useTransitionFunction(atf)
 *                  .useCostFunction(cf)
 *                  .useHeuristicFunction(hf)
 *                  .build();
 *
 *     Hipster.createAStar(p).search(goalState);
 *     }
 *

 */
package es.usc.citius.hipster.model.problem;


text:
package com.github.tkurz.sparqlmm.function.general.aggregation;

import com.github.tkurz.media.fragments.base.MediaFragment;
import com.github.tkurz.media.ontology.exception.NotAggregatableException;
import com.github.tkurz.media.ontology.function.SpatialFunction;
import com.github.tkurz.media.ontology.function.TemporalFunction;
import com.github.tkurz.media.ontology.type.SpatialEntity;
import com.github.tkurz.media.ontology.type.SpatialTemporalEntity;
import com.github.tkurz.media.ontology.type.TemporalEntity;
import com.github.tkurz.sparqlmm.Constants;
import com.github.tkurz.sparqlmm.doc.FunctionDoc;
import com.github.tkurz.sparqlmm.utils.FunctionHelper;
import com.google.common.base.Joiner;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.model.ValueFactory;
import org.openrdf.query.algebra.evaluation.ValueExprEvaluationException;
import org.openrdf.query.algebra.evaluation.function.Function;

/**
 * ...
 * <p/>
 * Author: Thomas Kurz (tkurz@apache.org)
 */
@FunctionDoc(title = "intersection", properties = {SpatialTemporalEntity.class,SpatialTemporalEntity.class}, reference = FunctionDoc.Reference.combined, description = "returns new MediaFragment / MediaFragmentURI with spatial and temporal fragment. It works like spatialFunction:boundingBox, temporalFunction:intersection and both.", type = FunctionDoc.Type.extensionAggregate)
public class IntersectionFunction implements Function {
    /**
     * return the URI
     */
    public String getURI() {
        return Constants.NAMESPACE + "intersection";
    }

    @Override
    public Value evaluate(ValueFactory valueFactory, Value... values) throws ValueExprEvaluationException {

        //check preconditions
        if(values.length != 2 || !FunctionHelper.isComparable(values)) return null;

        String [] res = new String[2];

        try {
            SpatialEntity[] entities = FunctionHelper.toSpatialEntities(values);
            res[0] = SpatialFunction.getIntersect(entities).stringValue();
        } catch (IllegalArgumentException e){}

        try {
            TemporalEntity[] entities = FunctionHelper.toTemporalEntities(values);
            res[1] = TemporalFunction.getIntersect(entities[0],entities[1]).stringValue();
        } catch (IllegalArgumentException | NotAggregatableException e) {}

        if(values[0] instanceof URI) {
            String uri = FunctionHelper.getCleanURI(values[0]);
            return  valueFactory.createURI(uri + MediaFragment.DEFAULT_TYPE.getDelimiter() + Joiner.on("&").skipNulls().join(res));
        } else {
            //evaluate
            return valueFactory.createLiteral(Joiner.on("&").skipNulls().join(res));
        }
    }
}