text:
function [All_constraints, All_feats] = compute_funcmap_constraints(image_dir_name, imgsize,flip, All_eig_vecs, All_superpixels, graph_weights, opt_flow_alg, feat_type, caffe_dir)
%% ======================================================
%% Compute all constraints, projected into reduced space of every image pair
% The correspondences used are both pixel-correspondences from optical flow
% fields, such as 'DSP' or 'SIFTflow', along with saliency correspondences
% derived from 'GBVS'.  For more info, please refer to:

% <http://people.csail.mit.edu/celiu/SIFTflow/>
% <http://vision.cs.utexas.edu/projects/dsp/>
% <http://www.vision.caltech.edu/~harel/share/gbvs.php>
% ======================================================
%% INPUTS
% image_dir_name - (str) name of image director
% imgsize - (int) reshaped image size to use
% flip - (int) 1 (no flipped copies) or 2 (flipped copies)
% All_eig_vecs - (N x F cell, N is #images, F is flip) each entry has all the eigenvectors for an image arranged in columns
% All_superpixels - (N x F cell, N is #images, F is flip) if type == superpixels, then this contains superpixel labels for each image
% type - either 'DSP' or 'SIFTflow' pixel correspondences
% =======================================================
%% OUTPUTS
% All_constraints - (N x F x N x F cell, N is #images, F is flip) contains the correspondences between each image-pair projected into reduced space
%% =======================================================

images = dir([image_dir_name '/*.JPEG']);
if isempty(images)
    images = dir([image_dir_name '/*.bmp']);
end
if isempty(images)
    images = dir([image_dir_name '/*.jpg']);
end

All_constraints = cell(length(images), flip, length(images), flip,2);
All_feats = cell(length(images), flip);

parfor f = 1:length(images)
    for f_flip = 1:flip
        if f_flip == 1
            im = imread([image_dir_name '/' images(f).name]);
        elseif f_flip == 2
            im = flip_image(imread([image_dir_name '/' images(f).name])); % use flipped copy
        end

        im = double(imresize(im, [imgsize imgsize]));

        im_f_feats = get_pix_features(im, feat_type, caffe_dir);
        All_feats{f, f_flip} = im_f_feats;
    end
end

parfor z = 1:length(images)

    for z_flip = 1:flip
        if z_flip == 1
            im1_whole = imread([image_dir_name '/' images(z).name]);
        elseif z_flip == 2
            im1_whole = flip_image(imread([image_dir_name '/' images(z).name])); % use flipped copy
        end

        All_constraints_z = cell(length(images), flip,2);

        % =============================
        %% resize image 1 and load basis
        im1 = double(imresize(im1_whole, [imgsize imgsize]));
        eig_vecs1 = All_eig_vecs{z,z_flip};
        % ==============================

        for y = 1:length(images)
            for y_flip = 1:flip
                if graph_weights(z, z_flip, y,y_flip) == 0
                    continue; % if no weight, don't update map
                end

                if y_flip == 1
                    im2_whole = imread([image_dir_name '/' images(y).name]);
                elseif y_flip ==2
                    im2_whole = flip_image(imread([image_dir_name '/' images(y).name]));
                end

                % ===========================================
                %% resize image 2 and load basis
                im2 = double(imresize(im2_whole, [imgsize imgsize]));
                eig_vecs2 = All_eig_vecs{y,y_flip};
                %========================================================================================
                %% Calculate all correspondences between the two images
                if z == y && z_flip ~= y_flip
                    [C,D] = get_flip_correspondences(im1); % gt-correspondences between an image and its flipped version
                else
                   [C, D, ~, ~] = get_pixel_correspondences(im1, im2, opt_flow_alg, caffe_dir, feat_type, All_feats{z, z_flip}, All_feats{y, y_flip}); % pixel correspondences using either 'SIFTflow' or 'DSP'

                end

                [im1_saliency, im2_saliency] = get_saliency_correspondences(im1, im2); %Saliency correspondences using 'GBVS'

                if iscell(All_superpixels) % move correspondences up to superpixel resolution if so desired
                    [C, D] = pixel_to_superpixel_correspondences(D, All_superpixels{z,z_flip}, All_superpixels{y,y_flip});
                    [im1_saliency]  = pixel_to_superpixel_saliency(im1_saliency, All_superpixels{z,z_flip});
                    [im2_saliency] =  pixel_to_superpixel_saliency(im2_saliency, All_superpixels{y,y_flip});
                end

                %============================================================================================
                %% gather all correspondences and save them
                img1_projected_indicators = [normalize_columns(eig_vecs1'*C) normalize_columns(eig_vecs1'*im1_saliency)]; % normalize so that correspondences have equal weight
                img2_projected_indicators = [normalize_columns(eig_vecs2'*D) normalize_columns(eig_vecs2'*im2_saliency)];

                indicators = {};
                indicators{1} = img1_projected_indicators;
                indicators{2} = img2_projected_indicators;
                for j = 1:2
                    All_constraints_z{y, y_flip,j} = indicators{j};

                end
                fprintf('Finished constraint pair in %d \n', z);
                %==============================================================================================
            end
        end

        All_constraints(z, z_flip, :,:,:) = All_constraints_z;

    end
    fprintf('Finished computing constraints for image (%d / %d) \n', z, length(images));
end
end


text:
"""Experimental APIs."""
from __future__ import annotations

from datetime import datetime

from airflow.exceptions import DagNotFound, DagRunNotFound, TaskNotFound
from airflow.models import DagBag, DagModel, DagRun

def check_and_get_dag(dag_id: str, task_id: str | None = None) -> DagModel:
    """Check DAG existence and in case it is specified that Task exists."""
    dag_model = DagModel.get_current(dag_id)
    if dag_model is None:
        raise DagNotFound(f"Dag id {dag_id} not found in DagModel")

    dagbag = DagBag(dag_folder=dag_model.fileloc, read_dags_from_db=True)
    dag = dagbag.get_dag(dag_id)
    if not dag:
        error_message = f"Dag id {dag_id} not found"
        raise DagNotFound(error_message)
    if task_id and not dag.has_task(task_id):
        error_message = f"Task {task_id} not found in dag {dag_id}"
        raise TaskNotFound(error_message)
    return dag

def check_and_get_dagrun(dag: DagModel, execution_date: datetime) -> DagRun:
    """Get DagRun object and check that it exists."""
    dagrun = dag.get_dagrun(execution_date=execution_date)
    if not dagrun:
        error_message = f"Dag Run for date {execution_date} not found in dag {dag.dag_id}"
        raise DagRunNotFound(error_message)
    return dagrun

redpajama_set_name: RedPajamaGithub


text:
<?php
// $Header: /cvsroot/html2ps/css.list-style.inc.php,v 1.2 2005/09/25 16:21:44 Konstantin Exp $

class ListStyleValue {
  var $image;
  var $position;
  var $type;

  function is_default() {
    return
      $this->image    == CSSListStyleImage::default_value() &&
      $this->position == CSSListStylePosition::default_value() &&
      $this->type     == CSSListStyleType::default_value();
  }

  function to_ps() {
    return
      "<< ".
      "/position ".CSSListStylePosition::value2ps($this->position)." ".
      "/type ".CSSListStyleType::value2ps($this->type)." ".
      ">>";
  }
}

class CSSListStyle extends CSSProperty {
  // CSS 2.1: list-style is inherited
  function CSSListStyle() {
    $this->default_value = new ListStyleValue;
    $this->default_value->image    = CSSListStyleImage::default_value();
    $this->default_value->position = CSSListStylePosition::default_value();
    $this->default_value->type     = CSSListStyleType::default_value();

    $this->CSSProperty(true, true);
  }

  function parse($value) {
    $style = new ListStyleValue;
    $style->image     = CSSListStyleImage::parse($value);
    $style->position  = CSSListStylePosition::parse($value);
    $style->type      = CSSListStyleType::parse($value);

    return $style;
  }

  function default_value() { return $this->default_value; }
}

$ls = new CSSListStyle;
register_css_property('list-style', $ls);
register_css_property('list-style-image',    new CSSListStyleImage($ls,    'image'));
register_css_property('list-style-position', new CSSListStylePosition($ls, 'position'));
register_css_property('list-style-type',     new CSSListStyleType($ls,     'type'));

?>


text:
package org.tguduru.guava.function;

import com.google.common.base.Function;
import com.google.common.base.Preconditions;

/**
 * Implementation of a {@link Function}
 * @author Guduru, Thirupathi Reddy
 */
public class StringLengthFunction implements Function<String, Long> {
    /**
     * Returns the result of applying this function to {@code input}. This method is generally
     * expected, but not absolutely required, to have the following properties:
     *

     *
Its execution does not cause any observable side effects.
     *
The computation is consistent with equals; that is, {@link com.google.common.base.Objects#equal
     * Objects.equal}{@code (a, b)} implies that {@code Objects.equal(function.apply(a), function.apply(b))}.
     *

     * @param input
     * @throws NullPointerException if {@code input} is null and this function does not accept null
     *             arguments
     */
    @Override
    public Long apply(final String input) {
        Preconditions.checkNotNull(input);
        return Long.valueOf(input.length());
    }
}


text:
import {createTestApp, patchDevkitTreeToExposeTypeScript} from '@angular/cdk/schematics/testing';
import {SchematicTestRunner, UnitTestTree} from '@angular-devkit/schematics/testing';
import {createNewTestRunner, migrateComponents, THEME_FILE} from '../test-setup-helper';

describe('slider styles', () => {
  let runner: SchematicTestRunner;
  let cliAppTree: UnitTestTree;

  async function runMigrationTest(oldFileContent: string, newFileContent: string) {
    cliAppTree.create(THEME_FILE, oldFileContent);
    const tree = await migrateComponents(['slider'], runner, cliAppTree);
    expect(tree.readContent(THEME_FILE)).toBe(newFileContent);
  }

  beforeEach(async () => {
    runner = createNewTestRunner();
    cliAppTree = patchDevkitTreeToExposeTypeScript(await createTestApp(runner));
  });

  describe('mixin migrations', () => {
    it('should replace the old theme with the new ones', async () => {
      await runMigrationTest(
        `
        @use '@angular/material' as mat;
        $theme: ();
        @include mat.legacy-slider-theme($theme);
      `,
        `
        @use '@angular/material' as mat;
        $theme: ();
        @include mat.slider-theme($theme);
      `,
      );
    });

    it('should use the correct namespace', async () => {
      await runMigrationTest(
        `
        @use '@angular/material' as arbitrary;
        $theme: ();
        @include arbitrary.legacy-slider-theme($theme);
      `,
        `
        @use '@angular/material' as arbitrary;
        $theme: ();
        @include arbitrary.slider-theme($theme);
      `,
      );
    });

    it('should handle updating multiple themes', async () => {
      await runMigrationTest(
        `
        @use '@angular/material' as mat;
        $light-theme: ();
        $dark-theme: ();
        @include mat.legacy-slider-theme($light-theme);
        @include mat.legacy-slider-theme($dark-theme);
      `,
        `
        @use '@angular/material' as mat;
        $light-theme: ();
        $dark-theme: ();
        @include mat.slider-theme($light-theme);
        @include mat.slider-theme($dark-theme);
      `,
      );
    });

    it('should preserve whitespace', async () => {
      await runMigrationTest(
        `
        @use '@angular/material' as mat;
        $theme: ();

        @include mat.legacy-slider-theme($theme);

      `,
        `
        @use '@angular/material' as mat;
        $theme: ();

        @include mat.slider-theme($theme);

      `,
      );
    });

    it('should update color mixin', async () => {
      await runMigrationTest(
        `
        @use '@angular/material' as mat;
        $theme: ();
        @include mat.legacy-slider-color($theme);
      `,
        `
        @use '@angular/material' as mat;
        $theme: ();
        @include mat.slider-color($theme);
      `,
      );
    });

    it('should update typography mixin', async () => {
      await runMigrationTest(
        `
        @use '@angular/material' as mat;
        $theme: ();
        @include mat.legacy-slider-typography($theme);
      `,
        `
        @use '@angular/material' as mat;
        $theme: ();
        @include mat.slider-typography($theme);
      `,
      );
    });
  });

  describe('selector migrations', () => {
    it('should update the legacy mat-slider classname', async () => {
      await runMigrationTest(
        `
        .mat-slider {
          width: 100%;
        }
      `,
        `
        .mat-mdc-slider {
          width: 100%;
        }
      `,
      );
    });

    it('should add comment for potentially deprecated multi-line selector', async () => {
      await runMigrationTest(
        `
        .some-class
        .mat-slider-thumb {
          height: 16px;
        }
      `,
        `
        /* TODO(mdc-migration): The following rule targets internal classes of slider that may no longer apply for the MDC version. */
        .some-class
        .mat-slider-thumb {
          height: 16px;
        }
      `,
      );
    });

    it('should update the legacy mat-slider class and add comment for potentially deprecated selector', async () => {
      await runMigrationTest(
        `
        .mat-slider.some-class, .mat-slider-thumb {
          background-color: transparent;
        }
      `,
        `
        /* TODO(mdc-migration): The following rule targets internal classes of slider that may no longer apply for the MDC version. */
        .mat-mdc-slider.some-class, .mat-slider-thumb {
          background-color: transparent;
        }
      `,
      );
    });
  });
});


text:
import events from './events';
import Store from './store';
import ui from './ui';
import * as Constants from './constants';
import xtend from 'xtend';

export default function(ctx) {

  let controlContainer = null;
  let mapLoadedInterval = null;

  const setup = {
    onRemove() {
      // Stop connect attempt in the event that control is removed before map is loaded
      ctx.map.off('load', setup.connect);
      clearInterval(mapLoadedInterval);

      setup.removeLayers();
      ctx.store.restoreMapConfig();
      ctx.ui.removeButtons();
      ctx.events.removeEventListeners();
      ctx.ui.clearMapClasses();
      ctx.map = null;
      ctx.container = null;
      ctx.store = null;

      if (controlContainer && controlContainer.parentNode) controlContainer.parentNode.removeChild(controlContainer);
      controlContainer = null;

      return this;
    },
    connect() {
      ctx.map.off('load', setup.connect);
      clearInterval(mapLoadedInterval);
      setup.addLayers();
      ctx.store.storeMapConfig();
      ctx.events.addEventListeners();
    },
    onAdd(map) {
      if (process.env.NODE_ENV !== 'test') {
        // Monkey patch to resolve breaking change to `fire` introduced by
        // mapbox-gl-js. See mapbox/mapbox-gl-draw/issues/766.
        const _fire = map.fire;
        map.fire = function(type, event) {
          // eslint-disable-next-line
          let args = arguments;

          if (_fire.length === 1 && arguments.length !== 1) {
            args = [xtend({}, { type }, event)];
          }

          return _fire.apply(map, args);
        };
      }

      ctx.map = map;
      ctx.events = events(ctx);
      ctx.ui = ui(ctx);
      ctx.container = map.getContainer();
      ctx.store = new Store(ctx);

      controlContainer = ctx.ui.addButtons();

      if (ctx.options.boxSelect) {
        map.boxZoom.disable();
        // Need to toggle dragPan on and off or else first
        // dragPan disable attempt in simple_select doesn't work
        map.dragPan.disable();
        map.dragPan.enable();
      }

      if (map.loaded()) {
        setup.connect();
      } else {
        map.on('load', setup.connect);
        mapLoadedInterval = setInterval(() => { if (map.loaded()) setup.connect(); }, 16);
      }

      ctx.events.start();
      return controlContainer;
    },
    addLayers() {
      // drawn features style
      ctx.map.addSource(Constants.sources.COLD, {
        data: {
          type: Constants.geojsonTypes.FEATURE_COLLECTION,
          features: []
        },
        type: 'geojson'
      });

      // hot features style
      ctx.map.addSource(Constants.sources.HOT, {
        data: {
          type: Constants.geojsonTypes.FEATURE_COLLECTION,
          features: []
        },
        type: 'geojson'
      });

      ctx.options.styles.forEach((style) => {
        ctx.map.addLayer(style);
      });

      ctx.store.setDirty(true);
      ctx.store.render();
    },
    // Check for layers and sources before attempting to remove
    // If user adds draw control and removes it before the map is loaded, layers and sources will be missing
    removeLayers() {
      ctx.options.styles.forEach((style) => {
        if (ctx.map.getLayer(style.id)) {
          ctx.map.removeLayer(style.id);
        }
      });

      if (ctx.map.getSource(Constants.sources.COLD)) {
        ctx.map.removeSource(Constants.sources.COLD);
      }

      if (ctx.map.getSource(Constants.sources.HOT)) {
        ctx.map.removeSource(Constants.sources.HOT);
      }
    }
  };

  ctx.setup = setup;

  return setup;
}


text:
(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@angular/common'), require('primeng/dom'), require('primeng/api')) :
    typeof define === 'function' && define.amd ? define('primeng/blockui', ['exports', '@angular/core', '@angular/common', 'primeng/dom', 'primeng/api'], factory) :
    (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.primeng = global.primeng || {}, global.primeng.blockui = {}), global.ng.core, global.ng.common, global.primeng.dom, global.primeng.api));
}(this, (function (exports, core, common, dom, api) { 'use strict';

    var BlockUI = /** @class */ (function () {
        function BlockUI(el, cd) {
            this.el = el;
            this.cd = cd;
            this.autoZIndex = true;
            this.baseZIndex = 0;
        }
        Object.defineProperty(BlockUI.prototype, "blocked", {
            get: function () {
                return this._blocked;
            },
            set: function (val) {
                this._blocked = val;
                if (this.mask && this.mask.nativeElement) {
                    if (this._blocked)
                        this.block();
                    else
                        this.unblock();
                }
            },
            enumerable: false,
            configurable: true
        });
        BlockUI.prototype.ngAfterViewInit = function () {
            if (this.target && !this.target.getBlockableElement) {
                throw 'Target of BlockUI must implement BlockableUI interface';
            }
        };
        BlockUI.prototype.ngAfterContentInit = function () {
            var _this = this;
            this.templates.forEach(function (item) {
                switch (item.getType()) {
                    case 'content':
                        _this.contentTemplate = item.template;
                        break;
                    default:
                        _this.contentTemplate = item.template;
                        break;
                }
            });
        };
        BlockUI.prototype.block = function () {
            if (this.target) {
                this.target.getBlockableElement().appendChild(this.mask.nativeElement);
                this.target.getBlockableElement().style.position = 'relative';
            }
            else {
                document.body.appendChild(this.mask.nativeElement);
            }
            if (this.autoZIndex) {
                this.mask.nativeElement.style.zIndex = String(this.baseZIndex + (++dom.DomHandler.zindex));
            }
        };
        BlockUI.prototype.unblock = function () {
            this.el.nativeElement.appendChild(this.mask.nativeElement);
        };
        BlockUI.prototype.ngOnDestroy = function () {
            this.unblock();
        };
        return BlockUI;
    }());
    BlockUI.decorators = [
        { type: core.Component, args: [{
                    selector: 'p-blockUI',
                    template: "\n        <div #mask [class]=\"styleClass\" [ngClass]=\"{'p-blockui-document':!target, 'p-blockui p-component-overlay': true}\" [ngStyle]=\"{display: blocked ? 'flex' : 'none'}\">\n            <ng-content></ng-content>\n            <ng-container *ngTemplateOutlet=\"contentTemplate\"></ng-container>\n        </div>\n    ",
                    changeDetection: core.ChangeDetectionStrategy.OnPush,
                    encapsulation: core.ViewEncapsulation.None,
                    styles: [".p-blockui{-ms-flex-align:center;-ms-flex-pack:center;align-items:center;background-color:rgba(0,0,0,0);display:-ms-flexbox;display:flex;height:100%;justify-content:center;left:0;top:0;transition-property:background-color;width:100%}.p-blockui,.p-blockui.p-component-overlay{position:absolute}.p-blockui-document.p-component-overlay{position:fixed}.p-blockui-leave.p-component-overlay{background-color:rgba(0,0,0,0)}"]
                },] }
    ];
    BlockUI.ctorParameters = function () { return [
        { type: core.ElementRef },
        { type: core.ChangeDetectorRef }
    ]; };
    BlockUI.propDecorators = {
        target: [{ type: core.Input }],
        autoZIndex: [{ type: core.Input }],
        baseZIndex: [{ type: core.Input }],
        styleClass: [{ type: core.Input }],
        templates: [{ type: core.ContentChildren, args: [api.PrimeTemplate,] }],
        mask: [{ type: core.ViewChild, args: ['mask',] }],
        blocked: [{ type: core.Input }]
    };
    var BlockUIModule = /** @class */ (function () {
        function BlockUIModule() {
        }
        return BlockUIModule;
    }());
    BlockUIModule.decorators = [
        { type: core.NgModule, args: [{
                    imports: [common.CommonModule],
                    exports: [BlockUI],
                    declarations: [BlockUI]
                },] }
    ];

    /**
     * Generated bundle index. Do not edit.
     */

    exports.BlockUI = BlockUI;
    exports.BlockUIModule = BlockUIModule;

    Object.defineProperty(exports, '__esModule', { value: true });

})));
//# sourceMappingURL=primeng-blockui.umd.js.map


