text:
function use(){
    echo "Usage: $0 [sim|phone] paintown-dir"
}

# Check if arguments are given and the paintown directory exists
if [ -n "$2" ] && [ -d "$2" ]; then
    if [ "$1" = "sim" ]; then
        make clean
        CFLAGS='-arch i386' LDFLAGS='-arch i386' CC=/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/gcc-4.2 ./configure --prefix=$2/misc/allegro-iphone/install/sim/ && make && make install
    elif [ "$1" = "phone" ]; then
        make clean
        CFLAGS='-arch armv6 -isysroot /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk -DDARWIN_NO_CARBON' LDFLAGS='-arch armv6 -isysroot /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk' CC=/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/gcc-4.2 ./configure --host=arm --build=i386 --prefix=$2/misc/allegro-iphone/install/phone/ --with-sysroot=/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk && make && make install
    fi
else
    use
fi


text:
@protocol SafariFactory;
@protocol MailComposeControllerFactory;
@class SpeakerInfoAlertFactory;

@interface SpeakerInfoRouter : NSObject <SpeakerInfoRouterInput>

@property (nonatomic, weak) id <RamblerViperModuleTransitionHandlerProtocol> transitionHandler;
@property (nonatomic, strong) id<SafariFactory> safariFactory;
@property (nonatomic, strong) id<MailComposeControllerFactory> mailComposeFactory;
@property (nonatomic, strong) SpeakerInfoAlertFactory *alertFactory;

@end

redpajama_set_name: RedPajamaGithub


text:
'''
Simple python wrapper for the GLSL reference compiler.
'''

import subprocess
import tempfile
import platform
import os
import sys
import genutil as util

def getToolsBinPath() :
    path = os.path.dirname(os.path.abspath(__file__))
    if platform.system() == 'Windows' :
        path += '/../../tools/win32/'
    elif platform.system() == 'Darwin' :
        path += '/../../tools/osx/'
    elif platform.system() == 'Linux' :
        path +=  '/../../tools/linux/'
    else :
        error("Unknown host system {}".format(platform.system()))
    return path;

def writeFile(f, lines) :
    '''
    Write an array of lines to a file.
    '''
    for line in lines :
        f.write(line.content + '\n')

def callValidator(cmd) :
    '''
    call the GLSL reference compiler and return its output
    '''
    child = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    out = ''
    while True :
        out += child.stdout.read()
        if child.poll() != None :
            break
    return out

def parseOutput(output, lines) :
    '''
    Parse error output lines from the GLSL reference compiler,
    map them to the original source code location and output
    an error message compatible with Xcode or VStudio
    '''
    hasError = False
    outLines = output.splitlines()
    for outLine in outLines :
        if outLine.startswith('ERROR: ') :
            hasError = True

            # extract generated shader source column, line and message
            colStartIndex = 7
            colEndIndex = outLine.find(':', colStartIndex)
            if colEndIndex == -1 :
                continue
            lineStartIndex = colEndIndex + 1
            lineEndIndex = outLine.find(':', lineStartIndex)
            if lineEndIndex == -1 :
                continue
            msgStartIndex = lineEndIndex + 1
            colNr = int(outLine[colStartIndex:colEndIndex])
            lineNr = int(outLine[lineStartIndex:lineEndIndex])
            msg = outLine[msgStartIndex:]

            # map to original location
            lineIndex = lineNr - 1
            if lineIndex >= len(lines) :
                lineIndex = len(lines) - 1
            srcPath = lines[lineIndex].path
            srcLineNr = lines[lineIndex].lineNumber

            # and output...
            util.setErrorLocation(srcPath, srcLineNr)
            util.fmtError(msg, False)

    if hasError :
        for line in lines :
            print(line.content)
        sys.exit(10)

def validate(lines, type, glslVersion) :
    '''
    Validate a vertex-/fragment-shader pair for a given glsl version.
    '''
    ext = {
        'vs': '.vert',
        'fs': '.frag'
    }
    f = tempfile.NamedTemporaryFile(suffix=ext[type], delete=False)
    writeFile(f, lines)
    f.close()

    toolPath = getToolsBinPath() + 'glslangValidator'
    cmd = [toolPath, f.name]
    output = callValidator(cmd)
    os.unlink(f.name)
    parseOutput(output, lines)


text:
#import <UIKit/UIKit.h>
#import <Photos/Photos.h>

NS_ASSUME_NONNULL_BEGIN

/**
 *  A view controller that shows selected photos and vidoes from user's photo library that let the user navigate the item page by page.
 */
@interface CTAssetsPageViewController : UIPageViewController

/**
 *  The index of the photo or video with the currently showing item.
 */
@property (nonatomic, assign) NSInteger pageIndex;

/**
 *  @name Creating a Assets Page View Controller
 */

/**
 *  Initializes a newly created view controller with a fetech result.
 *
 *  @param fetchResult A fetch result of `PHAsset` objects.
 *
 *  @return An instance of `CTAssetPageViewController` initialized to show the asset items in `fetchResult`.
 */
- (instancetype)initWithFetchResult:(PHFetchResult *)fetchResult;

/**
 *  Initializes a newly created view controller with an array of assets.
 *
 *  @param assets An array of `PHAsset` objects.
 *
 *  @return An instance of `CTAssetPageViewController` initialized to show the asset items in `assets`.
 */
- (instancetype)initWithAssets:(NSArray<PHAsset*> *)assets;

@end

NS_ASSUME_NONNULL_END


text:
require 'locomotive/common'

require_relative '../tools/styled_yaml'

require_relative 'loggers/sync_logger'

require_relative_all  'concerns'
require_relative      'sync_sub_commands/concerns/base_concern'

require_relative      'pull_sub_commands/pull_base_command'
require_relative_all  'pull_sub_commands'
require_relative_all  'sync_sub_commands'

module Locomotive::Wagon

  class SyncCommand < Struct.new(:env, :path, :options)

    RESOURCES = %w(pages content_entries translations).freeze

    include ApiConcern
    include DeployFileConcern
    include InstrumentationConcern

    def self.sync(env, path, options)
      self.new(env, path, options).sync
    end

    def sync
      SyncLogger.new if options[:verbose]

      api_client = api_site_client(connection_information)
      site = api_client.current_site.get

      each_resource do |klass|
        klass.sync(api_client, site, path)
      end
    end

    private

    def each_resource
      RESOURCES.each do |name|
        next if !options[:resources].blank? && !options[:resources].include?(name)

        klass = "Locomotive::Wagon::Sync#{name.camelcase}Command".constantize

        yield klass
      end
    end

    def connection_information
      read_deploy_settings(self.env, self.path)
    end

  end

end


text:
"""
These are the default bindings:
    Click button 1 on entry: Show calendar
    Click button 1 outsite calendar and entry: Hide calendar
    Escape: Hide calendar
    CTRL + PAGE UP: Move to the previous month.
    CTRL + PAGE DOWN: Move to the next month.
    CTRL + SHIFT + PAGE UP: Move to the previous year.
    CTRL + SHIFT + PAGE DOWN: Move to the next year.
    CTRL + LEFT: Move to the previous day.
    CTRL + RIGHT: Move to the next day.
    CTRL + UP: Move to the previous week.
    CTRL + DOWN: Move to the next week.
    CTRL + END: Close the datepicker and erase the date.
    CTRL + HOME: Move to the current month.
    CTRL + SPACE: Show date on calendar
    CTRL + Return: Set current selection to entry
"""

import calendar
import datetime

try:
    import Tkinter
    import tkFont
    import ttk

    from Tkconstants import CENTER, LEFT, N, E, W, S
    from Tkinter import StringVar
except ImportError: # py3k
    import tkinter as Tkinter
    import tkinter.font as tkFont
    import tkinter.ttk as ttk

    from tkinter.constants import CENTER, LEFT, N, E, W, S
    from tkinter import StringVar

def get_calendar(locale, fwday):
    # instantiate proper calendar class
    if locale is None:
        return calendar.TextCalendar(fwday)
    else:
        return calendar.LocaleTextCalendar(fwday, locale)

