text:
package com.amazonaws.services.cloudsearchv2.model;

import java.io.Serializable;

/**
 *

 * Configuration information for an analysis scheme. Each analysis scheme
 * has a unique name and specifies the language of the text to be
 * processed. The following options can be configured for an analysis
 * scheme: Synonyms ,
 * Stopwords ,
 * StemmingDictionary ,
 * JapaneseTokenizationDictionary and
 * AlgorithmicStemming .
 *

 */
public class AnalysisScheme implements Serializable, Cloneable {

    /**
     * Names must begin with a letter and can contain the following
     * characters: a-z (lowercase), 0-9, and _ (underscore).
     *

     * Constraints:

     * Length: 1 - 64

     * Pattern: [a-z][a-z0-9_]*

     */
    private String analysisSchemeName;

    /**
     * An IETF
     * RFC 4646 language code or mul for multiple languages.
     *

     * Constraints:

     * Allowed Values: ar, bg, ca, cs, da, de, el, en, es, eu, fa, fi, fr, ga, gl, he, hi, hu, hy, id, it, ja, ko, lv, mul, nl, no, pt, ro, ru, sv, th, tr, zh-Hans, zh-Hant
     */
    private String analysisSchemeLanguage;

    /**
     * Synonyms, stopwords, and stemming options for an analysis scheme.
     * Includes tokenization dictionary for Japanese.
     */
    private AnalysisOptions analysisOptions;

    /**
     * Names must begin with a letter and can contain the following
     * characters: a-z (lowercase), 0-9, and _ (underscore).
     *

     * Constraints:

     * Length: 1 - 64

     * Pattern: [a-z][a-z0-9_]*

     *
     * @return Names must begin with a letter and can contain the following
     *         characters: a-z (lowercase), 0-9, and _ (underscore).
     */
    public String getAnalysisSchemeName() {
        return analysisSchemeName;
    }

    /**
     * Names must begin with a letter and can contain the following
     * characters: a-z (lowercase), 0-9, and _ (underscore).
     *

     * Constraints:

     * Length: 1 - 64

     * Pattern: [a-z][a-z0-9_]*

     *
     * @param analysisSchemeName Names must begin with a letter and can contain the following
     *         characters: a-z (lowercase), 0-9, and _ (underscore).
     */
    public void setAnalysisSchemeName(String analysisSchemeName) {
        this.analysisSchemeName = analysisSchemeName;
    }

    /**
     * Names must begin with a letter and can contain the following
     * characters: a-z (lowercase), 0-9, and _ (underscore).
     *

     * Returns a reference to this object so that method calls can be chained together.
     *

     * Constraints:

     * Length: 1 - 64

     * Pattern: [a-z][a-z0-9_]*

     *
     * @param analysisSchemeName Names must begin with a letter and can contain the following
     *         characters: a-z (lowercase), 0-9, and _ (underscore).
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public AnalysisScheme withAnalysisSchemeName(String analysisSchemeName) {
        this.analysisSchemeName = analysisSchemeName;
        return this;
    }

    /**
     * An IETF
     * RFC 4646 language code or mul for multiple languages.
     *

     * Constraints:

     * Allowed Values: ar, bg, ca, cs, da, de, el, en, es, eu, fa, fi, fr, ga, gl, he, hi, hu, hy, id, it, ja, ko, lv, mul, nl, no, pt, ro, ru, sv, th, tr, zh-Hans, zh-Hant
     *
     * @return An IETF
     *         RFC 4646 language code or mul for multiple languages.
     *
     * @see AnalysisSchemeLanguage
     */
    public String getAnalysisSchemeLanguage() {
        return analysisSchemeLanguage;
    }

    /**
     * An IETF
     * RFC 4646 language code or mul for multiple languages.
     *

     * Constraints:

     * Allowed Values: ar, bg, ca, cs, da, de, el, en, es, eu, fa, fi, fr, ga, gl, he, hi, hu, hy, id, it, ja, ko, lv, mul, nl, no, pt, ro, ru, sv, th, tr, zh-Hans, zh-Hant
     *
     * @param analysisSchemeLanguage An IETF
     *         RFC 4646 language code or mul for multiple languages.
     *
     * @see AnalysisSchemeLanguage
     */
    public void setAnalysisSchemeLanguage(String analysisSchemeLanguage) {
        this.analysisSchemeLanguage = analysisSchemeLanguage;
    }

    /**
     * An IETF
     * RFC 4646 language code or mul for multiple languages.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *

     * Constraints:

     * Allowed Values: ar, bg, ca, cs, da, de, el, en, es, eu, fa, fi, fr, ga, gl, he, hi, hu, hy, id, it, ja, ko, lv, mul, nl, no, pt, ro, ru, sv, th, tr, zh-Hans, zh-Hant
     *
     * @param analysisSchemeLanguage An IETF
     *         RFC 4646 language code or mul for multiple languages.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     *
     * @see AnalysisSchemeLanguage
     */
    public AnalysisScheme withAnalysisSchemeLanguage(String analysisSchemeLanguage) {
        this.analysisSchemeLanguage = analysisSchemeLanguage;
        return this;
    }

    /**
     * An IETF
     * RFC 4646 language code or mul for multiple languages.
     *

     * Constraints:

     * Allowed Values: ar, bg, ca, cs, da, de, el, en, es, eu, fa, fi, fr, ga, gl, he, hi, hu, hy, id, it, ja, ko, lv, mul, nl, no, pt, ro, ru, sv, th, tr, zh-Hans, zh-Hant
     *
     * @param analysisSchemeLanguage An IETF
     *         RFC 4646 language code or mul for multiple languages.
     *
     * @see AnalysisSchemeLanguage
     */
    public void setAnalysisSchemeLanguage(AnalysisSchemeLanguage analysisSchemeLanguage) {
        this.analysisSchemeLanguage = analysisSchemeLanguage.toString();
    }

    /**
     * An IETF
     * RFC 4646 language code or mul for multiple languages.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *

     * Constraints:

     * Allowed Values: ar, bg, ca, cs, da, de, el, en, es, eu, fa, fi, fr, ga, gl, he, hi, hu, hy, id, it, ja, ko, lv, mul, nl, no, pt, ro, ru, sv, th, tr, zh-Hans, zh-Hant
     *
     * @param analysisSchemeLanguage An IETF
     *         RFC 4646 language code or mul for multiple languages.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     *
     * @see AnalysisSchemeLanguage
     */
    public AnalysisScheme withAnalysisSchemeLanguage(AnalysisSchemeLanguage analysisSchemeLanguage) {
        this.analysisSchemeLanguage = analysisSchemeLanguage.toString();
        return this;
    }

    /**
     * Synonyms, stopwords, and stemming options for an analysis scheme.
     * Includes tokenization dictionary for Japanese.
     *
     * @return Synonyms, stopwords, and stemming options for an analysis scheme.
     *         Includes tokenization dictionary for Japanese.
     */
    public AnalysisOptions getAnalysisOptions() {
        return analysisOptions;
    }

    /**
     * Synonyms, stopwords, and stemming options for an analysis scheme.
     * Includes tokenization dictionary for Japanese.
     *
     * @param analysisOptions Synonyms, stopwords, and stemming options for an analysis scheme.
     *         Includes tokenization dictionary for Japanese.
     */
    public void setAnalysisOptions(AnalysisOptions analysisOptions) {
        this.analysisOptions = analysisOptions;
    }

