text:
package header

import (
	"encoding/binary"

	"github.com/google/netstack/tcpip"
	"github.com/google/netstack/tcpip/buffer"
)

// ICMPv6 represents an ICMPv6 header stored in a byte array.
type ICMPv6 []byte

const (
	// ICMPv6HeaderSize is the size of the ICMPv6 header. That is, the
	// sum of the size of the ICMPv6 Type, Code and Checksum fields, as
	// per RFC 4443 section 2.1. After the ICMPv6 header, the ICMPv6
	// message body begins.
	ICMPv6HeaderSize = 4

	// ICMPv6MinimumSize is the minimum size of a valid ICMP packet.
	ICMPv6MinimumSize = 8

	// ICMPv6PayloadOffset is the offset of the payload in an
	// ICMP packet.
	ICMPv6PayloadOffset = 8

	// ICMPv6ProtocolNumber is the ICMP transport protocol number.
	ICMPv6ProtocolNumber tcpip.TransportProtocolNumber = 58

	// ICMPv6NeighborSolicitMinimumSize is the minimum size of a
	// neighbor solicitation packet.
	ICMPv6NeighborSolicitMinimumSize = ICMPv6HeaderSize + NDPNSMinimumSize

	// ICMPv6NeighborAdvertMinimumSize is the minimum size of a
	// neighbor advertisement packet.
	ICMPv6NeighborAdvertMinimumSize = ICMPv6HeaderSize + NDPNAMinimumSize

	// ICMPv6NeighborAdvertSize is size of a neighbor advertisement
	// including the NDP Target Link Layer option for an Ethernet
	// address.
	ICMPv6NeighborAdvertSize = ICMPv6HeaderSize + NDPNAMinimumSize + ndpTargetEthernetLinkLayerAddressSize

	// ICMPv6EchoMinimumSize is the minimum size of a valid ICMP echo packet.
	ICMPv6EchoMinimumSize = 8

	// ICMPv6DstUnreachableMinimumSize is the minimum size of a valid ICMP
	// destination unreachable packet.
	ICMPv6DstUnreachableMinimumSize = ICMPv6MinimumSize

	// ICMPv6PacketTooBigMinimumSize is the minimum size of a valid ICMP
	// packet-too-big packet.
	ICMPv6PacketTooBigMinimumSize = ICMPv6MinimumSize

	// icmpv6ChecksumOffset is the offset of the checksum field
	// in an ICMPv6 message.
	icmpv6ChecksumOffset = 2

	// icmpv6MTUOffset is the offset of the MTU field in an ICMPv6
	// PacketTooBig message.
	icmpv6MTUOffset = 4

	// icmpv6IdentOffset is the offset of the ident field
	// in a ICMPv6 Echo Request/Reply message.
	icmpv6IdentOffset = 4

	// icmpv6SequenceOffset is the offset of the sequence field
	// in a ICMPv6 Echo Request/Reply message.
	icmpv6SequenceOffset = 6

	// NDPHopLimit is the expected IP hop limit value of 255 for received
	// NDP packets, as per RFC 4861 sections 4.1 - 4.5, 6.1.1, 6.1.2, 7.1.1,
	// 7.1.2 and 8.1. If the hop limit value is not 255, nodes MUST silently
	// drop the NDP packet. All outgoing NDP packets must use this value for
	// its IP hop limit field.
	NDPHopLimit = 255
)

// ICMPv6Type is the ICMP type field described in RFC 4443 and friends.
type ICMPv6Type byte

// Typical values of ICMPv6Type defined in RFC 4443.
const (
	ICMPv6DstUnreachable ICMPv6Type = 1
	ICMPv6PacketTooBig   ICMPv6Type = 2
	ICMPv6TimeExceeded   ICMPv6Type = 3
	ICMPv6ParamProblem   ICMPv6Type = 4
	ICMPv6EchoRequest    ICMPv6Type = 128
	ICMPv6EchoReply      ICMPv6Type = 129

	// Neighbor Discovery Protocol (NDP) messages, see RFC 4861.

	ICMPv6RouterSolicit   ICMPv6Type = 133
	ICMPv6RouterAdvert    ICMPv6Type = 134
	ICMPv6NeighborSolicit ICMPv6Type = 135
	ICMPv6NeighborAdvert  ICMPv6Type = 136
	ICMPv6RedirectMsg     ICMPv6Type = 137
)

// Values for ICMP code as defined in RFC 4443.
const (
	ICMPv6PortUnreachable = 4
)

// Type is the ICMP type field.
func (b ICMPv6) Type() ICMPv6Type { return ICMPv6Type(b[0]) }

// SetType sets the ICMP type field.
func (b ICMPv6) SetType(t ICMPv6Type) { b[0] = byte(t) }

// Code is the ICMP code field. Its meaning depends on the value of Type.
func (b ICMPv6) Code() byte { return b[1] }

// SetCode sets the ICMP code field.
func (b ICMPv6) SetCode(c byte) { b[1] = c }

// Checksum is the ICMP checksum field.
func (b ICMPv6) Checksum() uint16 {
	return binary.BigEndian.Uint16(b[icmpv6ChecksumOffset:])
}

// SetChecksum sets the ICMP checksum field.
func (b ICMPv6) SetChecksum(checksum uint16) {
	binary.BigEndian.PutUint16(b[icmpv6ChecksumOffset:], checksum)
}

// SourcePort implements Transport.SourcePort.
func (ICMPv6) SourcePort() uint16 {
	return 0
}

// DestinationPort implements Transport.DestinationPort.
func (ICMPv6) DestinationPort() uint16 {
	return 0
}

// SetSourcePort implements Transport.SetSourcePort.
func (ICMPv6) SetSourcePort(uint16) {
}

// SetDestinationPort implements Transport.SetDestinationPort.
func (ICMPv6) SetDestinationPort(uint16) {
}

// MTU retrieves the MTU field from an ICMPv6 message.
func (b ICMPv6) MTU() uint32 {
	return binary.BigEndian.Uint32(b[icmpv6MTUOffset:])
}

// SetMTU sets the MTU field from an ICMPv6 message.
func (b ICMPv6) SetMTU(mtu uint32) {
	binary.BigEndian.PutUint32(b[icmpv6MTUOffset:], mtu)
}

// Ident retrieves the Ident field from an ICMPv6 message.
func (b ICMPv6) Ident() uint16 {
	return binary.BigEndian.Uint16(b[icmpv6IdentOffset:])
}

// SetIdent sets the Ident field from an ICMPv6 message.
func (b ICMPv6) SetIdent(ident uint16) {
	binary.BigEndian.PutUint16(b[icmpv6IdentOffset:], ident)
}

// Sequence retrieves the Sequence field from an ICMPv6 message.
func (b ICMPv6) Sequence() uint16 {
	return binary.BigEndian.Uint16(b[icmpv6SequenceOffset:])
}

// SetSequence sets the Sequence field from an ICMPv6 message.
func (b ICMPv6) SetSequence(sequence uint16) {
	binary.BigEndian.PutUint16(b[icmpv6SequenceOffset:], sequence)
}

// NDPPayload returns the NDP payload buffer. That is, it returns the ICMPv6
// packet's message body as defined by RFC 4443 section 2.1; the portion of the
// ICMPv6 buffer after the first ICMPv6HeaderSize bytes.
func (b ICMPv6) NDPPayload() []byte {
	return b[ICMPv6HeaderSize:]
}

// Payload implements Transport.Payload.
func (b ICMPv6) Payload() []byte {
	return b[ICMPv6PayloadOffset:]
}

// ICMPv6Checksum calculates the ICMP checksum over the provided ICMPv6 header,
// IPv6 src/dst addresses and the payload.
func ICMPv6Checksum(h ICMPv6, src, dst tcpip.Address, vv buffer.VectorisedView) uint16 {
	// Calculate the IPv6 pseudo-header upper-layer checksum.
	xsum := Checksum([]byte(src), 0)
	xsum = Checksum([]byte(dst), xsum)
	var upperLayerLength [4]byte
	binary.BigEndian.PutUint32(upperLayerLength[:], uint32(len(h)+vv.Size()))
	xsum = Checksum(upperLayerLength[:], xsum)
	xsum = Checksum([]byte{0, 0, 0, uint8(ICMPv6ProtocolNumber)}, xsum)
	for _, v := range vv.Views() {
		xsum = Checksum(v, xsum)
	}

	// h[2:4] is the checksum itself, set it aside to avoid checksumming the checksum.
	h2, h3 := h[2], h[3]
	h[2], h[3] = 0, 0
	xsum = ^Checksum(h, xsum)
	h[2], h[3] = h2, h3

	return xsum
}


text:
@interface NNRelatedTags (PrivateAPI)

- (void)updateRelatedTags;
- (NNTag*)getTagWithBestAbsoluteRating:(NSArray*)tags;

- (void)setUpdating:(BOOL)flag;

- (void)setRelatedTags:(NSMutableArray*)otherTags;

- (void)addTag:(NNTag*)aTag;
- (void)addTags:(NSArray*)someTags;

- (void)removeTag:(NNTag*)aTag;
- (void)removeTags:(NSArray*)someTags;

@end

@implementation NNRelatedTags

#pragma mark init + dealloc

- (id)initWithQuery:(NNQuery*)aQuery;
{
	if (self = [super init])
	{
		tags = [NNTags sharedTags];

		[self setUpdating:NO];

		[self setQuery:aQuery];
		[self setRelatedTags:[NSMutableArray array]];

		//register with notificationcenter - listen for changes in the query results -- activeFiles is the query
		nc = [NSNotificationCenter defaultCenter];
		[nc addObserver:self selector:@selector(queryNote:) name:nil object:query];
	}
	return self;
}

- (void)dealloc
{
	[nc removeObserver:self];
	[relatedTags release];
	[query release];
	[super dealloc];
}

#pragma mark accessors
- (void)addTag:(NNTag*)aTag
{
	[relatedTags addObject:aTag];

	[nc postNotificationName:@"NNRelatedTagsHaveChanged" object:self];
}

- (void)addTags:(NSArray*)someTags
{
	[relatedTags addObjectsFromArray:someTags];

	[nc postNotificationName:@"NNRelatedTagsHaveChanged" object:self];
}

- (void)removeTag:(NNTag*)aTag
{
	if ([relatedTags count] > 0)
	{
		[relatedTags removeObject:aTag];

		[nc postNotificationName:@"NNRelatedTagsHaveChanged" object:self];
	}
}

- (void)removeTags:(NSArray*)someTags
{
	NSUInteger beforeCount = [self count];

	[relatedTags removeObjectsInArray:someTags];

	// post notification if something was removed
	if ([self count] < beforeCount)
		[nc postNotificationName:@"NNRelatedTagsHaveChanged" object:self];
}

- (BOOL)isUpdating
{
	return updating;
}

- (void)setUpdating:(BOOL)flag
{
	updating = flag;
}

- (BOOL)containsTag:(NNTag*)aTag
{
	return [relatedTags containsObject:aTag];
}

- (void)setQuery:(NNQuery*)aQuery
{
	[aQuery retain];
	[query release];
	query = aQuery;
}

- (NSArray*)relatedTagArray
{
	return relatedTags;
}

- (NSMutableArray*)relatedTags;
{
	return relatedTags;
}

- (NSUInteger)count
{
	return [relatedTags count];
}

- (void)setRelatedTags:(NSMutableArray*)otherTags
{
	[otherTags retain];
	[relatedTags release];
	relatedTags = otherTags;

	[nc postNotificationName:@"NNRelatedTagsHaveChanged" object:self];
}