class Calendar(ttk.Frame):
    datetime = calendar.datetime.datetime
    timedelta = calendar.datetime.timedelta

    def __init__(self, master=None, year=None, month=None, firstweekday=calendar.MONDAY, locale=None, activebackground='#b1dcfb', activeforeground='black', selectbackground='#003eff', selectforeground='white', command=None, borderwidth=1, relief="solid", on_click_month_button=None):
        """
        WIDGET OPTIONS

            locale, firstweekday, year, month, selectbackground,
            selectforeground, activebackground, activeforeground,
            command, borderwidth, relief, on_click_month_button
        """

        if year is None:
            year = self.datetime.now().year

        if month is None:
            month = self.datetime.now().month

        self._selected_date = None

        self._sel_bg = selectbackground
        self._sel_fg = selectforeground

        self._act_bg = activebackground
        self._act_fg = activeforeground

        self.on_click_month_button = on_click_month_button

        self._selection_is_visible = False
        self._command = command

        ttk.Frame.__init__(self, master, borderwidth=borderwidth, relief=relief)

        self.bind("<FocusIn>", lambda event:self.event_generate('<<DatePickerFocusIn>>'))
        self.bind("<FocusOut>", lambda event:self.event_generate('<<DatePickerFocusOut>>'))

        self._cal = get_calendar(locale, firstweekday)

        # custom ttk styles
        style = ttk.Style()
        style.layout('L.TButton', (
            [('Button.focus', {'children': [('Button.leftarrow', None)]})]
        ))
        style.layout('R.TButton', (
            [('Button.focus', {'children': [('Button.rightarrow', None)]})]
        ))

        self._font = tkFont.Font()

        self._header_var = StringVar()

        # header frame and its widgets
        hframe = ttk.Frame(self)
        lbtn = ttk.Button(hframe, style='L.TButton', command=self._on_press_left_button)
        lbtn.pack(side=LEFT)

        self._header = ttk.Label(hframe, width=15, anchor=CENTER, textvariable=self._header_var)
        self._header.pack(side=LEFT, padx=12)

        rbtn = ttk.Button(hframe, style='R.TButton', command=self._on_press_right_button)
        rbtn.pack(side=LEFT)
        hframe.grid(columnspan=7, pady=4)

        self._day_labels = {}

        days_of_the_week = self._cal.formatweekheader(3).split()

        for i, day_of_the_week in enumerate(days_of_the_week):
            Tkinter.Label(self, text=day_of_the_week, background='grey90').grid(row=1, column=i, sticky=N+E+W+S)

        for i in range(6):
            for j in range(7):
                self._day_labels[i,j] = label = Tkinter.Label(self, background = "white")

                label.grid(row=i+2, column=j, sticky=N+E+W+S)
                label.bind("<Enter>", lambda event: event.widget.configure(background=self._act_bg, foreground=self._act_fg))
                label.bind("<Leave>", lambda event: event.widget.configure(background="white"))

                label.bind("<1>", self._pressed)

        # adjust its columns width
        font = tkFont.Font()
        maxwidth = max(font.measure(text) for text in days_of_the_week)
        for i in range(7):
            self.grid_columnconfigure(i, minsize=maxwidth, weight=1)

        self._year = None
        self._month = None

        # insert dates in the currently empty calendar
        self._build_calendar(year, month)

    def _build_calendar(self, year, month):
        if not( self._year == year and self._month == month):
            self._year = year
            self._month = month

            # update header text (Month, YEAR)
            header = self._cal.formatmonthname(year, month, 0)
            self._header_var.set(header.title())

            # update calendar shown dates
            cal = self._cal.monthdayscalendar(year, month)

            for i in range(len(cal)):

                week = cal[i]
                fmt_week = [('%02d' % day) if day else '' for day in week]

                for j, day_number in enumerate(fmt_week):
                    self._day_labels[i,j]["text"] = day_number

            if len(cal) < 6:
                for j in range(7):
                    self._day_labels[5,j]["text"] = ""

        if self._selected_date is not None and self._selected_date.year == self._year and self._selected_date.month == self._month:
            self._show_selection()

    def _find_label_coordinates(self, date):
         first_weekday_of_the_month = (date.weekday() - date.day) % 7

         return divmod((first_weekday_of_the_month - self._cal.firstweekday)%7 + date.day, 7)

    def _show_selection(self):
        """Show a new selection."""

        i,j = self._find_label_coordinates(self._selected_date)

        label = self._day_labels[i,j]

        label.configure(background=self._sel_bg, foreground=self._sel_fg)

        label.unbind("<Enter>")
        label.unbind("<Leave>")

        self._selection_is_visible = True

    def _clear_selection(self):
        """Show a new selection."""
        i,j = self._find_label_coordinates(self._selected_date)

        label = self._day_labels[i,j]
        label.configure(background= "white", foreground="black")

        label.bind("<Enter>", lambda event: event.widget.configure(background=self._act_bg, foreground=self._act_fg))
        label.bind("<Leave>", lambda event: event.widget.configure(background="white"))

        self._selection_is_visible = False

    # Callback

    def _pressed(self, evt):
        """Clicked somewhere in the calendar."""

        text = evt.widget["text"]

        if text == "":
            return

        day_number = int(text)

        new_selected_date = datetime.datetime(self._year, self._month, day_number)
        if self._selected_date != new_selected_date:
            if self._selected_date is not None:
                self._clear_selection()

            self._selected_date = new_selected_date

            self._show_selection()

        if self._command:
            self._command(self._selected_date)

    def _on_press_left_button(self):
        self.prev_month()

        if self.on_click_month_button is not None:
            self.on_click_month_button()

    def _on_press_right_button(self):
        self.next_month()

        if self.on_click_month_button is not None:
            self.on_click_month_button()

    def select_prev_day(self):
        """Updated calendar to show the previous day."""
        if self._selected_date is None:
            self._selected_date = datetime.datetime(self._year, self._month, 1)
        else:
            self._clear_selection()
            self._selected_date = self._selected_date - self.timedelta(days=1)

        self._build_calendar(self._selected_date.year, self._selected_date.month) # reconstruct calendar

    def select_next_day(self):
        """Update calendar to show the next day."""

        if self._selected_date is None:
            self._selected_date = datetime.datetime(self._year, self._month, 1)
        else:
            self._clear_selection()
            self._selected_date = self._selected_date + self.timedelta(days=1)

        self._build_calendar(self._selected_date.year, self._selected_date.month) # reconstruct calendar

    def select_prev_week_day(self):
        """Updated calendar to show the previous week."""
        if self._selected_date is None:
            self._selected_date = datetime.datetime(self._year, self._month, 1)
        else:
            self._clear_selection()
            self._selected_date = self._selected_date - self.timedelta(days=7)

        self._build_calendar(self._selected_date.year, self._selected_date.month) # reconstruct calendar

    def select_next_week_day(self):
        """Update calendar to show the next week."""
        if self._selected_date is None:
            self._selected_date = datetime.datetime(self._year, self._month, 1)
        else:
            self._clear_selection()
            self._selected_date = self._selected_date + self.timedelta(days=7)

        self._build_calendar(self._selected_date.year, self._selected_date.month) # reconstruct calendar

    def select_current_date(self):
        """Update calendar to current date."""
        if self._selection_is_visible: self._clear_selection()

        self._selected_date = datetime.datetime.now()
        self._build_calendar(self._selected_date.year, self._selected_date.month)

    def prev_month(self):
        """Updated calendar to show the previous week."""
        if self._selection_is_visible: self._clear_selection()

        date = self.datetime(self._year, self._month, 1) - self.timedelta(days=1)
        self._build_calendar(date.year, date.month) # reconstuct calendar

    def next_month(self):
        """Update calendar to show the next month."""
        if self._selection_is_visible: self._clear_selection()

        date = self.datetime(self._year, self._month, 1) + \
            self.timedelta(days=calendar.monthrange(self._year, self._month)[1] + 1)

        self._build_calendar(date.year, date.month) # reconstuct calendar

    def prev_year(self):
        """Updated calendar to show the previous year."""

        if self._selection_is_visible: self._clear_selection()

        self._build_calendar(self._year-1, self._month) # reconstruct calendar

    def next_year(self):
        """Update calendar to show the next year."""

        if self._selection_is_visible: self._clear_selection()

        self._build_calendar(self._year+1, self._month) # reconstruct calendar

    def get_selection(self):
        """Return a datetime representing the current selected date."""
        return self._selected_date

    selection = get_selection

    def set_selection(self, date):
        """Set the selected date."""
        if self._selected_date is not None and self._selected_date != date:
            self._clear_selection()

        self._selected_date = date

        self._build_calendar(date.year, date.month) # reconstruct calendar

# see this URL for date format information:
#     https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior

class Datepicker(ttk.Entry):
    def __init__(self, master, entrywidth=None, entrystyle=None, datevar=None, dateformat="%Y-%m-%d", onselect=None, firstweekday=calendar.MONDAY, locale=None, activebackground='#b1dcfb', activeforeground='black', selectbackground='#003eff', selectforeground='white', borderwidth=1, relief="solid"):

        if datevar is not None:
            self.date_var = datevar
        else:
            self.date_var = Tkinter.StringVar()

        entry_config = {}
        if entrywidth is not None:
            entry_config["width"] = entrywidth

        if entrystyle is not None:
            entry_config["style"] = entrystyle

        ttk.Entry.__init__(self, master, textvariable=self.date_var, **entry_config)

        self.date_format = dateformat

        self._is_calendar_visible = False
        self._on_select_date_command = onselect

        self.calendar_frame = Calendar(self.winfo_toplevel(), firstweekday=firstweekday, locale=locale, activebackground=activebackground, activeforeground=activeforeground, selectbackground=selectbackground, selectforeground=selectforeground, command=self._on_selected_date, on_click_month_button=lambda: self.focus())

        self.bind_all("<1>", self._on_click, "+")

        self.bind("<FocusOut>", lambda event: self._on_entry_focus_out())
        self.bind("<Escape>", lambda event: self.hide_calendar())
        self.calendar_frame.bind("<<DatePickerFocusOut>>", lambda event: self._on_calendar_focus_out())

        # CTRL + PAGE UP: Move to the previous month.
        self.bind("<Control-Prior>", lambda event: self.calendar_frame.prev_month())

        # CTRL + PAGE DOWN: Move to the next month.
        self.bind("<Control-Next>", lambda event: self.calendar_frame.next_month())

        # CTRL + SHIFT + PAGE UP: Move to the previous year.
        self.bind("<Control-Shift-Prior>", lambda event: self.calendar_frame.prev_year())

        # CTRL + SHIFT + PAGE DOWN: Move to the next year.
        self.bind("<Control-Shift-Next>", lambda event: self.calendar_frame.next_year())

        # CTRL + LEFT: Move to the previous day.
        self.bind("<Control-Left>", lambda event: self.calendar_frame.select_prev_day())

        # CTRL + RIGHT: Move to the next day.
        self.bind("<Control-Right>", lambda event: self.calendar_frame.select_next_day())

        # CTRL + UP: Move to the previous week.
        self.bind("<Control-Up>", lambda event: self.calendar_frame.select_prev_week_day())

        # CTRL + DOWN: Move to the next week.
        self.bind("<Control-Down>", lambda event: self.calendar_frame.select_next_week_day())

        # CTRL + END: Close the datepicker and erase the date.
        self.bind("<Control-End>", lambda event: self.erase())

        # CTRL + HOME: Move to the current month.
        self.bind("<Control-Home>", lambda event: self.calendar_frame.select_current_date())

        # CTRL + SPACE: Show date on calendar
        self.bind("<Control-space>", lambda event: self.show_date_on_calendar())

        # CTRL + Return: Set to entry current selection
        self.bind("<Control-Return>", lambda event: self.set_date_from_calendar())

    def set_date_from_calendar(self):
        if self.is_calendar_visible:
            selected_date = self.calendar_frame.selection()

            if selected_date is not None:
                self.date_var.set(selected_date.strftime(self.date_format))

                if self._on_select_date_command is not None:
                    self._on_select_date_command(selected_date)

            self.hide_calendar()

    @property
    def current_text(self):
        return self.date_var.get()

    @current_text.setter
    def current_text(self, text):
        return self.date_var.set(text)

    @property
    def current_date(self):
        try:
            date = datetime.datetime.strptime(self.date_var.get(), self.date_format)
            return date
        except ValueError:
            return None

    @current_date.setter
    def current_date(self, date):
        self.date_var.set(date.strftime(self.date_format))

    @property
    def is_valid_date(self):
        if self.current_date is None:
            return False
        else:
            return True

    def show_date_on_calendar(self):
        date = self.current_date
        if date is not None:
            self.calendar_frame.set_selection(date)

        self.show_calendar()

    def show_calendar(self):
        if not self._is_calendar_visible:
            self.calendar_frame.place(in_=self, relx=0, rely=1)
            self.calendar_frame.lift()

        self._is_calendar_visible = True

    def hide_calendar(self):
        if self._is_calendar_visible:
            self.calendar_frame.place_forget()

        self._is_calendar_visible = False

    def erase(self):
        self.hide_calendar()
        self.date_var.set("")

    @property
    def is_calendar_visible(self):
        return self._is_calendar_visible

    def _on_entry_focus_out(self):
        if not str(self.focus_get()).startswith(str(self.calendar_frame)):
            self.hide_calendar()

    def _on_calendar_focus_out(self):
        if self.focus_get() != self:
            self.hide_calendar()

    def _on_selected_date(self, date):
        self.date_var.set(date.strftime(self.date_format))
        self.hide_calendar()

        if self._on_select_date_command is not None:
            self._on_select_date_command(date)

    def _on_click(self, event):
        str_widget = str(event.widget)

        if str_widget == str(self):
            if not self._is_calendar_visible:
                self.show_date_on_calendar()
        else:
            if not str_widget.startswith(str(self.calendar_frame)) and self._is_calendar_visible:
                self.hide_calendar()

if __name__ == "__main__":
    import sys

    try:
        from Tkinter import Tk, Frame, Label
    except ImportError:
        from tkinter import Tk, Frame, Label

    root = Tk()
    root.geometry("500x600")

    main =Frame(root, pady =15, padx=15)
    main.pack(expand=True, fill="both")

    Label(main, justify="left", text=__doc__).pack(anchor="w", pady=(0,15))

    Datepicker(main).pack(anchor="w")

    if 'win' not in sys.platform:
        style = ttk.Style()
        style.theme_use('clam')

    root.mainloop()


text:
class _EditorBitMaskImportOptions : public Object {

	OBJ_TYPE(_EditorBitMaskImportOptions, Object);
public:

	bool _set(const StringName& p_name, const Variant& p_value) {

		return false;
	}

	bool _get(const StringName& p_name, Variant &r_ret) const{

		return false;
	}

	void _get_property_list(List<PropertyInfo> *p_list) const{

	}

	static void _bind_methods() {

		ADD_SIGNAL(MethodInfo("changed"));
	}

	_EditorBitMaskImportOptions() {

	}

};

class EditorBitMaskImportDialog : public ConfirmationDialog {

	OBJ_TYPE(EditorBitMaskImportDialog, ConfirmationDialog);

	EditorBitMaskImportPlugin *plugin;

	LineEdit *import_path;
	LineEdit *save_path;
	EditorFileDialog *file_select;
	EditorDirDialog *save_select;
	ConfirmationDialog *error_dialog;
	PropertyEditor *option_editor;

public:

	void _choose_files(const Vector<String>& p_path) {

		String files;
		for (int i = 0; i<p_path.size(); i++) {

			if (i>0)
				files += ",";
			files += p_path[i];
		}

		import_path->set_text(files);

	}
	void _choose_save_dir(const String& p_path) {

		save_path->set_text(p_path);
	}

	void _browse() {

		file_select->popup_centered_ratio();
	}

	void _browse_target() {

		save_select->popup_centered_ratio();

	}

	void popup_import(const String& p_path) {

		popup_centered(Size2(400, 100)*EDSCALE);
		if (p_path != "") {

			Ref<ResourceImportMetadata> rimd = ResourceLoader::load_import_metadata(p_path);
			ERR_FAIL_COND(!rimd.is_valid());

			save_path->set_text(p_path.get_base_dir());

			String src = "";
			for (int i = 0; i<rimd->get_source_count(); i++) {
				if (i>0)
					src += ",";
				src += EditorImportPlugin::expand_source_path(rimd->get_source_path(i));
			}
			import_path->set_text(src);
		}
	}