    /**
     * Synonyms, stopwords, and stemming options for an analysis scheme.
     * Includes tokenization dictionary for Japanese.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param analysisOptions Synonyms, stopwords, and stemming options for an analysis scheme.
     *         Includes tokenization dictionary for Japanese.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public AnalysisScheme withAnalysisOptions(AnalysisOptions analysisOptions) {
        this.analysisOptions = analysisOptions;
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getAnalysisSchemeName() != null) sb.append("AnalysisSchemeName: " + getAnalysisSchemeName() + ",");
        if (getAnalysisSchemeLanguage() != null) sb.append("AnalysisSchemeLanguage: " + getAnalysisSchemeLanguage() + ",");
        if (getAnalysisOptions() != null) sb.append("AnalysisOptions: " + getAnalysisOptions() );
        sb.append("}");
        return sb.toString();
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getAnalysisSchemeName() == null) ? 0 : getAnalysisSchemeName().hashCode());
        hashCode = prime * hashCode + ((getAnalysisSchemeLanguage() == null) ? 0 : getAnalysisSchemeLanguage().hashCode());
        hashCode = prime * hashCode + ((getAnalysisOptions() == null) ? 0 : getAnalysisOptions().hashCode());
        return hashCode;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null) return false;

        if (obj instanceof AnalysisScheme == false) return false;
        AnalysisScheme other = (AnalysisScheme)obj;

        if (other.getAnalysisSchemeName() == null ^ this.getAnalysisSchemeName() == null) return false;
        if (other.getAnalysisSchemeName() != null && other.getAnalysisSchemeName().equals(this.getAnalysisSchemeName()) == false) return false;
        if (other.getAnalysisSchemeLanguage() == null ^ this.getAnalysisSchemeLanguage() == null) return false;
        if (other.getAnalysisSchemeLanguage() != null && other.getAnalysisSchemeLanguage().equals(this.getAnalysisSchemeLanguage()) == false) return false;
        if (other.getAnalysisOptions() == null ^ this.getAnalysisOptions() == null) return false;
        if (other.getAnalysisOptions() != null && other.getAnalysisOptions().equals(this.getAnalysisOptions()) == false) return false;
        return true;
    }

    @Override
    public AnalysisScheme clone() {
        try {
            return (AnalysisScheme) super.clone();

        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException(
                    "Got a CloneNotSupportedException from Object.clone() "
                    + "even though we're Cloneable!",
                    e);
        }

    }

}


text:
import * as i0 from '@angular/core';
import * as i10 from '@angular/material/snack-bar';
import * as i6 from '@angular/forms';
import * as i7 from '@angular/material/button';
import * as i8 from '@angular/material/input';
import * as i9 from '@angular/material/select';
import { MatSnackBar } from '@angular/material/snack-bar';
import { MatSnackBarConfig } from '@angular/material/snack-bar';
import { MatSnackBarHorizontalPosition } from '@angular/material/snack-bar';
import { MatSnackBarRef } from '@angular/material/snack-bar';
import { MatSnackBarVerticalPosition } from '@angular/material/snack-bar';
import { TextOnlySnackBar } from '@angular/material/snack-bar';

declare namespace i1 {
    export {
        SnackBarComponentExample,
        PizzaPartyComponent
    }
}

declare namespace i2 {
    export {
        SnackBarHarnessExample
    }
}

declare namespace i3 {
    export {
        SnackBarOverviewExample
    }
}

declare namespace i4 {
    export {
        SnackBarPositionExample
    }
}

declare namespace i5 {
    export {
        SnackBarAnnotatedComponentExample,
        PizzaPartyAnnotatedComponent
    }
}

export declare class PizzaPartyAnnotatedComponent {
    snackBarRef: MatSnackBarRef<any>;
    static ɵfac: i0.ɵɵFactoryDeclaration<PizzaPartyAnnotatedComponent, never>;
    static ɵcmp: i0.ɵɵComponentDeclaration<PizzaPartyAnnotatedComponent, "snack-bar-annotated-component-example-snack", never, {}, {}, never, never, false, never>;
}

export declare class PizzaPartyComponent {
    static ɵfac: i0.ɵɵFactoryDeclaration<PizzaPartyComponent, never>;
    static ɵcmp: i0.ɵɵComponentDeclaration<PizzaPartyComponent, "snack-bar-component-example-snack", never, {}, {}, never, never, false, never>;
}

/**
 * @title Snack-bar with an annotated custom component
 */
export declare class SnackBarAnnotatedComponentExample {
    private _snackBar;
    durationInSeconds: number;
    constructor(_snackBar: MatSnackBar);
    openSnackBar(): void;
    static ɵfac: i0.ɵɵFactoryDeclaration<SnackBarAnnotatedComponentExample, never>;
    static ɵcmp: i0.ɵɵComponentDeclaration<SnackBarAnnotatedComponentExample, "snack-bar-annotated-component-example", never, {}, {}, never, never, false, never>;
}

/**
 * @title Snack-bar with a custom component
 */
export declare class SnackBarComponentExample {
    private _snackBar;
    durationInSeconds: number;
    constructor(_snackBar: MatSnackBar);
    openSnackBar(): void;
    static ɵfac: i0.ɵɵFactoryDeclaration<SnackBarComponentExample, never>;
    static ɵcmp: i0.ɵɵComponentDeclaration<SnackBarComponentExample, "snack-bar-component-example", never, {}, {}, never, never, false, never>;
}

export declare class SnackBarExamplesModule {
    static ɵfac: i0.ɵɵFactoryDeclaration<SnackBarExamplesModule, never>;
    static ɵmod: i0.ɵɵNgModuleDeclaration<SnackBarExamplesModule, [typeof i1.SnackBarComponentExample, typeof i2.SnackBarHarnessExample, typeof i3.SnackBarOverviewExample, typeof i4.SnackBarPositionExample, typeof i5.SnackBarAnnotatedComponentExample, typeof i1.PizzaPartyComponent, typeof i5.PizzaPartyAnnotatedComponent], [typeof i6.FormsModule, typeof i7.MatButtonModule, typeof i8.MatInputModule, typeof i9.MatSelectModule, typeof i10.MatSnackBarModule], [typeof i1.SnackBarComponentExample, typeof i2.SnackBarHarnessExample, typeof i3.SnackBarOverviewExample, typeof i4.SnackBarPositionExample, typeof i5.SnackBarAnnotatedComponentExample]>;
    static ɵinj: i0.ɵɵInjectorDeclaration<SnackBarExamplesModule>;
}

/**
 * @title Testing with MatSnackBarHarness
 */
export declare class SnackBarHarnessExample {
    readonly snackBar: MatSnackBar;
    constructor(snackBar: MatSnackBar);
    open(message: string, action?: string, config?: MatSnackBarConfig): MatSnackBarRef<TextOnlySnackBar>;
    static ɵfac: i0.ɵɵFactoryDeclaration<SnackBarHarnessExample, never>;
    static ɵcmp: i0.ɵɵComponentDeclaration<SnackBarHarnessExample, "snack-bar-harness-example", never, {}, {}, never, never, false, never>;
}

/**
 * @title Basic snack-bar
 */
export declare class SnackBarOverviewExample {
    private _snackBar;
    constructor(_snackBar: MatSnackBar);
    openSnackBar(message: string, action: string): void;
    static ɵfac: i0.ɵɵFactoryDeclaration<SnackBarOverviewExample, never>;
    static ɵcmp: i0.ɵɵComponentDeclaration<SnackBarOverviewExample, "snack-bar-overview-example", never, {}, {}, never, never, false, never>;
}

/**
 * @title Snack-bar with configurable position
 */
export declare class SnackBarPositionExample {
    private _snackBar;
    horizontalPosition: MatSnackBarHorizontalPosition;
    verticalPosition: MatSnackBarVerticalPosition;
    constructor(_snackBar: MatSnackBar);
    openSnackBar(): void;
    static ɵfac: i0.ɵɵFactoryDeclaration<SnackBarPositionExample, never>;
    static ɵcmp: i0.ɵɵComponentDeclaration<SnackBarPositionExample, "snack-bar-position-example", never, {}, {}, never, never, false, never>;
}

export { }

redpajama_set_name: RedPajamaGithub


text:
import { LayerCollectionLoadedAction, ShowAllLayers } from '../actions/layers.actions';
import { ILayerState, initialLayersState, LayersReducer } from './layers.reducer';
import { ILayer, layerPluginTypeEnum, LayerType } from '../models/layers.model';

describe('LayersReducer', () => {

	it('LAYER_COLLECTION_LOADED action should add the new layers to the state', () => {
		let staticLayer: ILayer = {
			url: 'fakeStaticUrl',
			id: 'staticLayerId',
			name: 'staticLayer',
			type: LayerType.annotation,
			creationTime: new Date(),
			layerPluginType: layerPluginTypeEnum.Annotations
		};

		let action: LayerCollectionLoadedAction = new LayerCollectionLoadedAction([staticLayer]);

		let result: ILayerState = LayersReducer(initialLayersState, action);
		expect(result.ids).toEqual(['staticLayerId']);
	});

	it('SHOW_ALL_LAYERS action should check all layers in the layers collection', () => {
		const layersState: ILayerState = {
			...initialLayersState,
			selectedLayersIds: ['staticLayerId2'],
			entities: <any>{
				'annotations': {
					id: 'annotations',
					type: LayerType.annotation
				},
				'annotations1': {
					id: 'annotations1',
					type: LayerType.annotation
				},
				'staticLayerId': {
					id: 'staticLayerId',
					type: LayerType.static
				},
				'staticLayerId2': {
					id: 'staticLayerId2',
					type: LayerType.static
				}
			},
			ids: ['annotations', 'annotations1', 'staticLayerId', 'staticLayerId2']
		};

		let action = new ShowAllLayers(LayerType.annotation);
		let result: ILayerState = LayersReducer(layersState, action);
		['annotations', 'annotations1', 'staticLayerId2'].forEach((id) => {
			expect(result.selectedLayersIds).toContain(id);
		});
	});

});


text:
#ifndef SkSVGCircle_DEFINED
#define SkSVGCircle_DEFINED

#include "experimental/svg/model/SkSVGShape.h"
#include "experimental/svg/model/SkSVGTypes.h"

struct SkPoint;

class SkSVGCircle final : public SkSVGShape {
public:
    ~SkSVGCircle() override = default;
    static sk_sp<SkSVGCircle> Make() { return sk_sp<SkSVGCircle>(new SkSVGCircle()); }

    void setCx(const SkSVGLength&);
    void setCy(const SkSVGLength&);
    void setR(const SkSVGLength&);

protected:
    void onSetAttribute(SkSVGAttribute, const SkSVGValue&) override;

    void onDraw(SkCanvas*, const SkSVGLengthContext&, const SkPaint&,
                SkPath::FillType) const override;

    SkPath onAsPath(const SkSVGRenderContext&) const override;

private:
    SkSVGCircle();

    // resolve and return the center and radius values
    std::tuple<SkPoint, SkScalar> resolve(const SkSVGLengthContext&) const;

    SkSVGLength fCx = SkSVGLength(0);
    SkSVGLength fCy = SkSVGLength(0);
    SkSVGLength fR  = SkSVGLength(0);

    typedef SkSVGShape INHERITED;
};

#endif // SkSVGCircle_DEFINED


text:
    <button
        onClick="sticker_actions.share_comment(2001, {{ comment.id }})"
        class="dismiss share share_facebook">
    </button><button
        onClick="sticker_actions.share_comment(2002, {{ comment.id }})"
        class="dismiss share share_twitter">
    </button><button
        onClick="sticker_actions.share_comment(2004, {{ comment.id }})"
        class="dismiss share share_tumblr">
    </button>


text:
#import <Foundation/Foundation.h>
#import "CDAPDFReaderDocument.h"
#import "CDAPDFReaderOrientationLayout.h"
@protocol CDAPdfReaderDelegateProtocol;

@protocol CDAPdfReaderProtocol <NSObject>

@property (nonatomic, weak) NSObject<CDAPdfReaderDelegateProtocol> *readerDelegate;

@property (nonatomic, strong) CDAPDFReaderDocument *readerDocument;
/**
 *  The orientation layout supported by the reader.
 *
 *  CDAPDFReaderOrientationLayoutPortrait           -> Portrait
 *
 *  CDAPDFReaderOrientationLayoutLandscape          -> Landscape
 *
 *
 *  Values can be combined, so can support several layouts at the same time
 *  @code
 *  orientationLayout = CDAPDFReaderOrientationLayoutPortrait | CDAPDFReaderOrientationLayoutLandscape;
 *  @endcode
 */
@property (nonatomic, assign) CDAPDFReaderOrientationLayout orientationLayout;

/// The current page index starting from 0, or NSNotFound in case no page is shown
@property (nonatomic, assign) NSUInteger currentPageIndex;

/**
 *  Specify the PDF document to be displayed
 *
 *  @param pdfDocumentPath Absolute path of the PDF document
 */
- (void) setDocumentPath:(NSString *)pdfDocumentPath;

/**
 *  Specify a group of CGPDFPageRef to be shown as a normal PDF document, even if they exist just in memory.
 *
 *  @param pdfPagesRef An array of CGPDFPageRef
 */
- (void) setPDFPagesRef:(NSArray *)pdfPagesRef;

/// Indicate whether the Reader supports the Portrait orientation layout or not
- (BOOL) isPortraitLayoutSupported;
/// Indicate whether the Reader supports the Landscape orientation layout or not
- (BOOL) isLandscapeLayoutSupported;

@end

@protocol CDAPdfReaderDelegateProtocol <NSObject>
- (void) CDAPdfReader:(UIViewController<CDAPdfReaderProtocol>*)pdfReader didChangeToPageIndex:(NSInteger)pageIndex;
@end


text:
import datetime

import mock
from oslo_utils import timeutils
import six

from heat.common import exception
from heat.common import template_format
from heat.engine import scheduler
from heat.tests.autoscaling import inline_templates
from heat.tests import common
from heat.tests import utils

as_template = inline_templates.as_template
as_params = inline_templates.as_params

class TestAutoScalingPolicy(common.HeatTestCase):
    def setUp(self):
        super(TestAutoScalingPolicy, self).setUp()

    def create_scaling_policy(self, t, stack, resource_name):
        rsrc = stack[resource_name]
        self.assertIsNone(rsrc.validate())
        scheduler.TaskRunner(rsrc.create)()
        self.assertEqual((rsrc.CREATE, rsrc.COMPLETE), rsrc.state)
        return rsrc

    def test_validate_scaling_policy_ok(self):
        t = template_format.parse(inline_templates.as_template)
        t['Resources']['WebServerScaleUpPolicy']['Properties'][
            'ScalingAdjustment'] = 33
        t['Resources']['WebServerScaleUpPolicy']['Properties'][
            'AdjustmentType'] = 'PercentChangeInCapacity'
        t['Resources']['WebServerScaleUpPolicy']['Properties'][
            'MinAdjustmentStep'] = 2
        stack = utils.parse_stack(t, params=as_params)
        self.policy = stack['WebServerScaleUpPolicy']
        self.assertIsNone(self.policy.validate())

    def test_validate_scaling_policy_error(self):
        t = template_format.parse(inline_templates.as_template)
        t['Resources']['WebServerScaleUpPolicy']['Properties'][
            'ScalingAdjustment'] = 1
        t['Resources']['WebServerScaleUpPolicy']['Properties'][
            'AdjustmentType'] = 'ChangeInCapacity'
        t['Resources']['WebServerScaleUpPolicy']['Properties'][
            'MinAdjustmentStep'] = 2
        stack = utils.parse_stack(t, params=as_params)
        self.policy = stack['WebServerScaleUpPolicy']
        ex = self.assertRaises(exception.ResourcePropertyValueDependency,
                               self.policy.validate)
        self.assertIn('MinAdjustmentStep property should only '
                      'be specified for AdjustmentType with '
                      'value PercentChangeInCapacity.', six.text_type(ex))

