text:
/***********************************************************************
    created:    Sun Jan 11 2009
    author:     Paul D Turner
*************************************************************************/
/***************************************************************************
     Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team

     Permission is hereby granted, free of charge, to any person obtaining
     a copy of this software and associated documentation files (the
     "Software"), to deal in the Software without restriction, including
     without limitation the rights to use, copy, modify, merge, publish,
     distribute, sublicense, and/or sell copies of the Software, and to
     permit persons to whom the Software is furnished to do so, subject to
     the following conditions:

     The above copyright notice and this permission notice shall be
     included in all copies or substantial portions of the Software.

     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
     EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
     MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
     IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
     OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
     ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
     OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUI/RendererModules/OpenGL/GLTexture.h"
#include "CEGUI/Exceptions.h"
#include "CEGUI/System.h"
#include "CEGUI/ImageCodec.h"

#include "CEGUI/RendererModules/OpenGL/GL.h"

#include <cmath>

// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
OpenGL1Texture::OpenGL1Texture(OpenGLRendererBase& owner, const String& name)
    : OpenGLTexture(owner, name)
{
}

//----------------------------------------------------------------------------//
void OpenGL1Texture::initInternalPixelFormatFields(const PixelFormat fmt)
{
    d_isCompressed = false;

    switch(fmt)
    {
    case PF_RGBA:
        d_format = GL_RGBA;
        d_subpixelFormat = GL_UNSIGNED_BYTE;
        break;

    case PF_RGB:
        d_format = GL_RGB;
        d_subpixelFormat = GL_UNSIGNED_BYTE;
        break;

    case PF_RGB_565:
        d_format = GL_RGB;
        d_subpixelFormat = GL_UNSIGNED_SHORT_5_6_5;
        break;

    case PF_RGBA_4444:
        d_format = GL_RGBA;
        d_subpixelFormat = GL_UNSIGNED_SHORT_4_4_4_4;
        break;

    case PF_RGB_DXT1:
        d_format = GL_COMPRESSED_RGB_S3TC_DXT1_EXT;
        d_subpixelFormat = GL_UNSIGNED_BYTE; // not used.
        d_isCompressed = true;
        break;

    case PF_RGBA_DXT1:
        d_format = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
        d_subpixelFormat = GL_UNSIGNED_BYTE; // not used.
        d_isCompressed = true;
        break;

    case PF_RGBA_DXT3:
        d_format = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
        d_subpixelFormat = GL_UNSIGNED_BYTE; // not used.
        d_isCompressed = true;
        break;

    case PF_RGBA_DXT5:
        d_format = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
        d_subpixelFormat = GL_UNSIGNED_BYTE; // not used.
        d_isCompressed = true;
        break;

    default:
        throw RendererException(
                        "invalid or unsupported CEGUI::PixelFormat.");
    }
}

//----------------------------------------------------------------------------//
OpenGL1Texture::~OpenGL1Texture()
{
}

//----------------------------------------------------------------------------//
GLsizei OpenGL1Texture::getCompressedTextureSize(const Sizef& pixel_size) const
{
    GLsizei blocksize = 16;

    if(d_format == GL_COMPRESSED_RGB_S3TC_DXT1_EXT ||
            d_format == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT)
    {
        blocksize = 8;
    }

    return (
               static_cast<GLsizei>(
                   std::ceil(pixel_size.d_width / 4) *
                   std::ceil(pixel_size.d_height / 4) *
                   blocksize));
}

//----------------------------------------------------------------------------//
void OpenGL1Texture::setTextureSize_impl(const Sizef& sz)
{
    const Sizef size(d_owner.getAdjustedTextureSize(sz));
    d_size = size;

    // make sure size is within boundaries
    GLfloat maxSize;
    glGetFloatv(GL_MAX_TEXTURE_SIZE, &maxSize);

    if((size.d_width > maxSize) || (size.d_height > maxSize))
        throw RendererException("size too big");

    // save old texture binding
    GLuint old_tex;
    glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast<GLint*>(&old_tex));

    // set texture to required size
    glBindTexture(GL_TEXTURE_2D, d_ogltexture);

    if(d_isCompressed)
    {
        const GLsizei image_size = getCompressedTextureSize(size);
        glCompressedTexImage2D(GL_TEXTURE_2D, 0, d_format,
                               static_cast<GLsizei>(size.d_width),
                               static_cast<GLsizei>(size.d_height),
                               0, image_size, 0);
    }
    else
    {
        glTexImage2D(GL_TEXTURE_2D, 0, d_format,
                     static_cast<GLsizei>(size.d_width),
                     static_cast<GLsizei>(size.d_height),
                     0, d_format, d_subpixelFormat, 0);
    }

    // restore previous texture binding.
    glBindTexture(GL_TEXTURE_2D, old_tex);
}

//----------------------------------------------------------------------------//
void OpenGL1Texture::blitToMemory(void* targetData)
{
    if (OpenGLInfo::getSingleton().isUsingOpenglEs())
    {
        /* OpenGL ES 3.1 or below doesn't support
        "glGetTexImage"/"glGetCompressedTexImage", so we need to emulate it
        using "glReadPixels". */

        GLint old_pack;
        glGetIntegerv(GL_PACK_ALIGNMENT, &old_pack);
        GLuint texture_framebuffer(0);
        GLint framebuffer_old(0), pack_alignment_old(0);
        glGenFramebuffers(1, &texture_framebuffer);
        GLenum framebuffer_target(0), framebuffer_param(0);
        if (OpenGLInfo::getSingleton()
            .isSeperateReadAndDrawFramebufferSupported())
        {
            framebuffer_param = GL_READ_FRAMEBUFFER_BINDING;
            framebuffer_target = GL_READ_FRAMEBUFFER;
        }
        else
        {
            framebuffer_param = GL_FRAMEBUFFER_BINDING;
            framebuffer_target = GL_FRAMEBUFFER;
        }
        glGetIntegerv(framebuffer_param, &framebuffer_old);
        glBindFramebuffer(framebuffer_target, texture_framebuffer);
        glFramebufferTexture2D(framebuffer_target, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, d_ogltexture, 0);
        GLint read_buffer_old(0), pixel_pack_buffer_old(0);
        if (OpenGLInfo::getSingleton().isReadBufferSupported())
        {
            glGetIntegerv(GL_READ_BUFFER, &read_buffer_old);
            glReadBuffer(GL_COLOR_ATTACHMENT0);
            glGetIntegerv(GL_PIXEL_PACK_BUFFER_BINDING, &pixel_pack_buffer_old);
            glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
        }
        glGetIntegerv(GL_PACK_ALIGNMENT, &pack_alignment_old);
        glPixelStorei(GL_PACK_ALIGNMENT, 1);
        glReadPixels(0, 0, static_cast<GLsizei>(d_dataSize.d_width),
            static_cast<GLsizei>(d_dataSize.d_height), GL_RGBA, GL_UNSIGNED_BYTE, targetData);
        glPixelStorei(GL_PACK_ALIGNMENT, pack_alignment_old);
        if (OpenGLInfo::getSingleton().isReadBufferSupported())
        {
            glBindBuffer(GL_PIXEL_PACK_BUFFER, pixel_pack_buffer_old);
            glReadBuffer(read_buffer_old);
        }
        glBindFramebuffer(framebuffer_target, framebuffer_old);
        glDeleteFramebuffers(1, &texture_framebuffer);

    }
    else // Desktop OpenGL
    {
        // save existing config
        GLuint old_tex;
        glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast<GLint*>(&old_tex));

        glBindTexture(GL_TEXTURE_2D, d_ogltexture);

        if (d_isCompressed)
        {
            glGetCompressedTexImage(GL_TEXTURE_2D, 0, targetData);
        }
        else
        {
            GLint old_pack;
            glGetIntegerv(GL_PACK_ALIGNMENT, &old_pack);

            glPixelStorei(GL_PACK_ALIGNMENT, 1);
            glGetTexImage(GL_TEXTURE_2D, 0, d_format, d_subpixelFormat, targetData);

            glPixelStorei(GL_PACK_ALIGNMENT, old_pack);
        }

        // restore previous config.
        glBindTexture(GL_TEXTURE_2D, old_tex);
    }
}

//----------------------------------------------------------------------------//
void OpenGL1Texture::setTextureEnvironment()
{
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
}
//----------------------------------------------------------------------------//

} // End of  CEGUI namespace section


text:
/**
 * Config block augmenting Guacamole's existing URL routing, automatically
 * redirecting requests for the legacy "/client/[TYPE]/[CONNECTION IDENTIFIER]"
 * to "/client/[CLIENT IDENTIFIER]".
 */
angular.module('legacyUrl').config(['$routeProvider',
        function legacyUrlRouteConfig($routeProvider) {

    /**
     * Re-authenticates with the Guacamole server and, if successful, redirects
     * for the legacy "/client/[TYPE]/[CONNECTION IDENTIFIER]" to the proper
     * "/client/[CLIENT IDENTIFIER]" URL. The client identifier is derived
     * assuming that the associated data source is the default data source
     * (the data source which authenticated the user).
     *
     * @param {Service} $injector
     *     The Angular $injector service.
     *
     * @returns {Promise}
     *     A promise which is rejected once the correct URL has been determined
     *     and the user has been redirected, or once authentication has failed.
     */
    var redirectToClient = ['$injector', function redirectToClient($injector) {

        // Required types
        var ClientIdentifier = $injector.get('ClientIdentifier');

        // Required services
        var $location             = $injector.get('$location');
        var $q                    = $injector.get('$q');
        var $route                = $injector.get('$route');
        var authenticationService = $injector.get('authenticationService');

        // Promise for routing attempt
        var route = $q.defer();

        // Re-authenticate including any parameters in URL
        authenticationService.updateCurrentToken($location.search())
        .then(function reauthenticationSucceeded() {

            // Derive client identifier directly from connection identifier
            var clientIdentifier = ClientIdentifier.toString({
                dataSource : authenticationService.getDataSource(),
                type       : $route.current.params.type,
                id         : $route.current.params.id
            });

            // Redirect to proper client URL
            $location.url('/client/' + encodeURIComponent(clientIdentifier));
            route.reject();

        })

        // Simply ignore if authentication fails
        ['catch'](function reauthenticationFailed() {
            route.reject();
        });

        // Return promise that will be rejected once either (1) the correct
        // client URL has been determined or (2) the correct client URL cannot
        // be determined because authentication has failed
        return route.promise;

    }];

    // Redirect /client/TYPE/IDENTIFIER to /client/...
    $routeProvider.when('/client/:type/:id/:params?', {
        resolve       : { redirectToClient : redirectToClient }
    });

}]);

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2022 Google LLC
//
// 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.

/**
 * RuleBasedFirstPartyAudienceSegment.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
 */

package com.google.api.ads.admanager.axis.v202202;

/**
 * A {@link RuleBasedFirstPartyAudienceSegment} is a {@link FirstPartyAudienceSegment}
 * owned by the
 *             publisher network. It contains a rule.
 */