	void _import() {

		Vector<String> bitmasks = import_path->get_text().split(",");

		if (bitmasks.size() == 0) {
			error_dialog->set_text(TTR("No bit masks to import!"));
			error_dialog->popup_centered(Size2(200, 100)*EDSCALE);
		}

		if (save_path->get_text().strip_edges() == "") {
			error_dialog->set_text(TTR("Target path is empty."));
			error_dialog->popup_centered_minsize();
			return;
		}

		if (!save_path->get_text().begins_with("res://")) {
			error_dialog->set_text(TTR("Target path must be a complete resource path."));
			error_dialog->popup_centered_minsize();
			return;
		}

		if (!DirAccess::exists(save_path->get_text())) {
			error_dialog->set_text(TTR("Target path must exist."));
			error_dialog->popup_centered_minsize();
			return;
		}

		for (int i = 0; i<bitmasks.size(); i++) {

			Ref<ResourceImportMetadata> imd = memnew(ResourceImportMetadata);

			imd->add_source(EditorImportPlugin::validate_source_path(bitmasks[i]));

			String dst = save_path->get_text();
			if (dst == "") {
				error_dialog->set_text(TTR("Save path is empty!"));
				error_dialog->popup_centered(Size2(200, 100)*EDSCALE);
			}

			dst = dst.plus_file(bitmasks[i].get_file().basename() + ".pbm");

			Error err = plugin->import(dst, imd);
		}

		hide();

	}

	void _notification(int p_what) {

	}

	static void _bind_methods() {

		ObjectTypeDB::bind_method("_choose_files", &EditorBitMaskImportDialog::_choose_files);
		ObjectTypeDB::bind_method("_choose_save_dir", &EditorBitMaskImportDialog::_choose_save_dir);
		ObjectTypeDB::bind_method("_import", &EditorBitMaskImportDialog::_import);
		ObjectTypeDB::bind_method("_browse", &EditorBitMaskImportDialog::_browse);
		ObjectTypeDB::bind_method("_browse_target", &EditorBitMaskImportDialog::_browse_target);
		//	ADD_SIGNAL( MethodInfo("imported",PropertyInfo(Variant::OBJECT,"scene")) );
	}

	EditorBitMaskImportDialog(EditorBitMaskImportPlugin *p_plugin) {

		plugin = p_plugin;

		set_title(TTR("Import BitMasks"));

		VBoxContainer *vbc = memnew(VBoxContainer);
		add_child(vbc);
		set_child_rect(vbc);

		HBoxContainer *hbc = memnew(HBoxContainer);
		vbc->add_margin_child(TTR("Source Texture(s):"), hbc);

		import_path = memnew(LineEdit);
		import_path->set_h_size_flags(SIZE_EXPAND_FILL);
		hbc->add_child(import_path);

		Button * import_choose = memnew(Button);
		import_choose->set_text(" .. ");
		hbc->add_child(import_choose);

		import_choose->connect("pressed", this, "_browse");

		hbc = memnew(HBoxContainer);
		vbc->add_margin_child(TTR("Target Path:"), hbc);

		save_path = memnew(LineEdit);
		save_path->set_h_size_flags(SIZE_EXPAND_FILL);
		hbc->add_child(save_path);

		Button * save_choose = memnew(Button);
		save_choose->set_text(" .. ");
		hbc->add_child(save_choose);

		save_choose->connect("pressed", this, "_browse_target");

		file_select = memnew(EditorFileDialog);
		file_select->set_access(EditorFileDialog::ACCESS_FILESYSTEM);
		add_child(file_select);
		file_select->set_mode(EditorFileDialog::MODE_OPEN_FILES);
		file_select->connect("files_selected", this, "_choose_files");

		List<String> extensions;
		ImageLoader::get_recognized_extensions(&extensions);
		file_select->clear_filters();
		for (int i = 0; i<extensions.size(); i++) {

			file_select->add_filter("*." + extensions[i] + " ; " + extensions[i].to_upper());
		}

		save_select = memnew(EditorDirDialog);
		add_child(save_select);

		//	save_select->set_mode(EditorFileDialog::MODE_OPEN_DIR);
		save_select->connect("dir_selected", this, "_choose_save_dir");

		get_ok()->connect("pressed", this, "_import");
		get_ok()->set_text(TTR("Import"));

		error_dialog = memnew(ConfirmationDialog);
		add_child(error_dialog);
		error_dialog->get_ok()->set_text(TTR("Accept"));
		//	error_dialog->get_cancel()->hide();

		set_hide_on_ok(false);
	}

	~EditorBitMaskImportDialog() {
	}

};

String EditorBitMaskImportPlugin::get_name() const {

	return "bitmask";
}
String EditorBitMaskImportPlugin::get_visible_name() const{

	return TTR("Bit Mask");
}
void EditorBitMaskImportPlugin::import_dialog(const String& p_from){

	dialog->popup_import(p_from);
}
Error EditorBitMaskImportPlugin::import(const String& p_path, const Ref<ResourceImportMetadata>& p_from){

	ERR_FAIL_COND_V(p_from->get_source_count() != 1, ERR_INVALID_PARAMETER);

	Ref<ResourceImportMetadata> from = p_from;

	String src_path = EditorImportPlugin::expand_source_path(from->get_source_path(0));
	Ref<ImageTexture> it = ResourceLoader::load(src_path);
	ERR_FAIL_COND_V(it.is_null(), ERR_CANT_OPEN);

	Ref<BitMap> target = memnew(BitMap);
	target->create_from_image_alpha(it.ptr()->get_data());

	from->set_source_md5(0, FileAccess::get_md5(src_path));
	from->set_editor(get_name());
	target->set_import_metadata(from);

	Error err = ResourceSaver::save(p_path, target);

	return err;

}

EditorBitMaskImportPlugin* EditorBitMaskImportPlugin::singleton = NULL;

void EditorBitMaskImportPlugin::import_from_drop(const Vector<String>& p_drop, const String &p_dest_path) {

	Vector<String> files;

	List<String> valid_extensions;
	ImageLoader::get_recognized_extensions(&valid_extensions);
	for(int i=0;i<p_drop.size();i++) {

		String extension=p_drop[i].extension().to_lower();

		for (List<String>::Element *E=valid_extensions.front();E;E=E->next()) {

			if (E->get()==extension) {
				files.push_back(p_drop[i]);
				break;
			}
		}
	}

	if (files.size()) {
		import_dialog();
		dialog->_choose_files(files);
		dialog->_choose_save_dir(p_dest_path);
	}
}

void EditorBitMaskImportPlugin::reimport_multiple_files(const Vector<String>& p_list) {

	if (p_list.size() == 0)
		return;

	Vector<String> sources;
	for (int i = 0; i<p_list.size(); i++) {
		int idx;
		EditorFileSystemDirectory *efsd = EditorFileSystem::get_singleton()->find_file(p_list[i], &idx);
		if (efsd) {
			for (int j = 0; j<efsd->get_source_count(idx); j++) {
				String file = expand_source_path(efsd->get_source_file(idx, j));
				if (sources.find(file) == -1) {
					sources.push_back(file);
				}

			}
		}
	}

	if (sources.size()) {

		dialog->popup_import(p_list[0]);
		dialog->_choose_files(sources);
		dialog->_choose_save_dir(p_list[0].get_base_dir());
	}
}

bool EditorBitMaskImportPlugin::can_reimport_multiple_files() const {

	return true;
}

EditorBitMaskImportPlugin::EditorBitMaskImportPlugin(EditorNode* p_editor) {

	singleton = this;
	dialog = memnew(EditorBitMaskImportDialog(this));
	p_editor->get_gui_base()->add_child(dialog);
}

EditorBitMaskExportPlugin::EditorBitMaskExportPlugin() {

}


text:
package com.cloud.api.response;

import com.cloud.api.ApiConstants;
import com.cloud.serializer.Param;

import com.google.gson.annotations.SerializedName;

public class LoginCmdResponse extends AuthenticationCmdResponse {

    @SerializedName(value = ApiConstants.USERNAME)
    @Param(description = "Username")
    private String username;

    @SerializedName(value = ApiConstants.USER_ID)
    @Param(description = "User ID")
    private String userId;

    @SerializedName(value = ApiConstants.DOMAIN_ID)
    @Param(description = "Domain ID that the user belongs to")
    private String domainId;

    @SerializedName(value = ApiConstants.DOMAIN_NAME)
    @Param(description = "Domain name that the user belongs to")
    private String domainName;

    @SerializedName(value = ApiConstants.TIMEOUT)
    @Param(description = "the time period before the session has expired")
    private Integer timeout;

    @SerializedName(value = ApiConstants.ACCOUNT)
    @Param(description = "the account name the user belongs to")
    private String account;

    @SerializedName(value = ApiConstants.FIRSTNAME)
    @Param(description = "first name of the user")
    private String firstName;

    @SerializedName(value = ApiConstants.LASTNAME)
    @Param(description = "last name of the user")
    private String lastName;

    @SerializedName(value = ApiConstants.TYPE)
    @Param(description = "the account type (admin, domain-admin, read-only-admin, user)")
    private String type;

    @SerializedName(value = ApiConstants.TIMEZONE)
    @Param(description = "user time zone")
    private String timeZone;

    @SerializedName(value = ApiConstants.REGISTERED)
    @Param(description = "Is user registered")
    private String registered;

    @SerializedName(value = ApiConstants.SESSIONKEY)
    @Param(description = "Session key that can be passed in subsequent Query command calls", isSensitive = true)
    private String sessionKey;

    public String getUsername() {
        return username;
    }

    public void setUsername(final String username) {
        this.username = username;
    }

    public String getUserId() {
        return userId;
    }

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

    public String getDomainId() {
        return domainId;
    }

    public void setDomainId(final String domainId) {
        this.domainId = domainId;
    }

    public Integer getTimeout() {
        return timeout;
    }

    public void setTimeout(final Integer timeout) {
        this.timeout = timeout;
    }

    public String getAccount() {
        return account;
    }