    def test_scaling_policy_bad_group(self):
        t = template_format.parse(inline_templates.as_template_bad_group)
        stack = utils.parse_stack(t, params=as_params)

        up_policy = self.create_scaling_policy(t, stack,
                                               'WebServerScaleUpPolicy')

        ex = self.assertRaises(exception.ResourceFailure, up_policy.signal)
        self.assertIn('Alarm WebServerScaleUpPolicy could '
                      'not find scaling group', six.text_type(ex))

    def test_scaling_policy_not_alarm_state(self):
        """If the details don't have 'alarm' then don't progress."""
        t = template_format.parse(as_template)
        stack = utils.parse_stack(t, params=as_params)
        pol = self.create_scaling_policy(t, stack, 'WebServerScaleUpPolicy')

        test = {'current': 'not_an_alarm'}
        with mock.patch.object(pol, '_cooldown_inprogress',
                               side_effect=AssertionError()) as dont_call:
            self.assertRaises(exception.NoActionRequired,
                              pol.handle_signal, details=test)
            self.assertEqual([], dont_call.call_args_list)

    def test_scaling_policy_cooldown_toosoon(self):
        """If _cooldown_inprogress() returns True don't progress."""
        t = template_format.parse(as_template)
        stack = utils.parse_stack(t, params=as_params)
        pol = self.create_scaling_policy(t, stack, 'WebServerScaleUpPolicy')
        test = {'current': 'alarm'}

        with mock.patch.object(pol.stack, 'resource_by_refid',
                               side_effect=AssertionError) as dont_call:
            with mock.patch.object(pol, '_cooldown_inprogress',
                                   return_value=True) as mock_cip:
                self.assertRaises(exception.NoActionRequired,
                                  pol.handle_signal, details=test)
                mock_cip.assert_called_once_with()
            self.assertEqual([], dont_call.call_args_list)

    def test_scaling_policy_cooldown_ok(self):
        t = template_format.parse(as_template)
        stack = utils.parse_stack(t, params=as_params)
        pol = self.create_scaling_policy(t, stack, 'WebServerScaleUpPolicy')
        test = {'current': 'alarm'}

        group = self.patchobject(pol.stack, 'resource_by_refid').return_value
        group.name = 'fluffy'
        with mock.patch.object(pol, '_cooldown_inprogress',
                               return_value=False) as mock_cip:
            pol.handle_signal(details=test)
            mock_cip.assert_called_once_with()
        group.adjust.assert_called_once_with(1, 'ChangeInCapacity', None,
                                             signal=True)

class TestCooldownMixin(common.HeatTestCase):
    def setUp(self):
        super(TestCooldownMixin, self).setUp()

    def create_scaling_policy(self, t, stack, resource_name):
        rsrc = stack[resource_name]
        self.assertIsNone(rsrc.validate())
        scheduler.TaskRunner(rsrc.create)()
        self.assertEqual((rsrc.CREATE, rsrc.COMPLETE), rsrc.state)
        return rsrc

    def test_cooldown_is_in_progress_toosoon(self):
        t = template_format.parse(as_template)
        stack = utils.parse_stack(t, params=as_params)
        pol = self.create_scaling_policy(t, stack, 'WebServerScaleUpPolicy')

        now = timeutils.utcnow()
        previous_meta = {'cooldown': {
            now.isoformat(): 'ChangeInCapacity : 1'}}
        self.patchobject(pol, 'metadata_get', return_value=previous_meta)
        self.assertTrue(pol._cooldown_inprogress())

    def test_cooldown_is_in_progress_scaling_unfinished(self):
        t = template_format.parse(as_template)
        stack = utils.parse_stack(t, params=as_params)
        pol = self.create_scaling_policy(t, stack, 'WebServerScaleUpPolicy')

        previous_meta = {'scaling_in_progress': True}
        self.patchobject(pol, 'metadata_get', return_value=previous_meta)
        self.assertTrue(pol._cooldown_inprogress())

    def test_cooldown_not_in_progress(self):
        t = template_format.parse(as_template)
        stack = utils.parse_stack(t, params=as_params)
        pol = self.create_scaling_policy(t, stack, 'WebServerScaleUpPolicy')

        awhile_ago = timeutils.utcnow() - datetime.timedelta(seconds=100)
        previous_meta = {
            'cooldown': {
                awhile_ago.isoformat(): 'ChangeInCapacity : 1'
            },
            'scaling_in_progress': False
        }
        self.patchobject(pol, 'metadata_get', return_value=previous_meta)
        self.assertFalse(pol._cooldown_inprogress())

    def test_scaling_policy_cooldown_zero(self):
        t = template_format.parse(as_template)

        # Create the scaling policy (with Cooldown=0) and scale up one
        properties = t['Resources']['WebServerScaleUpPolicy']['Properties']
        properties['Cooldown'] = '0'

        stack = utils.parse_stack(t, params=as_params)
        pol = self.create_scaling_policy(t, stack, 'WebServerScaleUpPolicy')

        now = timeutils.utcnow()
        previous_meta = {now.isoformat(): 'ChangeInCapacity : 1'}
        self.patchobject(pol, 'metadata_get', return_value=previous_meta)
        self.assertFalse(pol._cooldown_inprogress())

    def test_scaling_policy_cooldown_none(self):
        t = template_format.parse(as_template)

        # Create the scaling policy no Cooldown property, should behave the
        # same as when Cooldown==0
        properties = t['Resources']['WebServerScaleUpPolicy']['Properties']
        del properties['Cooldown']

        stack = utils.parse_stack(t, params=as_params)
        pol = self.create_scaling_policy(t, stack, 'WebServerScaleUpPolicy')

        now = timeutils.utcnow()
        previous_meta = {now.isoformat(): 'ChangeInCapacity : 1'}
        self.patchobject(pol, 'metadata_get', return_value=previous_meta)
        self.assertFalse(pol._cooldown_inprogress())

    def test_metadata_is_written(self):
        t = template_format.parse(as_template)
        stack = utils.parse_stack(t, params=as_params)
        pol = self.create_scaling_policy(t, stack, 'WebServerScaleUpPolicy')

        nowish = timeutils.utcnow()
        reason = 'cool as'
        meta_set = self.patchobject(pol, 'metadata_set')
        self.patchobject(timeutils, 'utcnow', return_value=nowish)
        pol._cooldown_timestamp(reason)
        meta_set.assert_called_once_with(
            {'cooldown': {nowish.isoformat(): reason},
             'scaling_in_progress': False})

class ScalingPolicyAttrTest(common.HeatTestCase):
    def setUp(self):
        super(ScalingPolicyAttrTest, self).setUp()
        t = template_format.parse(as_template)
        self.stack = utils.parse_stack(t, params=as_params)
        self.policy = self.stack['WebServerScaleUpPolicy']
        self.assertIsNone(self.policy.validate())
        scheduler.TaskRunner(self.policy.create)()
        self.assertEqual((self.policy.CREATE, self.policy.COMPLETE),
                         self.policy.state)

    def test_alarm_attribute(self):
        self.assertIn("WebServerScaleUpPolicy",
                      self.policy.FnGetAtt('AlarmUrl'))


text:
// This is a project skeleton file

import java.io.PrintStream;
import java.util.Vector;
import java.util.Enumeration;

/** This class is used for representing the inheritance tree during code
    generation. You will need to fill in some of its methods and
    potentially extend it in other useful ways. */
class CgenClassTable extends SymbolTable {

    /** All classes in the program, represented as CgenNode */
    private Vector nds;

    /** This is the stream to which assembly instructions are output */
    private PrintStream str;

    private int stringclasstag;
    private int intclasstag;
    private int boolclasstag;

    // The following methods emit code for constants and global
    // declarations.

    /** Emits code to start the .data segment and to
     * declare the global names.
     * */
    private void codeGlobalData() {
	// The following global names must be defined first.

	str.print("\t.data\n" + CgenSupport.ALIGN);
	str.println(CgenSupport.GLOBAL + CgenSupport.CLASSNAMETAB);
	str.print(CgenSupport.GLOBAL);
	CgenSupport.emitProtObjRef(TreeConstants.Main, str);
	str.println("");
	str.print(CgenSupport.GLOBAL);
	CgenSupport.emitProtObjRef(TreeConstants.Int, str);
	str.println("");
	str.print(CgenSupport.GLOBAL);
	CgenSupport.emitProtObjRef(TreeConstants.Str, str);
	str.println("");
	str.print(CgenSupport.GLOBAL);
	BoolConst.falsebool.codeRef(str);
	str.println("");
	str.print(CgenSupport.GLOBAL);
	BoolConst.truebool.codeRef(str);
	str.println("");
	str.println(CgenSupport.GLOBAL + CgenSupport.INTTAG);
	str.println(CgenSupport.GLOBAL + CgenSupport.BOOLTAG);
	str.println(CgenSupport.GLOBAL + CgenSupport.STRINGTAG);

	// We also need to know the tag of the Int, String, and Bool classes
	// during code generation.

	str.println(CgenSupport.INTTAG + CgenSupport.LABEL
		    + CgenSupport.WORD + intclasstag);
	str.println(CgenSupport.BOOLTAG + CgenSupport.LABEL
		    + CgenSupport.WORD + boolclasstag);
	str.println(CgenSupport.STRINGTAG + CgenSupport.LABEL
		    + CgenSupport.WORD + stringclasstag);

    }

    /** Emits code to start the .text segment and to
     * declare the global names.
     * */
    private void codeGlobalText() {
	str.println(CgenSupport.GLOBAL + CgenSupport.HEAP_START);
	str.print(CgenSupport.HEAP_START + CgenSupport.LABEL);
	str.println(CgenSupport.WORD + 0);
	str.println("\t.text");
	str.print(CgenSupport.GLOBAL);
	CgenSupport.emitInitRef(TreeConstants.Main, str);
	str.println("");
	str.print(CgenSupport.GLOBAL);
	CgenSupport.emitInitRef(TreeConstants.Int, str);
	str.println("");
	str.print(CgenSupport.GLOBAL);
	CgenSupport.emitInitRef(TreeConstants.Str, str);
	str.println("");
	str.print(CgenSupport.GLOBAL);
	CgenSupport.emitInitRef(TreeConstants.Bool, str);
	str.println("");
	str.print(CgenSupport.GLOBAL);
	CgenSupport.emitMethodRef(TreeConstants.Main, TreeConstants.main_meth, str);
	str.println("");
    }

    /** Emits code definitions for boolean constants. */
    private void codeBools(int classtag) {
	BoolConst.falsebool.codeDef(classtag, str);
	BoolConst.truebool.codeDef(classtag, str);
    }

    /** Generates GC choice constants (pointers to GC functions) */
    private void codeSelectGc() {
	str.println(CgenSupport.GLOBAL + "_MemMgr_INITIALIZER");
	str.println("_MemMgr_INITIALIZER:");
	str.println(CgenSupport.WORD
		    + CgenSupport.gcInitNames[Flags.cgen_Memmgr]);

	str.println(CgenSupport.GLOBAL + "_MemMgr_COLLECTOR");
	str.println("_MemMgr_COLLECTOR:");
	str.println(CgenSupport.WORD
		    + CgenSupport.gcCollectNames[Flags.cgen_Memmgr]);

	str.println(CgenSupport.GLOBAL + "_MemMgr_TEST");
	str.println("_MemMgr_TEST:");
	str.println(CgenSupport.WORD
		    + ((Flags.cgen_Memmgr_Test == Flags.GC_TEST) ? "1" : "0"));
    }