public class RuleBasedFirstPartyAudienceSegment  extends com.google.api.ads.admanager.axis.v202202.RuleBasedFirstPartyAudienceSegmentSummary  implements java.io.Serializable {
    /* Specifies the rule of the segment which determines user's eligibility
     * criteria to be part of
     *                     the segment. This attribute is required. */
    private com.google.api.ads.admanager.axis.v202202.FirstPartyAudienceSegmentRule rule;

    public RuleBasedFirstPartyAudienceSegment() {
    }

    public RuleBasedFirstPartyAudienceSegment(
           java.lang.Long id,
           java.lang.String name,
           long[] categoryIds,
           java.lang.String description,
           com.google.api.ads.admanager.axis.v202202.AudienceSegmentStatus status,
           java.lang.Long size,
           java.lang.Long mobileWebSize,
           java.lang.Long idfaSize,
           java.lang.Long adIdSize,
           java.lang.Long ppidSize,
           com.google.api.ads.admanager.axis.v202202.AudienceSegmentDataProvider dataProvider,
           com.google.api.ads.admanager.axis.v202202.AudienceSegmentType type,
           java.lang.Integer pageViews,
           java.lang.Integer recencyDays,
           java.lang.Integer membershipExpirationDays,
           com.google.api.ads.admanager.axis.v202202.FirstPartyAudienceSegmentRule rule) {
        super(
            id,
            name,
            categoryIds,
            description,
            status,
            size,
            mobileWebSize,
            idfaSize,
            adIdSize,
            ppidSize,
            dataProvider,
            type,
            pageViews,
            recencyDays,
            membershipExpirationDays);
        this.rule = rule;
    }

    @Override
    public String toString() {
        return com.google.common.base.MoreObjects.toStringHelper(this.getClass())
            .omitNullValues()
            .add("adIdSize", getAdIdSize())
            .add("categoryIds", getCategoryIds())
            .add("dataProvider", getDataProvider())
            .add("description", getDescription())
            .add("id", getId())
            .add("idfaSize", getIdfaSize())
            .add("membershipExpirationDays", getMembershipExpirationDays())
            .add("mobileWebSize", getMobileWebSize())
            .add("name", getName())
            .add("pageViews", getPageViews())
            .add("ppidSize", getPpidSize())
            .add("recencyDays", getRecencyDays())
            .add("rule", getRule())
            .add("size", getSize())
            .add("status", getStatus())
            .add("type", getType())
            .toString();
    }

    /**
     * Gets the rule value for this RuleBasedFirstPartyAudienceSegment.
     *
     * @return rule   * Specifies the rule of the segment which determines user's eligibility
     * criteria to be part of
     *                     the segment. This attribute is required.
     */
    public com.google.api.ads.admanager.axis.v202202.FirstPartyAudienceSegmentRule getRule() {
        return rule;
    }

    /**
     * Sets the rule value for this RuleBasedFirstPartyAudienceSegment.
     *
     * @param rule   * Specifies the rule of the segment which determines user's eligibility
     * criteria to be part of
     *                     the segment. This attribute is required.
     */
    public void setRule(com.google.api.ads.admanager.axis.v202202.FirstPartyAudienceSegmentRule rule) {
        this.rule = rule;
    }

    private java.lang.Object __equalsCalc = null;
    public synchronized boolean equals(java.lang.Object obj) {
        if (!(obj instanceof RuleBasedFirstPartyAudienceSegment)) return false;
        RuleBasedFirstPartyAudienceSegment other = (RuleBasedFirstPartyAudienceSegment) obj;
        if (obj == null) return false;
        if (this == obj) return true;
        if (__equalsCalc != null) {
            return (__equalsCalc == obj);
        }
        __equalsCalc = obj;
        boolean _equals;
        _equals = super.equals(obj) &&
            ((this.rule==null && other.getRule()==null) ||
             (this.rule!=null &&
              this.rule.equals(other.getRule())));
        __equalsCalc = null;
        return _equals;
    }

    private boolean __hashCodeCalc = false;
    public synchronized int hashCode() {
        if (__hashCodeCalc) {
            return 0;
        }
        __hashCodeCalc = true;
        int _hashCode = super.hashCode();
        if (getRule() != null) {
            _hashCode += getRule().hashCode();
        }
        __hashCodeCalc = false;
        return _hashCode;
    }

    // Type metadata
    private static org.apache.axis.description.TypeDesc typeDesc =
        new org.apache.axis.description.TypeDesc(RuleBasedFirstPartyAudienceSegment.class, true);

    static {
        typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202202", "RuleBasedFirstPartyAudienceSegment"));
        org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("rule");
        elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202202", "rule"));
        elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202202", "FirstPartyAudienceSegmentRule"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
    }

    /**
     * Return type metadata object
     */
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
        return typeDesc;
    }

    /**
     * Get Custom Serializer
     */
    public static org.apache.axis.encoding.Serializer getSerializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanSerializer(
            _javaType, _xmlType, typeDesc);
    }

    /**
     * Get Custom Deserializer
     */
    public static org.apache.axis.encoding.Deserializer getDeserializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanDeserializer(
            _javaType, _xmlType, typeDesc);
    }

}


text:
tags: greece memory
layout: post
title: "First thing to go"
---

During my walk to work I was mentally going through the places we visited in Greece last year (photos coming soon, honest) and for some reason I couldn't remember the place where this gate is. I could remember the treasury building nearby and this theater about a half-hour away, but not the famous place itself. What's good at getting rid of that kind of block?


text:
package executor

import (
	"bufio"
	"io"
	"log"
)

// bindLoggingPipe spawns a goroutine for passing through logging of the given output pipe.
func bindLoggingPipe(name string, pipe io.Reader, output io.Writer, logPrefix bool) {
	log.Printf("Started logging: %s from function.", name)

	scanner := bufio.NewScanner(pipe)
	logFlags := log.Flags()
	prefix := log.Prefix()
	if logPrefix == false {
		logFlags = 0
		prefix = "" // Unnecessary, but set explicitly for completeness.
	}

	logger := log.New(output, prefix, logFlags)

	go func() {
		for scanner.Scan() {
			if logPrefix {
				logger.Printf("%s: %s", name, scanner.Text())
			} else {
				logger.Printf(scanner.Text())
			}
		}
		if err := scanner.Err(); err != nil {
			log.Printf("Error scanning %s: %s", name, err.Error())
		}
	}()
}


text:
import { Group } from "../../../scene/group";
import { Line } from "../../../scene/shape/line";
import { Text } from "../../../scene/shape/text";
import { Selection } from "../../../scene/selection";
import { DropShadow } from "../../../scene/dropShadow";
import { LinearScale } from "../../../scale/linearScale";
import { Sector } from "../../../scene/shape/sector";
import { PolarTooltipRendererParams, SeriesNodeDatum, HighlightStyle, SeriesTooltip } from "./../series";
import { Label } from "../../label";
import { PointerEvents } from "../../../scene/node";
import { normalizeAngle180, toRadians } from "../../../util/angle";
import { Color } from "../../../util/color";
import { toFixed } from "../../../util/number";
import { LegendDatum } from "../../legend";
import { Caption } from "../../../caption";
import { reactive, Observable, TypedEvent } from "../../../util/observable";
import { PolarSeries } from "./polarSeries";
import { ChartAxisDirection } from "../../chartAxis";
import { TooltipRendererResult, toTooltipHtml } from "../../chart";

export interface PieSeriesNodeClickEvent extends TypedEvent {
    readonly type: 'nodeClick';
    readonly event: MouseEvent;
    readonly series: PieSeries;
    readonly datum: any;
    readonly angleKey: string;
    readonly labelKey?: string;
    readonly radiusKey?: string;
}

interface PieNodeDatum extends SeriesNodeDatum {
    readonly index: number;
    readonly radius: number; // in the [0, 1] range
    readonly startAngle: number;
    readonly endAngle: number;
    readonly midAngle: number;
    readonly midCos: number;
    readonly midSin: number;

    readonly label?: {
        readonly text: string;
        readonly textAlign: CanvasTextAlign;
        readonly textBaseline: CanvasTextBaseline;
    };
}

export interface PieTooltipRendererParams extends PolarTooltipRendererParams {
    readonly labelKey?: string;
    readonly labelName?: string;
}

interface PieHighlightStyle extends HighlightStyle {
    centerOffset?: number;
}

enum PieNodeTag {
    Sector,
    Callout,
    Label
}

export interface PieSeriesFormatterParams {
    readonly datum: any;
    readonly fill?: string;
    readonly stroke?: string;
    readonly strokeWidth: number;
    readonly highlighted: boolean;
    readonly angleKey: string;
    readonly radiusKey?: string;
}

export interface PieSeriesFormat {
    fill?: string;
    stroke?: string;
    strokeWidth?: number;
}

class PieSeriesLabel extends Label {
    @reactive('change') offset = 3; // from the callout line
    @reactive('dataChange') minAngle = 20; // in degrees
}

class PieSeriesCallout extends Observable {
    @reactive('change') colors: string[] = [];
    @reactive('change') length: number = 10;
    @reactive('change') strokeWidth: number = 1;
}

export class PieSeriesTooltip extends SeriesTooltip {
    @reactive('change') renderer?: (params: PieTooltipRendererParams) => string | TooltipRendererResult;
}

export class PieSeries extends PolarSeries {

    static className = 'PieSeries';
    static type = 'pie';

    private radiusScale: LinearScale = new LinearScale();
    private groupSelection: Selection<Group, Group, PieNodeDatum, any> = Selection.select(this.group).selectAll<Group>();

    /**
     * The processed data that gets visualized.
     */
    private groupSelectionData: PieNodeDatum[] = [];

    private angleScale: LinearScale = (() => {
        const scale = new LinearScale();
        // Each slice is a ratio of the whole, where all ratios add up to 1.
        scale.domain = [0, 1];
        // Add 90 deg to start the first pie at 12 o'clock.
        scale.range = [-Math.PI, Math.PI].map(angle => angle + Math.PI / 2);
        return scale;
    })();

    // When a user toggles a series item (e.g. from the legend), its boolean state is recorded here.
    public seriesItemEnabled: boolean[] = [];

    private _title?: Caption;
    set title(value: Caption | undefined) {
        const oldTitle = this._title;

        if (oldTitle !== value) {
            if (oldTitle) {
                oldTitle.removeEventListener('change', this.scheduleLayout);
                this.group.removeChild(oldTitle.node);
            }

            if (value) {
                value.node.textBaseline = 'bottom';
                value.addEventListener('change', this.scheduleLayout);
                this.group.appendChild(value.node);
            }

            this._title = value;
            this.scheduleLayout();
        }
    }
    get title(): Caption | undefined {
        return this._title;
    }

    readonly label = new PieSeriesLabel();
    readonly callout = new PieSeriesCallout();

