text:
import QuillCursors from './quill-cursors';
import Cursor from './cursor';
import '@testing-library/jest-dom/extend-expect';
import ResizeObserver from 'resize-observer-polyfill';

const mockObserver = jest.fn();
const mockDisconnect = jest.fn();
jest.mock('resize-observer-polyfill', () => {
  return jest.fn().mockImplementation(() => {
    return {
      observe: mockObserver,
      disconnect: mockDisconnect,
    };
  });
});

describe('QuillCursors', () => {
  let quill: any;

  beforeEach(() => {
    quill = {
      constructor: {
        events: {
          SELECTION_CHANGE: 'selection-change',
          TEXT_CHANGE: 'text-change',
        },
        sources: {
          API: 'api',
        },
      },
      addContainer: (className: string): HTMLElement => {
        const cursorsContainer = document.createElement('DIV');
        cursorsContainer.classList.add(className);
        quill.container.appendChild(cursorsContainer);

        return cursorsContainer;
      },
      container: null,
      emitter: {
        emit: (): void => {},
      },
      getBounds: (): any => {},
      getLeaf: (): any => {},
      getLength: (): number => 0,
      getSelection: (): void => {},
      getLines: (): any[] => [],
      on: (): void => {},
    };

    quill.container = document.createElement('DIV');
    document.body.appendChild(quill.container);

    const editor = document.createElement('DIV');
    editor.classList.add('ql-editor');
    quill.container.appendChild(editor);

    (ResizeObserver as any).mockClear();
    mockObserver.mockClear();
    mockDisconnect.mockClear();
  });

  describe('initialisation', () => {
    it('adds a container to Quill', () => {
      jest.spyOn(quill, 'addContainer');
      new QuillCursors(quill);
      expect(quill.addContainer).toHaveBeenCalledTimes(1);
    });

    it('registers a scroll listener', () => {
      const editor = quill.container.getElementsByClassName('ql-editor')[0];
      jest.spyOn(editor, 'addEventListener');
      const cursors = new QuillCursors(quill);
      expect(editor.addEventListener).toHaveBeenCalledWith('scroll', expect.anything());

      jest.spyOn(cursors, 'update');
      const scroll = new Event('scroll');
      editor.dispatchEvent(scroll);
      expect(cursors.update).toHaveBeenCalled();
    });
  });

  describe('ResizeObserver', () => {
    let cursors: QuillCursors;
    let editor: HTMLElement;

    beforeEach(() => {
      cursors = new QuillCursors(quill);
      cursors.createCursor('abc', 'Jane Bloggs', 'red');
      cursors.moveCursor('abc', {index: 0, length: 0});
      editor = quill.container.getElementsByClassName('ql-editor')[0];
    });

    it('registers a ResizeObserver', () => {
      expect(mockObserver).toHaveBeenCalledTimes(1);
      expect(mockObserver).toHaveBeenCalledWith(editor);

      expect(ResizeObserver).toHaveBeenCalledTimes(1);
      const callback = (ResizeObserver as any).mock.calls[0][0];
      jest.spyOn(cursors, 'update');
      callback([{target: {}}]);
      expect(cursors.update).toHaveBeenCalledTimes(1);
    });

    it('disconnects and reconnects the observer if the cursors are updated again', () => {
      mockObserver.mockReset();
      const callback = (ResizeObserver as any).mock.calls[0][0];
      callback([{target: {isConnected: false}}]);
      expect(mockDisconnect).toHaveBeenCalledTimes(1);

      cursors.moveCursor('abc', {index: 1, length: 0});
      expect(mockObserver).toHaveBeenCalledTimes(1);
    });

    it('does not disconnect if the node is still connected', () => {
      const callback = (ResizeObserver as any).mock.calls[0][0];
      callback([{target: {isConnected: true}}]);
      expect(mockDisconnect).toHaveBeenCalledTimes(0);
    });
  });

  describe('text change listener', () => {
    let listeners: any;

    beforeEach(() => {
      listeners = {};

      jest.spyOn(quill, 'on').mockImplementation(((event: string, callback: Function) => {
        listeners[event] = callback;
      }) as any);

      jest.spyOn(quill.emitter, 'emit');

      jest.spyOn(quill, 'getSelection').mockReturnValue({index: 0, length: 0});
    });

    it('registers the text change listener', () => {
      new QuillCursors(quill);
      expect(listeners['text-change']).toBeTruthy();
    });

    it('does not emit a selection change event if setting the source to null', () => {
      jest.useFakeTimers();
      new QuillCursors(quill, {selectionChangeSource: null});

      listeners['text-change']();
      jest.runAllTimers();

      expect(quill.emitter.emit).not.toHaveBeenCalled();
    });

    it('emits the selection on text change', () => {
      jest.useFakeTimers();
      new QuillCursors(quill);

      jest.spyOn(quill, 'getSelection').mockReturnValue({index: 10, length: 10});
      listeners['text-change']();
      jest.runAllTimers();

      expect(quill.emitter.emit).toHaveBeenCalledTimes(1);
      expect(quill.emitter.emit).toHaveBeenCalledWith(
        'selection-change',
        {index: 10, length: 10},
        {index: 0, length: 0},
        'api',
      );
    });

    it('emits a custom source for selection-change on text change', () => {
      jest.useFakeTimers();
      new QuillCursors(quill, {selectionChangeSource: 'quill-cursors'});

      jest.spyOn(quill, 'getSelection').mockReturnValue({index: 10, length: 10});
      listeners['text-change']();
      jest.runAllTimers();

      expect(quill.emitter.emit).toHaveBeenCalledTimes(1);
      expect(quill.emitter.emit).toHaveBeenCalledWith(
        'selection-change',
        {index: 10, length: 10},
        {index: 0, length: 0},
        'quill-cursors',
      );
    });

    it('transforms an existing cursor after an insertion', () => {
      jest.useFakeTimers();
      const cursors = new QuillCursors(quill, {transformOnTextChange: true});
      const cursor = cursors.createCursor('abc', 'Joe Bloggs', 'red');
      cursors.moveCursor('abc', {index: 10, length: 5});

      const delta = [
        {retain: 5},
        {insert: 'foo'},
      ];
      listeners['text-change'](delta);
      jest.runAllTimers();

      expect(cursor.range).toEqual({index: 13, length: 5});
    });
  });

  describe('tracking current selection', () => {
    let listeners: any;

    beforeEach(() => {
      listeners = {};

      jest.spyOn(quill, 'on').mockImplementation(((event: string, callback: Function) => {
        listeners[event] = callback;
      }) as any);

      jest.spyOn(quill.emitter, 'emit').mockImplementation(((event: string, ...args: any[]) => {
        const callback = listeners[event];
        callback(...args);
      }) as any);

      jest.spyOn(quill, 'getSelection').mockReturnValue({index: 0, length: 0});
    });

    it('updates the current selection on text change', () => {
      jest.useFakeTimers();
      new QuillCursors(quill);

      jest.spyOn(quill, 'getSelection').mockReturnValue({index: 10, length: 10});
      quill.emitter.emit('text-change');
      jest.runAllTimers();

      expect(quill.emitter.emit).toHaveBeenCalledWith(
        'selection-change',
        {index: 10, length: 10},
        {index: 0, length: 0},
        'api',
      );

      jest.spyOn(quill, 'getSelection').mockReturnValue({index: 20, length: 20});
      quill.emitter.emit('text-change');
      jest.runAllTimers();

      expect(quill.emitter.emit).toHaveBeenCalledWith(
        'selection-change',
        {index: 20, length: 20},
        {index: 10, length: 10},
        'api',
      );
    });
  });

  describe('creating a cursor', () => {
    it('creates a cursor', () => {
      const cursors = new QuillCursors(quill);
      expect(cursors.cursors()).toHaveLength(0);

      cursors.createCursor('abc', 'Joe Bloggs', 'red');
      expect(cursors.cursors()).toHaveLength(1);
    });

    it('only creates a cursor with a given ID once', () => {
      const cursors = new QuillCursors(quill);
      expect(cursors.cursors()).toHaveLength(0);

      cursors.createCursor('abc', 'Joe Bloggs', 'red');
      cursors.createCursor('abc', 'Joe Bloggs', 'red');
      expect(cursors.cursors()).toHaveLength(1);
    });

    it('adds the cursor to the DOM', () => {
      const cursors = new QuillCursors(quill);
      const cursorsContainer = quill.container.getElementsByClassName('ql-cursors')[0];

      expect(cursorsContainer.childElementCount).toBe(0);

      cursors.createCursor('abc', 'Joe Bloggs', 'red');
      expect(cursorsContainer.childElementCount).toBe(1);
    });

    it('can override the hide delay and speed', () => {
      const cursors = new QuillCursors(quill, {
        hideDelayMs: 1000,
        hideSpeedMs: 2000,
      });

      cursors.createCursor('abc', 'Jane Bloggs', 'red');

      const flag = quill.container.getElementsByClassName(Cursor.FLAG_CLASS)[0];
      expect(flag).toHaveStyle('transition-delay: 1000ms');
      expect(flag).toHaveStyle('transition-duration: 2000ms');
    });

    it('can override the Quill container class', () => {
      new QuillCursors(quill, {containerClass: 'my-class'});
      const containers = quill.container.getElementsByClassName('my-class');
      expect(containers.length).toBe(1);
    });
  });

  describe('moving a cursor', () => {
    it('updates the cursor range', () => {
      const cursors = new QuillCursors(quill);
      const cursor = cursors.createCursor('abc', 'Jane Bloggs', 'red');
      expect(cursor.range).toBeFalsy();

      cursors.moveCursor('abc', {index: 0, length: 0});
      expect(cursor.range).toEqual({index: 0, length: 0});
    });

    it('does not throw if the cursor does not exist', () => {
      const cursors = new QuillCursors(quill);
      expect(() => cursors.moveCursor('abc', null)).not.toThrow();
    });
  });

  describe('removing a cursor', () => {
    let cursors: QuillCursors;
    let cursor: Cursor;

    beforeEach(() => {
      cursors = new QuillCursors(quill);
      cursor = cursors.createCursor('abc', 'Joe Bloggs', 'red');
    });

    it('removes the cursor from the DOM', () => {
      const cursorsContainer = quill.container.getElementsByClassName('ql-cursors')[0];

      expect(cursorsContainer.childElementCount).toBe(1);
      expect(cursors.cursors()).toHaveLength(1);

      cursors.removeCursor(cursor.id);

      expect(cursorsContainer.childElementCount).toBe(0);
      expect(cursors.cursors()).toHaveLength(0);
    });

    it('clears cursors', () => {
      const cursorsContainer = quill.container.getElementsByClassName('ql-cursors')[0];

      expect(cursorsContainer.childElementCount).toBe(1);
      expect(cursors.cursors()).toHaveLength(1);

      cursors.clearCursors();

      expect(cursorsContainer.childElementCount).toBe(0);
      expect(cursors.cursors()).toHaveLength(0);
    });

    it('does not throw if the cursor does not exist', () => {
      expect(() => cursors.removeCursor('not-an-id')).not.toThrow();
    });
  });

  describe('updating cursors', () => {
    let cursors: QuillCursors;
    let cursor: Cursor;
    let mockRange: any;

    beforeEach(() => {
      cursors = new QuillCursors(quill);
      cursor = cursors.createCursor('abc', 'Joe Bloggs', 'red');

      jest.spyOn(quill, 'getBounds').mockReturnValue({
        top: 0,
        left: 0,
        width: 0,
        height: 0,
      });

      mockRange = {
        setStart: () => { },
        setStartBefore: () => { },
        setEnd: () => { },
        setEndAfter: () => { },
        getClientRects: () => {
          const rectangles: any[] = [];
          return rectangles;
        },
        getBoundingClientRect: () => ({}),
        cloneRange: () => mockRange,
        selectNode: () => { },
      };
      document.createRange = () => mockRange;
    });

    it('hides a cursor with no range', () => {
      jest.spyOn(cursor, 'hide');
      jest.spyOn(cursor, 'show');
      cursors.moveCursor(cursor.id, null);

      expect(cursor.hide).toHaveBeenCalled();
      expect(cursor.show).not.toHaveBeenCalled();
    });

    it('hides a cursor with no range if the range is updated manually', () => {
      jest.spyOn(cursor, 'hide');
      jest.spyOn(cursor, 'show');
      cursor.range = null;

      expect(cursor.hide).not.toHaveBeenCalled();
      cursors.update();

      expect(cursor.hide).toHaveBeenCalled();
      expect(cursor.show).not.toHaveBeenCalled();
    });

    it('hides a cursor with a range, but no valid leaf', () => {
      jest.spyOn(cursor, 'hide');
      jest.spyOn(cursor, 'show');
      jest.spyOn(quill, 'getLeaf').mockReturnValue(null);
      cursors.moveCursor(cursor.id, {index: 0, length: 0});

      expect(cursor.hide).toHaveBeenCalled();
      expect(cursor.show).not.toHaveBeenCalled();
    });

    it('shows a cursor with a valid range and leaf', () => {
      jest.spyOn(cursor, 'hide');
      jest.spyOn(cursor, 'show');
      jest.spyOn(quill, 'getLeaf').mockReturnValue(createLeaf());
      cursors.moveCursor(cursor.id, {index: 0, length: 0});

      expect(cursor.hide).not.toHaveBeenCalled();
      expect(cursor.show).toHaveBeenCalled();
    });

    it('forces ranges into the Quill bounds', () => {
      jest.spyOn(quill, 'getLength').mockReturnValue(10);
      jest.spyOn(quill, 'getLeaf');

      cursors.moveCursor(cursor.id, {index: -10, length: 100});

      expect(quill.getLeaf).toHaveBeenCalledWith(0);
      expect(quill.getLeaf).toHaveBeenCalledWith(9);
    });

    it('selects a block embed element', () => {
      const img = document.createElement('img');
      jest.spyOn(quill, 'getLeaf').mockReturnValue(createLeaf());
      jest.spyOn(quill, 'getLines').mockReturnValue([
        {domNode: img},
      ]);
      jest.spyOn(mockRange, 'selectNode');

      cursors.moveCursor(cursor.id, {index: 0, length: 0});

      expect(mockRange.selectNode).toHaveBeenCalledWith(img);
    });

    it('sets the range for a single line on the start and end leafs', () => {
      const startIndex = 0;
      const endIndex = 2;
      const startLeaf = createLeaf();
      const endLeaf = createLeaf();
      jest.spyOn(quill, 'getLeaf').mockImplementation(((index: number) => {
        switch (index) {
          case startIndex:
            return startLeaf;
          case endIndex:
            return endLeaf;
          default:
            return null;
        }
      }) as any);
      jest.spyOn(quill, 'getLines').mockReturnValue([{
        children: [],
      }]);
      jest.spyOn(mockRange, 'setStart');
      jest.spyOn(mockRange, 'setEnd');

      const range = {index: startIndex, length: endIndex - startIndex};

      cursors.moveCursor(cursor.id, range);

      expect(mockRange.setStart).toHaveBeenCalledWith(startLeaf[0].domNode, startLeaf[1]);
      expect(mockRange.setEnd).toHaveBeenCalledWith(endLeaf[0].domNode, endLeaf[1]);
    });

    it('sets the range for multiple lines based on the line path', () => {
      const startIndex = 0;
      const endIndex = 2;
      const startLeaf = createLeaf();
      const endLeaf = createLeaf();
      jest.spyOn(quill, 'getLeaf').mockImplementation(((index: number) => {
        switch (index) {
          case startIndex:
            return startLeaf;
          case endIndex:
            return endLeaf;
          default:
            return null;
        }
      }) as any);
      const line1Leaf = createLeaf();
      const line2Leaf = createLeaf();
      jest.spyOn(quill, 'getLines').mockReturnValue([
        {
          children: [],
          path: (): any[] => [line1Leaf],
          length: (): number => 1,
        },
        {
          children: [],
          path: (): any[] => [line2Leaf],
          length: (): number => 1,
        },
      ]);
      jest.spyOn(mockRange, 'setStart');
      jest.spyOn(mockRange, 'setEnd');

      const range = {index: startIndex, length: endIndex - startIndex};

      cursors.moveCursor(cursor.id, range);

      expect(mockRange.setStart).toHaveBeenCalledWith(startLeaf[0].domNode, startLeaf[1]);
      expect(mockRange.setEnd).toHaveBeenCalledWith(line1Leaf[0].domNode, line1Leaf[1]);

      expect(mockRange.setStart).toHaveBeenCalledWith(line2Leaf[0].domNode, line2Leaf[1]);
      expect(mockRange.setEnd).toHaveBeenCalledWith(line1Leaf[0].domNode, line1Leaf[1]);
    });

    it('sets the range on either side of an image', () => {
      const startIndex = 0;
      const endIndex = 1;
      const leaf = createLeaf('img');
      jest.spyOn(quill, 'getLeaf').mockImplementation(() => leaf);
      jest.spyOn(quill, 'getLines').mockReturnValue([{
        children: [],
      }]);
      jest.spyOn(mockRange, 'setStartBefore');
      jest.spyOn(mockRange, 'setEndAfter');

      const range = {index: startIndex, length: endIndex - startIndex};

      cursors.moveCursor(cursor.id, range);

      expect(mockRange.setStartBefore).toHaveBeenCalledWith(leaf[0].domNode);
      expect(mockRange.setEndAfter).toHaveBeenCalledWith(leaf[0].domNode);
    });
  });

  describe('flag', () => {
    it('toggles the flag of a cursor', () => {
      const cursors = new QuillCursors(quill);
      cursors.createCursor('abc', 'Joe Bloggs', 'red');

      const container = quill.container.getElementsByClassName(Cursor.CARET_CONTAINER_CLASS)[0];
      expect(container).not.toHaveClass(Cursor.CONTAINER_HOVER_CLASS);
      cursors.toggleFlag('abc', true);
      expect(container).toHaveClass(Cursor.CONTAINER_HOVER_CLASS);
    });

    it('does not throw if the cursor does not exist', () => {
      const cursors = new QuillCursors(quill);
      expect(() => cursors.toggleFlag('abc')).not.toThrow();
    });

    describe('touch', () => {
      it('toggles near flags by touchstart event', () => {
        const cursors = new QuillCursors(quill);
        cursors.createCursor('abc', 'Iron Man', 'red');

        const cursor = cursors.cursors()[0];
        jest.spyOn(cursor, 'toggleNearCursor');

        const touch = new TouchEvent('touchstart');
        const editor = quill.container.getElementsByClassName('ql-editor')[0];
        editor.dispatchEvent(touch);
        expect(cursor.toggleNearCursor).toBeCalled();
      });

      it('hide flags after 2 secs', () => {
        jest.useFakeTimers();
        const cursors = new QuillCursors(quill);
        cursors.createCursor('abc', 'Iron Man', 'red');

        const cursor = cursors.cursors()[0];
        jest.spyOn(cursor, 'toggleNearCursor');
        jest.spyOn(cursor, 'toggleFlag');

        const touch = new TouchEvent('touchstart');
        const editor = quill.container.getElementsByClassName('ql-editor')[0];
        editor.dispatchEvent(touch);
        expect(cursor.toggleNearCursor).toBeCalled();

        jest.runAllTimers();

        expect(cursor.toggleFlag).toBeCalled();
      });
    });
  });

  function createLeaf(tag?: string): any[] {
    const domNode = tag ? document.createElement(tag) : document.createTextNode('');
    return [{domNode}, 0];
  }
});


