text:
@interface MOBRefreshTableView ()

@property (strong, nonatomic, readwrite) UIRefreshControl *refreshControl;

@property (strong, nonatomic) UIView *infinityScrollView;
@property (strong, nonatomic) UIActivityIndicatorView *activityIndicator;

@end

@implementation MOBRefreshTableView

#pragma mark - PULL TO REFRESH

#pragma mark - Custom Accessors

- (BOOL)isRefreshing
{
    return self.refreshControl.isRefreshing;
}

#pragma mark - Actions

- (void)refresh
{
    [self.refreshDelegate tableViewDidRefresh:self];
}

#pragma mark - Public

- (void)addDefaultRefreshControl
{
    [self addCustomRefreshControl:[[UIRefreshControl alloc] init]];
}

- (void)addCustomRefreshControl:(UIRefreshControl *)refreshControl
{
    self.refreshControl = refreshControl;

    [refreshControl addTarget:self action:@selector(refresh) forControlEvents:UIControlEventValueChanged];

    [self addSubview:self.refreshControl];
    [self sendSubviewToBack:self.refreshControl];
}

- (void)removeRefreshControl
{
    [self.refreshControl removeFromSuperview];
    self.refreshControl = nil;
}

- (void)beginRefreshing
{
    [self.refreshControl beginRefreshing];
}

- (void)endRefreshing
{
    [self.refreshControl endRefreshing];
}

#pragma mark - INFINITY SCROLL

#pragma mark - Public

- (void)addDefaultInfinityScroll
{
    UIView *infinityScrollView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, 60.0f)];

    UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    spinner.color = [UIColor blackColor];
    spinner.hidesWhenStopped = NO;
    spinner.center = infinityScrollView.center;
    [infinityScrollView addSubview:spinner];

    [self addCustomInfinityScroll:infinityScrollView activityIndicator:spinner];
}

- (void)addCustomInfinityScroll:(UIView *)infinityScrollView activityIndicator:(UIActivityIndicatorView *)activityIndicator
{
    self.infinityScrollView = infinityScrollView;
    self.activityIndicator = activityIndicator;

    [self addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)removeInfinityScroll
{
    [self.infinityScrollView removeFromSuperview];
    self.infinityScrollView = nil;
    self.activityIndicator = nil;

    [self removeObserver:self forKeyPath:@"contentOffset"];
}

- (void)endInfinityScroll
{
    [self.infinityScrollView removeFromSuperview];
    [self.activityIndicator stopAnimating];

    UIEdgeInsets insets = self.contentInset;
    insets.bottom -= self.infinityScrollView.height;
    self.contentInset = insets;
}

#pragma mark - Private

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"contentOffset"])
    {
        CGPoint contentOffset = [[change valueForKey:NSKeyValueChangeNewKey] CGPointValue];
        CGFloat y = self.contentSize.height - self.bounds.size.height;
        if (y > 0 && contentOffset.y >= y)
        {
            if (self.infinityScrollView.superview == nil)
            {
                self.infinityScrollView.center = self.center;
                self.infinityScrollView.y = self.contentSize.height;
                [self addSubview:self.infinityScrollView];
            }

            if (contentOffset.y >= (y + self.infinityScrollView.height) && !self.activityIndicator.isAnimating)
            {
                [self.activityIndicator startAnimating];

                UIEdgeInsets insets = self.contentInset;
                insets.bottom += self.infinityScrollView.height;
                self.contentInset = insets;

                [self.scrollInfinityDelegate tableViewDidRequestNextPage:self];
            }
        }
    }
}

@end


text:
/*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */
/*global define, brackets, window, $, Mustache */