    /** Emits code to reserve space for and initialize all of the
     * constants.  Class names should have been added to the string
     * table (in the supplied code, is is done during the construction
     * of the inheritance graph), and code for emitting string constants
     * as a side effect adds the string's length to the integer table.
     * The constants are emmitted by running through the stringtable and
     * inttable and producing code for each entry. */
    private void codeConstants() {
	// Add constants that are required by the code generator.
	AbstractTable.stringtable.addString("");
	AbstractTable.inttable.addString("0");

	AbstractTable.stringtable.codeStringTable(stringclasstag, str);
	AbstractTable.inttable.codeStringTable(intclasstag, str);
	codeBools(boolclasstag);
    }

    /** Creates data structures representing basic Cool classes (Object,
     * IO, Int, Bool, String).  Please note: as is this method does not
     * do anything useful; you will need to edit it to make if do what
     * you want.
     * */
    private void installBasicClasses() {
	AbstractSymbol filename
	    = AbstractTable.stringtable.addString("<basic class>");

	// A few special class names are installed in the lookup table
	// but not the class list.  Thus, these classes exist, but are
	// not part of the inheritance hierarchy.  No_class serves as
	// the parent of Object and the other special classes.
	// SELF_TYPE is the self class; it cannot be redefined or
	// inherited.  prim_slot is a class known to the code generator.

	addId(TreeConstants.No_class,
	      new CgenNode(new class_c(0,
				      TreeConstants.No_class,
				      TreeConstants.No_class,
				      new Features(0),
				      filename),
			   CgenNode.Basic, this));

	addId(TreeConstants.SELF_TYPE,
	      new CgenNode(new class_c(0,
				      TreeConstants.SELF_TYPE,
				      TreeConstants.No_class,
				      new Features(0),
				      filename),
			   CgenNode.Basic, this));

	addId(TreeConstants.prim_slot,
	      new CgenNode(new class_c(0,
				      TreeConstants.prim_slot,
				      TreeConstants.No_class,
				      new Features(0),
				      filename),
			   CgenNode.Basic, this));

	// The Object class has no parent class. Its methods are
	//        cool_abort() : Object    aborts the program
	//        type_name() : Str        returns a string representation
	//                                 of class name
	//        copy() : SELF_TYPE       returns a copy of the object

	class_c Object_class =
	    new class_c(0,
		       TreeConstants.Object_,
		       TreeConstants.No_class,
		       new Features(0)
			   .appendElement(new method(0,
					      TreeConstants.cool_abort,
					      new Formals(0),
					      TreeConstants.Object_,
					      new no_expr(0)))
			   .appendElement(new method(0,
					      TreeConstants.type_name,
					      new Formals(0),
					      TreeConstants.Str,
					      new no_expr(0)))
			   .appendElement(new method(0,
					      TreeConstants.copy,
					      new Formals(0),
					      TreeConstants.SELF_TYPE,
					      new no_expr(0))),
		       filename);

	installClass(new CgenNode(Object_class, CgenNode.Basic, this));

	// The IO class inherits from Object. Its methods are
	//        out_string(Str) : SELF_TYPE  writes a string to the output
	//        out_int(Int) : SELF_TYPE      "    an int    "  "     "
	//        in_string() : Str            reads a string from the input
	//        in_int() : Int                "   an int     "  "     "

	class_c IO_class =
	    new class_c(0,
		       TreeConstants.IO,
		       TreeConstants.Object_,
		       new Features(0)
			   .appendElement(new method(0,
					      TreeConstants.out_string,
					      new Formals(0)
						  .appendElement(new formalc(0,
								     TreeConstants.arg,
								     TreeConstants.Str)),
					      TreeConstants.SELF_TYPE,
					      new no_expr(0)))
			   .appendElement(new method(0,
					      TreeConstants.out_int,
					      new Formals(0)
						  .appendElement(new formalc(0,
								     TreeConstants.arg,
								     TreeConstants.Int)),
					      TreeConstants.SELF_TYPE,
					      new no_expr(0)))
			   .appendElement(new method(0,
					      TreeConstants.in_string,
					      new Formals(0),
					      TreeConstants.Str,
					      new no_expr(0)))
			   .appendElement(new method(0,
					      TreeConstants.in_int,
					      new Formals(0),
					      TreeConstants.Int,
					      new no_expr(0))),
		       filename);

	CgenNode IO_node = new CgenNode(IO_class, CgenNode.Basic, this);
	installClass(IO_node);

	// The Int class has no methods and only a single attribute, the
	// "val" for the integer.

	class_c Int_class =
	    new class_c(0,
		       TreeConstants.Int,
		       TreeConstants.Object_,
		       new Features(0)
			   .appendElement(new attr(0,
					    TreeConstants.val,
					    TreeConstants.prim_slot,
					    new no_expr(0))),
		       filename);

	installClass(new CgenNode(Int_class, CgenNode.Basic, this));

	// Bool also has only the "val" slot.
	class_c Bool_class =
	    new class_c(0,
		       TreeConstants.Bool,
		       TreeConstants.Object_,
		       new Features(0)
			   .appendElement(new attr(0,
					    TreeConstants.val,
					    TreeConstants.prim_slot,
					    new no_expr(0))),
		       filename);

	installClass(new CgenNode(Bool_class, CgenNode.Basic, this));

	// The class Str has a number of slots and operations:
	//       val                              the length of the string
	//       str_field                        the string itself
	//       length() : Int                   returns length of the string
	//       concat(arg: Str) : Str           performs string concatenation
	//       substr(arg: Int, arg2: Int): Str substring selection

	class_c Str_class =
	    new class_c(0,
		       TreeConstants.Str,
		       TreeConstants.Object_,
		       new Features(0)
			   .appendElement(new attr(0,
					    TreeConstants.val,
					    TreeConstants.Int,
					    new no_expr(0)))
			   .appendElement(new attr(0,
					    TreeConstants.str_field,
					    TreeConstants.prim_slot,
					    new no_expr(0)))
			   .appendElement(new method(0,
					      TreeConstants.length,
					      new Formals(0),
					      TreeConstants.Int,
					      new no_expr(0)))
			   .appendElement(new method(0,
					      TreeConstants.concat,
					      new Formals(0)
						  .appendElement(new formalc(0,
								     TreeConstants.arg,
								     TreeConstants.Str)),
					      TreeConstants.Str,
					      new no_expr(0)))
			   .appendElement(new method(0,
					      TreeConstants.substr,
					      new Formals(0)
						  .appendElement(new formalc(0,
								     TreeConstants.arg,
								     TreeConstants.Int))
						  .appendElement(new formalc(0,
								     TreeConstants.arg2,
								     TreeConstants.Int)),
					      TreeConstants.Str,
					      new no_expr(0))),
		       filename);

	installClass(new CgenNode(Str_class, CgenNode.Basic, this));
    }

    // The following creates an inheritance graph from
    // a list of classes.  The graph is implemented as
    // a tree of `CgenNode', and class names are placed
    // in the base class symbol table.

    private void installClass(CgenNode nd) {
	AbstractSymbol name = nd.getName();
	if (probe(name) != null) return;
	nds.addElement(nd);
	addId(name, nd);
    }

    private void installClasses(Classes cs) {
        for (Enumeration e = cs.getElements(); e.hasMoreElements(); ) {
	    installClass(new CgenNode((Class_)e.nextElement(),
				       CgenNode.NotBasic, this));
        }
    }

    private void buildInheritanceTree() {
	for (Enumeration e = nds.elements(); e.hasMoreElements(); ) {
	    setRelations((CgenNode)e.nextElement());
	}
    }

    private void setRelations(CgenNode nd) {
	CgenNode parent = (CgenNode)probe(nd.getParent());
	nd.setParentNd(parent);
	parent.addChild(nd);
    }

    /** Constructs a new class table and invokes the code generator */
    public CgenClassTable(Classes cls, PrintStream str) {
	nds = new Vector();

	this.str = str;

	stringclasstag = 0 /* Change to your String class tag here */;
	intclasstag =    0 /* Change to your Int class tag here */;
	boolclasstag =   0 /* Change to your Bool class tag here */;

	enterScope();
	if (Flags.cgen_debug) System.out.println("Building CgenClassTable");

	installBasicClasses();
	installClasses(cls);
	buildInheritanceTree();

	code();

	exitScope();
    }

    /** This method is the meat of the code generator.  It is to be
        filled in programming assignment 5 */
    public void code() {
	if (Flags.cgen_debug) System.out.println("coding global data");
	codeGlobalData();

	if (Flags.cgen_debug) System.out.println("choosing gc");
	codeSelectGc();

	if (Flags.cgen_debug) System.out.println("coding constants");
	codeConstants();

	//                 Add your code to emit
	//                   - prototype objects
	//                   - class_nameTab
	//                   - dispatch tables

	if (Flags.cgen_debug) System.out.println("coding global text");
	codeGlobalText();

	//                 Add your code to emit
	//                   - object initializer
	//                   - the class methods
	//                   - etc...
    }