text: A tiny Lisp I wrote circa 2008.


text:
@implementation DBTEAMBaseDfbReport

#pragma mark - Constructors

- (instancetype)initWithStartDate:(NSString *)startDate {

  self = [super init];
  if (self) {
    _startDate = startDate;
  }
  return self;
}

#pragma mark - Serialization methods

+ (NSDictionary *)serialize:(id)instance {
  return [DBTEAMBaseDfbReportSerializer serialize:instance];
}

+ (id)deserialize:(NSDictionary *)dict {
  return [DBTEAMBaseDfbReportSerializer deserialize:dict];
}

#pragma mark - Description method

- (NSString *)description {
  return [[DBTEAMBaseDfbReportSerializer serialize:self] description];
}

@end

#pragma mark - Serializer Object

@implementation DBTEAMBaseDfbReportSerializer

+ (NSDictionary *)serialize:(DBTEAMBaseDfbReport *)valueObj {
  NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc] init];

  jsonDict[@"start_date"] = valueObj.startDate;

  return jsonDict;
}

+ (DBTEAMBaseDfbReport *)deserialize:(NSDictionary *)valueDict {
  NSString *startDate = valueDict[@"start_date"];

  return [[DBTEAMBaseDfbReport alloc] initWithStartDate:startDate];
}

@end


text:
// Copyright 1999 Association for Universities for Research in Astronomy, Inc.,
// Observatory Control System, Gemini Telescopes Project.
// See the file LICENSE for complete details.
//
// $Id: MemFactory.java 47005 2012-07-26 22:35:47Z swalker $
//

package edu.gemini.pot.sp.memImpl;

import edu.gemini.pot.sp.*;
import edu.gemini.pot.sp.version.LifespanId;
import edu.gemini.spModel.core.SPProgramID;

import java.util.*;

//
// TODO: This class has gotten out of control.  Creation of objects needs to
// TODO: be rethought
//

/**
 * This class is a concrete extension of the SPAbstractFactory
 * and is used to create the "Mem" family of program nodes.
 */
public class MemFactory extends SPAbstractFactory {

    private List<SPComponentType> _creatableObsComponents;
    private List<SPComponentType> _creatableSeqComponents;

    private final UUID uuid;

    public MemFactory(UUID uuid)  {
        if (uuid == null) throw new IllegalArgumentException("uuid is null");
        this.uuid = uuid;
    }

    /**
     * Returns the type of the factory.
     *
     * @return a String indicating the type of nodes created by the factory
     */
    public String getType() {
        return "Memory Program";
    }

    protected ISPProgram doCreateProgram(SPNodeKey key, SPProgramID progID) {
        return MemProgram.create(key, progID, uuid);
    }

    public ISPProgram copyWithNewKeys(ISPProgram program, SPProgramID newProgID) {
        final MemProgram copy = MemProgram.copyWithNewKeys(program, newProgID, uuid, this);
        return copy;
    }

    public ISPProgram copyWithSameKeys(ISPProgram in) {
        final MemProgram dup = MemProgram.copyWithSameKeys(in, uuid, this);
        dup.setVersions(in.getVersions());
        return dup;
    }

    public ISPProgram copyWithNewLifespanId(ISPProgram in) {
        final MemProgram dup = MemProgram.copyWithNewLifespanId(in, uuid, this);
        dup.setVersions(in.getVersions());
        return dup;
    }

