text:
package vmcompute

import (
	gcontext "context"
	"syscall"
	"time"

	"github.com/Microsoft/hcsshim/internal/interop"
	"github.com/Microsoft/hcsshim/internal/log"
	"github.com/Microsoft/hcsshim/internal/logfields"
	"github.com/Microsoft/hcsshim/internal/oc"
	"github.com/Microsoft/hcsshim/internal/timeout"
	"go.opencensus.io/trace"
)

//go:generate go run ../../mksyscall_windows.go -output zsyscall_windows.go vmcompute.go

//sys hcsEnumerateComputeSystems(query string, computeSystems **uint16, result **uint16) (hr error) = vmcompute.HcsEnumerateComputeSystems?
//sys hcsCreateComputeSystem(id string, configuration string, identity syscall.Handle, computeSystem *HcsSystem, result **uint16) (hr error) = vmcompute.HcsCreateComputeSystem?
//sys hcsOpenComputeSystem(id string, computeSystem *HcsSystem, result **uint16) (hr error) = vmcompute.HcsOpenComputeSystem?
//sys hcsCloseComputeSystem(computeSystem HcsSystem) (hr error) = vmcompute.HcsCloseComputeSystem?
//sys hcsStartComputeSystem(computeSystem HcsSystem, options string, result **uint16) (hr error) = vmcompute.HcsStartComputeSystem?
//sys hcsShutdownComputeSystem(computeSystem HcsSystem, options string, result **uint16) (hr error) = vmcompute.HcsShutdownComputeSystem?
//sys hcsTerminateComputeSystem(computeSystem HcsSystem, options string, result **uint16) (hr error) = vmcompute.HcsTerminateComputeSystem?
//sys hcsPauseComputeSystem(computeSystem HcsSystem, options string, result **uint16) (hr error) = vmcompute.HcsPauseComputeSystem?
//sys hcsResumeComputeSystem(computeSystem HcsSystem, options string, result **uint16) (hr error) = vmcompute.HcsResumeComputeSystem?
//sys hcsGetComputeSystemProperties(computeSystem HcsSystem, propertyQuery string, properties **uint16, result **uint16) (hr error) = vmcompute.HcsGetComputeSystemProperties?
//sys hcsModifyComputeSystem(computeSystem HcsSystem, configuration string, result **uint16) (hr error) = vmcompute.HcsModifyComputeSystem?
//sys hcsModifyServiceSettings(settings string, result **uint16) (hr error) = vmcompute.HcsModifyServiceSettings?
//sys hcsRegisterComputeSystemCallback(computeSystem HcsSystem, callback uintptr, context uintptr, callbackHandle *HcsCallback) (hr error) = vmcompute.HcsRegisterComputeSystemCallback?
//sys hcsUnregisterComputeSystemCallback(callbackHandle HcsCallback) (hr error) = vmcompute.HcsUnregisterComputeSystemCallback?
//sys hcsSaveComputeSystem(computeSystem HcsSystem, options string, result **uint16) (hr error) = vmcompute.HcsSaveComputeSystem?

//sys hcsCreateProcess(computeSystem HcsSystem, processParameters string, processInformation *HcsProcessInformation, process *HcsProcess, result **uint16) (hr error) = vmcompute.HcsCreateProcess?
//sys hcsOpenProcess(computeSystem HcsSystem, pid uint32, process *HcsProcess, result **uint16) (hr error) = vmcompute.HcsOpenProcess?
//sys hcsCloseProcess(process HcsProcess) (hr error) = vmcompute.HcsCloseProcess?
//sys hcsTerminateProcess(process HcsProcess, result **uint16) (hr error) = vmcompute.HcsTerminateProcess?
//sys hcsSignalProcess(process HcsProcess, options string, result **uint16) (hr error) = vmcompute.HcsSignalProcess?
//sys hcsGetProcessInfo(process HcsProcess, processInformation *HcsProcessInformation, result **uint16) (hr error) = vmcompute.HcsGetProcessInfo?
//sys hcsGetProcessProperties(process HcsProcess, processProperties **uint16, result **uint16) (hr error) = vmcompute.HcsGetProcessProperties?
//sys hcsModifyProcess(process HcsProcess, settings string, result **uint16) (hr error) = vmcompute.HcsModifyProcess?
//sys hcsGetServiceProperties(propertyQuery string, properties **uint16, result **uint16) (hr error) = vmcompute.HcsGetServiceProperties?
//sys hcsRegisterProcessCallback(process HcsProcess, callback uintptr, context uintptr, callbackHandle *HcsCallback) (hr error) = vmcompute.HcsRegisterProcessCallback?
//sys hcsUnregisterProcessCallback(callbackHandle HcsCallback) (hr error) = vmcompute.HcsUnregisterProcessCallback?

// errVmcomputeOperationPending is an error encountered when the operation is being completed asynchronously
const errVmcomputeOperationPending = syscall.Errno(0xC0370103)

// HcsSystem is the handle associated with a created compute system.
type HcsSystem syscall.Handle

// HcsProcess is the handle associated with a created process in a compute
// system.
type HcsProcess syscall.Handle

// HcsCallback is the handle associated with the function to call when events
// occur.
type HcsCallback syscall.Handle

// HcsProcessInformation is the structure used when creating or getting process
// info.
type HcsProcessInformation struct {
	// ProcessId is the pid of the created process.
	ProcessId uint32
	reserved  uint32 //nolint:structcheck
	// StdInput is the handle associated with the stdin of the process.
	StdInput syscall.Handle
	// StdOutput is the handle associated with the stdout of the process.
	StdOutput syscall.Handle
	// StdError is the handle associated with the stderr of the process.
	StdError syscall.Handle
}

func execute(ctx gcontext.Context, timeout time.Duration, f func() error) error {
	if timeout > 0 {
		var cancel gcontext.CancelFunc
		ctx, cancel = gcontext.WithTimeout(ctx, timeout)
		defer cancel()
	}

	done := make(chan error, 1)
	go func() {
		done <- f()
	}()
	select {
	case <-ctx.Done():
		if ctx.Err() == gcontext.DeadlineExceeded {
			log.G(ctx).WithField(logfields.Timeout, timeout).
				Warning("Syscall did not complete within operation timeout. This may indicate a platform issue. If it appears to be making no forward progress, obtain the stacks and see if there is a syscall stuck in the platform API for a significant length of time.")
		}
		return ctx.Err()
	case err := <-done:
		return err
	}
}

func HcsEnumerateComputeSystems(ctx gcontext.Context, query string) (computeSystems, result string, hr error) {
	ctx, span := trace.StartSpan(ctx, "HcsEnumerateComputeSystems")
	defer span.End()
	defer func() {
		if result != "" {
			span.AddAttributes(trace.StringAttribute("result", result))
		}
		oc.SetSpanStatus(span, hr)
	}()
	span.AddAttributes(trace.StringAttribute("query", query))

	return computeSystems, result, execute(ctx, timeout.SyscallWatcher, func() error {
		var (
			computeSystemsp *uint16
			resultp         *uint16
		)
		err := hcsEnumerateComputeSystems(query, &computeSystemsp, &resultp)
		if computeSystemsp != nil {
			computeSystems = interop.ConvertAndFreeCoTaskMemString(computeSystemsp)
		}
		if resultp != nil {
			result = interop.ConvertAndFreeCoTaskMemString(resultp)
		}
		return err
	})
}

func HcsCreateComputeSystem(ctx gcontext.Context, id string, configuration string, identity syscall.Handle) (computeSystem HcsSystem, result string, hr error) {
	ctx, span := trace.StartSpan(ctx, "HcsCreateComputeSystem")
	defer span.End()
	defer func() {
		if result != "" {
			span.AddAttributes(trace.StringAttribute("result", result))
		}
		if hr != errVmcomputeOperationPending {
			oc.SetSpanStatus(span, hr)
		}
	}()
	span.AddAttributes(
		trace.StringAttribute("id", id),
		trace.StringAttribute("configuration", configuration))

	return computeSystem, result, execute(ctx, timeout.SystemCreate, func() error {
		var resultp *uint16
		err := hcsCreateComputeSystem(id, configuration, identity, &computeSystem, &resultp)
		if resultp != nil {
			result = interop.ConvertAndFreeCoTaskMemString(resultp)
		}
		return err
	})
}

func HcsOpenComputeSystem(ctx gcontext.Context, id string) (computeSystem HcsSystem, result string, hr error) {
	ctx, span := trace.StartSpan(ctx, "HcsOpenComputeSystem")
	defer span.End()
	defer func() {
		if result != "" {
			span.AddAttributes(trace.StringAttribute("result", result))
		}
		oc.SetSpanStatus(span, hr)
	}()

	return computeSystem, result, execute(ctx, timeout.SyscallWatcher, func() error {
		var resultp *uint16
		err := hcsOpenComputeSystem(id, &computeSystem, &resultp)
		if resultp != nil {
			result = interop.ConvertAndFreeCoTaskMemString(resultp)
		}
		return err
	})
}

func HcsCloseComputeSystem(ctx gcontext.Context, computeSystem HcsSystem) (hr error) {
	ctx, span := trace.StartSpan(ctx, "HcsCloseComputeSystem")
	defer span.End()
	defer func() { oc.SetSpanStatus(span, hr) }()

	return execute(ctx, timeout.SyscallWatcher, func() error {
		return hcsCloseComputeSystem(computeSystem)
	})
}

func HcsStartComputeSystem(ctx gcontext.Context, computeSystem HcsSystem, options string) (result string, hr error) {
	ctx, span := trace.StartSpan(ctx, "HcsStartComputeSystem")
	defer span.End()
	defer func() {
		if result != "" {
			span.AddAttributes(trace.StringAttribute("result", result))
		}
		if hr != errVmcomputeOperationPending {
			oc.SetSpanStatus(span, hr)
		}
	}()
	span.AddAttributes(trace.StringAttribute("options", options))

	return result, execute(ctx, timeout.SystemStart, func() error {
		var resultp *uint16
		err := hcsStartComputeSystem(computeSystem, options, &resultp)
		if resultp != nil {
			result = interop.ConvertAndFreeCoTaskMemString(resultp)
		}
		return err
	})
}