    /** Gets the root of the inheritance tree */
    public CgenNode root() {
	return (CgenNode)probe(TreeConstants.Object_);
    }
}


text:
<?php

namespace CommonBundle\Repository;

/**
 * MembershipRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class MembershipRepository extends \Doctrine\ORM\EntityRepository
{
    public function findMaxByMember($member){

        $result = $this->createQueryBuilder('ms')
            ->select('MAX(ms.beginDate)')
            ->where('ms.member= :member')
            ->setParameter('member', $member)
            ->getQuery()
            ->getSingleResult();

        return $result;
    }

}


text:
local yui_path = (...):match('(.-)[^%.]+$')
local Object = require(yui_path .. 'UI.classic.classic')
local Tabs = Object:extend('Tabs')

function Tabs:new(yui, settings)
    self.yui = yui
    self.size = settings.size or 20
    self.name = settings.name
    self.x, self.y = 0, 0
    self.tabs = settings.tabs
    self.font = love.graphics.newFont(self.yui.Theme.open_sans_semibold, math.floor(self.size*0.7))
    self.hover_font = love.graphics.newFont(self.yui.Theme.open_sans_light, math.floor(math.max(self.size, 40)*0.4))
    local tabs_w = 0
    self.h = self.font:getHeight() + math.floor(self.size*0.7)
    self.selected_tab = settings.selected_tab or 1
    self.buttons = {}
    for i, tab in ipairs(self.tabs) do
        local w = self.font:getWidth(tab.text) + self.size
        tabs_w = tabs_w + w
        local button = self.yui.UI.Button(0, 0, w, self.h, {
            yui = self.yui,
            extensions = {self.yui.Theme.TabButton},
            parent = self,
            hover = tab.hover,
            text = tab.text,
            i = i,
        })
        table.insert(self.buttons, button)
        self[i] = button
        if tab.name then self[tab.name] = button end
    end
    self.w = tabs_w
end

function Tabs:update(dt)
    local w = 0
    for i, button in ipairs(self.buttons) do
        if i == 1 then
            button.x, button.y = self.x, self.y
            w = w + button.w
        else
            button.x, button.y = self.x + w, self.y
            w = w + button.w
        end
        if button.hot and button.pressed then
            self.selected_tab = i
            if self.tabs[i].onClick then
                self.tabs[i]:onClick()
            end
        end
        button:update(dt)
        if button.hot then love.mouse.setCursor(self.yui.Theme.hand_cursor) end
    end
end

function Tabs:draw()
    for _, button in ipairs(self.buttons) do button:draw() end
end

return Tabs


text:
package org.perftester.git

import java.io.File

import ammonite.ops.Path
import org.eclipse.jgit.api.ResetCommand.ResetType
import org.eclipse.jgit.api.{Git, ListBranchCommand}
import org.eclipse.jgit.internal.storage.file.FileRepository
import org.eclipse.jgit.lib.AnyObjectId
import org.eclipse.jgit.revwalk.RevCommit
import org.eclipse.jgit.transport.RemoteConfig

import scala.annotation.tailrec
import scala.collection.JavaConverters._
import scala.collection.mutable.ListBuffer

object WalkerApp extends App {
  for (commit <- GitUtils("s:\\scala\\dan\\scala1").branchRevisions("refs/remotes/scala/2.12.x",
                                                                    "refs/heads/2.12.x_flag")) {
    println(s"${commit.getName} ${commit.getShortMessage} ${commit.getCommitterIdent.getName}")
  }
}

object GitUtils {
  def apply(repoPath: File): GitUtils = {
    if (!repoPath.exists()) {
      throw new IllegalStateException(s"git repo does not exist - $repoPath")
    }

    if (!repoPath.toString.endsWith(".git"))
      apply(new File(repoPath, ".git"))
    else new GitUtils(repoPath)
  }

  def apply(repoPath: Path): GitUtils = GitUtils(repoPath.toIO)

  def apply(repoPath: String): GitUtils = GitUtils(new File(repoPath))
}

class GitUtils private (repoPath: File) {
  println(s"using git in repo $repoPath")
  val repository = new FileRepository(repoPath)

  val git = new Git(repository)

  def branches = {
    git.branchList.setListMode(ListBranchCommand.ListMode.ALL).call.asScala.toList
  }

  def dispose(): Unit = git.close()

  def resolveBranch(msg: String, branchSpec: String) = {
    val res = repository.resolve(branchSpec)
    if (res eq null) throw new IllegalStateException(s"cannot resolve $branchSpec - $msg")
    res
  }

  def branchRevisions(baseBranch: String, myBranch: String): List[RevCommit] = {
    val bases = git.log.add(resolveBranch("base", baseBranch)).call.asScala.toSet

    val it            = git.log.add(resolveBranch("branch", myBranch)).call.iterator.asScala
    val resultBuilder = ListBuffer[RevCommit]()

    @tailrec def add(): List[RevCommit] = {
      if (!it.hasNext) throw new Exception("no common commit")
      val next = it.next()
      resultBuilder += next
      if (!bases.contains(next)) add()
      else resultBuilder.result()
    }

    add().reverse
  }

  def remotes: Map[String, RemoteConfig] =
    git
      .remoteList()
      .call()
      .asScala
      .map {
        case remote => remote.getName -> remote
      }(collection.breakOut)

  def fetchAll(): Unit = {
    remotes.values foreach fetch
  }

  def fetch(remote: String): Unit = {
    fetch(remotes(remote))
  }

  def fetch(remote: RemoteConfig): Unit = {
    println(s"fetching ${remote.getName}")
    git
      .fetch()
      .setRemoveDeletedRefs(true) // -prune
      .setRemote(remote.getName)
      .setRefSpecs(remote.getFetchRefSpecs)
      .setDryRun(false)
      .setCheckFetchedObjects(true)
      .call()
  }

  def resetToRevision(rev: String): Unit = {
    println(s"resetting to $rev")
    git
      .reset()
      .setMode(ResetType.HARD)
      .setRef(rev)
      .call()
  }

  def cherryPick(sha: String): Unit = cherryPick(repository.resolve(sha))

  def cherryPick(sha: AnyObjectId): Unit = {
    println(s"cherry-pick $sha")
    git
      .cherryPick()
      .include(sha)
      .call()
  }
}


text:
class ImagesController < ApplicationController
  include NewRelic::Agent::Instrumentation::ControllerInstrumentation
  include CarrierWave::MiniMagick

  before_filter :authenticate_user!

  # GET /images
  def index
    @images = Image.find(:all)
  end

  # GET /images/1
  def show
    @image = Image.find(params[:id])
  end

  # GET /images/new
  def new
    @image = Image.new
  end

  # POST /images
  def create
    if params[:image]
      imageObj = Hash.new
      imageObj["project_id"]=params[:project_id].to_f
      imageObj["step_id"]=params[:step_id].to_f
      imageObj["saved"]=false
      imageObj["user_id"]=params[:user_id].to_f
      s3_image_url = params[:image][:image_path]
      Rails.logger.debug("s3_image_url: #{s3_image_url}")
      image_url = s3_image_url.gsub('%2F', '/')
      imageObj["s3_filepath"] = image_url
      @image = Image.new(imageObj)
      authorize! :create, @image
      @image.save
      # now that the temp image is saved, set the image path url
      @image.delay.upload_image
    else # image sent from android app
      imageObj = Hash.new
      imageObj["project_id"]=params[:project_id]
      imageObj["step_id"]=params[:step_id]
      imageObj["saved"]=false
      imageObj["image_path"]=params[:image_path]
      imageObj["user_id"]=params[:user_id]
      @image = Image.create(imageObj)
    end

    if @image.step_id != -1
      # adding image to existing step
      num_step_images = Step.find(@image.step_id).images.count
    else
      num_step_images =  Project.find(@image.project_id).images.where("step_id = ? AND user_id = ?", -1, @image.user_id).count
    end

    @image.update_attributes(:position => num_step_images-1)

    # update the corresponding project
    @image.project.touch

    respond_to do |format|
      if request.format.xhr?
        format.js
      else
        image_info = @image.id, @image.s3_filepath
        format.html{ render :json => image_info.to_json}
        format.js { render :json => image_info.to_json}
        format.xml { render :json => image_info.to_json}
      end
    end

  end

  # GET /images/1/edit
  def edit
    @image = Image.find(params[:id])
  end

  # rotate an image 90 degrees counter clockwise
  def rotate
    @image = Image.find(params[:id])
    @rotation = params[:rotation]
    if @rotation == "8"
      @rotation = 270
    end
    @image.update_column(:rotation, @rotation)
    respond_to do |format|
       format.js { render :nothing => true }
    end
  end

  # PUT /images/1
  def update
    @image = Image.find(params[:id])
    @project = @image.project_id
    @step = @image.step_id
    @position = Step.find_by_id(@step).position

      if @image.update_attributes(params[:image])
        redirect_to edit_project_step_url(@project, @position), notice: "image was successfully updated."
      else
        render :edit
      end
  end

  # DELETE /images/1
  def destroy
    if(params[:s3_filepath])
      # cleaned_filepath = params[:s3_filepath].gsub('%2F', '/').gsub(" ", "+")
      # @image = Image.where(:s3_filepath => cleaned_filepath).first
      @image = Image.where(:s3_filepath => params[:s3_filepath]).first
    else
      @image = Image.find(params[:id])
      authorize! :destroy, @image

      # delete any references to this image
      if !@image.is_remix_image?
        @image.remix_images.each do |image|
          if image.has_video?
            image.video.destroy
          end
          image.destroy
        end
      end

      if @image.step_id != -1
        if @image.position < @image.step.images.count
          @image.step.images.order(:position).where("position > ?", @image.position).each do |image|
            Rails.logger.debug "image position before: #{image.position}"
              image.update_attributes(:position => image.position-1)
            Rails.logger.debug "image position after: #{image.position}"
          end
        end
      else
        remix_images = @image.project.images.where(:step_id=>-1)
        if @image.position < remix_images.count
          remix_images.order(:position).where("position > ? ", @image.position).each do |image|
            image.update_attributes(:position=> image.position-1)
          end
        end
      end

      # set project to new unlisted if necessary
      if @image.project.images.count == 0
        @image.project.update_attributes(:privacy => nil)
      end
    end

    # destroy original image
    @image.destroy

    respond_to do |format|
      format.js {render :nothing => true}
    end
  end

   # Sorts images
  def sort
    params[:image].each_with_index do |id, index|
      Image.update_all({position: index}, {id: id})
    end
    render nothing: true
  end

  # finds the id of an image based on the s3 path url
  def find_image_id
    s3_url = params[:s3_url]
    image = Image.where("s3_filepath = ? ", s3_url).first
    if image != nil
      Rails.logger.debug("image.id : #{image.id}")
    end
    respond_to do |format|
      format.js {
        if image != nil
          render :json => image.id
        else
          render :nothing => true
        end
      }
    end
  end

  # export images
  def export
    image = Image.find(:params[:id])
    send_file(image.image_path_url, :type => 'image/jpeg')
  end

end


text:
#pragma once

#include <map>
#include "common/common.h"
#include "serialise/streamio.h"
#include "serialise/zstdio.h"

static const uint32_t ShaderCacheMagic = MAKE_FOURCC('R', 'D', '$', '$');

template <typename ResultType, typename ShaderCallbacks>
bool LoadShaderCache(const rdcstr &filename, const uint32_t magicNumber, const uint32_t versionNumber,
                     std::map<uint32_t, ResultType> &resultCache, const ShaderCallbacks &callbacks)
{
  rdcstr shadercache = FileIO::GetAppFolderFilename(filename);

  StreamReader fileReader(FileIO::fopen(shadercache, FileIO::ReadBinary));

  uint32_t globalMagic = 0, localMagic = 0, version = 0;
  fileReader.Read(globalMagic);
  fileReader.Read(localMagic);
  fileReader.Read(version);

  if(globalMagic != ShaderCacheMagic || localMagic != magicNumber || version != versionNumber)
    return false;

  uint64_t uncompressedSize = 0;
  fileReader.Read(uncompressedSize);

  // header has been read. The rest is zstd compressed
  StreamReader compressedReader(new ZSTDDecompressor(&fileReader, Ownership::Nothing),
                                uncompressedSize, Ownership::Stream);

  uint32_t numentries = 0;
  compressedReader.Read(numentries);

  bool ret = true;
  bytebuf data;

  for(uint32_t i = 0; i < numentries; i++)
  {
    uint32_t hash = 0, length = 0;
    compressedReader.Read(hash);
    compressedReader.Read(length);

    data.resize(length);
    compressedReader.Read(data.data(), length);

    ResultType result;
    bool created = callbacks.Create(length, data.data(), &result);

    if(!created)
    {
      RDCERR("Couldn't create blob of size %u from shadercache", length);
      ret = false;
      break;
    }

    resultCache[hash] = result;
  }

  return ret && !compressedReader.IsErrored() && !fileReader.IsErrored();
}

template <typename ResultType, typename ShaderCallbacks>
void SaveShaderCache(const rdcstr &filename, uint32_t magicNumber, uint32_t versionNumber,
                     const std::map<uint32_t, ResultType> &cache, const ShaderCallbacks &callbacks)
{
  rdcstr shadercache = FileIO::GetAppFolderFilename(filename);

  FILE *f = FileIO::fopen(shadercache, FileIO::WriteBinary);

  if(!f)
  {
    RDCERR("Error opening shader cache for write");
    return;
  }

  StreamWriter fileWriter(f, Ownership::Stream);

  fileWriter.Write(ShaderCacheMagic);
  fileWriter.Write(magicNumber);
  fileWriter.Write(versionNumber);

  uint32_t numentries = (uint32_t)cache.size();

  uint64_t uncompressedSize = sizeof(numentries);    // number of entries

  // hash + length + data for each entry
  for(auto it = cache.begin(); it != cache.end(); ++it)
    uncompressedSize += sizeof(uint32_t) * 2 + callbacks.GetSize(it->second);

  fileWriter.Write(uncompressedSize);

  StreamWriter compressedWriter(new ZSTDCompressor(&fileWriter, Ownership::Nothing),
                                Ownership::Stream);

  compressedWriter.Write(numentries);

  for(auto it = cache.begin(); it != cache.end(); ++it)
  {
    uint32_t hash = it->first;
    uint32_t len = callbacks.GetSize(it->second);
    const byte *data = callbacks.GetData(it->second);

    compressedWriter.Write(hash);
    compressedWriter.Write(len);
    compressedWriter.Write(data, len);

    callbacks.Destroy(it->second);
  }

  compressedWriter.Finish();

  RDCDEBUG("Successfully wrote %u entries to cache, compressed from %llu to %llu", numentries,
           uncompressedSize, fileWriter.GetOffset());
}


text:
#pragma once

#include <stdbool.h>
#include <stddef.h>

#include "api.h"

typedef struct fun_map fun_map_t;
struct fun_allocator;

FUN_API fun_map_t *fun_map_create(size_t key_size, size_t value_size, size_t (*hash)(const void *key),
        bool (*are_equal)(const void *x, const void *y));

FUN_API fun_map_t *fun_map_create_with_allocator(size_t key_size, size_t value_size, size_t (*hash)(const void *key),
        bool (*are_equal)(const void *x, const void *y), struct fun_allocator *allocator);

FUN_API void *fun_map_insert(fun_map_t *handle, const void *key, const void *value);

FUN_API void *fun_map_try_insert(fun_map_t *handle, const void *key, const void *value, bool *did_insert);

FUN_API void *fun_map_insert_uninit(fun_map_t *handle, const void *key);

FUN_API void *fun_map_find(fun_map_t *handle, const void *key);

FUN_API int fun_map_remove(fun_map_t *handle, const void *key);

FUN_API int fun_map_find_and_remove(fun_map_t *handle, const void *key, void *value);

FUN_API void fun_map_clear(fun_map_t *handle);

FUN_API void fun_map_destroy(fun_map_t *handle);

FUN_API fun_map_t *fun_map_copy(fun_map_t *handle);

FUN_API struct fun_allocator *fun_map_allocator(fun_map_t *handle);


text:
layout: post
title: Jekyll-hilmi
date: 2017-01-01 21:20:00
homepage: https://github.com/nix1947/jekyll-hilmi
download: https://github.com/nix1947/jekyll-hilmi/archive/master.zip
demo: http://nix1947.github.io/jekyll-hilmi
author: Manoj Gautam
thumbnail: jekyll-hilmi.png
license: MIT License
license_link: https://github.com/nix1947/jekyll-hilmi/blob/master/LICENSE.md
---

Jekyll-hilmi is the minimalist theme for clean blogging. It used google
oxygen fonts and plain HTML.


text:
<?php
/**
 * Map View Content
 * The content template for the map view of events. This template is also used for
 * the response that is returned on map view ajax requests.
 *
 * Override this template in your own theme by creating a file at [your-theme]/tribe-events/map/content.php
 *
 * @package TribeEventsCalendar
 * @since  3.0
 * @author Modern Tribe Inc.
 *
 */

if ( !defined('ABSPATH') ) { die('-1'); } ?>