text:
import { ViewUser } from './view-user';
import { User } from 'app/shared/models/users/user';

/**
 * Interface for correlating between strings representing BaseModels and existing
 * BaseModels.
 */
export interface CsvMapping {
    name: string;
    id?: number;
    multiId?: number[];
}

/**
 * View class for a new User during text imports. Offers a mapping and matching
 * to secondary import data (groups)
 *
 * @ignore
 */
export class ViewCsvCreateUser extends ViewUser {
    /**
     * Mapping for a new/existing groups.
     */
    public csvGroups: CsvMapping[] = [];

    public title: string;

    /**
     * Getter if the minimum requrements for a user are met: A name
     *
     * @returns false if the user has neither first nor last name
     */
    public get isValid(): boolean {
        if (this.user && (this.first_name || this.last_name)) {
            return true;
        }
        return false;
    }

    public constructor(user?: User) {
        super(user);
    }

    /**
     * takes a list of solved group maps to update. Returns the amount of
     * entries that remain unmatched
     *
     * @param groups
     */
    public solveGroups(groups: CsvMapping[]): number {
        let open = 0;
        const ids: number[] = [];
        this.csvGroups.forEach(group => {
            if (group.id) {
                ids.push(group.id);
                return;
            }
            if (!groups.length) {
                open += 1;
                return;
            }
            const mapped = groups.find(newGroup => newGroup.name === group.name);
            if (mapped) {
                group.id = mapped.id;
                ids.push(mapped.id);
            } else {
                open += 1;
            }
        });
        this.user.groups_id = ids;
        return open;
    }
}

redpajama_set_name: RedPajamaGithub


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using System;
using System.Collections;
using System.Collections.Generic;
using System.Management.Automation;
using System.Security.Permissions;
using Microsoft.Azure.Commands.Automation.Common;
using Microsoft.Azure.Commands.Automation.Model;
using Microsoft.WindowsAzure.Commands.Utilities.Common;

namespace Microsoft.Azure.Commands.Automation.Cmdlet
{
    /// <summary>
    /// Imports dsc configuration script
    /// </summary>
    [Cmdlet(VerbsData.Import, "AzureAutomationDscConfiguration")]
    [OutputType(typeof(DscConfiguration))]
    public class ImportAzureAutomationDscConfiguration : AzureAutomationBaseCmdlet
    {
        /// <summary>
        /// True to overwrite the existing configuration; false otherwise.
        /// </summary>
        private bool overwriteExistingConfiguration;

        /// <summary>
        /// True to publish the configuration; false otherwise.
        /// </summary>
        private bool publishConfiguration;