func HcsShutdownComputeSystem(ctx gcontext.Context, computeSystem HcsSystem, options string) (result string, hr error) {
	ctx, span := trace.StartSpan(ctx, "HcsShutdownComputeSystem")
	defer span.End()
	defer func() {
		if result != "" {
			span.AddAttributes(trace.StringAttribute("result", result))
		}
		if hr != errVmcomputeOperationPending {
			oc.SetSpanStatus(span, hr)
		}
	}()
	span.AddAttributes(trace.StringAttribute("options", options))

	return result, execute(ctx, timeout.SyscallWatcher, func() error {
		var resultp *uint16
		err := hcsShutdownComputeSystem(computeSystem, options, &resultp)
		if resultp != nil {
			result = interop.ConvertAndFreeCoTaskMemString(resultp)
		}
		return err
	})
}

func HcsTerminateComputeSystem(ctx gcontext.Context, computeSystem HcsSystem, options string) (result string, hr error) {
	ctx, span := trace.StartSpan(ctx, "HcsTerminateComputeSystem")
	defer span.End()
	defer func() {
		if result != "" {
			span.AddAttributes(trace.StringAttribute("result", result))
		}
		if hr != errVmcomputeOperationPending {
			oc.SetSpanStatus(span, hr)
		}
	}()
	span.AddAttributes(trace.StringAttribute("options", options))

	return result, execute(ctx, timeout.SyscallWatcher, func() error {
		var resultp *uint16
		err := hcsTerminateComputeSystem(computeSystem, options, &resultp)
		if resultp != nil {
			result = interop.ConvertAndFreeCoTaskMemString(resultp)
		}
		return err
	})
}

func HcsPauseComputeSystem(ctx gcontext.Context, computeSystem HcsSystem, options string) (result string, hr error) {
	ctx, span := trace.StartSpan(ctx, "HcsPauseComputeSystem")
	defer span.End()
	defer func() {
		if result != "" {
			span.AddAttributes(trace.StringAttribute("result", result))
		}
		if hr != errVmcomputeOperationPending {
			oc.SetSpanStatus(span, hr)
		}
	}()
	span.AddAttributes(trace.StringAttribute("options", options))

	return result, execute(ctx, timeout.SystemPause, func() error {
		var resultp *uint16
		err := hcsPauseComputeSystem(computeSystem, options, &resultp)
		if resultp != nil {
			result = interop.ConvertAndFreeCoTaskMemString(resultp)
		}
		return err
	})
}

func HcsResumeComputeSystem(ctx gcontext.Context, computeSystem HcsSystem, options string) (result string, hr error) {
	ctx, span := trace.StartSpan(ctx, "HcsResumeComputeSystem")
	defer span.End()
	defer func() {
		if result != "" {
			span.AddAttributes(trace.StringAttribute("result", result))
		}
		if hr != errVmcomputeOperationPending {
			oc.SetSpanStatus(span, hr)
		}
	}()
	span.AddAttributes(trace.StringAttribute("options", options))

	return result, execute(ctx, timeout.SystemResume, func() error {
		var resultp *uint16
		err := hcsResumeComputeSystem(computeSystem, options, &resultp)
		if resultp != nil {
			result = interop.ConvertAndFreeCoTaskMemString(resultp)
		}
		return err
	})
}

func HcsGetComputeSystemProperties(ctx gcontext.Context, computeSystem HcsSystem, propertyQuery string) (properties, result string, hr error) {
	ctx, span := trace.StartSpan(ctx, "HcsGetComputeSystemProperties")
	defer span.End()
	defer func() {
		if result != "" {
			span.AddAttributes(trace.StringAttribute("result", result))
		}
		oc.SetSpanStatus(span, hr)
	}()
	span.AddAttributes(trace.StringAttribute("propertyQuery", propertyQuery))

	return properties, result, execute(ctx, timeout.SyscallWatcher, func() error {
		var (
			propertiesp *uint16
			resultp     *uint16
		)
		err := hcsGetComputeSystemProperties(computeSystem, propertyQuery, &propertiesp, &resultp)
		if propertiesp != nil {
			properties = interop.ConvertAndFreeCoTaskMemString(propertiesp)
		}
		if resultp != nil {
			result = interop.ConvertAndFreeCoTaskMemString(resultp)
		}
		return err
	})
}

func HcsModifyComputeSystem(ctx gcontext.Context, computeSystem HcsSystem, configuration string) (result string, hr error) {
	ctx, span := trace.StartSpan(ctx, "HcsModifyComputeSystem")
	defer span.End()
	defer func() {
		if result != "" {
			span.AddAttributes(trace.StringAttribute("result", result))
		}
		oc.SetSpanStatus(span, hr)
	}()
	span.AddAttributes(trace.StringAttribute("configuration", configuration))

	return result, execute(ctx, timeout.SyscallWatcher, func() error {
		var resultp *uint16
		err := hcsModifyComputeSystem(computeSystem, configuration, &resultp)
		if resultp != nil {
			result = interop.ConvertAndFreeCoTaskMemString(resultp)
		}
		return err
	})
}

func HcsModifyServiceSettings(ctx gcontext.Context, settings string) (result string, hr error) {
	ctx, span := trace.StartSpan(ctx, "HcsModifyServiceSettings")
	defer span.End()
	defer func() {
		if result != "" {
			span.AddAttributes(trace.StringAttribute("result", result))
		}
		oc.SetSpanStatus(span, hr)
	}()
	span.AddAttributes(trace.StringAttribute("settings", settings))

	return result, execute(ctx, timeout.SyscallWatcher, func() error {
		var resultp *uint16
		err := hcsModifyServiceSettings(settings, &resultp)
		if resultp != nil {
			result = interop.ConvertAndFreeCoTaskMemString(resultp)
		}
		return err
	})
}

func HcsRegisterComputeSystemCallback(ctx gcontext.Context, computeSystem HcsSystem, callback uintptr, context uintptr) (callbackHandle HcsCallback, hr error) {
	ctx, span := trace.StartSpan(ctx, "HcsRegisterComputeSystemCallback")
	defer span.End()
	defer func() { oc.SetSpanStatus(span, hr) }()

	return callbackHandle, execute(ctx, timeout.SyscallWatcher, func() error {
		return hcsRegisterComputeSystemCallback(computeSystem, callback, context, &callbackHandle)
	})
}

func HcsUnregisterComputeSystemCallback(ctx gcontext.Context, callbackHandle HcsCallback) (hr error) {
	ctx, span := trace.StartSpan(ctx, "HcsUnregisterComputeSystemCallback")
	defer span.End()
	defer func() { oc.SetSpanStatus(span, hr) }()

	return execute(ctx, timeout.SyscallWatcher, func() error {
		return hcsUnregisterComputeSystemCallback(callbackHandle)
	})
}

func HcsCreateProcess(ctx gcontext.Context, computeSystem HcsSystem, processParameters string) (processInformation HcsProcessInformation, process HcsProcess, result string, hr error) {
	ctx, span := trace.StartSpan(ctx, "HcsCreateProcess")
	defer span.End()
	defer func() {
		if result != "" {
			span.AddAttributes(trace.StringAttribute("result", result))
		}
		oc.SetSpanStatus(span, hr)
	}()
	span.AddAttributes(trace.StringAttribute("processParameters", processParameters))

	return processInformation, process, result, execute(ctx, timeout.SyscallWatcher, func() error {
		var resultp *uint16
		err := hcsCreateProcess(computeSystem, processParameters, &processInformation, &process, &resultp)
		if resultp != nil {
			result = interop.ConvertAndFreeCoTaskMemString(resultp)
		}
		return err
	})
}

func HcsOpenProcess(ctx gcontext.Context, computeSystem HcsSystem, pid uint32) (process HcsProcess, result string, hr error) {
	ctx, span := trace.StartSpan(ctx, "HcsOpenProcess")
	defer span.End()
	defer func() {
		if result != "" {
			span.AddAttributes(trace.StringAttribute("result", result))
		}
		oc.SetSpanStatus(span, hr)
	}()
	span.AddAttributes(trace.Int64Attribute("pid", int64(pid)))

	return process, result, execute(ctx, timeout.SyscallWatcher, func() error {
		var resultp *uint16
		err := hcsOpenProcess(computeSystem, pid, &process, &resultp)
		if resultp != nil {
			result = interop.ConvertAndFreeCoTaskMemString(resultp)
		}
		return err
	})
}

func HcsCloseProcess(ctx gcontext.Context, process HcsProcess) (hr error) {
	ctx, span := trace.StartSpan(ctx, "HcsCloseProcess")
	defer span.End()
	defer func() { oc.SetSpanStatus(span, hr) }()

	return execute(ctx, timeout.SyscallWatcher, func() error {
		return hcsCloseProcess(process)
	})
}

func HcsTerminateProcess(ctx gcontext.Context, process HcsProcess) (result string, hr error) {
	ctx, span := trace.StartSpan(ctx, "HcsTerminateProcess")
	defer span.End()
	defer func() {
		if result != "" {
			span.AddAttributes(trace.StringAttribute("result", result))
		}
		oc.SetSpanStatus(span, hr)
	}()

	return result, execute(ctx, timeout.SyscallWatcher, func() error {
		var resultp *uint16
		err := hcsTerminateProcess(process, &resultp)
		if resultp != nil {
			result = interop.ConvertAndFreeCoTaskMemString(resultp)
		}
		return err
	})
}

func HcsSignalProcess(ctx gcontext.Context, process HcsProcess, options string) (result string, hr error) {
	ctx, span := trace.StartSpan(ctx, "HcsSignalProcess")
	defer span.End()
	defer func() {
		if result != "" {
			span.AddAttributes(trace.StringAttribute("result", result))
		}
		oc.SetSpanStatus(span, hr)
	}()
	span.AddAttributes(trace.StringAttribute("options", options))

	return result, execute(ctx, timeout.SyscallWatcher, func() error {
		var resultp *uint16
		err := hcsSignalProcess(process, options, &resultp)
		if resultp != nil {
			result = interop.ConvertAndFreeCoTaskMemString(resultp)
		}
		return err
	})
}

func HcsGetProcessInfo(ctx gcontext.Context, process HcsProcess) (processInformation HcsProcessInformation, result string, hr error) {
	ctx, span := trace.StartSpan(ctx, "HcsGetProcessInfo")
	defer span.End()
	defer func() {
		if result != "" {
			span.AddAttributes(trace.StringAttribute("result", result))
		}
		oc.SetSpanStatus(span, hr)
	}()

	return processInformation, result, execute(ctx, timeout.SyscallWatcher, func() error {
		var resultp *uint16
		err := hcsGetProcessInfo(process, &processInformation, &resultp)
		if resultp != nil {
			result = interop.ConvertAndFreeCoTaskMemString(resultp)
		}
		return err
	})
}