    /**
     * @deprecated Use {@link tooltip.renderer} instead.
     */
    tooltipRenderer?: (params: PieTooltipRendererParams) => string | TooltipRendererResult;
    tooltip: PieSeriesTooltip = new PieSeriesTooltip();

    constructor() {
        super();

        this.addEventListener('update', this.update, this);
        this.label.addEventListener('change', this.scheduleLayout, this);
        this.label.addEventListener('dataChange', this.scheduleData, this);
        this.callout.addEventListener('change', this.scheduleLayout, this);
        this.callout.colors = this.strokes;

        this.addPropertyListener('data', event => {
            if (event.value) {
                event.source.seriesItemEnabled = event.value.map(() => true);
            }
        });
    }

    /**
     * The key of the numeric field to use to determine the angle (for example,
     * a pie slice angle).
     */
    @reactive('dataChange') angleKey = '';
    @reactive('update') angleName = '';

    /**
     * The key of the numeric field to use to determine the radii of pie slices.
     * The largest value will correspond to the full radius and smaller values to
     * proportionally smaller radii.
     */
    @reactive('dataChange') radiusKey?: string;
    @reactive('update') radiusName?: string;
    @reactive('dataChange') radiusMin?: number;
    @reactive('dataChange') radiusMax?: number;

    @reactive('dataChange') labelKey?: string;
    @reactive('update') labelName?: string;

    private _fills: string[] = [
        '#c16068',
        '#a2bf8a',
        '#ebcc87',
        '#80a0c3',
        '#b58dae',
        '#85c0d1'
    ];
    set fills(values: string[]) {
        this._fills = values;
        this.strokes = values.map(color => Color.fromString(color).darker().toHexString());
        this.scheduleData();
    }
    get fills(): string[] {
        return this._fills;
    }

    private _strokes: string[] = [
        '#874349',
        '#718661',
        '#a48f5f',
        '#5a7088',
        '#7f637a',
        '#5d8692'
    ];
    set strokes(values: string[]) {
        this._strokes = values;
        this.callout.colors = values;
        this.scheduleData();
    }
    get strokes(): string[] {
        return this._strokes;
    }

    @reactive('layoutChange') fillOpacity = 1;
    @reactive('layoutChange') strokeOpacity = 1;

    @reactive('update') lineDash?: number[] = undefined;
    @reactive('update') lineDashOffset: number = 0;

    @reactive('update') formatter?: (params: PieSeriesFormatterParams) => PieSeriesFormat;

    /**
     * The series rotation in degrees.
     */
    @reactive('dataChange') rotation = 0;

    @reactive('layoutChange') outerRadiusOffset = 0;

    @reactive('dataChange') innerRadiusOffset = 0;

    @reactive('layoutChange') strokeWidth = 1;

    @reactive('layoutChange') shadow?: DropShadow;

    highlightStyle: PieHighlightStyle = { fill: 'yellow' };

    onHighlightChange() {
        this.updateNodes();
    }

    setColors(fills: string[], strokes: string[]) {
        this.fills = fills;
        this.strokes = strokes;
        this.callout.colors = strokes;
    }

    getDomain(direction: ChartAxisDirection): any[] {
        if (direction === ChartAxisDirection.X) {
            return this.angleScale.domain;
        } else {
            return this.radiusScale.domain;
        }
    }

    processData(): boolean {
        const { angleKey, radiusKey, seriesItemEnabled, angleScale, groupSelectionData } = this;
        const data = angleKey && this.data ? this.data : [];

        const angleData: number[] = data.map((datum, index) => seriesItemEnabled[index] && Math.abs(+datum[angleKey]) || 0);
        const angleDataTotal = angleData.reduce((a, b) => a + b, 0);

        // The ratios (in [0, 1] interval) used to calculate the end angle value for every pie slice.
        // Each slice starts where the previous one ends, so we only keep the ratios for end angles.
        const angleDataRatios = (() => {
            let sum = 0;
            return angleData.map(datum => sum += datum / angleDataTotal);
        })();

        const labelKey = this.label.enabled && this.labelKey;
        const labelData = labelKey ? data.map(datum => String(datum[labelKey])) : [];
        let radiusData: number[] = [];

        if (radiusKey) {
            const { radiusMin, radiusMax } = this;
            const radii = data.map(datum => Math.abs(datum[radiusKey]));
            const min = radiusMin !== undefined ? radiusMin : Math.min(...radii);
            const max = radiusMax !== undefined ? radiusMax : Math.max(...radii);
            const delta = max - min;

            radiusData = radii.map(value => delta ? (value - min) / delta : 1);
        }

        groupSelectionData.length = 0;

        const rotation = toRadians(this.rotation);
        const halfPi = Math.PI / 2;

        let datumIndex = 0;

        // Simply use reduce here to pair up adjacent ratios.
        angleDataRatios.reduce((start, end) => {
            const radius = radiusKey ? radiusData[datumIndex] : 1;
            const startAngle = angleScale.convert(start) + rotation;
            const endAngle = angleScale.convert(end) + rotation;

            const midAngle = (startAngle + endAngle) / 2;
            const span = Math.abs(endAngle - startAngle);
            const midCos = Math.cos(midAngle);
            const midSin = Math.sin(midAngle);

            const labelMinAngle = toRadians(this.label.minAngle);
            const labelVisible = labelKey && span > labelMinAngle;
            const midAngle180 = normalizeAngle180(midAngle);

            // Split the circle into quadrants like so: ⊗
            let quadrantStart = -3 * Math.PI / 4; // same as `normalizeAngle180(toRadians(-135))`
            let textAlign: CanvasTextAlign;
            let textBaseline: CanvasTextBaseline;

            if (midAngle180 >= quadrantStart && midAngle180 < (quadrantStart += halfPi)) {
                textAlign = 'center';
                textBaseline = 'bottom';
            } else if (midAngle180 >= quadrantStart && midAngle180 < (quadrantStart += halfPi)) {
                textAlign = 'left';
                textBaseline = 'middle';
            } else if (midAngle180 >= quadrantStart && midAngle180 < (quadrantStart += halfPi)) {
                textAlign = 'center';
                textBaseline = 'hanging';
            } else {
                textAlign = 'right';
                textBaseline = 'middle';
            }

            groupSelectionData.push({
                series: this,
                seriesDatum: data[datumIndex],
                index: datumIndex,
                radius,
                startAngle,
                endAngle,
                midAngle,
                midCos,
                midSin,
                label: labelVisible ? {
                    text: labelData[datumIndex],
                    textAlign,
                    textBaseline
                } : undefined
            });

            datumIndex++;

            return end;
        }, 0);

        return true;
    }

    update(): void {
        const { chart } = this;
        const visible = this.group.visible = this.visible && this.seriesItemEnabled.indexOf(true) >= 0;

        if (!visible || !chart || chart.dataPending || chart.layoutPending) {
            return;
        }

        const { radius, innerRadiusOffset, outerRadiusOffset, title } = this;

        this.radiusScale.range = [
            innerRadiusOffset ? radius + innerRadiusOffset : 0,
            radius + (outerRadiusOffset || 0)
        ];

        this.group.translationX = this.centerX;
        this.group.translationY = this.centerY;

        if (title) {
            title.node.translationY = -radius - outerRadiusOffset - 2;
            title.node.visible = title.enabled;
        }

        this.updateGroupSelection();
        this.updateNodes();
    }

    private updateGroupSelection() {
        const updateGroups = this.groupSelection.setData(this.groupSelectionData);
        updateGroups.exit.remove();

        const enterGroups = updateGroups.enter.append(Group);
        enterGroups.append(Sector).each(node => node.tag = PieNodeTag.Sector);
        enterGroups.append(Line).each(node => {
            node.tag = PieNodeTag.Callout;
            node.pointerEvents = PointerEvents.None;
        });
        enterGroups.append(Text).each(node => {
            node.tag = PieNodeTag.Label;
            node.pointerEvents = PointerEvents.None;
        });

        this.groupSelection = updateGroups.merge(enterGroups);
    }

    private updateNodes() {
        if (!this.chart) {
            return;
        }

        const {
            fills, strokes, fillOpacity, strokeOpacity, strokeWidth,
            outerRadiusOffset, radiusScale, callout, shadow,
            highlightStyle: { fill, stroke, centerOffset },
            angleKey, radiusKey, formatter
        } = this;
        const { highlightedDatum } = this.chart;

        const centerOffsets: number[] = [];
        const innerRadius = radiusScale.convert(0);

        this.groupSelection.selectByTag<Sector>(PieNodeTag.Sector).each((sector, datum, index) => {
            const radius = radiusScale.convert(datum.radius);
            const outerRadius = Math.max(0, radius + outerRadiusOffset);
            const highlighted = datum === highlightedDatum;
            const sectorFill = highlighted && fill !== undefined ? fill : fills[index % fills.length];
            const sectorStroke = highlighted && stroke !== undefined ? stroke : strokes[index % strokes.length];
            let format: PieSeriesFormat | undefined = undefined;

            if (formatter) {
                format = formatter({
                    datum: datum.seriesDatum,
                    fill: sectorFill,
                    stroke: sectorStroke,
                    strokeWidth,
                    highlighted,
                    angleKey,
                    radiusKey
                });
            }

            sector.innerRadius = innerRadius;
            sector.outerRadius = radius;

            sector.startAngle = datum.startAngle;
            sector.endAngle = datum.endAngle;

            sector.fill = format && format.fill || sectorFill;
            sector.stroke = format && format.stroke || sectorStroke;
            sector.strokeWidth = format && format.strokeWidth !== undefined ? format.strokeWidth : strokeWidth;
            sector.fillOpacity = fillOpacity;
            sector.strokeOpacity = strokeOpacity;
            sector.lineDash = this.lineDash;
            sector.lineDashOffset = this.lineDashOffset;
            sector.centerOffset = highlighted && centerOffset !== undefined ? centerOffset : 0;
            sector.fillShadow = shadow;
            sector.lineJoin = 'round';

            centerOffsets.push(sector.centerOffset);
        });

        const { colors: calloutColors, length: calloutLength, strokeWidth: calloutStrokeWidth } = callout;

        this.groupSelection.selectByTag<Line>(PieNodeTag.Callout).each((line, datum, index) => {
            if (datum.label) {
                const radius = radiusScale.convert(datum.radius);

                line.strokeWidth = calloutStrokeWidth;
                line.stroke = calloutColors[index % calloutColors.length];
                line.x1 = datum.midCos * radius;
                line.y1 = datum.midSin * radius;
                line.x2 = datum.midCos * (radius + calloutLength);
                line.y2 = datum.midSin * (radius + calloutLength);
            } else {
                line.stroke = undefined;
            }
        });

        {
            const { offset, fontStyle, fontWeight, fontSize, fontFamily, color } = this.label;

            this.groupSelection.selectByTag<Text>(PieNodeTag.Label).each((text, datum, index) => {
                const label = datum.label;

                if (label) {
                    const radius = radiusScale.convert(datum.radius);
                    const labelRadius = centerOffsets[index] + radius + calloutLength + offset;

                    text.fontStyle = fontStyle;
                    text.fontWeight = fontWeight;
                    text.fontSize = fontSize;
                    text.fontFamily = fontFamily;
                    text.text = label.text;
                    text.x = datum.midCos * labelRadius;
                    text.y = datum.midSin * labelRadius;
                    text.fill = color;
                    text.textAlign = label.textAlign;
                    text.textBaseline = label.textBaseline;
                } else {
                    text.fill = undefined;
                }
            });
        }
    }