- (void)removeAllTags
{
	if ([self count] > 0)
	{
		[relatedTags removeAllObjects];

		[nc postNotificationName:@"NNRelatedTagsHaveChanged" object:self];
	}
}

#pragma mark logic
//act on query notifications -- relatedTags need to be kept in sync with files
- (void)queryNote:(NSNotification*)note
{
	// check if objects are available
	if ([note name] == nil)
	{
		lcl_log(lcl_cnntagging, lcl_vError, @"Notificaton name not available");
		return;
	}

	// do the work
	if ([[note name] isEqualToString:NNQueryDidStartGatheringNotification])
	{
		[self setUpdating:YES];
	}
	else if ([[note name] isEqualToString:NNQueryGatheringProgressNotification]
			 || [[note name] isEqualToString:NNQueryDidUpdateNotification])
	{
		[self updateRelatedTags];
	}
	else if ([[note name] isEqualToString:NNQueryDidFinishGatheringNotification])
	{
		[self updateRelatedTags];
		[self setUpdating:NO];

		// if no tags what so ever have been found, post notification so that tag cloud
		// can update its message
		if ([self count] == 0)
		{
			[nc postNotificationName:@"NNRelatedTagsHaveChanged" object:self];
		}
	}
	else if ([[note name] isEqualToString:NNQueryDidResetNotification])
	{
		[self removeAllTags];
	}
}

- (void)updateRelatedTags
{
	[query disableUpdates];

	NSMutableArray *newRelatedTags = [NSMutableArray array];

	for (NNTaggableObject* taggableObject in [query flatPlainResults])
	{
		//get the related tags to the current results
		for (NNTag* tag in [taggableObject tags])
		{
			if (![newRelatedTags containsObject:tag])
			{
				// only add if not already present
				[newRelatedTags addObject:tag];
			}
		}
	}

	// remove old related Tags which are not present anymore
	NSMutableArray *tagsToDelete = [NSMutableArray array];

	for (NNTag* oldRelatedTag in relatedTags)
	{
		if (![newRelatedTags containsObject:oldRelatedTag])
		{
			// old related tag could not be found anymore,
			// maybe a relation was deleted
			// or the selected tags have changed completely
			[tagsToDelete addObject:oldRelatedTag];
		}
		else
		{
			// otherwise remove the tag from the new tags
			[newRelatedTags removeObject:oldRelatedTag];
		}
	}
	// newRelatedTags now holds only newly found related tags ;)

	// remove tags from selected tags from newRelatedTags
	NNSelectedTags *selectedTags = [query tags];
	[newRelatedTags removeObjectsInArray:[selectedTags selectedTags]];

	// remove tags in tagsToDelete from related Tags - post a single notification
	[self removeTags:tagsToDelete];

	// add new tags if there are any
	if ([newRelatedTags count] > 0)
		[self addTags:newRelatedTags];

	// reenable the query
	[query enableUpdates];
}

- (NSString*)description
{
	return [NSString stringWithFormat:@"Related Tags: %@",relatedTags];
}

@end

redpajama_set_name: RedPajamaGithub


text:
package ru.szhernovoy;

/**
 * Created by szhernovoy on 22.07.2016.
 */
public class MockIO implements IO {

    private String[] answers;
    private StringBuilder out = new StringBuilder();
    private int position = 0;

    public MockIO(String[] answer){
        this.answers = answer;
    }

    @Override
    public void println(Object value) {
        this.out.append(value).append("\n");
    }

    @Override
    public void print(Object value) {
        this.out.append(value).append("\n");
    }

    @Override
    public String read() {
        return answers[position++];
    }

    public String getOut(){
        return this.out.toString();
    }
}


text:
module BootstrapColorpicker2
      module Rails
        VERSION = '2.0.0'
      end
end


text:
<?php

if(!isset($member) || substr($_SERVER['PHP_SELF'], -11) != "console.php") {
	exit();
}
else {
	$memberInfo = $member->get_info();
	$consoleObj->select($_GET['cID']);
	if(!$member->hasAccess($consoleObj)) {
		exit();
	}
}

include_once($prevFolder."classes/btupload.php");
include_once($prevFolder."classes/medal.php");
$cID = $_GET['cID'];
$medalObj = new Medal($mysqli);

	$getMedals = $mysqli->query("SELECT * FROM ".$dbprefix."medals ORDER BY ordernum DESC");
	$medalOptions = array();
	while($arrMedals = $getMedals->fetch_assoc()) {
		$medalName = filterText($arrMedals['name']);
		$medalOptions[$arrMedals['medal_id']] = $medalName;

	}

	if(count($medalOptions) == 0) {
		$medalOptions['first'] = "(first medal)";
	}

	$i = 1;
	$arrComponents = array(
		"generalinfo" => array(
			"type" => "section",
			"options" => array("section_title" => "General Information:"),
			"sortorder" => $i++,
		),
		"medalname" => array(
			"type" => "text",
			"attributes" => array("class" => "textBox formInput"),
			"sortorder" => $i++,
			"db_name" => "name",
			"display_name" => "Medal Name",
			"validate" => array("NOT_BLANK")
		),
		"medalimage" => array(
			"type" => "file",
			"attributes" => array("class" => "textBox", "style" => "width: 100%"),
			"db_name" => "imageurl",
			"sortorder" => $i++,
			"options" => array("file_types" => array(".gif", ".png", ".jpg", ".bmp"), "file_prefix" => "medal_", "save_loc" => "../images/medals/", "ext_length" => 4, "append_db_value" => "images/medals/"),
			"display_name" => "Medal Image",
			"validate" => array("NOT_BLANK")
		),
		"medalimagewidth" => array(
			"type" => "text",
			"attributes" => array("class" => "textBox formInput", "style" => "width: 5%"),
			"html" => "
px
",
			"tooltip" => "Set the Image Width to the width that you would like the Medal Image to be displayed on your website.",
			"db_name" => "imagewidth",
			"validate" => array("POSITIVE_NUMBER"),
			"display_name" => "Image Width",
			"sortorder" => $i++
		),
		"medalimageheight" => array(
			"type" => "text",
			"attributes" => array("class" => "textBox formInput", "style" => "width: 5%"),
			"html" => "
px
",
			"tooltip" => "Set the Image Height to the height that you would like the Medal Image to be displayed on your website.",
			"db_name" => "imageheight",
			"validate" => array("POSITIVE_NUMBER"),
			"display_name" => "Image Height",
			"sortorder" => $i++
		),
		"medaldesc" => array(
			"type" => "textarea",
			"attributes" => array("class" => "textBox formInput", "rows" => 5, "cols" => 40),
			"db_name" => "description",
			"sortorder" => $i++,
			"display_name" => "Description"
		),
		"displayorder" => array(
			"type" => "beforeafter",
			"attributes" => array("class" => "textBox"),
			"display_name" => "Display Order",
			"options" => $medalOptions,
			"db_name" => "ordernum",
			"sortorder" => $i++,
			"validate" => array(array("name" => "VALIDATE_ORDER", "orderObject" => $medalObj))

		),
		"autoawardinfo" => array(
			"type" => "section",
			"options" => array("section_title" => "Auto-Award Information:", "section_description" => "Set these options if you want a member to be automatically awarded for being in the clan a certain number of days or recruiting a certain amount of members. Leave blank or 0 to disable this option."),
			"sortorder" => $i++
		),
		"autodays" => array(
			"type" => "text",
			"attributes" => array("class" => "textBox formInput", "style" => "width: 5%"),
			"display_name" => "Auto-Days",
			"sortorder" => $i++,
			"db_name" => "autodays"
		),
		"autorecruits" => array(
			"type" => "text",
			"attributes" => array("class" => "textBox formInput", "style" => "width: 5%"),
			"display_name" => "Auto-Recruits",
			"sortorder" => $i++,
			"db_name" => "autorecruits"
		),
		"submit" => array(
			"type" => "submit",
			"attributes" => array("class" => "submitButton formSubmitButton"),
			"value" => "Add Medal",
			"sortorder" => $i++
		)
	);

	$setupFormArgs = array(
		"name" => "console-".$cID,
		"components" => $arrComponents,
		"description" => "Fill out the form below to add a new medal.

NOTE: When adding a Medal Image, if both the File and URL are filled out, the File will be used.",
		"saveObject" => $medalObj,
		"saveMessage" => "Successfully Added New Medal: ".filterText($_POST['medalname'])."!",
		"saveType" => "add",
		"attributes" => array("action" => $MAIN_ROOT."members/console.php?cID=".$cID, "method" => "post"),
		"beforeAfter" => true
	);

?>


text:
package lambdasinaction.chap5;

import java.util.*;
import java.util.function.*;
import java.util.stream.*;

import static java.util.stream.Collectors.*;
import static lambdasinaction.chap5.Dish.menu;

public class Reducing {

    public static void main(String ... args) {
        System.out.println("Total calories in menu: " + calculateTotalCalories());
        System.out.println("Total calories in menu: " + calculateTotalCaloriesWithMethodReference());
        System.out.println("Total calories in menu: " + calculateTotalCaloriesWithoutCollectors());
        System.out.println("Total calories in menu: " + calculateTotalCaloriesUsingSum());
    }

    private static int calculateTotalCalories() {
        return menu.stream().collect(reducing(0, Dish::getCalories, (Integer i, Integer j) -> i + j));
    }

    private static int calculateTotalCaloriesWithMethodReference() {
        return menu.stream().collect(reducing(0, Dish::getCalories, Integer::sum));
    }

    private static int calculateTotalCaloriesWithoutCollectors() {
        return menu.stream().map(Dish::getCalories).reduce(Integer::sum).get();
    }

    private static int calculateTotalCaloriesUsingSum() {
        return menu.stream().mapToInt(Dish::getCalories).sum();
    }
}


text:
import numpy as np
import math
import time
import datetime
import urllib2
from scipy import stats
from django.utils import timezone

def get_slope(values):
    v_max = np.max(values)
    v_min = np.min(values)
    n_value = len(values)

    slope, intercept, r_value, p_value, std_err = stats.linregress(np.linspace(v_min, v_max, n_value), values)

    if math.isnan(slope):
        slope = 0
    return slope

def get_stock_history(stock, period=30):
    dt = timezone.now()
    past = dt + datetime.timedelta(days=-period)
    return stock.stockhistory_set.filter(pub_date__gte=past).order_by('pub_date')

def safe_request(url):
    header = {'User-Agent': 'Mozilla/5.0'}

    html = ""
    retry = 1200
    while not html:
        try:
            html = urllib2.urlopen(
                urllib2.Request(
                    url, headers=header
                )
            )
        except urllib2.HTTPError as e:
            if e.fp.getcode() < 500:
                break

            print 'Retry in {} mins'.format(retry/60)
            html = ""
            time.sleep(retry)
            retry *= 2
        except:
            break

    return html


text:
using Microsoft.Extensions.DependencyInjection;
using Umbraco.Cms.Core.Cache;
using Umbraco.Cms.Core.DependencyInjection;
using Umbraco.Cms.Core.Notifications;
using Umbraco.Cms.Core.Sync;
using Umbraco.Cms.Infrastructure.Sync;
using Umbraco.Extensions;

namespace Umbraco.Cms.Infrastructure.DependencyInjection;

