text:
NS_ASSUME_NONNULL_BEGIN

@interface JSCInvokedPluginCommand : NSObject

@property (nonatomic, readonly, copy) NSString *callbackId;
@property (nonatomic, readonly, copy) NSString *className;
@property (nonatomic, readonly, copy) NSString *methodName;
@property (nonatomic, readonly, strong) NSArray *arguments;

+ (JSCInvokedPluginCommand *)commandFromJSArray:(NSArray *)jsArray;

@end

NS_ASSUME_NONNULL_END


text:
var System = new Object();

System.SETTINGS_USE_CACHE	= true;

System.TYPE_UNDEFINED 		= undefined;
System.TYPE_STRING			= "string";

System.putInnerHtml = function(html, value){
	System.putInnerHTML(html, value);
};

System.putInnerHTML = function(html, value){
	if (System.TYPE_STRING === typeof(html)){
		var domElement = null;

		if (true === System.SETTINGS_USE_CACHE && System.Cache){
			domElement = System.Cache.getHtml(html);
		}
		else{
			domElement = document.getElementById(html);
		}

		Samsung.Widget.putInnerHTML(domElement, value);
	}
};

System.preventClosing = function(){
	if (event) Samsung.Widget.blockNavigation(event);
};

System.getWidgetId = function(){
	return curWidget.id;
};

System.ready = function(){
	Samsung.Widget.sendReadyEvent();
};

redpajama_set_name: RedPajamaGithub


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

/**
 * @fileoverview Unit tests for BeamJobRunResult.
 */

import { BeamJobRunResult } from 'domain/jobs/beam-job-run-result.model';

describe('BeamJobRunResult model', () => {
  it('should copy arguments', () => {
    const result = new BeamJobRunResult('abc', 'def');
    expect(result.stdout).toEqual('abc');
    expect(result.stderr).toEqual('def');
  });

  it('should copy values from backend dict', () => {
    const result = BeamJobRunResult.createFromBackendDict({
      stdout: 'abc', stderr: 'def'
    });
    expect(result.stdout).toEqual('abc');
    expect(result.stderr).toEqual('def');
  });

  it('should identify non-empty stdout', () => {
    const result = new BeamJobRunResult('abc', '');
    expect(result.isEmpty()).toBeFalse();
  });

  it('should identify non-empty stderr', () => {
    const result = new BeamJobRunResult('', 'def');
    expect(result.isEmpty()).toBeFalse();
  });

  it('should identify empty stdout and stderr', () => {
    const result = new BeamJobRunResult('', '');
    expect(result.isEmpty()).toBeTrue();
  });
});


text:
"use strict";

var Launcher = require("./Launcher"),
    Logger   = require("./Logger");

/**
 * @private
 * @type {DomainManager}
 * DomainManager provided at initialization time
 */
var _domainManager = null;

/**
 * @private
 * Implementation of base.enableDebugger commnad.
 * In the future, process._debugProcess may go away. In that case
 * we will probably have to implement re-launching of the Node process
 * with the --debug command line switch.
 */
function cmdEnableDebugger() {
    // Unfortunately, there's no indication of whether this succeeded
    // This is the case for _all_ of the methods for enabling the debugger.
    process._debugProcess(process.pid);
}

/**
 * @private
 * Implementation of base.restartNode command.
 */
function cmdRestartNode() {
    Launcher.exit();
}

/**
 * @private
 * Implementation of base.loadDomainModulesFromPaths
 * @param {Array.<string>} paths Paths to load
 * @return {boolean} Whether the load succeeded
 */
function cmdLoadDomainModulesFromPaths(paths) {
    if (_domainManager) {
        var success = _domainManager.loadDomainModulesFromPaths(paths);
        if (success) {
            _domainManager.emitEvent("base", "newDomains");
        }
        return success;
    } else {
        return false;
    }
}

/**
 *
 * Registers commands with the DomainManager
 * @param {DomainManager} domainManager The DomainManager to use
 */
function init(domainManager) {
    _domainManager = domainManager;

    _domainManager.registerDomain("base", {major: 0, minor: 1});
    _domainManager.registerCommand(
        "base",
        "enableDebugger",
        cmdEnableDebugger,
        false,
        "Attempt to enable the debugger",
        [], // no parameters
        []  // no return type
    );
    _domainManager.registerCommand(
        "base",
        "restartNode",
        cmdRestartNode,
        false,
        "Attempt to restart the Node server",
        [], // no parameters
        []  // no return type
    );
    _domainManager.registerCommand(
        "base",
        "loadDomainModulesFromPaths",
        cmdLoadDomainModulesFromPaths,
        false,
        "Attempt to load command modules from the given paths. " +
            "The paths should be absolute.",
        [{name: "paths", type: "array<string>"}],
        [{name: "success", type: "boolean"}]
    );

    _domainManager.registerEvent(
        "base",
        "log",
        [{name: "level", type: "string"},
            {name: "timestamp", type: "Date"},
            {name: "message", type: "string"}]
    );
    Logger.on(
        "log",
        function (level, timestamp, message) {
            _domainManager.emitEvent(
                "base",
                "log",
                [level, timestamp, message]
            );
        }
    );

    _domainManager.registerEvent("base", "newDomains", []);
}

exports.init = init;


text:
package org.onosproject.events;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collector;
import java.util.stream.Stream;

import org.apache.karaf.shell.commands.Command;
import org.apache.karaf.shell.commands.Option;
import org.joda.time.LocalDateTime;
import org.onosproject.cli.AbstractShellCommand;
import org.onosproject.cluster.ClusterEvent;
import org.onosproject.event.Event;
import org.onosproject.mastership.MastershipEvent;
import org.onosproject.net.Link;
import org.onosproject.net.device.DeviceEvent;
import org.onosproject.net.host.HostEvent;
import org.onosproject.net.link.LinkEvent;
import org.onosproject.net.topology.Topology;
import org.onosproject.net.topology.TopologyEvent;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableList;

import static java.util.stream.Collectors.toList;

/**
 * Command to print history of instance local ONOS Events.
 */
@Command(scope = "onos", name = "events",
         description = "Command to print history of instance local ONOS Events")
public class EventsCommand
    extends AbstractShellCommand {

    @Option(name = "--all", aliases = "-a",
            description = "Include all Events (default behavior)",
            required = false)
    private boolean all = false;

    @Option(name = "--mastership", aliases = "-m",
            description = "Include MastershipEvent",
            required = false)
    private boolean mastership = false;

    @Option(name = "--device", aliases = "-d",
            description = "Include DeviceEvent",
            required = false)
    private boolean device = false;

    @Option(name = "--link", aliases = "-l",
            description = "Include LinkEvent",
            required = false)
    private boolean link = false;

    @Option(name = "--topology", aliases = "-t",
            description = "Include TopologyEvent",
            required = false)
    private boolean topology = false;

    @Option(name = "--host", aliases = "-t",
            description = "Include HostEvent",
            required = false)
    private boolean host = false;

    @Option(name = "--cluster", aliases = "-c",
            description = "Include ClusterEvent",
            required = false)
    private boolean cluster = false;

    @Option(name = "--max-events", aliases = "-n",
            description = "Maximum number of events to print",
            required = false,
            valueToShowInHelp = "-1 [no limit]")
    private long maxSize = -1;

    @Override
    protected void execute() {
        EventHistoryService eventHistoryService = get(EventHistoryService.class);

        Stream<Event<?, ?>> events = eventHistoryService.history().stream();

        boolean dumpAll = all || !(mastership || device || link || topology || host);

        if (!dumpAll) {
            Predicate<Event<?, ?>> filter = (defaultIs) -> false;

            if (mastership) {
                filter = filter.or(evt -> evt instanceof MastershipEvent);
            }
            if (device) {
                filter = filter.or(evt -> evt instanceof DeviceEvent);
            }
            if (link) {
                filter = filter.or(evt -> evt instanceof LinkEvent);
            }
            if (topology) {
                filter = filter.or(evt -> evt instanceof TopologyEvent);
            }
            if (host) {
                filter = filter.or(evt -> evt instanceof HostEvent);
            }
            if (cluster) {
                filter = filter.or(evt -> evt instanceof ClusterEvent);
            }

            events = events.filter(filter);
        }

        if (maxSize > 0) {
            events = events.limit(maxSize);
        }

        if (outputJson()) {
            ArrayNode jsonEvents = events.map(this::json).collect(toArrayNode());
            printJson(jsonEvents);
        } else {
            events.forEach(this::printEvent);
        }

    }

    private Collector<JsonNode, ArrayNode, ArrayNode> toArrayNode() {
        return Collector.of(() -> mapper().createArrayNode(),
                            ArrayNode::add,
                            ArrayNode::addAll);
    }

    private ObjectNode json(Event<?, ?> event) {
        ObjectNode result = mapper().createObjectNode();

        result.put("time", event.time())
              .put("type", event.type().toString())
              .put("event", event.toString());

        return result;
    }

    /**
     * Print JsonNode using default pretty printer.
     *
     * @param json JSON node to print
     */
    @java.lang.SuppressWarnings("squid:S1148")
    private void printJson(JsonNode json) {
        try {
            print("%s", mapper().writerWithDefaultPrettyPrinter().writeValueAsString(json));
        } catch (JsonProcessingException e) {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw));
            print("[ERROR] %s\n%s", e.getMessage(), sw.toString());
        }
    }

    private void printEvent(Event<?, ?> event) {
        if (event instanceof DeviceEvent) {
            DeviceEvent deviceEvent = (DeviceEvent) event;
            if (event.type().toString().startsWith("PORT")) {
                // Port event
                print("%s %s\t%s/%s [%s]",
                      new LocalDateTime(event.time()),
                      event.type(),
                      deviceEvent.subject().id(), deviceEvent.port().number(),
                      deviceEvent.port()
                  );
            } else {
                // Device event
                print("%s %s\t%s [%s]",
                      new LocalDateTime(event.time()),
                      event.type(),
                      deviceEvent.subject().id(),
                      deviceEvent.subject()
                  );
            }

        } else if (event instanceof MastershipEvent) {
            print("%s %s\t%s [%s]",
                  new LocalDateTime(event.time()),
                  event.type(),
                  event.subject(),
                  ((MastershipEvent) event).roleInfo());

        } else if (event instanceof LinkEvent) {
            LinkEvent linkEvent = (LinkEvent) event;
            Link link = linkEvent.subject();
            print("%s %s\t%s/%s-%s/%s [%s]",
                  new LocalDateTime(event.time()),
                  event.type(),
                  link.src().deviceId(), link.src().port(), link.dst().deviceId(), link.dst().port(),
                  link);

        } else if (event instanceof HostEvent) {
            HostEvent hostEvent = (HostEvent) event;
            print("%s %s\t%s [%s->%s]",
                  new LocalDateTime(event.time()),
                  event.type(),
                  hostEvent.subject().id(),
                  hostEvent.prevSubject(), hostEvent.subject());

        } else if (event instanceof TopologyEvent) {
            TopologyEvent topoEvent = (TopologyEvent) event;
            List<Event> reasons = MoreObjects.firstNonNull(topoEvent.reasons(),
                                                           ImmutableList.<Event>of());
            Topology topo = topoEvent.subject();
            String summary = String.format("(d=%d,l=%d,c=%d)",
                                           topo.deviceCount(),
                                           topo.linkCount(),
                                           topo.clusterCount());
            print("%s %s%s [%s]",
                  new LocalDateTime(event.time()),
                  event.type(),
                  summary,
                  reasons.stream().map(e -> e.type()).collect(toList()));

        } else if (event instanceof ClusterEvent) {
            print("%s %s\t%s [%s]",
                  new LocalDateTime(event.time()),
                  event.type(),
                  ((ClusterEvent) event).subject().id(),
                  event.subject());

        } else {
            // Unknown Event?
            print("%s %s\t%s [%s]",
                  new LocalDateTime(event.time()),
                  event.type(),
                  event.subject(),
                  event);
        }
    }

}