define(function (require, exports, module) {
    "use strict";

    // Brackets modules
    var ProjectManager          = brackets.getModule("project/ProjectManager"),
        PreferencesDialogs      = brackets.getModule("preferences/PreferencesDialogs"),
        PreferencesManager      = brackets.getModule("preferences/PreferencesManager"),
        Commands                = brackets.getModule("command/Commands"),
        CommandManager          = brackets.getModule("command/CommandManager"),
        ExtensionUtils          = brackets.getModule("utils/ExtensionUtils"),
        AppInit                 = brackets.getModule("utils/AppInit"),
        Strings                 = brackets.getModule("strings"),
        SidebarView             = brackets.getModule("project/SidebarView"),
        Menus                   = brackets.getModule("command/Menus"),
        PopUpManager            = brackets.getModule("widgets/PopUpManager"),
        FileUtils               = brackets.getModule("file/FileUtils"),
        PlatformFileSystem      = brackets.getModule("file/PlatformFileSystem").PlatformFileSystem,
        ProjectsMenuTemplate    = require("hgn!htmlContent/projects-menu.html");

    var $dropdownToggle,
        $dropdown;

    var prefs = PreferencesManager.getPreferenceStorage(module);
    //TODO: Remove preferences migration code
    PreferencesManager.handleClientIdChange(prefs, "com.adobe.brackets.brackets-recent-projects");

    var MAX_PROJECTS = 20;

    /**
     * Get the stored list of recent projects, canonicalizing and updating paths as appropriate.
     */
    function getRecentProjects() {
        var recentProjects = prefs.getValue("recentProjects") || [],
            i;
        for (i = 0; i < recentProjects.length; i++) {
            recentProjects[i] = FileUtils.canonicalizeFolderPath(ProjectManager.updateWelcomeProjectPath(recentProjects[i]));
        }
        return recentProjects;
    }

    /**
     * Add a project to the stored list of recent projects, up to MAX_PROJECTS.
     */
    function add() {
        var root = FileUtils.canonicalizeFolderPath(ProjectManager.getProjectRoot().fullPath),
            recentProjects = getRecentProjects(),
            index = recentProjects.indexOf(root);
        if (index !== -1) {
            recentProjects.splice(index, 1);
        }
        recentProjects.unshift(root);
        if (recentProjects.length > MAX_PROJECTS) {
            recentProjects = recentProjects.slice(0, MAX_PROJECTS);
        }
        prefs.setValue("recentProjects", recentProjects);
    }

    /**
     * Check the list of items to see if any of them are hovered, and if so trigger a mouseenter.
     * Normally the mouseenter event handles this, but when a previous item is deleted and the next
     * item moves up to be underneath the mouse, we don't get a mouseenter event for that item.
     */
    function checkHovers(pageX, pageY) {
        $dropdown.children().each(function () {
            var offset = $(this).offset(),
                width  = $(this).outerWidth(),
                height = $(this).outerHeight();

            if (pageX >= offset.left && pageX <= offset.left + width &&
                    pageY >= offset.top && pageY <= offset.top + height) {
                $(".recent-folder-link", this).triggerHandler("mouseenter");
            }
        });
    }

    /**
     * Create the "delete" button that shows up when you hover over a project.
     */
    function renderDelete() {
        return $("

")
            .mouseup(function (e) {
                // Don't let the click bubble upward.
                e.stopPropagation();

                // Remove the project from the preferences.
                var recentProjects = getRecentProjects(),
                    index = recentProjects.indexOf($(this).parent().data("path")),
                    newProjects = [],
                    i;
                for (i = 0; i < recentProjects.length; i++) {
                    if (i !== index) {
                        newProjects.push(recentProjects[i]);
                    }
                }
                prefs.setValue("recentProjects", newProjects);
                $(this).closest("li").remove();
                checkHovers(e.pageX, e.pageY);

                if (newProjects.length === 1) {
                    $dropdown.find(".divider").remove();
                }
            });
    }

    /**
     * Close the dropdown.
     */
    function closeDropdown() {
        // Since we passed "true" for autoRemove to addPopUp(), this will
        // automatically remove the dropdown from the DOM. Also, PopUpManager
        // will call cleanupDropdown().
        if ($dropdown) {
            PopUpManager.removePopUp($dropdown);
        }
    }

    /**
     * Remove the various event handlers that close the dropdown. This is called by the
     * PopUpManager when the dropdown is closed.
     */
    function cleanupDropdown() {
        $("html").off("click", closeDropdown);
        $("#project-files-container").off("scroll", closeDropdown);
        $(SidebarView).off("hide", closeDropdown);
        $("#titlebar .nav").off("click", closeDropdown);
        $dropdown = null;
    }

    /**
     * Hide the delete button.
     */
    function hideDeleteButton() {
        $("#recent-folder-delete").remove();
    }

    /**
     * Show the delete button over a given target.
     */
    function showDeleteButton($target) {
        hideDeleteButton();
        renderDelete()
            .css("top", $target.position().top + 6)
            .appendTo($target);
    }

    /**
     * Adds the click and mouse enter/leave events to the dropdown
     */
    function _handleListEvents() {
        $dropdown.click(function (e) {
            var $link = $(e.target).closest("a"),
                id    = $link.attr("id"),
                path  = $link.data("path");

            if (path) {
                ProjectManager.openProject(path)
                    .fail(function () {
                        // Remove the project from the list only if it does not exist on disk
                        var recentProjects = getRecentProjects(),
                            index = recentProjects.indexOf(path);
                        if (index !== -1) {
                            PlatformFileSystem.requestNativeFileSystem(path,
                                function () {},
                                function () {
                                    recentProjects.splice(index, 1);
                                });
                        }
                    });
                closeDropdown();

            } else if (id === "open-folder-link") {
                CommandManager.execute(Commands.FILE_OPEN_FOLDER);
            }

        });

        $dropdown.find(".recent-folder-link")
            .mouseenter(function () {
                // Note: we can't depend on the event here because this can be triggered
                // manually from checkHovers().
                showDeleteButton($(this));
            })
            .mouseleave(function () {
                hideDeleteButton();
            });
    }

    /**
     * Parses the path and returns an object with the full path, the folder name and the path without the folder.
     * @param {string} path The full path to the folder.
     * @return {{path: string, folder: string, rest: string}}
     */
    function parsePath(path) {
        var lastSlash = path.lastIndexOf("/"), folder, rest;
        if (lastSlash === path.length - 1) {
            lastSlash = path.slice(0, path.length - 1).lastIndexOf("/");
        }
        if (lastSlash >= 0) {
            rest = " - " + (lastSlash ? path.slice(0, lastSlash) : "/");
            folder = path.slice(lastSlash + 1);
        } else {
            rest = "/";
            folder = path;
        }

        return {path: path, folder: folder, rest: rest};
    }

    /**
     * Create the list of projects in the dropdown menu.
     * @return {string} The html content
     */
    function renderList() {
        var recentProjects = getRecentProjects(),
            currentProject = FileUtils.canonicalizeFolderPath(ProjectManager.getProjectRoot().fullPath),
            templateVars   = {
                projectList : [],
                Strings     : Strings
            };

        recentProjects.forEach(function (root) {
            if (root !== currentProject) {
                templateVars.projectList.push(parsePath(root));
            }
        });

        return ProjectsMenuTemplate(templateVars);
    }

    /**
     * Show or hide the recent projects dropdown.
     * @param {$.Event} e The event object that triggered the toggling.
     */
    function toggle(e) {
        // If the dropdown is already visible, just return (so the root click handler on html
        // will close it).
        if ($dropdown) {
            return;
        }

        Menus.closeAll();

        // TODO: Can't just use Bootstrap 1.4 dropdowns for this since they're hard-coded to
        // assume that the dropdown is inside a top-level menubar created using
s.
        // Have to do this stopProp to avoid the html click handler from firing when this returns.
        e.stopPropagation();

        $dropdown = $(renderList());

        var toggleOffset = $dropdownToggle.offset();
        $dropdown
            .css({
                left: toggleOffset.left,
                top: toggleOffset.top + $dropdownToggle.outerHeight()
            })
            .appendTo($("body"));

        PopUpManager.addPopUp($dropdown, cleanupDropdown, true);

        // TODO: should use capture, otherwise clicking on the menus doesn't close it. More fallout
        // from the fact that we can't use the Boostrap (1.4) dropdowns.
        $("html").on("click", closeDropdown);

        // Hide the menu if the user scrolls in the project tree. Otherwise the Lion scrollbar
        // overlaps it.
        // TODO: This duplicates logic that's already in ProjectManager (which calls Menus.close()).
        // We should fix this when the popup handling is centralized in PopupManager, as well
        // as making Esc close the dropdown. See issue #1381.
        $("#project-files-container").on("scroll", closeDropdown);

        // Hide the menu if the sidebar is hidden.
        // TODO: Is there some more general way we could handle this for dropdowns?
        $(SidebarView).on("hide", closeDropdown);

        // Hacky: if we detect a click in the menubar, close ourselves.
        // TODO: again, we should have centralized popup management.
        $("#titlebar .nav").on("click", closeDropdown);

        _handleListEvents();
    }

    // Initialize extension
    AppInit.appReady(function () {
        ExtensionUtils.loadStyleSheet(module, "styles/styles.css");

        $(ProjectManager).on("projectOpen", add);
        $(ProjectManager).on("beforeProjectClose", add);
    });

    AppInit.htmlReady(function () {
        $("#project-title")
            .wrap("

")
            .after("");

        $dropdownToggle = $("#project-dropdown-toggle").click(toggle);
    });
});

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>Polymer ToolBar</title>
	<script src="bower_components/platform/platform.js"></script>
	<link rel="import"  href="bower_components/core-toolbar/core-toolbar.html">
	<link rel="import" href="bower_components/core-icon-button/core-icon-button.html">
	<link rel="import" href="bower_components/core-media-query/core-media-query.html">

	<style shim-shadowdom>
	 core-toolbar {
      background-color: #f9cccc;
    }
    </style>
</head>
<body resolved fullbleed>
	<core-toolbar>
	<core-icon-button icon="menu"></core-icon-button>
	<span flex>Componentizando Web</span>
	<core-icon-button icon="refresh"></core-icon-button>
	<core-icon-button icon="add"></core-icon-button>
</core-toolbar>
</body>
</html>


text:
<?php

/*
 * Created by tpay.com.
 * Date: 13.06.2017
 * Time: 17:05
 */

namespace tpayLibs\src\Dictionaries\Payments;

use tpayLibs\src\Dictionaries\FieldsConfigDictionary;

class CardFieldsDictionary
{
    /**
     * List of supported fields for card payment request
     * @var array
     */
    const REQUEST_FIELDS = array(
        /**
         * Transaction amount
         */
        FieldsConfigDictionary::AMOUNT => array(
            FieldsConfigDictionary::REQUIRED => true,
            FieldsConfigDictionary::VALIDATION => array(FieldsConfigDictionary::FLOAT),
        ),
        /**
         * Client name
         */
        'name' => array(
            FieldsConfigDictionary::REQUIRED => true,
            FieldsConfigDictionary::VALIDATION => array(
                FieldsConfigDictionary::STRING,
                FieldsConfigDictionary::MAXLENGTH_64
            ),
        ),
        /**
         * Client email
         */
        FieldsConfigDictionary::EMAIL => array(
            FieldsConfigDictionary::REQUIRED => true,
            FieldsConfigDictionary::VALIDATION => array(
                FieldsConfigDictionary::STRING,
                FieldsConfigDictionary::EMAIL_LIST
            ),
        ),
        /**
         * Sale description
         */
        'desc' => array(
            FieldsConfigDictionary::REQUIRED => true,
            FieldsConfigDictionary::VALIDATION => array(
                FieldsConfigDictionary::STRING,
                FieldsConfigDictionary::MAXLENGTH_128
            ),
        ),
        /**
         * Value from partner system
         */
        FieldsConfigDictionary::ORDER_ID => array(
            FieldsConfigDictionary::REQUIRED => false,
            FieldsConfigDictionary::VALIDATION => array(
                FieldsConfigDictionary::STRING,
                FieldsConfigDictionary::MAXLENGTH_40
            ),
        ),
        /**
         * 3ds return url enabled
         */
        'enable_pow_url' => array(
            FieldsConfigDictionary::REQUIRED => false,
            FieldsConfigDictionary::VALIDATION => array(FieldsConfigDictionary::INT),
        ),
        /**
         * 3ds success return url
         */
        'pow_url' => array(
            FieldsConfigDictionary::REQUIRED => false,
            FieldsConfigDictionary::VALIDATION => array(FieldsConfigDictionary::STRING),
        ),

        'card' => array(
            FieldsConfigDictionary::REQUIRED => false,
            FieldsConfigDictionary::VALIDATION => array(FieldsConfigDictionary::STRING),
        ),
        'method' => array(
            FieldsConfigDictionary::REQUIRED => true,
            FieldsConfigDictionary::VALIDATION => array(FieldsConfigDictionary::STRING),
        ),
        'sign' => array(
            FieldsConfigDictionary::REQUIRED => true,
            FieldsConfigDictionary::VALIDATION => array(FieldsConfigDictionary::STRING),
        ),
        'api_password' => array(
            FieldsConfigDictionary::REQUIRED => true,
            FieldsConfigDictionary::VALIDATION => array(FieldsConfigDictionary::STRING),
        ),
        /**
         * 3ds failure return url
         */
        'pow_url_blad' => array(
            FieldsConfigDictionary::REQUIRED => false,
            FieldsConfigDictionary::VALIDATION => array(FieldsConfigDictionary::STRING),
        ),
        /**
         * language
         */
        'language' => array(
            FieldsConfigDictionary::REQUIRED => false,
            FieldsConfigDictionary::VALIDATION => array(FieldsConfigDictionary::STRING),
        ),
        /**
         * Sale description
         */
        'currency' => array(
            FieldsConfigDictionary::REQUIRED => true,
            FieldsConfigDictionary::VALIDATION => array(
                FieldsConfigDictionary::INT,
                'maxlength_3'
            ),
        ),
        /**
         * If this parameter is present, card token will not be generated
         */
        'onetimer' => array(
            FieldsConfigDictionary::REQUIRED => false,
            FieldsConfigDictionary::TYPE => FieldsConfigDictionary::BOOLEAN,
            FieldsConfigDictionary::VALIDATION => array(FieldsConfigDictionary::BOOLEAN),
        ),
        /**
         * Module/integration name. Used for statistics.
         */
        'module' => BasicFieldsDictionary::REQUEST_FIELDS['module'],
    );

    /**
     * List of fields available in card payment response
     * @var array
     */
    const RESPONSE_FIELDS = array(
        /**
         * Method type
         */
        FieldsConfigDictionary::TYPE => array(
            FieldsConfigDictionary::REQUIRED => true,
            FieldsConfigDictionary::TYPE => FieldsConfigDictionary::STRING,
            FieldsConfigDictionary::VALIDATION => array(FieldsConfigDictionary::OPTIONS),
            FieldsConfigDictionary::OPTIONS => array('sale', 'refund', 'deregister'),
        ),
        /**
         * Merchant optional value
         */
        FieldsConfigDictionary::ORDER_ID => array(
            FieldsConfigDictionary::REQUIRED => true,
            FieldsConfigDictionary::TYPE => FieldsConfigDictionary::STRING,
            FieldsConfigDictionary::VALIDATION => array(
                FieldsConfigDictionary::STRING,
                FieldsConfigDictionary::MAXLENGTH_40
            )
        ),
        /**
         * Payment status
         */
        'status' => array(
            FieldsConfigDictionary::REQUIRED => true,
            FieldsConfigDictionary::TYPE => FieldsConfigDictionary::STRING,
            FieldsConfigDictionary::VALIDATION => array(FieldsConfigDictionary::OPTIONS),
            FieldsConfigDictionary::OPTIONS => array('correct', 'declined', 'done'),
        ),
        /**
         * Message checksum
         */
        'sign' => array(
            FieldsConfigDictionary::REQUIRED => true,
            FieldsConfigDictionary::TYPE => FieldsConfigDictionary::STRING,
            FieldsConfigDictionary::VALIDATION => array(
                FieldsConfigDictionary::STRING,
                FieldsConfigDictionary::MAXLENGTH_128,
                FieldsConfigDictionary::MINLENGTH_40
            )
        ),
        /**
         * Created sale/refund id
         */
        'sale_auth' => array(
            FieldsConfigDictionary::REQUIRED => true,
            FieldsConfigDictionary::TYPE => FieldsConfigDictionary::STRING,
            FieldsConfigDictionary::VALIDATION => array(
                FieldsConfigDictionary::STRING,
                FieldsConfigDictionary::MAXLENGTH_40
            )
        ),
        /**
         * Created client token
         */
        'cli_auth' => array(
            FieldsConfigDictionary::REQUIRED => false,
            FieldsConfigDictionary::TYPE => FieldsConfigDictionary::STRING,
            FieldsConfigDictionary::VALIDATION => array(
                FieldsConfigDictionary::STRING,
                FieldsConfigDictionary::MAXLENGTH_40
            )
        ),
        /**
         * Date of accounting/deregistering
         */
        'date' => array(
            FieldsConfigDictionary::REQUIRED => true,
            FieldsConfigDictionary::TYPE => FieldsConfigDictionary::STRING,
            FieldsConfigDictionary::VALIDATION => array(FieldsConfigDictionary::STRING)
        ),
        /**
         * carry value of 1 if account has test mode, otherwise parameter not sent
         */
        FieldsConfigDictionary::TEST_MODE => array(
            FieldsConfigDictionary::REQUIRED => false,
            FieldsConfigDictionary::TYPE => FieldsConfigDictionary::INT,
            FieldsConfigDictionary::VALIDATION => array(FieldsConfigDictionary::INT),
            FieldsConfigDictionary::OPTIONS => array(0, 1),
        ),
        /**
         * shortcut for client card number, eg ****5678
         */
        'card' => array(
            FieldsConfigDictionary::REQUIRED => true,
            FieldsConfigDictionary::TYPE => FieldsConfigDictionary::STRING,
            FieldsConfigDictionary::VALIDATION => array(FieldsConfigDictionary::STRING, 'maxlength_8', 'minlength_8')
        ),
        /**
         * shortcut for client card number, eg ****5678
         */
        'amount' => array(
            FieldsConfigDictionary::REQUIRED => true,
            FieldsConfigDictionary::TYPE => FieldsConfigDictionary::FLOAT,
            FieldsConfigDictionary::VALIDATION => array(FieldsConfigDictionary::FLOAT)
        ),
        /**
         * payment currency
         */
        FieldsConfigDictionary::CURRENCY => array(
            FieldsConfigDictionary::REQUIRED => true,
            FieldsConfigDictionary::TYPE => FieldsConfigDictionary::INT,
            FieldsConfigDictionary::VALIDATION => array(FieldsConfigDictionary::FLOAT, 'maxlength_3', 'minlength_3')
        ),
        'reason' => array(
            FieldsConfigDictionary::REQUIRED => false,
            FieldsConfigDictionary::TYPE => FieldsConfigDictionary::STRING,
            FieldsConfigDictionary::VALIDATION => array(FieldsConfigDictionary::STRING)
        ),
    );
}


text:
class PlosComments < Source
  def get_query_url(work)
    return {} unless work.doi =~ /^10.1371\/journal/

    url_private % { :doi => work.doi }
  end

  def parse_data(result, work, options={})
    return result if result[:error]

    related_works = get_related_works(result, work)
    replies = get_sum(result.fetch('data', []), 'totalNumReplies')
    total = related_works.length + replies
    events_url = related_works.length > 0 ? work.canonical_url : nil

    { works: related_works,
      events: {
        source: name,
        work: work.pid,
        discussed: total,
        total: total,
        events_url: events_url,
        extra: get_extra(result, work),
        days: get_events_by_day(related_works, work),
        months: get_events_by_month(related_works) } }
  end

  def get_related_works(result, work)
    Array(result['data']).map do |item|
      timestamp = get_iso8601_from_time(item.fetch("created", nil))

      { "author" => get_authors([item.fetch('creatorFormattedName', "")]),
        "title" => item.fetch('title', nil),
        "container-title" => 'PLOS Comments',
        "issued" => get_date_parts(timestamp),
        "timestamp" => timestamp,
        "URL" => work.doi_as_url,
        "type" => 'personal_communication',
        "related_works" => [{ "related_work" => work.pid,
                              "source" => name,
                              "relation_type" => "discusses" }] }
    end
  end

  def get_extra(result, work)
    Array(result['data']).map do |item|
      event_time = get_iso8601_from_time(item['created'])

      { event: item,
        event_time: event_time,
        event_url: nil,

        # the rest is CSL (citation style language)
        event_csl: {
          'author' => get_authors([item.fetch('creatorFormattedName', "")]),
          'title' => item.fetch('title', ""),
          'container-title' => 'PLOS Comments',
          'issued' => get_date_parts(event_time),
          'url' => work.doi_as_url,
          'type' => 'personal_communication' }
      }
    end
  end

  def config_fields
    [:url_private]
  end
end


text:
#include <unistd.h>
#include <errno.h>
#include <netinet/in.h>
#include "kern_constants.h"
#include "mcast.h"
#include "net_user.h"
#include "um_malloc.h"
#include "user.h"

static struct sockaddr_in *new_addr(char *addr, unsigned short port)
{
	struct sockaddr_in *sin;

	sin = uml_kmalloc(sizeof(struct sockaddr_in), UM_GFP_KERNEL);
	if (sin == NULL) {
		printk(UM_KERN_ERR "new_addr: allocation of sockaddr_in "
		       "failed\n");
		return NULL;
	}
	sin->sin_family = AF_INET;
	sin->sin_addr.s_addr = in_aton(addr);
	sin->sin_port = htons(port);
	return sin;
}

static int mcast_user_init(void *data, void *dev)
{
	struct mcast_data *pri = data;

	pri->mcast_addr = new_addr(pri->addr, pri->port);
	pri->dev = dev;
	return 0;
}

static void mcast_remove(void *data)
{
	struct mcast_data *pri = data;

	kfree(pri->mcast_addr);
	pri->mcast_addr = NULL;
}

static int mcast_open(void *data)
{
	struct mcast_data *pri = data;
	struct sockaddr_in *sin = pri->mcast_addr;
	struct ip_mreq mreq;
	int fd, yes = 1, err = -EINVAL;

	if ((sin->sin_addr.s_addr == 0) || (sin->sin_port == 0))
		goto out;

	fd = socket(AF_INET, SOCK_DGRAM, 0);

	if (fd < 0) {
		err = -errno;
		printk(UM_KERN_ERR "mcast_open : data socket failed, "
		       "errno = %d\n", errno);
		goto out;
	}

	if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) < 0) {
		err = -errno;
		printk(UM_KERN_ERR "mcast_open: SO_REUSEADDR failed, "
		       "errno = %d\n", errno);
		goto out_close;
	}

	/* set ttl according to config */
	if (setsockopt(fd, SOL_IP, IP_MULTICAST_TTL, &pri->ttl,
		       sizeof(pri->ttl)) < 0) {
		err = -errno;
		printk(UM_KERN_ERR "mcast_open: IP_MULTICAST_TTL failed, "
		       "error = %d\n", errno);
		goto out_close;
	}

	/* set LOOP, so data does get fed back to local sockets */
	if (setsockopt(fd, SOL_IP, IP_MULTICAST_LOOP, &yes, sizeof(yes)) < 0) {
		err = -errno;
		printk(UM_KERN_ERR "mcast_open: IP_MULTICAST_LOOP failed, "
		       "error = %d\n", errno);
		goto out_close;
	}

	/* bind socket to mcast address */
	if (bind(fd, (struct sockaddr *) sin, sizeof(*sin)) < 0) {
		err = -errno;
		printk(UM_KERN_ERR "mcast_open : data bind failed, "
		       "errno = %d\n", errno);
		goto out_close;
	}

	/* subscribe to the multicast group */
	mreq.imr_multiaddr.s_addr = sin->sin_addr.s_addr;
	mreq.imr_interface.s_addr = 0;
	if (setsockopt(fd, SOL_IP, IP_ADD_MEMBERSHIP,
		       &mreq, sizeof(mreq)) < 0) {
		err = -errno;
		printk(UM_KERN_ERR "mcast_open: IP_ADD_MEMBERSHIP failed, "
		       "error = %d\n", errno);
		printk(UM_KERN_ERR "There appears not to be a multicast-"
		       "capable network interface on the host.\n");
		printk(UM_KERN_ERR "eth0 should be configured in order to use "
		       "the multicast transport.\n");
		goto out_close;
	}

	return fd;

 out_close:
	close(fd);
 out:
	return err;
}