/// <summary>
///     Provides extension methods to the <see cref="IUmbracoBuilder" /> class.
/// </summary>
public static partial class UmbracoBuilderExtensions
{
    /// <summary>
    ///     Adds distributed cache support
    /// </summary>
    /// <remarks>
    ///     This is still required for websites that are not load balancing because this ensures that sites hosted
    ///     with managed hosts like IIS/etc... work correctly when AppDomains are running in parallel.
    /// </remarks>
    public static IUmbracoBuilder AddDistributedCache(this IUmbracoBuilder builder)
    {
        builder.Services.AddSingleton<LastSyncedFileManager>();
        builder.Services.AddSingleton<ISyncBootStateAccessor, SyncBootStateAccessor>();
        builder.SetServerMessenger<BatchedDatabaseServerMessenger>();
builder.AddNotificationHandler<UmbracoApplicationStartingNotification, DatabaseServerMessengerNotificationHandler>();
        builder.AddNotificationHandler<UmbracoRequestEndNotification, DatabaseServerMessengerNotificationHandler>();
        return builder;
    }

    /// <summary>
    ///     Sets the server registrar.
    /// </summary>
    /// <typeparam name="T">The type of the server registrar.</typeparam>
    /// <param name="builder">The builder.</param>
    public static IUmbracoBuilder SetServerRegistrar<T>(this IUmbracoBuilder builder)
        where T : class, IServerRoleAccessor
    {
        builder.Services.AddUnique<IServerRoleAccessor, T>();
        return builder;
    }

    /// <summary>
    ///     Sets the server registrar.
    /// </summary>
    /// <param name="builder">The builder.</param>
    /// <param name="factory">A function creating a server registrar.</param>
    public static IUmbracoBuilder SetServerRegistrar(
        this IUmbracoBuilder builder,
        Func<IServiceProvider, IServerRoleAccessor> factory)
    {
        builder.Services.AddUnique(factory);
        return builder;
    }

    /// <summary>
    ///     Sets the server registrar.
    /// </summary>
    /// <param name="builder">The builder.</param>
    /// <param name="registrar">A server registrar.</param>
    public static IUmbracoBuilder SetServerRegistrar(this IUmbracoBuilder builder, IServerRoleAccessor registrar)
    {
        builder.Services.AddUnique(registrar);
        return builder;
    }

    /// <summary>
    ///     Sets the server messenger.
    /// </summary>
    /// <typeparam name="T">The type of the server registrar.</typeparam>
    /// <param name="builder">The builder.</param>
    public static IUmbracoBuilder SetServerMessenger<T>(this IUmbracoBuilder builder)
        where T : class, IServerMessenger
    {
        builder.Services.AddUnique<IServerMessenger, T>();
        return builder;
    }

    /// <summary>
    ///     Sets the server messenger.
    /// </summary>
    /// <param name="builder">The builder.</param>
    /// <param name="factory">A function creating a server messenger.</param>
    public static IUmbracoBuilder SetServerMessenger(
        this IUmbracoBuilder builder,
        Func<IServiceProvider, IServerMessenger> factory)
    {
        builder.Services.AddUnique(factory);
        return builder;
    }