func HcsGetProcessProperties(ctx gcontext.Context, process HcsProcess) (processProperties, result string, hr error) {
	ctx, span := trace.StartSpan(ctx, "HcsGetProcessProperties")
	defer span.End()
	defer func() {
		if result != "" {
			span.AddAttributes(trace.StringAttribute("result", result))
		}
		oc.SetSpanStatus(span, hr)
	}()

	return processProperties, result, execute(ctx, timeout.SyscallWatcher, func() error {
		var (
			processPropertiesp *uint16
			resultp            *uint16
		)
		err := hcsGetProcessProperties(process, &processPropertiesp, &resultp)
		if processPropertiesp != nil {
			processProperties = interop.ConvertAndFreeCoTaskMemString(processPropertiesp)
		}
		if resultp != nil {
			result = interop.ConvertAndFreeCoTaskMemString(resultp)
		}
		return err
	})
}

func HcsModifyProcess(ctx gcontext.Context, process HcsProcess, settings string) (result string, hr error) {
	ctx, span := trace.StartSpan(ctx, "HcsModifyProcess")
	defer span.End()
	defer func() {
		if result != "" {
			span.AddAttributes(trace.StringAttribute("result", result))
		}
		oc.SetSpanStatus(span, hr)
	}()
	span.AddAttributes(trace.StringAttribute("settings", settings))

	return result, execute(ctx, timeout.SyscallWatcher, func() error {
		var resultp *uint16
		err := hcsModifyProcess(process, settings, &resultp)
		if resultp != nil {
			result = interop.ConvertAndFreeCoTaskMemString(resultp)
		}
		return err
	})
}

func HcsGetServiceProperties(ctx gcontext.Context, propertyQuery string) (properties, result string, hr error) {
	ctx, span := trace.StartSpan(ctx, "HcsGetServiceProperties")
	defer span.End()
	defer func() {
		if result != "" {
			span.AddAttributes(trace.StringAttribute("result", result))
		}
		oc.SetSpanStatus(span, hr)
	}()
	span.AddAttributes(trace.StringAttribute("propertyQuery", propertyQuery))

	return properties, result, execute(ctx, timeout.SyscallWatcher, func() error {
		var (
			propertiesp *uint16
			resultp     *uint16
		)
		err := hcsGetServiceProperties(propertyQuery, &propertiesp, &resultp)
		if propertiesp != nil {
			properties = interop.ConvertAndFreeCoTaskMemString(propertiesp)
		}
		if resultp != nil {
			result = interop.ConvertAndFreeCoTaskMemString(resultp)
		}
		return err
	})
}

func HcsRegisterProcessCallback(ctx gcontext.Context, process HcsProcess, callback uintptr, context uintptr) (callbackHandle HcsCallback, hr error) {
	ctx, span := trace.StartSpan(ctx, "HcsRegisterProcessCallback")
	defer span.End()
	defer func() { oc.SetSpanStatus(span, hr) }()

	return callbackHandle, execute(ctx, timeout.SyscallWatcher, func() error {
		return hcsRegisterProcessCallback(process, callback, context, &callbackHandle)
	})
}

func HcsUnregisterProcessCallback(ctx gcontext.Context, callbackHandle HcsCallback) (hr error) {
	ctx, span := trace.StartSpan(ctx, "HcsUnregisterProcessCallback")
	defer span.End()
	defer func() { oc.SetSpanStatus(span, hr) }()

	return execute(ctx, timeout.SyscallWatcher, func() error {
		return hcsUnregisterProcessCallback(callbackHandle)
	})
}

func HcsSaveComputeSystem(ctx gcontext.Context, computeSystem HcsSystem, options string) (result string, hr error) {
	ctx, span := trace.StartSpan(ctx, "HcsSaveComputeSystem")
	defer span.End()
	defer func() {
		if result != "" {
			span.AddAttributes(trace.StringAttribute("result", result))
		}
		if hr != errVmcomputeOperationPending {
			oc.SetSpanStatus(span, hr)
		}
	}()

	return result, execute(ctx, timeout.SyscallWatcher, func() error {
		var resultp *uint16
		err := hcsSaveComputeSystem(computeSystem, options, &resultp)
		if resultp != nil {
			result = interop.ConvertAndFreeCoTaskMemString(resultp)
		}
		return err
	})
}


text:
layout: post
title:  Welcome to Rudrakosh!
date:   2016-05-06 10:12:16
desc: This is the first blog post from the Rudrakos.
categories:
- General
tags:
- General
---

When I told my friends that I bought a domain named *Rudrakos* for blogging and the first question I got was:

> what does the name "Rudrakos" mean?

but before I tell the meaning of it, the first thing I wanted to share the real reason behind picking up this domain name. It is because "Rahul" is such a common name in India that finding a domain name would be like counting star in galaxy.

The site name, Rudrakos (pronounced "roo d-ruh kohs") is a combination of two Sanskrit words i.e. Rudra (mightiest of mighty) and Kosa (pocket), meaning container of omnipotent.

The name have so heavy meaning... and so I will try with every piece of writing here to be omnipotent. I will be writing about softwares, programming and lifelong learning experiences.

Also if you have some ideas to share, you can publish it here, just [mail](mailto:rahul@rudrakos.com) it to me.

redpajama_set_name: RedPajamaGithub


text:
'''
Created on 28 Mar 2013

@author: Jonathan Custance
'''
import sys
import xml.etree.ElementTree as ET
import Category
import Attribute
import Action
import Link
import Mixin
import Collection
import Model
import logging

from ParserCollection import ParserCollection

class Parser(object):
    '''
    Parse a set of XML model files and return a Models object containing all the
    models that have been successfully parsed.
    '''

    def __init__(self, files):
        '''
        Constructor
            @param files: list of files to parse
        '''
        self.files = files
        self.cats = Category.Categories()
        self.models = Model.Models()

        # Add the standard categories from OCCI Core
        self._built_in_model = Model.Model("core", "OCCI Core categories", "1.0,0")
        self.models.add(self._built_in_model)
        # Entity
        entity = Category.Category("entity", "http://schemas.ogf.org/occi/core#", "/entity/", None, "kind", self._built_in_model)
        entity.addattr(Attribute.Attribute("id", "string", "true", "true", None, "true"))
        entity.addattr(Attribute.Attribute("title", "string", "false", "false", None, "false"))
        self.cats.add(entity)

        # Resource
        resource = Category.Category("resource", "http://schemas.ogf.org/occi/core#", "/resource/",
                                     "http://schemas.ogf.org/occi/core#entity", "kind", self._built_in_model)
        resource.addattr(Attribute.Attribute("summary", "string", "false", "false", None, "false"))
        self.cats.add(resource)

        # Link
        link = Category.Category("link", "http://schemas.ogf.org/occi/core#", "/link/",
                                     "http://schemas.ogf.org/occi/core#entity", "link", self._built_in_model)
        link.addattr(Attribute.Attribute("source", "string", "true", "false", None, "false"))
        link.addattr(Attribute.Attribute("target", "string", "true", "false", None, "false"))
        self.cats.add(link)
        self.parsers = ParserCollection()

    def parse(self):
        '''
            Do the work of the Parser class
        '''
        # Parse each file / model
        for f in self.files:
            self._parse(f)
        # Resolve rels and collections/instances
        self.cats.resolve()
        self.parsers.resolve(self.cats.list.values())
        return self.models

    def _addcoll(self, colls, cat):
        '''
        Parse and add collection attributes to a category
            @param colls: a collection of XML Elements
            @param cat: the Category to add the collections to
        '''
        for coll in colls:
            name = coll.get("name")
            if name == None:
                logging.warn("Category "+cat.term+" - invalid collection")
                continue
            logging.info("Category "+cat.term+" collection "+name)
            try:
                cat.addcoll(Collection.Collection(name, coll.get("category"), coll.get("multiplicity"),
                                                  coll.get("legacytype"), coll.get("scope"), coll.get("script")))
            except:
                logging.error("Category "+cat.term+"Problem processing collection "+id)
                logging.error(sys.exc_info())

    def _addactions(self, category, cat):
        '''
        Parse and add all actions to a category
            @param category: a collection of XML Elements
            @param cat: the Category to add the collections to
        '''
        for action in category.findall("actions/action"):
            actionid = action.get("id")
            if actionid == None:
                logging.warn("Category "+cat.term+" - invalid action")
                continue
            logging.info("Category "+cat.term+" action "+actionid)
            try:
                cat.addaction(Action.Action(actionid))
            except:
                logging.error("Category "+cat.term+" Problem processing action "+actionid)
                logging.error(sys.exc_info())

    def _addlinks(self, category, cat):
        '''
        Parse and add all links to a category
            @param category: a collection of XML Elements
            @param cat: the Category to add the collections to
        '''
        for link in category.findall("links/link"):
            linkid = link.get("id")
            if linkid == None:
                logging.warn("Category "+cat.term+" - invalid link")
                continue
            logging.info("Category "+cat.term+" link "+linkid)
            try:
                cat.addlink(Link.Link(linkid))
            except:
                logging.error("Category "+cat.term+" Problem processing link "+linkid)
                logging.error(sys.exc_info())

    def _addmixins(self, category, cat):
        '''
        Parse and add all mixins to a category
            @param category: a collection of XML Elements
            @param cat: the Category to add the collections to
        '''
        for mixin in category.findall("mixins/mixin"):
            mixinid = mixin.get("id")
            if mixinid == None:
                logging.warn("Category "+cat.term+" - invalid mixin")
                continue
            logging.info("Category "+cat.term+" mixin "+mixinid)
            try:
                cat.addmixin(Mixin.Mixin(mixinid))
            except:
                logging.error("Category "+cat.term+" Problem processing mixin "+mixinid)
                logging.error(sys.exc_info())

    def _addattrs(self, category, cat):
        '''
        Parse and add all attributes to a category
            @param category: a collection of XML Elements
            @param cat: the Category to add the collections to
        '''
        # Parse attributes
        for attr in category.findall("attributes/attribute"):
            name = attr.get("name")
            if name == None:
                logging.warn("Category"+cat.term+" - invalid attribute")
                continue
            logging.info("Category "+cat.term+" attribute "+name)
            try:
                cat.addattr(Attribute.Attribute(name, attr.get("type"), attr.get("required"),
                                                attr.get("immutable"), attr.get("validation"),
                                                 attr.get("index"), attr.get("default"), attr.get("units"), attr.get("legacytype"),
                                                 attr.get("scope"),  attr.get("script")))
            except:
                logging.error("Category "+cat.term+"Problem processing attribute "+id)
                logging.error(sys.exc_info())

        # Parse instances
        colls = category.findall("attributes/instance")
        self._addcoll(colls, cat)

        # Parse collections
        colls = category.findall("attributes/collection")
        self._addcoll(colls, cat)

    def _parse(self, f):
        '''
        Parse a given XML file
            @param f File name
        '''
        logging.info("Processing "+f)
        try:
            tree = ET.parse(f)
            root = tree.getroot()
            # TODO schema version check etc.
            self._parse_models(root)
            self.parsers.parse(root)
            #TODO Check that at least one of the parsers read something
        except:
            logging.error("Problem parsing "+f)
            logging.error(sys.exc_info())

    def _parse_models(self, root):
        # TODO checking for single model
        # TODO warn about unknown XML nodes
        try:
            xmlmodel = root.find("model")
            if xmlmodel is None:
                return
            model = Model.Model(xmlmodel.get("name"), xmlmodel.get("description"),
                                xmlmodel.get("version"), xmlmodel.get("namespace"))
            logging.info("Model is "+model.name+" (v. "+model.version+")")
        except:
            logging.error("Problem processing model")
            raise
        # Find all categories
        for category in xmlmodel.findall("category"):
            term = category.get("term")
            if term == None:
                logging.warn("No category provided")
                continue
            logging.info("Category "+term)
            # Add a category
            try:
                scheme, klass, location, rel, struct_name, headerFilename = category.get("scheme"), category.get("class"), category.get("location"), category.get("rel"), category.get("structname"), category.get("headerfilename")
                cat = Category.Category(term, scheme, location, rel, klass, model, struct_name, headerFilename)
                self._addattrs(category, cat)
                self._addactions(category, cat)
                self._addlinks(category, cat)
                self._addmixins(category, cat)
                model.add(cat)
                self.cats.add(cat)
            except:
                logging.error("Problem processing category "+term)
                logging.error(sys.exc_info())
        # Add this model to the models collection
        self.models.add(model)