	<?php do_action( 'tribe_events_before_the_title' ); ?>

<?php echo tribe_get_events_title(); ?>

		<?php do_action( 'tribe_events_after_the_title' ); ?>

		<?php tribe_events_the_notices() ?>

		<?php do_action( 'tribe_events_before_header' ); ?>
		<div id="tribe-events-header" <?php tribe_events_the_header_attributes() ?>>

			<?php do_action( 'tribe_events_before_header_nav' ); ?>
			<?php tribe_get_template_part( 'pro/map/nav', 'header' ); ?>
			<?php do_action( 'tribe_events_after_header_nav' ); ?>

		<?php do_action( 'tribe_events_after_header' ); ?>

		<?php if ( have_posts() ) : ?>
			<?php do_action( 'tribe_events_before_loop' ); ?>

			<?php tribe_get_template_part( 'pro/map/loop' ) ?>

			<?php do_action( 'tribe_events_after_loop' ); ?>
		<?php endif; ?>

		<?php do_action( 'tribe_events_before_footer' ); ?>

			<?php do_action( 'tribe_events_before_footer_nav' ); ?>
			<?php tribe_get_template_part( 'pro/map/nav', 'footer' ); ?>
			<?php do_action( 'tribe_events_after_footer_nav' ); ?>

		<?php do_action( 'tribe_events_after_footer' ) ?>


text:
module RunInIsolation
  DEFAULT_TIMEOUT = 5

  def run_in_isolation(timeout: DEFAULT_TIMEOUT, &block)
    read, write = IO.pipe

    @fork_pid = fork do
      # use a custom failure notifier to forward errors back to the
      # testing process. This could also be done with rescue but as
      # rspec provides a clean way of doing this we should definitely
      # use it.
      RSpec::Support.failure_notifier = Proc.new  do |failure, _opts|
        write_result_to_buffer(write, timeout) { failure }
      end
      read.close
      write_result_to_buffer(write, timeout, &block)
    end

    write.close
    result_str = wait_for_buffer(read, @fork_pid, timeout)

    result = result_str == '' ? nil : Marshal.load(result_str)
    return result if result.is_a?(SystemExit) # without this it kills the parent process. :(
    raise(result) if result.is_a?(Exception)
    result
  end

  def forked_process_ended?
    Process.getpgid(@fork_pid)
    false
  rescue Errno::ESRCH
    true
  end

  def write_result_to_buffer(buffer, timeout, &block)
    result =  begin
        Timeout.timeout(timeout) do # timeout in the forked process as this will make testing cleaner
          block.call
        end
      rescue Exception => e
        e
      end
    Marshal.dump(result, buffer)
    exit!(0) # skips exit handlers.
  end

  def wait_for_buffer(buffer, pid, timeout)
    result = nil
    begin
      Timeout.timeout(timeout + 1) do # larger timeout in the local processor just in case the child dies/zombies
        result = buffer.read
        Process.wait(pid)
      end
    rescue Timeout::Error
      Process.kill('TERM', pid)
      raise
    end
    result
  end
end

RSpec.configure do |config|
  config.include RunInIsolation
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>P-Index</title>
<meta name="date" content="2017-12-20">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D J L M O P V

P

paint(Graphics) - Method in class main.java.xyz.mllnd.javapaint.JavaPaint

"Paints" the points on the frame

PaintButton - Class in main.java.xyz.mllnd.javapaint

PaintButton(JavaPaint, String, String) - Constructor for class main.java.xyz.mllnd.javapaint.PaintButton

PaintObject - Class in main.java.xyz.mllnd.javapaint

PaintObject(int, Color) - Constructor for class main.java.xyz.mllnd.javapaint.PaintObject

A B C D J L M O P V

Skip navigation links

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
package org.elasticsearch.xpack.security.authc.service;

import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.support.PlainActionFuture;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.xpack.core.security.action.service.TokenInfo.TokenSource;
import org.elasticsearch.xpack.security.authc.service.ServiceAccountTokenStore.StoreAuthenticationResult;
import org.junit.Before;
import org.mockito.Mockito;

import java.util.List;
import java.util.concurrent.ExecutionException;

import static org.hamcrest.Matchers.is;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;

public class CompositeServiceAccountTokenStoreTests extends ESTestCase {

    private ThreadContext threadContext;
    private ServiceAccountTokenStore store1;
    private ServiceAccountTokenStore store2;
    private ServiceAccountTokenStore store3;
    private CompositeServiceAccountTokenStore compositeStore;

    @Before
    public void init() {
        threadContext = new ThreadContext(Settings.EMPTY);
        store1 = mock(ServiceAccountTokenStore.class);
        store2 = mock(ServiceAccountTokenStore.class);
        store3 = mock(ServiceAccountTokenStore.class);
        compositeStore = new CompositeServiceAccountTokenStore(List.of(store1, store2, store3), threadContext);
    }

    public void testAuthenticate() throws ExecutionException, InterruptedException {
        Mockito.reset(store1, store2, store3);

        final ServiceAccountToken token = mock(ServiceAccountToken.class);
        final boolean store1Success = randomBoolean();
        final boolean store2Success = randomBoolean();
        final boolean store3Success = randomBoolean();
        final TokenSource tokenSource = randomFrom(TokenSource.values());

        doAnswer(invocationOnMock -> {
            @SuppressWarnings("unchecked")
            final ActionListener<StoreAuthenticationResult> listener = (ActionListener<StoreAuthenticationResult>) invocationOnMock
                .getArguments()[1];
            listener.onResponse(new StoreAuthenticationResult(store1Success, tokenSource));
            return null;
        }).when(store1).authenticate(eq(token), any());

        doAnswer(invocationOnMock -> {
            @SuppressWarnings("unchecked")
            final ActionListener<StoreAuthenticationResult> listener = (ActionListener<StoreAuthenticationResult>) invocationOnMock
                .getArguments()[1];
            listener.onResponse(new StoreAuthenticationResult(store2Success, tokenSource));
            return null;
        }).when(store2).authenticate(eq(token), any());

        doAnswer(invocationOnMock -> {
            @SuppressWarnings("unchecked")
            final ActionListener<StoreAuthenticationResult> listener = (ActionListener<StoreAuthenticationResult>) invocationOnMock
                .getArguments()[1];
            listener.onResponse(new StoreAuthenticationResult(store3Success, tokenSource));
            return null;
        }).when(store3).authenticate(eq(token), any());

        final PlainActionFuture<StoreAuthenticationResult> future = new PlainActionFuture<>();
        compositeStore.authenticate(token, future);
        if (store1Success || store2Success || store3Success) {
            assertThat(future.get().isSuccess(), is(true));
            assertThat(future.get().getTokenSource(), is(tokenSource));
            if (store1Success) {
                verify(store1).authenticate(eq(token), any());
                verifyNoMoreInteractions(store2);
                verifyNoMoreInteractions(store3);
            } else if (store2Success) {
                verify(store1).authenticate(eq(token), any());
                verify(store2).authenticate(eq(token), any());
                verifyNoMoreInteractions(store3);
            } else {
                verify(store1).authenticate(eq(token), any());
                verify(store2).authenticate(eq(token), any());
                verify(store3).authenticate(eq(token), any());
            }
        } else {
            assertThat(future.get().isSuccess(), is(false));
            assertThat(future.get().getTokenSource(), is(tokenSource));
            verify(store1).authenticate(eq(token), any());
            verify(store2).authenticate(eq(token), any());
            verify(store3).authenticate(eq(token), any());
        }
    }
}


text:
namespace Loopstream
{
    partial class UI_Winpeck
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.label1 = new System.Windows.Forms.Label();
            this.SuspendLayout();
            //
            // label1
            //
            this.label1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.label1.Location = new System.Drawing.Point(0, 0);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(545, 176);
            this.label1.TabIndex = 0;
            this.label1.Text = "Click me first!\r\n\r\nThen, click the window you\r\nwant Loopstream to target.";
            this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.label1.Click += new System.EventHandler(this.label1_Click);
            //
            // UI_Winpeck
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(545, 176);
            this.Controls.Add(this.label1);
            this.Name = "UI_Winpeck";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "UI_Winpeck";
            this.Load += new System.EventHandler(this.UI_Winpeck_Load);
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Label label1;

    }
}


text:
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('passive_data_kit', '0035_auto_20180323_1511'),
    ]

    operations = [
        migrations.AddField(
            model_name='datasourcegroup',
            name='suppress_alerts',
            field=models.BooleanField(default=False),
        ),
    ]


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Microsoft.DocAsCode.Build.SchemaDriven.Processors
{
    using System.Collections.Generic;
    using System.Linq;

    public class TagsInterpreter : IInterpreter
    {
        private readonly IList<ITagInterpreter> _tagInterpreters;
        public int Order => 0x100;
        public TagsInterpreter(IList<ITagInterpreter> tagInterpreters)
        {
            _tagInterpreters = tagInterpreters;
        }

        public bool CanInterpret(BaseSchema schema)
        {
            return _tagInterpreters?.Count > 0 && schema?.Tags?.Count > 0;
        }

        public object Interpret(BaseSchema schema, object value, IProcessContext context, string path)
        {
            if (!CanInterpret(schema))
            {
                return value;
            }
            var val = value;

            foreach(var tag in schema.Tags)
            {
                foreach (var i in _tagInterpreters.Where(t => t.Matches(tag)).OrderBy(t => t.Order))
                {
                    val = i.Interpret(tag, schema, val, context, path);
                }
            }

            return val;
        }
    }
}


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCarriersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('carriers', function (Blueprint $table) {

            $table->increments('id');
            $table->string('name');
            $table->string('name_new');
            $table->date('created_at');
            $table->integer('created_by_user_id');
            $table->date('updated_at');
            $table->integer('updated_by_user_id');
            $table->date('verified_at');
            $table->integer('verified_by_user_id');
            $table->binary('enabled');
            $table->binary('enabled_new');
            $table->string('content_state');
            $table->binary('verification_state');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('carriers');
    }
}