text:
This is just a demo for some features of Light Framework.

    1. Schema form Strap select for single and multiple select.

    2. Schema form UI select for single and multiple select.

    3. Test get command to REST Handler


text:
<?xml version="1.0" encoding="UTF-8"?>
<documentation id="io.sarl.demos.boids.awt"
               name="Reynolds Boids (AWT interface)"
               category="io.sarl.simulation.nature">
	<mainPage>docs/README.md</mainPage>
	<screenshot>docs/boids_screenshot.png</screenshot>
	<description>Simulation of the Reynolds' Boids based on an AWT user interface.</description>
</documentation>


text:
{% extends "base.html" %}
{% block title %}Fontify - Your font is ready to use!{% endblock %}

{% block body %}

Cheers!

Your font is ready to use!

<button class="gradient-rect">Download .ttf file</button>

Playground

See your own font in action!

    <textarea class="gradient-rect lighter" placeholder="I can eat glass, it does not hurt me."></textarea>

Use as webfont

Add the following lines to your CSS:

@font-face {
  font-family: {{ font_name }};
  src: url(http://fontifyapp.com/download/{{ key }}/fontify.woff);
}

/* Then use {{ font_name }} like this: */
p {
  font-family: {{ font_name }}, sans-serif;
}

{% endblock %}


text:
module Boot where

import BootUser

newtype Boot = Boot IntList
    deriving Show


text:
package info.voxtechnica.appraisers.service;

import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import info.voxtechnica.appraisers.db.dao.Events;
import info.voxtechnica.appraisers.model.Tuid;
import info.voxtechnica.appraisers.util.LicenseImporter;
import info.voxtechnica.appraisers.util.TuidFactory;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.concurrent.ExecutorService;

public class LicenseService {
    private static final Logger LOG = LoggerFactory.getLogger(LicenseService.class);
    private static boolean initialized = false;
    private static ListeningExecutorService importService;

    public static void initialize(ExecutorService executorService) {
        if (!initialized) {
            importService = MoreExecutors.listeningDecorator(executorService);
            initialized = true;
        } else LOG.info("Previously initialized.");
    }

    public static boolean isInitialized() {
        return initialized;
    }

    /**
     * Import ASC appraiser licenses from an ASC license data snapshot. Licenses are imported using concurrent workers.
     *
     * @param reader   Buffered reader
     * @param date     Optional local date used for importing historical data
     * @return number of licenses imported
     */
    public static String importLicenses(BufferedReader reader, LocalDate date) {
        boolean historical = (date != null);
        String importId = TuidFactory.getId();
        Integer day = date == null ? (new Tuid(importId)).getYearMonthDay() : (date.getYear() * 10000) + (date.getMonthValue() * 100) + date.getDayOfMonth();
        Long millis = date == null ? null : date.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli();
        long count = 0;
        String[] fieldNames = {};
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                // convert the Windows-1252 String to a UTF-8 String
                line = (new String(line.getBytes(), "UTF-8")).trim();
                // skip empty lines (e.g. ^Z EOF character)
                if (line.isEmpty() || !line.contains("\t")) continue;
                // the first line is a header line
                if (++count == 1) fieldNames = line.split("\t");
                else {
                    String id = historical ? TuidFactory.getIdFromTimestamp(millis + count) : TuidFactory.getId();
                    importService.submit(new LicenseImporter(importId, day, fieldNames, line, id));
                }
            }
        } catch (Exception e) {
            Events.error(null, importId, "LicenseService error: " + ExceptionUtils.getRootCauseMessage(e), ExceptionUtils.getStackTrace(e));
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                Events.error(null, importId, "LicenseService error: " + ExceptionUtils.getRootCauseMessage(e), ExceptionUtils.getStackTrace(e));
            }
        }
        String message = String.format("Import %s: enqueued %d licenses for day %d", importId, count - 1, day);
        Events.info(null, importId, message);
        return message;
    }
}


text:
<button id="${tryItButtonId}" class="btn btn-primary">Try it!</button>

    <button class="btn btn-primary" onclick="submitForm('${methodNameJsEscaped}', '${formVar}')">Invoke</button>

    <button class="btn btn-primary" onclick="$('#${tryItButtonId}').show(); $('#${explorerId}').hide(150, function(){$('#${formContainerId}').empty();});">Close</button>

Request

Result


text:
@class EMDayGrid;

@protocol EMDayGridDelegate <NSObject>

- (void)dayGrid:(EMDayGrid *)grid didSelectDay:(NSInteger)day;

@end

@interface EMDayGrid : UIView

@property (nonatomic, strong) UIColor *titleColor;
@property (nonatomic, strong) UIFont *titleFont;
@property (nonatomic, strong) NSDate *date;
@property (nonatomic, strong) NSDate *minimumDate, *maximumDate;
@property (nonatomic, assign, readonly) NSInteger selectedDay;
@property (nonatomic, weak) id<EMDayGridDelegate> delegate;

@end


text:
<form novalidate [formGroup]="myForm">
  <sky-radio-group ariaLabel="Demo options" formControlName="myOption">

        <sky-radio [disabled]="option.disabled" [value]="option.name">
          <sky-radio-label>
            {{ option.name }}
            <sky-help-inline
              (actionClick)="onActionClick()"
              class="sky-control-help"
            ></sky-help-inline>
          </sky-radio-label>
        </sky-radio>

  </sky-radio-group>
</form>

{{ myForm.value.myOption }} is selected