    fireNodeClickEvent(event: MouseEvent, datum: PieNodeDatum): void {
        this.fireEvent<PieSeriesNodeClickEvent>({
            type: 'nodeClick',
            event,
            series: this,
            datum: datum.seriesDatum,
            angleKey: this.angleKey,
            labelKey: this.labelKey,
            radiusKey: this.radiusKey
        });
    }

    getTooltipHtml(nodeDatum: PieNodeDatum): string {
        const { angleKey } = this;

        if (!angleKey) {
            return '';
        }

        const {
            fills,
            tooltip,
            angleName,
            radiusKey,
            radiusName,
            labelKey,
            labelName,
        } = this;

        const { renderer: tooltipRenderer = this.tooltipRenderer } = tooltip;
        const color = fills[nodeDatum.index % fills.length];
        const datum = nodeDatum.seriesDatum;
        const label = labelKey ? `${datum[labelKey]}: ` : '';
        const angleValue = datum[angleKey];
        const formattedAngleValue = typeof angleValue === 'number' ? toFixed(angleValue) : angleValue.toString();
        const title = this.title ? this.title.text : undefined;
        const content = label + formattedAngleValue;
        const defaults: TooltipRendererResult = {
            title,
            backgroundColor: color,
            content
        };

        if (tooltipRenderer) {
            return toTooltipHtml(tooltipRenderer({
                datum,
                angleKey,
                angleValue,
                angleName,
                radiusKey,
                radiusValue: radiusKey ? datum[radiusKey] : undefined,
                radiusName,
                labelKey,
                labelName,
                title,
                color,
            }), defaults);
        }

        return toTooltipHtml(defaults);
    }

    listSeriesItems(legendData: LegendDatum[]): void {
        const { labelKey, data } = this;

        if (data && data.length && labelKey) {
            const { fills, strokes, id } = this;

            data.forEach((datum, index) => {
                legendData.push({
                    id,
                    itemId: index,
                    enabled: this.seriesItemEnabled[index],
                    label: {
                        text: String(datum[labelKey])
                    },
                    marker: {
                        fill: fills[index % fills.length],
                        stroke: strokes[index % strokes.length],
                        fillOpacity: this.fillOpacity,
                        strokeOpacity: this.strokeOpacity
                    }
                });
            });
        }
    }

    toggleSeriesItem(itemId: number, enabled: boolean): void {
        this.seriesItemEnabled[itemId] = enabled;
        this.scheduleData();
    }
}


text:
Assignment: CSS Hell
====================

You will skin 3 project gutenberg stories with custom CSS.

You will skin 2 versions of a possible professional homepage for your
self with 2 versions of CSS.

Read requirements.org

Read this comic http://theoatmeal.com/comics/design_hell

git clone https://github.com/abramhindle/CMPUT404-assignment-css-hell.git

License/Copyright
=================

Textual content is copyright Abram Hindle (C) 2013 under the CC-BY-SA
4.0 unported license. Attribution should be a hyperlink to the
repository and (C) 2013 Abram Hindle visibile in the text.

Code is licensed under the Apache 2.0 license.


text:
<form action="buy.php" method="post">
    <fieldset>

            <input class="form-control" name="symbol" placeholder="Stock Symbol" type="text"/>

            <input class="form-control" name="share_amt" placeholder="Number of Shares" type="text"/>

            <button class="btn btn-default" type="submit">Buy</button>

    </fieldset>
</form>


text:
bool formatDirectoryPath(Client& client, Config* config){

	std::size_t pos = client.path.find("..");
	while(pos != std::string::npos){ //while there is .. not analysed somewhere

		if(pos == 0) //path start with '..'
			return false;

		if(client.path[pos - 1] == '/'){ //there is '/..'

			if(pos + 2 == client.path.size()) //path end by '/..'
				return false;

			if(client.path[pos + 2] == '/') //there is a '/' after '/..'
				return false;
		}

		pos = client.path.find("..", pos + 1);
	}

	if (!client.path.compare(0,8,"/Private")){

		client.path.insert(8, "/" + client.name());

		if(!config->privateFolderReadingAllowed() &&  !config->privateFolderWritingAllowed()){

			return false;
		}
	}

	else{
		client.path = "/Public" + client.path;
	}
	client.path = '.' + client.path;

	return true;
}


text:
'use strict';

module.exports = function cutTheMustardAdvanced(context) {
    context = context || window;
    return 'visibilityState' in context.document;
};


text:
require 'spec_helper'

describe Github::Client::Repos::Collaborators, '#remove' do
  let(:user) { 'peter-murach' }
  let(:repo) { 'github' }
  let(:collaborator) { 'octocat' }
  let(:request_path) { "/repos/#{user}/#{repo}/collaborators/#{collaborator}" }

  before {
    stub_delete(request_path).
      to_return(:body => body, :status => status,
        :headers => {:content_type => "application/json; charset=utf-8"})
  }

  after { reset_authentication_for(subject) }

  context "resouce removed" do
    let(:body) { '' }
    let(:status) { 204 }

    it { expect { subject.remove }.to raise_error(ArgumentError) }

    it "should fail to add resource if 'collaborator' input is missing" do
      expect { subject.remove user, repo }.to raise_error(ArgumentError)
    end

    it "should add resource successfully" do
      subject.remove user, repo, collaborator
      expect(a_delete(request_path)).to have_been_made
    end
  end

  it_should_behave_like 'request failure' do
    let(:requestable) { subject.remove user, repo, collaborator }
  end
end # remove


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="@dimen/margin_default"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        style="@style/TextView.Huge"
        android:id="@+id/speech_recognition_result_text_view"
        android:gravity="center"
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="0dp"/>

    <TextView
        style="@style/TextView"
        android:text="@string/speech_recognition_last_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <TextView
        style="@style/TextView"
        android:id="@+id/speech_recognition_last_text_text_view"
        android:layout_marginTop="@dimen/margin_medium"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>


text:
layout: post
title: The Times, They are a-Changing…
author: elliotfriend
date: '2010-08-21 06:51:29 -0500'
categories: technology family
img-name: tangled-network.jpg
seq: 2
---
### BIG GIANT EXCITING EXHILARATING NEWS!! ###