text:
@interface TCAMiscHelper : NSObject

+ (BOOL)isRange:(NSRange)aRange inBoundOfString:(NSString*)aString;

@end


text:
import gtk.gdk

from point import Point
from objects import NONE, HORIZONTAL, VERTICAL, BOTH

class Magneto(Point):
    """This class represents a object magnetic line"""

    __name__ = "Magneto"

    def __init__(self):
        Point.__init__(self)
        self.orientation = NONE

    def draw(self, context):
        context.set_line_width(1.0 / context.get_matrix()[0])

        if self.orientation in [ VERTICAL, BOTH ]:
            context.move_to(0, self.y)
            context.line_to(500, self.y)
        if self.orientation in [ HORIZONTAL, BOTH ]:
            context.move_to(self.x, 0)
            context.line_to(self.x, 500)

        context.set_source_rgba(0.0, 0.0, 0.75, 1.0)
        context.stroke()


text:
On window, paths looks bad, and are not agreeable to type. On, Linux, it's different. So, user friendly path are path that are inspired by Linux. Computer friendly path are path that are valid for a computer, depending on the OS.

# Example on window

|    Friendly form     |             Computer form             |
|----------------------|---------------------------------------|
| `~/folder/file.txt`  | `C:\Users\<username>\folder\file.txt` |
| `C:\Users\math\here` | `C:\Users\math\here`                  |

You'd like to use aliases? Have a look at the [aliases page](Aliases) then!


text:
#ifndef DISPATCH_LISTENER_H_
#define DISPATCH_LISTENER_H_

#include "SmartPointer.h"
#include "Mailer.h"

namespace dispatch {
class ServerListener
{
public:
  virtual void OnClientConnected(lep::SmartPointer<Mailer> mailer) = 0;
};
} // namespace dispatch

#endif // DISPATCH_LISTENER_H_


text:
`giving_schema.sql` contains our MySQL database schema, as created by `dump.sh`.

To create an empty database based on this schema, run:
```
mysql -h mydatabasehost -u user -ppasswd giving < schema
```