        /// <summary>
        /// Gets or sets the source path.
        /// </summary>
        [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Path to the configuration script .ps1 to import.")]
        [Alias("Path")]
        [ValidateNotNullOrEmpty]
        public string SourcePath { get; set; }

        /// <summary>
        /// Gets or sets the configuration tags.
        /// </summary>
        [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The dsc configuration tags.")]
        [Alias("Tag")]
        public IDictionary Tags { get; set; }

        /// <summary>
        /// Gets or sets the description.
        /// </summary>
        [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The description of the configuration being imported.")]
        public string Description { get; set; }

        /// <summary>
        /// Gets or sets the switch parameter to publish the configuration
        /// </summary>
        [Parameter(Mandatory = false, HelpMessage = "Import the configuration in published state.")]
        public SwitchParameter Published
        {
            get { return this.publishConfiguration; }
            set { this.publishConfiguration = value; }
        }

        /// <summary>
        /// Gets or sets switch parameter to confirm overwriting of existing configurations.
        /// </summary>
        [Parameter(Mandatory = false, HelpMessage = "Forces the command to overwrite an existing configuration.")]
        public SwitchParameter Force
        {
            get { return this.overwriteExistingConfiguration; }
            set { this.overwriteExistingConfiguration = value; }
        }

        /// <summary>
        /// Gets or sets a value indicating whether verbose logging should be turned on or off.
        /// </summary>
        [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Indicate whether verbose logging should be turned on or off.")]
        public bool? LogVerbose { get; set; }

        /// <summary>
        /// Execute this cmdlet.
        /// </summary>
        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        public override void ExecuteCmdlet()
        {
            var configuration = this.AutomationClient.CreateConfiguration(
                    this.ResourceGroupName,
                    this.AutomationAccountName,
                    this.SourcePath,
                    this.Tags,
                    this.Description,
                    this.LogVerbose,
                    this.Published,
                    this.Force);

            this.WriteObject(configuration);
        }
    }
}


text:
export { default as atRuleParamIndex } from "./atRuleParamIndex"
export { default as beforeBlockString } from "./beforeBlockString"
export { default as blockString } from "./blockString"
export { default as blurComments } from "./blurComments"
export { default as blurFunctionArguments } from "./blurFunctionArguments"
export { default as configurationError } from "./configurationError"
export { default as cssWordIsVariable } from "./cssWordIsVariable"
export { default as declarationValueIndex } from "./declarationValueIndex"
export { default as styleTagsFromHtmlExtracter } from "./styleTagsFromHtmlExtracter"
export { default as findAtRuleContext } from "./findAtRuleContext"
export { default as functionArgumentsSearch } from "./functionArgumentsSearch"
export { default as hasBlock } from "./hasBlock"
export { default as hasEmptyBlock } from "./hasEmptyBlock"
export { default as isAutoprefixable } from "./isAutoprefixable"
export { default as isCustomProperty } from "./isCustomProperty"
export { default as isKeyframeRule } from "./isKeyframeRule"
export { default as isKnownPseudoElement } from "./isKnownPseudoElement"
export { default as isKnownUnit } from "./isKnownUnit"
export { default as isLowerSpecificity } from "./isLowerSpecificity"
export { default as isSingleLineString } from "./isSingleLineString"
export { default as isStandardAtRule } from "./isStandardAtRule"
export { default as isStandardDeclaration } from "./isStandardDeclaration"
export { default as isStandardFunction } from "./isStandardFunction"
export { default as isStandardProperty } from "./isStandardProperty"
export { default as isStandardRule } from "./isStandardRule"
export { default as isStandardSelector } from "./isStandardSelector"
export { default as isStandardTypeSelector } from "./isStandardTypeSelector"
export { default as isStandardValue } from "./isStandardValue"
export { default as isValidHex } from "./isValidHex"
export { default as isVariable } from "./isVariable"
export { default as isWhitespace } from "./isWhitespace"
export { default as matchesStringOrRegExp } from "./matchesStringOrRegExp"
export { default as nextNonCommentNode } from "./nextNonCommentNode"
export { default as nodeContextLookup } from "./nodeContextLookup"
export { default as optionsHaveException } from "./optionsHaveException"
export { default as optionsHaveIgnored } from "./optionsHaveIgnored"
export { default as rawNodeString } from "./rawNodeString"
export { default as report } from "./report"
export { default as ruleMessages } from "./ruleMessages"
export { default as styleSearch } from "./styleSearch"
export { default as validateOptions } from "./validateOptions"
export { default as whitespaceChecker } from "./whitespaceChecker"


text:
#include <sol-pwm.h>

#include <v8.h>
#include <node.h>
#include <nan.h>

#include "../common.h"
#include "../structures/js-handle.h"
#include "../structures/sol-js-pwm.h"

using namespace v8;

class SolPwm : public JSHandle<SolPwm> {
public:
    static const char *jsClassName() { return "SolPwm"; }
};

NAN_METHOD(bind_sol_pwm_open) {
    VALIDATE_ARGUMENT_COUNT(info, 3);
    VALIDATE_ARGUMENT_TYPE(info, 0, IsInt32);
    VALIDATE_ARGUMENT_TYPE(info, 1, IsInt32);
    VALIDATE_ARGUMENT_TYPE(info, 2, IsObject);

    int device;
    int channel;
    sol_pwm_config config;
    sol_pwm *pwm = NULL;

    device = info[0]->Int32Value();
    channel = info[1]->Int32Value();

    if (!c_sol_pwm_config(info[2]->ToObject(), &config)) {
        return;
    }

    pwm = sol_pwm_open(device, channel, &config);
    if (pwm) {
        info.GetReturnValue().Set(SolPwm::New(pwm));
    }
}

NAN_METHOD(bind_sol_pwm_open_raw) {
    VALIDATE_ARGUMENT_COUNT(info, 3);
    VALIDATE_ARGUMENT_TYPE_OR_NULL(info, 0, IsInt32);
    VALIDATE_ARGUMENT_TYPE_OR_NULL(info, 1, IsInt32);
    VALIDATE_ARGUMENT_TYPE(info, 2, IsObject);

    int device;
    int channel;
    sol_pwm_config config;
    sol_pwm *pwm = NULL;

    device = info[0]->Int32Value();
    channel = info[1]->Int32Value();

    if (!c_sol_pwm_config(info[2]->ToObject(), &config)) {
        return;
    }

    pwm = sol_pwm_open_raw(device, channel, &config);
    if (pwm) {
        info.GetReturnValue().Set(SolPwm::New(pwm));
    }
}

NAN_METHOD(bind_sol_pwm_open_by_label) {
    VALIDATE_ARGUMENT_COUNT(info, 2);
    VALIDATE_ARGUMENT_TYPE_OR_NULL(info, 0, IsString);
    VALIDATE_ARGUMENT_TYPE(info, 1, IsObject);

    sol_pwm_config config;
    sol_pwm *pwm = NULL;

    if (!c_sol_pwm_config(info[1]->ToObject(), &config)) {
        return;
    }

    pwm = sol_pwm_open_by_label((const char *)*String::Utf8Value(info[0]),
        &config);

    if (pwm) {
        info.GetReturnValue().Set(SolPwm::New(pwm));
    }
}

NAN_METHOD(bind_sol_pwm_close) {
    VALIDATE_ARGUMENT_COUNT(info, 1);
    VALIDATE_ARGUMENT_TYPE(info, 0, IsObject);

    Local<Object> jsPwm = Nan::To<Object>(info[0]).ToLocalChecked();
    sol_pwm *pwm = (sol_pwm *)SolPwm::Resolve(jsPwm);
    if (!pwm)
        return;

    sol_pwm_close(pwm);
    Nan::SetInternalFieldPointer(jsPwm, 0, 0);
}

NAN_METHOD(bind_sol_pwm_set_enabled) {
    VALIDATE_ARGUMENT_COUNT(info, 2);
    VALIDATE_ARGUMENT_TYPE(info, 0, IsObject);
    VALIDATE_ARGUMENT_TYPE(info, 1, IsBoolean);

    Local<Object> jsPwm = Nan::To<Object>(info[0]).ToLocalChecked();
    sol_pwm *pwm = (sol_pwm *)SolPwm::Resolve(jsPwm);
    if (!pwm)
        return;

    bool value = info[1]->BooleanValue();
    info.GetReturnValue().Set(Nan::New(sol_pwm_set_enabled(pwm, value)));
}

NAN_METHOD(bind_sol_pwm_set_period) {
    VALIDATE_ARGUMENT_COUNT(info, 2);
    VALIDATE_ARGUMENT_TYPE(info, 0, IsObject);
    VALIDATE_ARGUMENT_TYPE(info, 1, IsUint32);

    Local<Object> jsPwm = Nan::To<Object>(info[0]).ToLocalChecked();
    sol_pwm *pwm = (sol_pwm *)SolPwm::Resolve(jsPwm);
    if (!pwm)
        return;

    uint32_t value = info[1]->Uint32Value();
    info.GetReturnValue().Set(Nan::New(sol_pwm_set_period(pwm, value)));
}

NAN_METHOD(bind_sol_pwm_set_duty_cycle) {
    VALIDATE_ARGUMENT_COUNT(info, 2);
    VALIDATE_ARGUMENT_TYPE(info, 0, IsObject);
    VALIDATE_ARGUMENT_TYPE(info, 1, IsUint32);

    Local<Object> jsPwm = Nan::To<Object>(info[0]).ToLocalChecked();
    sol_pwm *pwm = (sol_pwm *)SolPwm::Resolve(jsPwm);
    if (!pwm)
        return;

    uint32_t value = info[1]->Uint32Value();
    info.GetReturnValue().Set(Nan::New(sol_pwm_set_duty_cycle(pwm, value)));
}

NAN_METHOD(bind_sol_pwm_is_enabled) {
    VALIDATE_ARGUMENT_COUNT(info, 1);
    VALIDATE_ARGUMENT_TYPE(info, 0, IsObject);

    Local<Object> jsPwm = Nan::To<Object>(info[0]).ToLocalChecked();
    sol_pwm *pwm = (sol_pwm *)SolPwm::Resolve(jsPwm);
    if (!pwm)
        return;

    info.GetReturnValue().Set(Nan::New(sol_pwm_is_enabled(pwm)));
}

NAN_METHOD(bind_sol_pwm_get_period) {
    VALIDATE_ARGUMENT_COUNT(info, 1);
    VALIDATE_ARGUMENT_TYPE(info, 0, IsObject);

    Local<Object> jsPwm = Nan::To<Object>(info[0]).ToLocalChecked();
    sol_pwm *pwm = (sol_pwm *)SolPwm::Resolve(jsPwm);
    if (!pwm)
        return;

    info.GetReturnValue().Set(Nan::New(sol_pwm_get_period(pwm)));
}

NAN_METHOD(bind_sol_pwm_get_duty_cycle) {
    VALIDATE_ARGUMENT_COUNT(info, 1);
    VALIDATE_ARGUMENT_TYPE(info, 0, IsObject);

    Local<Object> jsPwm = Nan::To<Object>(info[0]).ToLocalChecked();
    sol_pwm *pwm = (sol_pwm *)SolPwm::Resolve(jsPwm);
    if (!pwm)
        return;

    info.GetReturnValue().Set(Nan::New(sol_pwm_get_duty_cycle(pwm)));
}

NAN_METHOD(bind_sol_pwm_alignment_from_str) {
    VALIDATE_ARGUMENT_COUNT(info, 1);
    VALIDATE_ARGUMENT_TYPE(info, 0, IsString);

    sol_pwm_alignment alignment = sol_pwm_alignment_from_str(
        (const char *)*String::Utf8Value(info[0]));
    info.GetReturnValue().Set(Nan::New(alignment));
}

NAN_METHOD(bind_sol_pwm_alignment_to_str) {
    VALIDATE_ARGUMENT_COUNT(info, 1);
    VALIDATE_ARGUMENT_TYPE(info, 0, IsInt32);

    const char *idString = sol_pwm_alignment_to_str(
        (sol_pwm_alignment)info[0]->Int32Value());

    if (idString) {
        info.GetReturnValue().Set(Nan::New(idString).ToLocalChecked());
    } else {
        info.GetReturnValue().Set(Nan::Null());
    }
}

NAN_METHOD(bind_sol_pwm_polarity_from_str) {
    VALIDATE_ARGUMENT_COUNT(info, 1);
    VALIDATE_ARGUMENT_TYPE(info, 0, IsString);

    sol_pwm_polarity polarity = sol_pwm_polarity_from_str(
        (const char *)*String::Utf8Value(info[0]));
    info.GetReturnValue().Set(Nan::New(polarity));
}

NAN_METHOD(bind_sol_pwm_polarity_to_str) {
    VALIDATE_ARGUMENT_COUNT(info, 1);
    VALIDATE_ARGUMENT_TYPE(info, 0, IsInt32);

    const char *idString = sol_pwm_polarity_to_str(
        (sol_pwm_polarity)info[0]->Int32Value());

    if (idString) {
        info.GetReturnValue().Set(Nan::New(idString).ToLocalChecked());
    } else {
        info.GetReturnValue().Set(Nan::Null());
    }
}


text:
package org.apache.hadoop.hbase.client;

import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.NavigableMap;
import java.util.TreeMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.HRegionLocation;
import org.apache.hadoop.hbase.MetaTableAccessor;
import org.apache.hadoop.hbase.RegionLocations;
import org.apache.hadoop.hbase.ServerName;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.TableNotFoundException;
import org.apache.hadoop.hbase.classification.InterfaceAudience;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.ExceptionUtil;

import com.google.common.annotations.VisibleForTesting;

/**
 * Scanner class that contains the hbase:meta table scanning logic.
 * Provided visitors will be called for each row.
 *
 * Although public visibility, this is not a public-facing API and may evolve in
 * minor releases.
 *
 *
 Note that during concurrent region splits, the scanner might not see
 * hbase:meta changes across rows (for parent and daughter entries) consistently.
 * see HBASE-5986, and {@link DefaultMetaScannerVisitor} for details.

 */
@InterfaceAudience.Private
//TODO: merge this to MetaTableAccessor, get rid of it.
public final class MetaScanner {
  private static final Log LOG = LogFactory.getLog(MetaScanner.class);

  private MetaScanner() {}

  /**
   * Scans the meta table and calls a visitor on each RowResult and uses a empty
   * start row value as table name.
   *
   *
Visible for testing. Use {@link
   * #metaScan(Connection, MetaScannerVisitor, TableName)} instead.
   *
   * @param visitor A custom visitor
   * @throws IOException e
   */
  @VisibleForTesting // Do not use. Used by tests only and hbck.
  public static void metaScan(Connection connection,
      MetaScannerVisitor visitor) throws IOException {
    metaScan(connection, visitor, null, null, Integer.MAX_VALUE);
  }

  /**
   * Scans the meta table and calls a visitor on each RowResult. Uses a table
   * name to locate meta regions.
   *
   * @param connection connection to use internally (null to use a new instance)
   * @param visitor visitor object
   * @param userTableName User table name in meta table to start scan at.  Pass
   * null if not interested in a particular table.
   * @throws IOException e
   */
  public static void metaScan(Connection connection,
      MetaScannerVisitor visitor, TableName userTableName) throws IOException {
    metaScan(connection, visitor, userTableName, null, Integer.MAX_VALUE,
        TableName.META_TABLE_NAME);
  }

  /**
   * Scans the meta table and calls a visitor on each RowResult. Uses a table
   * name and a row name to locate meta regions. And it only scans at most
   * rowLimit of rows.
   *
   *
Visible for testing. Use {@link
   * #metaScan(Connection, MetaScannerVisitor, TableName)} instead.
   *
   * @param connection to scan on
   * @param visitor Visitor object.
   * @param userTableName User table name in meta table to start scan at.  Pass
   * null if not interested in a particular table.
   * @param row Name of the row at the user table. The scan will start from
   * the region row where the row resides.
   * @param rowLimit Max of processed rows. If it is less than 0, it
   * will be set to default value Integer.MAX_VALUE.
   * @throws IOException e
   */
  @VisibleForTesting // Do not use. Used by Master but by a method that is used testing.
  public static void metaScan(Connection connection,
      MetaScannerVisitor visitor, TableName userTableName, byte[] row,
      int rowLimit)
  throws IOException {
    metaScan(connection, visitor, userTableName, row, rowLimit, TableName
        .META_TABLE_NAME);
  }

  /**
   * Scans the meta table and calls a visitor on each RowResult. Uses a table
   * name and a row name to locate meta regions. And it only scans at most
   * rowLimit of rows.
   *
   * @param connection connection to use internally (null to use a new instance)
   * @param visitor Visitor object. Closes the visitor before returning.
   * @param tableName User table name in meta table to start scan at.  Pass
   * null if not interested in a particular table.
   * @param row Name of the row at the user table. The scan will start from
   * the region row where the row resides.
   * @param rowLimit Max of processed rows. If it is less than 0, it
   * will be set to default value Integer.MAX_VALUE.
   * @param metaTableName Meta table to scan, root or meta.
   * @throws IOException e
   */
  static void metaScan(Connection connection,
      final MetaScannerVisitor visitor, final TableName tableName,
      final byte[] row, final int rowLimit, final TableName metaTableName)
    throws IOException {

    int rowUpperLimit = rowLimit > 0 ? rowLimit: Integer.MAX_VALUE;
    // Calculate startrow for scan.
    byte[] startRow;
    // If the passed in 'connection' is 'managed' -- i.e. every second test uses
    // an HTable or an HBaseAdmin with managed connections -- then doing
    // connection.getTable will throw an exception saying you are NOT to use
    // managed connections getting tables.  Leaving this as it is for now. Will
    // revisit when inclined to change all tests.  User code probaby makes use of
    // managed connections too so don't change it till post hbase 1.0.
    try (Table metaTable = new HTable(TableName.META_TABLE_NAME, connection, null)) {
      if (row != null) {
        // Scan starting at a particular row in a particular table
        Result startRowResult = getClosestRowOrBefore(metaTable, tableName, row);
        if (startRowResult == null) {
          throw new TableNotFoundException("Cannot find row in " + metaTable.getName() +
            " for table: " + tableName + ", row=" + Bytes.toStringBinary(row));
        }
        HRegionInfo regionInfo = getHRegionInfo(startRowResult);
        if (regionInfo == null) {
          throw new IOException("HRegionInfo was null or empty in Meta for " +
            tableName + ", row=" + Bytes.toStringBinary(row));
        }
        byte[] rowBefore = regionInfo.getStartKey();
        startRow = HRegionInfo.createRegionName(tableName, rowBefore, HConstants.ZEROES, false);
      } else if (tableName == null || tableName.getName().length == 0) {
        // Full hbase:meta scan
        startRow = HConstants.EMPTY_START_ROW;
      } else {
        // Scan hbase:meta for an entire table
        startRow = HRegionInfo.createRegionName(tableName, HConstants.EMPTY_START_ROW,
          HConstants.ZEROES, false);
      }
      final Scan scan = new Scan(startRow).addFamily(HConstants.CATALOG_FAMILY);
      int scannerCaching = connection.getConfiguration()
          .getInt(HConstants.HBASE_META_SCANNER_CACHING,
              HConstants.DEFAULT_HBASE_META_SCANNER_CACHING);
      if (rowUpperLimit <= scannerCaching) {
          scan.setSmall(true);
      }
      int rows = Math.min(rowLimit, scannerCaching);
      scan.setCaching(rows);
      if (LOG.isTraceEnabled()) {
        LOG.trace("Scanning " + metaTableName.getNameAsString() + " starting at row=" +
          Bytes.toStringBinary(startRow) + " for max=" + rowUpperLimit + " with caching=" + rows);
      }
      // Run the scan
      try (ResultScanner resultScanner = metaTable.getScanner(scan)) {
        Result result;
        int processedRows = 0;
        while ((result = resultScanner.next()) != null) {
          if (visitor != null) {
            if (!visitor.processRow(result)) break;
          }
          processedRows++;
          if (processedRows >= rowUpperLimit) break;
        }
      }
    } finally {
      if (visitor != null) {
        try {
          visitor.close();
        } catch (Throwable t) {
          ExceptionUtil.rethrowIfInterrupt(t);
          LOG.debug("Got exception in closing the meta scanner visitor", t);
        }
      }
    }
  }

  /**
   * @return Get closest metatable region row to passed row
   * @throws IOException
   */
  private static Result getClosestRowOrBefore(final Table metaTable, final TableName userTableName,
      final byte [] row)
  throws IOException {
    byte[] searchRow = HRegionInfo.createRegionName(userTableName, row, HConstants.NINES, false);
    Scan scan = Scan.createGetClosestRowOrBeforeReverseScan(searchRow);
    try (ResultScanner resultScanner = metaTable.getScanner(scan)) {
      return resultScanner.next();
    }
  }

  /**
   * Returns HRegionInfo object from the column
   * HConstants.CATALOG_FAMILY:HConstants.REGIONINFO_QUALIFIER of the catalog
   * table Result.
   * @param data a Result object from the catalog table scan
   * @return HRegionInfo or null
   * @deprecated Use {@link org.apache.hadoop.hbase.MetaTableAccessor#getRegionLocations(Result)}
   */
  @Deprecated
  public static HRegionInfo getHRegionInfo(Result data) {
    return HRegionInfo.getHRegionInfo(data);
  }

  /**
   * Lists all of the regions currently in META.
   * @param conf configuration
   * @param connection to connect with
   * @param offlined True if we are to include offlined regions, false and we'll
   * leave out offlined regions from returned list.
   * @return List of all user-space regions.
   * @throws IOException
   */
  @VisibleForTesting // And for hbck.
  public static List<HRegionInfo> listAllRegions(Configuration conf, Connection connection,
      final boolean offlined)
  throws IOException {
    final List<HRegionInfo> regions = new ArrayList<HRegionInfo>();
    MetaScannerVisitor visitor = new MetaScannerVisitorBase() {
        @Override
        public boolean processRow(Result result) throws IOException {
          if (result == null || result.isEmpty()) {
            return true;
          }

          RegionLocations locations = MetaTableAccessor.getRegionLocations(result);
          if (locations == null) return true;
          for (HRegionLocation loc : locations.getRegionLocations()) {
            if (loc != null) {
              HRegionInfo regionInfo = loc.getRegionInfo();
              // If region offline AND we are not to include offlined regions, return.
              if (regionInfo.isOffline() && !offlined) continue;
              regions.add(regionInfo);
            }
          }
          return true;
        }
    };
    metaScan(connection, visitor);
    return regions;
  }

  /**
   * Lists all of the table regions currently in META.
   * @param conf
   * @param offlined True if we are to include offlined regions, false and we'll
   * leave out offlined regions from returned list.
   * @return Map of all user-space regions to servers
   * @throws IOException
   * @deprecated Use {@link #allTableRegions(Connection, TableName)} instead
   */
  @Deprecated
  public static NavigableMap<HRegionInfo, ServerName> allTableRegions(Configuration conf,
      Connection connection, final TableName tableName, boolean offlined) throws IOException {
    return allTableRegions(connection, tableName);
  }

  /**
   * Lists all of the table regions currently in META.
   * @param connection
   * @param tableName
   * @return Map of all user-space regions to servers
   * @throws IOException
   */
  public static NavigableMap<HRegionInfo, ServerName> allTableRegions(
      Connection connection, final TableName tableName) throws IOException {
    final NavigableMap<HRegionInfo, ServerName> regions =
      new TreeMap<HRegionInfo, ServerName>();
    MetaScannerVisitor visitor = new TableMetaScannerVisitor(tableName) {
      @Override
      public boolean processRowInternal(Result result) throws IOException {
        RegionLocations locations = MetaTableAccessor.getRegionLocations(result);
        if (locations == null) return true;
        for (HRegionLocation loc : locations.getRegionLocations()) {
          if (loc != null) {
            HRegionInfo regionInfo = loc.getRegionInfo();
            regions.put(new UnmodifyableHRegionInfo(regionInfo), loc.getServerName());
          }
        }
        return true;
      }
    };
    metaScan(connection, visitor, tableName);
    return regions;
  }

  /**
   * Lists table regions and locations grouped by region range from META.
   */
  public static List<RegionLocations> listTableRegionLocations(Configuration conf,
      Connection connection, final TableName tableName) throws IOException {
    final List<RegionLocations> regions = new ArrayList<RegionLocations>();
    MetaScannerVisitor visitor = new TableMetaScannerVisitor(tableName) {
      @Override
      public boolean processRowInternal(Result result) throws IOException {
        RegionLocations locations = MetaTableAccessor.getRegionLocations(result);
        if (locations == null) return true;
        regions.add(locations);
        return true;
      }
    };
    metaScan(connection, visitor, tableName);
    return regions;
  }

  /**
   * Visitor class called to process each row of the hbase:meta table
   */
  public interface MetaScannerVisitor extends Closeable {
    /**
     * Visitor method that accepts a RowResult and the meta region location.
     * Implementations can return false to stop the region's loop if it becomes
     * unnecessary for some reason.
     *
     * @param rowResult result
     * @return A boolean to know if it should continue to loop in the region
     * @throws IOException e
     */
    boolean processRow(Result rowResult) throws IOException;
  }

  public static abstract class MetaScannerVisitorBase implements MetaScannerVisitor {
    @Override
    public void close() throws IOException {
    }
  }

  /**
   * A MetaScannerVisitor that skips offline regions and split parents
   */
  public static abstract class DefaultMetaScannerVisitor
    extends MetaScannerVisitorBase {

    public DefaultMetaScannerVisitor() {
      super();
    }

    public abstract boolean processRowInternal(Result rowResult) throws IOException;

    @Override
    public boolean processRow(Result rowResult) throws IOException {
      HRegionInfo info = getHRegionInfo(rowResult);
      if (info == null) {
        return true;
      }

      //skip over offline and split regions
      if (!(info.isOffline() || info.isSplit())) {
        return processRowInternal(rowResult);
      }
      return true;
    }
  }

  /**
   * A MetaScannerVisitor for a table. Provides a consistent view of the table's
   * hbase:meta entries during concurrent splits (see HBASE-5986 for details). This class
   * does not guarantee ordered traversal of meta entries, and can block until the
   * hbase:meta entries for daughters are available during splits.
   */
  public static abstract class TableMetaScannerVisitor extends DefaultMetaScannerVisitor {
    private TableName tableName;

    public TableMetaScannerVisitor(TableName tableName) {
      super();
      this.tableName = tableName;
    }

    @Override
    public final boolean processRow(Result rowResult) throws IOException {
      HRegionInfo info = getHRegionInfo(rowResult);
      if (info == null) {
        return true;
      }
      if (!(info.getTable().equals(tableName))) {
        return false;
      }
      return super.processRow(rowResult);
    }
  }
}


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('flatline', '0001_initial'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='user',
            name='flat',
        ),
    ]


text:
layout: page
title: "Harriet Alice Hanson"
comments: true
description: "blanks"
keywords: "Harriet Alice Hanson,CU,Boulder"
---
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://dl.dropboxusercontent.com/s/pc42nxpaw1ea4o9/highcharts.js?dl=0"></script>
<!-- <script src="../assets/js/highcharts.js"></script> -->
<style type="text/css">@font-face {
	font-family: "Bebas Neue";
	src: url(https://www.filehosting.org/file/details/544349/BebasNeue Regular.otf) format("opentype");
	}
	h1.Bebas {
		font-family: "Bebas Neue", Verdana, Tahoma;
	}
</style>
</head>

#### TEACHING INFORMATION

**College**: College of Arts and Sciences

**Classes taught**: ENGL 3000

#### ENGL 3000: Shakespeare for Nonmajors

**Terms taught**: Spring 2017

**Instructor rating**: 5.17

**Standard deviation in instructor rating**: 0.0

**Average grade** (4.0 scale): 3.0

**Standard deviation in grades** (4.0 scale): 0.0

**Average workload** (raw): 2.47

**Standard deviation in workload** (raw): 0.0


text:
namespace Toggl.Shared.Extensions
{
    public static class PasswordExtensions
    {
        public static Password ToPassword(this string self)
            => Password.From(self);
    }
}


text:
using DevExpress.XtraBars;

namespace Tralus.Framework.Module.Win.Controls
{
    partial class TralusDateTimeControl
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                this.persianDateControl.ValueChanged -= this.persianDateControl_ValueChanged;
                this.dateControl.EditValueChanged -= this.dateControl_EditValueChanged;
                this.timeControl.EditValueChanged -= this.timeEdit_EditValueChanged;

                foreach (var calendarBarButtonItem in calenderBarButtonItems)
                {
                    calendarBarButtonItem.ItemClick -= barButtonItemCalendar_ItemClick;
                }

                foreach (var timeZoneBarButtonItem in timeZoneBarButtonItems)
                {
                    timeZoneBarButtonItem.ItemClick -= barButtonItemTimeZone_ItemClick;
                }

                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.tableLayoutPanel = new System.Windows.Forms.TableLayoutPanel();
            this.persianDateControl = new Tralus.Framework.Module.Win.Controls.BaseControl.PersianDateControl();
            this.dateControl = new DevExpress.XtraEditors.DateEdit();
            this.dropDownButtonTimeZone = new DevExpress.XtraEditors.DropDownButton();
            this.popupTimeZoneMenu = new DevExpress.XtraBars.PopupMenu(this.components);
            this.barManager = new DevExpress.XtraBars.BarManager(this.components);
            this.barDockControlTop = new DevExpress.XtraBars.BarDockControl();
            this.barDockControlBottom = new DevExpress.XtraBars.BarDockControl();
            this.barDockControlLeft = new DevExpress.XtraBars.BarDockControl();
            this.barDockControlRight = new DevExpress.XtraBars.BarDockControl();
            this.barButtonItem1 = new DevExpress.XtraBars.BarButtonItem();
            this.timeControl = new DevExpress.XtraEditors.TimeEdit();
            this.dropDownButtonCalendar = new DevExpress.XtraEditors.DropDownButton();
            this.popupCalendarMenu = new DevExpress.XtraBars.PopupMenu(this.components);
            this.tableLayoutPanel.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.dateControl.Properties.CalendarTimeProperties)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.dateControl.Properties)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.popupTimeZoneMenu)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.barManager)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.timeControl.Properties)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.popupCalendarMenu)).BeginInit();
            this.SuspendLayout();
            //
            // tableLayoutPanel
            //
            this.tableLayoutPanel.BackColor = System.Drawing.Color.Transparent;
            this.tableLayoutPanel.ColumnCount = 5;
            this.tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
            this.tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
            this.tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
            this.tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
            this.tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
            this.tableLayoutPanel.Controls.Add(this.persianDateControl, 1, 0);
            this.tableLayoutPanel.Controls.Add(this.dateControl, 2, 0);
            this.tableLayoutPanel.Controls.Add(this.dropDownButtonTimeZone, 4, 0);
            this.tableLayoutPanel.Controls.Add(this.timeControl, 3, 0);
            this.tableLayoutPanel.Controls.Add(this.dropDownButtonCalendar, 0, 0);
            this.tableLayoutPanel.Dock = System.Windows.Forms.DockStyle.Fill;
            this.tableLayoutPanel.Location = new System.Drawing.Point(0, 0);
            this.tableLayoutPanel.Margin = new System.Windows.Forms.Padding(1);
            this.tableLayoutPanel.Name = "tableLayoutPanel";
            this.tableLayoutPanel.RowCount = 2;
            this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle());
            this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F));
            this.tableLayoutPanel.Size = new System.Drawing.Size(403, 24);
            this.tableLayoutPanel.TabIndex = 2;
            //
            // persianDateControl
            //
            this.persianDateControl.Dock = System.Windows.Forms.DockStyle.Fill;
            this.persianDateControl.Location = new System.Drawing.Point(48, 1);
            this.persianDateControl.Margin = new System.Windows.Forms.Padding(1);
            this.persianDateControl.Name = "persianDateControl";
            this.persianDateControl.Size = new System.Drawing.Size(100, 20);
            this.persianDateControl.TabIndex = 0;
            this.persianDateControl.Value = null;
            this.persianDateControl.ValueChanged += new System.EventHandler(this.persianDateControl_ValueChanged);
            //
            // dateControl
            //
            this.dateControl.Dock = System.Windows.Forms.DockStyle.Fill;
            this.dateControl.EditValue = null;
            this.dateControl.Location = new System.Drawing.Point(150, 1);
            this.dateControl.Margin = new System.Windows.Forms.Padding(1);
            this.dateControl.Name = "dateControl";
            this.dateControl.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
            new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)});
            this.dateControl.Properties.CalendarTimeProperties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
            new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)});
            this.dateControl.Size = new System.Drawing.Size(100, 20);
            this.dateControl.TabIndex = 1;
            this.dateControl.EditValueChanged += new System.EventHandler(this.dateControl_EditValueChanged);
            //
            // dropDownButtonTimeZone
            //
            this.dropDownButtonTimeZone.DropDownControl = this.popupTimeZoneMenu;
            this.dropDownButtonTimeZone.Location = new System.Drawing.Point(354, 1);
            this.dropDownButtonTimeZone.Margin = new System.Windows.Forms.Padding(1);
            this.dropDownButtonTimeZone.Name = "dropDownButtonTimeZone";
            this.dropDownButtonTimeZone.Size = new System.Drawing.Size(45, 20);
            this.dropDownButtonTimeZone.TabIndex = 3;
            //
            // popupTimeZoneMenu
            //
            this.popupTimeZoneMenu.Manager = this.barManager;
            this.popupTimeZoneMenu.Name = "popupTimeZoneMenu";
            //
            // barManager
            //
            this.barManager.DockControls.Add(this.barDockControlTop);
            this.barManager.DockControls.Add(this.barDockControlBottom);
            this.barManager.DockControls.Add(this.barDockControlLeft);
            this.barManager.DockControls.Add(this.barDockControlRight);
            this.barManager.Form = this;
            this.barManager.Items.AddRange(new DevExpress.XtraBars.BarItem[] {
            this.barButtonItem1});
            this.barManager.MaxItemId = 8;
            //
            // barDockControlTop
            //
            this.barDockControlTop.CausesValidation = false;
            this.barDockControlTop.Dock = System.Windows.Forms.DockStyle.Top;
            this.barDockControlTop.Location = new System.Drawing.Point(0, 0);
            this.barDockControlTop.Size = new System.Drawing.Size(403, 0);
            //
            // barDockControlBottom
            //
            this.barDockControlBottom.CausesValidation = false;
            this.barDockControlBottom.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.barDockControlBottom.Location = new System.Drawing.Point(0, 24);
            this.barDockControlBottom.Size = new System.Drawing.Size(403, 0);
            //
            // barDockControlLeft
            //
            this.barDockControlLeft.CausesValidation = false;
            this.barDockControlLeft.Dock = System.Windows.Forms.DockStyle.Left;
            this.barDockControlLeft.Location = new System.Drawing.Point(0, 0);
            this.barDockControlLeft.Size = new System.Drawing.Size(0, 24);
            //
            // barDockControlRight
            //
            this.barDockControlRight.CausesValidation = false;
            this.barDockControlRight.Dock = System.Windows.Forms.DockStyle.Right;
            this.barDockControlRight.Location = new System.Drawing.Point(403, 0);
            this.barDockControlRight.Size = new System.Drawing.Size(0, 24);
            //
            // barButtonItem1
            //
            this.barButtonItem1.Caption = "barButtonItem1";
            this.barButtonItem1.Id = 7;
            this.barButtonItem1.Name = "barButtonItem1";
            //
            // timeControl
            //
            this.timeControl.EditValue = null;
            this.timeControl.Location = new System.Drawing.Point(252, 1);
            this.timeControl.Margin = new System.Windows.Forms.Padding(1);
            this.timeControl.Name = "timeControl";
            this.timeControl.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
            new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)});
            this.timeControl.Size = new System.Drawing.Size(100, 20);
            this.timeControl.TabIndex = 4;
            this.timeControl.EditValueChanged += new System.EventHandler(this.timeEdit_EditValueChanged);
            //
            // dropDownButtonCalendar
            //
            this.dropDownButtonCalendar.DropDownControl = this.popupCalendarMenu;
            this.dropDownButtonCalendar.Location = new System.Drawing.Point(1, 1);
            this.dropDownButtonCalendar.Margin = new System.Windows.Forms.Padding(1);
            this.dropDownButtonCalendar.Name = "dropDownButtonCalendar";
            this.dropDownButtonCalendar.Size = new System.Drawing.Size(45, 20);
            this.dropDownButtonCalendar.TabIndex = 5;
            //
            // popupCalendarMenu
            //
            this.popupCalendarMenu.Manager = this.barManager;
            this.popupCalendarMenu.Name = "popupCalendarMenu";
            //
            // TralusDateTimeControl
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Controls.Add(this.tableLayoutPanel);
            this.Controls.Add(this.barDockControlLeft);
            this.Controls.Add(this.barDockControlRight);
            this.Controls.Add(this.barDockControlBottom);
            this.Controls.Add(this.barDockControlTop);
            this.Margin = new System.Windows.Forms.Padding(0);
            this.Name = "TralusDateTimeControl";
            this.Size = new System.Drawing.Size(403, 24);
            this.tableLayoutPanel.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.dateControl.Properties.CalendarTimeProperties)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.dateControl.Properties)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.popupTimeZoneMenu)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.barManager)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.timeControl.Properties)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.popupCalendarMenu)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.TableLayoutPanel tableLayoutPanel;
        private BaseControl.PersianDateControl persianDateControl;
        private DevExpress.XtraEditors.DateEdit dateControl;
        private DevExpress.XtraEditors.DropDownButton dropDownButtonTimeZone;
        //private System.Windows.Forms.BindingSource tralusDateTimeBindingSource;
        private DevExpress.XtraBars.PopupMenu popupTimeZoneMenu;
        private DevExpress.XtraBars.BarManager barManager;
        private DevExpress.XtraBars.BarDockControl barDockControlTop;
        private DevExpress.XtraBars.BarDockControl barDockControlBottom;
        private DevExpress.XtraBars.BarDockControl barDockControlLeft;
        private DevExpress.XtraBars.BarDockControl barDockControlRight;
        private DevExpress.XtraEditors.TimeEdit timeControl;
        private DevExpress.XtraEditors.DropDownButton dropDownButtonCalendar;
        private DevExpress.XtraBars.PopupMenu popupCalendarMenu;
        private BarButtonItem barButtonItem1;

    }
}