text:
<!DOCTYPE html>

{% include head.html %}

    {% include header.html %}

{{page.title}}

{{content}}

    {% include footer.html %}


text:
All of the source code for my blog tutorials can be found here.
Feel free to use any or all of the code on my GitHub as long as you give credit.


text:
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;

using TAPI;
using Terraria;

namespace jFlail.Projectiles
{
    public class GABall : ModProjectile
    {

        public override void PostAI()
        {
            float speedX = projectile.velocity.X * (float)Main.rand.Next(3) * 0.2f;
            float speedY = projectile.velocity.Y * (float)Main.rand.Next(3) * 0.2f;
            int sp = ProjDef.byName["jFlail:Starproj"].type;
            int i = Dust.NewDust(projectile.position, projectile.width, projectile.height, 29, speedX, speedY, 80, default(Color), 1.6f);
            Main.dust[i].noGravity = true;
            int j = Dust.NewDust(projectile.position, projectile.width, projectile.height, 0, speedX, speedY, 65, default(Color), 0.8f);
            Main.dust[j].noGravity = true;

            if (Main.rand.Next(1) == 0)
            {
                if (Main.rand.Next(35) == 0)
                Projectile.NewProjectile(projectile.position.X, projectile.position.Y + 1.0f, speedX, speedY, sp, 89, 0, projectile.whoAmI);
                Projectile.NewProjectile(projectile.position.X, projectile.position.Y + 1.0f, speedX, speedY, sp, 89, 0, projectile.whoAmI);
                Projectile.NewProjectile(projectile.position.X, projectile.position.Y + 1.0f, speedX, speedY, sp, 89, 0, projectile.whoAmI);
            }
        }
    }
}


text:
set(Plugin-Name "IGT APP: EchoTrack")
set(Plugin-Version "0.1")
set(Plugin-Vendor "DKFZ, Medical and Biological Informatics")
set(Plugin-ContactAddress "http://www.mitk.org")
set(Require-Plugin org.mitk.gui.qt.common org.mitk.gui.qt.stdmultiwidgeteditor)


text:
/**
 * Queue
 * {front} Node, the first element in the queue
 * {back} Node, the last element in the queue
 * {size} number, the number of nodes in the queue
 *
 * Asymptotic time complexities
 * +-------------------+
 * | enqueue  |  O(1)  |
 * | dequeue  |  O(1)  |
 * +-------------------+
 *
 */

const Node = require('../Nodes/unidirectional_node.js');

/**
 * Single argument constructor.
 * @param {*} [data] data for front node of queue
 * @return {void}
 */
const Queue = function(data){
  this.front;
  this.back;
  this.size;
  if(typeof data !== 'undefined'){
    this.front = new Node(data);
    this.back = this.front;
    this.front.next = this.back;
    this.back.next = null;
    this.size = 1;
  }else{
    this.front = null;
    this.back = null;
    this.size = 0;
  }
}

/**
 * Creates a node with the given data and adds that node
 * to the back of the queue
 * @param {*} data for head node of linked list
 * @return {void}
 */
Queue.prototype.enqueue = function(data){
  if(typeof data === 'undefined'){
    throw new Error("Too few arguments in Queue.enqueue");
  }
  var newNode = new Node(data);
  // Check to see if front/back exist
  if(this.front === null && this.back === null){
    this.front = newNode;
    this.back = this.front;
    this.front.next = this.back;
    this.back.next = null;
    ++this.size;
  }else if(this.front !== null && this.back !== null){
    // Add to end of the queue
    this.back.next = newNode;
    this.back = newNode;
    ++this.size;
  }
  // Both front and back should either be set or null; if not then something went wrong somewhere
  else{
    throw new Error("Either front or back is not set in an a queue at once. Please report this to https://github.com/nickzuber/needle/issues");
  }
}

/**
 * Removes the node at the front of the queue
 * @param {void}
 * @return {void}
 */
Queue.prototype.dequeue = function(){
  if(this.size === 0){
    throw new Error("Attempted to dequeue from empty queue in Queue.enqueue");
  }
  // Remove from the front
  var newHead = this.front.next;
  this.front = newHead;
  --this.size;
}

module.exports = Queue;


text:
var test = require("tape")
var h = require("virtual-dom/virtual-hyperscript")
var document = require("global/document")
var raf = require("raf")

var mainLoop = require("../index")

test("mainLoop is a function", function (assert) {
    assert.equal(typeof mainLoop, "function")
    assert.end()
})

test("can set up main loop", function (assert) {
    var initState = { fruits: ["apple", "banana"], name: "Steve" }

    function render(state) {
        return h("div", [
            h("div", [
                h("span", "hello "),
                h("span.name", state.name)
            ]),
            h("ul", state.fruits.map(renderFruit))
        ])

        function renderFruit(fruitName) {
            return h("li", [
                h("span", fruitName)
            ])
        }
    }

    // set up a loop
    var loop = mainLoop(initState, render, {
        document: document,
        create: require("virtual-dom/create-element"),
        diff: require("virtual-dom/diff"),
        patch: require("virtual-dom/patch")
    })
    document.body.appendChild(loop.target)

    var div = loop.target
    var span = div.childNodes[0].childNodes[1]
    var ul = div.childNodes[1]

    assert.equal(div.tagName, "DIV")
    assert.equal(span.childNodes[0].data, "Steve")
    assert.equal(ul.childNodes.length, 2)

    // update the loop with the new application state
    loop.update({
        fruits: ["apple", "banana", "cherry"],
        name: "Steve"
    })

    raf(function () {
        assert.equal(ul.childNodes.length, 3)

        loop.update({
            fruits: ["apple", "banana", "cherry"],
            name: "Stevie"
        })

        raf(function () {
            assert.equal(span.childNodes[0].data, "Stevie")

            document.body.removeChild(loop.target)
            assert.end()
        })
    })
})

test("loop.state exposed", function (assert) {
    var loop = mainLoop({ n: 0 }, render, {
        document: document,
        create: require("virtual-dom/create-element"),
        diff: require("virtual-dom/diff"),
        patch: require("virtual-dom/patch")
    })
    assert.equal(loop.state.n, 0)
    loop.update({ n: 4 })
    assert.equal(loop.state.n, 4)
    assert.end()

    function render(state) {
        return h('div', String(state.n))
    }
})