`queries` contains a number of SQL queries used to support various [API](https://github.com/dssg/givinggraph/wiki/API) calls


text:
<?php

if (!defined('ELK'))
	die('No access...');

/**
 * PostModeration Controller handles post moderation actions. (approvals, unapprovals)
 */
class PostModeration_Controller extends Action_Controller
{
	/**
	 * This is the entry point for all things post moderation.
	 *
	 * @uses ModerationCenter template
	 * @uses ModerationCenter language file
	 * @see Action_Controller::action_index()
	 */
	public function action_index()
	{
		// @todo We'll shift these later bud.
		loadLanguage('ModerationCenter');
		loadTemplate('ModerationCenter');

		require_once(SUBSDIR . '/Action.class.php');

		// Allowed sub-actions, you know the drill by now!
		$subActions = array(
			'approve' =>  array($this, 'action_approve'),
			'attachments' =>  array($this, 'action_unapproved_attachments'),
			'replies' =>  array($this, 'action_unapproved'),
			'topics' =>  array($this, 'action_unapproved'),
		);

		// Pick something valid...
		$subAction = !isset($_REQUEST['sa']) || !isset($subActions[$_REQUEST['sa']]) ? 'replies' : $_REQUEST['sa'];

		$action = new Action();
		$action->initialize($subActions, 'replies');
		$action->dispatch($subAction);
	}

	/**
	 * View all unapproved posts or topics
	 */
	public function action_unapproved()
	{
		global $txt, $scripturl, $context, $user_info;

		$db = database();

		$context['current_view'] = isset($_GET['sa']) && $_GET['sa'] == 'topics' ? 'topics' : 'replies';
		$context['page_title'] = $txt['mc_unapproved_posts'];
		$context['header_title'] = $txt['mc_' . ($context['current_view'] == 'topics' ? 'topics' : 'posts')];

		// Work out what boards we can work in!
		$approve_boards = !empty($user_info['mod_cache']['ap']) ? $user_info['mod_cache']['ap'] : boardsAllowedTo('approve_posts');

		// If we filtered by board remove ones outside of this board.
		// @todo Put a message saying we're filtered?
		if (isset($_REQUEST['brd']))
		{
			$filter_board = array((int) $_REQUEST['brd']);
			$approve_boards = $approve_boards == array(0) ? $filter_board : array_intersect($approve_boards, $filter_board);
		}

		if ($approve_boards == array(0))
			$approve_query = '';
		elseif (!empty($approve_boards))
			$approve_query = ' AND m.id_board IN (' . implode(',', $approve_boards) . ')';
		// Nada, zip, etc...
		else
			$approve_query = ' AND 1=0';

		// We also need to know where we can delete topics and/or replies to.
		if ($context['current_view'] == 'topics')
		{
			$delete_own_boards = boardsAllowedTo('remove_own');
			$delete_any_boards = boardsAllowedTo('remove_any');
			$delete_own_replies = array();
		}
		else
		{
			$delete_own_boards = boardsAllowedTo('delete_own');
			$delete_any_boards = boardsAllowedTo('delete_any');
			$delete_own_replies = boardsAllowedTo('delete_own_replies');
		}

		$toAction = array();
		// Check if we have something to do?
		if (isset($_GET['approve']))
			$toAction[] = (int) $_GET['approve'];
		// Just a deletion?
		elseif (isset($_GET['delete']))
			$toAction[] = (int) $_GET['delete'];
		// Lots of approvals?
		elseif (isset($_POST['item']))
			foreach ($_POST['item'] as $item)
				$toAction[] = (int) $item;

		// What are we actually doing.
		if (isset($_GET['approve']) || (isset($_POST['do']) && $_POST['do'] == 'approve'))
			$curAction = 'approve';
		elseif (isset($_GET['delete']) || (isset($_POST['do']) && $_POST['do'] == 'delete'))
			$curAction = 'delete';

		// Right, so we have something to do?
		if (!empty($toAction) && isset($curAction))
		{
			checkSession('request');

			require_once(SUBSDIR . '/Topic.subs.php');

			// Handy shortcut.
			$any_array = $curAction == 'approve' ? $approve_boards : $delete_any_boards;

			// Now for each message work out whether it's actually a topic, and what board it's on.
			$request = $db->query('', '
				SELECT m.id_msg, m.id_member, m.id_board, m.subject, t.id_topic, t.id_first_msg, t.id_member_started
				FROM {db_prefix}messages AS m
					INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)
				LEFT JOIN {db_prefix}boards AS b ON (t.id_board = b.id_board)
				WHERE m.id_msg IN ({array_int:message_list})
					AND m.approved = {int:not_approved}
					AND {query_see_board}',
				array(
					'message_list' => $toAction,
					'not_approved' => 0,
				)
			);
			$toAction = array();
			$details = array();
			while ($row = $db->fetch_assoc($request))
			{
				// If it's not within what our view is ignore it...
				if (($row['id_msg'] == $row['id_first_msg'] && $context['current_view'] != 'topics') || ($row['id_msg'] != $row['id_first_msg'] && $context['current_view'] != 'replies'))
					continue;

				$can_add = false;

				// If we're approving this is simple.
				if ($curAction == 'approve' && ($any_array == array(0) || in_array($row['id_board'], $any_array)))
					$can_add = true;
				// Delete requires more permission checks...
				elseif ($curAction == 'delete')
				{
					// Own post is easy!
					if ($row['id_member'] == $user_info['id'] && ($delete_own_boards == array(0) || in_array($row['id_board'], $delete_own_boards)))
						$can_add = true;
					// Is it a reply to their own topic?
					elseif ($row['id_member'] == $row['id_member_started'] && $row['id_msg'] != $row['id_first_msg'] && ($delete_own_replies == array(0) || in_array($row['id_board'], $delete_own_replies)))
						$can_add = true;
					// Someone elses?
					elseif ($row['id_member'] != $user_info['id'] && ($delete_any_boards == array(0) || in_array($row['id_board'], $delete_any_boards)))
						$can_add = true;
				}

				if ($can_add)
					$anItem = $context['current_view'] == 'topics' ? $row['id_topic'] : $row['id_msg'];
				$toAction[] = $anItem;

				// All clear. What have we got now, what, what?
				$details[$anItem] = array();
				$details[$anItem]["subject"] = $row['subject'];
				$details[$anItem]["topic"] = $row['id_topic'];
				$details[$anItem]["member"] = ($context['current_view'] == 'topics') ? $row['id_member_started'] : $row['id_member'];
				$details[$anItem]["board"] = $row['id_board'];
			}
			$db->free_result($request);

			// If we have anything left we can actually do the approving (etc).
			if (!empty($toAction))
			{
				if ($curAction == 'approve')
					approveMessages($toAction, $details, $context['current_view']);
				else
					removeMessages($toAction, $details, $context['current_view']);

				cache_put_data('num_menu_errors', null, 900);
			}
		}

		// Get the moderation values for the board level
		$brd = isset($_REQUEST['brd']) ? (int) $_REQUEST['brd'] : null;
		require_once(SUBSDIR . '/Moderation.subs.php');
		$mod_count = loadModeratorMenuCounts($brd);

		$context['total_unapproved_topics'] = $mod_count['topics'];
		$context['total_unapproved_posts'] = $mod_count['posts'];
		$context['page_index'] = constructPageIndex($scripturl . '?action=moderate;area=postmod;sa=' . $context['current_view'] . (isset($_REQUEST['brd']) ? ';brd=' . (int) $_REQUEST['brd'] : ''), $_GET['start'], $context['current_view'] == 'topics' ? $context['total_unapproved_topics'] : $context['total_unapproved_posts'], 10);
		$context['start'] = $_GET['start'];

		// We have enough to make some pretty tabs!
		$context[$context['moderation_menu_name']]['tab_data'] = array(
			'title' => $txt['mc_unapproved_posts'],
			'help' => 'postmod',
			'description' => $txt['mc_unapproved_posts_desc'],
		);

		// Update the tabs with the correct number of actions to account for brd filtering
		$context['menu_data_' . $context['moderation_menu_id']]['sections']['posts']['areas']['postmod']['subsections']['posts']['label'] = $context['menu_data_' . $context['moderation_menu_id']]['sections']['posts']['areas']['postmod']['subsections']['posts']['label'] . ' [' . $context['total_unapproved_posts'] . ']';
		$context['menu_data_' . $context['moderation_menu_id']]['sections']['posts']['areas']['postmod']['subsections']['topics']['label'] = $context['menu_data_' . $context['moderation_menu_id']]['sections']['posts']['areas']['postmod']['subsections']['topics']['label']. ' [' . $context['total_unapproved_topics'] . ']';

		// If we are filtering some boards out then make sure to send that along with the links.
		if (isset($_REQUEST['brd']))
		{
			$context['menu_data_' . $context['moderation_menu_id']]['sections']['posts']['areas']['postmod']['subsections']['posts']['add_params'] = ';brd=' . (int) $_REQUEST['brd'];
			$context['menu_data_' . $context['moderation_menu_id']]['sections']['posts']['areas']['postmod']['subsections']['topics']['add_params'] = ';brd=' . (int) $_REQUEST['brd'];
		}

		// Get all unapproved posts.
		$request = $db->query('', '
			SELECT m.id_msg, m.id_topic, m.id_board, m.subject, m.body, m.id_member,
				IFNULL(mem.real_name, m.poster_name) AS poster_name, m.poster_time, m.smileys_enabled,
				t.id_member_started, t.id_first_msg, b.name AS board_name, c.id_cat, c.name AS cat_name
			FROM {db_prefix}messages AS m
				INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)
				INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board)
				LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
				LEFT JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat)
			WHERE m.approved = {int:not_approved}
				AND t.id_first_msg ' . ($context['current_view'] == 'topics' ? '=' : '!=') . ' m.id_msg
				AND {query_see_board}
				' . $approve_query . '
			LIMIT ' . $context['start'] . ', 10',
			array(
				'not_approved' => 0,
			)
		);
		$context['unapproved_items'] = array();
		for ($i = 1; $row = $db->fetch_assoc($request); $i++)
		{
			// Can delete is complicated, let's solve it first... is it their own post?
			if ($row['id_member'] == $user_info['id'] && ($delete_own_boards == array(0) || in_array($row['id_board'], $delete_own_boards)))
				$can_delete = true;
			// Is it a reply to their own topic?
			elseif ($row['id_member'] == $row['id_member_started'] && $row['id_msg'] != $row['id_first_msg'] && ($delete_own_replies == array(0) || in_array($row['id_board'], $delete_own_replies)))
				$can_delete = true;
			// Someone elses?
			elseif ($row['id_member'] != $user_info['id'] && ($delete_any_boards == array(0) || in_array($row['id_board'], $delete_any_boards)))
				$can_delete = true;
			else
				$can_delete = false;

			$context['unapproved_items'][] = array(
				'id' => $row['id_msg'],
				'alternate' => $i % 2,
				'counter' => $context['start'] + $i,
				'href' => $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'],
				'link' => '' . $row['subject'] . '',
				'subject' => $row['subject'],
				'body' => parse_bbc($row['body'], $row['smileys_enabled'], $row['id_msg']),
				'time' => standardTime($row['poster_time']),
				'html_time' => htmlTime($row['poster_time']),
				'timestamp' => forum_time(true, $row['poster_time']),
				'poster' => array(
					'id' => $row['id_member'],
					'name' => $row['poster_name'],
					'link' => $row['id_member'] ? '' . $row['poster_name'] . '' : $row['poster_name'],
					'href' => $scripturl . '?action=profile;u=' . $row['id_member'],
				),
				'topic' => array(
					'id' => $row['id_topic'],
				),
				'board' => array(
					'id' => $row['id_board'],
					'name' => $row['board_name'],
					'link' => '' . $row['board_name'] . '',
				),
				'category' => array(
					'id' => $row['id_cat'],
					'name' => $row['cat_name'],
					'link' => '' . $row['cat_name'] . '',
				),
				'can_delete' => $can_delete,
			);
		}
		$db->free_result($request);

		$context['sub_template'] = 'unapproved_posts';
	}

	/**
	 * View all unapproved attachments.
	 */
	public function action_unapproved_attachments()
	{
		global $txt, $scripturl, $context, $user_info, $modSettings;

		$context['page_title'] = $txt['mc_unapproved_attachments'];

		// Once again, permissions are king!
		$approve_boards = !empty($user_info['mod_cache']['ap']) ? $user_info['mod_cache']['ap'] : boardsAllowedTo('approve_posts');

		if ($approve_boards == array(0))
			$approve_query = '';
		elseif (!empty($approve_boards))
			$approve_query = ' AND m.id_board IN (' . implode(',', $approve_boards) . ')';
		else
			$approve_query = ' AND 0';

		// Get together the array of things to act on, if any.
		$attachments = array();
		if (isset($_GET['approve']))
			$attachments[] = (int) $_GET['approve'];
		elseif (isset($_GET['delete']))
			$attachments[] = (int) $_GET['delete'];
		elseif (isset($_POST['item']))
		{
			foreach ($_POST['item'] as $item)
				$attachments[] = (int) $item;
		}

		// Are we approving or deleting?
		if (isset($_GET['approve']) || (isset($_POST['do']) && $_POST['do'] == 'approve'))
			$curAction = 'approve';
		elseif (isset($_GET['delete']) || (isset($_POST['do']) && $_POST['do'] == 'delete'))
			$curAction = 'delete';

		// Something to do, let's do it!
		if (!empty($attachments) && isset($curAction))
		{
			checkSession('request');

			// This will be handy.
			require_once(SUBSDIR . '/ManageAttachments.subs.php');

			// Confirm the attachments are eligible for changing!
			$attachments = validateAttachments($attachments, $approve_query);

			// Assuming it wasn't all like, proper illegal, we can do the approving.
			if (!empty($attachments))
			{
				if ($curAction == 'approve')
					approveAttachments($attachments);
				else
					removeAttachments(array('id_attach' => $attachments, 'do_logging' => true));

				cache_put_data('num_menu_errors', null, 900);
			}
		}

		require_once(SUBSDIR . '/List.class.php');
		require_once(SUBSDIR . '/ManageAttachments.subs.php');

		$listOptions = array(
			'id' => 'mc_unapproved_attach',
			'width' => '100%',
			'items_per_page' => $modSettings['defaultMaxMessages'],
			'no_items_label' => $txt['mc_unapproved_attachments_none_found'],
			'base_href' => $scripturl . '?action=moderate;area=attachmod;sa=attachments',
			'default_sort_col' => 'attach_name',
			'get_items' => array(
				'function' => 'list_getUnapprovedAttachments',
				'params' => array(
					$approve_query,
				),
			),
			'get_count' => array(
				'function' => 'list_getNumUnapprovedAttachments',
				'params' => array(
					$approve_query,
				),
			),
			'columns' => array(
				'attach_name' => array(
					'header' => array(
						'value' => $txt['mc_unapproved_attach_name'],
					),
					'data' => array(
						'db' => 'filename',
					),
					'sort' => array(
						'default' => 'a.filename',
						'reverse' => 'a.filename DESC',
					),
				),
				'attach_size' => array(
					'header' => array(
						'value' => $txt['mc_unapproved_attach_size'],
					),
					'data' => array(
						'db' => 'size',
					),
					'sort' => array(
						'default' => 'a.size',
						'reverse' => 'a.size DESC',
					),
				),
				'attach_poster' => array(
					'header' => array(
						'value' => $txt['mc_unapproved_attach_poster'],
					),
					'data' => array(
						'function' => create_function('$data', '
							return $data[\'poster\'][\'link\'];'
						)
					),
					'sort' => array(
						'default' => 'm.id_member',
						'reverse' => 'm.id_member DESC',
					),
				),
				'date' => array(
					'header' => array(
						'value' => $txt['date'],
						'style' => 'width: 18%;',
					),
					'data' => array(
						'db' => 'time',
						'class' => 'smalltext',
						'style' => 'white-space:nowrap;',
					),
					'sort' => array(
						'default' => 'm.poster_time',
						'reverse' => 'm.poster_time DESC',
					),
				),
				'message' => array(
					'header' => array(
						'value' => $txt['post'],
					),
					'data' => array(
						'function' => create_function('$data', '
							global $modSettings;
							return \'\' . shorten_text($data[\'message\'][\'subject\'], !empty($modSettings[\'subject_length\']) ? $modSettings[\'subject_length\'] : 24) . \'\';'
						),
						'class' => 'smalltext',
						'style' => 'width:15em;',
					),
					'sort' => array(
						'default' => 'm.subject',
						'reverse' => 'm.subject DESC',
					),
				),
				'action' => array(
					'header' => array(
						'value' => '<input type="checkbox" class="input_check" onclick="invertAll(this, this.form);" checked="checked" />',
						'style' => 'width: 4%;text-align: center',
					),
					'data' => array(
						'sprintf' => array(
							'format' => '<input type="checkbox" name="item[]" value="%1$d" checked="checked" class="input_check" />',
							'params' => array(
								'id' => false,
							),
						),
						'class' => 'centertext',
					),
				),
			),
			'form' => array(
				'href' => $scripturl . '?action=moderate;area=attachmod;sa=attachments',
				'include_sort' => true,
				'include_start' => true,
				'hidden_fields' => array(
					$context['session_var'] => $context['session_id'],
				),
				'token' => 'mod-ap',
			),
			'additional_rows' => array(
				array(
					'position' => 'bottom_of_list',
					'value' => '
						<select name="do" onchange="if (this.value != 0 && confirm(\'' . $txt['mc_unapproved_sure'] . '\')) submit();">
							<option value="0">' . $txt['with_selected'] . ':</option>
							<option value="0" disabled="disabled">' . str_repeat('—', strlen($txt['approve'])) . '</option>
							<option value="approve">' . (isBrowser('ie8') ? '»' : '➤') . ' ' . $txt['approve'] . '</option>
							<option value="delete">' . (isBrowser('ie8') ? '»' : '➤') . ' ' . $txt['delete'] . '</option>
						</select>
						<input type="submit" name="ml_go" value="' . $txt['go'] . '" class="right_submit" />',
					'class' => 'floatright',
				),
			),
		);

		// Create the request list.
		createToken('mod-ap');
		createList($listOptions);

		$context['sub_template'] = 'show_list';
		$context['default_list'] = 'mc_unapproved_attach';
		$context[$context['moderation_menu_name']]['tab_data'] = array(
			'title' => $txt['mc_unapproved_attachments'],
			'help' => '',
			'description' => $txt['mc_unapproved_attachments_desc']
		);
	}

	/**
	 * Approve a post, just the one.
	 */
	public function action_approve()
	{
		global $user_info, $topic, $board;

		checkSession('get');

		$current_msg = (int) $_REQUEST['msg'];

		require_once(SUBSDIR . '/Post.subs.php');
		require_once(SUBSDIR . '/Messages.subs.php');

		isAllowedTo('approve_posts');

		$message_info = basicMessageInfo($current_msg, false, true);

		// If it's the first in a topic then the whole topic gets approved!
		if ($message_info['id_first_msg'] == $current_msg)
		{
			approveTopics($topic, !$message_info['approved']);

			if ($message_info['id_member_started'] != $user_info['id'])
				logAction(($message_info['approved'] ? 'un' : '') . 'approve_topic', array('topic' => $topic, 'subject' => $message_info['subject'], 'member' => $message_info['id_member_started'], 'board' => $board));
		}
		else
		{
			approvePosts($current_msg, !$message_info['approved']);

			if ($message_info['id_member'] != $user_info['id'])
				logAction(($message_info['approved'] ? 'un' : '') . 'approve', array('topic' => $topic, 'subject' => $message_info['subject'], 'member' => $message_info['id_member'], 'board' => $board));
		}

		cache_put_data('num_menu_errors', null, 900);

		redirectexit('topic=' . $topic . '.msg' . $current_msg. '#msg' . $current_msg);
	}
}


text:
<!doctype html>

		<title>Zabuun - Learn Egyptian Arabic for English speakers</title>
		<meta name="description" content="">
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/head.php';?>

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/ie8.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/header.php';?>

			<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/side.php';?>

Essays > O.J. Simpson: American Hero and Villain

						Expand All | Collapse All

O.J. Simpson: American Hero and Villain

Simpson was later convicted in a Nevada court for several offenses, and is currently serving time in prison. Many believe this conviction was retribution for his earlier crimes.

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/footer.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/scripts.php';?>


text:
package edu.hku.sdb.parse;

import java.util.HashMap;
import java.util.List;

public class QueryDesc {

  // only names of physical tables are stored.
  protected List<String> tblNames;
  protected HashMap<String, List<String>> tblToCols;
}