static void mcast_close(int fd, void *data)
{
	struct ip_mreq mreq;
	struct mcast_data *pri = data;
	struct sockaddr_in *sin = pri->mcast_addr;

	mreq.imr_multiaddr.s_addr = sin->sin_addr.s_addr;
	mreq.imr_interface.s_addr = 0;
	if (setsockopt(fd, SOL_IP, IP_DROP_MEMBERSHIP,
		       &mreq, sizeof(mreq)) < 0) {
		printk(UM_KERN_ERR "mcast_open: IP_DROP_MEMBERSHIP failed, "
		       "error = %d\n", errno);
	}

	close(fd);
}

int mcast_user_write(int fd, void *buf, int len, struct mcast_data *pri)
{
	struct sockaddr_in *data_addr = pri->mcast_addr;

	return net_sendto(fd, buf, len, data_addr, sizeof(*data_addr));
}

const struct net_user_info mcast_user_info = {
	.init		= mcast_user_init,
	.open		= mcast_open,
	.close	 	= mcast_close,
	.remove	 	= mcast_remove,
	.add_address	= NULL,
	.delete_address = NULL,
	.mtu		= ETH_MAX_PACKET,
	.max_packet	= ETH_MAX_PACKET + ETH_HEADER_OTHER,
};


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Hyak.Common;
using Microsoft.Azure.Management.Automation.Models;

namespace Microsoft.Azure.Management.Automation.Models
{
    /// <summary>
    /// The parameters supplied to the create compilation job operation.
    /// </summary>
    public partial class DscCompilationJobCreateProperties
    {
        private DscConfigurationAssociationProperty _configuration;

        /// <summary>
        /// Required. Gets or sets the configuration.
        /// </summary>
        public DscConfigurationAssociationProperty Configuration
        {
            get { return this._configuration; }
            set { this._configuration = value; }
        }

        private bool _incrementNodeConfigurationBuild;

        /// <summary>
        /// Optional. Gets or sets if a new build version of NodeConfiguration
        /// is requested.
        /// </summary>
        public bool IncrementNodeConfigurationBuild
        {
            get { return this._incrementNodeConfigurationBuild; }
            set { this._incrementNodeConfigurationBuild = value; }
        }

        private IDictionary<string, string> _parameters;

        /// <summary>
        /// Optional. Gets or sets the parameters of the job.
        /// </summary>
        public IDictionary<string, string> Parameters
        {
            get { return this._parameters; }
            set { this._parameters = value; }
        }

        private string _runOn;

        /// <summary>
        /// Optional. Gets or sets the hybrid worker group name for the job.
        /// </summary>
        public string RunOn
        {
            get { return this._runOn; }
            set { this._runOn = value; }
        }

        /// <summary>
        /// Initializes a new instance of the DscCompilationJobCreateProperties
        /// class.
        /// </summary>
        public DscCompilationJobCreateProperties()
        {
            this.Parameters = new LazyDictionary<string, string>();
        }

        /// <summary>
        /// Initializes a new instance of the DscCompilationJobCreateProperties
        /// class with required arguments.
        /// </summary>
        public DscCompilationJobCreateProperties(DscConfigurationAssociationProperty configuration)
            : this()
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }
            this.Configuration = configuration;
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <parent>
    <groupId>com.thinkbiganalytics.kylo.integrations</groupId>
    <artifactId>kylo-nifi-nar-bundles</artifactId>
    <version>0.10.1-SNAPSHOT</version>
  </parent>
  <modelVersion>4.0.0</modelVersion>

  <artifactId>kylo-nifi-teradata-tdch-bundle</artifactId>
  <packaging>pom</packaging>

  <modules>
    <module>nifi-teradata-tdch-api</module>
    <module>nifi-teradata-tdch-core</module>
    <module>nifi-teradata-tdch-nar</module>
  </modules>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <plugin.license.parentRelative>../../../../</plugin.license.parentRelative>
    <nifi.nar.maven.plugin.version>1.1.0</nifi.nar.maven.plugin.version>
  </properties>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.nifi</groupId>
        <artifactId>nifi-nar-maven-plugin</artifactId>
        <version>${nifi.nar.maven.plugin.version}</version>
        <extensions>true</extensions>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>${maven.surefire.plugin.version}</version>
      </plugin>
    </plugins>
  </build>

</project>


text:
← [back to Commands](../README.md)

# `cf-mgmt update-space-users`

`update-space-users` command will:

- adds users from `ldap_groups` configured in spaceConfig.yml assuming that ldap.yml is configured
- adds ldap users in `ldap_users` configured in spaceConfig.yml assuming that ldap.yml is configured
- add internal `users` configured in spaceConfig.yml (internal users must exist in uaa first)
- add `saml_users` configured in spaceConfig.yml (internal users must exist in uaa first)
- will remove users from roles if `enable-remove-users` is set to `true` in spaceConfig.yml

## Command Usage

```
Usage:
  cf-mgmt [OPTIONS] update-space-users [update-space-users-OPTIONS]

Help Options:
  -h, --help               Show this help message

[update-space-users command options]
  --config-dir=    Name of the config directory (default: config) [$CONFIG_DIR]
  --system-domain= system domain [$SYSTEM_DOMAIN]
  --user-id=       user id that has privileges to create/update/delete users, orgs and spaces [$USER_ID]
  --password=      password for user account [optional if client secret is provided] [$PASSWORD]
  --client-secret= secret for user account that has sufficient privileges to create/update/delete users,
                   orgs and spaces] [$CLIENT_SECRET]
  --ldap-password= LDAP password for binding [$LDAP_PASSWORD]
  --peek           Preview entities to change without modifying. [$PEEK]
```


text:
timeseries
==========

Simple Time Series Scala Framework


text:
using System;
using JetBrains.Annotations;

namespace JsonApiDotNetCore.Queries.Internal.Parsing
{
    [PublicAPI]
    public sealed class QueryParseException : Exception
    {
        public QueryParseException(string message)
            : base(message)
        {
        }
    }
}


text:
<!DOCTYPE html >