    public void setAccount(final String account) {
        this.account = account;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(final String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(final String lastName) {
        this.lastName = lastName;
    }

    public String getType() {
        return type;
    }

    public void setType(final String type) {
        this.type = type;
    }

    public String getTimeZone() {
        return timeZone;
    }

    public void setTimeZone(final String timeZone) {
        this.timeZone = timeZone;
    }

    public String getRegistered() {
        return registered;
    }

    public void setRegistered(final String registered) {
        this.registered = registered;
    }

    public String getSessionKey() {
        return sessionKey;
    }

    public void setSessionKey(final String sessionKey) {
        this.sessionKey = sessionKey;
    }

    public String getDomainName() {
        return domainName;
    }

    public void setDomainName(final String domainName) {
        this.domainName = domainName;
    }
}


text:
package render

import (
	"github.com/thinkofdeath/steven/render/gl"
	"github.com/thinkofdeath/steven/render/glsl"
)

type chunkShader struct {
	Position          gl.Attribute `gl:"aPosition"`
	TextureInfo       gl.Attribute `gl:"aTextureInfo"`
	TextureOffset     gl.Attribute `gl:"aTextureOffset"`
	Color             gl.Attribute `gl:"aColor"`
	Lighting          gl.Attribute `gl:"aLighting"`
	PerspectiveMatrix gl.Uniform   `gl:"perspectiveMatrix"`
	CameraMatrix      gl.Uniform   `gl:"cameraMatrix"`
	Offset            gl.Uniform   `gl:"offset"`
	Texture           gl.Uniform   `gl:"textures"`
	LightLevel        gl.Uniform   `gl:"lightLevel"`
	SkyOffset         gl.Uniform   `gl:"skyOffset"`
}

func init() {
	glsl.Register("chunk_vertex", `
in vec3 aPosition;
in vec4 aTextureInfo;
in vec3 aTextureOffset;
in vec3 aColor;
in vec2 aLighting;

uniform mat4 perspectiveMatrix;
uniform mat4 cameraMatrix;
uniform ivec3 offset;
uniform float lightLevel;
uniform float skyOffset;

out vec3 vColor;
out vec4 vTextureInfo;
out vec2 vTextureOffset;
out float vAtlas;
out vec3 vLighting;

#include get_light

void main() {
	vec3 pos = vec3(aPosition.x, -aPosition.y, aPosition.z);
	vec3 o = vec3(offset.x, -offset.y / 4096.0, offset.z);
	gl_Position = perspectiveMatrix * cameraMatrix * vec4(pos + o * 16.0, 1.0);

	vColor = aColor;
	vTextureInfo = aTextureInfo;
	vTextureOffset = aTextureOffset.xy / 16.0;
	vAtlas = aTextureOffset.z;

	vLighting = getLight(aLighting / (4000.0));
}
`)
	glsl.Register("chunk_frag", `
uniform sampler2DArray textures;

in vec3 vColor;
in vec4 vTextureInfo;
in vec2 vTextureOffset;
in float vAtlas;
in vec3 vLighting;

#ifndef alpha
out vec4 fragColor;
#else
out vec4 accum;
out float revealage;
#endif

#include lookup_texture

void main() {
	vec4 col = atlasTexture();
	#ifndef alpha
	if (col.a < 0.5) discard;
	#endif
	col *= vec4(vColor, 1.0);
	col.rgb *= vLighting;

	#ifndef alpha
	fragColor = col;
	#else
	float z = gl_FragCoord.z;
	float al = col.a;
	float weight = pow(al + 0.01f, 4.0f) +
			  	   max(0.01f, min(3000.0f, 0.3f / (0.00001f + pow(abs(z) / 800.0f, 4.0f))));
	accum = vec4(col.rgb * al * weight, al);
	revealage = weight * al;
	#endif
}
`)
}


text:
import paramiko, sys, threading

def banner():
	print "[***]  SSH Tunneling p31  [***]"

def reverse_forward_tunnel(server_port, remote_host, remote_port, transport):
	transport.request_port_forward('', server_port)
	while True:
		chan = transport.accept(10001)
		if chan is None:
			continue
		thr = threading.Thread(target=handler, args=(chan, remote_host, remote_port))
		thr.setDaemon(True)
		thr.start()

def handler(chan, host, port):
	sock = socket.socket()
	try:
		sock.connect((host, port))
	except Exception as e:
		verbose('Forwarding reqeust to %s:%d failed: %r' (host, port, e))
		return
	verbose('Connected! Tunnel open %r -> %r -> %r ' %(chan.origin_addr, chan.getpeername(), host, port))
	while True:
		r, w, x = select.select([sock, chan], [], [])
		if sock in r:
			data=sock.recv(1024)
			if len(data)== 0:
				break
			chan.send(data)
	chan.close()
	sock.close()
	verbose('Tunnel Closed from %r' % (chan.origin_addr, ))

def main():
	banner()
	options, server, remote = parse_options()
	password = None
	if options.readpass:
		password = getpass.getpass('Enter SSH password: ')
	client = paramiko.SSHClinet()
	clinet.load_system_host_keys()
	client.set_missing_host_key_policy(paramiko.WarningPolicy())
	verbose('Connecting to ssh host %s:%d ...' (server[0], server[1]))
	try:
		client.connect(server[0], server[1], username=options.user, key_filename=options.keyfile, look_for_keys=options.look_for_keys, password=protected)
	except Exception as e:
		print "[-] Failed to connect to %s:%d ..." (server[0], server[1], e)
		sys.exit(1)
	verbose('Now forwarding remote port %d to %s:%d ...' % (options.port, remote[0], remote[1]))
	try:
		reverse_forward_tunnel(options.port, remote[0], remote[1], client.get_transport())
	except KeyboardInterrupt:
		print "C-c: Port forwarding stopped."
		sys.exit(0)

if __name__ == '__main__':
	main()


text:
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RandomTestValues.UnitTests.ShouldExtensions;

namespace RandomTestValues.UnitTests.ValuesTests
{
    [TestClass]
    public class BoolShould
    {
        [TestMethod]
        public void StatisticallyDistributed5050()
        {
            const int total = 1000000;
            var trueCases = Enumerable.Repeat(0, total).Count(i => RandomValue.Bool());
            var ratio = trueCases / (double)total;

            ratio.ShouldBeInRange(0.49, 0.51);
        }
    }
}


text:
		<form data-ng-submit="signin()" class="signin form-horizontal" autocomplete="off">

Login

			<fieldset>

					Username
					<input type="email" id="email" name="email" class="form-control" data-ng-model="credentials.email" placeholder="Email">

					Password
					<input type="password" id="password" name="password" class="form-control" data-ng-model="credentials.password" placeholder="Password">

					<button type="submit" class="btn btn-primary">Sign in</button>  or
					Sign up

			</fieldset>
		</form>


text:
class OutputR2 : public Connector {
    public:
    OutputR2() : Connector() {}
    OutputR2(cmdComponent* l, cmdComponent* r) : Connector(l,r) {}
    bool execute(int in, int out);
};

#endif


text:
package io.subutai.core.environment.impl.workflow.destruction.steps;

import io.subutai.common.environment.Environment;
import io.subutai.common.peer.ContainerHost;
import io.subutai.common.peer.PeerException;
import io.subutai.core.environment.impl.entity.EnvironmentContainerImpl;

public class DestroyContainerStep
{
    private final ContainerHost containerHost;

    public DestroyContainerStep( final ContainerHost containerHost )
    {
        this.containerHost = containerHost;
    }

    public Environment execute() throws PeerException
    {
        return ( ( EnvironmentContainerImpl ) containerHost ).destroy( false );
    }
}


text:
/* eslint-disable @typescript-eslint/ban-types */
import type { PeerCertificate } from 'tls';
import { expectAssignable, expectError, expectNotType, expectType } from 'tsd';

import {
  LoggerLevel,
  MongoClient,
  MongoClientOptions,
  ReadPreference,
  ReadPreferenceMode
} from '../../../src';
import type { PropExists } from '../utility_types';

type MongoDBImport = typeof import('../../../src');

const mongodb: MongoDBImport = null as unknown as MongoDBImport;

expectNotType<Function>(mongodb);
expectType<PropExists<MongoDBImport, 'connect'>>(false);

// MongoClientOptions
const options: MongoClientOptions = {};
// .readPreference no longer accepts boolean
expectNotType<boolean>(options.readPreference);
// .pkFactory cannot be an empty object
expectNotType<{}>(options.pkFactory);
// .checkServerIdentity cannot be `true`
expectNotType<true>(options.checkServerIdentity);
// .sslCA cannot be string[]
expectNotType<string[]>(options.sslCA);
// .sslCRL cannot be string[]
expectNotType<string[]>(options.sslCRL);
// .sslCert cannot be a Buffer
expectNotType<Buffer>(options.sslCert);
// .sslKey cannot be a Buffer
expectNotType<Buffer>(options.sslKey);
// .sslPass cannot be a Buffer
expectNotType<Buffer>(options.sslPass);

// Legacy option kept
expectType<PropExists<MongoClientOptions, 'w'>>(true);
// Removed options
expectType<PropExists<MongoClientOptions, 'wtimeout'>>(false);
expectType<PropExists<MongoClientOptions, 'j'>>(false);
expectType<PropExists<MongoClientOptions, 'bufferMaxEntries'>>(false);
expectType<PropExists<MongoClientOptions, 'poolSize'>>(false);
expectType<PropExists<MongoClientOptions, 'socketOptions'>>(false);
expectType<PropExists<MongoClientOptions, 'reconnectTries'>>(false);
expectType<PropExists<MongoClientOptions, 'reconnectInterval'>>(false);
expectType<PropExists<MongoClientOptions, 'compression'>>(false);
expectType<PropExists<MongoClientOptions, 'poolSize'>>(false);
expectType<PropExists<MongoClientOptions, 'minSize'>>(false);
expectType<PropExists<MongoClientOptions, 'socketOptions'>>(false);
expectType<PropExists<MongoClientOptions, 'reconnectTries'>>(false);
expectType<PropExists<MongoClientOptions, 'reconnectInterval'>>(false);
expectType<PropExists<MongoClientOptions, 'useNewUrlParser'>>(false);
expectType<PropExists<MongoClientOptions, 'useUnifiedTopology'>>(false);

expectType<string | undefined>(options.authSource);
expectType<LoggerLevel | undefined>(options.loggerLevel);
expectType<ReadPreferenceMode | ReadPreference | undefined>(options.readPreference);
expectType<boolean | undefined>(options.promoteValues);
expectType<number | undefined>(options.family);
expectType<boolean | undefined>(options.ssl);
expectType<boolean | undefined>(options.sslValidate);
expectAssignable<((host: string, cert: PeerCertificate) => Error | undefined) | undefined>(
  options.checkServerIdentity
);

// compression options have simpler specification:
// old way: {compression: { compressors: ['zlib', 'snappy'] }}
expectType<PropExists<MongoClientOptions, 'compression'>>(false);
expectType<('none' | 'snappy' | 'zlib' | 'zstd')[] | string | undefined>(options.compressors);

// Removed cursor API
const cursor = new MongoClient('').db().aggregate();
expectType<PropExists<typeof cursor, 'maxScan'>>(false);
expectType<PropExists<typeof cursor, 'setCursorOption'>>(false);
expectType<PropExists<typeof cursor, 'setReadPreference'>>(false);
expectType<PropExists<typeof cursor, 'snapshot'>>(false);

// Cursor returning functions don't take a callback
const db = new MongoClient('').db();
const collection = db.collection('');
// collection.find
// eslint-disable-next-line @typescript-eslint/no-unused-vars
expectError(collection.find({}, {}, (e: unknown, c: unknown) => undefined));
// collection.aggregate
// eslint-disable-next-line @typescript-eslint/no-unused-vars
expectError(collection.aggregate({}, {}, (e: unknown, c: unknown) => undefined));
// db.aggregate
// eslint-disable-next-line @typescript-eslint/no-unused-vars
expectError(db.aggregate({}, {}, (e: unknown, c: unknown) => undefined));

// insertOne and insertMany doesn't return:
const insertOneRes = await collection.insertOne({});
const insertManyRes = await collection.insertOne({});
expectType<PropExists<typeof insertManyRes, 'ops'>>(false);
expectType<PropExists<typeof insertManyRes, 'result'>>(false);
expectType<PropExists<typeof insertOneRes, 'ops'>>(false);
expectType<PropExists<typeof insertOneRes, 'result'>>(false);


text:
package de.iani.cubequest.commands;

import de.iani.cubequest.CubeQuest;
import de.iani.cubequest.quests.CommandQuest;
import de.iani.cubequest.quests.GotoQuest;
import de.iani.cubequest.quests.InteractorQuest;
import de.iani.cubequest.quests.Quest;
import de.iani.cubequest.util.ChatAndTextUtil;
import de.iani.cubesideutils.commands.ArgsParser;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;

public class SetOverwrittenNameForSthCommand extends AssistedSubCommand {

    public enum SpecificSth {

        INTERACTOR("InteractorName", InteractorQuest.class, "setInteractorName"),
        LOCATION("LocationName", GotoQuest.class, "setLocationName"),
        COMMAND("CommandName", CommandQuest.class, "setCommandName");

        public final String propertyName;
        public final String setCommandPath;
        public final String fullSetCommand;
        public final String resetCommandPath;
        public final String fullResetCommmand;
        public final Class<? extends Quest> questClass;
        public final Method setterMethod;

        private SpecificSth(String propertyName, Class<? extends Quest> questClass, String setterMethodName) {
            this.propertyName = propertyName;
            this.setCommandPath = "setQuest" + propertyName;
            this.fullSetCommand = "quest " + this.setCommandPath;
            this.resetCommandPath = "resetQuest" + propertyName;
            this.fullResetCommmand = "quest " + this.resetCommandPath;
            this.questClass = questClass;
            try {
                this.setterMethod = questClass.getMethod(setterMethodName, String.class);
            } catch (NoSuchMethodException | SecurityException e) {
                throw new AssertionError(e);
            }
        }
    }

    private SpecificSth sth;

    private static ParameterDefiner[] getParameterDefiners(SpecificSth sth, boolean set) {
        ParameterDefiner[] result = new ParameterDefiner[set ? 2 : 1];
        result[0] = new ParameterDefiner(ParameterType.CURRENTLY_EDITED_QUEST, "Quest",
                parsed -> (!sth.questClass.isInstance(parsed[1]) ? "Nur " + sth.questClass.getSimpleName() + "s haben diese Eigenschaft!" : null));
        if (set) {
            result[1] = new ParameterDefiner(ParameterType.STRING, "Name", parsed -> null);
        }

        return result;
    }

    private static Function<Object[], String> getPropertySetter(SpecificSth sth, boolean set) {
        return parsed -> {
            try {
                sth.setterMethod.invoke(parsed[1], set ? ChatAndTextUtil.convertColors((String) parsed[2]) : null);
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                throw new RuntimeException(e);
            }
            return null;
        };
    }

    private static Function<Object[], String> getSuccessMessageProvider(SpecificSth sth, boolean set) {
        return parsed -> {
            return sth.propertyName + " für Quest " + ((Quest) parsed[1]).getId()
                    + (set ? " auf " + ChatAndTextUtil.convertColors((String) parsed[2]) + " " : " zurück") + "gesetzt.";
        };
    }

    public SetOverwrittenNameForSthCommand(SpecificSth sth, boolean set) {
        super("quest " + sth.setCommandPath, AssistedSubCommand.ACCEPTING_SENDER_CONSTRAINT, getParameterDefiners(sth, set),
                getPropertySetter(sth, set), getSuccessMessageProvider(sth, set));
        this.sth = sth;
    }

    @Override
    public String getRequiredPermission() {
        return CubeQuest.EDIT_QUESTS_PERMISSION;
    }

    @Override
    public List<String> onTabComplete(CommandSender sender, Command command, String alias, ArgsParser args) {
        return Collections.emptyList();
    }

    @Override
    public String getUsage() {
        return "<" + this.sth.propertyName + ">";
    }

}


text:
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview Mixin for cr-radio-button-like elements.
 */

// clang-format off
import {dedupingMixin, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';

import {assert, assertNotReached} from '../../js/assert_ts.js';

interface PaperRippleElement {
  clear(): void;
  showAndHoldDown(): void;
}

type Constructor<T> = new (...args: any[]) => T;

export const CrRadioButtonMixin = dedupingMixin(
    <T extends Constructor<PolymerElement>>(superClass: T): T&
    Constructor<CrRadioButtonMixinInterface> => {
      class CrRadioButtonMixin extends superClass implements
          CrRadioButtonMixinInterface {
        static get properties() {
          return {
            checked: {
              type: Boolean,
              value: false,
              reflectToAttribute: true,
            },

            disabled: {
              type: Boolean,
              value: false,
              reflectToAttribute: true,
              notify: true,
            },

            /**
             * Whether the radio button should be focusable or not. Toggling
             * this property sets the corresponding tabindex of the button
             * itself as well as any links in the button description.
             */
            focusable: {
              type: Boolean,
              value: false,
              observer: 'onFocusableChanged_',
            },

            label: {
              type: String,
              value: '',  // Allows hidden$= binding to run without being set.
            },

            name: {
              type: String,
              notify: true,
              reflectToAttribute: true,
            },

            /**
             * Holds the tabIndex for the radio button.
             */
            buttonTabIndex_: {
              type: Number,
              computed: 'getTabIndex_(focusable)',
            },
          };
        }

        checked: boolean;
        disabled: boolean;
        focusable: boolean;
        label: string;
        name: string;
        private buttonTabIndex_: number;

        override connectedCallback() {
          super.connectedCallback();
          this.addEventListener('blur', this.hideRipple_.bind(this));
          this.addEventListener('focus', this.onFocus_.bind(this));
          this.addEventListener('up', this.hideRipple_.bind(this));
        }

        override focus() {
          const button = this.shadowRoot!.querySelector<HTMLElement>('#button');
          assert(button);
          button.focus();
        }

        getPaperRipple(): PaperRippleElement {
          assertNotReached();
        }

        private onFocus_() {
          this.getPaperRipple().showAndHoldDown();
        }

        private hideRipple_() {
          this.getPaperRipple().clear();
        }

        private onFocusableChanged_() {
          const links = this.querySelectorAll('a');
          links.forEach((link) => {
            // Remove the tab stop on any links when the row is unchecked.
            // Since the row is not tabbable, any links within the row
            // should not be either.
            link.tabIndex = this.checked ? 0 : -1;
          });
        }

        private getAriaChecked_(): string {
          return this.checked ? 'true' : 'false';
        }

        private getAriaDisabled_(): string {
          return this.disabled ? 'true' : 'false';
        }

        private getTabIndex_(): number {
          return this.focusable ? 0 : -1;
        }

        /**
         * When shift-tab is pressed, first bring the focus to the host
         * element. This accomplishes 2 things:
         * 1) Host doesn't get focused when the browser moves the focus
         *    backward.
         * 2) focus now escaped the shadow-dom of this element, so that
         *    it'll correctly obey non-zero tabindex ordering of the
         *    containing document.
         */
        private onInputKeydown_(e: KeyboardEvent) {
          if (e.shiftKey && e.key === 'Tab') {
            this.focus();
          }
        }
      }

      return CrRadioButtonMixin;
    });

export interface CrRadioButtonMixinInterface {
  checked: boolean;
  disabled: boolean;
  focusable: boolean;
  label: string;
  name: string;

  getPaperRipple(): PaperRippleElement;
}


text:
import './pretty_code.html';
import { Template } from 'meteor/templating';
import '../../../../node_modules/prismjs/themes/prism.css';
var Prism = require('prismjs');

/**
 * Template Helpers
 */
Template.PrettyCode.helpers({
  getLanguage(){
    return this.language || "javascript"
  }
});

/**
 * Template Event Handlers
 */
Template.PrettyCode.events({});

/**
 * Template Created
 */
Template.PrettyCode.onCreated(() => {

});

/**
 * Template Rendered
 */
Template.PrettyCode.onRendered(() => {
  let instance = Template.instance();

  instance.autorun(function () {
    let data = Template.currentData(),
        language = data.language || 'javascript';
    if (data.value) {
      instance.$('.code').html(Prism.highlight(data.value, Prism.languages[language]));
    }
  });
});

/**
 * Template Destroyed
 */
Template.PrettyCode.onDestroyed(() => {

});


text:
using System;
using System.Collections.Generic;

using Lidgren.Network;

using Agrotera.Core;
using Agrotera.Core.Entities;
using Agrotera.Setting;
using Agrotera.ShipLink;
using Agrotera.ShipLink.Messages.Join;

using SimulationServer.Peers;

namespace SimulationServer
{
	internal partial class Server : Host, PeerHandler
	{
		public Campaign TheCampaign = null;
		public Scenario TheScenario = null;

		public List<Ship> PlayerConnectedShips = new List<Ship>();

		protected MessageProcessor NewClientProcessor = new MessageProcessor();
		public Server()
		{
			NewClientProcessor.RegisterProcessor(typeof(CreateShipMessage), ProcessCreateShip);
			NewClientProcessor.RegisterProcessor(typeof(RejoinShipMessage), ProcessRejoinShip);
		}

		public void Startup(ScenarioConfig config)
		{
			DefaultPeerHandler = this;

			TheCampaign = Campaign.Get(config.CampaignName);
			TheScenario = Scenario.FindScenario(config.ScenarioName);

			TheScenario.Map = new Agrotera.Core.Areas.Zone();

			TheCampaign.Load();
			TheScenario.Load(TheCampaign);

			if(TheCampaign.ScienceDB.AutoGenerateDBEntriesForEntities)
				GenerateEntityScienceDBRecords();

			if(TheCampaign.ScienceDB.AutoGenerateDBEntriesFactions)
				GenerateFactionScienceDBRecords();

			Tick.UpdateGlobalClock();

			Listen(config.Port);
		}

		public override void Shutdown()
		{
			base.Shutdown();
		}

		public void Update()
		{

		}

		public Peer AddPeer(NetIncomingMessage msg)
		{
			ShipPeer sp = new ShipPeer();

			sp.ShipID = msg.ReadInt32();
			sp.authenticationToken = msg.ReadString();

			return sp;
		}

		public void DisconnectPeer(string reason, Peer peer)
		{
		}

		public void PeerDisconnected(string reason, Peer peer)
		{
		}

		public void PeerReceiveData(InboundNetworkMessage msg, Peer peer)
		{
			if (!NewClientProcessor.CallProcessor(peer,msg))
			{
				ShipPeer shipPeer = peer as ShipPeer;
				if(shipPeer == null || shipPeer.LinkedShip == null || shipPeer.ShipController == null || shipPeer.ShipController.NetworkPeer != peer)
					return;

				shipPeer.ShipController.ProcessMessage(msg);
			}
		}

		protected void GenerateFactionScienceDBRecords()
		{
			foreach(var faction in TheCampaign.Factions.Values)
			{
				if(faction.ScienceDBEntry == UInt32.MaxValue)
					continue;

				ScienceDatabaseItem item = TheCampaign.ScienceDB.New("Faction", faction.Name);
				item.Generalization = ScienceDatabaseItem.ItemGeneralizations.Data;
				item.LongDescription = faction.Description;
				foreach(string enimy in faction.Enimies)
					item.AddValue(enimy, "Hostile");

				item.Known = true;
				faction.ScienceDBEntry = item.ID;
			}
		}

		protected void GenerateEntityScienceDBRecords()
		{
			foreach(var entity in TheCampaign.Templates)
			{
				if(entity.ScienceDBID == UInt64.MaxValue)
				{
					ScienceDatabaseItem item = TheCampaign.ScienceDB.New(entity.EntityClass.ToString(), entity.Name);
					item.Generalization = ScienceDatabaseItem.ItemGeneralizations.Data;
					entity.SetScienceItemFields(item);
					item.Known = true;
					entity.ScienceDBID = item.ID;
				}
			}
		}
	}
}


text:
/**
* @class Revisions
*/
zrt.Revisions = function() {
	var oDataTable;
	var dataObj;
	var DEFAULT_COUNT = 10;
	var filterObj = {count: DEFAULT_COUNT};

	function getColDefs() {
		var innerHTMLFormatter = function(el, oRecord, oColumn, oData) {
			el.innerHTML = oData;
		};

		var changelogHTMLFormatter = function(el, oRecord, oColumn, oData) {
			el.innerHTML = '
' + oData + '
';
		};

		var viewdetailFormatter = function(el, oRecord, oColumn, oData) {
			var id = "viewdetail-btn-" + oRecord._oData.rev;
			el.innerHTML = "<button class='viewdetail-btn' id='" + id + "'>View</button>";
		};

		var changerevFormatter = function(el, oRecord, oColumn, oData) {
                        var id = "changerev-btn-" + oRecord._oData.rev;
			if(zrt.config["REV"] != oRecord._oData.rev)
                        	el.innerHTML = "<button class='changerev-btn' id='" + id + "'>Revert to ...</button>";
                };

		var colDefs = [
			{key:"rev", label:"REVISION", sortable:true},
			{key:"ts", label:"TIME", sortable:true, formatter:innerHTMLFormatter},
			{key:"author", label:"AUTHOR", sortable:true},
			{key:"ref", label:"REFERENCE", sortable:true},
			{key:"changelog", label:"CHANGELOG", formatter:changelogHTMLFormatter},
			{key:"viewdetail", label:"", formatter:viewdetailFormatter},
			{key:"changerev", label:"", formatter:changerevFormatter}
		];

		return colDefs;
	}

	function getFormattedData(o) {
		var ret = [];
		var rev = "rev";
		var cl = "changelog";

		for(var i in o) {
			ret.push({
				"rev":o[i][rev],
				"ts":Tools.getFormattedTime(o[i][cl].time),
				"author":o[i][cl].author,
				"ref":o[i][cl].reference,
				"changelog":formatChangelogDetail(o[i][cl].message)
			});
		}

		return ret;
	}

	function createTable() {
		var oColDefs = getColDefs();

		var oDataSource = new YAHOO.util.DataSource(getFormattedData(dataObj.output));
		oDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;

		var oConfigs = {
			MSG_EMPTY: "No revisions found"
        	};

		oDataTable = new YAHOO.widget.DataTable("revisions-table", oColDefs, oDataSource, oConfigs);

		oDataTable.setColumnWidth(oDataTable.getColumn(4), 500);
		oDataTable.render();
	}

	function initChangelogDetail() {
		$("#changelog-detail").dialog({
			modal:true,
			resizable:true,
			autoOpen:false,
			//width:600,
			//height:400,
			title:"Changelog Details",
			buttons:{
                        	"Close": function() { $(this).dialog("close"); }
                	}
		});
	}

	function initRevisionTableButtons() {
		$(".yui-dt-col-viewdetail .viewdetail-btn").unbind('click').bind('click', function(e) {
			var id = e.target.id;
			var tmp = id.split("-");
			var rev = tmp[tmp.length - 1];
			showChangelogDetail(rev);
		});

		$(".yui-dt-col-changerev .changerev-btn").unbind('click').bind('click', function(e) {
			var id = e.target.id;
			var tmp = id.split("-");
			var rev = tmp[tmp.length - 1];

			Controller.compareRevisions(zrt.config["REV"], rev, function(o) {
				var result = formatChangelogDetail(o.output);

                        	var cbSuccess = function() {
                                	console.log("Change revision succeeded.");
                                	filterRevisions();
                        	}

                        	var cbError = function() {
                                	console.log("Change revision failed.");
                        	}

                        	var dlg = new zrt.ConfirmDialog(function() {
                                	Controller.changerev(rev, cbSuccess, cbError);
                        	});
                        	dlg.show("Please confirm to revert to revision " + rev + ":

" + (result == "" ? "No changes!" : result));
			});
		});
	}

	function initFilterButtons() {
		$("#filter-key-text, #filter-user-text, #filter-start-text, #filter-end-text, #filter-count-text").unbind('keypress').bind('keypress', function(e) {
			var code = (e.keyCode ? e.keyCode : e.which);
			if(code == 13) {
				processFilter();
			}
		});

		$("#filter-btn").unbind('click').bind('click', function(e) {
			processFilter();
		});

		$("#filter-reset-btn").unbind('click').bind('click', function(e) {
			initFilterUI();
			filterObj = getFilterData();
			if(filterObj == false)
				filterObj = {count: DEFAULT_COUNT};
			filterRevisions();
		});
	}

	function initFilterUI() {
		$("#filter-key-text").val("");
		$("#filter-user-text").val("");
		$("#filter-start-text").val("");
		$("#filter-end-text").val("");
		$("#filter-count-text").val(DEFAULT_COUNT);
	}

	function processFilter() {
		filterObj = getFilterData();
		if(filterObj == false) {
			var dlg = new zrt.ErrorDialog(function() {});
			dlg.show("Invalid input.
Please double check your filter input boxes.");
		}
		else {
			filterRevisions();
		}
	}

	function getFilterData() {
		var ret = new Object();
		var count = $("#filter-count-text").val();
		var key = $("#filter-key-text").val();
		var user = $("#filter-user-text").val();
		var start = $("#filter-start-text").val();
		var end = $("#filter-end-text").val();

		if(count != null && count != "") {
			if(String(count).toLowerCase() == "all")
				ret.count = "all";
			else if(isNaN(Number(count)) == false && Number(count) > 0)
				ret.count = Number(count);
			else
				return false;
		}

		if(key != null && key != "")
                        ret.key = String(key).split(",");

		if(user != null && user != "")
                        ret.user = user;

		if(start != null && start != "") {
			var startTime = Tools.convertHumanReadableTimeToEpoch(start);
			if(startTime == false)
				return false;
			else
                        	ret.start = startTime;
		}

		if(end != null && end != "") {
			var endTime = Tools.convertHumanReadableTimeToEpoch(end);
			if(endTime == false)
				return false;
			else
				ret.end = endTime;
		}
		return ret;
	}

	function formatChangelogDetail(o) {
		var ret = '';

		var printValue = function(data) {
			if (Object.prototype.toString.call(data) === '[object Array]') {
				var r = "";
				for(var i = 0; i < data.length; i++) {
					r += "[" + i + "] " + data[i];
					r += "
";
				}
				return r;
			}
			else if (!data) {
				return data;
			}
			else {
				return data;
			}
		}

		var print = function(data, isUpdated) {
			var r = '';

			for(key in data) {
				if (r != '')
					r += '
';

				if (key == "REVERT") {
					r += '
';
					r += printValue(data[key]);
					r += '
';
					continue;
				}

				r += '
';
				r += 'Key: ' + key;
				r += '
';
				if (isUpdated == true) {
					r += '
';
					r += 'Change: ';
					r += '

' + printValue(data[key].oldValue) + '
';
					r += '
=>

' + printValue(data[key].newValue) + '

'
					r += '
';
				}
				else {
					r += '
';
                                	r += 'Value: ';
					if (Object.prototype.toString.call(data[key]) === '[object Array]')
						r += '

' + printValue(data[key]) + '

';
					else
						r += printValue(data[key]);
                                	r += '
';
				}
			}

			return r;
		}

		if(o.reverted) {
			ret += '
';
			ret += '
[ Reverted ]
';
			ret += print(o.reverted, false);
			ret += '

';
		}

		if(o.added) {
			ret += '
';
			ret += '
[ Added ]
';
			ret += print(o.added, false);
			ret += '

';
		}

		if(o.updated) {
			ret += '
';
            		ret += '
[ Updated ]
';
            		ret += print(o.updated, true);
			ret += '

';
        	}

		if(o.deleted) {
			ret += '
';
            		ret += '
[ Deleted ]
';
            		ret += print(o.deleted, false);
			ret += '

';
        	}

		return ret;
	}

	function showChangelogDetail(rev) {
		$el = $("#changelog-detail");
		$el.dialog("option", "title", "Revision " + rev);

		Controller.getRevision(rev, function(o) {
			var data = o.output;

			var ret = "";
			for(var key in data) {
				var value = data[key];
				var type = typeof value;
				if (value == null) {
					type = "null";
				}
				if (type == "object") {
					type = "array";
				}

				ret += "" + key + " [type: " + type + "]";
				switch(type) {
					case "boolean":
						value = String(value) + "
";
						break;
					case "array":
						ret += " (" + value.length + (value.length > 1 ? " entries)":" entry)");
						var temp = "";
						for(var i = 0; i < value.length; i++) {
							temp += value[i] + "
";
						}
						value = temp;
						break;
					case "null":
						value = String(value) + "
";
						break;
					default:
						value += "
";
						break;
				}
				ret += "
" + value + "
";
			}

                	$el.html(ret);
			$el.dialog('open');
        	});

		var w = Math.max($el.width(), 500);
		w = Math.min(w, $(window).width() - 100);
		var h = Math.max($el.height(), 500);
		h = Math.min(h, $(window).height() - 100);
		$el.dialog('option', 'width', w);
		$el.dialog('option', 'height', h);
	}

	function filterRevisions() {
                Controller.getChangelog(filterObj, function(o) {
                        if(o["liverev"]) {
                                if(o["liverev"] > 0) {
                                        zrt.config["REV"] = o["liverev"];
                                        $("#liveRevText").html(zrt.config["REV"]);
                                }
                        }
                        dataObj = o;

                        createTable();
                        initRevisionTableButtons();
                });
	}

	function init() {
		initChangelogDetail();
		//initFilterUI();
		initFilterButtons();

		filterObj = getFilterData();
		if(filterObj == false)
			filterObj = {count: DEFAULT_COUNT};

		filterRevisions();
        }

	return {
		init: init
        };
}


text:
<?php
namespace compress;

use php\io\File;
use php\io\Stream;

/**
 * @package compress
 * @packages compress
 */
class TarArchiveInput extends ArchiveInput
{
    /**
     * TarArchiveOutput constructor.
     * @param Stream|string|File $output
     * @param int $blockSize
     * @param string|null $encoding
     */
    public function __construct($output, int $blockSize = 512, string $encoding = null)
    {
    }

    /**
     * @return TarArchiveEntry
     */
    public function nextEntry()
    {
    }
}


text:
/*-
 * Copyright (c) 2010 David Malone <dwmalone@FreeBSD.org>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#ifndef TOEPLITZ_HH_
#define TOEPLITZ_HH_

#include <vector>

using rss_key_type = std::vector<uint8_t>;

// Mellanox Linux's driver key
static const rss_key_type default_rsskey_40bytes = {
    0xd1, 0x81, 0xc6, 0x2c, 0xf7, 0xf4, 0xdb, 0x5b,
    0x19, 0x83, 0xa2, 0xfc, 0x94, 0x3e, 0x1a, 0xdb,
    0xd9, 0x38, 0x9e, 0x6b, 0xd1, 0x03, 0x9c, 0x2c,
    0xa7, 0x44, 0x99, 0xad, 0x59, 0x3d, 0x56, 0xd9,
    0xf3, 0x25, 0x3c, 0x06, 0x2a, 0xdc, 0x1f, 0xfc
};

// Intel's i40e PMD default RSS key
static const rss_key_type default_rsskey_52bytes = {
    0x44, 0x39, 0x79, 0x6b, 0xb5, 0x4c, 0x50, 0x23,
    0xb6, 0x75, 0xea, 0x5b, 0x12, 0x4f, 0x9f, 0x30,
    0xb8, 0xa2, 0xc0, 0x3d, 0xdf, 0xdc, 0x4d, 0x02,
    0xa0, 0x8c, 0x9b, 0x33, 0x4a, 0xf6, 0x4a, 0x4c,
    0x05, 0xc6, 0xfa, 0x34, 0x39, 0x58, 0xd8, 0x55,
    0x7d, 0x99, 0x58, 0x3a, 0xe1, 0x38, 0xc9, 0x2e,
    0x81, 0x15, 0x03, 0x66
};

template<typename T>
static inline uint32_t
toeplitz_hash(const rss_key_type& key, const T& data)
{
	uint32_t hash = 0, v;
	u_int i, b;

	/* XXXRW: Perhaps an assertion about key length vs. data length? */

	v = (key[0]<<24) + (key[1]<<16) + (key[2] <<8) + key[3];
	for (i = 0; i < data.size(); i++) {
		for (b = 0; b < 8; b++) {
			if (data[i] & (1<<(7-b)))
				hash ^= v;
			v <<= 1;
			if ((i + 4) < key.size() &&
			    (key[i+4] & (1<<(7-b))))
				v |= 1;
		}
	}
	return (hash);
}
#endif


text:
declare namespace Mongo {
  interface Collection<T> {
    before: {
      find(hook: (
          userId: string,
          selector: Mongo.Selector,
          options: CollectionHooks.ModifierOptions
        ) => void
      ): void;
      findOne(hook: (
          userId: string,
          selector: Mongo.Selector,
          options: CollectionHooks.ModifierOptions
        ) => void
      ): void;
      insert(hook: (
          userId: string,
          doc: T
        ) => void
      ): void;
      remove(hook: (
          userId: string,
          doc: T
        ) => void
      ): void;
      update(hook: (
          userId: string,
          doc: T,
          fieldNames: string[],
          modifier: Mongo.Modifier,
          options: CollectionHooks.ModifierOptions
        ) => void
      ): void;
      upsert(hook: (
          userId: string,
          doc: T,
          selector: Mongo.Selector,
          modifier: Mongo.Modifier,
          options: CollectionHooks.ModifierOptions
        ) => void
      ): void;
    };
    after: {
      find(hook: (
          userId: string,
          selector: Mongo.Selector,
          options: CollectionHooks.ModifierOptions,
          cursor: Mongo.Cursor<T>
        ) => void
      ): void;
      findOne(hook: (
          userId: string,
          selector: Mongo.Selector,
          options: CollectionHooks.ModifierOptions,
          doc: T
        ) => void
      ): void;
      insert(hook: (
          userId: string,
          doc: T
        ) => void
      ): void;
      remove(hook: (
          userId: string,
          doc: T
        ) => void
      ): void;
      update(
        hook: (
          userId: string,
          doc: T,
          fieldNames: string[],
          modifier: Mongo.Modifier,
          options: CollectionHooks.ModifierOptions
        ) => void,
        options?: CollectionHooks.HookOptionValue
      ): void;
      upsert(
        hook: (
          userId: string,
          doc: T,
          selector: Mongo.Selector,
          modifier: Mongo.Modifier,
          options: CollectionHooks.ModifierOptions
        ) => void
      ): void;
    };
    direct: {
      find(selector?: Mongo.Selector | Mongo.ObjectID | string, options?: {
        sort?: Mongo.SortSpecifier;
        skip?: number;
        limit?: number;
        fields?: Mongo.FieldSpecifier;
        reactive?: boolean;
        transform?(doc: any): void;
      }): Mongo.Cursor<T>;
      findOne(selector?: Mongo.Selector | Mongo.ObjectID | string, options?: {
        sort?: Mongo.SortSpecifier;
        skip?: number;
        fields?: Mongo.FieldSpecifier;
        reactive?: boolean;
        transform?(doc: any): void;
      }): T;
      insert(
        doc: T,
        callback?: () => void
      ): string;
      remove(
        selector: Mongo.Selector | Mongo.ObjectID | string, callback?: () => void
      ): number;
      update(
        selector: Mongo.Selector | Mongo.ObjectID | string, modifier: Mongo.Modifier, options?: {
          multi?: boolean;
          upsert?: boolean;
        },
        callback?: () => void
      ): number;
      upsert(
        selector: Mongo.Selector | Mongo.ObjectID | string, modifier: Mongo.Modifier, options?: {
          multi?: boolean;
        },
        callback?: () => void
      ): { numberAffected?: number; insertedId?: string; };
    };
    hookOptions: CollectionHooks.GlobalHookOptions;
  }
}

declare namespace CollectionHooks {
  interface ModifierOptions {
    multi?: boolean;
    upsert?: boolean;
  }

  interface HookOptionValue {
    fetchPrevious?: boolean;
  }

  interface LocalHookOptions {
    all?: HookOptionValue;
    find?: HookOptionValue;
    findOne?: HookOptionValue;
    insert?: HookOptionValue;
    remove?: HookOptionValue;
    update?: HookOptionValue;
    upsert?: HookOptionValue;
  }

  interface GlobalHookOptions {
    before?: LocalHookOptions;
    after?: LocalHookOptions;
    all?: LocalHookOptions;
  }
}


text:
require 'yaml'

module Ec2ssh
  class AwsKeyNotFound < StandardError; end
  class Dotfile
    def initialize(config={})
      @config = {
        'path' => "#{ENV['HOME']}/.ssh/config",
        'aws_keys' => {
          'default' => {
            'access_key_id' => ENV['AMAZON_ACCESS_KEY_ID'],
            'secret_access_key' => ENV['AMAZON_SECRET_ACCESS_KEY']
          }
        },
        'regions' => %w(ap-northeast-1),
      }.merge(config)
    end

    def self.load(path)
      new YAML.load(open(path).read)
    end

    def save(path)
      open(path, 'w') {|f| f.write @config.to_yaml }
    end

    def self.update_or_create(path, config={})
      dotfile = if File.exist?(path)
        Dotfile.load(path)
      else
        new
      end
      dotfile.update(config)
      dotfile.save(path)
    end

    def [](key)
      @config[key]
    end

    def aws_key(keyname)
      self['aws_keys'][keyname] or raise AwsKeyNotFound
    end

    def update(config)
      @config = @config.merge config
    end
  end
end


text:
/* Фиксы для ie7
---------------------------------------------------------------*/
table.urv-table {border-collapse: collapse !important;}
/*table.urv-table{background-color: #bfdcff;}*/
table.urv-table thead tr th {border-left: none !important;}
.urv-table th {background-color: #bfdcff !important; border-color: #4382e6;}
.urv-table .no-top-border-in-child th {background-color: #ddd !important;}

.dataTables_wrapper .top {height: 30px;}
.dataTables_wrapper .bottom {height: 30px;}

.ColVis_MasterButton {overflow:visible} /* автоматическа ширина для кнопки */
.ajax-form {overflow:visible !important;}


text:
namespace ash {

namespace {

// Image buttons.
constexpr int kImageButtonSizeDip = 40;
constexpr int kActionButtonBetweenSpacing = 8;
// Button hover color, Google Grey 8%.
constexpr SkColor kButtonHoverColor = SkColorSetA(gfx::kGoogleGrey900, 0x14);

}  // namespace

// SearchResultImageButton renders the button defined by SearchResult::Action.
class SearchResultImageButton : public views::ImageButton {
 public:
  SearchResultImageButton(SearchResultActionsView* parent,
                          const SearchResult::Action& action);
  ~SearchResultImageButton() override {}

  // ui::EventHandler:
  void OnGestureEvent(ui::GestureEvent* event) override;

  // views::Button:
  void StateChanged(ButtonState old_state) override;

  // views::InkDropHostView:
  std::unique_ptr<views::InkDropRipple> CreateInkDropRipple() const override;
  std::unique_ptr<views::InkDropHighlight> CreateInkDropHighlight()
      const override;

  // Updates the button visibility upon state change of the button or the
  // search result view associated with it.
  void UpdateOnStateChanged();

 private:
  // views::View overrides:
  void OnPaintBackground(gfx::Canvas* canvas) override;

  void SetButtonImage(const gfx::ImageSkia& source, int icon_dimension);

  int GetInkDropRadius() const;
  const char* GetClassName() const override;

  SearchResultActionsView* parent_;
  const bool visible_on_hover_;
  bool to_be_activate_by_long_press_ = false;

  DISALLOW_COPY_AND_ASSIGN(SearchResultImageButton);
};

SearchResultImageButton::SearchResultImageButton(
    SearchResultActionsView* parent,
    const SearchResult::Action& action)
    : ImageButton(parent),
      parent_(parent),
      visible_on_hover_(action.visible_on_hover) {
  SetFocusBehavior(FocusBehavior::ALWAYS);
  // Avoid drawing default dashed focus and draw customized focus in
  // OnPaintBackground();
  SetFocusPainter(nullptr);
  SetInkDropMode(InkDropMode::ON);

  SetPreferredSize({kImageButtonSizeDip, kImageButtonSizeDip});
  SetImageHorizontalAlignment(views::ImageButton::ALIGN_CENTER);
  SetImageVerticalAlignment(views::ImageButton::ALIGN_MIDDLE);

  SetButtonImage(action.image,
                 AppListConfig::instance().search_list_icon_dimension());

  SetAccessibleName(action.tooltip_text);

  SetTooltipText(action.tooltip_text);

  SetVisible(!visible_on_hover_);
  views::InstallCircleHighlightPathGenerator(this);
}

void SearchResultImageButton::OnGestureEvent(ui::GestureEvent* event) {
  switch (event->type()) {
    case ui::ET_GESTURE_LONG_PRESS:
      to_be_activate_by_long_press_ = true;
      event->SetHandled();
      break;
    case ui::ET_GESTURE_END:
      if (to_be_activate_by_long_press_) {
        NotifyClick(*event);
        SetState(STATE_NORMAL);
        to_be_activate_by_long_press_ = false;
        event->SetHandled();
      }
      break;
    default:
      break;
  }
  if (!event->handled())
    Button::OnGestureEvent(event);
}

void SearchResultImageButton::StateChanged(
    views::Button::ButtonState old_state) {
  parent_->ActionButtonStateChanged();
}

std::unique_ptr<views::InkDropRipple>
SearchResultImageButton::CreateInkDropRipple() const {
  const gfx::Point center = GetLocalBounds().CenterPoint();
  const int ripple_radius = GetInkDropRadius();
  gfx::Rect bounds(center.x() - ripple_radius, center.y() - ripple_radius,
                   2 * ripple_radius, 2 * ripple_radius);
  constexpr SkColor ripple_color = SkColorSetA(gfx::kGoogleGrey900, 0x17);

  return std::make_unique<views::FloodFillInkDropRipple>(
      size(), GetLocalBounds().InsetsFrom(bounds),
      GetInkDropCenterBasedOnLastEvent(), ripple_color, 1.0f);
}

std::unique_ptr<views::InkDropHighlight>
SearchResultImageButton::CreateInkDropHighlight() const {
  // TODO(crbug.com/1051167): Grab ink drop related colors and opacities from a
  // theme.
  constexpr SkColor ripple_color = SkColorSetA(gfx::kGoogleGrey900, 0x12);
  auto highlight = std::make_unique<views::InkDropHighlight>(gfx::SizeF(size()),
                                                             ripple_color);
  highlight->set_visible_opacity(1.f);
  return highlight;
}

void SearchResultImageButton::UpdateOnStateChanged() {
  // Show button if the associated result row is hovered or selected, or one
  // of the action buttons is selected.
  if (visible_on_hover_)
    SetVisible(parent_->IsSearchResultHoveredOrSelected());
}

void SearchResultImageButton::OnPaintBackground(gfx::Canvas* canvas) {
  if (HasFocus() || parent_->GetSelectedAction() == tag()) {
    cc::PaintFlags circle_flags;
    circle_flags.setAntiAlias(true);
    circle_flags.setColor(kButtonHoverColor);
    circle_flags.setStyle(cc::PaintFlags::kFill_Style);
    canvas->DrawCircle(GetLocalBounds().CenterPoint(), GetInkDropRadius(),
                       circle_flags);
  }
}

void SearchResultImageButton::SetButtonImage(const gfx::ImageSkia& source,
                                             int icon_dimension) {
  SetImage(views::ImageButton::STATE_NORMAL,
           gfx::ImageSkiaOperations::CreateResizedImage(
               source, skia::ImageOperations::RESIZE_BEST,
               gfx::Size(icon_dimension, icon_dimension)));
}

int SearchResultImageButton::GetInkDropRadius() const {
  return width() / 2;
}

const char* SearchResultImageButton::GetClassName() const {
  return "SearchResultImageButton";
}

SearchResultActionsView::SearchResultActionsView(
    SearchResultActionsViewDelegate* delegate)
    : delegate_(delegate) {
  SetLayoutManager(std::make_unique<views::BoxLayout>(
      views::BoxLayout::Orientation::kHorizontal, gfx::Insets(),
      kActionButtonBetweenSpacing));
}

SearchResultActionsView::~SearchResultActionsView() {}

void SearchResultActionsView::SetActions(const SearchResult::Actions& actions) {
  if (selected_action_.has_value())
    selected_action_.reset();
  buttons_.clear();
  RemoveAllChildViews(true);

  for (size_t i = 0; i < actions.size(); ++i)
    CreateImageButton(actions[i], i);
  PreferredSizeChanged();
}

bool SearchResultActionsView::IsValidActionIndex(size_t action_index) const {
  return action_index < GetActionCount();
}

bool SearchResultActionsView::IsSearchResultHoveredOrSelected() const {
  return delegate_->IsSearchResultHoveredOrSelected();
}

void SearchResultActionsView::UpdateButtonsOnStateChanged() {
  for (SearchResultImageButton* button : buttons_)
    button->UpdateOnStateChanged();
}

void SearchResultActionsView::ActionButtonStateChanged() {
  UpdateButtonsOnStateChanged();
}

const char* SearchResultActionsView::GetClassName() const {
  return "SearchResultActionsView";
}

bool SearchResultActionsView::SelectInitialAction(bool reverse_tab_order) {
  if (GetActionCount() == 0)
    return false;

  if (reverse_tab_order) {
    selected_action_ = GetActionCount() - 1;
  } else {
    selected_action_.reset();
  }
  UpdateButtonsOnStateChanged();
  return selected_action_.has_value();
}

bool SearchResultActionsView::SelectNextAction(bool reverse_tab_order) {
  if (GetActionCount() == 0)
    return false;

  // For reverse tab order, consider moving to non-selected state.
  if (reverse_tab_order) {
    if (!selected_action_.has_value())
      return false;

    if (selected_action_.value() == 0) {
      ClearSelectedAction();
      return true;
    }
  }

  const int next_index =
      selected_action_.value_or(-1) + (reverse_tab_order ? -1 : 1);
  if (!IsValidActionIndex(next_index))
    return false;

  selected_action_ = next_index;
  UpdateButtonsOnStateChanged();
  return true;
}

void SearchResultActionsView::NotifyA11yResultSelected() {
  DCHECK(HasSelectedAction());

  int selected_action = GetSelectedAction();
  for (views::Button* button : buttons_) {
    if (button->tag() == selected_action) {
      button->NotifyAccessibilityEvent(ax::mojom::Event::kSelection, true);
      return;
    }
  }
}

void SearchResultActionsView::ClearSelectedAction() {
  selected_action_.reset();
  UpdateButtonsOnStateChanged();
}

int SearchResultActionsView::GetSelectedAction() const {
  return selected_action_.value_or(-1);
}

bool SearchResultActionsView::HasSelectedAction() const {
  return selected_action_.has_value();
}

void SearchResultActionsView::CreateImageButton(
    const SearchResult::Action& action,
    int action_index) {
  SearchResultImageButton* button = new SearchResultImageButton(this, action);
  button->set_tag(action_index);
  AddChildView(button);
  buttons_.emplace_back(button);
}

size_t SearchResultActionsView::GetActionCount() const {
  return buttons_.size();
}

void SearchResultActionsView::ChildVisibilityChanged(views::View* child) {
  PreferredSizeChanged();
}

void SearchResultActionsView::ButtonPressed(views::Button* sender,
                                            const ui::Event& event) {
  if (!delegate_)
    return;

  DCHECK_GE(sender->tag(), 0);
  DCHECK_LT(sender->tag(), static_cast<int>(GetActionCount()));
  delegate_->OnSearchResultActionActivated(sender->tag(), event.flags());
}

}  // namespace ash


text:
OTTO WG Minutes: 5/24/2017
STATUS: Draft

## Voting Members Attending:
 - Mike Schwartz
 - Yuriy Zabrovarnyy
 - Meg Joshi
 - Judith Bush
 - Keith Hazelton

Note: no minutes from last week. We just reviewed the draft SAML vocabulary,
changes will be reflected in the next github push.

## Review API doc for Search Federations

 API Spec: http://gluu.co/otto-api

Document needs parameter definitions--move from swagger-ui to XML.

For the filter, the API should return the key in the results for clarity and
to support multiple filters.

Note: Align pagination with SCIM:
  https://tools.ietf.org/html/rfc7644#section-3.4.2.4

Note on the API to "Link entity with federation"

There should at least be a check to make sure that the organization that
operates the entity should be a member of the federation.

We should clarify that a 200 means that the federation has received the
request, not necessarily that the federation has accepted it for publication
(there might be a human or other approval process to vet the entity.)

## Discussion of adding PATCH

Currently the OTTO API's support PUT. This requires replacement of the entire
object. It's sort of dangerous to do this. It's also prossible that certain
properties might not be writable by the owner. For example, a registration
authority or federation might manage certain propeties for an organization.
This would make it more difficult to delegate permissions to update.

PATCH could allow more granularity in updating properties of the class. SCIM uses PATCH, which is based on JSON Patch.

Some of the group think we should leave this to 'version 2.0' Mike posits that
it's better to get it right on the first go-around, as there is a long lag
between releasing a new spec, and for implemntations to catch up. If we know
we need it, we should just take the time and define it. It's three pages in the
SCIM spec, so it's not too bad.

SCIM 2.0 defines PATCH:
  https://tools.ietf.org/html/rfc7644#section-3.5.2

JSON Patch RFC 6902:
  https://tools.ietf.org/html/rfc6902

JSON Pointer RFC 6901:
  https://tools.ietf.org/html/rfc6901.

Here are Judith's notes:
```
JSON pointer describes a path to a specific JSON value.  We are also using a flavor of "XPath for JSON" as our query language: we chose JSpath as "most succinct."

They are somewhat different as my notes below outline.

While JSON Patch will simplify implementing PATCH, it is worth noting the two different syntaxes to follow.

----

Differences between JSON Pointer & JSPath

How to deal with various characters:

JSON Pointer: '~' needs to be encoded as '~0' and '/' needs to be encoded as '~1' when these characters appear in a reference token.
JSPath: If you need to locate properties containing non-alphanumerical characters, you have to quote them
The whole document

JSON Pointer: //
JSPath: .
To describe a token/property immediately descended from context

JSON Pointer: /token
JSPath: .property
To reference an array member (both 0 based):

JSON Pointer: "/#"
JSPath: [#]
JSON Pointer allows one to reference the (non-existent) array member after the last existing array member: /-

As a query language JSPath has

wildcard * for the properties
.. to refer to arbitrary depth ("locates property deeply descended from context items"
more array actions for queries including ranges
allows negative indices to count from the end
joins on properties using parenthesis and pipe; eg: ( .prop1 | .prop2)
absolute path notation: "If location path starts with the caret (^) you are using an absolute location path. This syntax is used to locate a property when another context is already used in the location path and/or the object predicates."

```

## Next Meeting 5/31 12pm US Eastern Time

*** NOTE: No meeting 5/3 because of IIW! ***

1.  Please join my meeting.
https://global.gotomeeting.com/join/162399285

2.  Use your microphone and speakers (VoIP) - a headset is recommended.  Or, call in using your telephone.

United States: +1 (669) 224-3319
Australia: +61 2 8355 1034
Austria: +43 7 2088 0716
Belgium: +32 28 93 7002
Canada: +1 (647) 497-9372
Denmark: +45 69 91 84 58
Finland: +358 923 17 0556
France: +33 170 950 590
Germany: +49 692 5736 7206
Ireland: +353 19 030 053
Italy: +39 0 699 26 68 65
Netherlands: +31 208 080 759
New Zealand: +64 9 974 9579
Norway: +47 21 04 30 59
Spain: +34 931 76 1534
Sweden: +46 852 500 691
Switzerland: +41 435 0026 89
United Kingdom: +44 20 3713 5011

Access Code: 162-399-285
Meeting ID: 162-399-285


text:
/*
 * Legal Notice
 *
 * This document and associated source code (the "Work") is a part of a
 * benchmark specification maintained by the TPC.
 *
 * The TPC reserves all right, title, and interest to the Work as provided
 * under U.S. and international laws, including without limitation all patent
 * and trademark rights therein.
 *
 * No Warranty
 *
 * 1.1 TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE INFORMATION
 *     CONTAINED HEREIN IS PROVIDED "AS IS" AND WITH ALL FAULTS, AND THE
 *     AUTHORS AND DEVELOPERS OF THE WORK HEREBY DISCLAIM ALL OTHER
 *     WARRANTIES AND CONDITIONS, EITHER EXPRESS, IMPLIED OR STATUTORY,
 *     INCLUDING, BUT NOT LIMITED TO, ANY (IF ANY) IMPLIED WARRANTIES,
 *     DUTIES OR CONDITIONS OF MERCHANTABILITY, OF FITNESS FOR A PARTICULAR
 *     PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OF
 *     WORKMANLIKE EFFORT, OF LACK OF VIRUSES, AND OF LACK OF NEGLIGENCE.
 *     ALSO, THERE IS NO WARRANTY OR CONDITION OF TITLE, QUIET ENJOYMENT,
 *     QUIET POSSESSION, CORRESPONDENCE TO DESCRIPTION OR NON-INFRINGEMENT
 *     WITH REGARD TO THE WORK.
 * 1.2 IN NO EVENT WILL ANY AUTHOR OR DEVELOPER OF THE WORK BE LIABLE TO
 *     ANY OTHER PARTY FOR ANY DAMAGES, INCLUDING BUT NOT LIMITED TO THE
 *     COST OF PROCURING SUBSTITUTE GOODS OR SERVICES, LOST PROFITS, LOSS
 *     OF USE, LOSS OF DATA, OR ANY INCIDENTAL, CONSEQUENTIAL, DIRECT,
 *     INDIRECT, OR SPECIAL DAMAGES WHETHER UNDER CONTRACT, TORT, WARRANTY,
 *     OR OTHERWISE, ARISING IN ANY WAY OUT OF THIS OR ANY OTHER AGREEMENT
 *     RELATING TO THE WORK, WHETHER OR NOT SUCH AUTHOR OR DEVELOPER HAD
 *     ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * Contributors
 * - Sergey Vasilevskiy
 */

/*
*   A fixed size array that provides random access by index.
*
*/
#ifndef FIXED_ARRAY_H
#define FIXED_ARRAY_H

#include "EGenUtilities_stdafx.h"

namespace TPCE
{

class CFixedArrayErr : public CBaseErr
{
public:
    enum eFixedArrayErrs
    {
        eNotEnoughMemory,
        eIndexOutOfRange,
        eOverflow
    };

    CFixedArrayErr( eFixedArrayErrs iErr, const char *szLoc) : CBaseErr(iErr, szLoc) {};
    int ErrorType() {return ERR_TYPE_FIXED_ARRAY;};

    const char *ErrorText() const
    {
        int i;
        static const char * szErrs[] = {
            "Not enough memory",
            "Index out of range.",
            "Cannot insert element - container is full.",
            ""
        };

        for(i = 0; szErrs[i][0]; i++)
        {
            // Confirm that an error message has been defined for the error code
            if ( i == m_idMsg )
                break;
        }

        return(szErrs[i][0] ? szErrs[i] : ERR_UNKNOWN);
    }
};

/*
*   Fixed-size array container
*
*   The first template parameter specifies data element type.
*   The second template parameter specifies a struct type that
*   contains the total number of data elements possible to store.
*   The struct in the second parameter must define TotalElements() public member function.
*/
template <typename TData, typename TElementsLimits>
class CFixedArray
{
    //Really using only the TotalElements() member function on this type
    TElementsLimits m_sLimits;
    int             m_iTotalElements;   // total elements from limits; taken once in the constructor for performance
    int             m_iCurrentElements; //current number of elements (cannot be greater than m_iTotalElements)
    TData           *m_pData;           //array of data elements

public:
    typedef TData*  PData;      //pointer to a data element

    //Constructor
    CFixedArray()
        : m_iCurrentElements(0) //no elements in the beginning
    {
        m_iTotalElements = m_sLimits.TotalElements();

        m_pData = new TData[m_iTotalElements];
    }
    //Destructor
    ~CFixedArray()
    {
        if (m_pData != NULL)
            delete [] m_pData;
    }

    //Add a (key, data) pair to the container.
    //Operation is performed in constant time for any (key, data) pair.
    void Add(TData *pData)
    {
        if (m_iCurrentElements < m_iTotalElements)
        {   //have place to insert new association

            m_pData[m_iCurrentElements] = *pData;   //copy the data value

            ++m_iCurrentElements;               //because just added one element
        }
        else
        {
            //container is full
            throw CFixedArrayErr(CFixedArrayErr::eOverflow, "CFixedArray::Add");
        }
    }

    //Element access by index
    TData& operator[](int iIndex)
    {
        assert(iIndex>=0 && iIndex < m_iTotalElements);
        //correct index value
        return m_pData[iIndex]; //return reference to the data value
    }

    //Return the total number of elements
    int size() {return m_iTotalElements;}
};

}   // namespace TPCE

#endif //FIXED_ARRAY_H


text:
package com.saintdan.util.commons.utils;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.File;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * Jaxb utilities.
 *
 * @author Liao Yifan
 * @date 9/1/15
 * @since JDK1.8
 */
public class JaxbUtils {

    /**
     * Parse xml string to xml object.
     *
     * @param clazz         xml object
     * @param xmlStr        xml string
     * @param <T>           T
     * @return              T instance
     * @throws JAXBException
     */
    public static <T> T parserXml(Class<T> clazz, String xmlStr) throws JAXBException {
        JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        return (T) jaxbUnmarshaller.unmarshal(new StringReader(xmlStr));
    }

    /**
     * Parse xml file to xml object.
     *
     * @param clazz         xml object
     * @param file          xml file
     * @param <T>           T
     * @return              T instance
     * @throws JAXBException
     */
    public static <T> T parserXml(Class<T> clazz, File file) throws JAXBException {
        JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        return (T) jaxbUnmarshaller.unmarshal(file);
    }

    /**
     * Save xml object to file.
     *
     * @param xmlObj    xml object
     * @param file      xml file
     * @throws JAXBException
     */
    public static void save(Object xmlObj, File file) throws JAXBException {
        Class<?> clazz = xmlObj.getClass();

        if (clazz.getAnnotation(XmlRootElement.class) == null) {
            throw new IllegalArgumentException("Object must be generate by jaxb.");
        }

        JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jaxbMarshaller.marshal(xmlObj, file);
    }

    /**
     * Transform xml object to xml string.
     *
     * @param xmlObj        xml object
     * @throws JAXBException
     *
     * @return
     */
    public static String toXmlString(Object xmlObj) throws JAXBException {
        Class<?> clazz = xmlObj.getClass();

        if (clazz.getAnnotation(XmlRootElement.class) == null) {
            throw new IllegalArgumentException("Object must be generate by jaxb.");
        }

        JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        StringWriter w = new StringWriter();
        jaxbMarshaller.marshal(xmlObj, w);
        return w.toString();
    }
}