As of today (yesterday, technically), I have eagerly accepted the position
of IT Supervisor at my school, [St. Louis Christian College](https://stlchristian.edu).
It appears that the stars must have aligned in my favor this week. For,
just four days ago, I had a conversation with my very close friend,
[J.C Sandt](https://twitter.com/jcsandt), about how much I hated my job.
We actually made a deal of epic proportions: by the end of the semester
we would both be employed in a rewarding job. I had no idea that things
would move so swiftly.

So, with my two weeks handed in at Schnucks, and with much dread and hope,
I excitedly begin to branch into this new adventure.

I say dread because there is much work to be done. There are routers to
be reset; Ethernet switches to be tested; Passwords to find; Printers to
fix; Web pages to design; As well as a whole host of other things that I
haven't even figured out yet. I have much work ahead, much trial and error,
and (hopefully) much success. This new job will surely prove to be
challenging, but it will no doubt be extremely rewarding.

That's why the element of hope is there, as well. I'm so eager to learn
and "get my hands dirty." I know that I'll be applying many band-aids to
the current system that is in need of repair, but in doing so I will gain
so much hands-on knowledge about what Information Technology is all about.
There is so much promise for what this year will hold for me.

The good news in all this is that I'm entering into this with a crew. I'm
not alone on this journey. I've got three [MAP](https://stlchristian.edu/academics/map)
students that I will be working with. I know that they're going to learn
a lot through this, and I'm sure I'll learn a lot from working with them.

My God, the God of Abraham, Isaac, and Jacob, is a God of providence. At
a point that I was looking for a fulfilling job (ideally, in the IT sector,
no less), He was working hard. It amazes me so much how the LORD **always**
comes through. He is faithful, and works all things for the good of those
who love him, and are called according to His will. I've seen an incredible
example this week of God's workings, and I know I'll only see more as time
goes on.

### Praise be to God! ###

Photo by [Bruno Girin](https://flic.kr/p/7sdJw)


text:
package com.apptentive.android.sdk.model;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SensitiveDataKey {
}


text:
package de.egore911.capacity.persistence.selector;

import java.util.List;

import javax.annotation.Nonnull;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;

import de.egore911.appframework.persistence.selector.AbstractResourceSelector;
import de.egore911.capacity.persistence.model.RequirementEntity;
import de.egore911.capacity.persistence.model.RequirementEntity_;

public class RequirementSelector extends AbstractResourceSelector<RequirementEntity> {

    private String search;

    public RequirementSelector(EntityManager em) {
        super(em);
    }

    @Override
    @Nonnull
    protected List<Predicate> generatePredicateList(@Nonnull CriteriaBuilder builder,
                                                    @Nonnull Root<RequirementEntity> from,
                                                    @Nonnull CriteriaQuery<?> criteriaQuery) {
        List<Predicate> predicates = super.generatePredicateList(builder, from, criteriaQuery);

        if (StringUtils.isNotEmpty(search)) {
            predicates.add(builder.like(from.get(RequirementEntity_.title), '%' + search + '%'));
        }

        return predicates;
    }

    @Override
    public RequirementSelector withSearch(String search) {
        this.search = search;
        return this;
    }

    @Override
    @Nonnull
    protected Class<RequirementEntity> getEntityClass() {
        return RequirementEntity.class;
    }

}


text:
<template name="postItem">

{{title}}

{{content}}

    Ways to share the post will be put here

</template>


text:
This script is used to generate the annual report required by my company policy. It groups the SVN log by a specified time delta and generates a report from the grouped logs.

## Requirements
* Lastest version of Python 2
* [python-docx](https://python-docx.readthedocs.org/en/latest/)

## Usage
1. Edit the file prefixed with "config_"
1. Put it and template document at the same directory as taskReportGenerator.py
1. cd to the directory and enter `python taskReportGenerator.py`


text:
/**
 * Module dependencies.
 */

var path = require('path'),
    phonegap = require('../main');

/**
 * Parse command-line arguments.
 *
 * Inspects the arguments and calls the appropriate action.
 *
 * Options:
 *
 *   - `argv` {Object} is an optimist.argv object.
 *   - `[callback]` {Function} is called on completion.
 */

module.exports = function(argv, callback) {
    // optional callback
    callback = callback || function() {};

    // parse process.argv for easy --flag handling
    // skipped when already parsed
    if (!argv._) {
        var processArgv = Array.prototype.slice.call(argv);
        argv = require('minimist')(argv.slice(2), {
            boolean: [
                'd', 'device',
                'e', 'emulator',
                'd', 'verbose',
                'v', 'version',
                'h', 'help',
                'autoreload',
                'browser',
                'localtunnel'
            ],
            default: {
                'autoreload': true,
                'browser': true,
                'localtunnel': false
            }
        });

        // add $0 for backward-compatibility for optimist.
        argv.$0 = path.basename(processArgv[1]).replace('.js', '');

        // add original argv command without minimist formatting
        argv.processArgv = processArgv;

        // add -e support to Cordova commands
        if (argv.e) {
            var index = argv.processArgv.indexOf('-e');
            if (index >= 0) {
                argv.processArgv[index] = '--emulator';
                argv.emulator = true;
                argv.e = false;
            }
        }
    }

    // cordova commands should bypass all processing
    if (argv._[0] && argv._[0].match(/cordova/i)) {
        this.cordova(argv, callback);
        return;
    }

    // --version
    if (argv.version || argv.v) {
        this.version(argv, callback);
        return;
    }

    // --verbose
    if (argv.verbose || argv.d) {
        argv.verbose = true;
        phonegap.mode({ verbose: true });
    }

    // --help
    // --help <command>
    if (argv.help || argv.h) {
        argv._.unshift('help');
    }

    // support <command> help
    if (argv._[argv._.length-1] === 'help' && argv._.length > 1) {
        argv._.pop();
        argv._.unshift('help');
    }

    // no command displays help
    if (!argv._.length) {
        argv._.unshift('help');
    }

    // lookup command to execute
    var command = this;
    for (var i = 0, l = argv._.length; i < l; i++) {
        if (typeof command[argv._[i]] === 'function') {
            command = command[argv._[i]];
        }
        else {
            break;
        }
    }

    // execute unknown commands with cordova
    if (command === this) {
        argv.processArgv.splice(2, 0, 'cordova');
        argv._.unshift('cordova');
        this.cordova(argv, callback);
    }
    // execute all other commands with phonegap
    else {
        command.call(this, argv, callback);
    }
};


text:
package org.mp4parser.examples.concatentation;

public class StreamingConcat {

}


text:
package org.elasticsearch.xpack.sql.expression.function.aggregate;

import org.elasticsearch.xpack.sql.expression.Expression;
import org.elasticsearch.xpack.sql.tree.Source;

import java.util.List;

// marker type for compound aggregates, that is aggregate that provide multiple values (like Stats or Matrix)
// and thus cannot be used directly in SQL and are mainly for internal use
public abstract class CompoundNumericAggregate extends NumericAggregate {

    CompoundNumericAggregate(Source source, Expression field, List<Expression> arguments) {
        super(source, field, arguments);
    }

    CompoundNumericAggregate(Source source, Expression field) {
        super(source, field);
    }
}


text:
"""
Test process list.
"""

from __future__ import print_function

import os
import lldb
import shutil
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil

class ProcessListTestCase(TestBase):

    mydir = TestBase.compute_mydir(__file__)

    NO_DEBUG_INFO_TESTCASE = True

    @skipIfWindows # https://bugs.llvm.org/show_bug.cgi?id=43702
    def test_process_list_with_args(self):
        """Test process list show process args"""
        self.build()
        exe = self.getBuildArtifact("TestProcess")

        # Spawn a new process
        popen = self.spawnSubprocess(exe, args=["arg1", "--arg2", "arg3"])
        self.addTearDownHook(self.cleanupSubprocesses)

        self.expect("platform process list -v",
                    substrs=["TestProcess arg1 --arg2 arg3", str(popen.pid)])


text:
"use strict";
var Base = require('./base');
var point_1 = require('./point');
var PmzSpline = (function () {
    function PmzSpline(line, src, dst, points, isSmooth) {
        this.line = line;
        this.src = src;
        this.dst = dst;
        this.points = points;
        this.isSmooth = isSmooth;
        return this;
    }
    PmzSpline.parse = function (text) {
        var parts = Base.asArray(text);
        var line = parts[0];
        var src = parts[1];
        var dst = parts[2];
        var isSmooth = parts.length % 2 === 0;
        var points = [];
        for (var i = 3; i < (parts.length - 1); i += 2) {
            points.push(new point_1.PmzPoint(parseInt(parts[i]), parseInt(parts[i + 1])));
        }
        return new PmzSpline(line, src, dst, points, isSmooth);
    };
    PmzSpline.format = function (spline) {
        return [
            spline.line,
            spline.src,
            spline.dst,
            point_1.PmzPoint.formatArray(spline.points),
            spline.isSmooth
        ].join(',');
    };
    return PmzSpline;
}());
exports.PmzSpline = PmzSpline;


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
es5id: 15.2.3.6-3-91-1
description: >
    Object.defineProperty - 'Attributes' is the Math object that uses
    Object's [[Get]] method to access the 'configurable' property
    (8.10.5 step 4.a)
---*/

        var obj = {};

            Object.prototype.configurable = true;

            Object.defineProperty(obj, "property", Math);

            var beforeDeleted = obj.hasOwnProperty("property");

            delete obj.property;

            var afterDeleted = obj.hasOwnProperty("property");

assert.sameValue(beforeDeleted, true, 'beforeDeleted');
assert.sameValue(afterDeleted, false, 'afterDeleted');


text:
package icsp

import (
	"fmt"
	"os"
	"testing"
	"time"

	"github.com/HewlettPackard/oneview-golang/icsp"
	"github.com/docker/machine/libmachine/log"
	"github.com/stretchr/testify/assert"
)

// Test SessionLogin
func TestSessionLogin(t *testing.T) {
	var (
		c *icsp.ICSPClient
	)
	if os.Getenv("ICSP_TEST_ACCEPTANCE") == "true" {
		_, c = getTestDriverA()
		if c == nil {
			t.Fatalf("Failed to execute getTestDriver() ")
		}
		data, err := c.SessionLogin()
		// fmt.Printf("after SessionLogin: %s -> (err) %+v", data.ID, err)
		assert.NoError(t, err, "SessionLogin threw error -> %s", err)
		assert.NotEmpty(t, data.ID, fmt.Sprintf("SessionLogin is empty! something went wrong, err -> %s, data -> %+v\n", err, data))
		assert.Equal(t, "none", c.APIKey)

		c.APIKey = data.ID
		err = c.SessionLogout()
		assert.NoError(t, err, "SessionLogout threw error -> %s", err)
		data, err = c.SessionLogin()
		assert.NoError(t, err, "SessionLogin threw error -> %s", err)
	} else {
		_, c = getTestDriverU()
		data, err := c.SessionLogin()
		assert.Error(t, err, fmt.Sprintf("ALL ok, no error, caught as expected: %s,%+v\n", err, data))
		assert.Equal(t, "none", c.APIKey)
	}
}

// Get the current idle timeout from the logged in session
func TestGetIdleTimeout(t *testing.T) {
	var (
		c *icsp.ICSPClient
		// d *ICSPTest
	)
	if os.Getenv("ONEVIEW_TEST_ACCEPTANCE") == "true" {
		_, c = getTestDriverA()
		if c == nil {
			t.Fatalf("Failed to execute getTestDriver() ")
		}
		err := c.RefreshLogin()
		log.Debugf(" login key -> %s", c.APIKey)
		assert.NoError(t, err, "RefreshLogin threw error -> %s", err)

		timeout, err := c.GetIdleTimeout()
		assert.NoError(t, err, "GetIdleTimeout threw error -> %s", err)
		log.Debugf(" idle timeout -> %d", timeout)
	}

}

// Set idle timeout
func TestSetIdleTimeout(t *testing.T) {
	var (
		c *icsp.ICSPClient
		// d *ICSPTest
		testtime int64
	)
	if os.Getenv("ONEVIEW_TEST_ACCEPTANCE") == "true" {
		testtime = 25000
		_, c = getTestDriverA()
		if c == nil {
			t.Fatalf("Failed to execute getTestDriver() ")
		}
		err := c.RefreshLogin()
		log.Debugf(" login key -> %s", c.APIKey)
		assert.NoError(t, err, "RefreshLogin threw error -> %s", err)

		err = c.SetIdleTimeout(testtime)
		assert.NoError(t, err, "SetIdleTimeout threw error -> %s", err)

		timeout, err := c.GetIdleTimeout()
		assert.NoError(t, err, "GetIdleTimeout threw error -> %s", err)
		assert.Equal(t, testtime, timeout, "Should get timeout equal, %s", timeout)
		log.Debugf(" idle timeout -> %d", timeout)
	}

}

// Test for expired key and see if RefreshLogin can restore the key if we have a bad key
func TestSessionExpiredKey(t *testing.T) {
	var (
		c *icsp.ICSPClient
		d *ICSPTest
	)
	if os.Getenv("ONEVIEW_TEST_ACCEPTANCE") == "true" {
		d, c = getTestDriverA()
		if c == nil {
			t.Fatalf("Failed to execute getTestDriver() ")
		}
		err := c.RefreshLogin()
		log.Debugf(" login key -> %s", c.APIKey)
		assert.NoError(t, err, "RefreshLogin threw error -> %s", err)
		// force key to timeout
		err = c.SetIdleTimeout(800)
		assert.NoError(t, err, "SetIdleTimeout threw error -> %s", err)

		// 1 millisecond and we should be timeout with the current key
		time.Sleep(1 * time.Millisecond)

		// verify we are timed out
		_, err = c.GetIdleTimeout()
		assert.Error(t, err, "should be 404 not found -> %s ", err)

		// verify that we can access something from icps with this client
		// This should not fail because it uses RefreshLogin to get a new login session and avoid timeout
		serialNumber := d.Tc.GetTestData(d.Env, "SerialNumber").(string)
		s, err := c.GetServerBySerialNumber(serialNumber)
		assert.NoError(t, err, "GetServerBySerialNumber threw error -> %s, server -> %+v", err, s)
	}

}

// Test SessionLogout
func TestSessionLogout(t *testing.T) {
	var (
		//d *OVTest
		c *icsp.ICSPClient
		//testSerial string
	)
	if os.Getenv("ONEVIEW_TEST_ACCEPTANCE") == "true" {
		_, c = getTestDriverA()
		if c == nil {
			t.Fatalf("Failed to execute getTestDriver() ")
		}
		//data, err := c.SessionLogin()
		// this is needed so we can "copy" the session id to the ov client
		err := c.RefreshLogin()
		//log.Debugf(" login key -> %s, session data -> %+v", c.APIKey, data)
		log.Debugf(" login key -> %s", c.APIKey)
		assert.NoError(t, err, "SessionLogin threw error -> %s", err)
		//assert.NotEmpty(t, data.ID, fmt.Sprintf("SessionLogin is empty! something went wrong, err -> %s, data -> %+v\n", err, data))
		//assert.Equal(t, "none", c.APIKey)
		err = c.SessionLogout()
		log.Debugf(" login key after logout -> %s", c.APIKey)
		assert.NoError(t, err, "SessionLogout threw error -> %s", err)
		// test if we can perform an op after logout
		//_, err = c.GetProfileBySN(testSerial)
		//assert.Error(t, err, "SessionLogin threw error -> %s", err)
	} else {
		/*_, c = getTestDriverU()
		data, err := c.SessionLogin()
		assert.Error(t,err, fmt.Sprintf("ALL ok, no error, caught as expected: %s,%+v\n",err, data))
		assert.Equal(t, "none", c.APIKey)
		*/
	}
}


text:
import unittest

from betterversion.better import version_windows, VersionIdentifier

class TestSequenceFunctions(unittest.TestCase):
    def setUp(self):
        self.versions = [
            VersionIdentifier("0.1.0"),
            VersionIdentifier("0.2.0"),
            VersionIdentifier("0.2.1"),
            VersionIdentifier("0.3.0"),
            VersionIdentifier("0.3.1"),
            VersionIdentifier("1.1.0"),
            VersionIdentifier("1.2.0"),
            VersionIdentifier("1.3.0"),
            VersionIdentifier("2.1.0"),
            VersionIdentifier("2.2.0"),
            VersionIdentifier("2.3.0"),
            VersionIdentifier("2.3.1"),
            VersionIdentifier("2.3.2"),
            VersionIdentifier("2.3.3"),
        ]

    def test_major(self):
        major_versions = version_windows(self.versions, major=1)
        self.assertEqual(len(major_versions), 1)

        major_versions = version_windows(self.versions, major=2)
        self.assertEqual(len(major_versions), 2)

        major_versions = version_windows(self.versions, major=3)
        self.assertEqual(len(major_versions), 3)

        major_versions = version_windows(self.versions, major=4)
        self.assertEqual(len(major_versions), 3)

    def test_minor(self):
        minor_versions = version_windows(self.versions, minor=1)
        self.assertEqual(len(minor_versions[2]), 1)

        minor_versions = version_windows(self.versions, minor=2)
        self.assertEqual(len(minor_versions[2]), 2)

        minor_versions = version_windows(self.versions, minor=3)
        self.assertEqual(len(minor_versions[2]), 3)

        minor_versions = version_windows(self.versions, minor=4)
        self.assertEqual(len(minor_versions[2]), 3)

    def test_point(self):
        point_versions = version_windows(self.versions, point=1)
        self.assertEqual(len(point_versions[2][3]), 1)

        point_versions = version_windows(self.versions, point=2)
        self.assertEqual(len(point_versions[2][3]), 2)

        point_versions = version_windows(self.versions, point=3)
        self.assertEqual(len(point_versions[2][3]), 3)

        point_versions = version_windows(self.versions, point=4)
        self.assertEqual(len(point_versions[2][3]), 4)

        point_versions = version_windows(self.versions, point=5)
        self.assertEqual(len(point_versions[2][3]), 4)

    def test_sort(self):
        final_versions = version_windows(self.versions,
                                         major=2, minor=2, point=1)
        self.assertTrue(final_versions[1][2][0] == VersionIdentifier('1.2.0'))
        self.assertTrue(final_versions[1][3][0] == VersionIdentifier('1.3.0'))
        self.assertTrue(final_versions[2][3][0] == VersionIdentifier('2.3.3'))
        self.assertTrue(final_versions[2][3][0] != VersionIdentifier('2.3.0'))

        final_versions = version_windows(self.versions,
                                         major=1, minor=2, point=2)
        # 1 major version
        self.assertEqual(final_versions[1], {})
        # 2 minor versions
        self.assertEqual(len(final_versions[2]), 2)
        # 2 point versions
        self.assertEqual(len(final_versions[2][3]), 2)
        final_versions = version_windows(self.versions,
                                         major=1, minor=2, point=3)
        # 2 point versions
        self.assertEqual(len(final_versions[2][3]), 3)

    def test_flat(self):
        final_versions = version_windows(self.versions,
                                         major=2, minor=2, point=1, flat=True)
        self.assertEqual(len(final_versions), 4)
        self.assertEqual(
            final_versions,
            [
                VersionIdentifier('1.2.0'),
                VersionIdentifier('1.3.0'),
                VersionIdentifier('2.2.0'),
                VersionIdentifier('2.3.3')
            ]
        )

        final_versions = version_windows(self.versions,
                                         major=3, minor=2, point=1, flat=True)
        self.assertEqual(len(final_versions), 6)
        self.assertEqual(
            final_versions,
            [
                VersionIdentifier('0.2.1'),
                VersionIdentifier('0.3.1'),
                VersionIdentifier('1.2.0'),
                VersionIdentifier('1.3.0'),
                VersionIdentifier('2.2.0'),
                VersionIdentifier('2.3.3')
            ]
        )

        final_versions = version_windows(self.versions,
                                         major=3, minor=2, point=2, flat=True)
        self.assertEqual(len(final_versions), 9)

if __name__ == '__main__':
    unittest.main()


text:
//----------------------------------------------------------------------------
// Copyright (C) 2003  Rafael H. Bordini, Jomi F. Hubner, et al.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
// To contact the authors:
// http://www.inf.ufrgs.br/~bordini
// http://www.das.ufsc.br/~jomi
//
//----------------------------------------------------------------------------

package jason.stdlib;

import jason.JasonException;
import jason.asSemantics.DefaultInternalAction;
import jason.asSemantics.InternalAction;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.ListTerm;
import jason.asSyntax.StringTerm;
import jason.asSyntax.StringTermImpl;
import jason.asSyntax.Term;

/**

Internal action: .reverse.

Description: reverses strings or lists.

Parameters:

+ arg[0] (list or string): the list to be reversed.

+/- arg[1]: the result.

Examples:

 .reverse("abc",X): X unifies with "cba".

 .reverse("[a,b,c]",X): X unifies with "[c,b,a]".

 .reverse("[a,b,c|T]",X): X unifies with "[c,b,a|T]".

  @see jason.stdlib.concat
  @see jason.stdlib.delete
  @see jason.stdlib.length
  @see jason.stdlib.nth
  @see jason.stdlib.max
  @see jason.stdlib.member
  @see jason.stdlib.min
  @see jason.stdlib.sort
  @see jason.stdlib.substring

  @see jason.stdlib.difference
  @see jason.stdlib.intersection
  @see jason.stdlib.union

*/
public class reverse extends DefaultInternalAction {

    private static InternalAction singleton = null;
    public static InternalAction create() {
        if (singleton == null)
            singleton = new reverse();
        return singleton;
    }

    @Override public int getMinArgs() { return 2; }
    @Override public int getMaxArgs() { return 2; }

    @Override
    public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
        checkArguments(args);

        if (args[0].isList()) {
            // list reverse
            if (!args[1].isVar() && !args[1].isList())
                throw JasonException.createWrongArgument(this,"last argument '"+args[1]+"' must be a list or a variable.");

            return un.unifies(((ListTerm)args[0]).reverse(), args[1]);

        } else {
            // string reverse
            if (!args[1].isVar() && !args[1].isString())
                throw JasonException.createWrongArgument(this,"last argument '"+args[1]+"' must be a string or a variable.");
            String vl = args[0].toString();
            if (args[0].isString())
                vl = ((StringTerm)args[0]).getString();

            return un.unifies(new StringTermImpl(new StringBuilder(vl).reverse().toString()), args[1]);
        }
    }
}


text:
import hashlib
import os
import sqlite3
import time
from pathlib import Path

from ifsApprover import Log
from ifsApprover.Utils import rnd_string

logger = Log.get_logger("DB")

class DB:
    STATUS_OK = 1
    STATUS_NO_IMAGE = 2
    STATUS_APPROVED = 3
    STATUS_REJECTED = 4

    _SYSTEM_USER = "_system_".lower()

    def __init__(self, filename):
        file = Path(filename)
        logger.info("Using db %s", file.absolute())
        if not file.exists():
            logger.info("Creating new database file...")
        self._connection = sqlite3.connect(filename, check_same_thread=False)
        self._connection.row_factory = sqlite3.Row
        self._cursor = self._connection.cursor()
        if not self._exist_table("users"):
            self._create_table_users()
        if not self._exist_table("images"):
            self._create_table_images()

    def _exist_table(self, table_name):
        self._cursor.execute(f"SELECT count(name) FROM sqlite_master WHERE type='table' AND name='{table_name}'")
        return self._cursor.fetchone()[0] == 1

    def _create_table_images(self):
        logger.info("Creating tables images")
        self._cursor.execute("""
        CREATE TABLE images (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            sender TEXT NOT NULL,
            filename TEXT,
            status INT NOT NULL,
            description TEXT,
            date INT NOT NULL,
            width INT,
            height INT,
            changed_by INTEGER,
            action_reason TEXT,
            FOREIGN KEY(changed_by) REFERENCES users(id)
        )""")

    def _create_table_users(self):
        logger.info("Creating tables users")
        self._cursor.execute("""
        CREATE TABLE users (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            login TEXT NOT NULL UNIQUE,
            password TEXT NOT NULL,
            salt TEXT NOT NULL
        )""")

        data = (0, DB._SYSTEM_USER, "-", "-")
        self._cursor.execute("""
        INSERT INTO users
            (id, login, password, salt)
            VALUES (?, ?, ?, ?)
        """, data)
        self._connection.commit()

    def is_system_user(self, user):
        return user["login"] == DB._SYSTEM_USER

    #
    # Images
    #

    def _insert_images(self, sender, description, status, filename=None, width=None, height=None, changed_by=None):
        now = int(time.time())
        data = (sender, filename, status, description, now, width, height, changed_by)
        logger.debug(f"Insert new entry: {str(data)}")

        self._cursor.execute("""
        INSERT INTO images
            (sender, filename, status, description, date, width, height, changed_by)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        """, data)
        self._connection.commit()

    def add_image(self, sender, description, filename, width, height):
        self._insert_images(
            sender=sender,
            description=description,
            status=self.STATUS_OK,
            filename=filename,
            width=width,
            height=height
        )

    def add_no_image(self, sender, description):
        self._insert_images(sender, description, self.STATUS_NO_IMAGE)

    def get_pending_images(self):
        self._cursor.execute("SELECT * FROM images where status = ? ORDER BY date desc", [self.STATUS_OK])
        return self._cursor.fetchall()

    def get_pending_images_count(self):
        self._cursor.execute("SELECT count(*) FROM images where status = ?", [self.STATUS_OK])
        return self._cursor.fetchone()[0]

    def get_missing_images(self):
        self._cursor.execute("SELECT * FROM images where status = ? ORDER BY date desc", [self.STATUS_NO_IMAGE])
        return self._cursor.fetchall()

    def get_processed_images(self):
        """
        Gets all images that are APPROVED or REJECTED
        :return:
        """
        self._cursor.execute(
            "SELECT i.*, u.login AS changed_by_name FROM images i, users u where u.id = i.changed_by AND status in(?, ?) ORDER BY date desc",
            [self.STATUS_REJECTED, self.STATUS_APPROVED])
        return self._cursor.fetchall()

    def _change_image(self, image_id, user_login, status, reason="null"):
        if user_login == DB._SYSTEM_USER:
            user_id = 0
        else:
            user_id = self.get_user_id(user_login)
            if user_id is None:
                raise Exception("user login should not be None at this time.")

        logger.info(f"Change the image id {image_id} by user {user_login} to {status} (reason {reason})")
        self._cursor.execute("UPDATE images SET status = :status, changed_by = :by, action_reason = :reason WHERE id = :imgId",
                             {"status": status, "by": user_id, "reason": reason, "imgId": image_id})
        self._connection.commit()

    def get_single_image(self, image_id):
        self._cursor.execute("SELECT * FROM images where id = ?", [image_id])
        return self._cursor.fetchone()

    def approve_image(self, image_id, user_login):
        self._change_image(image_id, user_login, DB.STATUS_APPROVED)

    def reject_image(self, image_id, user_login, reject_reason):
        self._change_image(image_id, user_login, DB.STATUS_REJECTED, reason=reject_reason)

    def update_image_by_system(self, image_id, status):
        self._change_image(image_id, DB._SYSTEM_USER, status)

    #
    # User
    #

    @staticmethod
    def _hash_password(plain_text, salt):
        return hashlib.sha512((plain_text + salt).encode()).hexdigest()

    def get_users_list(self):
        self._cursor.execute("SELECT id, login FROM users")
        return self._cursor.fetchall()

    def check_login(self, login, plain_password):
        login = login.lower()
        self._cursor.execute("SELECT salt FROM users where login = ?", [login])
        salt = self._cursor.fetchone()
        if salt is None:
            return False
        salt = salt[0]

        password = self._hash_password(plain_password, salt)
        self._cursor.execute("SELECT count(id) FROM users where login = ? and password = ?", [login, password])
        return self._cursor.fetchone()[0] == 1

    def add_user(self, login, plain_password):
        login = login.lower()
        logger.info("Creating new user %s", login)
        salt = rnd_string(8)
        password = self._hash_password(plain_password, salt)
        data = (login, password, salt)
        self._cursor.execute("""
        INSERT INTO users
            (login, password, salt)
            VALUES (?, ?, ?)
        """, data)
        self._connection.commit()

    def get_user_id(self, login):
        login = login.lower()
        if login == DB._SYSTEM_USER:
            return None
        self._cursor.execute("SELECT id FROM users where login = ?", [login])
        result = self._cursor.fetchone()
        if result is None:
            return None
        else:
            return result[0]

    def update_password(self, login, new_plain_password):
        login = login.lower()
        logger.info("Updating user %s", login)
        salt = rnd_string(8)
        password = self._hash_password(new_plain_password, salt)
        self._cursor.execute("UPDATE users SET salt = ?, password = ? WHERE login = ?", [salt, password, login])
        self._connection.commit()


text:
/*
 * callback.h
 *
 * vi:set ts=4:
 */
#ifndef CALLBACK_H
#define CALLBACK_H

/*
 * Write data callback function (called within the context of
 * curl_easy_perform.
 * TODO: document parameters and return value
 */
size_t write_data(void *buffer, size_t size, size_t nmemb, void *userp);

#endif							/* CALLBACK_H */


text:
function mmala(model::Model, opts::MmalaOpts)
  mcmc = Array(Float64, opts.mcmc.nPostBurnin, model.nPars)
  z = Array(Float64, opts.mcmc.nPostBurnin, model.nPars)
  invGDerivG = Array(Float64, model.nPars, model.nPars, model.nPars)
  traceInvGDerivG = Array(Float64, model.nPars)
  currentSecondTerm = Array(Float64, model.nPars, model.nPars)
  proposedSecondTerm = Array(Float64, model.nPars, model.nPars)
  proposed, accepted = 0., 0.

  println("Running burn-in iterations...")

  currentPars = model.randPrior()
  currentLogPosterior = model.logPosterior(currentPars)
  currentGradLogPosterior = model.gradLogPosterior(currentPars)
  currentG = model.tensor(currentPars)
  currentInvG = inv(currentG)
  derivG = model.derivTensor(currentPars)
  currentFirstTerm = currentInvG*currentGradLogPosterior
  for i = 1:model.nPars
    invGDerivG[:, :, i] = currentInvG*derivG[:, :, i]
    traceInvGDerivG[i] = trace(invGDerivG[:, :, i])
    currentSecondTerm[:, i] = invGDerivG[:, :, i]*currentInvG[:, i]
  end
  currentThirdTerm = currentInvG*traceInvGDerivG
  driftStep = opts.setDriftStep(1, 0., opts.mcmc.n, opts.mcmc.nBurnin, 0.)

  for i = 1:opts.mcmc.n
    proposed += 1

    proposedPars = copy(currentPars)
    parameterMeans = (proposedPars+(driftStep/2)*currentFirstTerm
      -driftStep*sum(currentSecondTerm, 2)[:]+(driftStep/2)*currentThirdTerm)
    cholCurrentInvG = chol(driftStep*currentInvG)
    proposedPars = parameterMeans+cholCurrentInvG'*randn(model.nPars)
    proposedLogPosterior = model.logPosterior(proposedPars)
    probNewGivenOld = (-sum(log(diag(cholCurrentInvG)))
      -(0.5*(parameterMeans-proposedPars)'
      *(currentG/driftStep)*(parameterMeans-proposedPars))[1])
    proposedG = model.tensor(proposedPars)
    proposedInvG = inv(proposedG)
    proposedGradLogPosterior = model.gradLogPosterior(proposedPars)
    proposedFirstTerm = proposedInvG*proposedGradLogPosterior
    derivG = model.derivTensor(proposedPars)
    for j = 1:model.nPars
      invGDerivG[:, :, j] = proposedInvG*derivG[:, :, j]
      traceInvGDerivG[j] = trace(invGDerivG[:, :, j])
      proposedSecondTerm[:, j] = invGDerivG[:, :, j]*proposedInvG[:, j]
    end
    proposedThirdTerm = proposedInvG*traceInvGDerivG
    parameterMeans = (proposedPars+(driftStep/2)*proposedFirstTerm
      -driftStep*sum(proposedSecondTerm, 2)[:]+(driftStep/2)*proposedThirdTerm)
    probOldGivenNew =
      (-sum(log(diag(chol(driftStep*eye(model.nPars)*proposedInvG))))
      -(0.5*(parameterMeans-currentPars)'
      *(proposedG/driftStep)*(parameterMeans-currentPars))[1])

    ratio =
      proposedLogPosterior+probOldGivenNew-currentLogPosterior-probNewGivenOld

    if ratio > 0 || (ratio > log(rand()))
      accepted += 1

      currentPars = copy(proposedPars)
      currentLogPosterior = copy(proposedLogPosterior)
      currentGradLogPosterior = copy(proposedGradLogPosterior)
      currentG = copy(proposedG)
      currentInvG = copy(proposedInvG)
      currentFirstTerm = copy(proposedFirstTerm)
      currentSecondTerm = copy(proposedSecondTerm)
      currentThirdTerm = copy(proposedThirdTerm)
    end

    if i > opts.mcmc.nBurnin
      mcmc[i-opts.mcmc.nBurnin, :] = currentPars;
      z[i-opts.mcmc.nBurnin, :] = -currentGradLogPosterior/2;
    end

    if mod(i, opts.mcmc.monitorRate) == 0
      acceptanceRatio = accepted/proposed

    driftStep = opts.setDriftStep(i, acceptanceRatio, opts.mcmc.n,
      opts.mcmc.nBurnin, driftStep)

      println("Iteration $i of $(opts.mcmc.n): ", round(100*acceptanceRatio, 2),
        " % acceptance ratio")

      proposed, accepted = 0., 0.
    end

    if i == opts.mcmc.nBurnin
      println("Burn-in completed...\n\nRunning post burn-in MCMC...");
    end
  end

  return mcmc, z
end


text:
template <typename T>
class Vec{
public:
	Vec() :
		elements(nullptr), first_free(nullptr), cap(nullptr) { }
	Vec(std::initializer_list<T>);
	Vec(const Vec&);				// copy constructor func
	Vec& operator=(const Vec &);	// copy assignment func
	~Vec();							// destructor

	void push_back(const T&);
	size_t size() const { return first_free - elements; }
	size_t capacity() const { return cap - elements; }
	void reserve(size_t);
	T* begin() const { return elements; }
	T* end() const { return first_free; }
private:
	static std::allocator<std::string> alloc;
	// used by func that adds elements
	void chk_n_alloc()
	{
		if (size() == capacity()) reallocate();
	}
	// utility func used by copy control func
	std::pair<T*, T*>
		alloc_n_copy(const T*, const T*);
	void free();			// destroy elements and free memory
	void reallocate();		// allocate more memory and copy the elements
	T *elements;
	T *first_free;
	T *cap;
};

#endif


text:
package javax.xml.ws.soap;

import javax.xml.ws.WebServiceException;
import javax.xml.ws.WebServiceFeature;

public final class MTOMFeature extends WebServiceFeature {
    public static final String ID = "http://www.w3.org/2004/08/soap/features/http-optimization";

    protected int threshold;

    public MTOMFeature() {
        this(true, 0);
    }

    public MTOMFeature(boolean enabled) {
        this(enabled, 0);
    }

    public MTOMFeature(int threshold) {
        this(true, threshold);
    }

    public MTOMFeature(boolean enabled, int threshold) {
        super();

        //TODO NLS enable
        if (threshold < 0)
            throw new WebServiceException("MTOM threshold size cannot be less than zero. It was " + threshold);

        this.enabled   = enabled;
        this.threshold = threshold;
    }

    public int getThreshold() {
        return threshold;
    }

    @Override
    public String getID() {
        return ID;
    }
}


text:
module Azure::DataMigration::Mgmt::V2018_07_15_preview
  module Models
    #
    # Information of backup set
    #
    class BackupSetInfo

      include MsRestAzure

      # @return [String] Id for the set of backup files
      attr_accessor :backup_set_id

      # @return [String] First log sequence number of the backup file
      attr_accessor :first_lsn

      # @return [String] Last log sequence number of the backup file
      attr_accessor :last_lsn

      # @return [DateTime] Last modified time of the backup file in share
      # location
      attr_accessor :last_modified_time

      # @return [BackupType] Enum of the different backup types. Possible
      # values include: 'Database', 'TransactionLog', 'File',
      # 'DifferentialDatabase', 'DifferentialFile', 'Partial',
      # 'DifferentialPartial'
      attr_accessor :backup_type

      # @return [Array<BackupFileInfo>] List of files in the backup set
      attr_accessor :list_of_backup_files

      # @return [String] Name of the database to which the backup set belongs
      attr_accessor :database_name

      # @return [DateTime] Date and time that the backup operation began
      attr_accessor :backup_start_date

      # @return [DateTime] Date and time that the backup operation finished
      attr_accessor :backup_finished_date

      # @return [Boolean] Whether the backup set is restored or not
      attr_accessor :is_backup_restored

      #
      # Mapper for BackupSetInfo class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'BackupSetInfo',
          type: {
            name: 'Composite',
            class_name: 'BackupSetInfo',
            model_properties: {
              backup_set_id: {
                client_side_validation: true,
                required: false,
                serialized_name: 'backupSetId',
                type: {
                  name: 'String'
                }
              },
              first_lsn: {
                client_side_validation: true,
                required: false,
                serialized_name: 'firstLsn',
                type: {
                  name: 'String'
                }
              },
              last_lsn: {
                client_side_validation: true,
                required: false,
                serialized_name: 'lastLsn',
                type: {
                  name: 'String'
                }
              },
              last_modified_time: {
                client_side_validation: true,
                required: false,
                serialized_name: 'lastModifiedTime',
                type: {
                  name: 'DateTime'
                }
              },
              backup_type: {
                client_side_validation: true,
                required: false,
                serialized_name: 'backupType',
                type: {
                  name: 'String'
                }
              },
              list_of_backup_files: {
                client_side_validation: true,
                required: false,
                serialized_name: 'listOfBackupFiles',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'BackupFileInfoElementType',
                      type: {
                        name: 'Composite',
                        class_name: 'BackupFileInfo'
                      }
                  }
                }
              },
              database_name: {
                client_side_validation: true,
                required: false,
                serialized_name: 'databaseName',
                type: {
                  name: 'String'
                }
              },
              backup_start_date: {
                client_side_validation: true,
                required: false,
                serialized_name: 'backupStartDate',
                type: {
                  name: 'DateTime'
                }
              },
              backup_finished_date: {
                client_side_validation: true,
                required: false,
                serialized_name: 'backupFinishedDate',
                type: {
                  name: 'DateTime'
                }
              },
              is_backup_restored: {
                client_side_validation: true,
                required: false,
                serialized_name: 'isBackupRestored',
                type: {
                  name: 'Boolean'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
@interface QJTopMenuView : UIView

+ (instancetype)topMenuViewWithControllerView:(UIView *)controllView;

@end


text:
<?php
/**
 * Created by PhpStorm.
 * User: Angelo
 * Date: 18/11/2016
 * Time: 19:22
 */

namespace AppBundle\Controller;

use AppBundle\Manager\ManagerUser;
use AppBundle\Model\Partecipazione;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use AppBundle\Manager\ManagerPartecipazione;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class PartecipazioneController extends Controller
{

    /**
     * @Route("/partecipazioni/all",name="allPartecipazioni")
     * @Method("GET")
     */
    public function getAllPartecipazioni(){
        $manager = new ManagerPartecipazione();
        $risultati = $manager->getAll();
        if($risultati!=FALSE){
            $toReturn = "{\"partecipazioni\":[";
            foreach ($risultati as $s){
                $toReturn = $toReturn.$s.",";
            }
            $toReturn = $toReturn."]}";
            $re = new Response($toReturn);
            $re->headers->set('Content-type','application/json');
            return $re;
        }
        else {
            return new Response("Non ci sono elementi nella tabella partecipazioni",404);
        }
    }

    /**
     * @Route("/partecipazioni/bySquadra/{id}",name="getPartecipazioniBySquadra")
     * @Method("GET")
     */
    public function getPartecipazioniBySquadra($id){
        $manager = new ManagerPartecipazione();
        $risultato = $manager->getPartecipazioniBySquadra($id);
        if($risultato!=FALSE){
            $toReturn = "{\"partecipazione\":[";
            foreach ($risultato as $s)
                $toReturn = $toReturn . $s.",";

            $toReturn = $toReturn."]}";
            $re = new Response($toReturn);
            $re->headers->set('Content-type','application/json');
            return $re;
        } else {
            return new Response("La partecipazione con questo id squadra: ".$id." non esiste",404);
        }
    }

    /**
     * @Route("/partecipazioni/byId/{id}",name="getPartecipazioniById")
     * @Method("GET")
     */
    public function getPartecipazioniByID($id){
        $manager = new ManagerPartecipazione();
        $risultato = $manager->getPartecipazioneById($id);
        if($risultato!=FALSE){
            $re = new Response($risultato);
            $re->headers->set('Content-type','application/json');
            return $re;
        } else {
            return new Response("La partecipazione con questo id squadra: ".$id." non esiste",404);
        }
    }

    /**
     * @Route("/partecipazioni/inserisci",name="inserisciPart")
     * @Method("POST")
     */
    public function inserisciPartecipazione(Request $req){
        $manager = new ManagerPartecipazione();
        $part = new Partecipazione();
        $managerUser = new ManagerUser();
        if($managerUser->check($req->request->get("idSquadra"))) {
            $part->setIdSquadre($req->request->get("idSquadra"));
            $part->setPunteggio($req->request->get("punteggio"));
            $part->setVittorie($req->request->get("vittorie"));
            $part->setPareggi($req->request->get("pareggi"));
            $part->setSconfitte($req->request->get("sconfitte"));
            $part->setNomeTorneo($req->request->get("nomeTorneo"));
            $risultato = $manager->inserisciPartecipazione($part);
            if ($risultato != FALSE) {
                return new Response("Partecipazione inserita correttamente");
            } else {
                return new Response(" id squadra: " . $part->getIdSquadre() . " non esiste", 404);
            }
        } else {
            return new Response("non hai accesso a questa risorsa",404);
        }
    }

    /**
     * @Route("/partecipazioni/aggiorna",name="aggiornaPart")
     * @Method("POST")
     */
    public function aggiornaPartecipazione(Request $req){
        $manager = new ManagerPartecipazione();
        $part = new Partecipazione();
        $part->setIdPartecipazione($req->request->get("idPartecipazione"));
        $part->setNomeTorneo($req->request->get("nomeTorneo"));
        $part->setPunteggio($req->request->get("punteggio"));
        $part->setVittorie($req->request->get("vittorie"));
        $part->setPareggi($req->request->get("pareggi"));
        $part->setSconfitte($req->request->get("sconfitte"));
        $partDat = $manager->getPartecipazioneById($req->request->get("idPartecipazione"));
        if($partDat!=FALSE) {
            $managerUser = new ManagerUser();
            if($managerUser->check($partDat->getIdSquadre())) {
                $risultato = $manager->aggiornaPartecipazione($part);
                if ($risultato != FALSE) {
                    return new Response("Partecipazione modificata correttamente");
                } else {
                    return new Response("con questo id part: " . $part->getIdPartecipazione() . " non esiste", 404);
                }
            } else {
                return  new Response("non hai accesso a questa risorsa",404);
            }
        } else {
            return new Response("la risorsa non esiste", 404);
        }
    }

    /**
     * @Route("/partecipazioni/elimina",name="eliminaPart")
     * @Method("POST")
     */
    public function eliminaPartecipazione(Request $req){
        $manager = new ManagerPartecipazione();
        $part = new Partecipazione();
        $part->setIdPartecipazione($req->request->get("idPartecipazione"));
        $partDb = $manager->getPartecipazioneById($req->request->get("idPartecipazione"));
        if($partDb!=FALSE) {
            $managerUser = new ManagerUser();
            if($managerUser->check($partDb->getIdSquadre())) {
                $risultato = $manager->eliminaPartecipazione($part);
                if ($risultato != FALSE) {
                    return new Response("Partecipazione eliminata correttamente");
                } else {
                    return new Response("Questo id partecipazione non esiste", 404);
                }
            } else {
                return new Response("non hai accesso a questa risorsa",404);
            }
        } else {
            return new Response("la risorsa non esiste", 404);
        }
    }

}


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">
<meta charset="utf-8">
<title>Zend AMF API Documentation » \Zend_Server_Reflection_Parameter</title>
<meta name="author" content="Mike van Riel">
<meta name="description" content="">
<link href="../css/template.css" rel="stylesheet" media="all">
<link rel="shortcut icon" href="../img/favicon.ico">
<link rel="apple-touch-icon" href="../img/apple-touch-icon.png">
<link rel="apple-touch-icon" sizes="72x72" href="../img/apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="114x114" href="../img/apple-touch-icon-114x114.png">

Zend AMF API Documentation

                                    API Documentation

Packages

 Zend

 Zend_Amf

 Zend_Auth

 Zend_Date

 Zend_Loader

 Zend_Server

 Zend_Session

 Zend_Version

                                    Reports

 Errors
                77

 Markers

 Deprecated elements
                5

Back to top

                            Javascript is disabled; several features are only available
                            if Javascript is enabled.

<button class="btn public active" title="Show public elements">Public</button><button class="btn protected" title="Show protected elements">Protected</button><button class="btn private" title="Show private elements">Private</button><button class="btn inherited active" title="Show inherited elements">Inherited</button>

<button class="btn details" title="Show descriptions and method names"></button><button class="btn simple" title="Show only method names"></button>

 Methods

Proxy reflection calls
__call()

Constructor
__construct()

Retrieve parameter description
getDescription()

Return parameter position
getPosition()

Retrieve parameter type
getType()

Set parameter description
setDescription()

Set parameter position
setPosition()

Set parameter type
setType()

 Properties

» Protected

$_description

$_position

$_reflection

$_type

\

\Zend_Server_Reflection_Parameter

Parameter Reflection

Decorates a ReflectionParameter to allow setting the parameter type

category
Zend

package
Zend_Server

subpackage
Reflection

copyright
Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)

license
New BSD License

version
$Id$

 Methods

Proxy reflection calls

__call(string $method, array $args) : mixed

Parameters

$method

string

$args

array

Returns

mixed

Constructor

__construct(\ReflectionParameter $r, string $type = 'mixed', string $description = '')

Parameters

$r

\ReflectionParameter

$type

string
Parameter type

$description

string
Parameter description

Retrieve parameter description

getDescription() : string

Returns

string

Return parameter position

getPosition() : integer

Returns

integer

Retrieve parameter type

getType() : string

Returns

string

Set parameter description

setDescription(string|null $description) : void

Parameters

$description

stringnull

Set parameter position

setPosition(integer $index) : void

Parameters

$index

integer

Set parameter type

setType(string|null $type) : void

Parameters

$type

stringnull

 Properties

Parameter description

$_description : string

Default

Parameter position

$_position : integer

Default

$_reflection

$_reflection : \ReflectionParameter

Default

Parameter type

$_type : string

Default

            Template is built using Twitter Bootstrap 2 and icons provided by Glyphicons.

            Documentation is powered by phpDocumentor 2.8.5 and

            generated on 2015-11-23T12:38:54-06:00.