    <link rel="stylesheet" href="demos.css" type="text/css" media="screen" />

    <title>A Scatter chart with the ability to add markers</title>

    <meta name="robots" content="noindex,nofollow" />
    <meta name="description" content="A Scatter chart with the ability to add markers" />

A Scatter chart with the ability to add markers

        You can click on the Scatter chart to add a red circle. When the circles are then clicked on nothing happens.

    <canvas id="cvs" width="600" height="200">[No canvas support]</canvas>

        « Back


text:
package com.alibaba.druid.bvt.pool.xa;

import java.lang.reflect.Constructor;

import junit.framework.TestCase;
import net.sourceforge.jtds.jdbc.JtdsConnection;

import org.junit.Assert;

import com.alibaba.druid.pool.xa.JtdsXAConnection;
import com.alibaba.druid.pool.xa.JtdsXAResource;

public class JtdsXAConnectionTest extends TestCase {

    public void test_jtds() throws Exception {
        Constructor<JtdsConnection> constrcutor = JtdsConnection.class.getDeclaredConstructor();
        constrcutor.setAccessible(true);
        JtdsConnection jtdsConn = constrcutor.newInstance();
        JtdsXAConnection xaConn = new JtdsXAConnection(jtdsConn);
        Assert.assertSame(jtdsConn, xaConn.getConnection());

        JtdsXAResource xaResource = (JtdsXAResource) xaConn.getXAResource();
        Assert.assertTrue(xaResource.isSameRM(xaResource));
        Assert.assertFalse(xaResource.isSameRM(null));

        {
            Exception error = null;
            try {
                xaResource.commit(null, true);
            } catch (Exception ex) {
                error = ex;
            }
            Assert.assertNotNull(error);
        }
        {
            Exception error = null;
            try {
                xaResource.start(null, 0);
            } catch (Exception ex) {
                error = ex;
            }
            Assert.assertNotNull(error);
        }
        {
            Exception error = null;
            try {
                xaResource.end(null, 0);
            } catch (Exception ex) {
                error = ex;
            }
            Assert.assertNotNull(error);
        }
        {
            Exception error = null;
            try {
                xaResource.forget(null);
            } catch (Exception ex) {
                error = ex;
            }
            Assert.assertNotNull(error);
        }
        {
            Exception error = null;
            try {
                xaResource.rollback(null);
            } catch (Exception ex) {
                error = ex;
            }
            Assert.assertNotNull(error);
        }
        xaResource.recover(0);
        {
            Exception error = null;
            try {
                xaResource.prepare(null);
            } catch (Exception ex) {
                error = ex;
            }
            Assert.assertNotNull(error);
        }
        xaConn.close();
    }
}


text:
(typeof(process) !== "undefined" ? process : (function() {
    var shift = Array.prototype.shift,
        has = Object.prototype.hasOwnProperty;

    function EventObject(listener, ctx) {
        this.listener = listener;
        this.ctx = ctx;
    }

    function EventEmitter() {

        this._events = {};
        this._maxListeners = EventEmitter.defaultMaxListeners;
    }

    EventEmitter.prototype.on = function(type, listener, ctx) {
        if (typeof(listener) !== "function") throw new TypeError("EventEmitter.on(type, listener[, ctx]) listener must be a function");
        var events = this._events,
            eventList = (events[type] || (events[type] = [])),
            maxListeners = this._maxListeners;

        eventList.push(new EventObject(listener, ctx || this));

        if (maxListeners !== -1 && eventList.length > maxListeners) {
            console.error("EventEmitter.on(type, listener, ctx) possible EventEmitter memory leak detected. " + maxListeners + " listeners added");
        }

        return this;
    };

    EventEmitter.prototype.addListener = EventEmitter.prototype.on;

    EventEmitter.prototype.once = function(type, listener, ctx) {
        var _this = this;
        ctx || (ctx = this);

        function once() {
            _this.off(type, once, ctx);
            var length = arguments.length;

            if (length === 0) {
                return listener.call(ctx);
            } else if (length === 1) {
                return listener.call(ctx, arguments[0]);
            } else if (length === 2) {
                return listener.call(ctx, arguments[0], arguments[1]);
            } else if (length === 3) {
                return listener.call(ctx, arguments[0], arguments[1], arguments[2]);
            } else if (length === 4) {
                return listener.call(ctx, arguments[0], arguments[1], arguments[2], arguments[3]);
            } else if (length === 5) {
                return listener.call(ctx, arguments[0], arguments[1], arguments[2], arguments[3], arguments[4]);
            }

            return listener.apply(ctx, arguments);
        }

        return this.on(type, once, ctx);
    };

    EventEmitter.prototype.listenTo = function(obj, type, listener, ctx) {
        if (!(has.call(obj, "on") && typeof(obj.on) === "function")) {
            throw new TypeError("EventEmitter.listenTo(obj, type, listener, ctx) obj must have a on function taking (type, listener[, ctx])");
        }

        obj.on(type, listener, ctx || this);
        return this;
    };

    EventEmitter.prototype.off = function(type, listener, ctx) {
        var events = this._events,
            eventList, event, i;

        if (!type) return this.removeAllListeners();

        eventList = events[type];
        if (!eventList) return this;

        if (!listener) {
            i = eventList.length;
            while (i--) {
                event = eventList[i];
                this.emit("removeListener", type, event.listener, event.ctx);
            }
            eventList.length = 0;
            delete events[type];
        } else {
            ctx = ctx || this;
            i = eventList.length;
            while (i--) {
                event = eventList[i];

                if (event.listener === listener) {
                    this.emit("removeListener", type, event.listener, event.ctx);
                    eventList.splice(i, 1);
                }
            }
            if (eventList.length === 0) delete events[type];
        }

        return this;
    };

    EventEmitter.prototype.removeListener = EventEmitter.prototype.off;

    EventEmitter.prototype.removeAllListeners = function() {
        var events = this._events,
            eventList, event, i;

        for (var key in events) {
            if ((eventList = events[key])) {
                i = eventList.length;
                while (i--) {
                    event = eventList[i];
                    this.emit("removeListener", type, event.listener, event.ctx);
                }
                eventList.length = 0;
                delete events[key];
            }
        }

        return this;
    };

    EventEmitter.prototype.emit = function(type) {
        var eventList = this._events[type],
            a1, a2, a3, a4,
            length, event,
            i;

        if (!eventList || !eventList.length) return this;
        length = arguments.length;

        if (length === 1) {
            i = eventList.length;
            while (i--) {
                if ((event = eventList[i])) event.listener.call(event.ctx);
            }
        } else if (length === 2) {
            a1 = arguments[1];
            i = eventList.length;
            while (i--) {
                if ((event = eventList[i])) event.listener.call(event.ctx, a1);
            }
        } else if (length === 3) {
            a1 = arguments[1];
            a2 = arguments[2];
            i = eventList.length;
            while (i--) {
                if ((event = eventList[i])) event.listener.call(event.ctx, a1, a2);
            }
        } else if (length === 4) {
            a1 = arguments[1];
            a2 = arguments[2];
            a3 = arguments[3];
            i = eventList.length;
            while (i--) {
                if ((event = eventList[i])) event.listener.call(event.ctx, a1, a2, a3);
            }
        } else if (length === 5) {
            a1 = arguments[1];
            a2 = arguments[2];
            a3 = arguments[3];
            a4 = arguments[4];
            i = eventList.length;
            while (i--) {
                if ((event = eventList[i])) event.listener.call(event.ctx, a1, a2, a3, a4);
            }
        } else {
            shift.apply(arguments);
            i = eventList.length;
            while (i--) {
                if ((event = eventList[i])) event.listener.apply(event.ctx, arguments);
            }
        }

        return this;
    };

    EventEmitter.prototype.listeners = function(type) {
        var eventList = this._events[type];

        return eventList ? eventList.slice() : [];
    };

    EventEmitter.prototype.listenerCount = function(type) {
        var eventList = this._events[type];

        return eventList ? eventList.length : 0;
    };

    EventEmitter.prototype.setMaxListeners = function(value) {
        if ((value = +value) !== value) throw new TypeError("EventEmitter.setMaxListeners(value) value must be a number");

        this._maxListeners = value < 0 ? -1 : value;
        return this;
    };

    EventEmitter.defaultMaxListeners = 10;

    EventEmitter.listeners = function(obj, type) {
        if (obj == null) throw new TypeError("EventEmitter.listeners(obj, type) obj required");
        var eventList = obj._events && obj._events[type];

        return eventList ? eventList.slice() : [];
    };

    EventEmitter.listenerCount = function(obj, type) {
        if (obj == null) throw new TypeError("EventEmitter.listenerCount(obj, type) obj required");
        var eventList = obj._events && obj._events[type];

        return eventList ? eventList.length : 0;
    };

    EventEmitter.setMaxListeners = function(value) {
        if ((value = +value) !== value) throw new TypeError("EventEmitter.setMaxListeners(value) value must be a number");

        EventEmitter.defaultMaxListeners = value < 0 ? -1 : value;
        return value;
    };

    EventEmitter.extend = function(child, parent) {
        if (!parent) parent = this;

        child.prototype = Object.create(parent.prototype);
        child.prototype.constructor = child;
        child.prototype._super = parent.prototype;
        child.extend = parent.extend;
        child._super = parent;

        return child;
    };

    function Process() {

        EventEmitter.call(this);
        var arch = /\b(?:AMD|IA|Win|WOW|x86_|x)64\b/i.exec(navigator.platform);

        this.pid = 0;
        this.title = "browser";
        this.env = {};
        this.argv = [];
        this.version = "1.0.0";
        this.versions = {};
        this.config = {};
        this.execPath = ".";
        this.execArgv = [];
        this.arch = arch ? arch[0] : "unknown"
        this.platform = (navigator.platform.split(/[ \s]+/)[0]).toLowerCase() || "unknown";
        this.maxTickDepth = 1000;
        this._cwd = location.pathname;
    }
    EventEmitter.extend(Process);

    Object.defineProperty(Process.prototype, "browser", {
        get: function() {
            return true;
        }
    });

    Process.prototype.memoryUsage = (function() {
        var performance = window.performance || {},
            memory = {
                rss: 0,
                heapTotal: 0,
                heapUsed: 0
            };

        performance.memory || (performance.memory = {});

        return function memoryUsage() {
            memory.rss = performance.memory.jsHeapSizeLimit || 0;
            memory.heapTotal = performance.memory.totalJSHeapSize || 0;
            memory.heapUsed = performance.memory.usedJSHeapSize || 0;

            return memory;
        };
    }());

    Process.prototype.nextTick = (function() {
        var canSetImmediate = !!window.setImmediate,
            canPost = window.postMessage && window.addEventListener;

        if (canSetImmediate) {
            return function(fn) {
                return window.setImmediate(fn)
            };
        }

        if (canPost) {
            var queue = [];

            window.addEventListener("message", function(e) {
                var source = e.source;

                if ((source === window || source === null) && e.data === "process-tick") {
                    e.stopPropagation();

                    if (queue.length > 0) queue.shift()();
                }
            }, true);

            return function nextTick(fn) {
                queue.push(fn);
                window.postMessage("process-tick", "*");
            };
        }

        return function nextTick(fn) {
            window.setTimeout(fn, 0);
        };
    }());

    Process.prototype.cwd = function() {
        return this._cwd;
    };

    Process.prototype.chdir = function(dir) {
        var cwd = location.pathname;

        if (cwd.indexOf(dir.substring(0, cwd.length)) === 0) {
            this._cwd = dir;
        } else {
            throw new Error("process.chdir can't change to directory " + dir);
        }
    };

    Process.prototype.hrtime = (function() {
        var performance = window.performance || {},
            start;

        Date.now || (Date.now = function now() {
            return (new Date()).getTime();
        });
        start = Date.now();

        performance.now || (performance.now =
            performance.mozNow ||
            performance.msNow ||
            performance.oNow ||
            performance.webkitNow ||
            function now() {
                return Date.now() - start;
            }
        );

        function performanceNow() {
            return start + performance.now();
        }

        return function hrtime(previousTimestamp) {
            var clocktime = performanceNow() * 1e-3,
                seconds = Math.floor(clocktime),
                nanoseconds = (clocktime % 1) * 1e9;

            if (previousTimestamp) {
                seconds -= previousTimestamp[0];
                nanoseconds -= previousTimestamp[1];

                if (nanoseconds < 0) {
                    seconds--;
                    nanoseconds += 1e9;
                }
            }

            return [seconds, nanoseconds]
        }
    }());

    Process.prototype.uptime = (function() {
        var start = Date.now();

        return function uptime() {
            return ((Date.now() - start) * 1e-3) | 0;
        }
    }());

    Process.prototype.abort = function() {
        throw new Error("process.abort is not supported");
    };

    Process.prototype.binding = function(name) {
        throw new Error("process.binding is not supported");
    };

    Process.prototype.umask = function(mask) {
        throw new Error("process.umask is not supported");
    };

    Process.prototype.kill = function(id, signal) {
        throw new Error("process.kill is not supported");
    };

    Process.prototype.initgroups = function(user, extra_group) {
        throw new Error("process.initgroups is not supported");
    };

    Process.prototype.setgroups = function(groups) {
        throw new Error("process.setgroups is not supported");
    };

    Process.prototype.getgroups = function() {
        throw new Error("process.getgroups is not supported");
    };

    Process.prototype.getuid = function() {
        throw new Error("process.getuid is not supported");
    };

    Process.prototype.setgid = function() {
        throw new Error("process.setgid is not supported");
    };

    Process.prototype.getgid = function() {
        throw new Error("process.getgid is not supported");
    };

    Process.prototype.exit = function() {
        throw new Error("process.exit is not supported");
    };

    Process.prototype.setuid = function(id) {
        throw new Error("process.setuid is not supported");
    };

    Object.defineProperty(Process.prototype, "stderr", {
        get: function() {
            throw new Error("process.stderr is not supported");
        },
        set: function() {
            throw new Error("process.stderr is not supported");
        }
    });

    Object.defineProperty(Process.prototype, "stdin", {
        get: function() {
            throw new Error("process.stderr is not supported");
        },
        set: function() {
            throw new Error("process.stderr is not supported");
        }
    });

    Object.defineProperty(Process.prototype, "stdout", {
        get: function() {
            throw new Error("process.stderr is not supported");
        },
        set: function() {
            throw new Error("process.stderr is not supported");
        }
    });

    return new Process();
}()))


text:
layout: post
title:  "[NYE 2016 --> 2017]"
date:   2016-12-31 23:59:12 -0500
---

Today is my birthday. I'm not bragging or looking for attention. Ok, maybe a little, but I'm looking forward to writing code here with the learn.community...

2016 was a very strange year. It feels as if human consciousness stumbled in the universe and we landed in a different timeline than where we started. It difficult to explain, but I imagine you understand what I'm talking about.

Here's to a far less weird 2017. (updated 7.13.2018: so much for that ;)

Any fool can write code that a computer can understand. Good programmers write code that humans can understand. 😏 #Programming #inspiration
— iLoveCoding (@ilovecodingorg) February 8, 2017


text:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("EasyNetQ.Wf")]
[assembly: AssemblyDescription("EasyNetQ Windows Workflow Foundation Extensions")]