text:
Project to implement the bluetooth protocol of the yeelight bedside lamp, using Noble library.
I have (almost) completely retro engineered the protocol, you can watch the doc in doc/protocol.htm.

Node implementation in progress :)


text:
Gitlab Authentication
=====================

Requirements
------------

- Account on [Gitlab.com](https://gitlab.com) or you own self-hosted Gitlab instance
- Have Kanboard registered as application in Gitlab

How does this work?
-------------------

The Gitlab authentication in Kanboard uses the [OAuth 2.0](http://oauth.net/2/) protocol, so any user of Kanboard can be linked to a Gitlab account.

That means you can use your Gitlab account to login on Kanboard.

How to link a Gitlab account
----------------------------

1. Go to your user profile
2. Click on **External accounts**
3. Click on the link **Link my Gitlab Account**
4. You are redirected to the **Gitlab authorization form**
5. Authorize Kanboard by clicking on the button **Accept**
6. Your account is now linked

Now, on the login page you can be authenticated in one click with the link **Login with my Gitlab Account**.

Your name and email are automatically updated from your Gitlab Account if defined.

Installation instructions
-------------------------

### Setting up OAuth 2.0

- On Gitlab, register a new application by following the [official documentation](http://doc.gitlab.com/ce/integration/oauth_provider.html)
- In Kanboard, you can get the **callback url** in **Settings > Integrations > Gitlab Authentication**, just copy and paste the url

### Setting up Kanboard

Either create a new `config.php` file or rename the `config.default.php` file and set the following values:

```php
// Enable/disable Gitlab authentication
define('GITLAB_AUTH', true);

// Gitlab application id
define('GITLAB_CLIENT_ID', 'YOUR_APPLICATION_ID');

// Gitlab application secret
define('GITLAB_CLIENT_SECRET', 'YOUR_APPLICATION_SECRET');
```

### Custom endpoints for self-hosted Gitlab

Change these default values if you use a self-hosted instance of Gitlab:

```php
// Gitlab oauth2 authorize url
define('GITLAB_OAUTH_AUTHORIZE_URL', 'https://gitlab.com/oauth/authorize');

// Gitlab oauth2 token url
define('GITLAB_OAUTH_TOKEN_URL', 'https://gitlab.com/oauth/token');

// Gitlab API url endpoint (don't forget the slash at the end)
define('GITLAB_API_URL', 'https://gitlab.com/api/v3/');
```

Notes
-----

Kanboard uses these information from your Gitlab profile:

- Full name
- Email address
- Gitlab unique id

The Gitlab unique id is used to link the local user account and the Gitlab account.

Known issues
------------

Gitlab OAuth will work only with url rewrite enabled. At the moment, Gitlab doesn't support callback url with query string parameters. See [Gitlab issue](https://gitlab.com/gitlab-org/gitlab-ce/issues/2443)


text:
package net.iskandar.examples.project_management.dao;

import java.util.List;
import net.iskandar.examples.project_management.domain.Project;

public interface ProjectDao extends Dao<Project>, ListLoader<Project> {
    List<Project> list();
}


text:
<?= $wrapParams['header'] ?>

    <?= $out; ?>


text:
/*
 * analysis.h
 *
 *  Created on: 25-jan-2013
 *      Author: M. El-Kebir
 */

#ifndef MWCSANALYZE_H
#define MWCSANALYZE_H

#include <lemon/core.h>
#include <lemon/dijkstra.h>
#include <lemon/suurballe.h>
#include <limits>
#include <set>
#include <vector>
#include <list>
#include "mwcsgraph.h"

namespace nina {
namespace mwcs {

template<typename GR,
         typename WGHT = typename GR::template NodeMap<double> >
class MwcsAnalyze
{
public:
  typedef GR Graph;
  typedef WGHT WeightNodeMap;
  typedef MwcsGraph<GR, WGHT> MwcsGraphType;
  typedef typename GR::template ArcMap<double> WeightArcMap;
  typedef typename GR::template NodeMap<WeightNodeMap*> WeightNodeMatrix;

  TEMPLATE_GRAPH_TYPEDEFS(Graph);

  typedef typename GR::template NodeMap<BoolNodeMap*> BoolNodeMatrix;

  typedef typename std::vector<Node> NodeVector;
  typedef typename std::set<Node> NodeSet;
  typedef typename NodeSet::const_iterator NodeSetIt;
  typedef typename std::vector<NodeSet> NodeSetVector;
  typedef typename NodeSetVector::const_iterator NodeSetVectorIt;

  typedef typename lemon::Dijkstra<GR, WeightArcMap> DijkstraType;
  typedef typename std::list<Node> NodeList;
  typedef typename NodeList::const_iterator NodeListIt;

  typedef typename lemon::Suurballe<GR, WeightArcMap> SuurballeType;
  typedef typename SuurballeType::Path PathType;
  typedef typename GR::template NodeMap<PathType> PathMap;
  typedef typename GR::template NodeMap<PathMap*> PathMatrix;

  typedef typename GR::template NodeMap<NodeSet> NodeSetMap;

public:
  MwcsAnalyze(const MwcsGraphType& mwcsGraph);
  MwcsAnalyze(const Graph& g,
              const WeightNodeMap& weight,
              const IntNodeMap& comp);
  ~MwcsAnalyze();

  void analyze(bool eqClasses = false);
  void analyzeS(int k);
  void analyzeNegHubs();

  int getEqClassesCount() const { return static_cast<int>(_eqClasses.size()); }
  const NodeSetVector& getEqClasses() const { return _eqClasses; }
  int getEqClass(Node n) const { return _eqClassMap[n]; }
  void print(std::ostream& out) const
  {
    int eqClassIdx = 0;
    for (NodeSetVectorIt nodeSetIt = _eqClasses.begin(); nodeSetIt != _eqClasses.end(); nodeSetIt++, eqClassIdx++)
    {
      if (nodeSetIt->size() == 1) continue;
      out << "// Equivalence class " << eqClassIdx << " size " << nodeSetIt->size() << std::endl;
      out << "// ";
      for (NodeSetIt nodeIt = nodeSetIt->begin(); nodeIt != nodeSetIt->end(); nodeIt++)
      {
        out << _g.id(*nodeIt) << " ";
      }
      out << std::endl;
    }
  }

  void print(const PathType& p, std::ostream& out) const
  {
    NodeList path;
    bool f = true;
    for (typename PathType::ArcIt a(p); a != lemon::INVALID; ++a)
    {
      if (f)
      {
        path.push_back(_g.source(a));
        f = false;
      }
      path.push_back(_g.target(a));
    }

    double cumWeight = 0;
    double maxCumWeight = -std::numeric_limits<double>::max();

    bool first = true;
    for (NodeListIt nodeIt = path.begin(); nodeIt != path.end(); nodeIt++)
    {
      cumWeight += _weight[*nodeIt];
      if (cumWeight > maxCumWeight)
        maxCumWeight = cumWeight;

      if (!first)
      {
        std::cout << " -> ";
      }
      else
      {
        first = false;
      }

      out << _g.id(*nodeIt) << " (" << _weight[*nodeIt] << ")";
    }
    out << " : " << cumWeight << "/" << maxCumWeight << std::endl;
  }

  bool ok(Node i, Node j) const
  {
    if (_ok[i] != NULL)
      return (*_ok[i])[j];
    else
      return false;
  }

  const PathType& path(Node i, Node j) const
  {
    assert(_path[i] != NULL);
    return (*_path[i])[j];
  }

  void printNegHubs(const MwcsGraphType& mwcsGraph, std::ostream& out) const
  {
    for (NodeIt v(_g); v != lemon::INVALID; ++v)
    {
      if (_beneficial[v])
      {
        out << "// NegHub: " << mwcsGraph.getLabel(v) << "\t"
            << _weight[v] << "\t"
            << _benefit[v] << std::endl;

        const NodeSet& posNeighbors = _posNeighbors[v];
        for (NodeSetIt nodeIt = posNeighbors.begin();
             nodeIt != posNeighbors.end(); nodeIt++)
        {
          out << mwcsGraph.getLabel(*nodeIt) << "\t"
              << _weight[*nodeIt] << std::endl;
        }
        out << std::endl;
      }
    }
  }

private:
  const Graph& _g;
  const WeightNodeMap& _weight;
  const IntNodeMap& _comp;
  WeightArcMap _arcWeight;
  NodeSetVector _eqClasses;
  IntNodeMap _eqClassMap;
  BoolNodeMatrix _ok;
  PathMatrix _path;

  DoubleNodeMap _benefit;
  NodeSetMap _posNeighbors;
  BoolNodeMap _beneficial;
  int _nBenificialNegHubs;
  NodeSet _beneficialNegHubs;
  NodeVector _rouletteWheel;

  double initArcWeights();
  bool isPathOK(const PathType& p) const;

public:
  const NodeSet& getBeneficialNegHubs() const
  {
    return _beneficialNegHubs;
  }

  double getBenefit(Node negHub) const
  {
    return _benefit[negHub];
  }

  int getNumberOfBeneficialNegHubs() const
  {
    return _nBenificialNegHubs;
  }

  const NodeSet& getPosNeighbors(Node negHub) const
  {
    return _posNeighbors[negHub];
  }

  const NodeVector& getRouletteWheel() const
  {
    return _rouletteWheel;
  }
};

template<typename GR, typename WGHT>
inline MwcsAnalyze<GR, WGHT>::~MwcsAnalyze()
{
  for (NodeIt n(_g); n != lemon::INVALID; ++n)
  {
    delete _ok[n];
    delete _path[n];
  }
}

template<typename GR, typename WGHT>
inline MwcsAnalyze<GR, WGHT>::MwcsAnalyze(const MwcsGraphType& mwcsGraph)
  : _g(mwcsGraph.getGraph())
  , _weight(mwcsGraph.getScores())
  , _comp(mwcsGraph.getComponentMap())
  , _arcWeight(_g)
  , _eqClasses()
  , _eqClassMap(_g, -1)
  , _ok(_g, NULL)
  , _path(_g, NULL)
  , _benefit(_g)
  , _posNeighbors(_g)
  , _beneficial(_g, false)
  , _nBenificialNegHubs(0)
  , _beneficialNegHubs()
  , _rouletteWheel()
{
}

template<typename GR, typename WGHT>
inline MwcsAnalyze<GR, WGHT>::MwcsAnalyze(const Graph& g,
                                          const WeightNodeMap& weight,
                                          const IntNodeMap& comp)
  : _g(g)
  , _weight(weight)
  , _comp(comp)
  , _arcWeight(_g)
  , _eqClasses()
  , _eqClassMap(_g, -1)
  , _ok(_g, NULL)
  , _path(_g, NULL)
  , _benefit(_g)
  , _posNeighbors(_g)
  , _beneficial(_g, false)
  , _nBenificialNegHubs(0)
  , _beneficialNegHubs()
  , _rouletteWheel()
{
}

template<typename GR, typename WGHT>
inline bool MwcsAnalyze<GR, WGHT>::isPathOK(const PathType& p) const
{
  NodeList path;
  bool f = true;
  for (typename PathType::ArcIt a(p); a != lemon::INVALID; ++a)
  {
    if (f)
    {
      path.push_back(_g.source(a));
      f = false;
    }
    path.push_back(_g.target(a));
  }

  //if (path.size() && path.front() != i)
  //  return false;

  //bool first = true;

  double cumWeight = 0;
  double maxCumWeight = -std::numeric_limits<double>::max();

  for (NodeListIt nodeIt = path.begin(); nodeIt != path.end(); nodeIt++)
  {
    cumWeight += _weight[*nodeIt];
    if (cumWeight > maxCumWeight)
      maxCumWeight = cumWeight;

    //if (!first)
    //{
    //  std::cout << " -> ";
    //}
    //else
    //{
    //  first = false;
    //}

    //std::cout << _g.id(*nodeIt);
  }
  //std::cout << " : " << cumWeight << "/" << maxCumWeight << std::endl;

  return cumWeight == maxCumWeight && cumWeight >= 0;
}

template<typename GR, typename WGHT>
inline void MwcsAnalyze<GR, WGHT>::analyzeS(int k)
{
  initArcWeights();
  SuurballeType sb(_g, _arcWeight);

  for (NodeIt i(_g); i != lemon::INVALID; ++i)
  {
    if (_weight[i] <= 0)
      continue;

    int comp_i = _comp[i];
    delete _ok[i];
    _ok[i] = new BoolNodeMap(_g, false);

    // compute single source shortest path from i
    sb.init(i);

    for (NodeIt j(_g); j != lemon::INVALID; ++j)
    {
      if (i == j)
        continue;

      if (_weight[j] <= 0 || comp_i != _comp[j])
        continue;

      int n = sb.start(j, k);
      for (int idx = 0; idx < n; idx++)
      {
        PathType path = sb.path(idx);
        if (isPathOK(path))
        {
          (*_ok[i])[j] = true;
          break;
        }
      }
    }
  }
}

template<typename GR, typename WGHT>
inline void MwcsAnalyze<GR, WGHT>::analyze(bool eqClasses)
{
  initArcWeights();
  lemon::Dijkstra<GR, WeightArcMap> dijkstra(_g, _arcWeight);

  int count = 0;
  for (NodeIt i(_g); i != lemon::INVALID; ++i)
  {
    if (_weight[i] <= 0)
      continue;

    int comp_i = _comp[i];
    _ok[i] = new BoolNodeMap(_g, false);
    _path[i] = new PathMap(_g);

    // compute single source shortest path from i
    int localCount = 0;
    do
    {
      dijkstra.init();
      dijkstra.run(i);

      for (NodeIt j(_g); j != lemon::INVALID; ++j)
      {
        if (i == j)
          continue;

        if (_weight[j] <= 0 || comp_i != _comp[j])
          continue;

        if (dijkstra.reached(j))
        {
          PathType p = dijkstra.path(j);
          if (isPathOK(p))
          {
            (*_ok[i])[j] = true;
            (*_path[i])[j] = p;
            count++;
          }
        }
      }
    } while (localCount != 0);
  }

  if (g_verbosity >= VERBOSE_ESSENTIAL)
    std::cout << "// Identified " << count << " dependent node pairs" << std::endl;

  // determine all equivalence classes
  if (eqClasses)
  {
    lemon::mapFill(_g, _eqClassMap, -1);
    int eqClassIdx = 0;
    _eqClasses.clear();

    for (NodeIt i(_g); i != lemon::INVALID; ++i)
    {
      if (_weight[i] <= 0)
        continue;

      for (NodeIt j = i; j != lemon::INVALID; ++j)
      {
        if (_weight[j] <= 0)
          continue;

        if (i != j)
        {
          bool ok_i_j = (*_ok[i])[j];
          bool ok_j_i = (*_ok[j])[i];

          if (_g.id(i) == 3522 && _g.id(j) == 3437)
          {
            print(path(i, j), std::cerr);
            print(path(j, i), std::cerr);
          }

          if (ok_i_j && ok_j_i)
          {
            print(path(i, j), std::cerr);
            print(path(j, i), std::cerr);

            if (_eqClassMap[i] == -1 && _eqClassMap[j] == -1)
            {
              // add to new eqClass
              _eqClasses.push_back(NodeSet());
              _eqClassMap[i] = _eqClassMap[j] = eqClassIdx;
              _eqClasses[eqClassIdx].insert(i);
              _eqClasses[eqClassIdx].insert(j);

              eqClassIdx++;
            }
            else if (_eqClassMap[i] == -1)
            {
              _eqClassMap[i] = _eqClassMap[j];
              _eqClasses[_eqClassMap[i]].insert(i);
            }
            else if (_eqClassMap[j] == -1)
            {
              _eqClassMap[j] = _eqClassMap[i];
              _eqClasses[_eqClassMap[j]].insert(j);
            }
            else
            {
//              assert(_eqClassMap[i] == _eqClassMap[j]);
              // merge j into i
              for (NodeSetIt it = _eqClasses[_eqClassMap[j]].begin(), it_end = _eqClasses[_eqClassMap[j]].end();
                   it != it_end; ++it)
              {
                _eqClassMap[*it] = _eqClassMap[i];
              }
              _eqClasses[_eqClassMap[i]].insert(_eqClasses[_eqClassMap[j]].begin(), _eqClasses[_eqClassMap[j]].end());
            }
            std::cerr << _eqClassMap[i] << std::endl << std::endl;
          }
        }
      }

      // wtf is this?
//      if (_eqClassMap[i] == -1)
//      {
//        _eqClassMap[i] = eqClassIdx;
//        _eqClasses.push_back(NodeSet());
//        _eqClasses[eqClassIdx].insert(i);
//        eqClassIdx++;
//      }
    }
  }
}

template<typename GR, typename WGHT>
inline void MwcsAnalyze<GR, WGHT>::analyzeNegHubs()
{
  // 1. start by identifying all negative hubs
  _nBenificialNegHubs = 0;
  _beneficialNegHubs.clear();
  for (NodeIt v(_g); v != lemon::INVALID; ++v)
  {
    _beneficial[v] = false;
    _benefit[v] = 0;

    NodeSet& posNeighbors = _posNeighbors[v];
    posNeighbors.clear();

    if (_weight[v] >= 0) continue;

    double maxPosWeight = 0;
    _benefit[v] = _weight[v];
    for (IncEdgeIt e(_g, v); e != lemon::INVALID; ++e)
    {
      Node w = _g.oppositeNode(v, e);
      double weight_w = _weight[w];
      if (weight_w >= 0)
      {
        posNeighbors.insert(w);
        _benefit[v] += weight_w;
        if (weight_w > maxPosWeight)
        {
          maxPosWeight = weight_w;
        }
      }
    }

    if (_benefit[v] >= maxPosWeight)
    {
      _beneficial[v] = true;
      _nBenificialNegHubs++;
      _beneficialNegHubs.insert(v);
    }
  }

  // 2. construct roulette wheel
  _rouletteWheel.clear();

  for (NodeSetIt nodeIt = _beneficialNegHubs.begin();
       nodeIt != _beneficialNegHubs.end(); nodeIt++)
  {
    int b = round(_benefit[*nodeIt]);
    for (int i = 0; i < b; i++) _rouletteWheel.push_back(*nodeIt);
  }
}

template<typename GR, typename WGHT>
inline double MwcsAnalyze<GR, WGHT>::initArcWeights()
{
  double offset = 0;

  // first determine the offset
  for (NodeIt n(_g); n != lemon::INVALID; ++n)
  {
    if (_weight[n] < offset)
    {
      offset = _weight[n];
    }
  }

  // now compute arc weights
  for (ArcIt a(_g); a != lemon::INVALID; ++a)
  {
    Node v = _g.target(a);
    _arcWeight[a] = _weight[v] - offset;
  }

  return -offset;
}

} // namespace mwcs
} // namespace nina

#endif // MWCSANALYZE_H


text:
if [ "$(stat --format "%Y" "${CONFLUENCE_INSTALL}/conf/server.xml")" -eq "0" ]; then
  if [ -n "${X_PROXY_NAME}" ]; then
    xmlstarlet ed --inplace --pf --ps --insert '//Connector[@port="8090"]' --type "attr" --name "proxyName" --value "${X_PROXY_NAME}" "${CONFLUENCE_INSTALL}/conf/server.xml"
  fi
  if [ -n "${X_PROXY_PORT}" ]; then
    xmlstarlet ed --inplace --pf --ps --insert '//Connector[@port="8090"]' --type "attr" --name "proxyPort" --value "${X_PROXY_PORT}" "${CONFLUENCE_INSTALL}/conf/server.xml"
  fi
  if [ -n "${X_PROXY_SCHEME}" ]; then
    xmlstarlet ed --inplace --pf --ps --insert '//Connector[@port="8090"]' --type "attr" --name "scheme" --value "${X_PROXY_SCHEME}" "${CONFLUENCE_INSTALL}/conf/server.xml"
  fi
  if [ -n "${X_PROXY_SECURE}" ]; then
    xmlstarlet ed --inplace --pf --ps --insert '//Connector[@port="8090"]' --type "attr" --name "secure" --value "${X_PROXY_SECURE}" "${CONFLUENCE_INSTALL}/conf/server.xml"
  fi
  if [ -n "${X_PATH}" ]; then
    xmlstarlet ed --inplace --pf --ps --update '//Context/@path' --value "${X_PATH}" "${CONFLUENCE_INSTALL}/conf/server.xml"
  fi
fi

if [ -f "${CERTIFICATE}" ]; then
  keytool -noprompt -storepass changeit -keystore ${JAVA_CACERTS} -import -file ${CERTIFICATE} -alias CompanyCA
fi

exec "$@"


text:
//------------------------------------------------------------------------------
// <copyright file="FileSecurityNativeMethods.cs" company="Microsoft">
//    Copyright (c) Microsoft Corporation
// </copyright>
//------------------------------------------------------------------------------

namespace Microsoft.Azure.Storage.DataMovement.Interop
{
    using System;
    using System.Runtime.InteropServices;
    using System.Text;

    internal static partial class NativeMethods
    {
        public const int SE_PRIVILEGE_ENABLED = 0x00000002;
        public const int SE_PRIVILEGE_DISABLED = 0x00000000;

        public const int ERROR_ACCESS_DENIED = 5;
        public const int ERROR_NOT_ALL_ASSIGNED = 1300;
        public const int ERROR_INVALID_OWNER = 1307;
        public const int ERROR_PRIVILEGE_NOT_HELD = 1314;
        public const int ERROR_INSUFFICIENT_BUFFER = 122;
        public const int SDDL_REVISION_1 = 1;

        public const string SACLPrivilegeName = "SeSecurityPrivilege";
        public const string OwnerPrivilegeName = "SeRestorePrivilege";

        [Flags]
        public enum SECURITY_INFORMATION : uint
        {
            OWNER_SECURITY_INFORMATION = 0x00000001,
            GROUP_SECURITY_INFORMATION = 0x00000002,
            DACL_SECURITY_INFORMATION = 0x00000004,
            SACL_SECURITY_INFORMATION = 0x00000008,
            UNPROTECTED_SACL_SECURITY_INFORMATION = 0x10000000,
            UNPROTECTED_DACL_SECURITY_INFORMATION = 0x20000000,
            PROTECTED_SACL_SECURITY_INFORMATION = 0x40000000,
            PROTECTED_DACL_SECURITY_INFORMATION = 0x80000000
        }

        public enum SE_OBJECT_TYPE
        {
            SE_UNKNOWN_OBJECT_TYPE = 0,
            SE_FILE_OBJECT,
            SE_SERVICE,
            SE_PRINTER,
            SE_REGISTRY_KEY,
            SE_LMSHARE,
            SE_KERNEL_OBJECT,
            SE_WINDOW_OBJECT,
            SE_DS_OBJECT,
            SE_DS_OBJECT_ALL,
            SE_PROVIDER_DEFINED_OBJECT,
            SE_WMIGUID_OBJECT,
            SE_REGISTRY_WOW64_32KEY
        }

        public enum SID_NAME_USE
        {
            SidTypeUser,
            SidTypeGroup,
            SidTypeDomain,
            SidTypeAlias,
            SidTypeWellKnownGroup,
            SidTypeDeletedAccount,
            SidTypeInvalid,
            SidTypeUnknown,
            SidTypeComputer,
            SidTypeLabel,
            SidTypeLogonSession
        };

        [StructLayout(LayoutKind.Sequential)]
        public struct LUID
        {
            public UInt32 LowPart;
            public Int32 HighPart;
        }

        [StructLayout(LayoutKind.Sequential, Pack = 4)]
        public struct LUID_AND_ATTRIBUTES
        {
            public LUID Luid;
            public UInt32 Attributes;
        }

        public struct TOKEN_PRIVILEGES
        {
            public int PrivilegeCount;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
            public LUID_AND_ATTRIBUTES[] Privileges;
        }

        #region Get/Set FileDDL
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2205:UseManagedEquivalentsOfWin32Api")]
        [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool GetUserName(StringBuilder sb, ref Int32 length);

        [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool LookupAccountName(
            string lpSystemName,
            string lpAccountName,
            [MarshalAs(UnmanagedType.LPArray)] byte[] Sid,
            ref uint cbSid,
            StringBuilder ReferencedDomainName,
            ref uint cchReferencedDomainName,
            out SID_NAME_USE peUse);

        [DllImport("advapi32", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool GetWindowsAccountDomainSid(
            [MarshalAs(UnmanagedType.LPArray)] byte[] sid,
            [MarshalAs(UnmanagedType.LPArray)] byte[] domainSid,
            ref uint length);

        [DllImport("advapi32.dll", EntryPoint = "GetNamedSecurityInfoW", SetLastError = true, CharSet = CharSet.Unicode)]
        public static extern uint GetNamedSecurityInfoW(
                 string pObjectName,
                 SE_OBJECT_TYPE ObjectType,
                 SECURITY_INFORMATION SecurityInfo,
                 out IntPtr pSidOwner,
                 out IntPtr pSidGroup,
                 out IntPtr pDacl,
                 out IntPtr pSacl,
                 out IntPtr pSecurityDescriptor);

        [DllImport("Advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern void SetFileSecurity(string path, int type_of_sd, IntPtr sd);

        [DllImport("kernel32.dll", EntryPoint = "LocalFree", SetLastError = true)]
        public static extern IntPtr LocalFree(IntPtr handle);

        [DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool ConvertSidToStringSid([MarshalAs(UnmanagedType.LPArray)] byte[] sid, out IntPtr ptrSid);

        // Call LocalFree to free SecurityDescriptor pointer.
        [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool ConvertStringSecurityDescriptorToSecurityDescriptor(
               string StringSecurityDescriptor,
               uint StringSDRevision,
               out IntPtr SecurityDescriptor,
               out UIntPtr SecurityDescriptorSize);

        [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool ConvertSecurityDescriptorToStringSecurityDescriptor(
            IntPtr SecurityDescriptor,
            uint StringSDRevision,
            SECURITY_INFORMATION SecurityInformation,
            out IntPtr StringSecurityDescriptor,
            out UIntPtr StringSecurityDescriptorLen);
        #endregion

        [DllImport("advapi32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool AdjustTokenPrivileges(IntPtr TokenHandle,
           [MarshalAs(UnmanagedType.Bool)]bool DisableAllPrivileges,
           ref TOKEN_PRIVILEGES NewState,
           UInt32 BufferLengthInBytes,
           ref TOKEN_PRIVILEGES PreviousState,
           out UInt32 ReturnLengthInBytes);

        [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool LookupPrivilegeValue(string lpSystemName, string lpName,
            ref LUID lpLuid);
    }
}


text:
package org.jgroups.auth;

import org.jgroups.*;
import org.jgroups.annotations.Property;
import org.jgroups.conf.ClassConfigurator;
import org.jgroups.protocols.AUTH;
import org.jgroups.util.Util;

import java.io.DataInput;
import java.io.DataOutput;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

/**
 * AuthToken implementation which shows how to send messages back and forth in order to perform authentication. Could
 * be used as a template for a challenge-response based AuthToken impl.
 * @author Bela Ban
 * @since  3.3
 */
public class DemoToken extends AuthToken implements AUTH.UpHandler {
    protected static final short ID=1555; // the ID to fetch a DemoHeader from a message

    @Property(description="How long to wait (in ms) for a response to a challenge")
    protected long block_time=5000;

    // Used to correlate pending challenge requests sent with responses received
    protected final Map<Address,Entry> pending_requests=new HashMap<>();

    static {
        ClassConfigurator.add((short)1555, DemoHeader.class);
    }

    public String getName() {return "org.jgroups.auth.DemoToken";}
    public void   init()    {auth.register(this);}

    public boolean authenticate(AuthToken token, Message msg) {
        Address sender=msg.getSrc();

        // 1. send a challenge to the sender
        Message    challenge=new Message(sender).setFlag(Message.Flag.OOB);
        byte[]     buf=generateRandomBytes();
        DemoHeader hdr=new DemoHeader(buf);
        challenge.putHeader(ID, hdr);

        Entry entry=new Entry(buf);
        pending_requests.put(sender, entry); // here we'd have to check if a latch already exists...
        if(log.isTraceEnabled())
            log.trace(auth.getAddress() + ": sending challenge to " + sender);
        auth.getDownProtocol().down(challenge);
        try {
            entry.latch.await(block_time, TimeUnit.MILLISECONDS);
            pending_requests.remove(sender);
            boolean result=entry.hash > 0 && entry.hash == hash(encrypt(entry.challenge));
            if(log.isTraceEnabled())
                log.trace(auth.getAddress() + ": authentication of " + sender + ": " + result + " (hash=" + entry.hash + ")");
            return result;
        }
        catch(InterruptedException e) {
            return false;
        }
    }

    public void writeTo(DataOutput out) throws Exception {}
    public void readFrom(DataInput in) throws Exception {}
    public int  size() {return 0;}

    public boolean handleUpMessage(Message msg) {
        DemoHeader hdr=msg.getHeader(ID);
        if(hdr == null)
            return true;
        switch(hdr.type) {
            case DemoHeader.CHALLENGE:
                if(log.isTraceEnabled())
                    log.trace(auth.getAddress() + ": received CHALLENGE from " + msg.getSrc());
                long hash=hash(encrypt(hdr.payload));
                Message response=new Message(msg.getSrc()).setFlag(Message.Flag.OOB);
                response.putHeader(ID, new DemoHeader(hash));
                if(log.isTraceEnabled())
                    log.trace(auth.getAddress() + ": sending RESPONSE to " + msg.getSrc());
                auth.getDownProtocol().down(response);
                break;
            case DemoHeader.RESPONSE:
                if(log.isTraceEnabled())
                    log.trace(auth.getAddress() + ": received RESPONSE from " + msg.getSrc());
                Entry entry=pending_requests.get(msg.getSrc());
                if(entry == null) {
                    // error message
                    break;
                }
                entry.setResponse(hdr.hash);
                break;
        }
        return false; // don't pass up
    }

    protected static byte[] generateRandomBytes() {
        byte[] retval=new byte[10]; // here we'd have to generate a buffer with random contents
        for(int i=0; i < retval.length; i++)
            retval[i]=(byte)Util.random(Byte.MAX_VALUE);
        return retval;
    }

    protected static byte[] encrypt(byte[] buf) {
        return  buf; // here real encryption would have to be provided...
    }

    // A real hash would have to be provided here...
    protected static long hash(byte[] buf) {
        long retval=0;
        for(int i=0; i < buf.length; i++)
            retval+=buf[i];
        return retval;
    }

    protected static class Entry {
        protected final CountDownLatch latch=new CountDownLatch(1);
        protected final byte[]         challenge;
        protected long                 hash; // set by response

        public Entry(byte[] challenge) {
            this.challenge=challenge;
        }

        public void setResponse(long hash) {
            this.hash=hash;
            latch.countDown();
        }
    }

    public static class DemoHeader extends Header {
        protected static final byte CHALLENGE = 1;
        protected static final byte RESPONSE  = 2;

        protected byte   type;
        protected byte[] payload;  // CHALLENGE
        protected long   hash;     // RESPONSE

        public DemoHeader() {
        }

        public DemoHeader(byte[] payload) {
            this.type=CHALLENGE;
            this.payload=payload;
        }

        public DemoHeader(long hash) {
            type=RESPONSE;
            this.hash=hash;
        }
        public short getMagicId() {return 1555;}
        public Supplier<? extends Header> create() {
            return DemoHeader::new;
        }

        public void writeTo(DataOutput out) throws Exception {
            out.writeByte(type);
            switch(type) {
                case CHALLENGE:
                    Util.writeByteBuffer(payload, out);
                    break;
                case RESPONSE:
                    out.writeLong(hash);
                    break;
            }
        }

        public void readFrom(DataInput in) throws Exception {
            type=in.readByte();
            switch(type) {
                case CHALLENGE:
                    payload=Util.readByteBuffer(in);
                    break;
                case RESPONSE:
                    hash=in.readLong();
                    break;
            }
        }

        public int size() {
            int retval=Global.BYTE_SIZE; // type
            switch(type) {
                case CHALLENGE:
                    retval+=Util.size(payload);
                    break;
                case RESPONSE:
                    retval+=Global.LONG_SIZE;
                    break;
            }
            return retval;
        }

        public String toString() {
            return type == CHALLENGE? "CHALLENGE" : "RESPONSE" + ", payload=" + (payload != null? payload.length : 0) + " bytes";
        }
    }
}