    /// <summary>
    ///     Sets the server messenger.
    /// </summary>
    /// <param name="builder">The builder.</param>
    /// <param name="registrar">A server messenger.</param>
    public static IUmbracoBuilder SetServerMessenger(this IUmbracoBuilder builder, IServerMessenger registrar)
    {
        builder.Services.AddUnique(registrar);
        return builder;
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>nucleo-dynamixel: HAL COMP Aliased Macros maintained for legacy purpose</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

nucleo-dynamixel
    0.0.1

A library for controlling dynamixel servomotors, designed for nucleo stm32

Main Page

Related Pages

Modules

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Macros

HAL COMP Aliased Macros maintained for legacy purpose

Macros

#define 	__HAL_COMP_EXTI_RISING_IT_ENABLE(__EXTILINE__)

#define 	__HAL_COMP_EXTI_RISING_IT_DISABLE(__EXTILINE__)

#define 	__HAL_COMP_EXTI_FALLING_IT_ENABLE(__EXTILINE__)

#define 	__HAL_COMP_EXTI_FALLING_IT_DISABLE(__EXTILINE__)

#define 	__HAL_COMP_EXTI_ENABLE_IT(__EXTILINE__)

#define 	__HAL_COMP_EXTI_DISABLE_IT(__EXTILINE__)

#define 	__HAL_COMP_EXTI_GET_FLAG(__FLAG__)

#define 	__HAL_COMP_EXTI_CLEAR_FLAG(__FLAG__)

#define 	__HAL_COMP_GET_EXTI_LINE   COMP_GET_EXTI_LINE

Detailed Description

Macro Definition Documentation

          #define __HAL_COMP_EXTI_CLEAR_FLAG
          (

          __FLAG__	)

Value:

(((__FLAG__)  == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_CLEAR_FLAG() : \

                                                          __HAL_COMP_COMP2_EXTI_CLEAR_FLAG())

          #define __HAL_COMP_EXTI_DISABLE_IT
          (

          __EXTILINE__	)

Value:

(((__EXTILINE__)  == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_DISABLE_IT() : \

                                                          __HAL_COMP_COMP2_EXTI_DISABLE_IT())

          #define __HAL_COMP_EXTI_ENABLE_IT
          (

          __EXTILINE__	)

Value:

(((__EXTILINE__)  == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_IT() : \

                                                          __HAL_COMP_COMP2_EXTI_ENABLE_IT())

          #define __HAL_COMP_EXTI_FALLING_IT_DISABLE
          (

          __EXTILINE__	)

Value:

(((__EXTILINE__)  == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_FALLING_EDGE() : \

                                                          __HAL_COMP_COMP2_EXTI_DISABLE_FALLING_EDGE())

          #define __HAL_COMP_EXTI_FALLING_IT_ENABLE
          (

          __EXTILINE__	)

Value:

(((__EXTILINE__)  == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_FALLING_EDGE() : \

                                                          __HAL_COMP_COMP2_EXTI_ENABLE_FALLING_EDGE())

          #define __HAL_COMP_EXTI_GET_FLAG
          (

          __FLAG__	)

Value:

(((__FLAG__)  == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_GET_FLAG() : \

                                                          __HAL_COMP_COMP2_EXTI_GET_FLAG())

          #define __HAL_COMP_EXTI_RISING_IT_DISABLE
          (

          __EXTILINE__	)

Value:

(((__EXTILINE__)  == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_RISING_EDGE() : \

                                                          __HAL_COMP_COMP2_EXTI_DISABLE_RISING_EDGE())

          #define __HAL_COMP_EXTI_RISING_IT_ENABLE
          (

          __EXTILINE__	)

Value:

(((__EXTILINE__)  == COMP_EXTI_LINE_COMP1) ? __HAL_COMP_COMP1_EXTI_ENABLE_RISING_EDGE() : \

                                                          __HAL_COMP_COMP2_EXTI_ENABLE_RISING_EDGE())

Generated by

     1.8.11


text:
import warnings
from typing import Any
from typing import Callable
from typing import List

from openapi_core.deserializing.exceptions import DeserializeError
from openapi_core.deserializing.parameters.datatypes import (
    DeserializerCallable,
)
from openapi_core.deserializing.parameters.exceptions import (
    EmptyQueryParameterValue,
)
from openapi_core.schema.parameters import get_aslist
from openapi_core.schema.parameters import get_explode
from openapi_core.spec import Spec

class BaseParameterDeserializer:
    def __init__(self, param_or_header: Spec, style: str):
        self.param_or_header = param_or_header
        self.style = style

    def __call__(self, value: Any) -> Any:
        raise NotImplementedError

class UnsupportedStyleDeserializer(BaseParameterDeserializer):
    def __call__(self, value: Any) -> Any:
        warnings.warn(f"Unsupported {self.style} style")
        return value

class CallableParameterDeserializer(BaseParameterDeserializer):
    def __init__(
        self,
        param_or_header: Spec,
        style: str,
        deserializer_callable: DeserializerCallable,
    ):
        super().__init__(param_or_header, style)
        self.deserializer_callable = deserializer_callable

        self.aslist = get_aslist(self.param_or_header)
        self.explode = get_explode(self.param_or_header)

    def __call__(self, value: Any) -> Any:
        # if "in" not defined then it's a Header
        if "allowEmptyValue" in self.param_or_header:
            warnings.warn(
                "Use of allowEmptyValue property is deprecated",
                DeprecationWarning,
            )
        allow_empty_values = self.param_or_header.getkey(
            "allowEmptyValue", False
        )
        location_name = self.param_or_header.getkey("in", "header")
        if location_name == "query" and value == "" and not allow_empty_values:
            name = self.param_or_header["name"]
            raise EmptyQueryParameterValue(name)

        if not self.aslist or self.explode:
            return value
        try:
            return self.deserializer_callable(value)
        except (ValueError, TypeError, AttributeError):
            raise DeserializeError(location_name, self.style, value)


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
   Copyright 2008-2015 Genentech Inc.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
-->
<sqls xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
      xsi:noNamespaceSchemaLocation='../../../code/java/src/com/aestel/io/dataAccess/sql.xsd'>
<toolConfig>
   <exporter xmlns:noNamespaceSchemaLocation='http://www.gene.com/2008/cheminfo/exporter'>
      <outPrefix>demo</outPrefix>

      <commands>
         sdfExport.pl $sqlFile sdf        -o structs.sdf
      </commands>

      <email>test@test.com</email>
      <mailText>
      This is for testing only and not meant to be used for production

      For questions please e-mail: test@test.com

      Best regards the bot.
      </mailText>
   </exporter>
</toolConfig>

    <sql name='sdf' paramTypes="int">
    <![CDATA[
      select
         c.chemistry MOLFILE, cl.salt_code, cl.cl.compound_lot_id, cl.structure_id
      from SUBSTANCE_CHEMISTRY c
         join compound_lots cl on cl.structure_id = c.substance_id
      where c.chemistry is not null
        and cl.compound_lot_id=?
    ]]>
    </sql>

</sqls>


text:
DEFINE_double(delta, fst::kDelta, "Comparison/quantization delta");
DEFINE_int64(nstate, fst::kNoStateId, "State number threshold");
DEFINE_string(weight, "", "Weight threshold");
DEFINE_int64(subsequential_label, 0,
             "Input label of arc corresponding to residual final output when"
             " producing a subsequential transducer");

int main(int argc, char **argv) {
  namespace s = fst::script;
  using fst::script::FstClass;
  using fst::script::MutableFstClass;
  using fst::script::VectorFstClass;
  using fst::script::WeightClass;

  string usage = "Determinizes an FST.\n\n  Usage: ";
  usage += argv[0];
  usage += " [in.fst [out.fst]]\n";

  std::set_new_handler(FailedNewHandler);
  SET_FLAGS(usage.c_str(), &argc, &argv, true);
  if (argc > 3) {
    ShowUsage();
    return 1;
  }

  string in_name = (argc > 1 && strcmp(argv[1], "-") != 0) ? argv[1] : "";
  string out_name = argc > 2 ? argv[2] : "";

  FstClass *ifst = FstClass::Read(in_name);
  if (!ifst) return 1;

  VectorFstClass ofst(ifst->ArcType());

  s::DeterminizeOptions opts(
      FLAGS_delta, FLAGS_weight.empty() ?
      WeightClass::Zero() : WeightClass(ifst->WeightType(), FLAGS_weight),
      FLAGS_nstate, FLAGS_subsequential_label);

  s::Determinize(*ifst, &ofst, opts);

  ofst.Write(out_name);

  return 0;
}


text:
/* Prerequisite
create an Trakt API App at: https://trakt.tv/oauth/applications/new
*/

/*  Docker run command
docker run -d --name compare-trakt-and-radarr \
-v "<host path to app config location>":"/config" \
-v "<host path of watch folder from Handbrake container>":"/watch" \
-e traktFriendID="<friends trakt ID>" \
-e traktClientID="<from Trakt API App>" \
-e radarrIP="<http://radarr.ip.address>" \
-e radarrPort="<7878>" \
-e radarrApiKey="<Radarr API Key>" \
-e hbVolumeMappingHandbrake="<Media storage path from Handbrake container>" \
-e hbVolumeMappingRadarr="<Media storage path from Radarr container>" \
-e movieHistory="path to movieHistory.txt from within this container" \
compare-trakt-and-radarr
*/

var { exec } = require('child_process');
var request = require('request');
var fs = require('fs');

if (process.env.traktFriendID
	&& process.env.traktClientID
	&& process.env.radarrIP
	&& process.env.radarrPort
	&& process.env.radarrApiKey
	&& process.env.hbVolumeMappingHandbrake
	&& process.env.hbVolumeMappingRadarr
	&& process.env.movieHistory
	&& fs.existsSync('/config')
	&& fs.existsSync('/watch')) {
		console.log("All env variables and volume mappings are present, starting script");
		main();
	} else {
		console.log("Environment variables or volume mappings are missing, aborting. Check your docker run command")
	};

function main(){
	console.log("Starting movie processing " + new Date(new Date()+3600*1000*10).toISOString());
	getTraktMovies( (traktMovies) => {
		getRadarrMovies( (radarrMovies) => {
      compareResults(traktMovies, radarrMovies, (movieMatches) => { // TODO: add count of files to process
				createSymlinkForHandbrake(movieMatches);
				console.log("Movie processing completed " + new Date(new Date()+3600*1000*10).toISOString());
				});
      });
		});
	}

function getTraktMovies(callback){
	console.log("starting getTraktMovies");
  request({
    method: 'GET',
    url: 'https://api.trakt.tv/users/' + process.env.traktFriendID +'/watchlist/movies',
    headers: {
      'Content-Type': 'application/json',
      'trakt-api-version': '2',
      'trakt-api-key': process.env.traktClientID
    }}, function (error, response, body) {
       console.log('Status:', response.statusCode);
       //console.log('Headers:', JSON.stringify(response.headers));
       //console.log('Response:', body);
  	  callback(JSON.parse(body));
    });
}

function getRadarrMovies(callback){
	console.log("starting getRadarrMovies");
  request({
    method: 'GET',
    url: process.env.radarrIP + ':' + process.env.radarrPort + '/api/v3/movie',
    headers: {
      'Content-Type': 'application/json',
      'X-API-Key': process.env.radarrApiKey
    }}, function (error, response, body) {
       console.log('Status:', response.statusCode);
       //console.log('Headers:', JSON.stringify(response.headers));
       //console.log('Response:', body);
       callback(new Error('bad resp.'));
      callback(JSON.parse(body));
    });
}

function compareResults(traktMovies, radarrMovies, callback){
	console.log("starting compareResults");
	var movieMatches = []; // array of imdbID and file path for movies matches between trakt and radarr that has not been previously processed
	// get array of previously processed movies to avoid double-processing
	if (!fs.existsSync(process.env.movieHistory)) {
		try {
			fs.appendFileSync(process.env.movieHistory, "These movies have already been processed and will be ignored" + "\n");
		} catch (err) {
			console.log(err);
		}
	}
	if (fs.existsSync(process.env.movieHistory)) {
		try {
			console.log("movieHistory exists");
			var data = fs.readFileSync(process.env.movieHistory);
			var movieHistory = data.toString().split("\n");
			movieHistory.splice(-1,1);

			// iterate through items in traktMovies that have not been previously processed and store the imdbIDs
			for (var i = 0; i < traktMovies.length; i++) {
				if (traktMovies[i].movie.ids.imdb != null && !(movieHistory.indexOf(traktMovies[i].movie.ids.imdb) > -1)) {

					// match traktImdbIDs to items in radarrMovies where downloaded = true
					for (var j = 0; j < radarrMovies.length; j++) {
						if ( traktMovies[i].movie.ids.imdb == radarrMovies[j].imdbId && radarrMovies[j].hasFile == true) {
							var movieDetails = {};
							movieDetails["imdbId"] = traktMovies[i].movie.ids.imdb;
							movieDetails["folderPath"] = radarrMovies[j].folderName;
							movieDetails["fileName"] = radarrMovies[j].movieFile.relativePath;
							movieMatches.push(movieDetails);
						}
					}
				}
			};
			console.log("Matching movies " + JSON.stringify(movieMatches, null, 2));
			callback(movieMatches);
		} catch (err) {
			console.error(err);
		}
	}
}

function createSymlinkForHandbrake(movies){
	// create symlink in Handbrake watch folder with volume mapping substitution
	// then add imdb of movie to history log to prevent re-processing
	// Node docker needs the exact same /watch folder mapping as Handbrake is using
	var completedSymlinks = "";
  for (var i = 0; i < movies.length; i++) {
		try {
			var destFile = "/watch/" + movies[i].fileName;
	    var remappedSourceFile = movies[i].folderPath.replace(process.env.hbVolumeMappingRadarr, process.env.hbVolumeMappingHandbrake) + "/" + movies[i].fileName;
	    fs.symlinkSync(remappedSourceFile, destFile);
			console.log("symlink created: " + destFile);
			completedSymlinks += destFile + "\n";
			fs.appendFileSync(process.env.movieHistory, movies[i].imdbId + "\n"); // log processed movies to file
		} catch (err) {
			console.log(err);
		}
  };

  /* TO DO: need differnt notification method, can't really access unraid notification systsem from wihtin docker (without PHP)
	// send unraid notification with list of created symlinks
	if (completedSymlinks) {
		var unraidNotification = "/usr/local/emhttp/webGui/scripts/notify -e 'unRAID Server Notice' -s 'Handbrake Symlink creation' -d '" + completedSymlinks + "' -i 'normal'";
		exec(unraidNotification, (err, stdout, stderr) => {
			if (err) {
				console.log(err);
				return;
			}
			// the *entire* stdout and stderr (buffered)
	    // console.log(`stdout: ${stdout}`);
	    // console.log(`stderr: ${stderr}`);
		});
	}
	*/
}


text:
package Activity;

import javafx.event.EventHandler;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.scene.shape.Rectangle;

public class ATime extends Rectangle {

	public Line l0;
	public Line l1;
	public Line l2;
	public Line l3;

	public ATime(double startx, double starty, Color color) {
		super(startx, starty, 30, 40);
		setFill(Color.WHITE);
		if(color.toString().equals("0xffffffff"))
			 color=Color.BLACK;

		l0 = new Line();

		l0.setStroke(color);
		l0.startXProperty().bind(xProperty());
		l0.startYProperty().bind(yProperty());
		l0.endXProperty().bind(xProperty().add(30));
		l0.endYProperty().bind(yProperty().add(40));

		l1 = new Line();
		l1.setStroke(color);
		l1.startXProperty().bind(xProperty());
		l1.startYProperty().bind(yProperty());
		l1.endXProperty().bind(xProperty().add(30));
		l1.endYProperty().bind(yProperty());

		l2 = new Line();
		l2.setStroke(color);
		l2.startXProperty().bind(l1.endXProperty());
		l2.startYProperty().bind(l1.endYProperty());
		l2.endXProperty().bind(xProperty());
		l2.endYProperty().bind(yProperty().add(40));

		l3 = new Line();
		l3.setStroke(color);
		l3.startXProperty().bind(xProperty());
		l3.startYProperty().bind(yProperty().add(40));
		l3.endXProperty().bind(xProperty().add(30));
		l3.endYProperty().bind(yProperty().add(40));

		addEventFilter(MouseEvent.MOUSE_DRAGGED, new EventHandler<MouseEvent>() {
			@Override
			public void handle(MouseEvent e) {
				setX(e.getX());
				setY(e.getY());

			}
		});
	}
}


text:
#ifndef __MATRIX_H__
#define __MATRIX_H__

#if defined( __cplusplus )
extern "C" {
#endif

#include "Vector.h"

#define MAT2	( 2 )
#define MAT3	( 3 )
#define MAT4	( 4 )

/*
================================================================================

	Matrix structures
	Built in the style of GLSL
	They all contain padding so sizeof == sizeof( float ) * 16
	Use Matrix_ToFloatPtr for uploading onto GPU!

================================================================================
*/
typedef struct mat4_s {
	vec4_t	x;
	vec4_t	y;
	vec4_t	z;
	vec4_t	w;
} mat4_t;

typedef struct mat3_s {
	vec3_t	x;
	vec3_t	y;
	vec3_t	z;

	struct {
		vec3_t	w;
	} _padding;
} mat3_t;

typedef struct mat2_s {
	vec2_t	x;
	vec2_t	y;

	struct {
		vec2_t	z;
		vec2_t	w;
	} _padding;
} mat2_t;

void	Matrix_Clear( void * const matrix );
void	Matrix_ToFloatPtr( const void * const matrix, float * const floatPtr, const size_t length );
void	Matrix_Mul( void * const matrix, const void * const left, const void * const right, const size_t length );
void	Matrix_Inverse( void * const matrix, const void * const input, const size_t length );
float	Matrix_Determinant( const void * const matrix, const size_t length );
void	Matrix_LookAt( void * const matrix, const void * const eyePos, const void * const target, const void * const up );
void	Matrix_Perspective( void * const matrix, const float fovDegree, const float ratio, const float near, const float far );
void	Matrix_Orthographic( void * const matrix, const float left, const float right, const float bottom, const float top, const float near, const float far );
void	Matrix_RotationDegree( void * const matrix, const void * const rotationVec, const size_t length );
void	Matrix_Identity( void * const matrix );
void	Matrix_Scale(  void * const matrix, const void * const vector, const size_t length );
void	Matrix_Translation(  void * const matrix, const void * const vector, const size_t length );

#if defined( __cplusplus )
}
#endif

#endif


text:
/

//***************************************************************************************
// Defines
//***************************************************************************************
#ifndef __CSIILGIFFileDriver_H__
#define __CSIILGIFFileDriver_H__

//***************************************************************************************
// Includes
//***************************************************************************************
#include <SIBCPixMap.h>

//***************************************************************************************
// Typedefs
//***************************************************************************************

//! GIF file loader class
class XSIEXPORT CSIILGIFFileDriver : public CSIBCPixMapDriver
{
public:
	/*! Constructor
	* \return an instance of CSIILGIFFileDriver
	*/
	CSIILGIFFileDriver();

	/*! Destructor
	*/
	virtual ~CSIILGIFFileDriver();

	/*! tells whether the extension passed in the string is supported by this driver
	* \param in_Filename file name to check
	* \return SI_Bool
	* \retval TRUE if this file is supported
	* \retval FALSE if this file is not supported
	*/
	virtual SI_Bool Supported( CSIBCString &in_Filename );

	/*! Loads a bitmap file into a CSIBCPixMap object
	* \param in_filename bitmap file name
	* \param in_PixMap CSIBCPixMap object to load the file into
	* \return SI_Error
	* \retval SI_SUCCESS loading has been succesful
	* \retval SI_ERR_ERROR_MSG loading has failed
	* \retval SI_FILE_NOT_FOUND the file has not been found
	*/
	virtual SI_Error Load( CSIBCString &in_filename, CSIBCPixMap &in_PixMap );

	/*! returns the global GIF loader instance
	* \return CSIILGIFFileDriver*
	*/
	static CSIILGIFFileDriver *Driver();
protected:

private:

};

#endif // CSIILGIFFileDriver


text:
package lutron

import (
	"bufio"
	"fmt"
	"log"
	"net"
	"regexp"
	"strconv"
	"strings"

	"github.com/cskr/pubsub"
)

type MsgType int
type Command string

const (
	Get MsgType = iota
	Set
	Watch
	Response
)

const (
	Output  Command = "OUTPUT"
	Device  Command = "DEVICE"
	Group   Command = "GROUP"
	Unknown Command = "UNKNOWN"
)

type Lutron struct {
	hostName  string
	Port      string
	conn      net.Conn
	reader    *bufio.Reader
	Username  string
	Password  string
	done      chan bool
	inventory Inventory
	broker    *pubsub.PubSub
}

type LutronMsg struct {
	// the lutron component number
	Id    int
	Name  string
	Value float64
	// duration in seconds for a set action
	// TODO parse > 60 seconds into string "M:SS"
	Fade float64
	// the action to take with the command, Get, Set, Watch, Default: Get
	Type MsgType
	// the integration command type - Output, Device
	Cmd Command
	// usually the button press
	Action int
	// in Unix nanos format
	Timestamp int64
	// TODO
	// Action Number - default to 1 for now
}

type ResponseWatcher struct {
	matchMsg  *LutronMsg
	incomming chan interface{}
	Responses chan *LutronMsg
	stop      chan bool
}

// custom io scanner splitter
// splits on either '>' or '\n' as depending on whether
// the session is at a prompt - or just sent a change event
func lutronSplitter(data []byte, atEOF bool) (advance int, token []byte, err error) {
	delim := strings.IndexAny(string(data), ">\n")
	if delim == -1 {
		// keep reading
		return 0, nil, nil
	}
	// else split the token
	return delim + 1, data[:delim], nil
}

func NewLutron(hostName, inventoryPath string) *Lutron {
	inv := NewCasetaInventory(inventoryPath)

	l := &Lutron{
		hostName: hostName,
		Port:     "23",
		Username: "lutron",
		Password: "integration",
		// Responses: make(chan string, 5),
		done:      make(chan bool),
		inventory: inv,
	}
	l.broker = pubsub.New(10)
	return l
}

func (l *Lutron) Connect() error {

	conn, err := net.Dial("tcp", l.hostName+":"+l.Port)
	if err != nil {
		return err
	}
	l.conn = conn
	loginReader := bufio.NewReader(l.conn)
	l.reader = loginReader
	// TODO turn to logging
	fmt.Printf("Connection established between %s and localhost.\n", l.hostName)
	fmt.Printf("Local Address : %s \n", l.conn.LocalAddr().String())
	fmt.Printf("Remote Address : %s \n", l.conn.RemoteAddr().String())
	message, _ := loginReader.ReadString(':')
	fmt.Print("Message from server: " + message + "\n")
	// send to socket
	fmt.Fprintf(conn, l.Username+"\n")
	// listen for reply
	message, _ = loginReader.ReadString(':')
	fmt.Print("Message from server: " + message + "\n")
	fmt.Fprintf(l.conn, l.Password+"\n")
	message, _ = loginReader.ReadString('>')
	fmt.Print("prompt ready: " + message + "\n")
	// TODO set up scanner on l.conn
	scanner := bufio.NewScanner(l.conn)
	scanner.Split(lutronSplitter)
	go func() {
		re := regexp.MustCompile(
			// ^~(?P<command>[^,]+),(?P<id>\d+),(?P<action>\d+)(?:,(?P<value>\d+(?:\.\d+)?))?$
			`^~(?P<command>[^,]+),` + // the the commmand
				`(?P<id>\d+),` +
				`(?P<action>\d+)` +
				`(?:,(?P<value>\d+` + //values are optional
				`(?:\.\d+)?` + // not all values are floats
				`))?$`) // end optional value capture
		for scanner.Scan() {
			scannedMsg := strings.TrimSpace(scanner.Text())
			// fmt.Printf("scannedMsg: %v\n", scannedMsg)
			select {
			case <-l.done:
				return
			// case l.Responses <- scannedMsg:
			default:
				fmt.Println(scannedMsg)
			}
			response := &LutronMsg{}
			groups := re.FindStringSubmatch(scannedMsg)
			if len(groups) == 0 {
				// fmt.Println("no groups")
				continue
			}
			lutronItems := make(map[string]string)

			// fmt.Printf("%v\n", groups)
			for i, name := range re.SubexpNames() {
				if i > 0 && i <= len(groups) {
					lutronItems[name] = groups[i]
				}
			}
			// fmt.Println(lutronItems)
			switch lutronItems["command"] {
			case "OUTPUT":
				response.Cmd = Output
			case "DEVICE":
				response.Cmd = Device
			default:
				response.Cmd = Unknown
			}
			// response.Cmd = lutronItems["command"]
			// response.Cmd = "OUTPUT".(Command)
			response.Id, err = strconv.Atoi(lutronItems["id"])
			response.Action, err = strconv.Atoi(lutronItems["action"])
			if err != nil {
				log.Println(err.Error())
			}
			response.Type = Response
			response.Name, err = l.inventory.NameFromId(response.Id)
			response.Value, _ = strconv.ParseFloat(lutronItems["value"], 64)
			if err != nil {
				log.Println(err.Error())
			}
			// fmt.Printf("publishing %+v\n", response)
			l.broker.Pub(response, "responses")
		}
	}()
	return nil
}

func (l *Lutron) Disconnect() error {
	l.done <- true
	return l.conn.Close()
}

// TODO - how many API variations to support - need to have one
// with Fade
func (l *Lutron) SetById(id int, level float64) error {
	return l.Send(fmt.Sprintf("#OUTPUT,%d,1,%f", id, level))
}

func (l *Lutron) SetByName(name string, level float64) error {
	var id int
	var err error
	if id, err = l.inventory.IdFromName(name); err != nil {
		return err
	}
	return l.SetById(id, level)
}

func (l *Lutron) Send(msg string) error {
	fmt.Fprintf(l.conn, msg+"\n")
	// TODO return meaningful error
	return nil
}

func (l *Lutron) Watch(c *LutronMsg) (responses chan *LutronMsg, stop chan bool) {
	watcher := &ResponseWatcher{
		matchMsg: c,
	}
	watcher.incomming = make(chan interface{}, 5)
	watcher.Responses = make(chan *LutronMsg, 5)
	watcher.stop = make(chan bool)
	l.broker.AddSub(watcher.incomming, "responses")
	go func() {
		for {
			select {
			case msg := <-watcher.incomming:
				// match msg
				watcher.Responses <- msg.(*LutronMsg)
			case <-watcher.stop:
				l.broker.Unsub(watcher.incomming, "responses")
				close(watcher.Responses)
				return
			}
		}

	}()
	return watcher.Responses, watcher.stop
}

func (l *Lutron) NameFromId(i int) (string, error) {
	return l.inventory.NameFromId(i)
}

func (l *Lutron) SendCommand(c *LutronMsg) (resp string, err error) {
	var cmd string
	if c.Id == 0 {
		c.Id, err = l.inventory.IdFromName(c.Name)
		if err != nil {
			return "", err
		}
	}
	if c.Cmd == "" {
		c.Cmd = Output
	}

	switch c.Type {
	case Get:
		cmd = fmt.Sprintf("?%s,%d,1", c.Cmd, c.Id)
		// TODO confirm level and fade are 0
	case Set:
		cmd = fmt.Sprintf("#%s,%d,1,%.2f", c.Cmd, c.Id, c.Value)
	case Watch:
		// TODO
		// create mechanism to add a fmt.scanner on responses in a goroutine
		// with a dedicated channel for matches
		log.Fatal("Watch not implemented")
	}

	if c.Fade > 0.0 {
		// TODO - longer fades don't expose themselves well in the integration
		// the final value is reported for the item immediately on the sending
		// of the command. So if you set a light to dim from 100 to 10 over 20
		// seconds, the light reports out at 10 immediately. The way to perhaps
		// to approximate (as an option) is to manage the fade here, with a ticker
		cmd = fmt.Sprintf("%s,%.2f", cmd, c.Fade)
	}
	// fmt.Println("debug: ", cmd)
	// TODO need to decide how to capture and bubble up either
	// transport/connection errors, or semantic lighting errors
	l.Send(cmd)
	fmt.Println("sent ", cmd)
	return "", nil
}


text:
var module = angular.module('models.note',['ngResource']);

module.factory('Note', ['$resource', function($resource) {
  return $resource('/api/notes/:id', {}, {
    query: {
      method: 'GET',
      isArray: true,
      transformResponse: [
        angular.fromJson,
        requestTransformers.pluckData,
        requestTransformers.timestampsToDate
      ]
    },
    save: {
      method: 'POST',
      transformResponse: [
        angular.fromJson,
        requestTransformers.pluckData
      ]
    },
    delete: {
      method: 'DELETE',
      params: {id: '@id'}
    }
  });
}]);


text:
Simple Library to make the process of executing system commands through java a simple task.
The library is thread-safe, can be used to execute multiple commands asynchronously.

------
**How to**

If you want to execute a command, and redirect the output to the `console`:

    try {
    CommandExecutor.execute("ping google.com");
    }
    catch (IOException e) {
    e.printStackTrace();
    }

------
However, this library gives you more control over the commands being executed;

 - You can use the `CommandBuilder` as *wrapper* for the parts that form the command line you
   want to execute; such as arguments
   (`CommandBuilder#withArgs`) and
   options(`CommandBuilder#withOptions`).

 - You can *redirect* the `standard` and `error` outputs to any object You want, just *implement* the `Appender` interface.

 - You can *retrieve* the `exit code` of the process, or *abort* the process,
   by simply using the `ProcessMonitor` and `ExecutionReport` objects.

------
An advanced example:

    Command cmd = new CommandBuilder().forCommandLine("ping").withArgs("google.com").build();
    ExecutionOutputPrinter eop = new ExecutionOutputPrinter(new Appender() {

    @Override
    public void appendStdText(String text) {
    // your code to show std output lines.
    }

    @Override
    public void appendErrText(String text) {
    // your code to show error lines.
    }
    });

    try {
    ProcessMonitor pMonitor = CommandExecutor.execute(cmd, null, eop); //execute the command, redirect the output to eop.
    ExecutionReport report = pMonitor.getExecutionReport(); //blocks until the process finishes or gets aborted.

    String commandLine = cmd.string();
    int exitCode = report.exitValue();

    System.out.printf("command line: %s\nexecution finished with exit code: %d\n\n", commandLine, exitCode);
    }
    catch (UnrecognisedCmdException e) {
    System.err.println(e);
    }

to abort a running process (command), you can use the `ProcessMonitor` instance that you obtained previously:

    pMonitor.abort();

----------


text:
DataStore.js
============

A complete Web storage wrapper (sessionStorage/localStorage). Provides a fallback when not supported.

## How To Use?

### sessionStorage

Those storage entries are temporary and only available in the page they are in use, and MAY be kept across navigation in the same tab.

* DataStore.hasDB() - Returns whether sessionStorage is available or not
* DataStore.getDB(database, table, row) - Get a value (database->table->row)
* DataStore.setDB(database, table, row, value) - Stores a value (database->table->row:value)
* DataStore.removeDB(database, table, row) - Removes a value (database->table->row)
* DataStore.existDB(database, table, row) - Returns whether a value is set or none
* DataStore.resetDB() - Clear the whole database values

### localStorage

Those storage entries are persistent, so that database MAY be kept across browser (and system) restart. Available across all tabs, too.

* DataStore.hasPersistent() - Returns whether localStorage is available or not
* DataStore.getPersistent(database, table, row) - Get a value (database->table->row)
* DataStore.setPersistent(database, table, row, value) - Stores a value (database->table->row:value)
* DataStore.removePersistent(database, table, row) - Removes a value (database->table->row)
* DataStore.existPersistent(database, table, row) - Returns whether a value is set or none
* DataStore.resetPersistent() - Clear the whole database values


text:
"""Controllers for the collections editor."""

from core.controllers import base
from core.domain import collection_services
from core.domain import config_domain
from core.domain import rights_manager
from core.platform import models
import utils

current_user_services = models.Registry.import_current_user_services()

def _require_valid_version(version_from_payload, collection_version):
    """Check that the payload version matches the given collection version."""
    if version_from_payload is None:
        raise base.BaseHandler.InvalidInputException(
            'Invalid POST request: a version must be specified.')

    if version_from_payload != collection_version:
        raise base.BaseHandler.InvalidInputException(
            'Trying to update version %s of collection from version %s, '
            'which is too old. Please reload the page and try again.'
            % (collection_version, version_from_payload))

def require_editor(handler):
    """Decorator that checks if the user can edit the given collection."""
    def test_collection_editor(self, collection_id, **kwargs):
        """Gets the user and collection id if the user can edit it.

        Args:
            self: the handler instance
            collection_id: the collection id
            **kwargs: any other arguments passed to the handler

        Returns:
            The relevant handler, if the user is authorized to edit this
            collection.

        Raises:
            self.PageNotFoundException: if no such collection exists.
            self.UnauthorizedUserException: if the user exists but does not
                have the right credentials.
        """
        if not self.user_id:
            self.redirect(current_user_services.create_login_url(
                self.request.uri))
            return

        if (self.username in config_domain.BANNED_USERNAMES.value
                or self.username not in
                config_domain.WHITELISTED_COLLECTION_EDITOR_USERNAMES.value):
            raise self.UnauthorizedUserException(
                'You do not have the credentials to access this page.')

        try:
            collection_services.get_collection_by_id(collection_id)
        except:
            raise self.PageNotFoundException

        if not rights_manager.Actor(self.user_id).can_edit(
                rights_manager.ACTIVITY_TYPE_COLLECTION, collection_id):
            raise self.UnauthorizedUserException(
                'You do not have the credentials to edit this collection.',
                self.user_id)

        return handler(self, collection_id, **kwargs)

    return test_collection_editor

class CollectionEditorHandler(base.BaseHandler):
    """Base class for all handlers for the collection editor page."""

    # The page name to use as a key for generating CSRF tokens.
    PAGE_NAME_FOR_CSRF = 'collection_editor'

class CollectionEditorPage(CollectionEditorHandler):
    """The editor page for a single collection."""

    # TODO(bhenning): Implement read-only version of the editor. Until that
    # exists, ensure the user has proper permission to edit this collection
    # before seeing the editor.
    @require_editor
    def get(self, collection_id):
        """Handles GET requests."""

        collection = collection_services.get_collection_by_id(
            collection_id, strict=False)

        if (collection is None or
                not rights_manager.Actor(self.user_id).can_view(
                    rights_manager.ACTIVITY_TYPE_COLLECTION, collection_id)):
            self.redirect('/')
            return

        can_edit = (
            bool(self.user_id) and
            self.username not in config_domain.BANNED_USERNAMES.value and
            rights_manager.Actor(self.user_id).can_edit(
                rights_manager.ACTIVITY_TYPE_COLLECTION, collection_id))

        self.values.update({
            'is_private': rights_manager.is_collection_private(collection_id),
            'can_edit': can_edit,
            'collection_id': collection.id,
            'title': collection.title,
            'can_unpublish': rights_manager.Actor(
                self.user_id).can_unpublish(
                    rights_manager.ACTIVITY_TYPE_COLLECTION, collection_id)
        })

        self.render_template('collection_editor/collection_editor.html')

class WritableCollectionDataHandler(CollectionEditorHandler):
    """A data handler for collections which supports writing."""

    def _require_valid_version(self, version_from_payload, collection_version):
        """Check that the payload version matches the given collection version.
        """
        if version_from_payload is None:
            raise base.BaseHandler.InvalidInputException(
                'Invalid POST request: a version must be specified.')

        if version_from_payload != collection_version:
            raise base.BaseHandler.InvalidInputException(
                'Trying to update version %s of collection from version %s, '
                'which is too old. Please reload the page and try again.'
                % (collection_version, version_from_payload))

    @require_editor
    def put(self, collection_id):
        """Updates properties of the given collection."""

        collection = collection_services.get_collection_by_id(collection_id)
        version = self.payload.get('version')
        self._require_valid_version(version, collection.version)

        commit_message = self.payload.get('commit_message')
        change_list = self.payload.get('change_list')

        try:
            collection_services.update_collection(
                self.user_id, collection_id, change_list, commit_message)
        except utils.ValidationError as e:
            raise self.InvalidInputException(e)

        # Retrieve the updated collection.
        collection_dict = (
            collection_services.get_learner_collection_dict_by_id(
                collection_id, self.user_id, allow_invalid_explorations=True))

        # Send the updated collection back to the frontend.
        self.values.update(collection_dict)
        self.render_json(self.values)

class CollectionRightsHandler(CollectionEditorHandler):
    """Handles management of collection editing rights."""

    @require_editor
    def put(self, collection_id):
        """Updates the editing rights for the given collection."""
        collection = collection_services.get_collection_by_id(collection_id)
        version = self.payload.get('version')
        _require_valid_version(version, collection.version)

        # TODO(bhenning): Implement other rights changes here.
        is_public = self.payload.get('is_public')

        if is_public is not None:
            if is_public:
                try:
                    collection.validate(strict=True)
                    collection_services.validate_exps_in_collection_are_public(
                        collection)
                except utils.ValidationError as e:
                    raise self.InvalidInputException(e)

                collection_services.publish_collection_and_update_user_profiles(
                    self.user_id, collection_id)
                collection_services.index_collections_given_ids([
                    collection_id])
            elif rights_manager.Actor(self.user_id).can_unpublish(
                    rights_manager.ACTIVITY_TYPE_COLLECTION, collection_id):
                rights_manager.unpublish_collection(self.user_id, collection_id)
                collection_services.delete_documents_from_search_index([
                    collection_id])
            else:
                raise self.InvalidInputException(
                    'Cannot unpublish a collection.')

        self.render_json({
            'rights': rights_manager.get_collection_rights(
                collection_id).to_dict()
        })


text:
from fractions import Fraction

def parse_frac(infrac):
    if type(infrac) == str:
        slash_pos = infrac.find('/')
        if slash_pos != -1:
            num = infrac[:slash_pos]
            den = infrac[slash_pos + 1:]
            return Fraction(num) / Fraction(den)

    return Fraction(infrac)

def ticks2time(ticks, tickrate):
    time_frac = Fraction(ticks) / tickrate

    measures = time_frac // 4
    beats = int(time_frac) % 4
    remainder = time_frac - (4 * measures) - beats
    return '{!s:<8}{!s:<8}{!s:<8}'.format(measures, beats, remainder)

def time2ticks(time, tickrate):
    # Converts a string representation of time to ticks.

    splitted = time.split(':')
    measures, beats = splitted[:2]
    if len(splitted) >= 3:
        other = splitted[2]
        other_frac = parse_frac(other)

    out_beats = 4*measures + beats + other_frac
    out_ticks = out_beats * tickrate

    return out_ticks


text:
This inspection checks for `QName`s that contain a namespace prefix that is
not defined in the current scope. This includes predefined namespaces that
are provided by the implementation.

These constructs would raise `XPST0081` errors on the XQuery processor.


text:
"""Dock"""

# -----------------------------------------------------------------------------
# Imports
# -----------------------------------------------------------------------------
from phyui.qt.qtversion import QtCore, QtGui

# -----------------------------------------------------------------------------
# Dock widget class
# -----------------------------------------------------------------------------
class ViewDockWidget(QtGui.QDockWidget):
    closed = QtCore.pyqtSignal(object)
    def __init__(self, parent=None):
        super(ViewDockWidget, self).__init__(parent)
        self.setFocusPolicy(QtCore.Qt.WheelFocus)

    def closeEvent(self, e):
        self.closed.emit(self)
        super(ViewDockWidget, self).closeEvent(e)

    def keyPressEvent(self, e):
        super(ViewDockWidget, self).keyPressEvent(e)
        # Notify the main window of the key events when the dock widget
        # is floating.
        if self.isFloating():
            self.parent().keyPressEvent(e)

    def keyReleaseEvent(self, e):
        super(ViewDockWidget, self).keyReleaseEvent(e)
        # Notify the main window of the key events when the dock widget
        # is floating.
        if self.isFloating():
            self.parent().keyReleaseEvent(e)

# -----------------------------------------------------------------------------
# Title bar for dock widgets
# -----------------------------------------------------------------------------
DOCKSTYLESHEET = """

QToolButton {
    margin: 0px 2px;
    padding: 2px;
    border: 0;
}

QToolButton:checked {
    background-color: #606060;
}

"""

class DockTitleBar(QtGui.QWidget):
    def __init__(self, parent=None, name=''):
        super(DockTitleBar, self).__init__(parent)
        self.name = name
        self.create_buttons()
        self.create_layout()
        self.show()

    def is_floatable(self):
        return self.parent().features() & QtGui.QDockWidget.DockWidgetFloatable

    def is_closable(self):
        return self.parent().features() & QtGui.QDockWidget.DockWidgetClosable

    # Layout.
    # -------
    def add_button(self, name, text, callback=None, shortcut=None,
            checkable=False, icon=None):
        # Creation action.
        action = QtGui.QAction(text, self)
        if callback is None:
            callback = getattr(self, name + '_callback', None)
        if callback:
            action.triggered.connect(callback)
        if shortcut:
            action.setShortcut(shortcut)
        #if icon:
        #    action.setIcon(get_icon(icon))
        action.setCheckable(checkable)
        # Create button
        button = QtGui.QToolButton(self)
        button.setContentsMargins(*((5,)*4))
        button.setDefaultAction(action)
        return button

    def create_buttons(self):
        if self.is_floatable():
            self.dockable_button = self.add_button('dockable',
                'Pin/Unpin', icon='pin', checkable=True)
            self.dock_button = self.add_button('dock',
                'Dock/Undock', icon='dockable')
            self.maximize_button = self.add_button('maximize',
                'Maximize', icon='fullscreen')
        if self.is_closable():
            self.close_button = self.add_button('close',
                'Close', icon='close')

    def create_layout(self):

        self.setStyleSheet(DOCKSTYLESHEET)

        # Create the title layout.
        self.setContentsMargins(0, 0, 0, 0)
        box = QtGui.QHBoxLayout()
        box.setContentsMargins(0, 2, 0, 2)
        box.setSpacing(0)

        # Add the title.
        self.title_widget = QtGui.QLabel(self.name, self)
        box.addSpacing(5)
        box.addWidget(self.title_widget)

        # Add spacing.
        box.addStretch(1000)

        # Add the dock-related buttons.
        if self.is_floatable():
            box.addWidget(self.dockable_button)
            box.addWidget(self.maximize_button)
            box.addWidget(self.dock_button)

        # Add the close button.
        if self.is_closable():
            box.addWidget(self.close_button)

        self.setLayout(box)

    # Callbacks.
    # ----------
    def dockable_callback(self, checked=None):
        if checked is False:
            self.parent().setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
        else:
            self.parent().setAllowedAreas(QtCore.Qt.NoDockWidgetArea)

    def dock_callback(self, checked=None):
        self.parent().setFloating(not(self.parent().isFloating()))

    def maximize_callback(self, checked=None):
        # Force floating.
        if not self.parent().isFloating():
            self.parent().setFloating(True)
            self.forced_float = True
        # and cancel floating for minimize if it was triggered by maximize
        # button.
        elif self.forced_float:
            self.forced_float = False
            self.parent().showNormal()
            self.parent().setFloating(False)
        if self.parent().isMaximized():
            self.parent().showNormal()
        else:
            self.parent().showMaximized()

    def close_callback(self, checked=None):
        self.parent().close()

    # Size.
    # -----
    # def sizeHint(self):
        # return QtCore.QSize(200, 24)

    def minimumSizeHint(self):
        return QtCore.QSize(50, 24)


text:
module Main where

import Control.Monad
import Language.Haskell.HLint
import System.Environment
import System.Exit

main :: IO ()
main = do
    args <- getArgs
    hints <- hlint $ ["src", "--cross"] ++ args
    unless (null hints) exitFailure


text:
'use strict';

module.exports = function(Handlebars) {
  var helpersConfig = require('./../../../shared/handlebars_helpers/helpers_config')(Handlebars);
  for (var helper in helpersConfig) {
    if (helpersConfig.hasOwnProperty(helper)) {
      Handlebars.registerHelper(helper, helpersConfig[helper]);
    }
  }
  Handlebars.registerHelper('data-context', function() {
    return new Handlebars.SafeString(' data-context=\'' + 'Rendered from client' + '\'');
  });

};


text:
//
//  AST.hpp
//  Letter
//
//  Created by Harlan Haskins on 12/24/15.
//  Copyright © 2015 Harlan Haskins. All rights reserved.
//

#ifndef AST_hpp
#define AST_hpp

#include <stdio.h>

#include <stdlib.h>
#include <vector>
#include <iostream>
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"

class IRGenerator;

using namespace llvm;

typedef struct SourceLoc {
    int column;
    int line;
} SourceLoc;

class SourceItem {
public:
    SourceLoc sourceLoc;
    int getLine() { return this->sourceLoc.line; }
    int getColumn() { return this->sourceLoc.column; }
    std::string dumpLoc() { return "[line " + std::to_string(getLine()) + ", column " + std::to_string(getColumn()) + "]"; }
    virtual std::string dump(std::string indent = "") = 0;
    virtual Value *codegen(IRGenerator &gen) = 0;
};

class NumExp: public SourceItem {
public:
    long value;
    NumExp(long value, SourceLoc loc): value(value) { this->sourceLoc = loc; }
    virtual std::string dump(std::string indent = "");
    virtual Value *codegen(IRGenerator &gen);
};

class VarExp: public SourceItem {
public:
    std::string name;
    VarExp(std::string name, SourceLoc loc): name(name) { this->sourceLoc = loc; }
    virtual std::string dump(std::string indent = "");
    virtual Value *codegen(IRGenerator &gen);
};

class FunCallExp: public SourceItem {
public:
    std::string func;
    std::vector<std::shared_ptr<SourceItem>> args;
    static std::shared_ptr<FunCallExp> create(std::string name, std::vector<std::shared_ptr<SourceItem>> args);
    FunCallExp(std::string func, std::vector<std::shared_ptr<SourceItem>> args, SourceLoc loc): func(func), args(args) { this->sourceLoc = loc; }
    virtual std::string dump(std::string indent = "");
    virtual Value *codegen(IRGenerator &gen);
};

#endif /* AST_hpp */


text:
v<!DOCTYPE html>

      <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="description" content="Notes on Data Science, Machine Learning, & Artificial Intelligence">
    <meta name="author" content="Chris Albon">
    <link rel="icon" href="../favicon.ico">

    <title>Automatically Add Keys To Rows - SQL</title>

    <link rel="stylesheet" href="../theme/css/bootstrap.css" />

    <link rel="stylesheet" type="text/css" href="../theme/css/ie10-viewport-bug-workaround.css" />

    <link rel="stylesheet" type="text/css" href="../theme/css/style.css" />
    <link rel="stylesheet" type="text/css" href="../theme/css/notebooks.css" />
    <link href='https://fonts.googleapis.com/css?family=PT+Serif:400,700|Roboto:400,500,700' rel='stylesheet' type='text/css'>

     <link href="http://runningthenumbers.co.uk/feeds/all.rss.xml" type="application/rss+xml" rel="alternate" title="Running the Numbers | Data Science Notes and Resources Full RSS Feed" />         <link href="http://runningthenumbers.co.uk/feeds/sql.rss.xml" type="application/rss+xml" rel="alternate" title="Running the Numbers | Data Science Notes and Resources Categories RSS Feed" />

    <meta name="tags" content="Basics" />

    <meta name="google-site-verification" content="7RLmddm4HbzdQLpwH2LH94_vBNmcaMGZSEhmmF5n0NM" />

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

                </button>
                Running The Numbers

                      ML/AI Notes

Blog

Machine Learning

Deep Learning

Algorithms

Python

Statistics

Cloud Computing

Javascript

SQL

Scala

Regex

Mathematics

                        About

About Chris

GitHub

Twitter

LinkedIn

Pinboard

                <form class="navbar-form" action="../search.html" onsubmit="return validateForm(this.elements['q'].value);">

                            <input class="form-control search-query" name="q" id="tipue_search_input" placeholder="e.g. scikit KNN, pandas merge" required autocomplete="off" type="text">

                </form>

    Want to learn machine learning? Use my machine learning flashcards.

      Automatically Add Keys To Rows

        <time class="published" datetime="2016-05-01T12:00:00+01:00">
            01 May 2016
        </time>

SQL

Basics

Note: This tutorial was written using Catherine Devlin's SQL in Jupyter Notebooks library. If you have not using a Jupyter Notebook, you can ignore the two lines of code below and any line containing %%sql. Furthermore, this tutorial uses SQLite's flavor of SQL, your version might have some differences in syntax.

For more, check out Learning SQL by Alan Beaulieu.

# Ignore
%load_ext sql
%sql sqlite://
%config SqlMagic.feedback = False

Create Data With 'pid' As An Auto-Generated Primary Key

%%sql

-- Create a table of criminals with pid being a primary key integer that is auto-incremented
CREATE TABLE criminals (pid INTEGER PRIMARY KEY AUTOINCREMENT,
                        name,
                        age,
                        sex,
                        city,
                        minor);

-- Add a single row with a null value for pid
INSERT INTO criminals VALUES (NULL, 'James Smith', 15, 'M', 'Santa Rosa', 1);

[]

View Table

%%sql

-- Select everything
SELECT *

-- From the table 'criminals'
FROM criminals

        pid
        name
        age
        sex
        city
        minor

        1
        James Smith
        15
        M
        Santa Rosa
        1

Added More Rows With NULL Values For pid

%%sql

INSERT INTO criminals VALUES (NULL, 'Bill James', 22, 'M', 'Santa Rosa', 0);
INSERT INTO criminals VALUES (NULL, 'Stacy Miller', 23, 'F', 'Santa Rosa', 0);
INSERT INTO criminals VALUES (NULL, 'Betty Bob', NULL, 'F', 'Petaluma', 1);
INSERT INTO criminals VALUES (NULL, 'Jaden Ado', 49, 'M', NULL, 0);
INSERT INTO criminals VALUES (NULL, 'Gordon Ado', 32, 'F', 'Santa Rosa', 0);
INSERT INTO criminals VALUES (NULL, 'Bill Byson', 21, 'M', 'Santa Rosa', 0);
INSERT INTO criminals VALUES (NULL, 'Bob Iton', NULL, 'M', 'San Francisco', 0);

[]

View Table

%%sql

-- Select everything
SELECT *

-- From the table 'criminals'
FROM criminals

        pid
        name
        age
        sex
        city
        minor

        1
        James Smith
        15
        M
        Santa Rosa
        1

        2
        Bill James
        22
        M
        Santa Rosa
        0

        3
        Stacy Miller
        23
        F
        Santa Rosa
        0

        4
        Betty Bob
        None
        F
        Petaluma
        1

        5
        Jaden Ado
        49
        M
        None
        0

        6
        Gordon Ado
        32
        F
        Santa Rosa
        0

        7
        Bill Byson
        21
        M
        Santa Rosa
        0

        8
        Bob Iton
        None
        M
        San Francisco
        0

Find an error or bug?

Everything on this site is available on GitHub. Head to and submit a suggested change. You can also message me directly on Twitter.

                This project contains 486 pages and is available on GitHub.

                Copyright © Chris Albon,
                    <time datetime="2017">2017</time>.


text:
//
//  NavResourceView.m
//  Bitmarket
//
//  Created by Steve Dekorte on 2/5/14.
//  Copyright (c) 2014 voluntary.net. All rights reserved.
//

#import "NavResourceView.h"
#import <NavKit/NavKit.h>

@implementation NavResourceView

- (id)initWithFrame:(NSRect)frameRect
{
    self = [super initWithFrame:frameRect];
    [self setThemePath:@"message/body"];
    [self setAutoresizesSubviews:YES];
    [self setAutoresizingMask:NSViewHeightSizable | NSViewWidthSizable];
    [self setupBody];
    return self;
}

- (void)dealloc
{
    //NSLog(@"dealloc BMMessageView %p", (__bridge void *)self);
}

/*
- (NSString *)fontName
{
    return [NavTheme.sharedNavTheme lightFontName];
}
*/

- (NSDictionary *)bodyAttributes
{
    NSDictionary *themeDict = [NavTheme.sharedNavTheme attributesDictForPath:@"message/body"];
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:themeDict];
    //[dict setObject:self.dynamicBackgroundColor forKey:NSBackgroundColorAttributeName];
    return dict;
}

/*
- (NSDictionary *)linkAttributes
{
    return [NavTheme.sharedNavTheme attributesDictForPath:@"message/link"];
}

- (NSMutableAttributedString *)linkForAddress:(NSString *)address
{
    NSMutableDictionary *att = [NSMutableDictionary dictionaryWithDictionary:[self infoAttributes]];

    if ([address hasPrefix:@"BM-"])
    {
        att = [NSMutableDictionary dictionaryWithDictionary:[self linkAttributes]];
        [att setObject:[NSString stringWithFormat:@"BitmessageAddContact://%@", address] forKey:NSLinkAttributeName];
    }

    NSMutableAttributedString *string = [[NSMutableAttributedString alloc]
                                                initWithString:address
                                                attributes:att];

    return string;
}
*/

- (NSString *)nodeContentString
{
    if ([self.node respondsToSelector:@selector(nodeContentString)])
    {
        NSString *s = [(id)self.node nodeContentString];

        if (s)
        {
            return s;
        }
    }

    return @"";
}

- (NSAttributedString *)attributedBodyString
{
    NSMutableParagraphStyle *indented = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];

    [indented setAlignment:NSLeftTextAlignment];
    [indented setLineSpacing:1.0];
    [indented setParagraphSpacing:1.0];
    [indented setHeadIndent:0.0];
    [indented setTailIndent:0.0];
    //[indented setFirstLineHeadIndent:45.0];
    [indented setLineBreakMode:NSLineBreakByWordWrapping];

    NSMutableAttributedString *fullMessage = [[NSMutableAttributedString alloc] initWithString:@""];
    //NSString *rawString = [NSString stringWithFormat:@"%@\n\n", self.nodeContentString];
    NSMutableAttributedString *infoString = [[NSMutableAttributedString alloc]
                                                initWithString:self.nodeContentString
                                                attributes:self.bodyAttributes];

    [fullMessage appendAttributedString:infoString];

    return fullMessage;
}

- (void)setNode:(NavNode *)node
{
    if (_node != node)
    {
        _node = node;

        //[self.textView setString:message.messageString];
        //[self.textView setFont:nil];

        [self.textView setRichText:YES];
        [self.textView setEditable:NO];
        [self.textView setString:@""];
        [self.textView.textStorage setAttributedString:[self attributedBodyString]];
        [self.textView setWidth:self.frame.size.width];

        [[self.scrollView contentView] scrollToPoint:NSMakePoint (0, 0)];
        [self.scrollView reflectScrolledClipView: [self.scrollView contentView]];
    }

    [self configBody];
}

- (void)setNavView:(id)navView
{
    _navView = navView;
}

- (void)setupBody
{
    NSRect f = self.frame;

    self.scrollView = [[NavResizingScrollView alloc] initWithFrame:f];
    [self addSubview:self.scrollView];
    [self.scrollView setHasVerticalScroller:YES];
    [self.scrollView setHasHorizontalRuler:NO];
    [self.scrollView setHorizontalScrollElasticity:NSScrollElasticityNone];
    [self.scrollView setAutoresizesSubviews:YES];
    [self.scrollView setAutoresizingMask:NSViewHeightSizable | NSViewWidthSizable];

    self.textView = [[NavMarginTextView alloc] initWithFrame:self.scrollView.bounds];
    [self.scrollView setDocumentView:self.textView];
    //[self.textView setDelegate:self];

    [self configBody];
}

- (void)configBody
{
    [self.textView setThemePath:@"message/background"];
    //[self.textView setLinkTextAttributes:[self linkAttributes]];
}

- (void)drawRect:(NSRect)dirtyRect
{
    [super drawRect:dirtyRect];
    [self.textView.backgroundColor set];
    NSRectFill(dirtyRect);
}

- (NSString *)selectedContent
{
    return [[self.textView string]
            substringWithRange:[self.textView selectedRange]];
}

- (void)prepareToDisplay
{

}

@end


text:
package com.gitblit.servlet;

import java.io.IOException;
import java.text.MessageFormat;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gitblit.manager.IRepositoryManager;
import com.gitblit.manager.IRuntimeManager;
import com.gitblit.models.RepositoryModel;
import com.gitblit.models.UserModel;
import com.gitblit.utils.StringUtils;

import dagger.ObjectGraph;

/**
 * The AccessRestrictionFilter is an AuthenticationFilter that confirms that the
 * requested repository can be accessed by the anonymous or named user.
 *
 * The filter extracts the name of the repository from the url and determines if
 * the requested action for the repository requires a Basic authentication
 * prompt. If authentication is required and no credentials are stored in the
 * "Authorization" header, then a basic authentication challenge is issued.
 *
 * http://en.wikipedia.org/wiki/Basic_access_authentication
 *
 * @author James Moger
 *
 */
public abstract class AccessRestrictionFilter extends AuthenticationFilter {

	protected IRuntimeManager runtimeManager;

	protected IRepositoryManager repositoryManager;

	@Override
	protected void inject(ObjectGraph dagger, FilterConfig filterConfig) {
		super.inject(dagger, filterConfig);
		this.runtimeManager = dagger.get(IRuntimeManager.class);
		this.repositoryManager = dagger.get(IRepositoryManager.class);
	}

	/**
	 * Extract the repository name from the url.
	 *
	 * @param url
	 * @return repository name
	 */
	protected abstract String extractRepositoryName(String url);

	/**
	 * Analyze the url and returns the action of the request.
	 *
	 * @param url
	 * @return action of the request
	 */
	protected abstract String getUrlRequestAction(String url);

	/**
	 * Determine if a non-existing repository can be created using this filter.
	 *
	 * @return true if the filter allows repository creation
	 */
	protected abstract boolean isCreationAllowed();

	/**
	 * Determine if the action may be executed on the repository.
	 *
	 * @param repository
	 * @param action
	 * @return true if the action may be performed
	 */
	protected abstract boolean isActionAllowed(RepositoryModel repository, String action);

	/**
	 * Determine if the repository requires authentication.
	 *
	 * @param repository
	 * @param action
	 * @return true if authentication required
	 */
	protected abstract boolean requiresAuthentication(RepositoryModel repository, String action);

	/**
	 * Determine if the user can access the repository and perform the specified
	 * action.
	 *
	 * @param repository
	 * @param user
	 * @param action
	 * @return true if user may execute the action on the repository
	 */
	protected abstract boolean canAccess(RepositoryModel repository, UserModel user, String action);

	/**
	 * Allows a filter to create a repository, if one does not exist.
	 *
	 * @param user
	 * @param repository
	 * @param action
	 * @return the repository model, if it is created, null otherwise
	 */
	protected RepositoryModel createRepository(UserModel user, String repository, String action) {
		return null;
	}

	/**
	 * doFilter does the actual work of preprocessing the request to ensure that
	 * the user may proceed.
	 *
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
	 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	@Override
	public void doFilter(final ServletRequest request, final ServletResponse response,
			final FilterChain chain) throws IOException, ServletException {

		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;

		String fullUrl = getFullUrl(httpRequest);
		String repository = extractRepositoryName(fullUrl);
		if (StringUtils.isEmpty(repository)) {
			httpResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			return;
		}

		if (repositoryManager.isCollectingGarbage(repository)) {
			logger.info(MessageFormat.format("ARF: Rejecting request for {0}, busy collecting garbage!", repository));
			httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
			return;
		}

		// Determine if the request URL is restricted
		String fullSuffix = fullUrl.substring(repository.length());
		String urlRequestType = getUrlRequestAction(fullSuffix);

		UserModel user = getUser(httpRequest);

		// Load the repository model
		RepositoryModel model = repositoryManager.getRepositoryModel(repository);
		if (model == null) {
			if (isCreationAllowed()) {
				if (user == null) {
					// challenge client to provide credentials for creation. send 401.
					if (runtimeManager.isDebugMode()) {
						logger.info(MessageFormat.format("ARF: CREATE CHALLENGE {0}", fullUrl));
					}
					httpResponse.setHeader("WWW-Authenticate", CHALLENGE);
					httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
					return;
				} else {
					// see if we can create a repository for this request
					model = createRepository(user, repository, urlRequestType);
				}
			}

			if (model == null) {
				// repository not found. send 404.
				logger.info(MessageFormat.format("ARF: {0} ({1})", fullUrl,
						HttpServletResponse.SC_NOT_FOUND));
				httpResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
				return;
			}
		}

		// Confirm that the action may be executed on the repository
		if (!isActionAllowed(model, urlRequestType)) {
			logger.info(MessageFormat.format("ARF: action {0} on {1} forbidden ({2})",
					urlRequestType, model, HttpServletResponse.SC_FORBIDDEN));
			httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
			return;
		}

		// Wrap the HttpServletRequest with the AccessRestrictionRequest which
		// overrides the servlet container user principal methods.
		// JGit requires either:
		//
		// 1. servlet container authenticated user
		// 2. http.receivepack = true in each repository's config
		//
		// Gitblit must conditionally authenticate users per-repository so just
		// enabling http.receivepack is insufficient.
		AuthenticatedRequest authenticatedRequest = new AuthenticatedRequest(httpRequest);
		if (user != null) {
			authenticatedRequest.setUser(user);
		}

		// BASIC authentication challenge and response processing
		if (!StringUtils.isEmpty(urlRequestType) && requiresAuthentication(model, urlRequestType)) {
			if (user == null) {
				// challenge client to provide credentials. send 401.
				if (runtimeManager.isDebugMode()) {
					logger.info(MessageFormat.format("ARF: CHALLENGE {0}", fullUrl));
				}
				httpResponse.setHeader("WWW-Authenticate", CHALLENGE);
				httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
				return;
			} else {
				// check user access for request
				if (user.canAdmin() || canAccess(model, user, urlRequestType)) {
					// authenticated request permitted.
					// pass processing to the restricted servlet.
					newSession(authenticatedRequest, httpResponse);
					logger.info(MessageFormat.format("ARF: {0} ({1}) authenticated", fullUrl,
							HttpServletResponse.SC_CONTINUE));
					chain.doFilter(authenticatedRequest, httpResponse);
					return;
				}
				// valid user, but not for requested access. send 403.
				if (runtimeManager.isDebugMode()) {
					logger.info(MessageFormat.format("ARF: {0} forbidden to access {1}",
							user.username, fullUrl));
				}
				httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
				return;
			}
		}

		if (runtimeManager.isDebugMode()) {
			logger.info(MessageFormat.format("ARF: {0} ({1}) unauthenticated", fullUrl,
					HttpServletResponse.SC_CONTINUE));
		}
		// unauthenticated request permitted.
		// pass processing to the restricted servlet.
		chain.doFilter(authenticatedRequest, httpResponse);
	}
}


text:
import * as ComponentHelpers from '../../../ui/components/helpers/helpers.js';
import * as LitHtml from '../../../ui/lit-html/lit-html.js';
import elementsPanelLinkStyles from './elementsPanelLink.css.js';

export interface ElementsPanelLinkData {
  onElementRevealIconClick: (event?: Event) => void;
  onElementRevealIconMouseEnter: (event?: Event) => void;
  onElementRevealIconMouseLeave: (event?: Event) => void;
}
export class ElementsPanelLink extends HTMLElement {
  static readonly litTagName = LitHtml.literal`devtools-elements-panel-link`;
  readonly #shadow = this.attachShadow({mode: 'open'});

  #onElementRevealIconClick: ((event?: Event) => void) = () => {};
  #onElementRevealIconMouseEnter: ((event?: Event) => void) = () => {};
  #onElementRevealIconMouseLeave: ((event?: Event) => void) = () => {};

  set data(data: ElementsPanelLinkData) {
    this.#onElementRevealIconClick = data.onElementRevealIconClick;
    this.#onElementRevealIconMouseEnter = data.onElementRevealIconMouseEnter;
    this.#onElementRevealIconMouseLeave = data.onElementRevealIconMouseLeave;
    this.#update();
  }

  #update(): void {
    this.#render();
  }

  connectedCallback(): void {
    this.#shadow.adoptedStyleSheets = [elementsPanelLinkStyles];
  }

  #render(): void {
    // clang-format off
      LitHtml.render(LitHtml.html`
      <span
        class="element-reveal-icon"
        @click=${this.#onElementRevealIconClick}
        @mouseenter=${this.#onElementRevealIconMouseEnter}
        @mouseleave=${this.#onElementRevealIconMouseLeave}></span>
      `, this.#shadow, {host: this});
    // clang-format on
  }
}

ComponentHelpers.CustomElements.defineComponent('devtools-elements-panel-link', ElementsPanelLink);

declare global {
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  interface HTMLElementTagNameMap {
    'devtools-elements-panel-link': ElementsPanelLink;
  }
}


text:
describe 'author/show.rss.builder', type: :view do
  let!(:blog) { create(:blog) }

  describe 'rendering articles (with some funny characters)' do
    before(:each) do
      article1 = stub_full_article(1.minute.ago)
      article1.body = 'écoute!'
      article2 = stub_full_article(2.minutes.ago)
      article2.body = 'is 4 < 2? no!'
      assign(:articles, [article1, article2])
      render
    end

    it 'creates an RSS feed with two items' do
      assert_rss20 rendered, 2
    end

    it 'renders the article RSS partial twice' do
      expect(view).to render_template(partial: 'shared/_rss_item_article', count: 2)
    end
  end
end