#if DEBUG
[assembly: AssemblyConfiguration("DEBUG")]
#else
[assembly: AssemblyConfiguration("RELEASE")]
#endif

[assembly: AssemblyCompany("Jeffrey Huntsman")]
[assembly: AssemblyProduct("EasyNetQ.Wf")]
[assembly: AssemblyCopyright("Copyright © Jeffrey Huntsman 2015-2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("0.50.7.*")]
[assembly: AssemblyInformationalVersion("0.50.7-alpha35")]


text:
namespace crypto {
namespace tink {

///////////////////////////////////////////////////////////////////////////////
// Static methods and constants for registering with the Registry
// all instances of DeterministicAead key types supported in a release of Tink.
//
// To register all DeterministicAead key types from the current Tink release
// one can do:
//
//   auto status = DeterministicAeadConfig::Register();
//
class DeterministicAeadConfig {
 public:
  static constexpr char kCatalogueName[] = "TinkDeterministicAead";
  static constexpr char kPrimitiveName[] = "DeterministicAead";

  // Returns config of DeterministicAead implementations supported
  // in the current Tink release.
  ABSL_DEPRECATED("This is not supported anymore.")
  static const google::crypto::tink::RegistryConfig& Latest();

  // Registers DeterministicAead primitive wrapper and key managers for all
  // DeterministicAead key types from the current Tink release.
  static crypto::tink::util::Status Register();

 private:
  DeterministicAeadConfig() {}
};

}  // namespace tink
}  // namespace crypto

#endif  // TINK_DAEAD_DETERMINISTIC_AEAD_CONFIG_H_


text:
<!DOCTYPE html>

    <title>New Year, New Domain.</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="HandheldFriendly" content="True">
    <meta name="MobileOptimized" content="320">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="apple-touch-icon" sizes="57x57" href="//jaredleonmorgan.net/themes/uno-zen/assets/img/apple-touch-icon-57x57.png?v=wAAv6Wqe6l?v=1535063628146">
    <link rel="apple-touch-icon" sizes="60x60" href="//jaredleonmorgan.net/themes/uno-zen/assets/img/apple-touch-icon-60x60.png?v=wAAv6Wqe6l?v=1535063628146">
    <link rel="apple-touch-icon" sizes="72x72" href="//jaredleonmorgan.net/themes/uno-zen/assets/img/apple-touch-icon-72x72.png?v=wAAv6Wqe6l?v=1535063628146">
    <link rel="apple-touch-icon" sizes="76x76" href="//jaredleonmorgan.net/themes/uno-zen/assets/img/apple-touch-icon-76x76.png?v=wAAv6Wqe6l?v=1535063628146">
    <link rel="apple-touch-icon" sizes="114x114" href="//jaredleonmorgan.net/themes/uno-zen/assets/img/apple-touch-icon-114x114.png?v=wAAv6Wqe6l?v=1535063628146">
    <link rel="apple-touch-icon" sizes="120x120" href="//jaredleonmorgan.net/themes/uno-zen/assets/img/apple-touch-icon-120x120.png?v=wAAv6Wqe6l?v=1535063628146">
    <link rel="apple-touch-icon" sizes="144x144" href="//jaredleonmorgan.net/themes/uno-zen/assets/img/apple-touch-icon-144x144.png?v=wAAv6Wqe6l?v=1535063628146">
    <link rel="apple-touch-icon" sizes="152x152" href="//jaredleonmorgan.net/themes/uno-zen/assets/img/apple-touch-icon-152x152.png?v=wAAv6Wqe6l?v=1535063628146">
    <link rel="apple-touch-icon" sizes="180x180" href="//jaredleonmorgan.net/themes/uno-zen/assets/img/apple-touch-icon-180x180.png?v=wAAv6Wqe6l?v=1535063628146">
    <link rel="icon" type="image/png" href="//jaredleonmorgan.net/themes/uno-zen/assets/img/favicon-32x32.png?v=wAAv6Wqe6l?v=1535063628146" sizes="32x32">
    <link rel="icon" type="image/png" href="//jaredleonmorgan.net/themes/uno-zen/assets/img/favicon-194x194.png?v=wAAv6Wqe6l?v=1535063628146" sizes="194x194">
    <link rel="icon" type="image/png" href="//jaredleonmorgan.net/themes/uno-zen/assets/img/favicon-96x96.png?v=wAAv6Wqe6l?v=1535063628146" sizes="96x96">
    <link rel="icon" type="image/png" href="//jaredleonmorgan.net/themes/uno-zen/assets/img/android-chrome-192x192.png?v=wAAv6Wqe6l?v=1535063628146" sizes="192x192">
    <link rel="icon" type="image/png" href="//jaredleonmorgan.net/themes/uno-zen/assets/img/favicon-16x16.png?v=wAAv6Wqe6l?v=1535063628146" sizes="16x16">
    <link rel="manifest" href="//jaredleonmorgan.net/themes/uno-zen/assets/img/manifest.json?v=wAAv6Wqe6l?v=1535063628146">
    <link rel="shortcut icon" href="//jaredleonmorgan.net/themes/uno-zen/assets/img/favicon.ico?v=wAAv6Wqe6l?v=1535063628146">
    <meta name="msapplication-TileColor" content="#e74c3c">
    <meta name="msapplication-TileImage" content="//jaredleonmorgan.net/themes/uno-zen/assets/img/mstile-144x144.png?v=wAAv6Wqe6l?v=1535063628146">
    <meta name="msapplication-config" content="//jaredleonmorgan.net/themes/uno-zen/assets/img/browserconfig.xml?v=wAAv6Wqe6l?v=1535063628146">
    <meta name="theme-color" content="#e74c3c">
    <link rel="stylesheet" type="text/css" href="//jaredleonmorgan.net/themes/uno-zen/assets/css/uno-zen.css?v=1535063628146" />
    <link rel="canonical" href="http://jaredleonmorgan.net/2016/01/12/New-Year-New-Domain.html" />
    <meta name="referrer" content="origin" />

    <meta property="og:site_name" content="Jared Morgan (jaredmorgs) " />
    <meta property="og:type" content="article" />
    <meta property="og:title" content="New Year, New Domain." />
    <meta property="og:description" content="Happy New Year! It&#8217;s taken me five months, but I&#8217;ve finally activated my new domain name. The old http://jaredmorgs.github.io site should now redirect to the new http://jaredleonmorgan.net site. Any other sites like the previous home of the Pinball Arcade Android Users" />
    <meta property="og:url" content="http://jaredleonmorgan.net/2016/01/12/New-Year-New-Domain.html" />
    <meta property="og:image" content="covers/open_source.jpg" />
    <meta property="article:published_time" content="2016-01-12T00:00:00.000Z" />
    <meta property="article:tag" content="2016" />
    <meta property="article:tag" content="open source" />

    <meta name="twitter:card" content="summary_large_image" />
    <meta name="twitter:title" content="New Year, New Domain." />
    <meta name="twitter:description" content="Happy New Year! It&#8217;s taken me five months, but I&#8217;ve finally activated my new domain name. The old http://jaredmorgs.github.io site should now redirect to the new http://jaredleonmorgan.net site. Any other sites like the previous home of the Pinball Arcade Android Users" />
    <meta name="twitter:url" content="http://jaredleonmorgan.net/2016/01/12/New-Year-New-Domain.html" />
    <meta name="twitter:image:src" content="covers/open_source.jpg" />

    <meta name="generator" content="HubPress" />
    <link rel="alternate" type="application/rss+xml" title="Jared Morgan (jaredmorgs) " href="http://jaredleonmorgan.net/rss/" />
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/prism/1.14.0/themes/prism-okaidia.min.css">

Jared Morgan (jaredmorgs)

Tech Writer with a Product focus | Podcaster | Pinball Nut

                      Twitter

                      Google-plus

                      Github

                      Instagram

                      Flickr

                      LinkedIn

                      Email

        <time datetime="12 Jan 2016">12 Jan 2016</time>
        in 2016 open source

         ~  read.

New Year, New Domain.

Happy New Year!

It’s taken me five months, but I’ve finally activated my new domain name.

The old http://jaredmorgs.github.io site should now redirect to the new http://jaredleonmorgan.net site.

Any other sites like the previous home of the Pinball Arcade Android Users Guide (http://jaredmorgs.github.io/Pinball_Arcade_Users_Guide_Android) should also switch over automatically.

Static Site Experimentation

I had been experimenting with a few different static site generators during this time. I’ve tried Middleman and Awestruct (although not in a very concerted way), and I drifted back to the Jekyll Asciidoctor Quickstart as well, trying out the Lanyon theme.

My goal to set up a web page that let me both show my Resume in a single location, and to continue to offer a blog service.

Which Static Site Generator Won?

The solution I’ve chosen? HubPress!

Even though HubPress is one year old this February 2016 (give or take a few months), I still love what this static site generator has done for both the adoption of AsciiDoc and the GitHub Pages static site movement.

There are some pretty wonderful static sites out there using HubPress as their backbone.

I think with a few tweaks to page layouts in Ghost themes, I should be able to add the Documentation and Resume areas I need into HubPress and continue to use HubPress to manage page content authoring.

        Please enable JavaScript to view the comments powered by Disqus.
        comments powered by Disqus

            © 2018. All rights reserved. Built with Uno Zen under HubPress.


text:
// Copyright (c) DNN Software. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System;
using System.CodeDom;
using System.Linq;
using System.Net.Http.Formatting;
using System.Web.Mvc;
using Dnn.DynamicContent;
using Dnn.Modules.DynamicContentViewer.Models;
using DotNetNuke.Collections;
using DotNetNuke.Common;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Security;
using DotNetNuke.Security.Permissions;
using DotNetNuke.Services.FileSystem;
using DotNetNuke.Web.Mvc.Framework.ActionFilters;
using DotNetNuke.Web.Mvc.Framework.Controllers;

namespace Dnn.Modules.DynamicContentViewer.Controllers
{
    /// <summary>
    /// The ViewerController is used to manage the Actions associated with the Dynamic Content Viewer
    /// </summary>
    public class ViewerController : DnnController
    {
        /// <summary>
        /// The Edit Action will render the Content associated with this module using an Edit template
        /// </summary>
        /// <returns>The ViewResult</returns>
        [HttpGet]
        public ActionResult Edit()
        {
            string templateName;
            var templateId = ActiveModule.ModuleSettings.GetValueOrDefault(Settings.DCC_EditTemplateId, -1);
            ContentTemplate template = null;
            if (templateId > -1)
            {
                template = ContentTemplateManager.Instance.GetContentTemplate(templateId, PortalSettings.PortalId, true);
                templateName = GetTemplateName(template);
            }
            else
            {
                templateName = Globals.ApplicationPath + "/DesktopModules/MVC/Dnn/DynamicContentViewer/Views/Viewer/AutoGenerated.cshtml";
            }

            ViewData["Template"] = templateName;

            return View(GetContentItem());
        }

        /// <summary>
        /// The Edit Action will process the posted Form
        /// </summary>
        /// <param name="collection">The collection of Form name/value pairs that represents the Content Item's fields</param>
        /// <returns>The ViewResult</returns>
        [HttpPost]
        [ValidateInput(false)]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(FormCollection collection)
        {
            DynamicContentItem contentItem = GetContentItem();

            if (contentItem != null)
            {
                ProcessFields(contentItem.Content, collection, String.Empty);
                DynamicContentItemManager.Instance.UpdateContentItem(contentItem);
            }

            return RedirectToDefaultRoute();
        }

        private DynamicContentItem GetContentItem()
        {
            var contentTypeId = ActiveModule.ModuleSettings.GetValueOrDefault(Settings.DCC_ContentTypeId, -1);
            DynamicContentItem contentItem = null;
            if (contentTypeId > -1)
            {
                contentItem = DynamicContentItemManager.Instance.GetContentItems(ActiveModule.ModuleID, contentTypeId).SingleOrDefault();
            }

            return contentItem;
        }

        /// <summary>
        /// GetIndexActions returns the DNN Module Actions associated with the Index MVC Action/View
        /// </summary>
        /// <returns>A collection of Module Actions</returns>
        public ModuleActionCollection GetIndexActions()
        {
            var actions = new ModuleActionCollection();

            var contentTypeId = ActiveModule.ModuleSettings.GetValueOrDefault(Settings.DCC_ContentTypeId, -1);

            if (contentTypeId > -1)
            {
                actions.Add(-1,
                        LocalizeString("EditContent"),
                        ModuleActionType.AddContent,
                        "",
                        "",
                        ModuleContext.EditUrl("Edit"),
                        false,
                        SecurityAccessLevel.Edit,
                        true,
                        false);
            }

            var managerModule = ModuleController.Instance.GetModuleByDefinition(PortalSettings.PortalId, "Dnn.DynamicContentManager");

            if (managerModule != null && ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Edit, "EDIT", managerModule))
            {
                actions.Add(-1,
                        LocalizeString("EditTemplates"),
                        ModuleActionType.AddContent,
                        "",
                        "",
                        Globals.NavigateURL(managerModule.TabID, String.Empty, "tab=Templates"),
                        false,
                        SecurityAccessLevel.Edit,
                        true,
                        false);
            }
            return actions;
        }

        private DynamicContentItem GetOrCreateContentItem(int contentTypeId)
        {
            var contentItem = DynamicContentItemManager.Instance.GetContentItems(ActiveModule.ModuleID, contentTypeId).SingleOrDefault();

            if (contentItem == null)
            {
                var contentType = DynamicContentTypeManager.Instance.GetContentType(contentTypeId, PortalSettings.PortalId, true);
                contentItem = DynamicContentItemManager.Instance.CreateContentItem(PortalSettings.PortalId, ActivePage.TabID, ActiveModule.ModuleID, contentType);
                DynamicContentItemManager.Instance.AddContentItem(contentItem);
            }
            return contentItem;
        }

        private string GetTemplateName(ContentTemplate template)
        {
            string templateName = String.Empty;
            IFileInfo file = null;
            if (template != null)
            {
                file = FileManager.Instance.GetFile(template.TemplateFileId);
            }

            if (file != null)
            {
                if (file.PortalId > -1)
                {
                    templateName = PortalSettings.HomeDirectory + file.RelativePath;
                }
                else
                {
                    templateName = Globals.HostPath + file.RelativePath;
                }
            }
            return templateName;
        }

        /// <summary>
        /// The Index Action is the default Action for the controller - and will render the Content associated with this module
        /// </summary>
        /// <returns>The ViewResult</returns>
		[ModuleActionItems]
        public ActionResult Index()
        {
            string templateName;
            var contentTypeId = ActiveModule.ModuleSettings.GetValueOrDefault(Settings.DCC_ContentTypeId, -1);
            var templateId = ActiveModule.ModuleSettings.GetValueOrDefault(Settings.DCC_ViewTemplateId, -1);
            ContentTemplate template = null;
            if (templateId > -1)
            {
                template = ContentTemplateManager.Instance.GetContentTemplate(templateId, PortalSettings.PortalId, true);
                templateName = GetTemplateName(template);
            }
            else
            {
                if (contentTypeId > -1)
                {
                    templateName = Globals.ApplicationPath + "/DesktopModules/MVC/Dnn/DynamicContentViewer/Views/Viewer/AutoGeneratedView.cshtml";
                }
                else
                {
                    template = ContentTemplateManager.Instance.GetContentTemplates(PortalSettings.PortalId, true).SingleOrDefault(t => t.Name == "Getting Started");
                    templateName = GetTemplateName(template);
                }
            }

            if (String.IsNullOrEmpty(templateName))
            {
                return View("GettingStarted");
            }

            DynamicContentItem contentItem = null;
            if (contentTypeId > -1)
            {
                contentItem = GetOrCreateContentItem(contentTypeId);
            }
            else
            {
                var contentType = DynamicContentTypeManager.Instance.GetContentTypes(PortalSettings.PortalId, true).SingleOrDefault(ct => ct.Name == "HTML");
                contentItem = DynamicContentItemManager.Instance.CreateContentItem(PortalSettings.PortalId, ActivePage.TabID, ActiveModule.ModuleID, contentType);
            }

            ViewData["Template"] = templateName;

            return View(contentItem);
        }

        private void ProcessFields(DynamicContentPart contentPart, FormCollection collection, string prefix)
        {
            foreach (var field in contentPart.Fields.Values)
            {
                if (field.Definition.IsReferenceType)
                {
                    var part = field.Value as DynamicContentPart;
                    if (part != null)
                    {
                        var newPrefix = (String.IsNullOrEmpty(prefix)) ? field.Definition.Name : prefix + field.Definition.Name;
                        newPrefix += "/";
                        ProcessFields(part, collection, newPrefix);
                    }
                }
                else
                {
                    var fieldName = prefix + field.Definition.Name;

                    switch (field.Definition.DataType.Name)
                    {
                        case "Rich Text":
                            var html = collection[fieldName];
                            field.Value = String.IsNullOrEmpty(html) ? String.Empty : Server.HtmlEncode(html);
                            break;
                        case "Markdown":
                            var markdown = collection[fieldName];
                            field.Value = String.IsNullOrEmpty(markdown) ? String.Empty : markdown;
                            break;
                        default:
                            switch (field.Definition.DataType.UnderlyingDataType)
                            {
                                case UnderlyingDataType.Boolean:
                                    //Handle special case of Boolean values due to the way a checkbox works with MVC Helpers
                                    // return value is "true;false" if true and "false" if false
                                    field.Value = (collection[fieldName].Contains("true"));
                                    break;
                                case UnderlyingDataType.Integer:
                                    field.Value = collection.GetValueOrDefault(fieldName, 0);
                                    break;
                                case UnderlyingDataType.Float:
                                    field.Value = collection.GetValueOrDefault(fieldName, 0.0);
                                    break;
                                default:
                                    field.Value = collection.GetValueOrDefault(fieldName, String.Empty);
                                    break;
                            }
                            break;
                    }

                }
            }
        }
    }
}


text:
<!DOCTYPE html>
<meta charset='UTF-8'>
<title>Core</title>
<link rel='stylesheet' href='https://code.jquery.com/qunit/qunit-1.19.0.css'>


text:
/* Subscribe to a subset of the available Worker.js events */

function registerTaskRouterCallbacks() {
    worker.on('ready', function(worker) {
        agentActivityChanged(worker.activity_name);
        logger("Successfully registered as: " + worker.friendly_name)
        logger("Current activity is: " + worker.activity_name);
    });

    worker.on('activity.update', function(worker) {
        agentActivityChanged(worker.activity_name);
        logger("Worker activity changed to: " + worker.activity_name);
    });

    worker.on("reservation.created", function(task) {
        logger("-----");
        logger("You have been reserved to handle a call!");
        logger("Call from: " + task.attributes.from);
        logger("Selected language: " + task.attributes.selected_language);
        logger("-----");
    });

    worker.on("reservation.accepted", function(task) {
        logger("Reservation " + task.reservation_sid + " accepted!");
    });

    worker.on("reservation.rejected", function(task) {
        logger("Reservation " + task.reservation_sid + " rejected!");
    });

    worker.on("reservation.timeout", function(task) {
        logger("Reservation " + task.reservation_sid + " timed out!");
    });

    worker.on("reservation.canceled", function(task) {
        logger("Reservation " + task.reservation_sid + " canceled!");
    });
}

/* Hook up the agent Activity buttons to Worker.js */

function bindAgentActivityButtons() {
    // Fetch the full list of available Activities from TaskRouter. Store each
    // ActivitySid against the matching Friendly Name
    var activitySids = {};
    worker.fetchActivityList(function(error, activityList) {
        var activities = activityList.activities;
        var i = activities.length;
        while (i--) {
            activitySids[activities[i].friendly_name] = activities[i].sid;
        }
    });

    /* For each button of class 'change-activity' in our Agent UI, look up the
     ActivitySid corresponding to the Friendly Name in the button's next-activity
     data attribute. Use Worker.js to transition the agent to that ActivitySid
     when the button is clicked.*/
    var elements = document.getElementsByClassName('change-activity');
    var i = elements.length;
    while (i--) {
        elements[i].onclick = function() {
            var nextActivity = this.dataset.nextActivity;
            var nextActivitySid = activitySids[nextActivity];
            worker.updateActivity(nextActivitySid);
        }
    }
}

/* Update the UI to reflect a change in Activity */

function agentActivityChanged(activity) {
    hideAgentActivities();
    showAgentActivity(activity);
}

function hideAgentActivities() {
    var elements = document.getElementsByClassName('agent-activity');
    var i = elements.length;
    while (i--) {
        elements[i].style.display = 'none';
    }
}

function showAgentActivity(activity) {
    activity = activity.toLowerCase();
    var elements = document.getElementsByClassName(('agent-activity ' + activity));
    elements.item(0).style.display = 'block';
}

/* Other stuff */

function logger(message) {
    var log = document.getElementById('log');
    log.value += "\n> " + message;
    log.scrollTop = log.scrollHeight;
}

window.onload = function() {
    // Initialize Worker.js on page load using window.workerToken -
    // a Twilio Capability token that was set in a <script> in agent.php
    logger("Initializing...");
    window.worker = new Twilio.TaskRouter.Worker(workerToken);
    registerTaskRouterCallbacks();
    bindAgentActivityButtons();
};


text:
package org.mapfish.print.map.geotools;

import com.google.common.base.Predicate;
import com.google.common.io.Files;
import org.geotools.data.Query;
import org.geotools.map.FeatureLayer;
import org.geotools.map.Layer;
import org.junit.Test;
import org.mapfish.print.AbstractMapfishSpringTest;
import org.mapfish.print.IllegalFileAccessException;
import org.mapfish.print.TestHttpClientFactory;
import org.mapfish.print.config.Configuration;
import org.mapfish.print.config.Template;
import org.mapfish.print.parser.MapfishParserTest;
import org.mapfish.print.processor.map.CreateMapProcessorFixedScaleBBoxGeoJsonTest;
import org.mapfish.print.processor.map.CreateMapProcessorFlexibleScaleBBoxGeoJsonTest;
import org.mapfish.print.servlet.fileloader.ConfigFileLoaderManager;
import org.mapfish.print.wrapper.json.PJsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.mock.http.client.MockClientHttpRequest;
import org.springframework.test.annotation.DirtiesContext;

import java.io.File;
import java.net.URI;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mapfish.print.processor.map.CreateMapProcessorFlexibleScaleBBoxGeoJsonTest.BASE_DIR;

/**
 * Test GeoJson layer
 *
 * @author Jesse on 3/27/14.
 */
public class GeoJsonLayerTest extends AbstractMapfishSpringTest {

    @Autowired
    private GeoJsonLayer.Plugin geojsonLayerParser;
    @Autowired
    private TestHttpClientFactory httpRequestFactory;
    @Autowired
    private ConfigFileLoaderManager fileLoaderManager;

    @Test
    public void testGeoJsonEmbedded() throws Exception {
        final PJsonObject requestData = CreateMapProcessorFixedScaleBBoxGeoJsonTest.loadJsonRequestData()
                .getJSONObject("attributes")
                .getJSONObject("mapDef")
                .getJSONArray("layers").getJSONObject(0);

        final Configuration configuration = new Configuration();
        configuration.setConfigurationFile(new File("."));
        configuration.setFileLoaderManager(this.fileLoaderManager);

        Template template = new Template();
        template.setConfiguration(configuration);

        GeoJsonLayer.GeoJsonParam param = new GeoJsonLayer.GeoJsonParam();
        MapfishParserTest.populateLayerParam(requestData, param, "type");
        final GeoJsonLayer layer = geojsonLayerParser.parse(template, param);

        assertNotNull(layer);

        final List<? extends Layer> layers = layer.getLayers(httpRequestFactory, AbstractMapfishSpringTest.createTestMapContext(), true);

        assertEquals(1, layers.size());

        FeatureLayer featureLayer = (FeatureLayer) layers.get(0);
        final int count = featureLayer.getFeatureSource().getCount(Query.ALL);
        assertEquals(3, count);
        assertEquals(true, layer.shouldRenderAsSvg());
    }

    @Test(expected = IllegalFileAccessException.class)
    public void testGeoIllegalFileUrl() throws Exception {
        final File file = getFile(CreateMapProcessorFlexibleScaleBBoxGeoJsonTest.class, BASE_DIR + "geojson.json");
        final PJsonObject requestData = parseJSONObjectFromString("{type:\"geojson\";style:\"polygon\";geoJson:\""
                                                                  + file.toURI().toURL() + "\"}");

        final Configuration configuration = new Configuration();
        configuration.setConfigurationFile(File.createTempFile("xyz", ".yaml"));
        configuration.setFileLoaderManager(this.fileLoaderManager);

        Template template = new Template();
        template.setConfiguration(configuration);

        GeoJsonLayer.GeoJsonParam param = new GeoJsonLayer.GeoJsonParam();
        MapfishParserTest.populateLayerParam(requestData, param, "type");
        geojsonLayerParser.parse(template, param).getLayers(httpRequestFactory, AbstractMapfishSpringTest.createTestMapContext(), true);

    }

    @Test(expected = IllegalArgumentException.class)
    public void testGeoIllegalFileUrl2() throws Exception {
        final Configuration configuration = new Configuration();
        configuration.setConfigurationFile(File.createTempFile("xyz", ".yaml"));
        configuration.setFileLoaderManager(this.fileLoaderManager);

        Template template = new Template();
        template.setConfiguration(configuration);

        GeoJsonLayer.GeoJsonParam param = new GeoJsonLayer.GeoJsonParam();
        param.geoJson = "file://../" + BASE_DIR + "/geojson.json";
        geojsonLayerParser.parse(template, param).getLayers(httpRequestFactory, AbstractMapfishSpringTest.createTestMapContext(), true);
    }

    @Test(expected = Exception.class)
    public void testGeoNotUrlNotGeoJson() throws Exception {
        final File file = getFile(CreateMapProcessorFlexibleScaleBBoxGeoJsonTest.class, BASE_DIR + "geojson.json");
        final PJsonObject requestData = parseJSONObjectFromString("{type:\"geojson\";style:\"polygon\";geoJson:\"Random\"}");

        final Configuration configuration = new Configuration();
        configuration.setConfigurationFile(file);
        configuration.setFileLoaderManager(this.fileLoaderManager);

        Template template = new Template();
        template.setConfiguration(configuration);

        GeoJsonLayer.GeoJsonParam param = new GeoJsonLayer.GeoJsonParam();
        MapfishParserTest.populateLayerParam(requestData, param, "type");
        geojsonLayerParser.parse(template, param).getLayers(httpRequestFactory, AbstractMapfishSpringTest.createTestMapContext(), true);
    }

    @Test
    @DirtiesContext
    public void testUrl() throws Exception {
        final String host = "GeoJsonLayerTest.com";
        this.httpRequestFactory.registerHandler(
                new Predicate<URI>() {
                    @Override
                    public boolean apply(URI input) {
                        return (("" + input.getHost()).contains(host)) || input.getAuthority().contains(host);
                    }
                }, new TestHttpClientFactory.Handler() {
                    @Override
                    public MockClientHttpRequest handleRequest(URI uri, HttpMethod httpMethod) throws Exception {
                        try {
                            final File file = getFile(CreateMapProcessorFlexibleScaleBBoxGeoJsonTest.class, uri.getPath().substring(1));
                            byte[] bytes = Files.toByteArray(file);
                            return ok(uri, bytes, httpMethod);
                        } catch (AssertionError e) {
                            return error404(uri, httpMethod);
                        }
                    }
                }
        );
        final PJsonObject requestData = parseJSONObjectFromString("{type:\"geojson\";style:\"polygon\";geoJson:\"http://"
                                                                  + host + "/" + BASE_DIR + "geojson.json" + "\"}");

        final File file = getFile(CreateMapProcessorFlexibleScaleBBoxGeoJsonTest.class, BASE_DIR + "geojson.json");
        final Configuration configuration = new Configuration();
        configuration.setConfigurationFile(file);
        configuration.setFileLoaderManager(this.fileLoaderManager);

        Template template = new Template();
        template.setConfiguration(configuration);

        GeoJsonLayer.GeoJsonParam param = new GeoJsonLayer.GeoJsonParam();
        MapfishParserTest.populateLayerParam(requestData, param, "type");
        final GeoJsonLayer mapLayer = geojsonLayerParser.parse(template, param);

        assertNotNull(mapLayer);

        final List<? extends Layer> layers = mapLayer.getLayers(httpRequestFactory, AbstractMapfishSpringTest.createTestMapContext(), true);

        assertEquals(1, layers.size());

        FeatureLayer layer = (FeatureLayer) layers.get(0);
        final int count = layer.getFeatureSource().getCount(Query.ALL);
        assertEquals(3, count);
    }

    @Test
    public void testRelativeFileUrl() throws Exception {
        final File file = getFile(CreateMapProcessorFlexibleScaleBBoxGeoJsonTest.class, BASE_DIR + "geojson.json");
        final PJsonObject requestData = parseJSONObjectFromString("{type:\"geojson\";style:\"polygon\";geoJson:\"file://"
                                                                  + file.getName() + "\"}");

        final Configuration configuration = new Configuration();
        configuration.setConfigurationFile(file);
        configuration.setFileLoaderManager(this.fileLoaderManager);

        Template template = new Template();
        template.setConfiguration(configuration);

        GeoJsonLayer.GeoJsonParam param = new GeoJsonLayer.GeoJsonParam();
        MapfishParserTest.populateLayerParam(requestData, param, "type");
        final GeoJsonLayer mapLayer = geojsonLayerParser.parse(template, param);

        assertNotNull(mapLayer);

        final List<? extends Layer> layers = mapLayer.getLayers(httpRequestFactory, AbstractMapfishSpringTest.createTestMapContext(), true);

        assertEquals(1, layers.size());

        FeatureLayer layer = (FeatureLayer) layers.get(0);
        final int count = layer.getFeatureSource().getCount(Query.ALL);
        assertEquals(3, count);
        assertEquals(false, mapLayer.shouldRenderAsSvg());
    }
}


text:
class TradeRevenueTradeDateTrailer < ActiveRecord::Base
  # relationships .............................................................
  has_many :trade_revenue_trade_date_trades, :class_name => 'TradeRevenueTradeDateTrade', :primary_key => 'run_date', :foreign_key => 'run_date_01', :order => "id ASC"

  # validations ...............................................................
  validates_uniqueness_of :run_date
end


text:
package io.redlink.smarti.processor.token.filter;

import java.util.Collection;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import com.google.common.base.Objects;

import io.redlink.smarti.model.Conversation;
import io.redlink.smarti.model.Token;
import io.redlink.smarti.processor.token.TokenFilter;

@Component
@EnableConfigurationProperties(StopwordlistConfiguration.class)
public class StopwordlistTokenFilter implements TokenFilter {

    private final StopwordlistConfiguration config;

    public StopwordlistTokenFilter(StopwordlistConfiguration config) {
        this.config = config;
    }

    @Override
    public boolean filter(Token token, String lang, Conversation c) {
        if(token.getValue() == null){
            return false;
        } else if(!(token.getValue() instanceof CharSequence)){
            return false;
        }
        String value = String.valueOf(token.getValue());
        if(StringUtils.isBlank(value)){
            return false;
        }
        Locale locale = lang == null ? null : Locale.forLanguageTag(lang);
        //the key is the lower case stop word the values are case sensitive variants
        Map<String, Collection<String>> langStopwords = config.getStopwords(locale);
        Map<String, Collection<String>> defaultStopwords = config.getStopwords(null);
        Collection<String> defLangVariants = defaultStopwords != null ? defaultStopwords.get(value.toLowerCase(Locale.ROOT)) : null;
        Collection<String> langVariants = langStopwords != null ? langStopwords.get(value.toLowerCase(Locale.ROOT)) : null;
        if(defLangVariants == null && langVariants == null){
            return false;
        } else if(!isAllAlphaUpperCase(value)){ //TODO: make case sensitivity configurable (now SMART)
            return true;
        } else { //require an exact match with one of the variants
            return (defLangVariants == null ? langVariants : langVariants == null ?
                    defLangVariants : CollectionUtils.union(langVariants, defLangVariants)).stream()
                    .filter(sw -> Objects.equal(value, sw)).findAny().isPresent();

        }

    }

    /**
     * Checks if all {@link Character#isAlphabetic(char)} are also
     * {@link Character#isUpperCase(char)}.
     * @param cs
     * @return the state. false if the parsed sequence does not
     * contain a single alphabetic char
     */
    private static boolean isAllAlphaUpperCase(final CharSequence cs) {
        if(StringUtils.isBlank(cs)){
            return false;
        }
        final int sz = cs.length();
        boolean hasAlpha = false;
        for (int i = 0; i < sz; i++) {
            char c = cs.charAt(i);
            if(Character.isAlphabetic(c)){
                if(!Character.isUpperCase(c)){
                    return false;
                }
                hasAlpha = true;
            }
        }
        return hasAlpha; //return false if no alpha char is present
    }

}


text:
===========================
MP Tracker, Openpolitics.ro
===========================

http://parlament.openpolitics.ro/

A database of Romanian MPs and their activity. It crawls the `Chamber of
Deputies website`_ and extracts questions submitted by MPs.

.. _Chamber of Deputies website: http://www.cdep.ro/

Getting started
===============

The easy way, using Vagrant
~~~~~~~~~~~~~~~~~~~~~~~~~~~

1. Download and install vagrant_.

2. Set up the virtual machine. This will take a while and download
   several hundred MBs of images and packages::

    $ vagrant up

3. Log into the machine and start the app. It will be accessible at
http://localhost:5001/ (vagrant takes care of mapping port 5000 in the
VM to port 5001 on the host computer)::

    $ vagrant ssh
    $ cd /vagrant
    $ ./manage.py runserver -t 0.0.0.0

4. Load a database dump. Copy the archive to the repository root, then
import it::

    $ zcat /vagrant/mptracker-yyyy-mm-dd.sql.gz | psql mptracker

.. _vagrant: http://www.vagrantup.com/

The hard way, by hand
~~~~~~~~~~~~~~~~~~~~~
Requirements:

* Python 3.3
* PostgreSQL 9.3 (debian/ubuntu: https://wiki.postgresql.org/wiki/Apt )
* libxml, libxslt (debian/ubuntu: ``apt-get install libxml2-dev libxslt-dev``)

Install dependencies (consider using virtualenv_, it makes life easier
when working with multiple projects)::

    $ pip install -r requirements-dev.txt

Configure the application. Here's a sample ``settings.py`` (it should be
in the same folder as ``manage.py``)::

    DEBUG = True
    SECRET_KEY = 'foo'
    SQLALCHEMY_DATABASE_URI = 'postgresql:///mptracker'

Set up the database::

    $ createdb mptracker
    $ ./manage.py db sync

Run the application::

    $ ./manage.py runserver

.. _virtualenv: http://www.virtualenv.org/


text:
"""Find files and directories which IPython uses.
"""
import os.path
import shutil
import tempfile
from warnings import warn

import IPython
from IPython.utils.importstring import import_item
from IPython.utils.path import (
    get_home_dir, get_xdg_dir, get_xdg_cache_dir, compress_user, _writable_dir,
    ensure_dir_exists, fs_encoding, filefind
)
from IPython.utils import py3compat

def get_ipython_dir():
    """Get the IPython directory for this platform and user.

    This uses the logic in `get_home_dir` to find the home directory
    and then adds .ipython to the end of the path.
    """

    env = os.environ
    pjoin = os.path.join

    ipdir_def = '.ipython'

    home_dir = get_home_dir()
    xdg_dir = get_xdg_dir()

    # import pdb; pdb.set_trace()  # dbg
    if 'IPYTHON_DIR' in env:
        warn('The environment variable IPYTHON_DIR is deprecated. '
                'Please use IPYTHONDIR instead.')
    ipdir = env.get('IPYTHONDIR', env.get('IPYTHON_DIR', None))
    if ipdir is None:
        # not set explicitly, use ~/.ipython
        ipdir = pjoin(home_dir, ipdir_def)
        if xdg_dir:
            # Several IPython versions (up to 1.x) defaulted to .config/ipython
            # on Linux. We have decided to go back to using .ipython everywhere
            xdg_ipdir = pjoin(xdg_dir, 'ipython')

            if _writable_dir(xdg_ipdir):
                cu = compress_user
                if os.path.exists(ipdir):
                    warn(('Ignoring {0} in favour of {1}. Remove {0} to '
                        'get rid of this message').format(cu(xdg_ipdir), cu(ipdir)))
                elif os.path.islink(xdg_ipdir):
                    warn(('{0} is deprecated. Move link to {1} to '
                        'get rid of this message').format(cu(xdg_ipdir), cu(ipdir)))
                else:
                    warn('Moving {0} to {1}'.format(cu(xdg_ipdir), cu(ipdir)))
                    shutil.move(xdg_ipdir, ipdir)

    ipdir = os.path.normpath(os.path.expanduser(ipdir))

    if os.path.exists(ipdir) and not _writable_dir(ipdir):
        # ipdir exists, but is not writable
        warn("IPython dir '{0}' is not a writable location,"
                " using a temp directory.".format(ipdir))
        ipdir = tempfile.mkdtemp()
    elif not os.path.exists(ipdir):
        parent = os.path.dirname(ipdir)
        if not _writable_dir(parent):
            # ipdir does not exist and parent isn't writable
            warn("IPython parent '{0}' is not a writable location,"
                    " using a temp directory.".format(parent))
            ipdir = tempfile.mkdtemp()

    return py3compat.cast_unicode(ipdir, fs_encoding)

def get_ipython_cache_dir():
    """Get the cache directory it is created if it does not exist."""
    xdgdir = get_xdg_cache_dir()
    if xdgdir is None:
        return get_ipython_dir()
    ipdir = os.path.join(xdgdir, "ipython")
    if not os.path.exists(ipdir) and _writable_dir(xdgdir):
        ensure_dir_exists(ipdir)
    elif not _writable_dir(xdgdir):
        return get_ipython_dir()

    return py3compat.cast_unicode(ipdir, fs_encoding)

def get_ipython_package_dir():
    """Get the base directory where IPython itself is installed."""
    ipdir = os.path.dirname(IPython.__file__)
    return py3compat.cast_unicode(ipdir, fs_encoding)

def get_ipython_module_path(module_str):
    """Find the path to an IPython module in this version of IPython.

    This will always find the version of the module that is in this importable
    IPython package. This will always return the path to the ``.py``
    version of the module.
    """
    if module_str == 'IPython':
        return os.path.join(get_ipython_package_dir(), '__init__.py')
    mod = import_item(module_str)
    the_path = mod.__file__.replace('.pyc', '.py')
    the_path = the_path.replace('.pyo', '.py')
    return py3compat.cast_unicode(the_path, fs_encoding)

def locate_profile(profile='default'):
    """Find the path to the folder associated with a given profile.

    I.e. find $IPYTHONDIR/profile_whatever.
    """
    from IPython.core.profiledir import ProfileDir, ProfileDirError
    try:
        pd = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile)
    except ProfileDirError:
        # IOError makes more sense when people are expecting a path
        raise IOError("Couldn't find profile %r" % profile)
    return pd.location


text:
require 'facets/proc/bind'

unless (RUBY_VERSION[0,3] == '1.9')

  module Kernel

    # Like instance_eval but allows parameters to be passed.
    #
    # NOTE: This is deprecated b/c implementation is fragile.
    # Use Ruby 1.9 instead.

    def instance_exec(*arguments, &block)
      block.bind(self)[*arguments]
    end

  end

end


text:
/*
 * Floern, dev@floern.com, 2017, MIT Licence
 */
package com.floern.genericbot.frame.net;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class HttpPostUrlEncoded extends HttpPost {

	public HttpPostUrlEncoded(String url, String... data) {
		this(url, IntStream.range(1, data.length)
				.filter(i -> (i & 1) == 1)
				.mapToObj(i -> new BasicNameValuePair(data[i - 1], data[i]))
				.collect(Collectors.toList()));
	}

	public HttpPostUrlEncoded(String url, List<NameValuePair> data) {
		super(url);

		try {
			StringEntity dataEntity = new UrlEncodedFormEntity(data);
			setEntity(dataEntity);
		}
		catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}

}