    protected ISPNightlyRecord doCreateNightlyPlan(SPNodeKey key, SPProgramID planID) {
        return MemNightlyRecord.create(key, planID, uuid);
    }

    /**
     * Creates a deep copy of the given nightly record
     */
    public ISPNightlyRecord renameNightlyRecord(ISPNightlyRecord record, SPNodeKey newKey, SPProgramID recordId) {
        MemNightlyRecord spPlan = MemNightlyRecord.rename(record, newKey, recordId, uuid);
        if (_nightlyPlanInit != null) _nightlyPlanInit.updateNode(spPlan);
        return spPlan;
    }

    @Override
    public ISPConflictFolder createConflictFolder(ISPProgram prog, SPNodeKey key) throws SPUnknownIDException {
        MemConflictFolder f = new MemConflictFolder((MemProgram) prog, key);
        if (_conflictFolderInit != null) _conflictFolderInit.initNode(this, f);
        return f;
    }

    @Override
    public ISPConflictFolder createConflictFolderCopy(ISPProgram prog, ISPConflictFolder that, boolean preserveKeys) throws SPUnknownIDException {
        MemConflictFolder f = new MemConflictFolder((MemProgram) prog, this, that, preserveKeys);
        if (_conflictFolderInit != null) _conflictFolderInit.initNode(this, f);
        return f;
    }

    public ISPTemplateFolder createTemplateFolder(ISPProgram prog, SPNodeKey key)
        throws SPUnknownIDException {
        MemTemplateFolder f = new MemTemplateFolder((MemProgram) prog, key);
        if (_templateFolderInit != null) _templateFolderInit.initNode(this, f);
        return f;
    }

    public ISPTemplateFolder createTemplateFolderCopy(ISPProgram prog, ISPTemplateFolder that, boolean preserveKeys)
        throws SPUnknownIDException {
        MemTemplateFolder folder = new MemTemplateFolder((MemProgram) prog, this, that, preserveKeys);
        if (_templateFolderInit != null) _templateFolderInit.updateNode(folder);
        return folder;
    }

    public ISPTemplateGroup createTemplateGroup(ISPProgram prog, SPNodeKey key)
        throws SPUnknownIDException {
        MemTemplateGroup tg = new MemTemplateGroup((MemProgram) prog, key);
        if (_templateGroupInit != null) _templateGroupInit.initNode(this, tg);
        return tg;
    }

    public ISPTemplateGroup createTemplateGroupCopy(ISPProgram prog, ISPTemplateGroup that, boolean preserveKeys)
        throws SPUnknownIDException {

        MemTemplateGroup tg = new MemTemplateGroup((MemProgram) prog, this, that, preserveKeys);
        if (_templateGroupInit != null) _templateGroupInit.updateNode(tg);
        return tg;
    }

    public ISPTemplateParameters createTemplateParameters(ISPProgram prog, SPNodeKey key)
            throws SPUnknownIDException {
        MemTemplateParameters tp = new MemTemplateParameters((MemProgram) prog, key);
        if (_templateParametersInit != null) _templateParametersInit.initNode(this, tp);
        return tp;
    }

    public ISPTemplateParameters createTemplateParametersCopy(ISPProgram prog, ISPTemplateParameters that, boolean preserveKeys)
            throws SPUnknownIDException {
        MemTemplateParameters tp = new MemTemplateParameters((MemProgram) prog, that, preserveKeys);
        if (_templateParametersInit != null) _templateParametersInit.updateNode(tp);
        return tp;
    }

    /**
     * Creates an ISPObservation.
     */
    @Override protected ISPObservation doCreateObservation(ISPProgram prog, int index, SPNodeKey key) throws SPException {
        final MemProgram  mp = (MemProgram) prog;
        final ProgramData pd = (ProgramData) mp.getDocumentData();
        if (index < 0) {
            index = pd.nextObsNumber();
        } else {
            pd.updateNextObsNumber(index);
        }
        return new MemObservation(mp, index, key);
    }

    /**
     * Creates a deep copy of the given observation
     */
    public ISPObservation createObservationCopy(ISPProgram prog,
                                                ISPObservation observation,
                                                boolean preserveKeys)
            throws SPUnknownIDException {
        MemProgram mprog = (MemProgram) prog;
        ProgramData progData = (ProgramData) mprog.getDocumentData();
        int index;
        if (preserveKeys) {
            // Updated to avoid renumbering observations on fetch/store.
            //
            index = observation.getObservationNumber();
            progData.updateNextObsNumber(index);
        } else {
            index = progData.nextObsNumber();
        }
        MemObservation obs = new MemObservation(mprog, index, this, observation,
                                                preserveKeys);
        if (_obsInit != null) _obsInit.updateNode(obs);
        return obs;
    }

    /**
     * Creates an ISPGroup.
     */
    public ISPGroup doCreateGroup(ISPProgram prog, SPNodeKey key)
            throws SPUnknownIDException {
        return new MemGroup((MemProgram) prog, key);
    }

    /**
     * Creates a deep copy of the given group
     */
    public ISPGroup createGroupCopy(ISPProgram prog,
                                    ISPGroup ispGroup,
                                    boolean preserveKeys)
            throws SPUnknownIDException {
        MemGroup group = new MemGroup((MemProgram) prog, this, ispGroup, preserveKeys);
        if (_groupInit != null) _groupInit.updateNode(group);
        return group;
    }

    /**
     * Creates an ISPObsComponent.
     */
    public ISPObsComponent doCreateObsComponent(ISPProgram prog,
                                                SPComponentType type,
                                                SPNodeKey key)
            throws SPUnknownIDException {
        return new MemObsComponent((MemProgram) prog, type, key);
    }

    /**
     * Creates a deep copy of the given component
     */
    public ISPObsComponent createObsComponentCopy(ISPProgram prog,
                                                  ISPObsComponent component,
                                                  boolean preserveKeys)
            throws SPUnknownIDException {
        MemObsComponent obsComp = new MemObsComponent((MemProgram) prog, component, preserveKeys);
        if (_obsCompInitMap != null) {
            ISPNodeInitializer init = _obsCompInitMap.get(obsComp.getType());
            if (init != null) init.updateNode(obsComp);
        }
        return obsComp;
    }

    public ISPObsQaLog doCreateObsQaLog(ISPProgram prog, SPNodeKey key) throws SPUnknownIDException {
        return new MemObsQaLog((MemProgram) prog, key);
    }

    public ISPObsQaLog createObsQaLogCopy(ISPProgram prog, ISPObsQaLog log, boolean preserveKeys) throws SPUnknownIDException {
        final MemObsQaLog mol = new MemObsQaLog((MemProgram) prog, log, preserveKeys);
        if (_obsQaLogInit != null) _obsQaLogInit.updateNode(mol);
        return mol;
    }

    public ISPObsExecLog doCreateObsExecLog(ISPProgram prog, SPNodeKey key) throws SPUnknownIDException {
        return new MemObsExecLog((MemProgram) prog, key);
    }

    public ISPObsExecLog createObsExecLogCopy(ISPProgram prog, ISPObsExecLog log, boolean preserveKeys) throws SPUnknownIDException {
        final MemObsExecLog mol = new MemObsExecLog((MemProgram) prog, log, preserveKeys);
        if (_obsExecLogInit != null) _obsExecLogInit.updateNode(mol);
        return mol;
    }

    /**
     * Creates an ISPSeqComponent.
     */
    public ISPSeqComponent doCreateSeqComponent(ISPProgram prog,
                                                SPComponentType type,
                                                SPNodeKey key)
            throws SPUnknownIDException {
        return new MemSeqComponent((MemProgram) prog, type, key);
    }

    /**
     * Creates a deep copy of the given component
     */
    public ISPSeqComponent createSeqComponentCopy(ISPProgram prog,
                                                  ISPSeqComponent component,
                                                  boolean preserveKeys)
            throws SPUnknownIDException {
        MemSeqComponent seqComp = new MemSeqComponent((MemProgram) prog, this, component, preserveKeys);
        if (_sequenceCompInitMap != null) {
            ISPNodeInitializer init = _sequenceCompInitMap.get(seqComp.getType());
            if (init != null) init.updateNode(seqComp);
        }
        return seqComp;
    }

    /**
     * Returns a List of {@link SPComponentType} objects, one
     * for each type of obs component that can be created by the factory
     * of this database.
     * In order to discover the types that can be
     * created by the factory, a client can use this method.
     */
    public List<SPComponentType> getCreatableObsComponents()  {
        if (_creatableObsComponents == null) return new ArrayList<SPComponentType>();
        return new ArrayList<SPComponentType>(_creatableObsComponents);
    }

    /**
     * Returns a List of {@link SPComponentType} objects, one
     * for each type of seq component that can be created by this factory.
     * In order to discover the types that can be
     * created by the factory, a client can use this method.
     */
    public List<SPComponentType> getCreatableSeqComponents()  {
        if (_creatableSeqComponents == null) return new ArrayList<SPComponentType>();
        return new ArrayList<SPComponentType>(_creatableSeqComponents);
    }

    /**
     * Public method to allow the DatabaseManager to set the list
     * of obs component createables.  Used for internal implementation only.
     */
    public void setCreatableObsComponents(List<SPComponentType> ocl) {
        _creatableObsComponents = ocl;
    }

    /**
     * Package only method to allow the DatabaseManager to set the list
     * of seq component createables.  Used for internal implmentation only.
     */
    public void setCreatableSeqComponents(List<SPComponentType> scl) {
        _creatableSeqComponents = scl;
    }
}