text:
namespace chrome_pdf {

namespace {

bool IsNegative(int32_t num) {
  return num < 0;
}

}  // namespace

// ----------------------------------------------------------------------------
// ALGORITHM NOTES
//
// We attempt to maintain a scroll rect in the presence of invalidations that
// are contained within the scroll rect.  If an invalidation crosses a scroll
// rect, then we just treat the scroll rect as an invalidation rect.
//
// For invalidations performed prior to scrolling and contained within the
// scroll rect, we offset the invalidation rects to account for the fact that
// the consumer will perform scrolling before painting.
//
// We only support scrolling along one axis at a time.  A diagonal scroll will
// therefore be treated as an invalidation.
// ----------------------------------------------------------------------------

PaintAggregator::PaintUpdate::PaintUpdate() = default;

PaintAggregator::PaintUpdate::PaintUpdate(const PaintUpdate& that) = default;

PaintAggregator::PaintUpdate::~PaintUpdate() = default;

PaintAggregator::InternalPaintUpdate::InternalPaintUpdate()
    : synthesized_scroll_damage_rect_(false) {}

PaintAggregator::InternalPaintUpdate::~InternalPaintUpdate() = default;

gfx::Rect PaintAggregator::InternalPaintUpdate::GetScrollDamage() const {
  // Should only be scrolling in one direction at a time.
  DCHECK(!(scroll_delta.x() && scroll_delta.y()));

  gfx::Rect damaged_rect;

  // Compute the region we will expose by scrolling, and paint that into a
  // shared memory section.
  if (scroll_delta.x()) {
    int32_t dx = scroll_delta.x();
    damaged_rect.set_y(scroll_rect.y());
    damaged_rect.set_height(scroll_rect.height());
    if (dx > 0) {
      damaged_rect.set_x(scroll_rect.x());
      damaged_rect.set_width(dx);
    } else {
      damaged_rect.set_x(scroll_rect.right() + dx);
      damaged_rect.set_width(-dx);
    }
  } else {
    int32_t dy = scroll_delta.y();
    damaged_rect.set_x(scroll_rect.x());
    damaged_rect.set_width(scroll_rect.width());
    if (dy > 0) {
      damaged_rect.set_y(scroll_rect.y());
      damaged_rect.set_height(dy);
    } else {
      damaged_rect.set_y(scroll_rect.bottom() + dy);
      damaged_rect.set_height(-dy);
    }
  }

  // In case the scroll offset exceeds the width/height of the scroll rect
  return gfx::IntersectRects(scroll_rect, damaged_rect);
}

PaintAggregator::PaintAggregator() = default;

bool PaintAggregator::HasPendingUpdate() const {
  return !update_.scroll_rect.IsEmpty() || !update_.paint_rects.empty();
}

void PaintAggregator::ClearPendingUpdate() {
  update_ = InternalPaintUpdate();
}

PaintAggregator::PaintUpdate PaintAggregator::GetPendingUpdate() {
  // Convert the internal paint update to the external one, which includes a
  // bit more precomputed info for the caller.
  PaintUpdate ret;
  ret.scroll_delta = update_.scroll_delta;
  ret.scroll_rect = update_.scroll_rect;
  ret.has_scroll = ret.scroll_delta.x() != 0 || ret.scroll_delta.y() != 0;

  // Include the scroll damage (if any) in the paint rects.
  // Code invalidates damaged rect here, it pick it up from the list of paint
  // rects in the next block.
  if (ret.has_scroll && !update_.synthesized_scroll_damage_rect_) {
    update_.synthesized_scroll_damage_rect_ = true;
    gfx::Rect scroll_damage = update_.GetScrollDamage();
    InvalidateRectInternal(scroll_damage, false);
  }

  ret.paint_rects.reserve(update_.paint_rects.size() + 1);
  ret.paint_rects.insert(ret.paint_rects.end(), update_.paint_rects.begin(),
                         update_.paint_rects.end());

  return ret;
}

void PaintAggregator::SetIntermediateResults(
    const std::vector<PaintReadyRect>& ready,
    const std::vector<gfx::Rect>& pending) {
  update_.ready_rects.insert(update_.ready_rects.end(), ready.begin(),
                             ready.end());
  update_.paint_rects = pending;
}

std::vector<PaintReadyRect> PaintAggregator::GetReadyRects() const {
  return update_.ready_rects;
}

void PaintAggregator::InvalidateRect(const gfx::Rect& rect) {
  InvalidateRectInternal(rect, true);
}

void PaintAggregator::ScrollRect(const gfx::Rect& clip_rect,
                                 const gfx::Vector2d& amount) {
  // We only support scrolling along one axis at a time.
  if (amount.x() != 0 && amount.y() != 0) {
    InvalidateRect(clip_rect);
    return;
  }

  // We can only scroll one rect at a time.
  if (!update_.scroll_rect.IsEmpty() && update_.scroll_rect != clip_rect) {
    InvalidateRect(clip_rect);
    return;
  }

  // Again, we only support scrolling along one axis at a time.  Make sure this
  // update doesn't scroll on a different axis than any existing one.
  if ((amount.x() && update_.scroll_delta.y()) ||
      (amount.y() && update_.scroll_delta.x())) {
    InvalidateRect(clip_rect);
    return;
  }

  // If we scroll in a reverse direction to the direction we originally scrolled
  // and there were invalidations that happened in-between we may end up
  // incorrectly clipping the invalidated rects (see crbug.com/488390). This bug
  // doesn't exist in the original implementation
  // (ppapi/utility/graphics/paint_aggregator.cc) which uses a different method
  // of handling invalidations that occur after a scroll. The problem is that
  // when we scroll the invalidated region, we clip it to the scroll rect. This
  // can cause us to lose information about what the invalidated region was if
  // it gets scrolled back into view. We either need to not do this clipping or
  // disallow combining scrolls that occur in different directions with
  // invalidations that happen in-between. This code really needs some tests...
  if (!update_.paint_rects.empty()) {
    if (IsNegative(amount.x()) != IsNegative(update_.scroll_delta.x()) ||
        IsNegative(amount.y()) != IsNegative(update_.scroll_delta.y())) {
      InvalidateRect(clip_rect);
      return;
    }
  }

  // The scroll rect is new or isn't changing (though the scroll amount may
  // be changing).
  update_.scroll_rect = clip_rect;
  update_.scroll_delta += amount;

  // We might have just wiped out a pre-existing scroll.
  if (update_.scroll_delta == gfx::Vector2d()) {
    update_.scroll_rect = gfx::Rect();
    return;
  }

  // Adjust any paint rects that intersect the scroll. For the portion of the
  // paint that is inside the scroll area, move it by the scroll amount and
  // replace the existing paint with it. For the portion (if any) that is
  // outside the scroll, just invalidate it.
  std::vector<gfx::Rect> leftover_rects;
  for (size_t i = 0; i < update_.paint_rects.size(); ++i) {
    if (!update_.scroll_rect.Intersects(update_.paint_rects[i]))
      continue;

    gfx::Rect intersection =
        gfx::IntersectRects(update_.paint_rects[i], update_.scroll_rect);
    gfx::Rect rect = update_.paint_rects[i];
    while (!rect.IsEmpty()) {
      gfx::Rect leftover = gfx::SubtractRects(rect, intersection);
      if (leftover.IsEmpty())
        break;
      // Don't want to call InvalidateRectInternal now since it'll modify
      // update_.paint_rects, so keep track of this and do it below.
      leftover_rects.push_back(leftover);
      rect.Subtract(leftover);
    }

    update_.paint_rects[i] = ScrollPaintRect(intersection, amount);

    // The rect may have been scrolled out of view.
    if (update_.paint_rects[i].IsEmpty()) {
      update_.paint_rects.erase(update_.paint_rects.begin() + i);
      i--;
    }
  }

  for (const auto& leftover_rect : leftover_rects)
    InvalidateRectInternal(leftover_rect, false);

  for (auto& update_rect : update_.ready_rects) {
    if (update_.scroll_rect.Contains(update_rect.rect()))
      update_rect.set_rect(ScrollPaintRect(update_rect.rect(), amount));
  }

  if (update_.synthesized_scroll_damage_rect_) {
    InvalidateRect(update_.GetScrollDamage());
  }
}

gfx::Rect PaintAggregator::ScrollPaintRect(const gfx::Rect& paint_rect,
                                           const gfx::Vector2d& amount) const {
  gfx::Rect result = paint_rect + amount;
  result.Intersect(update_.scroll_rect);
  return result;
}

void PaintAggregator::InvalidateScrollRect() {
  gfx::Rect scroll_rect = update_.scroll_rect;
  update_.scroll_rect = gfx::Rect();
  update_.scroll_delta = gfx::Vector2d();
  InvalidateRect(scroll_rect);
}

void PaintAggregator::InvalidateRectInternal(const gfx::Rect& rect_old,
                                             bool check_scroll) {
  gfx::Rect rect = rect_old;
  // Check if any rects that are ready to be painted overlap.
  for (size_t i = 0; i < update_.ready_rects.size(); ++i) {
    const gfx::Rect& existing_rect = update_.ready_rects[i].rect();
    if (rect.Intersects(existing_rect)) {
      // Re-invalidate in case the union intersects other paint rects.
      rect.Union(existing_rect);
      update_.ready_rects.erase(update_.ready_rects.begin() + i);
      break;
    }
  }

  bool add_paint = true;

  // Combine overlapping paints using smallest bounding box.
  for (size_t i = 0; i < update_.paint_rects.size(); ++i) {
    const gfx::Rect& existing_rect = update_.paint_rects[i];
    if (existing_rect.Contains(rect))  // Optimize out redundancy.
      add_paint = false;
    if (rect.Intersects(existing_rect) || rect.SharesEdgeWith(existing_rect)) {
      // Re-invalidate in case the union intersects other paint rects.
      gfx::Rect combined_rect = gfx::UnionRects(rect, existing_rect);
      update_.paint_rects.erase(update_.paint_rects.begin() + i);
      InvalidateRectInternal(combined_rect, check_scroll);
      add_paint = false;
    }
  }

  if (add_paint) {
    // Add a non-overlapping paint.
    update_.paint_rects.push_back(rect);
  }

  // If the new paint overlaps with a scroll, then also invalidate the rect in
  // its new position.
  if (check_scroll && !update_.scroll_rect.IsEmpty() &&
      update_.scroll_rect.Intersects(rect)) {
    InvalidateRectInternal(ScrollPaintRect(rect, update_.scroll_delta), false);
  }
}

}  // namespace chrome_pdf


text:
escrima_sticks
==============

Arduino-based "NIghtwing" Escrima Sticks


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Boost.Geometry (aka GGL, Generic Geometry Library)</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Related Pages

Modules

Namespaces

Classes

Files

Examples

File List

File Members

home

ubuntu

boost

boost

geometry

io

wkt

Functions

stream.hpp File Reference

Functions

template<typename Char , typename Traits , typename Geometry >

std::basic_ostream< Char,

Traits > & 	operator<< (std::basic_ostream< Char, Traits > &os, Geometry const &geom)

Function Documentation

template<typename Char , typename Traits , typename Geometry >

          std::basic_ostream<Char, Traits>& operator<<
          (
          std::basic_ostream< Char, Traits > &
          os,

          Geometry const &
          geom

          )

April 2, 2011

Copyright © 2007-2011 Barend Gehrels, Amsterdam, the Netherlands

Copyright © 2008-2011 Bruno Lalande, Paris, France

Copyright © 2009-2010 Mateusz Loskot, London, UK

<address style="text-align: right;">
Documentation is generated by Doxygen
</address>


text:
<?php namespace Anomaly\PostsModule\Post\Form\Command;

use Anomaly\PostsModule\Post\Contract\PostInterface;
use Anomaly\PostsModule\Post\Form\PostEntryFormBuilder;
use Anomaly\PostsModule\Post\Form\PostFormBuilder;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Foundation\Bus\DispatchesJobs;

/**
 * Class AddPostFormFromPost
 *
 * @link          http://anomaly.is/streams-platform
 * @author        AnomalyLabs, Inc. <hello@anomaly.is>
 * @author        Ryan Thompson <ryan@anomaly.is>
 * @package       Anomaly\PostsModule\Post\Form\Command
 */
class AddPostFormFromPost implements SelfHandling
{

    use DispatchesJobs;

    /**
     * The multiple form builder.
     *
     * @var PostEntryFormBuilder
     */
    protected $builder;

    /**
     * The post instance.
     *
     * @var PostInterface
     */
    protected $post;

    /**
     * Create a new AddPostFormFromPost instance.
     *
     * @param PostEntryFormBuilder $builder
     * @param PostInterface        $post
     */
    public function __construct(PostEntryFormBuilder $builder, PostInterface $post)
    {
        $this->builder = $builder;
        $this->post    = $post;
    }