text:
function highlighter(e, f) {
	if ($("html").hasClass("lt9")) {
		// doesn't work with IE8 and below
		return true;
	}
	hljs.highlightBlock(f);
	var text = e.html().replace(/^\n+|\n+$/g, '');
	if (e.hasClass("blank")) { e.html(text); }
	else {
		var nb = text.split(/\n/).length;
		var html = "
";
		for (var i = 1; i < nb+1; i++) {
			html += ""+i+"\n";
		}
		e.html(html+"	"+text+"

");
	}
}

function update_position(scrollto) {
	if ($("html").hasClass("lt8")) { return true; }
	$(".div-affix").each(function() {
		var elm = $(this),
			container = elm.parent(),
			top = $(window).scrollTop(),
			offset = elm.parent().offset(),
			classes = "aligned-fixed aligned-bottom";
		if (elm.height()+24 >= $(window).height()) {
			if (container.hasClass("aligned-fixed")) {
				if (scrollto) {
					container.removeClass(classes).addClass("aligned-bottom");
					$(window).scrollTop(elm.offset().top);
				}
				else {
					container.removeClass(classes);
				}
			}

		}
		else if (top + 12 <= offset.top) {
			container.removeClass(classes);
		}
		else if (top + 12 + elm.height() >= $("body").height()) {
			container.removeClass(classes).addClass("aligned-bottom");
		}
		else {
			container.removeClass(classes).addClass("aligned-fixed");
		}
	});
}

(function($) {
	$.fn.pie = function() {
		return this.each(function() {
			var pie = $(this);
			if (!pie.get(0).getContext) { return true; }
			var ctx = pie.get(0).getContext("2d"),
				pie_width = parseInt(pie.attr("width"), 10),
				pie_height = parseInt(pie.attr("height"), 10),
				pie_radius = pie_height/2-12,
				pie_radius2 = pie_radius/2,
				pie_hover = false,
				pie_data = pies_data[pie.data("data")];
			function pie_get_mouse_position(e) {
				var x = Math.floor((e.pageX-pie.offset().left));
				var y = Math.floor((e.pageY-pie.offset().top));
				var fromCenterX = x-pie_width/2;
				var fromCenterY = y-pie_height/2;
				var fromCenter = Math.sqrt(Math.pow(Math.abs(fromCenterX), 2) +
					Math.pow(Math.abs(fromCenterY), 2));
				if (fromCenter <= pie_radius && fromCenter >= pie_radius2-12) {
					var angle = Math.atan2(fromCenterY, fromCenterX);
					if (angle < 0) angle = 2 * Math.PI + angle; // normalize
					for (var i=0; i<pie_data.length; i++) {
						if (angle <= pie_data[i].end) {
							return i;
						}
					}
				}
				return false;
			}
			function pie_draw_arc(start, end, color, radius, border) {
				ctx.fillStyle = color;
				ctx.beginPath();
				ctx.moveTo(pie_width/2, pie_height/2);
				ctx.arc(pie_width/2, pie_height/2, radius, start, end, false);
				ctx.lineTo(pie_width/2, pie_height/2);
				ctx.fill();
				if (border) { ctx.stroke(); }
			}
			function pie_draw() {
				ctx.clearRect(0, 0, pie_width, pie_height);
				ctx.lineWidth = 2;
				ctx.lineCap = "round";
				ctx.strokeStyle = $("body").css("background-color");
				for (var i=0; i<pie_data.length; i++) {
					var arc = pie_data[i];
					pie_draw_arc(
						arc.start,
						arc.end,
						arc.color,
						pie_radius,
						true
					);
				}
				pie_draw_arc(
					0,
					2*Math.PI,
					$("body").css("background-color"),
					pie_radius-pie_radius2,
					false
				);
			}
			pie.mousemove(function(e) {
				var new_hover = pie_get_mouse_position(e);
				if (new_hover !== pie_hover) {
					if (pie_hover !== false) {
						pie_draw();
						pie.css("cursor", "auto");
					}
					if (new_hover !== false) {
						var arc = pie_data[new_hover];
						ctx.globalCompositeOperation = "destination-over";
						pie_draw_arc(
							arc.start,
							arc.end,
							arc.color,
							pie_radius+6,
							true
						);
						ctx.globalCompositeOperation = "source-over";
						pie.css("cursor", "pointer");
						pie_draw_arc(
							0,
							2*Math.PI,
							arc.color,
							pie_radius-pie_radius2-2,
							false
						);
						ctx.font = "900 32px "+$("body").css("font-family");
						ctx.fillStyle = "#fff";
						ctx.textAlign = "center";
						ctx.textBaseline = "middle";
						ctx.fillText(arc.nb, pie_width/2, pie_height/2, 50);
					}
					pie_hover = new_hover;
				}
			});
			pie.click(function(e) {
				var position = pie_get_mouse_position(e);
				if (position !== false) {
					window.location.href = pie_data[position].url;
				}
			});
			pie_draw();
			pie.closest(".div-pie-statuses").show();
		});
	};
})(jQuery);

$(document).ready(function(){

	$(".box-settings .top").click(function() {
		$(this)
			.find("i")
				.toggleClass("icon-chevron-down")
				.toggleClass("icon-chevron-up").end()
			.closest(".box-settings").find(".inner-form")
				.slideToggle();
	});
	$(".a-help-markdown").click(function() {
		$(this).closest(".box").find(".div-help-markdown").toggle();
	});

	$(".alert").click(function() { $(this).slideUp(); });

	$(".main-right-open").click(function() {
		$(".main-right").toggleClass("open");
	});
	$(".a-menu").click(function() {
		$(".main-right").toggleClass("open");
	});

// Pie chart
	$(".pie-statuses").pie();

// Markdown preview
	$(document).on("click", ".btn-preview", function() {
		var btn = $(this),
			form = $(this).closest("form");
		$.ajax({
			type: "POST",
			url: ajax,
			data: {
				action: "markdown",
				text: form.find("textarea").val()
			}
		}).done(function(ans) {
			ans = jQuery.parseJSON(ans);
			if (ans.success) {
				form
					.find("textarea").hide().end()
					.find(".preview").html(ans.text).show().end()
					.find("pre code").each(function(i,e) {
						highlighter($(this), e);
					});
				btn
					.removeClass("btn-preview")
					.addClass("btn-edit")
					.text(verb_edit);
				update_position(true);
			}
			else {
				alert(ans.text);
			}
		});
		return false;
	});
	$(document).on("click", ".btn-edit", function() {
		$(this)
			.removeClass("btn-edit")
			.addClass("btn-preview")
			.text(verb_preview)
			.closest("form")
				.find(".preview").hide().end()
				.find("textarea").show();
		update_position(true);
		return false;
	});

// Form validation
	$("form").submit(function() {
		if ($(this).find("input[name=\"issue_labels\"]").length) {
			var val = "";
			$(this).find(".label.selected").each(function() {
				val += $(this).data("id")+",";
			});
			$(this).find("input[name=\"issue_labels\"]").val(val);
		}
	});

// Sort
	$(".box-sort-filter form").submit(function(){
		var sel = $(this).find("select"),
			val = "",
			arr = [];
		if (sel.eq(0).val() == "id") { val = "id_"; }
		else { val = "mod_"; }
		if (sel.eq(1).val() == "desc") { val = val+"desc"; }
		else { val = val+"asc"; }
		$(this).find("input[name=\"sort\"]").val(val);

		$(this).find(".btn-status.selected").each(function() {
			arr.push($(this).data("id"));
		});
		$(this).find("input[name=\"statuses\"]").val(arr.join(","));

		val = "all";
		var ok1 = $(this).find(".btn-open").hasClass("selected");
		var ok2 = $(this).find(".btn-closed").hasClass("selected");
		if (ok1 && !ok2) {
			val = "open";
		}
		else if (ok2 && !ok1) {
			val = "closed";
		}
		$(this).find("input[name=\"open\"]").val(val);
	});
	$(".box-sort-filter .btn-open,\
		.box-sort-filter .btn-closed,\
		.box-sort-filter .btn-status"
	).not(".disabled").click(function() {
		$(this).toggleClass("selected").toggleClass("unselected");
	});

// Issue creation / update
	$(".p-edit-labels .label").click(function() {
		$(this).toggleClass("selected").toggleClass("unselected");
	});
	$(".select-status").change(function() {
		if ($(this).find("option:selected").data("match")) {
			$(".select-users").show();
		}
		else {
			$(".select-users").hide();
		}
	}).change();
	$(".btn-cancel").click(function() {
		$(this).closest(".box")
			.find(".t-display").show().end()
			.find(".i-display").hide();
	});
	$(".a-edit-content").click(function() {
		$(this).closest(".box")
			.find(".t-display.div-left").hide().end()
			.find(".i-display.div-left").show();
	});
	$(".a-edit-details").click(function() {
		$(this).closest(".box")
			.find(".t-display.div-right").hide().end()
			.find(".i-display.div-right").show();
		$(".select-status").change();
	});
	$(".a-remove-issue").click(function() {
		if (confirm(confirm_delete_issue)) {
			$(this).closest("form")
				.find("input[name=\"action\"]").attr("name", "delete_issue").end()
				.submit();
		}
	});
	$(".a-notifications").click(function() {
		$(this).closest("form")
			.find("input[name=\"action\"]").attr("name", "notifications").end()
			.submit();
	});
	$(".btn-reopen").click(function() {
		$(this).closest("form").find("input[name=\"issue_open\"]").val("open");
	});
	$(".btn-close").click(function() {
		$(this).closest("form").find("input[name=\"issue_open\"]").val("closed");
	});
	$(".a-edit").click(function() {
		$(this).closest(".box, form")
			.find(".t-display").toggle().end()
			.find(".i-display").toggle();
	});
	$(".a-remove-comment").click(function() {
		if (confirm(confirm_delete_comment)) {
			$(this).closest(".box").find("form")
				.find("input[name=\"edit_comment\"]").attr("name", "delete_comment").end()
				.submit();
		}
	});

// Uploads
	$(".form-upload").each(function() {
		var form = $(this);
		function upload_callback(ans) {
			form
				.find(".btn-upload")
					.toggleClass("disabled")
					.find("span").toggle().end()
					.find("i").toggle().end().end()
				.find(".bar").css("width", 0);
			if (ans.success) {
				form.find(".uploads").append(ans.text);
			}
			else {
				alert(ans.text);
			}
			form
				.find("input[name=\"token\"]").val(ans.token).end()
				.find("input[name=\"upload\"]").remove().end()
				.find(".btn-upload").append("<input type=\"file\" name=\"upload\" />");
			update_position(true);
		}
		form.on("change", "input[name=\"upload\"]", function() {
			var file = $(this)[0].files;

			if (typeof file != "undefined" && window.XMLHttpRequestUpload && window.FormData) {
				file = file[0];
				xhr = new XMLHttpRequest();
				xhr.upload.addEventListener("progress", function(evt) {
					if (evt.lengthComputable) {
						form.find(".bar").css("width", (evt.loaded/evt.total)*100+"%");
					}
				}, false);
				xhr.addEventListener("load", function(evt) {
					upload_callback(jQuery.parseJSON(evt.target.responseText));
				}, false);

				xhr.open("post", ajax, true);

				var formData = new FormData();
				formData.append("type", "xhr");
				formData.append("token", form.find("input[name=\"token\"]").val());
				formData.append("action", "upload");
				formData.append("upload", file);
				xhr.send(formData);
			}
			else {
				form.submit();
			}
			form
				.find(".btn-upload")
					.toggleClass("disabled")
					.find("span").toggle().end()
					.find("i").toggle();
		});
		form.on("click", ".icon-trash", function() {
			var div = $(this).closest("div");
			$.ajax({
				type: "POST",
				url: ajax,
				data: {
					action: "upload_remove",
					token: token,
					name: div.data("name")
				}
			}).done(function(ans) {
				ans = jQuery.parseJSON(ans);
				if (ans.success) {
					div.remove();
				}
				else {
					alert(ans.text);
				}
				token = ans.token;
			});
		});
		$(form.data("link")).submit(function() {
			var uploads = "";
			form.find(".uploads div").each(function() {
				uploads += $(this).data("name")+",";
			});
			$(this).find("input[name=\"uploads\"]").val(uploads);
		});
	});
	$(".a-remove-upload").click(function() {
		if (!confirm(confirm_delete_upload)) { return false; }
		var p = $(this).closest("p"),
			progress = $(this).closest(".div-list-uploads").find(".progress");
		$.ajax({
			type: "POST",
			url: ajax,
			data: {
				action: "upload_remove_linked",
				token: token,
				name: p.data("name"),
				user: p.data("user")
			}
		}).done(function(ans) {
			ans = jQuery.parseJSON(ans);
			if (ans.success) {
				p.remove();
				progress.find("span").html(ans.space);
				progress.find(".bar").css("width", ans.percent+"%");
			}
			else {
				alert(ans.text);
			}
			token = ans.token;
		});
	});

// Highlights code
	$("pre code").each(function(i,e) { highlighter($(this), e); });

// Blocks with fixed position
	$(window).scroll(function() { update_position(); });
	$(window).resize(function() { update_position(); });
	update_position();

});


text:
DROP INDEX IF EXISTS idx1;
-- end_ignore
CREATE INDEX idx1 on pt_lt_tab(col1,col2);
SELECT * FROM pt_lt_tab WHERE col2 > 10.00 OR col1 = 50 ORDER BY col2,col3 LIMIT 5;


text:
package pt.simdea.gmlrva.lib.decoration;

import android.graphics.Canvas;
import android.graphics.Rect;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import pt.simdea.gmlrva.lib.decoration.specs.ItemDecorationSpec;

/**
 * This class is meant to apply any generic implementation of an {@link ItemDecorationSpec} to a {@link RecyclerView}.
 *
 * @param <T> an instance of {@link ItemDecorationSpec}.
 *
 * Created by Paulo Ribeiro on 10/7/2017.
 * Simdea © All Rights Reserved.
 * paulo.ribeiro@simdea.pt
 */
public abstract class GenericItemDecoration<T extends ItemDecorationSpec> extends RecyclerView.ItemDecoration {

    /**
     * Instantiates a new GenericItemDecoration.
     * @param configurationSpec a valid {@link ItemDecorationSpec} containing this item decoration specification.
     */
    protected GenericItemDecoration(@NonNull final T configurationSpec) {
        super();
        applySpec(configurationSpec);
    }

    /** {@inheritDoc} */
    @Override
    public abstract void getItemOffsets(@NonNull final Rect outRect, @NonNull final View view,
                                        @NonNull final RecyclerView parent, @NonNull final RecyclerView.State state);

    /** {@inheritDoc} */
    @Override
    public abstract void onDrawOver(@NonNull final Canvas canvas, @NonNull final RecyclerView parent,
                                    @NonNull final RecyclerView.State state);

    /**
     * Procedure meant to apply a given {@link ItemDecorationSpec} to this item decoration.
     * @param configurationSpec the valid {@link ItemDecorationSpec} containing this item decoration specification.
     */
    protected abstract void applySpec(@NonNull final T configurationSpec);

}


text:
export default class PubSub {
  static pub(topic, data) {
    PubSub.ps.publish(topic, data);
  }

  static sub(topic, fun) {
    return PubSub.ps.subscribe(topic, fun);
  }

  static unsub(token) {
    PubSub.ps.unsubscribe(token);
  }

  static prom(topic, data) {
    return new Promise(PubSub._promisedPubSub.bind(null, topic, data));
  }

  static reg(topic, fun) {
    return PubSub.sub(`${topic}.request`, (reqTopic, reqData) => {
      let [realm, component, topic, resReq, id] = reqTopic.split('.');
      let resTopic = `${realm}.${component}.${topic}.response.${id}`;

      try {
        let funRes = fun(realm, component, topic, id, reqData);

        if (funRes && typeof funRes.then === 'function') {
          funRes.catch(err => {
            return {error: err};
          }).then(res => {
            PubSub.pub(resTopic, res);
          });
          return;
        }

        PubSub.pub(resTopic, funRes);
      } catch (e) {
        PubSub.pub(resTopic, {error: e})
      }
    });
  }

  static _promisedPubSub(topic, data, resolve, reject) {
    let requestId = PubSub.uuid();
    let cancelToken = PubSub.sub(`${topic}.response.${requestId}`, (resTopic, resData) => {
      PubSub.unsub(cancelToken);

      if (resData && resData.error) {
        reject(resData.error);
        return;
      }

      resolve(resData);
    });

    PubSub.pub(`${topic}.request.${requestId}`, data);
  }
}


text:
from ctypes import c_void_p, POINTER, sizeof, Structure, windll, WinError, WINFUNCTYPE, addressof, c_size_t, c_ulong
from ctypes.wintypes import BOOL, BYTE, DWORD, HANDLE, LARGE_INTEGER

LPVOID = c_void_p
LPDWORD = POINTER(DWORD)
SIZE_T = c_size_t
ULONG_PTR = POINTER(c_ulong)

# A ULONGLONG is a 64-bit unsigned integer.
# Thus there are 8 bytes in a ULONGLONG.
# XXX why not import c_ulonglong ?
ULONGLONG = BYTE * 8

class IO_COUNTERS(Structure):
    # The IO_COUNTERS struct is 6 ULONGLONGs.
    # TODO: Replace with non-dummy fields.
    _fields_ = [('dummy', ULONGLONG * 6)]

class JOBOBJECT_BASIC_ACCOUNTING_INFORMATION(Structure):
    _fields_ = [('TotalUserTime', LARGE_INTEGER),
                ('TotalKernelTime', LARGE_INTEGER),
                ('ThisPeriodTotalUserTime', LARGE_INTEGER),
                ('ThisPeriodTotalKernelTime', LARGE_INTEGER),
                ('TotalPageFaultCount', DWORD),
                ('TotalProcesses', DWORD),
                ('ActiveProcesses', DWORD),
                ('TotalTerminatedProcesses', DWORD)]

class JOBOBJECT_BASIC_AND_IO_ACCOUNTING_INFORMATION(Structure):
    _fields_ = [('BasicInfo', JOBOBJECT_BASIC_ACCOUNTING_INFORMATION),
                ('IoInfo', IO_COUNTERS)]

# see http://msdn.microsoft.com/en-us/library/ms684147%28VS.85%29.aspx
class JOBOBJECT_BASIC_LIMIT_INFORMATION(Structure):
    _fields_ = [('PerProcessUserTimeLimit', LARGE_INTEGER),
                ('PerJobUserTimeLimit', LARGE_INTEGER),
                ('LimitFlags', DWORD),
                ('MinimumWorkingSetSize', SIZE_T),
                ('MaximumWorkingSetSize', SIZE_T),
                ('ActiveProcessLimit', DWORD),
                ('Affinity', ULONG_PTR),
                ('PriorityClass', DWORD),
                ('SchedulingClass', DWORD)
                ]

class JOBOBJECT_ASSOCIATE_COMPLETION_PORT(Structure):
    _fields_ = [('CompletionKey', c_ulong),
                ('CompletionPort', HANDLE)]

# see http://msdn.microsoft.com/en-us/library/ms684156%28VS.85%29.aspx
class JOBOBJECT_EXTENDED_LIMIT_INFORMATION(Structure):
    _fields_ = [('BasicLimitInformation', JOBOBJECT_BASIC_LIMIT_INFORMATION),
                ('IoInfo', IO_COUNTERS),
                ('ProcessMemoryLimit', SIZE_T),
                ('JobMemoryLimit', SIZE_T),
                ('PeakProcessMemoryUsed', SIZE_T),
                ('PeakJobMemoryUsed', SIZE_T)]

# These numbers below come from:
# http://msdn.microsoft.com/en-us/library/ms686216%28v=vs.85%29.aspx
JobObjectAssociateCompletionPortInformation = 7
JobObjectBasicAndIoAccountingInformation = 8
JobObjectExtendedLimitInformation = 9

class JobObjectInfo(object):
    mapping = { 'JobObjectBasicAndIoAccountingInformation': 8,
                'JobObjectExtendedLimitInformation': 9,
                'JobObjectAssociateCompletionPortInformation': 7
                }
    structures = {
                   7: JOBOBJECT_ASSOCIATE_COMPLETION_PORT,
                   8: JOBOBJECT_BASIC_AND_IO_ACCOUNTING_INFORMATION,
                   9: JOBOBJECT_EXTENDED_LIMIT_INFORMATION
                   }
    def __init__(self, _class):
        if isinstance(_class, basestring):
            assert _class in self.mapping, 'Class should be one of %s; you gave %s' % (self.mapping, _class)
            _class = self.mapping[_class]
        assert _class in self.structures, 'Class should be one of %s; you gave %s' % (self.structures, _class)
        self.code = _class
        self.info = self.structures[_class]()

QueryInformationJobObjectProto = WINFUNCTYPE(
    BOOL,        # Return type
    HANDLE,      # hJob
    DWORD,       # JobObjectInfoClass
    LPVOID,      # lpJobObjectInfo
    DWORD,       # cbJobObjectInfoLength
    LPDWORD      # lpReturnLength
    )

QueryInformationJobObjectFlags = (
    (1, 'hJob'),
    (1, 'JobObjectInfoClass'),
    (1, 'lpJobObjectInfo'),
    (1, 'cbJobObjectInfoLength'),
    (1, 'lpReturnLength', None)
    )

_QueryInformationJobObject = QueryInformationJobObjectProto(
    ('QueryInformationJobObject', windll.kernel32),
    QueryInformationJobObjectFlags
    )

class SubscriptableReadOnlyStruct(object):
    def __init__(self, struct):
        self._struct = struct

    def _delegate(self, name):
        result = getattr(self._struct, name)
        if isinstance(result, Structure):
            return SubscriptableReadOnlyStruct(result)
        return result

    def __getitem__(self, name):
        match = [fname for fname, ftype in self._struct._fields_
                 if fname == name]
        if match:
            return self._delegate(name)
        raise KeyError(name)

    def __getattr__(self, name):
        return self._delegate(name)

def QueryInformationJobObject(hJob, JobObjectInfoClass):
    jobinfo = JobObjectInfo(JobObjectInfoClass)
    result = _QueryInformationJobObject(
        hJob=hJob,
        JobObjectInfoClass=jobinfo.code,
        lpJobObjectInfo=addressof(jobinfo.info),
        cbJobObjectInfoLength=sizeof(jobinfo.info)
        )
    if not result:
        raise WinError()
    return SubscriptableReadOnlyStruct(jobinfo.info)


text:
import cgi

form = cgi.FieldStorage()

birthdate = form.getvalue('birthdate')
hobby = form.getvalue('hobby')
gender = form.getvalue('gender')
card = form.getvalue('credit')

print "Content-type: text/html"
print
print "<title>Page1</title>"

if (birthdate or hobby or gender or card):
    print "
The data from page2 is:

"

if (birthdate):
    print "Birthdate: " + birthdate + "
"
if (hobby):
    print "Hobby: " + hobby + "
"
if (gender):
    print "Gender: " + gender + "
"
if (card):
    print "Credit Card: " + card + "
"

if (birthdate or hobby or gender or card):
    print "
"

print """
Please enter the following information:
<form method="post" action="page2.py">
First Name: <input type="text" name="name" value=""></input>

Last Name: <input type="text" name="family" value=""></input>

Password: <input type="password" name="password" value=""></input>

Which is better:
<input type="radio" name="city" value="Edmonton" checked>Edmonton</input>

<input type="radio" name="city" value="Calgary" disabled="disabled">Calgary</input>

<input type="submit" value="Submit">
</form>"""


text:
package javay.test.sound;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;

import javax.swing.JComponent;

public final class Picture extends JComponent {

	private static final long serialVersionUID = 1L;

	private Image composerImage;

	/**
	 * @param collection
	 */
	public Picture() {
	}

	{
		setOpaque(true);
		setPreferredSize(new Dimension(200, 200));
	}

	public final void setComposerImage(Image image) {
		composerImage = image;
	}

	@Override
	public void paint(Graphics g) {
		g.setColor(getBackground());
		g.fillRect(0, 0, getWidth(), getHeight());
		if (composerImage != null) {
			int picWidth = composerImage.getWidth(null);
			int picHeight = composerImage.getHeight(null);

			int availableWidth = getWidth();
			int availableHeight = getHeight();

			/* figure out which dimension limits scaling first */
			float scaleW = (float) availableWidth / picWidth;
			float scaleH = (float) availableHeight / picHeight;

			float safeScale = scaleW > scaleH ? scaleH : scaleW;
			picWidth *= safeScale;
			picHeight *= safeScale;

			((Graphics2D) g).setRenderingHint(RenderingHints.KEY_INTERPOLATION,
					RenderingHints.VALUE_INTERPOLATION_BICUBIC);
			g.drawImage(composerImage, (availableWidth - picWidth) / 2,
					(availableHeight - picHeight) / 2, picWidth, picHeight,
					null);
		}
	}

	@Override
	public void update(Graphics g) {
		paint(g);
	}
}


text:
<?php
			if(count($notifications)>0)
			{
			foreach($notifications as $k=>$notification)
			{
			$class="";
			$script="";
			if($notification['Read']==0)
			{
			$class="unread-notif";
			$script='onmouseout="readNotif(this.id)"';
			}
			echo '

'.$notification['Title'].'

'.$notification['SubTitle'].'

';
			}
			}
?>


text:
$_L(["$wt.widgets.Layout"],"$wt.layout.FillLayout",["$wt.graphics.Point","$wt.layout.FillData"],function(){
c$=$_C(function(){
this.type=256;
this.marginWidth=0;
this.marginHeight=0;
this.spacing=0;
$_Z(this,arguments);
},$wt.layout,"FillLayout",$wt.widgets.Layout);
$_K(c$,
function(){
$_R(this,$wt.layout.FillLayout,[]);
});
$_K(c$,
function(type){
$_R(this,$wt.layout.FillLayout,[]);
this.type=type;
},"~N");
$_V(c$,"computeSize",
function(composite,wHint,hHint,flushCache){
var children=composite.getChildren();
var count=children.length;
var maxWidth=0;
var maxHeight=0;
for(var i=0;i<count;i++){
var child=children[i];
var w=wHint;
var h=hHint;
if(count>0){
if(this.type==256&&wHint!=-1){
w=Math.max(0,$_dI((wHint-(count-1)*this.spacing)/count));
}if(this.type==512&&hHint!=-1){
h=Math.max(0,$_dI((hHint-(count-1)*this.spacing)/count));
}}var size=this.computeChildSize(child,w,h,flushCache);
maxWidth=Math.max(maxWidth,size.x);
maxHeight=Math.max(maxHeight,size.y);
}
var width=0;
var height=0;
if(this.type==256){
width=count*maxWidth;
if(count!=0)width+=(count-1)*this.spacing;
height=maxHeight;
}else{
width=maxWidth;
height=count*maxHeight;
if(count!=0)height+=(count-1)*this.spacing;
}width+=this.marginWidth*2;
height+=this.marginHeight*2;
if(wHint!=-1)width=wHint;
if(hHint!=-1)height=hHint;
return new $wt.graphics.Point(width,height);
},"$wt.widgets.Composite,~N,~N,~B");
$_M(c$,"computeChildSize",
function(control,wHint,hHint,flushCache){
var data=control.getLayoutData();
if(data==null){
data=new $wt.layout.FillData();
control.setLayoutData(data);
}var size=null;
if(wHint==-1&&hHint==-1){
size=data.computeSize(control,wHint,hHint,flushCache);
}else{
var trimX;
var trimY;
if($_O(control,$wt.widgets.Scrollable)){
var rect=(control).computeTrim(0,0,0,0);
trimX=rect.width;
trimY=rect.height;
}else{
trimX=trimY=control.getBorderWidth()*2;
}var w=wHint==-1?wHint:Math.max(0,wHint-trimX);
var h=hHint==-1?hHint:Math.max(0,hHint-trimY);
size=data.computeSize(control,w,h,flushCache);
}return size;
},"$wt.widgets.Control,~N,~N,~B");
$_V(c$,"flushCache",
function(control){
var data=control.getLayoutData();
if(data!=null)(data).flushCache();
return true;
},"$wt.widgets.Control");
$_M(c$,"getName",
function(){
var string=this.getClass().getName();
var index=string.lastIndexOf('.');
if(index==-1)return string;
return string.substring(index+1,string.length);
});
$_V(c$,"layout",
function(composite,flushCache){
var rect=composite.getClientArea();
var children=composite.getChildren();
var count=children.length;
if(count==0)return;
var width=rect.width-this.marginWidth*2;
var height=rect.height-this.marginHeight*2;
if(this.type==256){
width-=(count-1)*this.spacing;
var x=rect.x+this.marginWidth;
var extra=width%count;
var y=rect.y+this.marginHeight;
var cellWidth=$_dI(width/count);
for(var i=0;i<count;i++){
var child=children[i];
var childWidth=cellWidth;
if(i==0){
childWidth+=$_dI(extra/2);
}else{
if(i==count-1)childWidth+=$_dI((extra+1)/2);
}child.setBounds(x,y,childWidth,height);
x+=childWidth+this.spacing;
}
}else{
height-=(count-1)*this.spacing;
var x=rect.x+this.marginWidth;
var cellHeight=$_dI(height/count);
var y=rect.y+this.marginHeight;
var extra=height%count;
for(var i=0;i<count;i++){
var child=children[i];
var childHeight=cellHeight;
if(i==0){
childHeight+=$_dI(extra/2);
}else{
if(i==count-1)childHeight+=$_dI((extra+1)/2);
}child.setBounds(x,y,width,childHeight);
y+=childHeight+this.spacing;
}
}},"$wt.widgets.Composite,~B");
$_V(c$,"toString",
function(){
var string=this.getName()+" {";
string+="type="+((this.type==512)?"SWT.VERTICAL":"SWT.HORIZONTAL")+" ";
if(this.marginWidth!=0)string+="marginWidth="+this.marginWidth+" ";
if(this.marginHeight!=0)string+="marginHeight="+this.marginHeight+" ";
if(this.spacing!=0)string+="spacing="+this.spacing+" ";
string=string.trim();
string+="}";
return string;
});
});


text:
using namespace std;

class vertex_property
{
public:
    vertex_property():degree(0),core(0){}

    int16_t degree;
    uint16_t core;
};
class edge_property
{
public:
    edge_property():value(0){}
    edge_property(uint8_t x):value(x){}

    uint8_t value;
};

typedef openG::extGraph<vertex_property, edge_property> graph_t;
typedef graph_t::vertex_iterator    vertex_iterator;
typedef graph_t::edge_iterator      edge_iterator;
//==============================================================//
void arg_init(argument_parser & arg)
{
    arg.add_arg("kcore","3","kCore k value");
}
//==============================================================//
inline unsigned vertex_distributor(uint64_t vid, unsigned threadnum)
{
    return vid%threadnum;
}

void seq_init(graph_t& g)
{
    // initialize
    for (vertex_iterator vit=g.vertices_begin(); vit!=g.vertices_end(); vit++)
    {
        size_t degree = vit->edges_size();
        vit->property().degree = (int16_t)degree;
    }
}
void kcore(graph_t& g, size_t k,
        gBenchPerf_event & perf, int perf_group)
{
    perf.open(perf_group);
    perf.start(perf_group);

    // remove vertices iteratively
    for (unsigned iter=1;iter<=k;iter++)
    {
        for (vertex_iterator vit=g.vertices_begin(); vit!=g.vertices_end(); vit++)
        {
            if (vit->property().core != 0) continue;
            if (vit->property().degree > (int16_t)iter) continue;

            vit->property().core = iter;
            for (edge_iterator eit=vit->edges_begin(); eit!=vit->edges_end(); eit++)
            {
                size_t targ = eit->target();
                vertex_iterator targ_vit = g.find_vertex(targ);
                targ_vit->property().degree--;
            }
        }

    }

    perf.stop(perf_group);
}  // end kcore

void parallel_kcore(graph_t& g, size_t k, unsigned threadnum,
        gBenchPerf_multi & perf, int perf_group)
{
    unsigned chunk = (unsigned) ceil(g.num_vertices()/(double)threadnum);
    #pragma omp parallel num_threads(threadnum)
    {
        unsigned tid = omp_get_thread_num();
        unsigned start = tid*chunk;
        unsigned end = start + chunk;
        if (end > g.num_vertices()) end = g.num_vertices();

        perf.open(tid, perf_group);
        perf.start(tid, perf_group);
#ifdef SIM
        SIM_BEGIN(true);
#endif
        for (unsigned iter=1;iter<=k;iter++)
        {
            #pragma omp barrier

            for (unsigned vid=start;vid<end;vid++)
            {
                vertex_iterator vit = g.find_vertex(vid);
                if (vit->property().core != 0) continue;
                if (vit->property().degree > (int16_t)iter) continue;

                vit->property().core = iter;

                for (edge_iterator eit=vit->edges_begin();eit!=vit->edges_end();eit++)
                {
                    uint64_t dest_vid = eit->target();
                    vertex_iterator destvit = g.find_vertex(dest_vid);
#ifdef HMC
                    HMC_ADD_16B(&(destvit->property().degree), -1);
#else
                    __sync_fetch_and_sub(&(destvit->property().degree), 1);
#endif
                }
            }
        }
#ifdef SIM
        SIM_END(true);
#endif
        perf.stop(tid, perf_group);
    }

}
//==============================================================//
void output(graph_t& g)
{
    cout<<"kCore Results: \n";
    vertex_iterator vit;
    for (vit=g.vertices_begin(); vit!=g.vertices_end(); vit++)
    {
        cout<<"== vertex "<<vit->id()<<": core-"<<vit->property().core<<"\n";
    }
}
void reset_graph(graph_t & g)
{
    vertex_iterator vit;
    for (vit=g.vertices_begin(); vit!=g.vertices_end(); vit++)
    {
        vit->property().degree = 0;
        vit->property().core = 0;
    }

}

//==============================================================//
int main(int argc, char * argv[])
{
    graphBIG::print();
    cout<<"Benchmark: kCore decomposition\n";
    double t1, t2;

    argument_parser arg;
    gBenchPerf_event perf;
    arg_init(arg);
    if (arg.parse(argc,argv,perf,false)==false)
    {
        arg.help();
        return -1;
    }
    string path, separator;
    arg.get_value("dataset",path);
    arg.get_value("separator",separator);

    size_t k,threadnum;
    arg.get_value("kcore",k);
    arg.get_value("threadnum",threadnum);

    graph_t graph;
    cout<<"loading data... \n";

    t1 = timer::get_usec();
    string vfile = path + "/vertex.csv";
    string efile = path + "/edge.csv";

#ifndef EDGES_ONLY
    if (graph.load_csv_vertices(vfile, true, separator, 0) == -1)
        return -1;
    if (graph.load_csv_edges(efile, true, separator, 0, 1) == -1)
        return -1;
#else
    if (graph.load_csv_edges(efile, true, separator, 0, 1) == -1)
        return -1;
#endif

    size_t vertex_num = graph.num_vertices();
    size_t edge_num = graph.num_edges();
    t2 = timer::get_usec();

    cout<<"== "<<vertex_num<<" vertices  "<<edge_num<<" edges\n";

#ifndef ENABLE_VERIFY
    cout<<"== time: "<<t2-t1<<" sec\n\n";
#endif

    cout<<"computing kCore: k="<<k<<"\n";

    gBenchPerf_multi perf_multi(threadnum, perf);
    unsigned run_num = ceil(perf.get_event_cnt() /(double) DEFAULT_PERF_GRP_SZ);
    if (run_num==0) run_num = 1;
    double elapse_time = 0;

    for (unsigned i=0;i<run_num;i++)
    {
        seq_init(graph);

        t1 = timer::get_usec();

        if (threadnum==1)
            kcore(graph, k, perf, i);
        else
            parallel_kcore(graph, k, threadnum, perf_multi, i);
        t2 = timer::get_usec();
        elapse_time += t2-t1;
        if ((i+1)<run_num) reset_graph(graph);
    }
#ifndef ENABLE_VERIFY
    cout<<"== time: "<<elapse_time/run_num<<" sec\n";
    if (threadnum == 1)
        perf.print();
    else
        perf_multi.print();

#endif

#ifdef ENABLE_OUTPUT
    cout<<"\n";
    output(graph);
#endif
    cout<<"==================================================================\n";
    return 0;
}  // end main


text:
/*! http://mths.be/placeholder v1.8.6 by @mathias */
;(function(window, document, $) {

	var isInputSupported = 'placeholder' in document.createElement('input'),
	    isTextareaSupported = 'placeholder' in document.createElement('textarea'),
	    prototype = $.fn,
	    placeholder;

	if (isInputSupported && isTextareaSupported) {

		placeholder = prototype.placeholder = function() {
			return this;
		};

		placeholder.input = placeholder.textarea = true;

	} else {

		placeholder = prototype.placeholder = function() {
			return this
				.filter((isInputSupported ? 'textarea' : ':input') + '[placeholder]')
				.not('.placeholder')
				.bind('focus.placeholder', clearPlaceholder)
				.bind('blur.placeholder', setPlaceholder)
				.trigger('blur.placeholder').end();
		};

		placeholder.input = isInputSupported;
		placeholder.textarea = isTextareaSupported;

		$(function() {
			// Look for forms
			$('form').bind('submit.placeholder', function() {
				// Clear the placeholder values so they don't get submitted
				var $inputs = $('.placeholder', this).each(clearPlaceholder);
				setTimeout(function() {
					$inputs.each(setPlaceholder);
				}, 10);
			});
		});

		// Clear placeholder values upon page reload
		$(window).bind('unload.placeholder', function() {
			$('.placeholder').val('');
		});

	}

	function args(elem) {
		// Return an object of element attributes
		var newAttrs = {},
		    rinlinejQuery = /^jQuery\d+$/;
		$.each(elem.attributes, function(i, attr) {
			if (attr.specified && !rinlinejQuery.test(attr.name)) {
				newAttrs[attr.name] = attr.value;
			}
		});
		return newAttrs;
	}

	function clearPlaceholder() {
		var $input = $(this);
		if ($input.val() === $input.attr('placeholder') && $input.hasClass('placeholder')) {
			if ($input.data('placeholder-password')) {
				$input.hide().next().show().focus().attr('id', $input.removeAttr('id').data('placeholder-id'));
			} else {
				$input.val('').removeClass('placeholder');
			}
		}
	}

	function setPlaceholder() {
		var $replacement,
		    $input = $(this),
		    $origInput = $input,
		    id = this.id;
		if ($input.val() === '') {
			if ($input.is(':password')) {
				if (!$input.data('placeholder-textinput')) {
					try {
						$replacement = $input.clone().attr({ 'type': 'text' });
					} catch(e) {
						$replacement = $('<input>').attr($.extend(args(this), { 'type': 'text' }));
					}
					$replacement
						.removeAttr('name')
						// We could just use the `.data(obj)` syntax here, but that wouldn't work in pre-1.4.3 jQueries
						.data('placeholder-password', true)
						.data('placeholder-id', id)
						.bind('focus.placeholder', clearPlaceholder);
					$input
						.data('placeholder-textinput', $replacement)
						.data('placeholder-id', id)
						.before($replacement);
				}
				$input = $input.removeAttr('id').hide().prev().attr('id', id).show();
			}
			$input.addClass('placeholder').val($input.attr('placeholder'));
		} else {
			$input.removeClass('placeholder');
		}
	}

}(this, document, jQuery));


text:
package com.google.cloud.texttospeech.v1.stub;

import com.google.api.gax.core.BackgroundResource;
import com.google.api.gax.core.BackgroundResourceAggregation;
import com.google.api.gax.grpc.GrpcCallSettings;
import com.google.api.gax.grpc.GrpcStubCallableFactory;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.cloud.texttospeech.v1.ListVoicesRequest;
import com.google.cloud.texttospeech.v1.ListVoicesResponse;
import com.google.cloud.texttospeech.v1.SynthesizeSpeechRequest;
import com.google.cloud.texttospeech.v1.SynthesizeSpeechResponse;
import com.google.longrunning.stub.GrpcOperationsStub;
import io.grpc.MethodDescriptor;
import io.grpc.protobuf.ProtoUtils;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.annotation.Generated;

// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
 * gRPC stub implementation for the TextToSpeech service API.
 *
 * <p>This class is for advanced usage and reflects the underlying API directly.
 */
@Generated("by gapic-generator-java")
public class GrpcTextToSpeechStub extends TextToSpeechStub {
  private static final MethodDescriptor<ListVoicesRequest, ListVoicesResponse>
      listVoicesMethodDescriptor =
          MethodDescriptor.<ListVoicesRequest, ListVoicesResponse>newBuilder()
              .setType(MethodDescriptor.MethodType.UNARY)
              .setFullMethodName("google.cloud.texttospeech.v1.TextToSpeech/ListVoices")
              .setRequestMarshaller(ProtoUtils.marshaller(ListVoicesRequest.getDefaultInstance()))
              .setResponseMarshaller(ProtoUtils.marshaller(ListVoicesResponse.getDefaultInstance()))
              .build();

  private static final MethodDescriptor<SynthesizeSpeechRequest, SynthesizeSpeechResponse>
      synthesizeSpeechMethodDescriptor =
          MethodDescriptor.<SynthesizeSpeechRequest, SynthesizeSpeechResponse>newBuilder()
              .setType(MethodDescriptor.MethodType.UNARY)
              .setFullMethodName("google.cloud.texttospeech.v1.TextToSpeech/SynthesizeSpeech")
              .setRequestMarshaller(
                  ProtoUtils.marshaller(SynthesizeSpeechRequest.getDefaultInstance()))
              .setResponseMarshaller(
                  ProtoUtils.marshaller(SynthesizeSpeechResponse.getDefaultInstance()))
              .build();

  private final UnaryCallable<ListVoicesRequest, ListVoicesResponse> listVoicesCallable;
  private final UnaryCallable<SynthesizeSpeechRequest, SynthesizeSpeechResponse>
      synthesizeSpeechCallable;

  private final BackgroundResource backgroundResources;
  private final GrpcOperationsStub operationsStub;
  private final GrpcStubCallableFactory callableFactory;

  public static final GrpcTextToSpeechStub create(TextToSpeechStubSettings settings)
      throws IOException {
    return new GrpcTextToSpeechStub(settings, ClientContext.create(settings));
  }

  public static final GrpcTextToSpeechStub create(ClientContext clientContext) throws IOException {
    return new GrpcTextToSpeechStub(TextToSpeechStubSettings.newBuilder().build(), clientContext);
  }

  public static final GrpcTextToSpeechStub create(
      ClientContext clientContext, GrpcStubCallableFactory callableFactory) throws IOException {
    return new GrpcTextToSpeechStub(
        TextToSpeechStubSettings.newBuilder().build(), clientContext, callableFactory);
  }

  /**
   * Constructs an instance of GrpcTextToSpeechStub, using the given settings. This is protected so
   * that it is easy to make a subclass, but otherwise, the static factory methods should be
   * preferred.
   */
  protected GrpcTextToSpeechStub(TextToSpeechStubSettings settings, ClientContext clientContext)
      throws IOException {
    this(settings, clientContext, new GrpcTextToSpeechCallableFactory());
  }

  /**
   * Constructs an instance of GrpcTextToSpeechStub, using the given settings. This is protected so
   * that it is easy to make a subclass, but otherwise, the static factory methods should be
   * preferred.
   */
  protected GrpcTextToSpeechStub(
      TextToSpeechStubSettings settings,
      ClientContext clientContext,
      GrpcStubCallableFactory callableFactory)
      throws IOException {
    this.callableFactory = callableFactory;
    this.operationsStub = GrpcOperationsStub.create(clientContext, callableFactory);

    GrpcCallSettings<ListVoicesRequest, ListVoicesResponse> listVoicesTransportSettings =
        GrpcCallSettings.<ListVoicesRequest, ListVoicesResponse>newBuilder()
            .setMethodDescriptor(listVoicesMethodDescriptor)
            .build();
    GrpcCallSettings<SynthesizeSpeechRequest, SynthesizeSpeechResponse>
        synthesizeSpeechTransportSettings =
            GrpcCallSettings.<SynthesizeSpeechRequest, SynthesizeSpeechResponse>newBuilder()
                .setMethodDescriptor(synthesizeSpeechMethodDescriptor)
                .build();

    this.listVoicesCallable =
        callableFactory.createUnaryCallable(
            listVoicesTransportSettings, settings.listVoicesSettings(), clientContext);
    this.synthesizeSpeechCallable =
        callableFactory.createUnaryCallable(
            synthesizeSpeechTransportSettings, settings.synthesizeSpeechSettings(), clientContext);

    this.backgroundResources =
        new BackgroundResourceAggregation(clientContext.getBackgroundResources());
  }

  public GrpcOperationsStub getOperationsStub() {
    return operationsStub;
  }

  @Override
  public UnaryCallable<ListVoicesRequest, ListVoicesResponse> listVoicesCallable() {
    return listVoicesCallable;
  }

  @Override
  public UnaryCallable<SynthesizeSpeechRequest, SynthesizeSpeechResponse>
      synthesizeSpeechCallable() {
    return synthesizeSpeechCallable;
  }

  @Override
  public final void close() {
    try {
      backgroundResources.close();
    } catch (RuntimeException e) {
      throw e;
    } catch (Exception e) {
      throw new IllegalStateException("Failed to close resource", e);
    }
  }

  @Override
  public void shutdown() {
    backgroundResources.shutdown();
  }

  @Override
  public boolean isShutdown() {
    return backgroundResources.isShutdown();
  }

  @Override
  public boolean isTerminated() {
    return backgroundResources.isTerminated();
  }

  @Override
  public void shutdownNow() {
    backgroundResources.shutdownNow();
  }

  @Override
  public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException {
    return backgroundResources.awaitTermination(duration, unit);
  }
}


text:
bool AES_CCM_Encrypt(COSE_Encrypt * pcose, int TSize, int LSize, int KSize, byte * pbAuthData, int cbAuthData)
{
	NTSTATUS err;
	BCRYPT_ALG_HANDLE hAlg = NULL;
	BCRYPT_KEY_DATA_BLOB_HEADER * pHdr = NULL;
	BCRYPT_KEY_HANDLE hKey = NULL;
	BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO authInfo = { 0 };
	byte rgbTag[16];
	int cbOut;
	byte * pbOut = NULL;

	err = BCryptOpenAlgorithmProvider(&hAlg, "AES_CCM", NULL, 0);
	if (err != 0) {
	error:
		if (pbOut != NULL) free(pbOut);
		if (pHdr != NULL) free(pHdr);
		if (hKey != NULL) BCryptDestroyKey(hKey);
		if (hAlg != NULL) BCryptCloseAlgorithmProvider(hAlg, 0);
		return false;
	}

	pHdr = (BCRYPT_KEY_DATA_BLOB_HEADER *)malloc(sizeof(*pHdr) + KSize / 8);
	if (pHdr == NULL) goto error;
	pHdr->dwMagic = BCRYPT_KEY_DATA_BLOB_MAGIC;
	pHdr->dwVersion = BCRYPT_KEY_DATA_BLOB_VERSION1;
	pHdr->cbKeyData = KSize / 8;
	memcpy(&pHdr[1], pcose->pbKey, pcose->cbKey);

	err = BCryptImportKey(hAlg, NULL, BCRYPT_KEY_DATA_BLOB, &hKey, NULL, 0, pHdr, (sizeof(*pHdr) + KSize / 8), 0);
	if (err != 0) goto error;

	BCRYPT_INIT_AUTH_MODE_INFO(authInfo);
	authInfo.pbNonce = pcose->pbIV;
	authInfo.cbNonce = pcose->cbIV;
	authInfo.pbAuthData = pbAuthData;
	authInfo.cbAuthData = cbAuthData;
	authInfo.pbTag = rgbTag;
	authInfo.cbTag = TSize / 8;
	authInfo.pbMacContext = NULL;

	cbOut = pcose->cbContent + TSize / 8;
	pbOut = (byte *)malloc(cbOut);
	if (pbOut == NULL) goto error;

	err = BCryptEncrypt(hKey, pcose->pbContent, pcose->cbContent, &authInfo, NULL, 0, pbOut, cbOut, 0, 0);
	if (err != 0) goto error;

	memcpy(&pbOut[pcose->cbContent], rgbTag, TSize / 8);

	cn_cbor_mapput_int(pcose->m_message.m_cbor, COSE_Header_Ciphertext, cn_cbor_data_create(pbOut, cbOut, NULL), NULL);

	return true;
}

#endif // USE_BCRYPT


text:
package org.topbraid.jenax.progress;

/**
 * Inspired by the Eclipse IProgressMonitor, this interface supports monitoring long-running processes with intermediate
 * status messages and the ability to cancel.
 *
 * @author Holger Knublauch
 */
public interface ProgressMonitor {

	/**
	 * Typically used by the (long-running) process to determine whether the user has requested cancellation.
	 * The process should then find a suitable, clean termination.
	 * @return true  if cancel was requested
	 */
	boolean isCanceled();

	/**
	 * Informs the progress monitor that a new task has been started, with a given number of expected steps.
	 * A UI connected to the ProgressMonitor would typically display something like a progress bar and the task name.
	 * @param label  the name of the task
	 * @param totalWork  the number of steps (see worked) that is expected to be needed to complete the task
	 */
	void beginTask(String label, int totalWork);

	/**
	 * Informs the progress monitor that all is completed.
	 */
	void done();

	/**
	 * Typically called from a parallel thread triggered by the user, this informs the progress monitor that it needs to
	 * return true for isCanceled.
	 * Once a process has been canceled, it should not be un-canceled.
	 * @param value  true if canceled
	 */
	void setCanceled(boolean value);

	/**
	 * Changes the name or label of the current task.
	 * @param value
	 */
	void setTaskName(String value);

	/**
	 * Sets the label that serves as sub-task, typically printed under the main task name.
	 * @param label  the subtask label
	 */
	void subTask(String label);

	/**
	 * Informs the progress monitor that one or more steps have been completed towards the current task (see beginTask).
	 * @param amount  the number of steps completed
	 */
	void worked(int amount);
}


text:
class ProjectsSweeper < ActionController::Caching::Sweeper

  include CommonSweepers

  observe Project

  def before_save(p)
    if (p.changed.include?("avatar_id"))
      expire_all_favourite_fragments
    end
  end

  def after_create(p)

  end

  def after_update(p)

  end

  def after_destroy(p)

  end

end


text:
  <cr-button-link
    type="button"
    buttonClass="btn-secondary"
    routerLink="/courses/new"
    [buttonSize]="'medium'">Add course</cr-button-link>


text:
(function() {
  'use strict';

  /**
   * @ngdoc module
   * @name material.components.fabToolbar
   */
  angular
    // Declare our module
    .module('material.components.fabToolbar', [
      'material.core',
      'material.components.fabShared',
      'material.components.fabActions'
    ])

    // Register our directive
    .directive('mdFabToolbar', MdFabToolbarDirective)

    // Register our custom animations
    .animation('.md-fab-toolbar', MdFabToolbarAnimation)

    // Register a service for the animation so that we can easily inject it into unit tests
    .service('mdFabToolbarAnimation', MdFabToolbarAnimation);

  /**
   * @ngdoc directive
   * @name mdFabToolbar
   * @module material.components.fabToolbar
   *
   * @restrict E
   *
   * @description
   *
   * The `<md-fab-toolbar>` directive is used to present a toolbar of elements (usually `<md-button>`s)
   * for quick access to common actions when a floating action button is activated (via click or
   * keyboard navigation).
   *
   * You may also easily position the trigger by applying one one of the following classes to the
   * `<md-fab-toolbar>` element:
   *  - `md-fab-top-left`
   *  - `md-fab-top-right`
   *  - `md-fab-bottom-left`
   *  - `md-fab-bottom-right`
   *
   * These CSS classes use `position: absolute`, so you need to ensure that the container element
   * also uses `position: absolute` or `position: relative` in order for them to work.
   *
   * @usage
   *
   * <hljs lang="html">
   * <md-fab-toolbar md-direction='left'>
   *   <md-fab-trigger>
   *     <md-button aria-label="Add..."><md-icon md-svg-src="/img/icons/plus.svg"></md-icon></md-button>
   *   </md-fab-trigger>
   *
   *   <md-toolbar>
   *    <md-fab-actions>
   *      <md-button aria-label="Add User">
   *        <md-icon md-svg-src="/img/icons/user.svg"></md-icon>
   *      </md-button>
   *
   *      <md-button aria-label="Add Group">
   *        <md-icon md-svg-src="/img/icons/group.svg"></md-icon>
   *      </md-button>
   *    </md-fab-actions>
   *   </md-toolbar>
   * </md-fab-toolbar>
   * </hljs>
   *
   * @param {string} md-direction From which direction you would like the toolbar items to appear
   * relative to the trigger element. Supports `left` and `right` directions.
   * @param {expression=} md-open Programmatically control whether or not the toolbar is visible.
   */
  function MdFabToolbarDirective() {
    return {
      restrict: 'E',
      transclude: true,
      template: '
' +
      '

' +
      '
',

      scope: {
        direction: '@?mdDirection',
        isOpen: '=?mdOpen'
      },

      bindToController: true,
      controller: 'MdFabController',
      controllerAs: 'vm',

      link: link
    };

    function link(scope, element, attributes) {
      // Add the base class for animations
      element.addClass('md-fab-toolbar');

      // Prepend the background element to the trigger's button
      element.find('md-fab-trigger').find('button')
        .prepend('

');
    }
  }

  /**
   * @ngInject
   */
  function MdFabToolbarAnimation($window) {

    function runAnimation(element, className, done) {
      // If no className was specified, don't do anything
      if (!className) {
        return;
      }

      var el = element[0];
      var ctrl = element.controller('mdFabToolbar');

      // Grab the relevant child elements
      var backgroundElement = el.querySelector('.md-fab-toolbar-background');
      var triggerElement = el.querySelector('md-fab-trigger button');
      var toolbarElement = el.querySelector('md-toolbar');
      var iconElement = el.querySelector('md-fab-trigger button md-icon');
      var actions = element.find('md-fab-actions').children();

      // If we have both elements, use them to position the new background
      if (triggerElement && backgroundElement) {
        // Get our variables
        var color = $window.getComputedStyle(triggerElement).getPropertyValue('background-color');
        var width = el.offsetWidth;
        var height = el.offsetHeight;

        // Make it twice as big as it should be since we scale from the center
        var scale = 2 * (width / triggerElement.offsetWidth);

        // Set some basic styles no matter what animation we're doing
        backgroundElement.style.backgroundColor = color;
        backgroundElement.style.borderRadius = width + 'px';

        // If we're open
        if (ctrl.isOpen) {
          // Turn on toolbar pointer events when closed
          toolbarElement.style.pointerEvents = 'inherit';

          backgroundElement.style.width = triggerElement.offsetWidth + 'px';
          backgroundElement.style.height = triggerElement.offsetHeight + 'px';
          backgroundElement.style.transform = 'scale(' + scale + ')';

          // Set the next close animation to have the proper delays
          backgroundElement.style.transitionDelay = '0ms';
          iconElement && (iconElement.style.transitionDelay = '.3s');

          // Apply a transition delay to actions
          angular.forEach(actions, function(action, index) {
            action.style.transitionDelay = (actions.length - index) * 25 + 'ms';
          });
        } else {
          // Turn off toolbar pointer events when closed
          toolbarElement.style.pointerEvents = 'none';

          // Scale it back down to the trigger's size
          backgroundElement.style.transform = 'scale(1)';

          // Reset the position
          backgroundElement.style.top = '0';

          if (element.hasClass('md-right')) {
            backgroundElement.style.left = '0';
            backgroundElement.style.right = null;
          }

          if (element.hasClass('md-left')) {
            backgroundElement.style.right = '0';
            backgroundElement.style.left = null;
          }

          // Set the next open animation to have the proper delays
          backgroundElement.style.transitionDelay = '200ms';
          iconElement && (iconElement.style.transitionDelay = '0ms');

          // Apply a transition delay to actions
          angular.forEach(actions, function(action, index) {
            action.style.transitionDelay = 200 + (index * 25) + 'ms';
          });
        }
      }
    }

    return {
      addClass: function(element, className, done) {
        runAnimation(element, className, done);
        done();
      },

      removeClass: function(element, className, done) {
        runAnimation(element, className, done);
        done();
      }
    };
  }
})();


text:
package uk.ac.ebi.eva.pipeline.parameters.validation.step;

import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersInvalidException;
import org.springframework.batch.core.JobParametersValidator;
import org.springframework.batch.core.job.CompositeJobParametersValidator;
import org.springframework.batch.core.job.DefaultJobParametersValidator;

import uk.ac.ebi.eva.pipeline.parameters.JobParametersNames;
import uk.ac.ebi.eva.pipeline.parameters.validation.ConfigRestartabilityAllowValidator;
import uk.ac.ebi.eva.pipeline.parameters.validation.DbCollectionsFeaturesNameValidator;
import uk.ac.ebi.eva.pipeline.parameters.validation.DbNameValidator;
import uk.ac.ebi.eva.pipeline.parameters.validation.OptionalValidator;

import java.util.Arrays;
import java.util.List;

/**
 * Validates the job parameters necessary to execute an {@link uk.ac.ebi.eva.pipeline.jobs.steps.GeneLoaderStep}
 */
public class IndexesGeneratorStepParametersValidator extends DefaultJobParametersValidator {

    public IndexesGeneratorStepParametersValidator() {
        super(new String[]{JobParametersNames.DB_COLLECTIONS_FEATURES_NAME,
                           JobParametersNames.DB_NAME},
                new String[]{});
    }

    @Override
    public void validate(JobParameters parameters) throws JobParametersInvalidException {
        super.validate(parameters);
        compositeJobParametersValidator().validate(parameters);
    }

    private CompositeJobParametersValidator compositeJobParametersValidator() {
        final List<JobParametersValidator> jobParametersValidators = Arrays.asList(
                new DbCollectionsFeaturesNameValidator(),
                new DbNameValidator(),
                new OptionalValidator(new ConfigRestartabilityAllowValidator(),
                                      JobParametersNames.CONFIG_RESTARTABILITY_ALLOW)
        );

        CompositeJobParametersValidator compositeJobParametersValidator = new CompositeJobParametersValidator();
        compositeJobParametersValidator.setValidators(jobParametersValidators);
        return compositeJobParametersValidator;
    }

}


text:
Connection::Connection(const Connection& connection)
	:	m_Weight(connection.m_Weight),
		m_Delta(connection.m_Delta),
		m_SourceNeuronIndex(connection.m_SourceNeuronIndex)
{
	initProperties();
}

Connection::Connection(unsigned sourceNeuronIndex) : m_SourceNeuronIndex(sourceNeuronIndex) {
	initProperties();
}

void Connection::initProperties() {
	this->Weight.set(&Connection::_setWeight, this);
	this->Weight.get(&Connection::_getWeight, this);
	this->Delta.set(&Connection::_setDelta, this);
	this->Delta.get(&Connection::_getDelta, this);
	this->SourceNeuronIndex.set(&Connection::_setSourceNeuronIndex, this);
	this->SourceNeuronIndex.get(&Connection::_getSourceNeuronIndex, this);
}

double const Connection::_getWeight()
{
	return this->m_Weight;
}

void Connection::_setWeight(double const value)
{
	this->m_Weight = value;
}

double const Connection::_getDelta()
{
	return this->m_Delta;
}

void Connection::_setDelta(double const value)
{
	this->m_Delta = value;
}

unsigned const Connection::_getSourceNeuronIndex()
{
	return this->m_SourceNeuronIndex;
}

void Connection::_setSourceNeuronIndex(unsigned const value)
{
	this->m_SourceNeuronIndex = value;
}


text:
```BASH
cmake CMakeList.txt
make
./factory_method
```

##### Using CLion
Import this directory


text:
/**
 *
 */
package org.ovirt.engine.extensions.aaa.builtin.kerberosldap;

import java.security.PrivilegedAction;
import java.util.Properties;

import javax.naming.directory.SearchControls;
import javax.security.auth.Subject;
import javax.security.auth.login.LoginContext;

import org.ovirt.engine.extensions.aaa.builtin.kerberosldap.utils.ldap.LdapProviderType;
import org.springframework.ldap.core.NameClassPairCallbackHandler;
import org.springframework.ldap.core.support.DirContextAuthenticationStrategy;
import org.springframework.ldap.core.support.LdapContextSource;

/**
 *
 */
public class GSSAPILdapTemplateWrapper extends LDAPTemplateWrapper {

    private LoginContext loginContext;

    public GSSAPILdapTemplateWrapper(Properties configuration,
            LdapContextSource contextSource,
            String userName,
            String password,
            String path) {
        super(configuration, contextSource, userName, password, path);
    }

    /**
     *
     */

    /*
     * (non-Javadoc)
     *
     * @see
     * org.ovirt.engine.core.builtin.extensions.aaa.ldap..LDapTemplateWrapper#search(java.lang.String
     * , java.lang.String, javax.naming.directory.SearchControls,
     * org.springframework.ldap.core.NameClassPairCallbackHandler)
     */
    @Override
    public void search(String baseDN, String filter, String displayFilter, SearchControls searchControls, NameClassPairCallbackHandler handler) {
        Subject.doAs(loginContext.getSubject(), new SearchAction(baseDN, filter, displayFilter, searchControls, handler));

    }

    private class SearchAction implements PrivilegedAction<NameClassPairCallbackHandler> {

        private String baseDN;
        private String filter;
        private String displayFilter;
        private SearchControls searchControls;
        private NameClassPairCallbackHandler handler;

        public SearchAction(String baseDN, String filter, String displayFilter, SearchControls searchControls,
                            NameClassPairCallbackHandler handler) {
            this.baseDN = baseDN;
            this.filter = filter;
            this.displayFilter = displayFilter;
            this.searchControls = searchControls;
            this.handler = handler;
        }

        @Override
        public NameClassPairCallbackHandler run() {
            return pagedSearch(baseDN, filter, displayFilter, searchControls, handler);
        }

    }

    @Override
    protected DirContextAuthenticationStrategy buildContextAuthenticationStategy() {
        return new GSSAPIDirContextAuthenticationStrategy(configuration, userName, password);
    }

    @Override
    public void useAuthenticationStrategy() throws AuthenticationResultException {
        super.useAuthenticationStrategy();
        GSSAPIDirContextAuthenticationStrategy strategy = (GSSAPIDirContextAuthenticationStrategy) authStrategy;
        strategy.authenticate();
        loginContext = strategy.getLoginContext();

    }

    @Override
    public void adjustUserName(LdapProviderType ldapProviderType) {
        // No manipulation on user name is required, in contrast to SIMPLE
        // authentication

    }

    @Override
    protected void setCredentialsOnContext() {
        // Does nothing - credentials are used by JAAS
    }

}


text:
//  DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
//
//   Copyright 2016-2018 Pascal ECHEMANN.
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

import {SessionContext, JsletContext, SecurityConstraint, Session,
        SessionOwner, SessionError, SessionErrorType, SecurityContext,
        StaticResources, SessionId, AuthenticationError} from "jec-exchange";
import * as express from "express";
import {HttpService} from "../services/http/HttpService";
import {ContextRootUtil} from "../util/contextroot/ContextRootUtil";
import {ContextRootData} from "../util/contextroot/ContextRootData";
import {DomainConnector} from "../domains/connectors/DomainConnector";
import {DomainContainer} from "../domains/containers/DomainContainer";
import {UrlUtils} from "../util/url/UrlUtils";
import {HttpListener} from "../services/http/listeners/HttpListener";
import {DomainConnectorManager} from "./DomainConnectorManager";
import {ResourceProxy} from "../services/http/proxy/ResourceProxy";
import {DomainState} from "../domains/containers/DomainState";
import {SessionUtil} from "../security/session/utils/SessionUtil";
import {HttpLocalProperties} from "../services/http/utils/HttpLocalProperties";
import {SessionIdUtil} from "../security/session/utils/SessionIdUtil";
import {UrlStringsEnum, HttpStatusCode} from "jec-commons";
import {BasicAuthenticationError} from "../security/session/errors/BasicAuthenticationError";

/**
 * The manager for secured session accesses over the current GlassCat container.
 */
export class SecurityManager {

  //////////////////////////////////////////////////////////////////////////////
  // Constructor function
  //////////////////////////////////////////////////////////////////////////////

  /**
   * Creates a new SecurityManager instance.
   */
  constructor() {
    this.init();
  }

  //////////////////////////////////////////////////////////////////////////////
  // Private properties
  //////////////////////////////////////////////////////////////////////////////

  /**
   * The reference to the ContextRootUtil instance for this
   * manager.
   */
  private _contextRootUtil:ContextRootUtil = null;

  /**
   * The reference to the DomainConnectorManager object for this
   * manager.
   */
  private _connectorManager:DomainConnectorManager = null;

  //////////////////////////////////////////////////////////////////////////////
  // Private methods
  //////////////////////////////////////////////////////////////////////////////

  /**
   * Initializes this security manager.
   */
  private init():void {
    this._contextRootUtil = new ContextRootUtil();
  }

  /**
   * Returns a boolean value that inicates whether the specified session has
   * security access rights for the current HTTP transcation
   * (true), or not (false).
   *
   * @param {Session} session the session to validate.
   * @param {SecurityConstraint} constraint the security constraints specified
   *                                        for the current HTTP transction.
   * @return {boolean} true whether the session is authorized for
   *                   the current transaction; false otherwise.
   */
  private validateSession(session:Session,
                          constraint:SecurityConstraint):boolean {
    let isValid:boolean =
                   session ? session.sessionOwner.isGranted(constraint) : false;
    return isValid;
  }

  /**
   * Returns a boolean value that inicates whether the current HTTP transaction
   * processes static resources (true), or not (false).
   *
   * @param {ContextRootData} crd the context root data for the current HTTP
   *                              transaction.
   * @param {SecurityContext} context the security context related to the
   *                                  the current HTTP transaction.
   * @param {HttpLocalProperties} properties the reference to the HTTP local
   *                                         properties for the current HTTP
   *                                         transaction.
   * @return {boolean} true whether current HTTP transaction
   *                   processes static resources; false
   *                   otherwise.
   */
  private isStaticResource(crd:ContextRootData,
                           context:SecurityContext,
                           properties:HttpLocalProperties):boolean {
    let result:boolean = false;
    let staticResources:StaticResources =
                              context.getStaticResources(properties.trimmedUrl);
    if(staticResources) {
      properties.isStatic = result = true;
    }
    return result;
  }

  //////////////////////////////////////////////////////////////////////////////
  // Public methods
  //////////////////////////////////////////////////////////////////////////////

  /**
   * Sets the reference to the DomainConnectorManager instance for this
   * security manager. This method is called by the kernel.
   *
   * @param {DomainConnectorManager} connectorManager the reference to the
   *                                         DomainConnectorManager
   *                                                  instance.
   */
  public setDomainConnectorManager(manager:DomainConnectorManager):void {
    this._connectorManager = manager;
  }

  /**
   * Returns a boolean that indicates whether the transaction is authorized
   * (true), or nor (false).
   *
   * @param {express.Request} req the HTTP request for the current HTTP
   *                              transaction.
   * @param {express.Response} res the HTTP response for the current HTTP
   *                               transaction.
   * @param {HttpService} service the HTTP service that intercepts the current
   *                              HTTP transaction.
   * @param {Function} result the callback method used to handle the result of
   *                          the operation. When the operation has failed,
   *                          the result() methods takes a
   *                          AuthenticationError object as
   *                          parameter.
   */
  public validateTransaction(req:express.Request, res:express.Response,
                             service:HttpService,
                             result:(error?:AuthenticationError)=>any):void {
    let isSecuredTransaction:boolean = true;
    let properties:HttpLocalProperties = res.locals.properties;
    let crd:ContextRootData = properties.contextRootData;
    let listener:HttpListener = service.getHttpListener();
    let connector:DomainConnector = properties.connector;
    let redirectUrl:string = null;
    let jsletContext:JsletContext = null;
    let securityConstraint:SecurityConstraint = null;
    let session:Session = null;
    let err:AuthenticationError = null;
    let sessionId:SessionId = null;
    let errorStatusCode:HttpStatusCode = (0 as HttpStatusCode);
    if(crd.containsNestedResource) {
      crd.newPath = ResourceProxy.getInstance().getProxyPath(
        req.url, listener, this._connectorManager
      );
    } else if(properties.containerState === DomainState.STATEFUL) {
      if(!crd.needsRedirection) {
        if(!connector || connector.getServer() !== listener.getServer()) {
          isSecuredTransaction = false;
          errorStatusCode = HttpStatusCode.NOT_FOUND;
        } else {
          jsletContext = connector.getContainer().getJsletContext();
          securityConstraint = jsletContext.getSecurityContext()
                                  .getSecurityConstraint(properties.trimmedUrl);
          if(securityConstraint) {
            session = jsletContext.getSessionContext()
                                  .getSession(properties.sessionId);
            isSecuredTransaction = this.validateSession(
              session, securityConstraint
            );
            if(!isSecuredTransaction) {
              errorStatusCode = HttpStatusCode.UNAUTHORIZED;
            }
          }
        }
      }
    }
    if(!isSecuredTransaction) {
      sessionId = properties.sessionId;
      if(!sessionId.authurl) {
        sessionId.authurl = req.url;
        SessionUtil.setSessionCookie(res, sessionId, service);
      }
      err = new BasicAuthenticationError(errorStatusCode);
    }
    result(err);
  }

  /**
   * Returns the header security parameters for the specified HTTP service.
   *
   * @param {HttpService} service the HTTP service for which to return the
   *                              header security parameters.
   */
  public getHeaderSecurityParams(service:HttpService):string[] {
    let secParams:string[] = new Array<string>();
    return secParams;
  }

  /**
   * Checks whether the EJP session exists on the specified HTTP request; if the
   * EJP session does not exist, creates and attaches a new EJP session to the
   * request, regarding the current state of the domain container.
   *
   * @param {HttpService} service the HTTP service that intercepts the current
   *                              HTTP transaction.
   * @param {express.Request} req the HTTP request for the current HTTP
   *                              transaction.
   * @param {express.Response} res the HTTP response for the current HTTP
   *                               transaction.
   * @param {Function} result the callback method used to handle the result of
   *                          the operation. When the operation has failed,
   *                          the result() methods takes a
   *                          SessionError object as parameter.
   */
  public processSession(service:HttpService,
                        req:express.Request, res:express.Response,
                        result:(error?:SessionError)=>any):void {
    let sessionId:SessionId = null;
    let connector:DomainConnector = null;
    let container:DomainContainer = null;
    let jsletContext:JsletContext = null;
    let sessionContext:SessionContext = null;
    let isStaticUrl:boolean = false;
    let ctxRootRef:string = null;
    let crd:ContextRootData = this._contextRootUtil.extractContextRoot(req);
    let properties:HttpLocalProperties = res.locals.properties;
    let cookies:any = null;
    let errorType:SessionErrorType = null;
    properties.contextRootData = crd;
    connector = this._connectorManager.getDomainConnector(crd.contextRoot);
    properties.connector = connector;
    properties.sessionId = null;
    if(connector) {
      container = connector.getContainer();
      ctxRootRef = UrlStringsEnum.SLASH + connector.getContextRoot();
      properties.trimmedUrl = UrlUtils.getInstance()
                                      .trimContextRoot(req.url, ctxRootRef);
      if(container.getState() === DomainState.STATEFUL) {
        properties.containerState = DomainState.STATEFUL;
        properties.contextRootRef = ctxRootRef;
        jsletContext = container.getJsletContext();
        sessionContext = jsletContext.getSessionContext();
        isStaticUrl = this.isStaticResource(
                              crd,
                              jsletContext.getSecurityContext(),
                              properties
                            );
        if(isStaticUrl) result();
        else {
          cookies = req[SessionIdUtil.COOKIES];
          sessionId = SessionIdUtil.parseSessionIdCookie(cookies);
          if(!sessionId) {
            sessionId = sessionContext.initSessionId();
            SessionUtil.setSessionCookie(res, sessionId, service);
            properties.sessionId = sessionId;
            result();
          } else {
            properties.sessionId = sessionId;
            sessionContext.loadSession(
              sessionId,
              (err:SessionError) => {
                if(err) {
                  errorType = err.getErrorType();
                  // Session does not exists => owner is not authenticated yet:
                   if(errorType === SessionErrorType.INVALID_SESSION_ID) {
                     result();
                   } else {
                     properties.redirectUrl = sessionContext.getErrorUrl();
                     result(err);
                   }
                } else result();
              }
            );
          }
        }
      } else result();
    } else result();
  }
};