text:
using ElectronicObserver.Data;
using ElectronicObserver.Observer;
using ElectronicObserver.Utility;
using ElectronicObserver.Utility.Mathematics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ElectronicObserver.Resource.Record {

	/// <summary>
	/// 資源のレコードを保持します。
	/// </summary>
	public class ResourceRecord : RecordBase {

		public class ResourceElement : RecordElementBase {

			/// <summary>
			/// 記録日時
			/// </summary>
			public DateTime Date { get; set; }

			/// <summary>
			/// 燃料
			/// </summary>
			public int Fuel { get; set; }

			/// <summary>
			/// 弾薬
			/// </summary>
			public int Ammo { get; set; }

			/// <summary>
			/// 鋼材
			/// </summary>
			public int Steel { get; set; }

			/// <summary>
			/// ボーキサイト
			/// </summary>
			public int Bauxite { get; set; }

			/// <summary>
			/// 高速建造材
			/// </summary>
			public int InstantConstruction { get; set; }

			/// <summary>
			/// 高速修復材
			/// </summary>
			public int InstantRepair { get; set; }

			/// <summary>
			/// 開発資材
			/// </summary>
			public int DevelopmentMaterial { get; set; }

			/// <summary>
			/// 改修資材
			/// </summary>
			public int ModdingMaterial { get; set; }

			/// <summary>
			/// 艦隊司令部Lv.
			/// </summary>
			public int HQLevel { get; set; }

			/// <summary>
			/// 提督経験値
			/// </summary>
			public int HQExp { get; set; }

			public ResourceElement() {
				Date = DateTime.Now;
			}

			public ResourceElement( string line )
				: base( line ) { }

			public ResourceElement( int fuel, int ammo, int steel, int bauxite, int instantConstruction, int instantRepair, int developmentMaterial, int moddingMaterial, int hqLevel, int hqExp )
				: this() {
				Fuel = fuel;
				Ammo = ammo;
				Steel = steel;
				Bauxite = bauxite;
				InstantConstruction = instantConstruction;
				InstantRepair = instantRepair;
				DevelopmentMaterial = developmentMaterial;
				ModdingMaterial = moddingMaterial;
				HQLevel = hqLevel;
				HQExp = hqExp;
			}

			public override void LoadLine( string line ) {

				string[] elem = line.Split( ",".ToCharArray() );
				if ( elem.Length < 11 ) throw new ArgumentException( "要素数が少なすぎます。" );

				Date = DateTimeHelper.CSVStringToTime( elem[0] );
				Fuel = int.Parse( elem[1] );
				Ammo = int.Parse( elem[2] );
				Steel = int.Parse( elem[3] );
				Bauxite = int.Parse( elem[4] );
				InstantConstruction = int.Parse( elem[5] );
				InstantRepair = int.Parse( elem[6] );
				DevelopmentMaterial = int.Parse( elem[7] );
				ModdingMaterial = int.Parse( elem[8] );
				HQLevel = int.Parse( elem[9] );
				HQExp = int.Parse( elem[10] );

			}

			public override string SaveLine() {
				return string.Format( "{" + string.Join( "},{", Enumerable.Range( 0, 11 ) ) + "}",
					DateTimeHelper.TimeToCSVString( Date ),
					Fuel,
					Ammo,
					Steel,
					Bauxite,
					InstantConstruction,
					InstantRepair,
					DevelopmentMaterial,
					ModdingMaterial,
					HQLevel,
					HQExp );
			}

		}

		public List<ResourceElement> Record { get; private set; }
		private DateTime _prevTime;
		private bool _initialFlag;

		public ResourceRecord()
			: base() {

			Record = new List<ResourceElement>();
			_prevTime = DateTime.Now;
			_initialFlag = false;

			APIObserver.Instance.APIList["api_start2"].ResponseReceived += ResourceRecord_Started;
			APIObserver.Instance.APIList["api_port/port"].ResponseReceived += ResourceRecord_Updated;
		}

		private void ResourceRecord_Started( string apiname, dynamic data ) {
			_initialFlag = true;
		}

		void ResourceRecord_Updated( string apiname, dynamic data ) {

			if ( _initialFlag || DateTimeHelper.IsCrossedHour( _prevTime ) ) {
				_prevTime = DateTime.Now;
				_initialFlag = false;

				var material = KCDatabase.Instance.Material;
				var admiral = KCDatabase.Instance.Admiral;
				Record.Add( new ResourceElement(
					material.Fuel,
					material.Ammo,
					material.Steel,
					material.Bauxite,
					material.InstantConstruction,
					material.InstantRepair,
					material.DevelopmentMaterial,
					material.ModdingMaterial,
					admiral.Level,
					admiral.Exp ) );
			}
		}

		public ResourceElement this[int i] {
			get { return Record[i]; }
			set { Record[i] = value; }
		}

		/// <summary>
		/// 指定した日時以降の最も古い記録を返します。
		/// </summary>
		public ResourceElement GetRecord( DateTime target ) {

			int i;
			for ( i = Record.Count - 1; i >= 0; i-- ) {
				if ( Record[i].Date < target ) {
					i++;
					break;
				}
			}
			// Record内の全ての記録がtarget以降だった
			if ( i < 0 )
				i = 0;

			if ( 0 <= i && i < Record.Count ) {
				return Record[i];
			} else {
				return null;
			}
		}

		/// <summary>
		/// 前回の戦果更新以降の最も古い記録を返します。
		/// </summary>
		public ResourceElement GetRecordPrevious() {

			DateTime now = DateTime.Now;
			DateTime target;
			if ( now.TimeOfDay.Hours < 2 ) {
				target = new DateTime( now.Year, now.Month, now.Day, 14, 0, 0 ).Subtract( TimeSpan.FromDays( 1 ) );
			} else if ( now.TimeOfDay.Hours < 14 ) {
				target = new DateTime( now.Year, now.Month, now.Day, 2, 0, 0 );
			} else {
				target = new DateTime( now.Year, now.Month, now.Day, 14, 0, 0 );
			}

			return GetRecord( target );
		}

		/// <summary>
		/// 今日の戦果更新以降の最も古い記録を返します。
		/// </summary>
		public ResourceElement GetRecordDay() {

			DateTime now = DateTime.Now;
			DateTime target;
			if ( now.TimeOfDay.Hours < 2 ) {
				target = new DateTime( now.Year, now.Month, now.Day, 2, 0, 0 ).Subtract( TimeSpan.FromDays( 1 ) );
			} else {
				target = new DateTime( now.Year, now.Month, now.Day, 2, 0, 0 );
			}

			return GetRecord( target );
		}

		/// <summary>
		/// 今月の戦果更新以降の最も古い記録を返します。
		/// </summary>
		public ResourceElement GetRecordMonth() {
			DateTime now = DateTime.Now;

			return GetRecord( new DateTime( now.Year, now.Month, 1 ) );
		}

		protected override void LoadLine( string line ) {
			Record.Add( new ResourceElement( line ) );
		}

		protected override string SaveLines() {

			StringBuilder sb = new StringBuilder();

			var list = new List<ResourceElement>( Record );
			list.Sort( ( e1, e2 ) => e1.Date.CompareTo( e2.Date ) );

			foreach ( var elem in list ) {
				sb.AppendLine( elem.SaveLine() );
			}

			return sb.ToString();
		}

		protected override void ClearRecord() {
			Record.Clear();
		}

		//protected override bool IsAppend { get { return true; } }

		/*/
		public override bool Save( string path ) {
			bool ret = base.Save( path );

			Record.Clear();
			return ret;
		}
		//*/

		protected override string RecordHeader {
			get { return "日時,燃料,弾薬,鋼材,ボーキ,高速建造材,高速修復材,開発資材,改修資材,司令部Lv,提督Exp"; }
		}

		public override string FileName {
			get { return "ResourceRecord.csv"; }
		}
	}
}


text:
'''
Created on Aug 29 2015

@author: Kevin Chien
'''
import types

def import_resource(full_resource_name):
    index = full_resource_name.rfind(".")
    module_name = full_resource_name[0:index]
    resource_name = full_resource_name[index + 1:len(full_resource_name)]

    mod = __import__(module_name, fromlist=[resource_name])
    if hasattr(mod, resource_name):
        return getattr(mod, resource_name)
    else:
        return None

def get_class(full_path):
    index = full_path.rfind('.')
    resource_name = full_path[0:index]
    class_name = full_path[index + 1:]
    module = import_resource(resource_name)
    return getattr(module, class_name)

def enum(*sequential, **named):
    enums = dict(zip(sequential, range(len(sequential))), **named)
    reverse = dict((value, key) for key, value in enums.iteritems())
    enums['reverse'] = reverse
    obj = type('Enum', (), enums)
    obj.list = list(sequential) + named.values()
    return obj

class EqualDict(dict):
    '''
    Implement __eq__ and __ne__ functions to make dict objects compare each other by key value.
    The key value would be empty, so use compare_empty_key flag to determine whether the empty value should be compared.
    More examples can be found in test case.
    '''
    def __init__(self, d, *keys):
        super(EqualDict, self).__init__(**d)
        self.keys = keys

    def __eq__(self, other):
        if isinstance(other, dict):
            for key in self.keys:
                self_value = self.get(key)
                other_value = other.get(key)

                if self_value != other_value:
                    return False
            return True

        return False

    def __ne__(self, other):
        return not self.__eq__(other)

def merge_nested_dict(x, y):
    # store a copy of x, but overwrite with y's values where applicable
    merged = dict(x,**y)

    # if the value of merged[key] was overwritten with y[key]'s value
    # then we need to put back any missing x[key] values
    for key in x.keys():
        # if this key is a dictionary, recurse
        if type(x[key]) is types.DictType and y.has_key(key):
            merged[key] = merge_nested_dict(x[key],y[key])

    return merged

def dict_copy(d, source_keys, dest_keys):
    new_d = {}
    for source_key, dest_key in zip(source_keys, dest_keys):
        value =  d.get(source_key)
        if value:
            new_d[dest_key] = value

    return new_d


text:
del test\01-*
pause
java YUIHelper ./test 01-
pause