    /**
     * Handle the command.
     *
     * @param PostFormBuilder $builder
     */
    public function handle(PostFormBuilder $builder)
    {
        $builder->setEntry($this->post->getId());

        $this->builder->addForm('post', $builder);
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.skife.gressil</groupId>
    <artifactId>gressil</artifactId>
    <packaging>jar</packaging>
    <version>0.0.5-SNAPSHOT</version>
    <name>gressil</name>
    <url>http://github.com/brianm/gressil</url>
    <description>
        Java Process Daemonization via posix_spawn
    </description>

    <parent>
        <groupId>org.basepom</groupId>
        <artifactId>basepom-standard-oss</artifactId>
        <version>4</version>
    </parent>

    <licenses>
        <license>
            <name>Apache License 2.0</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0.html</url>
            <distribution>repo</distribution>
        </license>
    </licenses>

    <scm>
        <connection>scm:git:git://github.com/brianm/gressil.git</connection>
        <developerConnection>scm:git:git@github.com:brianm/gressil.git</developerConnection>
        <url>http://github.com/brianm/gressil/tree/master</url>
      <tag>gressil-0.0.5</tag>
  </scm>

    <properties>
        <project.jdk7.home>${env.JAVA7_HOME}</project.jdk7.home>
        <project.build.targetJdk>1.7</project.build.targetJdk>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <basepom.check.skip-basic>true</basepom.check.skip-basic>
        <basepom.check.skip-findbugs>true</basepom.check.skip-findbugs>
        <basepom.check.skip-pmd>true</basepom.check.skip-pmd>
        <basepom.check.fail-checkstyle>false</basepom.check.fail-checkstyle>
        <basepom.check.skip-license>true</basepom.check.skip-license>
    </properties>

    <dependencies>

        <dependency>
            <groupId>com.github.jnr</groupId>
            <artifactId>jnr-ffi</artifactId>
            <version>0.6.0</version>
        </dependency>

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>11.0.1</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-release-plugin</artifactId>
                <version>2.4.2</version>
                <dependencies>
                    <dependency>
                        <groupId>org.apache.maven.scm</groupId>
                        <artifactId>maven-scm-provider-gitexe</artifactId>
                        <version>1.9</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>

    <developers>
        <developer>
            <id>brianm</id>
            <name>Brian McCallister</name>
            <email>brianm@skife.org</email>
        </developer>
    </developers>

</project>


text:
var obj = {
  val: 'Hi There',
    //It does not matter where function is declared, for example here in obj. What matters where the function is executed.
  printVal: function() {
      //console.log(this);
      console.log(this.val);
  }
};

var obj2  = {
    val: 'I am amazing'
};

//Javascript basically looks at the left side of the DOT(.)  and that becomes This. So in the below statement obj2 becomes this
obj2.printVal = obj.printVal;

//Here obj becomes This.
obj.printVal();

obj2.printVal();

//Javascript basically looks at the left side of the DOT(.)  and that becomes This. So in the below statement there is no DOT(.) Hence it defaults
//to binding to Global object.
var print = obj.printVal;

print();
//You can bind the function to an object. So here This refers to obj2
var printer = obj.printVal.bind(obj2);
printer();


text:
package kafka.server

import com.yammer.metrics.core.Gauge
import kafka.cluster.BrokerEndPoint
import kafka.metrics.KafkaYammerMetrics
import kafka.utils.TestUtils
import org.apache.kafka.common.TopicPartition
import org.easymock.EasyMock
import org.junit.jupiter.api.{BeforeEach, Test}
import org.junit.jupiter.api.Assertions._

import scala.jdk.CollectionConverters._

class AbstractFetcherManagerTest {

  @BeforeEach
  def cleanMetricRegistry(): Unit = {
    TestUtils.clearYammerMetrics()
  }

  private def getMetricValue(name: String): Any = {
    KafkaYammerMetrics.defaultRegistry.allMetrics.asScala.filter { case (k, _) => k.getName == name }.values.headOption.get.
      asInstanceOf[Gauge[Int]].value()
  }

  @Test
  def testAddAndRemovePartition(): Unit = {
    val fetcher: AbstractFetcherThread = EasyMock.mock(classOf[AbstractFetcherThread])
    val fetcherManager = new AbstractFetcherManager[AbstractFetcherThread]("fetcher-manager", "fetcher-manager", 2) {
      override def createFetcherThread(fetcherId: Int, sourceBroker: BrokerEndPoint): AbstractFetcherThread = {
        fetcher
      }
    }

    val fetchOffset = 10L
    val leaderEpoch = 15
    val tp = new TopicPartition("topic", 0)
    val initialFetchState = InitialFetchState(
      leader = new BrokerEndPoint(0, "localhost", 9092),
      currentLeaderEpoch = leaderEpoch,
      initOffset = fetchOffset)

    EasyMock.expect(fetcher.start())
    EasyMock.expect(fetcher.addPartitions(Map(tp -> initialFetchState)))
        .andReturn(Set(tp))
    EasyMock.expect(fetcher.fetchState(tp))
      .andReturn(Some(PartitionFetchState(fetchOffset, None, leaderEpoch, Truncating, lastFetchedEpoch = None)))
    EasyMock.expect(fetcher.removePartitions(Set(tp))).andReturn(Map.empty)
    EasyMock.expect(fetcher.fetchState(tp)).andReturn(None)
    EasyMock.replay(fetcher)

    fetcherManager.addFetcherForPartitions(Map(tp -> initialFetchState))
    assertEquals(Some(fetcher), fetcherManager.getFetcher(tp))

    fetcherManager.removeFetcherForPartitions(Set(tp))
    assertEquals(None, fetcherManager.getFetcher(tp))

    EasyMock.verify(fetcher)
  }

  @Test
  def testMetricFailedPartitionCount(): Unit = {
    val fetcher: AbstractFetcherThread = EasyMock.mock(classOf[AbstractFetcherThread])
    val fetcherManager = new AbstractFetcherManager[AbstractFetcherThread]("fetcher-manager", "fetcher-manager", 2) {
      override def createFetcherThread(fetcherId: Int, sourceBroker: BrokerEndPoint): AbstractFetcherThread = {
        fetcher
      }
    }

    val tp = new TopicPartition("topic", 0)
    val metricName = "FailedPartitionsCount"

    // initial value for failed partition count
    assertEquals(0, getMetricValue(metricName))

    // partition marked as failed increments the count for failed partitions
    fetcherManager.failedPartitions.add(tp)
    assertEquals(1, getMetricValue(metricName))

    // removing fetcher for the partition would remove the partition from set of failed partitions and decrement the
    // count for failed partitions
    fetcherManager.removeFetcherForPartitions(Set(tp))
    assertEquals(0, getMetricValue(metricName))
  }
  @Test
  def testDeadThreadCountMetric(): Unit = {
    val fetcher: AbstractFetcherThread = EasyMock.mock(classOf[AbstractFetcherThread])
    val fetcherManager = new AbstractFetcherManager[AbstractFetcherThread]("fetcher-manager", "fetcher-manager", 2) {
      override def createFetcherThread(fetcherId: Int, sourceBroker: BrokerEndPoint): AbstractFetcherThread = {
        fetcher
      }
    }

    val fetchOffset = 10L
    val leaderEpoch = 15
    val tp = new TopicPartition("topic", 0)
    val initialFetchState = InitialFetchState(
      leader = new BrokerEndPoint(0, "localhost", 9092),
      currentLeaderEpoch = leaderEpoch,
      initOffset = fetchOffset)

    EasyMock.expect(fetcher.start())
    EasyMock.expect(fetcher.addPartitions(Map(tp -> initialFetchState)))
        .andReturn(Set(tp))
    EasyMock.expect(fetcher.isThreadFailed).andReturn(true)
    EasyMock.replay(fetcher)

    fetcherManager.addFetcherForPartitions(Map(tp -> initialFetchState))

    assertEquals(1, fetcherManager.deadThreadCount)
    EasyMock.verify(fetcher)

    EasyMock.reset(fetcher)
    EasyMock.expect(fetcher.isThreadFailed).andReturn(false)
    EasyMock.replay(fetcher)

    assertEquals(0, fetcherManager.deadThreadCount)
    EasyMock.verify(fetcher)
  }
}


text:
typedef enum {
    chapter,//章节
    answer,//题目
    speciality//专项
}DataType;

@interface DataManager : NSObject
+(NSArray *)getData:(DataType)type;
@end


text:
using System;

using Kyru;
using Kyru.Network;

using MbUnit.Framework;

namespace Tests
{
	internal sealed class KademliaNearestTest
	{
		private Node node;
		private Kademlia kademlia;

		[SetUp]
		internal void PrepareKademlia()
		{
			node = new Node(null);
			kademlia = node.Kademlia;
		}

		[TearDown]
		internal void TearDown()
		{
			node.Dispose();
		}

		[Test]
		internal void TestNearest([Column(0, 1, 20, 100)] int contacts)
		{
			TestHelper.PrepareFakeContacts(kademlia, contacts);

			var result = kademlia.NearestContactsTo(KademliaId.RandomId, null);
			Assert.AreEqual(Math.Min(contacts, 20), result.Count);
		}
	}
}


text:
Introducción a AngularJS
===============

### Introducción
- Que es
- Para que sirve: SPAs, aplicaciones +/- complejas
- Beneficios: Estructuración de código, separación de responsabilidades, muy fácil de testear, no tiene dependencias pero otras librerías son fácilmente integrables.

- Desventajas: Peso, curva de aprendizaje, juegos.

- Data binding [users:filtro+labels]
- Programación declarativa (templates) e imperativa (controllers, services, etc) [users:labels]
- Inyección de dependencias [users:Users]

### MVC
- Controllers y $scope [users]
- Factories/Services [users]
- Templates [users]
- Directives [users:table ng-repeat, ng-click, ng-include]
    - Extendiendo HTML [users:pagination]
- Router [spa]
- Donde va cada cosa [users]

### Bootstrapping / Tipos de App
- 1 app por página [users]
- SPAs [spa]

### Ajax, $http, REST y $resource [users]

### Performance [users]

### Unit testing, Karma y Jasmine [users]

### angular-seed, yeoman y ngbp


text:
using System;
using ZyGames.Framework.Model;
using ZyGames.Framework.Net.Redis;
using ZyGames.Framework.Net.Sql;
using ZyGames.Framework.Redis;

namespace ZyGames.Framework.Net
{
    /// <summary>
    /// 数据同步管理类
    /// </summary>
    public static class DataSyncManager
    {
        #region SQL
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public static IDataSender GetDataSender()
        {
            return new SqlDataSender();
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="schema"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public static IDataReceiver GetDataGetter(SchemaTable schema, DbDataFilter filter)
        {
            return GetDataGetter(schema, filter.Capacity, filter);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="schema"></param>
        /// <param name="capacity"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public static IDataReceiver GetDataGetter(SchemaTable schema, int capacity, DbDataFilter filter)
        {
            return new SqlDataReceiver(schema, capacity, filter);
        }
        #endregion

        #region Redis

        /// <summary>
        ///
        /// </summary>
        /// <param name="redisKey"></param>
        /// <returns></returns>
        public static IDataSender GetRedisSender(string redisKey)
        {
            return new RedisDataSender();
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="schema"></param>
        /// <param name="redisKey"></param>
        /// <returns></returns>
        public static IDataReceiver GetRedisGetter(SchemaTable schema, string redisKey)
        {
            return new RedisDataGetter(redisKey);
        }
        #endregion
    }

}


text:
from django.test import TestCase
from django.contrib.auth.models import User
from django.db import IntegrityError

from topo import graph
from topo.models import Topic, Concept

from .models import Quiz, QuizAttempt
from .diagnose import get_serialized_quizzes_by_topic

from uber.tests import UberTest
from uber.tests import UserClient

import simplejson

def json_decode(x):
    return simplejson.loads(x)

class QuizByTopicTest(UberTest):

    def test_get_quizzes_by_topic(self):
        t = Topic.objects.get(id=1)
        concept_count = t.concept_set.all().count()
        quizzes = get_serialized_quizzes_by_topic(t)
        quizzes = json_decode(quizzes)

        self.assertEqual(concept_count, len(quizzes))

        top_sorted_concepts = t.get_top_sorted_concepts()
        self.assertEqual(concept_count , len(top_sorted_concepts))

class QuizAttemptCreationTest(UberTest):

    def test_user_create(self):
        quiz = Quiz.objects.get(id=1)
        user = User.objects.create(username="one", password="one")

        x = QuizAttempt.objects.create_quiz_attempt(quiz=quiz, user=user, result=False, guess="what")
        self.assertEqual(x.attempt_number, 1)
        y = QuizAttempt.objects.create_quiz_attempt(quiz=quiz, user=user, result=False, guess="yep")
        self.assertEqual(y.attempt_number, 2)

        duplicate = False
        try:
            z = QuizAttempt.objects.create_quiz_attempt(quiz=quiz, user=user, result=False, guess="what")
        except IntegrityError:
            duplicate = True

        self.assertEqual(duplicate, True)

        def test_anon_create(self):
            quiz = Quiz.objects.get(id=1)
            user_key = "34ssdfafdadfe"

            x = QuizAttempt.objects.create_quiz_attempt(quiz=quiz, user_key=user_key, result=False, guess="what")
            self.assertEqual(x.attempt_number, 1)
            y = QuizAttempt.objects.create_quiz_attempt(quiz=quiz, user_key=user_key, result=True, guess="yep")
            self.assertEqual(y.attempt_number, 2)

            duplicate = False
            try:
                z = QuizAttempt.objects.create_quiz_attempt(quiz=quiz, user_key=user_key, result=True, guess="yep")
            except IntegrityError:
                duplicate = True

            self.assertEqual(duplicate, True)

from . import stats

class QuizStatsTest(UberTest):

    def test_quiz_and_concept_count_with_one_quiz(self):
        quiz = Quiz.objects.get(id=1)
        user = User.objects.create(username="one", password="one")
        anon_user_key = "asdf"

        x = QuizAttempt.objects.create_quiz_attempt(quiz=quiz, user=user, result=True, guess="what")
        self.assertEqual(x.attempt_number, 1)
        y = QuizAttempt.objects.create_quiz_attempt(quiz=quiz, user_key=anon_user_key, result=False, guess="yep")
        self.assertEqual(y.attempt_number, 1)

        #import ipdb;ipdb.set_trace()
        named_counts = stats.get_quiz_counts(quiz)
        self.assertEqual(named_counts.correct, 1)
        self.assertEqual(named_counts.wrong, 1)

        #concept =
        quiz = Quiz.objects.get(id=2)

        x = QuizAttempt.objects.create_quiz_attempt(quiz=quiz, user=user, result=True, guess="what")
        self.assertEqual(x.attempt_number, 1)
        y = QuizAttempt.objects.create_quiz_attempt(quiz=quiz, user_key=anon_user_key, result=False, guess="yep")
        self.assertEqual(y.attempt_number, 1)
        quiz = Quiz.objects.get(id=2)

        named_counts = stats.get_quiz_counts(quiz)
        self.assertEqual(named_counts.correct, 1)
        self.assertEqual(named_counts.wrong, 1)
        #import ipdb;ipdb.set_trace()
        named_counts = stats.get_concept_counts(quiz.concept)

        self.assertEqual(named_counts.correct, 1)
        self.assertEqual(named_counts.wrong, 1)

class QuizConceptStatsTest(UberTest):

    def test_concept_count_with_multiple_quizzes(self):
        concept = Concept.objects.get(topic_id=1, name="strings")
        quizzes = concept.quiz_set.all()

        user = User.objects.create(username="one", password="one")
        anon_user_key = "asdf"

        for index, quiz in enumerate(quizzes):
            result_user = index % 2 == 0
            result_anon = not result_user

            x = QuizAttempt.objects.create_quiz_attempt(quiz=quiz,
                user=user, result=result_user, guess="what")
            self.assertEqual(x.attempt_number, 1)
            y = QuizAttempt.objects.create_quiz_attempt(quiz=quiz,
                user_key=anon_user_key, result=result_anon, guess="yep")
            self.assertEqual(y.attempt_number, 1)

        quiz_count = quizzes.count()

        named_counts = stats.get_concept_counts(concept)
        self.assertEqual(named_counts.correct, quiz_count)
        self.assertEqual(named_counts.wrong, quiz_count)

from django.test import Client
import simplejson

class QuizUserAttemptIntegrationTest(UberTest):

    def test_user_attempt(self):
        print "Testing test_user_attempt"
        user = User.objects.create(username="one", password="two")
        c = UserClient()
        c.login_user(user)
        quiz = Quiz.objects.get(id=1)

        payload = {"result":False,"guess":"//","quizId":quiz.id,"created":"2014-03-03T16:49:32.415Z"}
        json_payload = simplejson.dumps(payload)
        response = c.post("/api/quiz/attempt/create/", json_payload, content_type="application/json")

        payload['guess'] = "correct_guess"
        payload['result'] = True
        json_payload = simplejson.dumps(payload)
        response = c.post("/api/quiz/attempt/create/", json_payload, content_type="application/json")

        attempts = QuizAttempt.objects.filter(user=user)
        #import ipdb;ipdb.set_trace()
        self.assertEqual(attempts.count(), 2)

        concept = quiz.concept
        named_counts = stats.get_concept_counts(concept)

        self.assertEqual(named_counts.correct, 1)
        self.assertEqual(named_counts.wrong, 1)

        named_quiz_counts = stats.get_quiz_counts(quiz)
        self.assertEqual(named_counts.correct, 1)
        self.assertEqual(named_counts.wrong, 1)

        response = c.post("/api/quiz/attempt/create/", json_payload, content_type="application/json")
        self.assertEqual(response.status_code, 400)

class QuizAnonAttemptIntegrationTest(UberTest):

    def test_anon_attempt(self):
        c = Client()
        quiz = Quiz.objects.get(id=1)

        payload = {"result":False,"guess":"//","quizId":quiz.id,"created":"2014-03-03T16:49:32.415Z"}
        json_payload = simplejson.dumps(payload)
        response = c.post("/api/quiz/attempt/create/", json_payload, content_type="application/json")
        self.assertEqual(response.status_code, 200)

        payload['guess'] = "correct_guess"
        payload['result'] = True
        json_payload = simplejson.dumps(payload)
        response = c.post("/api/quiz/attempt/create/", json_payload, content_type="application/json")
        self.assertEqual(response.status_code, 200)

        response = c.post("/api/quiz/attempt/create/", json_payload, content_type="application/json")
        self.assertEqual(response.status_code, 400)

        user_key = c.session.session_key
        assert(user_key)

        attempts = QuizAttempt.objects.filter(user_key=user_key)
        self.assertEqual(attempts.count(), 2)

        concept = quiz.concept
        named_counts = stats.get_concept_counts(concept)

        self.assertEqual(named_counts.correct, 1)
        self.assertEqual(named_counts.wrong, 1)

        named_quiz_counts = stats.get_quiz_counts(quiz)
        self.assertEqual(named_counts.correct, 1)
        self.assertEqual(named_counts.wrong, 1)


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/html; charset=utf-8" />

    <title>Inspecting the Model Results for ADFS07 — uvmcmcfit 0.1 documentation</title>

    <link rel="stylesheet" href="_static/default.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="top" title="uvmcmcfit 0.1 documentation" href="index.html" />
    <link rel="up" title="ADFS07: A Single, Strongly Lensed Galaxy" href="adfs07.html" />
    <link rel="next" title="Accessing the Data Directly" href="adfs07-access.html" />
    <link rel="prev" title="Running uvmcmcfit" href="usage.html" />

Navigation

          index

          next |

          previous |

uvmcmcfit 0.1 documentation »

Examples »

ADFS07: A Single, Strongly Lensed Galaxy »

Inspecting the Model Results for ADFS07¶

It is essential to inspect the results of the model fitting process to ensure
the best-fit model and the associated parameter uncertainties are robust and
acceptable.  <tt class="docutils literal">uvmcmcfit</tt> provides a suite of visualization routines that will
assist you in this task.

Accessing the Data Directly

Testing Convergence

Plot the Best-fit Model

Some Preliminaries

The Simplest Best-fit Plot

Comparison to Alternative Imaging

Additional Options

Plot Several Acceptable Model Fits

Plot the Posterior PDFs

Plot the Covariance Matrix

Previous topic

Running <tt class="docutils literal">uvmcmcfit</tt>

Next topic

Accessing the Data Directly

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          next |

          previous |

uvmcmcfit 0.1 documentation »

Examples »

ADFS07: A Single, Strongly Lensed Galaxy »

        © Copyright 2014, Shane Bussmann.
      Created using Sphinx 1.2.2.


text:
<?php

namespace Mauchede\RancherApi\Collection;

use Mauchede\RancherApi\Client\ClientAwareInterface;
use Mauchede\RancherApi\Exception\ColumnNotFoundException;
use Mauchede\RancherApi\Exception\InvalidActionException;
use Mauchede\RancherApi\Resource\ResourceInterface;
use Rancher\Exception\ResourceNotFoundException;

/**
 * Interface CollectionInterface is implemented by all Rancher API collection classes.
 *
 * @author Morgan Auchede <morgan.auchede@gmail.com>
 */
interface CollectionInterface extends ClientAwareInterface
{
    /**
     * Gets all resources.
     *
     * @return ResourceInterface[]
     */
    public function all();

    /**
     * Gets a specified resource.
     *
     * @param string $id
     *
     * @return ResourceInterface
     *
     * @throws ResourceNotFoundException if the resource does not exist.
     */
    public function get($id);

    /**
     * Gets the URI.
     *
     * @return string
     *
     * @throws InvalidActionException if the collection does not have URI.
     */
    public function getUri();

    /**
     * Reloads the information.
     *
     * @return $this
     *
     * @throws InvalidActionException if the collection does not have URI.
     */
    public function reload();

    /**
     * Sorts the resource by a column.
     *
     * @param string $column
     *
     * @return $this
     *
     * @throws ColumnNotFoundException if the column does not exist.
     */
    public function sortBy($column);
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace Wodsoft.ComBoost.Website
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute("Home", "", new { controller = "Home", action = "Init" });

            routes.MapRoute("License", "license", new { controller = "Home", action = "License" });

            routes.MapRoute(
                name: "Default",
                url: "{lang}/{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}


text:
importScripts('/sw-toolbox/sw-toolbox.js');

const config = {
  offlinePage: '/youre_offline/'
};

const IGNORED_URLS = [
  /.*\/shopping_cart$/,
  /.*\/favorite$/,
  /.*\/favorite-with-count$/,
  /.*\/slow-json-with-items$/
];

config.filesToCache = [
  '/',
  '/components/amp-img/',
  '/components/amp-install-serviceworker/',
  config.offlinePage,
  '/img/offline.png',
  '/playground/',
  '/img/amp_by_example_logo.svg',
  '/playground/images/logo.svg',
  '/img/amp_logo_black.svg'
];

/**
 * Generates a placeholder SVG image of the given size.
 */
function offlineImage(name, width, height) {
  return
    `<?xml version="1.0"?>
<svg width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" xmlns="http://www.w3.org/2000/svg" version="1.1">
  <g fill="none" fill-rule="evenodd"><path fill="#F8BBD0" d="M0 0h${width}v${height}H0z"/></g>
  <text text-anchor="middle" x="${Math.floor(width / 2)}" y="${Math.floor(height / 2)}">image offline (${name})</text>
<style><![CDATA[
text{
  font: 48px Roboto,Verdana, Helvetica, Arial, sans-serif;
}
]]></style>
</svg>`;
}
/**
 * Returns true if the Accept header contains the given content type string.
 */
function requestAccepts(request, contentType) {
  return request.headers.get('Accept').indexOf(contentType) != -1;
}

/**
 * ampbyexample.com fetch handler:
 *
 * - one-behind caching
 * - shows offline page
 * - generates placeholder image for unavailable images
 */
function ampByExampleHandler(request, values) {
  if (shouldNotCache(request)) {
    return toolbox.networkOnly(request, values);
  }
  // for samples show offline page if offline and samples are not cached
  if (requestAccepts(request, 'text/html')) {
    // never use cached version for AMP CORS requests (e.g. amp-live-list) or pages that shouldn't be cached
    if (request.url.indexOf("__amp_source_origin") != -1) {
      return toolbox.networkOnly(request, values);
    }
    // network first, we always want to get the latest
    return toolbox.networkFirst(request, values).catch(function() {
      return toolbox.cacheOnly(new Request(config.offlinePage), values)
        .then(function(response) {
          return response || new Response('You\'re offline. Sorry.', {
            status: 500,
            statusText: 'Offline Page Missing'
          });
        });
    });
  }
  // always try to load images from the cache first
  // fallback to placeholder SVG image if offline and image not available
  if (requestAccepts(request, 'image/')) {
    return toolbox.cacheFirst(request, values).catch(function() {
      const url = request.url;
      const fileName = url.substring(url.lastIndexOf('/') + 1);
      // TODO use correct image dimensions
      return new Response(offlineImage(fileName, 1080, 610), {
        headers: {
          'Content-Type': 'image/svg+xml'
        }
      });
    });
  } else {
    // cache first for all other requests
    return toolbox.cacheFirst(request, values);
  }
}

function shouldNotCache(request) {
  const path = new URL(request.url).pathname;
  return IGNORED_URLS.some(url => {
    //console.log('ignore? ' + path + ' ' + url + ' -> ' + url.test(path));
    return url.test(path);
  });
}

toolbox.options.debug = false;
toolbox.router.default = toolbox.networkFirst;
toolbox.router.get('/(.*)', ampByExampleHandler, {
  origin: self.location.origin
});
// network first amp runtime
toolbox.router.get('/(.*)', toolbox.networkFirst, {
  origin: 'https://cdn.ampproject.org'
});

toolbox.precache(config.filesToCache);

// Cache the page registering the service worker. Without this, the
// "first" page the user visits is only cached on the second visit,
// since the first load is uncontrolled.
toolbox.precache(
  clients.matchAll({
    includeUncontrolled: true
  }).then(l => {
    return l.map(c => c.url);
  })
);

// Claim clients so that the very first page load is controlled by a service
// worker. (Important for responding correctly in offline state.)
self.addEventListener('activate', () => self.clients.claim());

// Make sure the SW the page we register() is the service we use.
self.addEventListener('install', () => self.skipWaiting());


text:
package org.elasticsearch.painless;

import org.elasticsearch.bootstrap.BootstrapInfo;
import org.elasticsearch.painless.Variables.Reserved;
import org.elasticsearch.painless.antlr.Walker;
import org.elasticsearch.painless.node.SSource;

import java.net.MalformedURLException;
import java.net.URL;
import java.security.CodeSource;
import java.security.SecureClassLoader;
import java.security.cert.Certificate;
import java.util.BitSet;

import static org.elasticsearch.painless.WriterConstants.CLASS_NAME;

/**
 * The Compiler is the entry point for generating a Painless script.  The compiler will receive a Painless
 * tree based on the type of input passed in (currently only ANTLR).  Two passes will then be run over the tree,
 * one for analysis using the {@link Analyzer} and another to generate the actual byte code using ASM in
 * the {@link Writer}.
 */
final class Compiler {

    /**
     * The maximum number of characters allowed in the script source.
     */
    static int MAXIMUM_SOURCE_LENGTH = 16384;

    /**
     * Define the class with lowest privileges.
     */
    private static final CodeSource CODESOURCE;

    /**
     * Setup the code privileges.
     */
    static {
        try {
            // Setup the code privileges.
            CODESOURCE = new CodeSource(new URL("file:" + BootstrapInfo.UNTRUSTED_CODEBASE), (Certificate[]) null);
        } catch (MalformedURLException impossible) {
            throw new RuntimeException(impossible);
        }
    }

    /**
     * A secure class loader used to define Painless scripts.
     */
    static final class Loader extends SecureClassLoader {
        /**
         * @param parent The parent ClassLoader.
         */
        Loader(ClassLoader parent) {
            super(parent);
        }

        /**
         * Generates a Class object from the generated byte code.
         * @param name The name of the class.
         * @param bytes The generated byte code.
         * @return A Class object extending {@link Executable}.
         */
        Class<? extends Executable> define(String name, byte[] bytes) {
            return defineClass(name, bytes, 0, bytes.length, CODESOURCE).asSubclass(Executable.class);
        }
    }

    /**
     * Runs the two-pass compiler to generate a Painless script.
     * @param loader The ClassLoader used to define the script.
     * @param name The name of the script.
     * @param source The source code for the script.
     * @param settings The CompilerSettings to be used during the compilation.
     * @return An {@link Executable} Painless script.
     */
    static Executable compile(Loader loader, String name, String source, CompilerSettings settings) {
        if (source.length() > MAXIMUM_SOURCE_LENGTH) {
            throw new IllegalArgumentException("Scripts may be no longer than " + MAXIMUM_SOURCE_LENGTH +
                " characters.  The passed in script is " + source.length() + " characters.  Consider using a" +
                " plugin if a script longer than this length is a requirement.");
        }

        Reserved reserved = new Reserved();
        SSource root = Walker.buildPainlessTree(name, source, reserved, settings);
        Variables variables = Analyzer.analyze(reserved, root);
        BitSet expressions = new BitSet(source.length());
        byte[] bytes = Writer.write(settings, name, source, variables, root, expressions);

        try {
            Class<? extends Executable> clazz = loader.define(CLASS_NAME, bytes);
            java.lang.reflect.Constructor<? extends Executable> constructor =
                    clazz.getConstructor(String.class, String.class, BitSet.class);

            return constructor.newInstance(name, source, expressions);
        } catch (Exception exception) { // Catch everything to let the user know this is something caused internally.
            throw new IllegalStateException("An internal error occurred attempting to define the script [" + name + "].", exception);
        }
    }

    /**
     * Runs the two-pass compiler to generate a Painless script.  (Used by the debugger.)
     * @param source The source code for the script.
     * @param settings The CompilerSettings to be used during the compilation.
     * @return The bytes for compilation.
     */
    static byte[] compile(String name, String source, CompilerSettings settings) {
        if (source.length() > MAXIMUM_SOURCE_LENGTH) {
            throw new IllegalArgumentException("Scripts may be no longer than " + MAXIMUM_SOURCE_LENGTH +
                " characters.  The passed in script is " + source.length() + " characters.  Consider using a" +
                " plugin if a script longer than this length is a requirement.");
        }

        Reserved reserved = new Reserved();
        SSource root = Walker.buildPainlessTree(name, source, reserved, settings);
        Variables variables = Analyzer.analyze(reserved, root);

        return Writer.write(settings, name, source, variables, root, new BitSet(source.length()));
    }

    /**
     * All methods in the compiler should be static.
     */
    private Compiler() {}
}


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

namespace Affecto.IdentityManagement.Store.Model
{
    public class Permission
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }

        public virtual List<Role> Roles { get; set; }

        public Permission()
        {
            Roles = new List<Role>();
        }
    }
}