text:
![uniqid logo](http://i.imgur.com/OrZC1lc.png)

![unqiid npm badge](http://img.shields.io/npm/v/uniqid.svg) ![uniqid npm downloads badge](https://img.shields.io/npm/dm/uniqid.svg)

### A Unique Hexatridecimal ID generator.
It will always create unique id's based on the current time, process and machine name.

```
npm install uniqid
```

## Usage
```js
var uniqid = require('uniqid');

console.log(uniqid()); // -> 4n5pxq24kpiob12og9
console.log(uniqid(), uniqid()); // -> 4n5pxq24kriob12ogd, 4n5pxq24ksiob12ogl
```

## Features
- Very fast
- Generates unique id's on multiple processes and machines even if called at the same time.
- Shorter 8 and 12 byte versions with less uniqueness.

# How it works
- With the current time the ID's are always unique in a single process.
- With the Process ID the ID's are unique even if called at the same time from multiple processes.
- With the MAC Address the ID's are unique even if called at the same time from multiple machines and processes.

## API:
####  **uniqid(** prefix *optional string* **)**
Generate 18 byte unique id's based on the time, process id and mac address. Works on multiple processes and machines.

```js
uniqid() -> "4n5pxq24kpiob12og9"
uniqid('hello-') -> "hello-4n5pxq24kpiob12og9"
```

####  **uniqid.process(** prefix *optional string* **)**
Generate 12 byte unique id's based on the time and the process id. Works on multiple processes within a single machine but not on multiple machines.
```js
uniqid.process() -> "24ieiob0te82"
```

####  **uniqid.time(** prefix *optional string* **)**
Generate 8 byte unique id's based on the current time only. Recommended only on a single process on a single machine.

```js
uniqid.time() -> "iob0ucoj"
```

## Webpack and Browserify
Since browsers don't provide a Process ID and in most cases neither give a Mac Address using uniqid from Webpack and Browserify falls back to `uniqid.time()` for all the other methods too. The browser is the single process, single machine case anyway.

## Debug
Debug messages are turned of by default as of `v4.1.0`. To turn on debug messages you'll need to set `uniqid_debug` to `true` before you require the module.

```js
// enable debug messages
module.uniqid_debug = true

// require the module
var uniqid = require('uniqid')
```

## **License**

(The MIT License)

Copyright (c) 2014 Halász Ádám <mail@adamhalasz.com>

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

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

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
package com.github.dockerjava.jaxrs;

import static javax.ws.rs.client.Entity.entity;

import java.io.InputStream;

import javax.ws.rs.client.WebTarget;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.github.dockerjava.api.command.CopyArchiveToContainerCmd;
import com.github.dockerjava.core.DockerClientConfig;

public class CopyArchiveToContainerCmdExec extends AbstrSyncDockerCmdExec<CopyArchiveToContainerCmd, Void> implements
        CopyArchiveToContainerCmd.Exec {

    private static final Logger LOGGER = LoggerFactory.getLogger(CopyArchiveFromContainerCmdExec.class);

    public CopyArchiveToContainerCmdExec(WebTarget baseResource, DockerClientConfig dockerClientConfig) {
        super(baseResource, dockerClientConfig);
    }

    @Override
    protected Void execute(CopyArchiveToContainerCmd command) {
        WebTarget webResource = getBaseResource().path("/containers/{id}/archive").resolveTemplate("id",
                command.getContainerId());

        LOGGER.trace("PUT: " + webResource.toString());
        InputStream streamToUpload = command.getTarInputStream();
        webResource.queryParam("path", command.getRemotePath())
                .queryParam("noOverwriteDirNonDir", command.isNoOverwriteDirNonDir()).request()
                .put(entity(streamToUpload, "application/x-tar")).close();
        return null;

    }
}


text:
'use strict';

/**
 * @ngdoc function
 * @name magosApp.controller:KidsCtrl
 * @description
 * # KidsCtrl
 * Controller of the magosApp
 */
angular.module('magosApp')
  .controller('KidsCtrl', function ($scope) {

    $scope.kids = [
      {
        name: 'Aitana',
        state: '0 regalos no adscritos',
        present: true,
      },
      {
        name: 'Patricia',
        state: '4 regalos no adscritos',
        present: false,
      },
      {
        name: 'Hugo',
        state: '2 regalos no adscritos',
        present: true,
      },
    ];
  });


text:
from perms import Perm

class Group(dict):
    """The class defining a perm group."""

    def __init__(self):
        """Load up a Group instance."""
        perm = Perm()
        self[perm.label()] = perm

    # __str__ dziedziczone z dict

    order = dict.__len__            # the group order

    def insert(self, perm):
        """The perm inserted into the group generates new
        perms in order to satisfy the group properties."""
        if perm in self:
            return
        old_order = self.order()
        label1 = perm.label()
        self[label1] = perm
        perms_added = dict()
        perms_added[label1] = perm
        perms_generated = dict()
        new_order = self.order()
        while new_order > old_order:
            old_order = new_order
            for label1 in perms_added:
                for label2 in self.iterlabels():
                    perm3 = perms_added[label1] * self[label2]
                    label3 = perm3.label()
                    if perm3 not in self:
                        perms_generated[label3] = perm3
            self.update(perms_generated)
            perms_added = perms_generated
            perms_generated = dict()
            new_order = self.order()

    def __contains__(self, perm):   # perm in group
        """ Test if the perm belongs to the group."""
        return dict.__contains__(self, perm.label())

    def iterperms(self):
        """The generator for perms from the group."""
        for key in self:
            yield self[key]

    def iterlabels(self):
        """The generator for perm labels from the group."""
        for key in self:
            yield key

    def is_trivial(self):
        """Test if the group is trivial."""
        return self.order() == 1

    def orbits(self, points):
        """Return a list of orbits."""
        used = dict()   # set can be used
        orbit_list = list()
        for pt1 in points:
            if pt1 in used:
                continue
            orbit = [pt1]     # we start a new orbit
            used[pt1] = True
            for perm in self.iterperms():
                pt2 = perm[pt1]
                if pt2 not in used:
                    orbit.append(pt2)
                    used[pt2] = True
            orbit_list.append(orbit)
        return orbit_list

    def is_transitive(self, points, strict=True):
        """Test if the group is transitive (has a single orbit).
        If strict is False the group is transitive if it has
        a single orbit of length different from 1.
        """
        # Jest problem, bo nie ma self.size dla grupy.
        if strict:
            return len(self.orbits(points)) == 1
        else:   # ignorujemy nieruchome punkty
            number = sum(1 for orbit in self.orbits(points) if len(orbit) > 1)
            return number == 1

    def subgroup_search(self, prop):
        """Return a subgroup of all elements satisfying the property."""
        # Jezeli prop(perm) jest True, to perm zaliczamy do podgrupy.
        # Funkcja prop() nie moze byc byle jaka.
        new_group = Group()
        for perm in self.iterperms():
            if prop(perm):
                new_group.insert(perm)
        return new_group

    def stabilizer(self, point):
        """Return a stabilizer subgroup."""
        return self.subgroup_search(
            lambda perm: perm[point] == point)

    def centralizer(self, other):
        """G.centralizer(H) - return the centralizer of H."""
        if other.is_trivial() or self.is_trivial():
            return self
        return self.subgroup_search(lambda perm:
            all(perm * perm2 == perm2 * perm for perm2 in other.iterperms()))

    def center(self):
        """Return the center of the group."""
        return self.centralizer(self)

    def normalizer(self, other):
        """G.normalizer(H) - return the normalizer of H."""
        return self.subgroup_search(lambda perm:
            all((perm * perm2 * ~perm in other) for perm2 in other.iterperms()))

    def is_abelian(self):
        """Test if the group is abelian."""
        for perm1 in self.iterperms():
            for perm2 in self.iterperms():
                # Trzeba umiec porownywac perms.
                #if perm2 <= perm1:
                    #continue
                if not perm1.commutes_with(perm2):
                    return False
        return True

    def is_subgroup(self, other):
        """H.is_subgroup(G) - test if H is a subgroup of G.
        Return True if all elements of H belong to G.
        """
        if other.order() % self.order() != 0:
            return False
        return all(perm in other for perm in self.iterperms())

    def is_normal(self, other):
        """H.is_normal(G) - test if H is a normal subgroup of G.
        For each h in H, g in G, g*h*~g belongs to H.
        """
        for perm1 in self.iterperms():
            for perm2 in other.iterperms():
                if perm2 * perm1 * ~perm2 not in self:
                    return False
        return True

    def normal_closure(self, other):
        """Return the normal closure (conjugate closure)."""
        new_group = Group()
        for perm1 in self.iterperms():
            for perm2 in other.iterperms():
                new_group.insert(perm1 * perm2 * ~perm1)
        return new_group

    def commutator(self, group1, group2):
        """Return the commutator of the groups."""
        new_group = Group()
        for perm1 in group1.iterperms():
            for perm2 in group2.iterperms():
                new_group.insert(perm1.commutator(perm2))
        return new_group

    def derived_subgroup(self):
        """Return the derived subgroup of the group."""
        return self.commutator(self, self)

    def action(self, points):
        """Return a new group induced by the action."""
        # Sprawdzamy, czy grupa jest tranzytywna na punktach.
        if not self.is_transitive(points):
            raise TypeError("the group is not transitive on points")
        adict = dict()   # for numbering of points
        for i, pt in enumerate(points):
            adict[pt] = i
        new_group = Group()
        for perm in self.iterperms():
            new_data = [adict[perm[pt]] for pt in points]
            new_group.insert(Perm(data=new_data))
        return new_group

# EOF


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="gov.nih.nci.caintegrator.domain.application">
	<class name="UserWorkspace" table="USER_WORKSPACE" lazy="false" polymorphism="explicit">
		<cache usage="read-write" />
		<id name="id" type="long" column="ID">
			<generator class="native" />
		</id>
		<property name="username" type="string" column="USERNAME"/>
		<!-- Attributes mapping for the UserWorkspace class -->
		<!-- Associations mapping for the UserWorkspace class -->
		<many-to-one name="defaultSubscription" class="gov.nih.nci.caintegrator.domain.application.StudySubscription" column="DEFAULT_STUDY_SUBSCRIPTION_ID" unique="true" lazy="proxy" cascade="save-update,merge"/>
		<set name="subscriptionCollection" lazy="true" cascade="save-update,merge" >
			<cache usage="read-write" />
			<key column="USER_WORKSPACE_ID" />
			<one-to-many class="gov.nih.nci.caintegrator.domain.application.StudySubscription"/>
		</set>
	</class>
</hibernate-mapping>


text:
cd %~dp0
cd ..

tools\fastcopy.exe /auto_close Z:\abanu /to="C:\Temp\abanu"

c:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe C:\Temp\abanu\src\abanu.sln

cd C:\Temp\abanu\internal


text:
#include "dcmtk/config/osconfig.h"    /* make sure OS specific configuration is included first */

#include "dcmtk/dcmsr/dsrimgvl.h"
#include "dcmtk/dcmsr/dsrxmld.h"
#include "dcmtk/dcmimgle/dcmimage.h"
#include "dcmtk/dcmimgle/diutils.h"
#include "dcmtk/dcmimage/diregist.h"  /* add support for color images */

DSRImageReferenceValue::DSRImageReferenceValue()
  : DSRCompositeReferenceValue(),
    PresentationState(),
    FrameList(),
    IconImage(NULL)
{
}

DSRImageReferenceValue::DSRImageReferenceValue(const OFString &sopClassUID,
                                               const OFString &sopInstanceUID,
                                               const OFBool check)
  : DSRCompositeReferenceValue(),
    PresentationState(),
    FrameList(),
    IconImage(NULL)
{
    /* use the set method for checking purposes */
    setReference(sopClassUID, sopInstanceUID, check);
}

DSRImageReferenceValue::DSRImageReferenceValue(const OFString &imageSOPClassUID,
                                               const OFString &imageSOPInstanceUID,
                                               const OFString &pstateSOPClassUID,
                                               const OFString &pstateSOPInstanceUID,
                                               const OFBool check)
  : DSRCompositeReferenceValue(),
    PresentationState(),
    FrameList(),
    IconImage(NULL)
{
    /* use the set methods for checking purposes */
    setReference(imageSOPClassUID, imageSOPInstanceUID, check);
    setPresentationState(DSRCompositeReferenceValue(pstateSOPClassUID, pstateSOPInstanceUID, OFFalse /*check*/), check);
}

DSRImageReferenceValue::DSRImageReferenceValue(const DSRImageReferenceValue &referenceValue)
  : DSRCompositeReferenceValue(referenceValue),
    PresentationState(referenceValue.PresentationState),
    FrameList(referenceValue.FrameList),
    IconImage(NULL)
{
    /* do not check values since this would be unexpected to the user */

    /* create copy of icon image (if any), first frame only */
    if (referenceValue.IconImage != NULL)
        IconImage = referenceValue.IconImage->createDicomImage(0 /*fstart*/, 1 /*fcount*/);
}

DSRImageReferenceValue::DSRImageReferenceValue(const DSRCompositeReferenceValue &imageReferenceValue,
                                               const DSRCompositeReferenceValue &pstateReferenceValue)
  : DSRCompositeReferenceValue(imageReferenceValue),
    PresentationState(pstateReferenceValue),
    FrameList(),
    IconImage(NULL)
{
}

DSRImageReferenceValue::~DSRImageReferenceValue()
{
    deleteIconImage();
}

DSRImageReferenceValue &DSRImageReferenceValue::operator=(const DSRImageReferenceValue &referenceValue)
{
    DSRCompositeReferenceValue::operator=(referenceValue);
    /* do not check since this would be unexpected to the user */
    PresentationState = referenceValue.PresentationState;
    FrameList = referenceValue.FrameList;
    /* create copy of icon image (if any), first frame only */
    IconImage = (referenceValue.IconImage != NULL) ? referenceValue.IconImage->createDicomImage(0 /*fstart*/, 1 /*fcount*/) : NULL;
    return *this;
}

void DSRImageReferenceValue::clear()
{
    DSRCompositeReferenceValue::clear();
    PresentationState.clear();
    FrameList.clear();
    deleteIconImage();
}

OFBool DSRImageReferenceValue::isValid() const
{
    return DSRCompositeReferenceValue::isValid() && checkPresentationState(PresentationState).good();
}

OFBool DSRImageReferenceValue::isShort(const size_t flags) const
{
    return FrameList.isEmpty() || !(flags & DSRTypes::HF_renderFullData);
}

OFCondition DSRImageReferenceValue::print(STD_NAMESPACE ostream &stream,
                                          const size_t flags) const
{
    const char *modality = dcmSOPClassUIDToModality(SOPClassUID.c_str());
    stream << "(";
    if (modality != NULL)
        stream << modality << " image";
    else
        stream << "\"" << SOPClassUID << "\"";
    stream << ",";
    if (flags & DSRTypes::PF_printSOPInstanceUID)
        stream << "\"" << SOPInstanceUID << "\"";
    if (!FrameList.isEmpty())
    {
        stream << ",";
        FrameList.print(stream, flags);
    }
    stream << ")";
    if (PresentationState.isValid())
    {
        const DSRTypes::E_PresentationStateType pstateType = DSRTypes::sopClassUIDToPresentationStateType(PresentationState.getSOPClassUID());
        if (pstateType != DSRTypes::PT_invalid)
            stream << ",(" << DSRTypes::presentationStateTypeToShortName(pstateType) << ",";
        else
            stream << ",(" << PresentationState.getSOPClassUID() << ",";
        if (flags & DSRTypes::PF_printSOPInstanceUID)
            stream << "\"" << PresentationState.getSOPInstanceUID() << "\"";
        stream << ")";
    }
    return EC_Normal;
}

OFCondition DSRImageReferenceValue::readXML(const DSRXMLDocument &doc,
                                            DSRXMLCursor cursor)
{
    /* first read general composite reference information */
    OFCondition result = DSRCompositeReferenceValue::readXML(doc, cursor);
    /* then read image related XML tags */
    if (result.good())
    {
        /* frame list (optional) */
        const DSRXMLCursor childCursor = doc.getNamedNode(cursor.getChild(), "frames", OFFalse /*required*/);
        if (childCursor.valid())
        {
            OFString tmpString;
            /* put element content to the channel list */
            result = FrameList.putString(doc.getStringFromNodeContent(childCursor, tmpString).c_str());
        }
        if (result.good())
        {
            /* presentation state (optional) */
            cursor = doc.getNamedNode(cursor.getChild(), "pstate", OFFalse /*required*/);
            if (cursor.getChild().valid())
                result = PresentationState.readXML(doc, cursor);
        }
    }
    return result;
}

OFCondition DSRImageReferenceValue::writeXML(STD_NAMESPACE ostream &stream,
                                             const size_t flags) const
{
    OFCondition result = DSRCompositeReferenceValue::writeXML(stream, flags);
    if ((flags & DSRTypes::XF_writeEmptyTags) || !FrameList.isEmpty())
    {
        stream << "<frames>";
        FrameList.print(stream);
        stream << "</frames>" << OFendl;
    }
    if ((flags & DSRTypes::XF_writeEmptyTags) || PresentationState.isValid())
    {
        stream << "<pstate>" << OFendl;
        if (PresentationState.isValid())
            PresentationState.writeXML(stream, flags);
        stream << "</pstate>" << OFendl;
    }
    return result;
}

OFCondition DSRImageReferenceValue::readItem(DcmItem &dataset)
{
    /* be very careful, delete any previously created icon image (should never apply) */
    deleteIconImage();
    /* read ReferencedSOPClassUID and ReferencedSOPInstanceUID */
    OFCondition result = DSRCompositeReferenceValue::readItem(dataset);
    /* read ReferencedFrameNumber (conditional) */
    if (result.good())
        FrameList.read(dataset);
    /* read ReferencedSOPSequence (Presentation State, optional) */
    if (result.good())
        PresentationState.readSequence(dataset, "3" /*type*/);
    /* read IconImageSequence (optional) */
    if (result.good())
    {
        DcmSequenceOfItems dseq(DCM_IconImageSequence);
        /* use local status variable since the sequence is optional */
        const OFCondition seqStatus = DSRTypes::getElementFromDataset(dataset, dseq);
        DSRTypes::checkElementValue(dseq, "1", "3", seqStatus, "IMAGE content item");
        if (seqStatus.good())
        {
            /* check for empty sequence (allowed!) */
            if (!dseq.isEmpty())
            {
                /* read first item */
                DcmItem *ditem = dseq.getItem(0);
                if ((ditem != NULL) && !ditem->isEmpty())
                {
                    /* try to load/process the icon image */
                    IconImage = new DicomImage(ditem, EXS_LittleEndianExplicit);
                    if (IconImage != NULL)
                    {
                        if (IconImage->getStatus() != EIS_Normal)
                            result = SR_EC_CannotCreateIconImage;
                    } else
                        result = EC_MemoryExhausted;
                } else
                    result = SR_EC_InvalidDocumentTree;
            }
        }
    }
    return result;
}

OFCondition DSRImageReferenceValue::writeItem(DcmItem &dataset) const
{
    /* write ReferencedSOPClassUID and ReferencedSOPInstanceUID */
    OFCondition result = DSRCompositeReferenceValue::writeItem(dataset);
    /* write ReferencedFrameNumber (conditional) */
    if (result.good())
    {
        if (!FrameList.isEmpty())
            result = FrameList.write(dataset);
    }
    /* write ReferencedSOPSequence (Presentation State, optional) */
    if (result.good())
    {
        if (PresentationState.isValid())
            result = PresentationState.writeSequence(dataset);
    }
    /* write IconImageSequence (optional) */
    if (result.good() && (IconImage != NULL))
    {
        DcmItem *ditem = NULL;
        /* create sequence with a single item */
        result = dataset.findOrCreateSequenceItem(DCM_IconImageSequence, ditem, 0 /*position*/);
        if (result.good())
        {
            /* write icon image */
            if (IconImage->writeFrameToDataset(*ditem))
            {
                /* delete unwanted element NumberOfFrames (0028,0008) */
                ditem->findAndDeleteElement(DCM_NumberOfFrames);
            } else
                result = EC_CorruptedData;
        }
    }
    return result;
}

OFCondition DSRImageReferenceValue::renderHTML(STD_NAMESPACE ostream &docStream,
                                               STD_NAMESPACE ostream &annexStream,
                                               size_t &annexNumber,
                                               const size_t flags) const
{
    /* reference: image */
    docStream << "<a href=\"" << HTML_HYPERLINK_PREFIX_FOR_CGI;
    docStream << "?image=" << SOPClassUID << "+" << SOPInstanceUID;
    /* reference: pstate */
    if (PresentationState.isValid())
    {
        docStream << "&pstate=" << PresentationState.getSOPClassUID();
        docStream << "+" << PresentationState.getSOPInstanceUID();
    }
    /* reference: frames */
    if (!FrameList.isEmpty())
    {
        docStream << "&frames=";
        FrameList.print(docStream, 0 /*flags*/, '+');
    }
    docStream << "\">";
    /* text: image */
    const char *modality = dcmSOPClassUIDToModality(SOPClassUID.c_str());
    if (modality != NULL)
        docStream << modality;
    else
        docStream << "unknown";
    docStream << " image";
    /* text: pstate */
    if (PresentationState.isValid())
        docStream << " with presentation state";
    docStream << "";
    if (!isShort(flags))
    {
        const char *lineBreak = (flags & DSRTypes::HF_renderSectionTitlesInline) ? " " :
                                (flags & DSRTypes::HF_XHTML11Compatibility) ? "
" : "
";
        if (flags & DSRTypes::HF_currentlyInsideAnnex)
        {
            docStream << OFendl << "
" << OFendl;
            /* render frame list (= print)*/
            docStream << "Referenced Frame Number:" << lineBreak;
            FrameList.print(docStream);
            docStream << "
";
        } else {
            docStream << " ";
            DSRTypes::createHTMLAnnexEntry(docStream, annexStream, "for more details see", annexNumber, flags);
            annexStream << "
" << OFendl;
            /* render frame list (= print)*/
            annexStream << "Referenced Frame Number:" << lineBreak;
            FrameList.print(annexStream);
            annexStream << "
" << OFendl;
        }
    }
    return EC_Normal;
}

OFCondition DSRImageReferenceValue::createIconImage(const OFString &filename,
                                                    const unsigned long frame,
                                                    const unsigned long width,
                                                    const unsigned long height)
{
    /* delete old icon image (if any) */
    deleteIconImage();
    OFCondition result = EC_IllegalParameter;
    if (!filename.empty())
    {
        /* try to load specified DICOM image */
        const unsigned long flags = CIF_UsePartialAccessToPixelData | CIF_NeverAccessEmbeddedOverlays;
        DicomImage *image = new DicomImage(filename.c_str(), flags, frame, 1 /*fcount*/);
        if (image != NULL)
        {
            /* set VOI window (for monochrome images) */
            if (image->isMonochrome() && !image->setWindow(0))
                image->setMinMaxWindow();
            /* do the real work: create a down-scaled version of the DICOM image */
            result = createIconImage(image, width, height);
            delete image;
        } else
            result = EC_MemoryExhausted;
    }
    return result;
}

OFCondition DSRImageReferenceValue::createIconImage(DcmObject *object,
                                                    const E_TransferSyntax xfer,
                                                    const unsigned long frame,
                                                    const unsigned long width,
                                                    const unsigned long height)
{
    /* delete old icon image (if any) */
    deleteIconImage();
    OFCondition result = EC_IllegalParameter;
    if (object != NULL)
    {
        /* try to load specified DICOM image */
        const unsigned long flags = CIF_UsePartialAccessToPixelData | CIF_NeverAccessEmbeddedOverlays;
        DicomImage *image = new DicomImage(object, xfer, flags, frame, 1 /*fcount*/);
        if (image != NULL)
        {
            /* set VOI window (for monochrome images) */
            if (image->isMonochrome() && !image->setWindow(0))
                image->setMinMaxWindow();
            /* do the real work: create a down-scaled version of the DICOM image */
            result = createIconImage(image, width, height);
            delete image;
        } else
            result = EC_MemoryExhausted;
    }
    return result;
}

OFCondition DSRImageReferenceValue::createIconImage(const DicomImage *image,
                                                    const unsigned long width,
                                                    const unsigned long height)
{
    /* delete old icon image (if any) */
    deleteIconImage();
    OFCondition result = EC_IllegalParameter;
    if (image != NULL)
    {
        const EI_Status imageStatus = image->getStatus();
        /* check whether image loading/processing was successful */
        switch (imageStatus)
        {
            case EIS_Normal:
            {
                if (image->getFrameCount() > 1)
                    DCMSR_DEBUG("DICOM image passed for creating an icon image contains multiple frames");
                /* create a down-scaled version of the DICOM image */
                const int aspect = (width == 0) || (height == 0);
                IconImage = image->createScaledImage(width, height, 1 /*interpolate*/, aspect);
                result = (IconImage != NULL) ? EC_Normal : SR_EC_CannotCreateIconImage;
                break;
            }
            case EIS_InvalidDocument:
            case EIS_InvalidImage:
                result = SR_EC_InvalidDocument;
                break;
            case EIS_MissingAttribute:
                result = SR_EC_MandatoryAttributeMissing;
                break;
            case EIS_InvalidValue:
                result = SR_EC_InvalidValue;
                break;
            case EIS_NotSupportedValue:
                result = SR_EC_UnsupportedValue;
                break;
            case EIS_MemoryFailure:
                result = EC_MemoryExhausted;
                break;
            default:
                /* this is the fallback for all other kind of errors */
                result = SR_EC_CannotCreateIconImage;
                break;
        }
    }
    return result;
}

void DSRImageReferenceValue::deleteIconImage()
{
    delete IconImage;
    IconImage = NULL;
}

OFCondition DSRImageReferenceValue::getValue(DSRImageReferenceValue &referenceValue) const
{
    referenceValue = *this;
    return EC_Normal;
}

OFCondition DSRImageReferenceValue::setValue(const DSRImageReferenceValue &referenceValue,
                                             const OFBool check)
{
    OFCondition result = DSRCompositeReferenceValue::setValue(referenceValue, check);
    if (result.good())
    {
        FrameList = referenceValue.FrameList;
        /* ignore status (return value) since the presentation state is optional */
        setPresentationState(referenceValue.PresentationState, check);
    }
    return result;
}

OFCondition DSRImageReferenceValue::setPresentationState(const DSRCompositeReferenceValue &pstateValue,
                                                         const OFBool check)
{
    OFCondition result = EC_Normal;
    /* check whether the passed value is valid */
    if (check)
        result = checkPresentationState(pstateValue);
    /* both UID values need to be empty or non-empty (optional) */
    else if (pstateValue.getSOPClassUID().empty() != pstateValue.getSOPInstanceUID().empty())
        result = SR_EC_InvalidValue;
    if (result.good())
        PresentationState = pstateValue;
    return result;
}

OFBool DSRImageReferenceValue::appliesToFrame(const Sint32 frameNumber) const
{
    OFBool result = OFTrue;
    if (!FrameList.isEmpty())
        result = FrameList.isElement(frameNumber);
    return result;
}

OFCondition DSRImageReferenceValue::checkSOPClassUID(const OFString &sopClassUID) const
{
    OFCondition result = DSRCompositeReferenceValue::checkSOPClassUID(sopClassUID);
    if (result.good())
    {
        /* tbd: might check for known IMAGE storage class later on */
    }
    return result;
}

OFCondition DSRImageReferenceValue::checkPresentationState(const DSRCompositeReferenceValue &referenceValue) const
{
    OFCondition result = EC_Normal;
    /* the reference to a presentation state is optional, so an empty value is also valid */
    if (!referenceValue.isEmpty())
    {
        result = referenceValue.checkCurrentValue();
        if (result.good() && (DSRTypes::sopClassUIDToPresentationStateType(referenceValue.getSOPClassUID()) == DSRTypes::PT_invalid))
            result = SR_EC_InvalidValue;
    }
    return result;
}


text:
/**
 * Paquete que ofrece las clases para poder generar y acceder a las gramáticas en las que se basa
 * la constucción de los distintos árboles que componen los individuos.
 *
 *
 * @author jirsis
 * @since 2.0
 * @see progen.kernel
 */
package progen.kernel.grammar;


text:
package com.bilibili.socialize.share.download;

/**
 * @author Jungly
 * @email jungly.ik@gmail.com
 * @since 2015/10/24 22:59
 */
public class DefaultImageDownloader extends AbsImageDownloader {

    @Override
    protected void downloadDirectly(String imageUrl, String filePath, OnImageDownloadListener listener) {
        if (listener != null) {
            listener.onStart();
        }
        new DefaultImageDownLoadTask(imageUrl, filePath, listener).start();
    }

}


text:
#include <linux/atomic.h>
#include <linux/export.h>
#include <linux/init.h>
#include <linux/irqchip/metag.h>
#include <linux/perf_event.h>
#include <linux/slab.h>

#include <asm/core_reg.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/processor.h>

#include "perf_event.h"

static int _hw_perf_event_init(struct perf_event *);
static void _hw_perf_event_destroy(struct perf_event *);

/* Determines which core type we are */
static struct metag_pmu *metag_pmu __read_mostly;

/* Processor specific data */
static DEFINE_PER_CPU(struct cpu_hw_events, cpu_hw_events);

/* PMU admin */
const char *perf_pmu_name(void)
{
	if (!metag_pmu)
		return NULL;

	return metag_pmu->name;
}
EXPORT_SYMBOL_GPL(perf_pmu_name);

int perf_num_counters(void)
{
	if (metag_pmu)
		return metag_pmu->max_events;

	return 0;
}
EXPORT_SYMBOL_GPL(perf_num_counters);

static inline int metag_pmu_initialised(void)
{
	return !!metag_pmu;
}

static void release_pmu_hardware(void)
{
	int irq;
	unsigned int version = (metag_pmu->version &
			(METAC_ID_MINOR_BITS | METAC_ID_REV_BITS)) >>
			METAC_ID_REV_S;

	/* Early cores don't have overflow interrupts */
	if (version < 0x0104)
		return;

	irq = internal_irq_map(17);
	if (irq >= 0)
		free_irq(irq, (void *)1);

	irq = internal_irq_map(16);
	if (irq >= 0)
		free_irq(irq, (void *)0);
}

static int reserve_pmu_hardware(void)
{
	int err = 0, irq[2];
	unsigned int version = (metag_pmu->version &
			(METAC_ID_MINOR_BITS | METAC_ID_REV_BITS)) >>
			METAC_ID_REV_S;

	/* Early cores don't have overflow interrupts */
	if (version < 0x0104)
		goto out;

	/*
	 * Bit 16 on HWSTATMETA is the interrupt for performance counter 0;
	 * similarly, 17 is the interrupt for performance counter 1.
	 * We can't (yet) interrupt on the cycle counter, because it's a
	 * register, however it holds a 32-bit value as opposed to 24-bit.
	 */
	irq[0] = internal_irq_map(16);
	if (irq[0] < 0) {
		pr_err("unable to map internal IRQ %d\n", 16);
		goto out;
	}
	err = request_irq(irq[0], metag_pmu->handle_irq, IRQF_NOBALANCING,
			"metagpmu0", (void *)0);
	if (err) {
		pr_err("unable to request IRQ%d for metag PMU counters\n",
				irq[0]);
		goto out;
	}

	irq[1] = internal_irq_map(17);
	if (irq[1] < 0) {
		pr_err("unable to map internal IRQ %d\n", 17);
		goto out_irq1;
	}
	err = request_irq(irq[1], metag_pmu->handle_irq, IRQF_NOBALANCING,
			"metagpmu1", (void *)1);
	if (err) {
		pr_err("unable to request IRQ%d for metag PMU counters\n",
				irq[1]);
		goto out_irq1;
	}

	return 0;

out_irq1:
	free_irq(irq[0], (void *)0);
out:
	return err;
}

/* PMU operations */
static void metag_pmu_enable(struct pmu *pmu)
{
}

static void metag_pmu_disable(struct pmu *pmu)
{
}

static int metag_pmu_event_init(struct perf_event *event)
{
	int err = 0;
	atomic_t *active_events = &metag_pmu->active_events;

	if (!metag_pmu_initialised()) {
		err = -ENODEV;
		goto out;
	}

	if (has_branch_stack(event))
		return -EOPNOTSUPP;

	event->destroy = _hw_perf_event_destroy;

	if (!atomic_inc_not_zero(active_events)) {
		mutex_lock(&metag_pmu->reserve_mutex);
		if (atomic_read(active_events) == 0)
			err = reserve_pmu_hardware();

		if (!err)
			atomic_inc(active_events);

		mutex_unlock(&metag_pmu->reserve_mutex);
	}

	/* Hardware and caches counters */
	switch (event->attr.type) {
	case PERF_TYPE_HARDWARE:
	case PERF_TYPE_HW_CACHE:
	case PERF_TYPE_RAW:
		err = _hw_perf_event_init(event);
		break;

	default:
		return -ENOENT;
	}

	if (err)
		event->destroy(event);

out:
	return err;
}

void metag_pmu_event_update(struct perf_event *event,
		struct hw_perf_event *hwc, int idx)
{
	u64 prev_raw_count, new_raw_count;
	s64 delta;

	/*
	 * If this counter is chained, it may be that the previous counter
	 * value has been changed beneath us.
	 *
	 * To get around this, we read and exchange the new raw count, then
	 * add the delta (new - prev) to the generic counter atomically.
	 *
	 * Without interrupts, this is the simplest approach.
	 */
again:
	prev_raw_count = local64_read(&hwc->prev_count);
	new_raw_count = metag_pmu->read(idx);

	if (local64_cmpxchg(&hwc->prev_count, prev_raw_count,
			new_raw_count) != prev_raw_count)
		goto again;

	/*
	 * Calculate the delta and add it to the counter.
	 */
	delta = (new_raw_count - prev_raw_count) & MAX_PERIOD;

	local64_add(delta, &event->count);
	local64_sub(delta, &hwc->period_left);
}

int metag_pmu_event_set_period(struct perf_event *event,
		struct hw_perf_event *hwc, int idx)
{
	s64 left = local64_read(&hwc->period_left);
	s64 period = hwc->sample_period;
	int ret = 0;

	/* The period may have been changed */
	if (unlikely(period != hwc->last_period))
		left += period - hwc->last_period;

	if (unlikely(left <= -period)) {
		left = period;
		local64_set(&hwc->period_left, left);
		hwc->last_period = period;
		ret = 1;
	}

	if (unlikely(left <= 0)) {
		left += period;
		local64_set(&hwc->period_left, left);
		hwc->last_period = period;
		ret = 1;
	}

	if (left > (s64)metag_pmu->max_period)
		left = metag_pmu->max_period;

	if (metag_pmu->write) {
		local64_set(&hwc->prev_count, -(s32)left);
		metag_pmu->write(idx, -left & MAX_PERIOD);
	}

	perf_event_update_userpage(event);

	return ret;
}

static void metag_pmu_start(struct perf_event *event, int flags)
{
	struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
	struct hw_perf_event *hwc = &event->hw;
	int idx = hwc->idx;

	if (WARN_ON_ONCE(idx == -1))
		return;

	/*
	 * We always have to reprogram the period, so ignore PERF_EF_RELOAD.
	 */
	if (flags & PERF_EF_RELOAD)
		WARN_ON_ONCE(!(hwc->state & PERF_HES_UPTODATE));

	hwc->state = 0;

	/*
	 * Reset the period.
	 * Some counters can't be stopped (i.e. are core global), so when the
	 * counter was 'stopped' we merely disabled the IRQ. If we don't reset
	 * the period, then we'll either: a) get an overflow too soon;
	 * or b) too late if the overflow happened since disabling.
	 * Obviously, this has little bearing on cores without the overflow
	 * interrupt, as the performance counter resets to zero on write
	 * anyway.
	 */
	if (metag_pmu->max_period)
		metag_pmu_event_set_period(event, hwc, hwc->idx);
	cpuc->events[idx] = event;
	metag_pmu->enable(hwc, idx);
}

static void metag_pmu_stop(struct perf_event *event, int flags)
{
	struct hw_perf_event *hwc = &event->hw;

	/*
	 * We should always update the counter on stop; see comment above
	 * why.
	 */
	if (!(hwc->state & PERF_HES_STOPPED)) {
		metag_pmu_event_update(event, hwc, hwc->idx);
		metag_pmu->disable(hwc, hwc->idx);
		hwc->state |= PERF_HES_STOPPED | PERF_HES_UPTODATE;
	}
}

static int metag_pmu_add(struct perf_event *event, int flags)
{
	struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
	struct hw_perf_event *hwc = &event->hw;
	int idx = 0, ret = 0;

	perf_pmu_disable(event->pmu);

	/* check whether we're counting instructions */
	if (hwc->config == 0x100) {
		if (__test_and_set_bit(METAG_INST_COUNTER,
				cpuc->used_mask)) {
			ret = -EAGAIN;
			goto out;
		}
		idx = METAG_INST_COUNTER;
	} else {
		/* Check whether we have a spare counter */
		idx = find_first_zero_bit(cpuc->used_mask,
				atomic_read(&metag_pmu->active_events));
		if (idx >= METAG_INST_COUNTER) {
			ret = -EAGAIN;
			goto out;
		}

		__set_bit(idx, cpuc->used_mask);
	}
	hwc->idx = idx;

	/* Make sure the counter is disabled */
	metag_pmu->disable(hwc, idx);

	hwc->state = PERF_HES_STOPPED | PERF_HES_UPTODATE;
	if (flags & PERF_EF_START)
		metag_pmu_start(event, PERF_EF_RELOAD);

	perf_event_update_userpage(event);
out:
	perf_pmu_enable(event->pmu);
	return ret;
}

static void metag_pmu_del(struct perf_event *event, int flags)
{
	struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
	struct hw_perf_event *hwc = &event->hw;
	int idx = hwc->idx;

	WARN_ON(idx < 0);
	metag_pmu_stop(event, PERF_EF_UPDATE);
	cpuc->events[idx] = NULL;
	__clear_bit(idx, cpuc->used_mask);

	perf_event_update_userpage(event);
}

static void metag_pmu_read(struct perf_event *event)
{
	struct hw_perf_event *hwc = &event->hw;

	/* Don't read disabled counters! */
	if (hwc->idx < 0)
		return;

	metag_pmu_event_update(event, hwc, hwc->idx);
}

static struct pmu pmu = {
	.pmu_enable	= metag_pmu_enable,
	.pmu_disable	= metag_pmu_disable,

	.event_init	= metag_pmu_event_init,

	.add		= metag_pmu_add,
	.del		= metag_pmu_del,
	.start		= metag_pmu_start,
	.stop		= metag_pmu_stop,
	.read		= metag_pmu_read,
};

/* Core counter specific functions */
static const int metag_general_events[] = {
	[PERF_COUNT_HW_CPU_CYCLES] = 0x03,
	[PERF_COUNT_HW_INSTRUCTIONS] = 0x100,
	[PERF_COUNT_HW_CACHE_REFERENCES] = -1,
	[PERF_COUNT_HW_CACHE_MISSES] = -1,
	[PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = -1,
	[PERF_COUNT_HW_BRANCH_MISSES] = -1,
	[PERF_COUNT_HW_BUS_CYCLES] = -1,
	[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] = -1,
	[PERF_COUNT_HW_STALLED_CYCLES_BACKEND] = -1,
	[PERF_COUNT_HW_REF_CPU_CYCLES] = -1,
};

static const int metag_pmu_cache_events[C(MAX)][C(OP_MAX)][C(RESULT_MAX)] = {
	[C(L1D)] = {
		[C(OP_READ)] = {
			[C(RESULT_ACCESS)] = 0x08,
			[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
		},
		[C(OP_WRITE)] = {
			[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
			[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
		},
		[C(OP_PREFETCH)] = {
			[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
			[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
		},
	},
	[C(L1I)] = {
		[C(OP_READ)] = {
			[C(RESULT_ACCESS)] = 0x09,
			[C(RESULT_MISS)] = 0x0a,
		},
		[C(OP_WRITE)] = {
			[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
			[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
		},
		[C(OP_PREFETCH)] = {
			[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
			[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
		},
	},
	[C(LL)] = {
		[C(OP_READ)] = {
			[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
			[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
		},
		[C(OP_WRITE)] = {
			[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
			[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
		},
		[C(OP_PREFETCH)] = {
			[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
			[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
		},
	},
	[C(DTLB)] = {
		[C(OP_READ)] = {
			[C(RESULT_ACCESS)] = 0xd0,
			[C(RESULT_MISS)] = 0xd2,
		},
		[C(OP_WRITE)] = {
			[C(RESULT_ACCESS)] = 0xd4,
			[C(RESULT_MISS)] = 0xd5,
		},
		[C(OP_PREFETCH)] = {
			[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
			[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
		},
	},
	[C(ITLB)] = {
		[C(OP_READ)] = {
			[C(RESULT_ACCESS)] = 0xd1,
			[C(RESULT_MISS)] = 0xd3,
		},
		[C(OP_WRITE)] = {
			[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
			[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
		},
		[C(OP_PREFETCH)] = {
			[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
			[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
		},
	},
	[C(BPU)] = {
		[C(OP_READ)] = {
			[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
			[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
		},
		[C(OP_WRITE)] = {
			[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
			[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
		},
		[C(OP_PREFETCH)] = {
			[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
			[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
		},
	},
	[C(NODE)] = {
		[C(OP_READ)] = {
			[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
			[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
		},
		[C(OP_WRITE)] = {
			[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
			[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
		},
		[C(OP_PREFETCH)] = {
			[C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED,
			[C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED,
		},
	},
};

static void _hw_perf_event_destroy(struct perf_event *event)
{
	atomic_t *active_events = &metag_pmu->active_events;
	struct mutex *pmu_mutex = &metag_pmu->reserve_mutex;

	if (atomic_dec_and_mutex_lock(active_events, pmu_mutex)) {
		release_pmu_hardware();
		mutex_unlock(pmu_mutex);
	}
}

static int _hw_perf_cache_event(int config, int *evp)
{
	unsigned long type, op, result;
	int ev;

	if (!metag_pmu->cache_events)
		return -EINVAL;

	/* Unpack config */
	type = config & 0xff;
	op = (config >> 8) & 0xff;
	result = (config >> 16) & 0xff;

	if (type >= PERF_COUNT_HW_CACHE_MAX ||
			op >= PERF_COUNT_HW_CACHE_OP_MAX ||
			result >= PERF_COUNT_HW_CACHE_RESULT_MAX)
		return -EINVAL;

	ev = (*metag_pmu->cache_events)[type][op][result];
	if (ev == 0)
		return -EOPNOTSUPP;
	if (ev == -1)
		return -EINVAL;
	*evp = ev;
	return 0;
}

static int _hw_perf_event_init(struct perf_event *event)
{
	struct perf_event_attr *attr = &event->attr;
	struct hw_perf_event *hwc = &event->hw;
	int mapping = 0, err;

	switch (attr->type) {
	case PERF_TYPE_HARDWARE:
		if (attr->config >= PERF_COUNT_HW_MAX)
			return -EINVAL;

		mapping = metag_pmu->event_map(attr->config);
		break;

	case PERF_TYPE_HW_CACHE:
		err = _hw_perf_cache_event(attr->config, &mapping);
		if (err)
			return err;
		break;

	case PERF_TYPE_RAW:
		mapping = attr->config;
		break;
	}

	/* Return early if the event is unsupported */
	if (mapping == -1)
		return -EINVAL;

	/*
	 * Don't assign an index until the event is placed into the hardware.
	 * -1 signifies that we're still deciding where to put it. On SMP
	 * systems each core has its own set of counters, so we can't do any
	 * constraint checking yet.
	 */
	hwc->idx = -1;

	/* Store the event encoding */
	hwc->config |= (unsigned long)mapping;

	/*
	 * For non-sampling runs, limit the sample_period to half of the
	 * counter width. This way, the new counter value should be less
	 * likely to overtake the previous one (unless there are IRQ latency
	 * issues...)
	 */
	if (metag_pmu->max_period) {
		if (!hwc->sample_period) {
			hwc->sample_period = metag_pmu->max_period >> 1;
			hwc->last_period = hwc->sample_period;
			local64_set(&hwc->period_left, hwc->sample_period);
		}
	}

	return 0;
}

static void metag_pmu_enable_counter(struct hw_perf_event *event, int idx)
{
	struct cpu_hw_events *events = this_cpu_ptr(&cpu_hw_events);
	unsigned int config = event->config;
	unsigned int tmp = config & 0xf0;
	unsigned long flags;

	raw_spin_lock_irqsave(&events->pmu_lock, flags);

	/*
	 * Check if we're enabling the instruction counter (index of
	 * MAX_HWEVENTS - 1)
	 */
	if (METAG_INST_COUNTER == idx) {
		WARN_ONCE((config != 0x100),
			"invalid configuration (%d) for counter (%d)\n",
			config, idx);
		local64_set(&event->prev_count, __core_reg_get(TXTACTCYC));
		goto unlock;
	}

	/* Check for a core internal or performance channel event. */
	if (tmp) {
		/* PERF_ICORE/PERF_CHAN only exist since Meta2 */
#ifdef METAC_2_1
		void *perf_addr;

		/*
		 * Anything other than a cycle count will write the low-
		 * nibble to the correct counter register.
		 */
		switch (tmp) {
		case 0xd0:
			perf_addr = (void *)PERF_ICORE(idx);
			break;

		case 0xf0:
			perf_addr = (void *)PERF_CHAN(idx);
			break;

		default:
			perf_addr = NULL;
			break;
		}

		if (perf_addr)
			metag_out32((config & 0x0f), perf_addr);
#endif

		/*
		 * Now we use the high nibble as the performance event to
		 * to count.
		 */
		config = tmp >> 4;
	}

	tmp = ((config & 0xf) << 28) |
			((1 << 24) << hard_processor_id());
	if (metag_pmu->max_period)
		/*
		 * Cores supporting overflow interrupts may have had the counter
		 * set to a specific value that needs preserving.
		 */
		tmp |= metag_in32(PERF_COUNT(idx)) & 0x00ffffff;
	else
		/*
		 * Older cores reset the counter on write, so prev_count needs
		 * resetting too so we can calculate a correct delta.
		 */
		local64_set(&event->prev_count, 0);

	metag_out32(tmp, PERF_COUNT(idx));
unlock:
	raw_spin_unlock_irqrestore(&events->pmu_lock, flags);
}

static void metag_pmu_disable_counter(struct hw_perf_event *event, int idx)
{
	struct cpu_hw_events *events = this_cpu_ptr(&cpu_hw_events);
	unsigned int tmp = 0;
	unsigned long flags;

	/*
	 * The cycle counter can't be disabled per se, as it's a hardware
	 * thread register which is always counting. We merely return if this
	 * is the counter we're attempting to disable.
	 */
	if (METAG_INST_COUNTER == idx)
		return;

	/*
	 * The counter value _should_ have been read prior to disabling,
	 * as if we're running on an early core then the value gets reset to
	 * 0, and any read after that would be useless. On the newer cores,
	 * however, it's better to read-modify-update this for purposes of
	 * the overflow interrupt.
	 * Here we remove the thread id AND the event nibble (there are at
	 * least two events that count events that are core global and ignore
	 * the thread id mask). This only works because we don't mix thread
	 * performance counts, and event 0x00 requires a thread id mask!
	 */
	raw_spin_lock_irqsave(&events->pmu_lock, flags);

	tmp = metag_in32(PERF_COUNT(idx));
	tmp &= 0x00ffffff;
	metag_out32(tmp, PERF_COUNT(idx));

	raw_spin_unlock_irqrestore(&events->pmu_lock, flags);
}

static u64 metag_pmu_read_counter(int idx)
{
	u32 tmp = 0;

	if (METAG_INST_COUNTER == idx) {
		tmp = __core_reg_get(TXTACTCYC);
		goto out;
	}

	tmp = metag_in32(PERF_COUNT(idx)) & 0x00ffffff;
out:
	return tmp;
}

static void metag_pmu_write_counter(int idx, u32 val)
{
	struct cpu_hw_events *events = this_cpu_ptr(&cpu_hw_events);
	u32 tmp = 0;
	unsigned long flags;

	/*
	 * This _shouldn't_ happen, but if it does, then we can just
	 * ignore the write, as the register is read-only and clear-on-write.
	 */
	if (METAG_INST_COUNTER == idx)
		return;

	/*
	 * We'll keep the thread mask and event id, and just update the
	 * counter itself. Also , we should bound the value to 24-bits.
	 */
	raw_spin_lock_irqsave(&events->pmu_lock, flags);

	val &= 0x00ffffff;
	tmp = metag_in32(PERF_COUNT(idx)) & 0xff000000;
	val |= tmp;
	metag_out32(val, PERF_COUNT(idx));

	raw_spin_unlock_irqrestore(&events->pmu_lock, flags);
}

static int metag_pmu_event_map(int idx)
{
	return metag_general_events[idx];
}

static irqreturn_t metag_pmu_counter_overflow(int irq, void *dev)
{
	int idx = (int)dev;
	struct cpu_hw_events *cpuhw = this_cpu_ptr(&cpu_hw_events);
	struct perf_event *event = cpuhw->events[idx];
	struct hw_perf_event *hwc = &event->hw;
	struct pt_regs *regs = get_irq_regs();
	struct perf_sample_data sampledata;
	unsigned long flags;
	u32 counter = 0;

	/*
	 * We need to stop the core temporarily from generating another
	 * interrupt while we disable this counter. However, we don't want
	 * to flag the counter as free
	 */
	__global_lock2(flags);
	counter = metag_in32(PERF_COUNT(idx));
	metag_out32((counter & 0x00ffffff), PERF_COUNT(idx));
	__global_unlock2(flags);

	/* Update the counts and reset the sample period */
	metag_pmu_event_update(event, hwc, idx);
	perf_sample_data_init(&sampledata, 0, hwc->last_period);
	metag_pmu_event_set_period(event, hwc, idx);

	/*
	 * Enable the counter again once core overflow processing has
	 * completed. Note the counter value may have been modified while it was
	 * inactive to set it up ready for the next interrupt.
	 */
	if (!perf_event_overflow(event, &sampledata, regs)) {
		__global_lock2(flags);
		counter = (counter & 0xff000000) |
			  (metag_in32(PERF_COUNT(idx)) & 0x00ffffff);
		metag_out32(counter, PERF_COUNT(idx));
		__global_unlock2(flags);
	}

	return IRQ_HANDLED;
}

static struct metag_pmu _metag_pmu = {
	.handle_irq	= metag_pmu_counter_overflow,
	.enable		= metag_pmu_enable_counter,
	.disable	= metag_pmu_disable_counter,
	.read		= metag_pmu_read_counter,
	.write		= metag_pmu_write_counter,
	.event_map	= metag_pmu_event_map,
	.cache_events	= &metag_pmu_cache_events,
	.max_period	= MAX_PERIOD,
	.max_events	= MAX_HWEVENTS,
};

/* PMU CPU hotplug notifier */
static int metag_pmu_cpu_notify(struct notifier_block *b, unsigned long action,
				void *hcpu)
{
	unsigned int cpu = (unsigned int)hcpu;
	struct cpu_hw_events *cpuc = &per_cpu(cpu_hw_events, cpu);

	if ((action & ~CPU_TASKS_FROZEN) != CPU_STARTING)
		return NOTIFY_DONE;

	memset(cpuc, 0, sizeof(struct cpu_hw_events));
	raw_spin_lock_init(&cpuc->pmu_lock);

	return NOTIFY_OK;
}

static struct notifier_block metag_pmu_notifier = {
	.notifier_call = metag_pmu_cpu_notify,
};

/* PMU Initialisation */
static int __init init_hw_perf_events(void)
{
	int ret = 0, cpu;
	u32 version = *(u32 *)METAC_ID;
	int major = (version & METAC_ID_MAJOR_BITS) >> METAC_ID_MAJOR_S;
	int min_rev = (version & (METAC_ID_MINOR_BITS | METAC_ID_REV_BITS))
			>> METAC_ID_REV_S;

	/* Not a Meta 2 core, then not supported */
	if (0x02 > major) {
		pr_info("no hardware counter support available\n");
		goto out;
	} else if (0x02 == major) {
		metag_pmu = &_metag_pmu;

		if (min_rev < 0x0104) {
			/*
			 * A core without overflow interrupts, and clear-on-
			 * write counters.
			 */
			metag_pmu->handle_irq = NULL;
			metag_pmu->write = NULL;
			metag_pmu->max_period = 0;
		}

		metag_pmu->name = "meta2";
		metag_pmu->version = version;
		metag_pmu->pmu = pmu;
	}

	pr_info("enabled with %s PMU driver, %d counters available\n",
			metag_pmu->name, metag_pmu->max_events);

	/*
	 * Early cores have "limited" counters - they have no overflow
	 * interrupts - and so are unable to do sampling without extra work
	 * and timer assistance.
	 */
	if (metag_pmu->max_period == 0) {
		metag_pmu->pmu.capabilities |= PERF_PMU_CAP_NO_INTERRUPT;
	}

	/* Initialise the active events and reservation mutex */
	atomic_set(&metag_pmu->active_events, 0);
	mutex_init(&metag_pmu->reserve_mutex);

	/* Clear the counters */
	metag_out32(0, PERF_COUNT(0));
	metag_out32(0, PERF_COUNT(1));

	for_each_possible_cpu(cpu) {
		struct cpu_hw_events *cpuc = &per_cpu(cpu_hw_events, cpu);

		memset(cpuc, 0, sizeof(struct cpu_hw_events));
		raw_spin_lock_init(&cpuc->pmu_lock);
	}

	register_cpu_notifier(&metag_pmu_notifier);
	ret = perf_pmu_register(&pmu, metag_pmu->name, PERF_TYPE_RAW);
out:
	return ret;
}
early_initcall(init_hw_perf_events);