text:
import { Compiler, makeGloballyAddressable } from '@cardstack/core/src/compiler';
import {
  CardId,
  CardModel,
  CardSchemaModule,
  CompiledCard,
  Format,
  ModuleRef,
  RawCard,
  Unsaved,
} from '@cardstack/core/src/interfaces';
import CardModelImpl from '@cardstack/core/src/card-model';
import { RawCardDeserializer, RawCardSerializer } from '@cardstack/core/src/serializers';
import { cardURL } from '@cardstack/core/src/utils';
import { JS_TYPE } from '@cardstack/core/src/utils/content';
import {
  CardstackError,
  isCardstackError,
  serializableError,
  UnprocessableEntity,
} from '@cardstack/core/src/utils/errors';
import { getOwner, inject } from '@cardstack/di';
import { PoolClient } from 'pg';
import Cursor from 'pg-cursor';
import { BROWSER, NODE } from '../interfaces';
import { Expression, expressionToSql, Param, param, PgPrimitive, upsert } from '../utils/expressions';
import type { types as t } from '@babel/core';
import logger from '@cardstack/logger';
import { service } from '@cardstack/hub/services';

import { transformToCommonJS } from '../utils/transforms';
import flatMap from 'lodash/flatMap';
import { INSECURE_CONTEXT } from './card-service';

const log = logger('hub/search-index');

function assertNever(value: never) {
  throw new Error(`unsupported operation ${value}`);
}
export default class SearchIndex {
  private realmManager = service('realm-manager', { as: 'realmManager' });
  private database = inject('database-manager', { as: 'database' });
  private notifyQueue: { cardURL: string; action: 'save' | 'delete' }[] = [];
  private notifyQueuePromise: Promise<void> = Promise.resolve();

  async indexAllRealms(): Promise<void> {
    log.trace('indexAllRealms: begin');
    await Promise.all(
      this.realmManager.realms.map((realm) => {
        return this.runIndexing(realm.url, async (ops) => {
          let meta = await ops.loadMeta();
          let newMeta = await realm.reindex(ops, meta);
          ops.setMeta(newMeta);
        });
      })
    );
    log.trace('indexAllRealms: end');
  }

  notify(cardURL: string, action: 'save' | 'delete'): void {
    log.trace('notify', cardURL);
    this.notifyQueue.push({ cardURL, action });
    (async () => this.drainNotifyQueue())();
  }

  flushNotifications(): Promise<void> {
    return this.notifyQueuePromise;
  }

  async teardown(): Promise<void> {
    await this.notifyQueuePromise;
  }

  private async drainNotifyQueue(): Promise<void> {
    await this.notifyQueuePromise;

    let queueDrained: () => void;
    this.notifyQueuePromise = new Promise<void>((res) => (queueDrained = res));

    while (this.notifyQueue.length > 0) {
      let { cardURL, action } = this.notifyQueue.shift()!;
      log.trace('drainNotifyQueue', cardURL);
      await this.indexCardFromNotification(cardURL, action);
    }
    queueDrained!();
  }

  private async indexCardFromNotification(cardURL: string, action: 'save' | 'delete') {
    let cardID = this.realmManager.parseCardURL(cardURL);
    log.trace('indexCardFromNotification', cardURL);
    await this.runIndexing(cardID.realm, async (ops) => {
      await ops.reindex(cardID, action);
    });
  }

  async deleteCard(raw: RawCard) {
    let url = cardURL(raw);
    log.trace('deleteCard', url);
    await this.runIndexing(raw.realm, async (ops) => {
      return await ops.delete(url);
    });
  }

  async indexCard(
    raw: RawCard,
    compiled: CompiledCard<Unsaved, ModuleRef>,
    compiler: Compiler<Unsaved>
  ): Promise<CompiledCard> {
    log.trace('indexCard', cardURL(raw));
    return await this.runIndexing(raw.realm, async (ops) => {
      return await ops.internalSave(raw, compiled, compiler);
    });
  }

  async indexData(raw: RawCard, cardModel: CardModel): Promise<CompiledCard> {
    log.trace('indexData', cardURL(raw));
    return await this.runIndexing(raw.realm, async (ops) => {
      return await ops.writeDataToIndex(raw, cardModel);
    });
  }

  private async runIndexing<Out>(realmURL: string, fn: (ops: IndexerRun) => Promise<Out>): Promise<Out> {
    let db = await this.database.getPool();
    try {
      log.trace(`starting to index realm`, realmURL);
      let run = await getOwner(this).instantiate(IndexerRun, db, realmURL);
      let result = await fn(run);
      await run.finalize();
      log.trace(`finished indexing realm`, realmURL);
      return result;
    } finally {
      db.release();
    }
  }
}

// this is the methods that we allow Realms to call
export interface IndexerHandle {
  save(card: RawCard): Promise<void>;
  delete(cardURL: string): Promise<void>;
  beginReplaceAll(): Promise<void>;
  finishReplaceAll(): Promise<void>;
}

class IndexerRun implements IndexerHandle {
  private builder = service('card-builder', { as: 'builder' });
  private fileCache = service('file-cache', { as: 'fileCache' });
  private cardService = service('card-service', { as: 'cardService' });
  private generation?: number;
  private touchCounter = 0;
  private touched = new Map<string, number>();
  private newMeta: PgPrimitive = null;
  private realmManager = service('realm-manager', { as: 'realmManager' });

  constructor(private db: PoolClient, private realmURL: string) {}

  async loadMeta(): Promise<PgPrimitive | undefined> {
    let {
      rows: [result],
    } = await this.db.query(expressionToSql(['select meta from realm_metas where realm=', param(this.realmURL)]));
    if (!result) {
      return;
    }
    return result.meta;
  }

  setMeta(meta: PgPrimitive) {
    this.newMeta = meta;
  }

  private async storeMeta(): Promise<void> {
    log.trace('IndexerRun: Storing meta', this.realmURL);
    await this.db.query(
      expressionToSql(
        upsert('realm_metas', 'realm_metas_pkey', { realm: param(this.realmURL), meta: param(this.newMeta) })
      )
    );
  }

  async finalize() {
    log.trace('IndexerRun: Finalize', this.realmURL);
    await this.possiblyInvalidatedCards(async (cardURL: string, deps: string[], raw: RawCard) => {
      if (!this.isValid(cardURL, deps)) {
        log.trace(`reindexing %s because %s`, cardURL, deps);
        await this.save(raw);
      }
    });
    await this.storeMeta();
  }

  // This doesn't need to recurse because we intend for the `deps` column to
  // contain all deep references, not  just immediate references
  private async possiblyInvalidatedCards(fn: (cardURL: string, deps: string[], raw: RawCard) => Promise<void>) {
    const queryBatchSize = 100;
    let queue = [...this.touched.keys()];
    for (let i = 0; i < queue.length; i += queryBatchSize) {
      let queryRefs = queue.slice(i, i + queryBatchSize);
      await this.iterateThroughRows(
        [
          'select url, deps, raw, (url, deps)::card_dep as c_dep from cards where',
          param(queryRefs),
          '&&',
          'deps',
          'order by c_dep using >^',
        ],
        async (row) => {
          let deserializer = new RawCardDeserializer();
          let { raw } = deserializer.deserialize(row.raw.data, row.raw);
          await fn(row.url, row.deps, raw);
        }
      );
    }
  }

  private isValid(cardURL: string, deps: string[]): boolean {
    let maybeTouchedAt = this.touched.get(cardURL);
    if (maybeTouchedAt == null) {
      // our card hasn't been updated at all, so it definitely needs to be redone
      return false;
    }
    let cardTouchedAt = maybeTouchedAt;
    return deps.every((dep) => {
      let depTouchedAt = this.touched.get(dep);
      depTouchedAt == null || depTouchedAt < cardTouchedAt;
    });
  }

  private async iterateThroughRows(expression: Expression, fn: (row: Record<string, any>) => Promise<void>) {
    const rowBatchSize = 100;
    let { text, values } = expressionToSql(expression);
    let cursor: Cursor = this.db.query(new Cursor(text, values) as any);
    let rows;
    do {
      rows = await readCursor(cursor, rowBatchSize);
      for (let row of rows) {
        await fn(row);
      }
    } while (rows.length > 0);
  }

  async reindex(card: CardId, action: 'save' | 'delete'): Promise<void> {
    switch (action) {
      case 'save': {
        try {
          let rawCard = await this.realmManager.read(card);
          await this.save(rawCard);
        } catch (err: any) {
          log.trace('Read: Error during compile', cardURL(card));
          await this.saveErrorState(card, err, new Set());
        }
        break;
      }
      case 'delete': {
        await this.delete(cardURL(card));
        break;
      }
      default:
        assertNever(action);
    }
  }

  // available to each realm's indexer
  async save(card: RawCard): Promise<void> {
    let compiler = await this.builder.compileCardFromRaw(card);
    try {
      let compiledCard = await compiler.compile();
      await this.internalSave(card, compiledCard, compiler);
    } catch (err: any) {
      log.trace('Save: Error during compile', cardURL(card));
      await this.saveErrorState(card, err, compiler.dependencies);
    }
  }

  // used directly by the hub when mutating cards
  async internalSave(
    rawCard: RawCard,
    compiledCard: CompiledCard<Unsaved, ModuleRef>,
    compiler: Compiler<Unsaved>
  ): Promise<CompiledCard> {
    let url = cardURL(rawCard);
    let definedCard = makeGloballyAddressable(url, compiledCard, (local, type, src, ast) =>
      this.define(cardURL(rawCard), local, type, src, ast)
    );
    let format: Format = 'isolated';

    let schemaModule: CardSchemaModule = await this.fileCache.loadModule(definedCard.schemaModule.global);
    let cardService = await this.cardService.as(INSECURE_CONTEXT);

    let cardModel = new CardModelImpl(
      cardService,
      {
        type: 'loaded',
        url,
        allFields: false,
        makeDataComplete: true,
      },
      {
        format,
        realm: rawCard.realm,
        rawData: rawCard.data ?? {},
        schemaModuleRef: definedCard.schemaModule.global,
        schemaModule,
        componentModuleRef: definedCard.componentInfos[format].componentModule.global,
        saveModel: cardService.saveModel.bind(cardService),
      }
    );
    return await this.writeToIndex(rawCard, definedCard, compiler, cardModel);
  }

  private define(cardURL: string, localPath: string, type: string, source: string, ast: t.File | undefined): string {
    log.trace('Defining module:', cardURL, localPath);
    switch (type) {
      case JS_TYPE:
        this.fileCache.setModule(BROWSER, cardURL, localPath, source);
        return this.fileCache.setModule(NODE, cardURL, localPath, transformToCommonJS(localPath, source, ast));
      default:
        return this.fileCache.writeAsset(cardURL, localPath, source);
    }
  }

  private async writeToIndex(
    rawCard: RawCard,
    compiledCard: CompiledCard,
    compiler: Compiler<Unsaved>,
    cardModel: CardModel
  ): Promise<CompiledCard> {
    let url = cardURL(rawCard);
    let searchData = await this.getSearchData(rawCard, compiledCard, cardModel, compiler.dependencies);
    if (searchData === undefined) {
      // the error state has been written out already
      return compiledCard;
    }
    log.trace('Writing card to index', url);
    let expression = upsert('cards', 'cards_pkey', {
      url: param(url),
      realm: param(this.realmURL),
      generation: param(this.generation || null),
      ancestors: param(ancestorsOf(compiledCard)),
      data: param(rawCard.data ?? null),
      raw: param(new RawCardSerializer().serialize(rawCard)),
      compiled: param(new RawCardSerializer().serialize(rawCard, compiledCard)),
      searchData: param(searchData),
      compileErrors: param(null),
      deps: param([...compiler.dependencies]),
      schemaModule: param(compiledCard.schemaModule.global),
      componentInfos: param(compiledCard.componentInfos as Record<Format, any>),
    });

    await this.db.query(expressionToSql(expression));
    this.touched.set(url, this.touchCounter++);
    return compiledCard;
  }

  // used directly by the hub when mutating card data only
  async writeDataToIndex(rawCard: RawCard, cardModel: CardModel): Promise<CompiledCard> {
    let url = cardURL(rawCard);
    log.trace('Writing card to index', url);
    let compiled;
    let isNew = false;
    let deps: string[] | undefined;
    try {
      compiled = await this.builder.getCompiledCard(url);
    } catch (e: any) {
      if (!rawCard.adoptsFrom || !isCardstackError(e) || e.status !== 404) {
        throw e;
      }
      isNew = true;
      let parentCompiled = await this.builder.getCompiledCard(rawCard.adoptsFrom);
      compiled = wrapCompiledCard(parentCompiled, rawCard, url);
      let {
        rows: [{ deps: result }],
      } = await this.db.query(expressionToSql(['select deps from cards where url =', param(rawCard.adoptsFrom)]));
      deps = [...(result as string[]), rawCard.adoptsFrom];
    }

    let searchData = await this.getSearchData(rawCard, compiled, cardModel, new Set(deps));
    if (searchData === undefined) {
      // the error state has been written out already
      return compiled;
    }

    let expression: Expression;
    if (isNew) {
      if (!deps) {
        throw new Error('This should never happen');
      }
      expression = [
        'INSERT INTO cards (url, realm, generation, ancestors, data, raw, compiled, "searchData", "compileErrors", deps, "schemaModule", "componentInfos") VALUES (',
        ...(flatMap(
          [
            param(url),
            param(this.realmURL),
            param(this.generation || null),
            param(ancestorsOf(compiled)),
            param(rawCard.data ?? null),
            param(new RawCardSerializer().serialize(rawCard)),
            param(new RawCardSerializer().serialize(rawCard, compiled)),
            param(searchData),
            param(null),
            param([deps]),
            param(compiled.schemaModule.global),
            param(compiled.componentInfos as Record<Format, any>),
          ],
          (p, i, all) => (i === all.length - 1 ? [p] : [p, ',']) // add commas in
        ) as (string | Param)[]),
        ')',
      ];
    } else {
      expression = [
        'UPDATE cards SET generation =',
        param(this.generation || null),
        ', data =',
        param(rawCard.data ?? null),
        ', raw =',
        param(new RawCardSerializer().serialize(rawCard)),
        ', "searchData" =',
        param(searchData),
        'WHERE url =',
        param(url),
      ];
    }
    await this.db.query(expressionToSql(expression));

    this.touched.set(url, this.touchCounter++);
    return compiled;
  }

  private async getSearchData(
    rawCard: RawCard,
    compiled: CompiledCard,
    cardModel: CardModel,
    deps: Set<string>
  ): Promise<Record<string, any> | null | undefined> {
    try {
      return rawCard.data ? await searchOptimizedData(rawCard.data, compiled, cardModel) : null;
    } catch (err: any) {
      await this.saveErrorState(rawCard, err, new Set(deps));
    }
    return undefined;
  }

  private async saveErrorState(card: RawCard, err: any, deps: Set<string>): Promise<void> {
    let url = cardURL(card);
    let expression = upsert('cards', 'cards_pkey', {
      url: param(url),
      realm: param(this.realmURL),
      generation: param(this.generation || null),
      ancestors: param(null),
      data: param(card.data ?? null),
      raw: param(new RawCardSerializer().serialize(card)),
      compiled: param(null),
      searchData: param(null),
      compileErrors: param(serializableError(err)),
      schemaModule: param(null),
      componentInfos: param(null),
      deps: param([...deps]),
    });
    this.touched.set(url, this.touchCounter++);
    await this.db.query(expressionToSql(expression));
  }

  async delete(url: string): Promise<void> {
    this.touched.set(url, this.touchCounter++);
    await this.db.query('DELETE FROM cards where url = $1', [url]);
    this.fileCache.deleteCardModules(url);
  }

  async beginReplaceAll(): Promise<void> {
    this.generation = Math.floor(Math.random() * 1000000000);
  }

  async finishReplaceAll(): Promise<void> {
    await this.db.query('DELETE FROM cards where realm = $1 AND (generation != $2 OR generation IS NULL)', [
      this.realmURL,
      this.generation,
    ]);
  }
}

function ancestorsOf(compiledCard: CompiledCard): string[] {
  if (!compiledCard.adoptsFrom) {
    return [];
  }
  return [compiledCard.adoptsFrom.url, ...ancestorsOf(compiledCard.adoptsFrom)];
}

// TODO consider using the compiler to return a function that can be used to
// generate these values for a card
async function searchOptimizedData(
  data: Record<string, any>,
  compiled: CompiledCard,
  cardModel: CardModel
): Promise<Record<string, any>> {
  let result: Record<string, any> = {};

  for (let fieldName of Object.keys(compiled.fields)) {
    let currentCard: CompiledCard | undefined = compiled;
    do {
      let entry = result[currentCard.url];
      if (!entry) {
        entry = result[currentCard.url] = {};
      }
      if (cardModel && currentCard.fields[fieldName].computed) {
        try {
          entry[fieldName] = await cardModel.getField(fieldName);
        } catch (err: any) {
          let newError = new UnprocessableEntity(`Could not load field '${fieldName}' for card ${compiled.url}`);
          newError.additionalErrors = [new CardstackError(err.message)];
          throw newError;
        }
      } else {
        entry[fieldName] = data[fieldName];
      }
      currentCard = currentCard.adoptsFrom;
    } while (currentCard && currentCard.fields[fieldName]);
  }

  return result;
}

function wrapCompiledCard(compiled: CompiledCard, raw: RawCard, url: string): CompiledCard {
  return {
    url,
    realm: raw.realm,
    adoptsFrom: compiled,
    fields: compiled.fields,
    schemaModule: compiled.schemaModule,
    serializerModule: compiled.serializerModule,
    componentInfos: compiled.componentInfos,
    modules: compiled.modules,
    deps: [...compiled.deps, compiled.url],
  };
}

function readCursor(cursor: Cursor, rowCount: number): Promise<Record<string, any>[]> {
  return new Promise((resolve, reject) => {
    cursor.read(rowCount, (err, rows) => {
      if (err) {
        reject(err);
      } else {
        resolve(rows);
      }
    });
  });
}

declare module '@cardstack/hub/services' {
  interface HubServices {
    searchIndex: SearchIndex;
  }
}


text:
package randoop.test;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import randoop.Globals;
import randoop.main.ClassReader;
import randoop.main.GenInputsAbstract;
import randoop.operation.Operation;
import randoop.reflection.OperationExtractor;
import randoop.sequence.ForwardGenerator;
import randoop.util.Timer;

import junit.framework.TestCase;

// DEPRECATED. Will delete after testing other performance tests
// in different machines.
public class ForwardExplorerPerformanceTest extends TestCase {

  private static final int TIME_LIMIT_SECS = 10;
  private static final long EXPECTED_MIN = 18000000 / performanceMultiplier();

  private static long performanceMultiplier() {
    String foo = "make sure that the loop doesn't get optimized away";
    List<String> list = new ArrayList<String>();
    Timer t = new Timer();
    t.startTiming();
    for (int i = 0; i < 10000000; i++) {
      list.add(foo);
      list.remove(0);
    }
    return t.getTimeElapsedMillis();
  }

  @SuppressWarnings("unchecked")
  public static void test1() {

    String resourcename = "java.util.classlist.java1.6.txt";

    InputStream classStream =
        ForwardExplorerPerformanceTest.class.getResourceAsStream(resourcename);

    List<Operation> model =
        OperationExtractor.getOperations(
            ClassReader.getClassesForStream(classStream, resourcename), null);
    System.out.println("done creating model.");
    GenInputsAbstract.dontexecute = true; // FIXME make this an instance field?
    GenInputsAbstract.debug_checks = false;
    ForwardGenerator explorer =
        new ForwardGenerator(
            model, TIME_LIMIT_SECS * 1000, Integer.MAX_VALUE, Integer.MAX_VALUE, null, null, null);
    System.out.println("" + Globals.lineSep + "Will explore for " + TIME_LIMIT_SECS + " seconds.");
    explorer.explore();
    System.out.println(
        ""
            + Globals.lineSep
            + ""
            + Globals.lineSep
            + "Expected "
            + EXPECTED_MIN
            + " sequences, created "
            + explorer.allSequences.size()
            + " sequences.");
    GenInputsAbstract.dontexecute = false;
    GenInputsAbstract.debug_checks = true;
    if (explorer.allSequences.size() < EXPECTED_MIN) {
      StringBuilder b = new StringBuilder();
      b.append("Randoop's explorer created fewer than " + EXPECTED_MIN);
      b.append(" inputs (precisely, " + explorer.allSequences.size() + ") in ");
      b.append(TIME_LIMIT_SECS + " seconds." + Globals.lineSep + "");
      b.append("This failure could have two causes:" + Globals.lineSep + "");
      b.append(" (1) Our guess as to how fast your machine is is wrong." + Globals.lineSep + "");
      b.append(
          " (2) You made a change to Randoop that slows down its performance."
              + Globals.lineSep
              + "");
      b.append("     No tips available here.");
      fail(b.toString());
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

describe Valvat::Checksum::DK do
  %w[DK13585628 DK61126228].each do |valid_vat|
    it "returns true on valid VAT #{valid_vat}" do
      expect(Valvat::Checksum.validate(valid_vat)).to be(true)
    end

    invalid_vat = "#{valid_vat[0..-3]}#{valid_vat[-1]}#{valid_vat[-2]}"

    it "returns false on invalid VAT #{invalid_vat}" do
      expect(Valvat::Checksum.validate(invalid_vat)).to be(false)
    end
  end
end


text:
    A loosely based Material UI module

    mui-progresscircle.lua : This is for creating progress circles. Percentage based (0..100%)

    The MIT License (MIT)

    Copyright (C) 2016 Anedix Technologies, Inc.  All Rights Reserved.

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

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

    For other software and binaries included in this module see their licenses.
    The license and the software must remain in full when copying or distributing.

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

--]]--

-- mui
local muiData = require( "materialui.mui-data" )

local mathFloor = math.floor
local mathMod = math.fmod
local mathABS = math.abs

local M = muiData.M -- {} -- for module array/table

--
-- createProgressCircle
--
--[[
  params:
    name = <name of widget>
    radius = mui.getScaleVal(200),
    x = display.contentCenterX,
    y = display.contentCenterY,
    foregroundColor = { 0, 0.78, 1, 1 },
    backgroundColor = { 0.82, 0.95, 0.98, 0.8 },
    startPercent = 20,
    fillType = "outward", -- "outward" or "inward"
    iterations = 1,
    labelText = "20%",
    labelFont = native.systemFont,
    labelFontSize = mui.getScaleVal(24),
    labelColor = {  0.4, 0.4, 0.4, 1 },
    labelAlign = "center",
    labelStyle = "basic", -- "basic" or "embossed"
    labelEmbossedHighlight = { R,G,B,A},
    labelEmbossedShadow = { R,G,B,A},
    callBack = mui.postProgressCallBack,
    --repeatCallBack = <your method here>,
    hideBackdropWhenDone = false
--]]--
function M.createProgressCircle(options)
    M.newProgressCircle(options)
end

function M.newProgressCircle(options)
    if options == nil then return end

    local x,y = 160, 240
    if options.x ~= nil then
        x = options.x
    end
    if options.y ~= nil then
        y = options.y
    end

    if options.foregroundColor == nil then
        options.foregroundColor = { 0, 0, 1, 0, 1 }
    end

    if options.backgroundColor == nil then
        options.backgroundColor = { 0, 0, 1, 0, 0.8 }
    end

    options.backgroundStrokeWidth = options.backgroundStrokeWidth or 5
    options.backgroundStrokeColor = options.backgroundStrokeColor or { 0, 0, 0 }

    if options.iterations == nil then
        options.iterations = 1
    end

    if options.fillType == nil then
        options.fillType = "outward" -- or "inward"
        -- options.iterations = -1
    end

    if options.delay == nil then
        options.delay = 500
    end

    local startPercent = 1
    if options.startPercent == nil then
        options.startPercent = 1
    else
        if options.startPercent < 1 then options.startPercent = 1 end
        if options.startPercent > 100 then options.startPercent = 100 end
    end
    startPercent = options.startPercent
    options.startPercent = options.startPercent / 100

    if options.hideBackdropWhenDone == nil then
        options.hideBackdropWhenDone = false
    end

    options.embossedColor = nil
    if options.labelStyle == "embossed" then
        options.labelEmbossedHighlight = options.labelEmbossedHighlight or { r=1, g=1, b=1 }
        options.labelEmbossedShadow = options.labelEmbossedShadow or { r=0.3, g=0.3, b=0.3 }

        options.embossedColor =
        {
            highlight = options.labelEmbossedHighlight,
            shadow = options.labelEmbossedShadow
        }
    end

    muiData.widgetDict[options.name] = {}

    local objectSize = (options.radius or 100)
    objectSize = objectSize * 2

    muiData.widgetDict[options.name]["mygroup"] = display.newContainer(objectSize, objectSize)
    muiData.widgetDict[options.name]["mygroup"].x = x
    muiData.widgetDict[options.name]["mygroup"].y = y
    muiData.widgetDict[options.name]["touching"] = false

    if options.scrollView ~= nil then
        muiData.widgetDict[options.name]["scrollView"] = options.scrollView
        muiData.widgetDict[options.name]["scrollView"]:insert( muiData.widgetDict[options.name]["mygroup"] )
    end

    if options.parent ~= nil then
        muiData.widgetDict[options.name]["parent"] = options.parent
        muiData.widgetDict[options.name]["parent"]:insert( muiData.widgetDict[options.name]["mygroup"] )
    end

    muiData.widgetDict[options.name]["busy"] = false
    muiData.widgetDict[options.name]["options"] = options
    muiData.widgetDict[options.name]["type"] = "ProgressCircle"
    muiData.widgetDict[options.name]["progressbackdrop"] = display.newCircle( 0, 0, options.radius - options.backgroundStrokeWidth)
    muiData.widgetDict[options.name]["progressbackdrop"]:setFillColor( unpack(options.backgroundColor) )
    muiData.widgetDict[options.name]["progressbackdrop"].strokeWidth = options.backgroundStrokeWidth
    muiData.widgetDict[options.name]["progressbackdrop"]:setStrokeColor( unpack(options.backgroundStrokeColor) )
    muiData.widgetDict[options.name]["progresscircle"] = display.newCircle( 0, 0, options.radius - options.backgroundStrokeWidth)
    muiData.widgetDict[options.name]["progresscircle"]:setFillColor( unpack(options.foregroundColor) )
    muiData.widgetDict[options.name]["progresscircle"].name = options.name
    muiData.widgetDict[options.name]["progresscircle"].percentComplete = 0

    if options.fillType == "outward" then
        transition.from(muiData.widgetDict[options.name]["progresscircle"], {xScale=0.01,yScale=0.01,time=0})
    else
        transition.to(muiData.widgetDict[options.name]["progresscircle"], {xScale=1,yScale=1,time=0})
    end
    muiData.widgetDict[options.name]["fillType"] = options.fillType

    if options.callBack ~= nil then
        muiData.widgetDict[options.name]["progresscircle"].callBack = options.callBack
    end
    if options.onComplete ~= nil then
        muiData.widgetDict[options.name]["progresscircle"].onComplete = options.onComplete
    end
    if options.repeatCallBack ~= nil then
        muiData.widgetDict[options.name]["progresscircle"].repeatCallBack = options.repeatCallBack
    end
    muiData.widgetDict[options.name]["mygroup"]:insert(muiData.widgetDict[options.name]["progressbackdrop"])
    muiData.widgetDict[options.name]["mygroup"]:insert(muiData.widgetDict[options.name]["progresscircle"])

    if options.labelText ~= nil and options.labelFontSize ~= nil then
        if options.labelAlign == nil then
            options.labelAlign = "center"
        end
        local textOptions =
        {
            text = "",
            x = 0,
            y = 0,
            width = options.width,
            font = options.labelFont,
            fontSize = options.labelFontSize,
            align = options.labelAlign,  --new alignment parameter
        }
        if options.embossedColor == nil then
            muiData.widgetDict[options.name]["label"] = display.newText( textOptions )
        else
            muiData.widgetDict[options.name]["label"] = display.newEmbossedText( textOptions )
        end
        muiData.widgetDict[options.name]["label"]:setFillColor( unpack(options.labelColor) )
        if options.embossedColor ~= nil then
            muiData.widgetDict[options.name]["label"]:setEmbossColor( options.embossedColor )
        end
        muiData.widgetDict[options.name]["mygroup"]:insert( muiData.widgetDict[options.name]["label"] )
    end

    muiData.widgetDict[options.name]["progresscircle"].percentComplete = 0
    M.increaseProgressCircle( options.name, startPercent )
end

function M.getProgressCircleProperty(widgetName, propertyName)
    local data = nil

    if widgetName == nil or propertyName == nil then return data end

    if propertyName == "object" then
        data = muiData.widgetDict[widgetName]["mygroup"] -- x,y movement
    elseif propertyName == "label" then
        data = muiData.widgetDict[widgetName]["label"] -- the progress text
    elseif propertyName == "value" then
        data = muiData.widgetDict[widgetName]["progresscircle"].percentComplete
    elseif propertyName == "layer_1" then
        data = muiData.widgetDict[widgetName]["progressbackdrop"] -- backdrop of whole bar
    elseif propertyName == "layer_2" then
        data = muiData.widgetDict[widgetName]["progresscircle"] -- the bar that gets sized horizontally
    end
    return data
end

--
-- expects: widget name and percent to increase the progress bar by.
--
-- example: M.increaseProgressCircle("foo", 20) -- increase progress bar widget named "foo" by 20%
--
-- note: queue any additional increases if already processing one
--
function M.increaseProgressCircle( widgetName, percent, __forceprocess__ )
    if percent < 1 and __forceprocess__ == nil then return end
    if muiData.widgetDict[widgetName] == nil then return end

    local options = muiData.widgetDict[widgetName]["options"]

    if muiData.widgetDict[widgetName]["transition"] ~= nil and options.iterations == -1 then
        return
    end

    if muiData.widgetDict[widgetName]["busy"] == true then
        -- queue the percent increase for later processing
        table.insert(muiData.progresscircleDict, {name=widgetName, value=percent})
        return
    elseif #muiData.progresscircleDict > 0 then
        -- find entry
        local idx = 0
        for i, v in ipairs(muiData.progresscircleDict) do
           if v.name == widgetName then
                idx = i
                percent = v.value
                break
           end
        end
        if idx > 0 then table.remove(muiData.progresscircleDict, idx) end
    end

    muiData.widgetDict[widgetName]["busy"] = true

    muiData.widgetDict[widgetName]["progresscircle"].percentComplete = muiData.widgetDict[widgetName]["progresscircle"].percentComplete + percent

    muiData.widgetDict[options.name]["label"].text = muiData.widgetDict[widgetName]["progresscircle"].percentComplete .. "%"

    local percentComplete = muiData.widgetDict[widgetName]["progresscircle"].percentComplete
    if muiData.widgetDict[widgetName]["progresscircle"].percentComplete > 100 then
        percentComplete = 100
    end
    if options.fillType == "outward" then
        muiData.widgetDict[options.name]["transition"] = transition.to( muiData.widgetDict[options.name]["progresscircle"], {
            time = options.delay,
            xScale = percentComplete / 100,
            yScale = percentComplete / 100,
            transition = easing.linear,
            iterations = options.iterations,
            onComplete = M.completeProgressCircleCallBack,
            onRepeat = M.repeatProgressCircleCallBack,
        } )
    else
        if muiData.widgetDict[widgetName]["progresscircle"].percentComplete > 100 then
            percentComplete = 100
        end
        muiData.widgetDict[options.name]["transition"] = transition.to( muiData.widgetDict[options.name]["progresscircle"], {
            time = options.delay,
            xScale = 1 - (percentComplete / 100),
            yScale = 1 - (percentComplete / 100),
            transition = easing.linear,
            iterations = options.iterations,
            onComplete = M.completeProgressCircleCallBack,
            onRepeat = M.repeatProgressCircleCallBack,
        } )
    end
end

function M.repeatProgressCircleCallBack( object )
    -- M.debug("repeatProgressCircleCallBack")
    if object.callBack ~= nil then
        assert(object.callBack)( object )
    end
end

function M.completeProgressCircleCallBack( object )
    -- M.debug("completeProgressCircleCallBack")
    if object.name == nil then return end
    if muiData.widgetDict[object.name] == nil then return end

    muiData.widgetDict[object.name]["busy"] = false

    if object.noFinishAnimation == nil and object.percentComplete >= 99 and muiData.widgetDict[object.name]["fillType"] == "outward" then
        transition.fadeOut( muiData.widgetDict[object.name]["progresscircle"], {onComplete=M.completeProgressCircleFinalCallBack})
    elseif #muiData.progresscircleDict > 0 then
        M.increaseProgressCircle( object.name, 1, "__forceprocess__")
    else
        M.postProgressCircleCompleteCallBack(object)
    end
    muiData.widgetDict[object.name]["label"].text = object.percentComplete .. "%"
end

function M.postProgressCircleCompleteCallBack( object )
    if object.name ~= nil then
        if muiData.widgetDict[object.name] == nil then return end
        if object.onComplete ~= nil then
            assert(object.onComplete)( object )
        end
    end
end

function M.completeProgressCircleFinalCallBack(object)
    if object.name ~= nil then
        if muiData.widgetDict[object.name] == nil then return end
        muiData.widgetDict[object.name]["progresscircle"].isVisible = false
        if object.callBack ~= nil then
            assert(object.callBack)( object )
        end
    end
end

function M.postProgressCircleCallBack( object )
    M.debug("postProgressCallBack")
end

function M.removeWidgetProgressCircle(widgetName)
    M.removeProgressCircle(widgetName)
end

function M.removeProgressCircle(widgetName)
    if widgetName == nil then
        return
    end

    if muiData.widgetDict[widgetName] == nil then return end

    muiData.widgetDict[widgetName]["progressbackdrop"]:removeSelf()
    muiData.widgetDict[widgetName]["progressbackdrop"] = nil
    muiData.widgetDict[widgetName]["progresscircle"]:removeSelf()
    muiData.widgetDict[widgetName]["progresscircle"] = nil
    if muiData.widgetDict[widgetName]["label"] ~= nil then
        muiData.widgetDict[widgetName]["label"]:removeSelf()
        muiData.widgetDict[widgetName]["label"] = nil
    end
    muiData.widgetDict[widgetName]["mygroup"]:removeSelf()
    muiData.widgetDict[widgetName]["mygroup"] = nil
    muiData.widgetDict[widgetName] = nil
end

return M


text:
/* Generated By:JJTree&JavaCC: Do not edit this line. regExpGrammar2.java */
package regExParsePkg2;

public class regExpGrammar2/*@bgen(jjtree)*/implements regExpGrammar2TreeConstants, regExpGrammar2Constants {/*@bgen(jjtree)*/
  protected JJTregExpGrammar2State jjtree = new JJTregExpGrammar2State();public static void main(String args []) throws ParseException
  {
    regExpGrammar2 parser = new regExpGrammar2(System.in);
        parser.Start();
  }

  final public SimpleNode Start() throws ParseException {
 /*@bgen(jjtree) START */
  SimpleNode jjtn000 = new SimpleNode(JJTSTART);
  boolean jjtc000 = true;
  jjtree.openNodeScope(jjtn000);
    try {
      expr();
      jj_consume_token(0);
    jjtree.closeNodeScope(jjtn000, true);
    jjtc000 = false;
    jjtn000.jjtSetValue("START");
    {if (true) return jjtn000;}
    } catch (Throwable jjte000) {
          if (jjtc000) {
            jjtree.clearNodeScope(jjtn000);
            jjtc000 = false;
          } else {
            jjtree.popNode();
          }
          if (jjte000 instanceof RuntimeException) {
            {if (true) throw (RuntimeException)jjte000;}
          }
          if (jjte000 instanceof ParseException) {
            {if (true) throw (ParseException)jjte000;}
          }
          {if (true) throw (Error)jjte000;}
    } finally {
          if (jjtc000) {
            jjtree.closeNodeScope(jjtn000, true);
          }
    }
    throw new Error("Missing return statement in function");
  }

  final public void expr() throws ParseException {
    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
    case OPENPAR:
    case CONSTANT:
      term();
      label_1:
      while (true) {
        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
        case CHOICE:
        case CONCAT:
          ;
          break;
        default:
          jj_la1[0] = jj_gen;
          break label_1;
        }
        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
        case CONCAT:
          concatExpr();
          break;
        case CHOICE:
          choiceExpr();
          break;
        default:
          jj_la1[1] = jj_gen;
          jj_consume_token(-1);
          throw new ParseException();
        }
      }

      break;
    case NOT:
      negTerm();
      break;
    default:
      jj_la1[2] = jj_gen;
      jj_consume_token(-1);
      throw new ParseException();
    }
  }

  final public void negTerm() throws ParseException {
 /*@bgen(jjtree) #NEGCONCAT( 2) */
  SimpleNode jjtn000 = new SimpleNode(JJTNEGCONCAT);
  boolean jjtc000 = true;
  jjtree.openNodeScope(jjtn000);
    try {
      jj_consume_token(NOT);
    jjtn000.jjtSetValue("NOT");
      term();
      jj_consume_token(CONCAT);
      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
      case OPENPAR:
      case CONSTANT:
        term();
        break;
      case NOT:
        negTerm();
        break;
      default:
        jj_la1[3] = jj_gen;
        jj_consume_token(-1);
        throw new ParseException();
      }
    } catch (Throwable jjte000) {
      if (jjtc000) {
        jjtree.clearNodeScope(jjtn000);
        jjtc000 = false;
      } else {
        jjtree.popNode();
      }
      if (jjte000 instanceof RuntimeException) {
        {if (true) throw (RuntimeException)jjte000;}
      }
      if (jjte000 instanceof ParseException) {
        {if (true) throw (ParseException)jjte000;}
      }
      {if (true) throw (Error)jjte000;}
    } finally {
      if (jjtc000) {
        jjtree.closeNodeScope(jjtn000,  2);
      }
    }
  }

  final public void concatExpr() throws ParseException {
 /*@bgen(jjtree) #CONCAT( 2) */
  SimpleNode jjtn000 = new SimpleNode(JJTCONCAT);
  boolean jjtc000 = true;
  jjtree.openNodeScope(jjtn000);
    try {
      jj_consume_token(CONCAT);
          jjtn000.jjtSetValue("CONCAT");
      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
      case OPENPAR:
      case CONSTANT:
        positiveConcatExpr();
        break;
      case NOT:
        negativeConcatExpr();
        break;
      default:
        jj_la1[4] = jj_gen;
        jj_consume_token(-1);
        throw new ParseException();
      }
    } catch (Throwable jjte000) {
          if (jjtc000) {
            jjtree.clearNodeScope(jjtn000);
            jjtc000 = false;
          } else {
            jjtree.popNode();
          }
          if (jjte000 instanceof RuntimeException) {
            {if (true) throw (RuntimeException)jjte000;}
          }
          if (jjte000 instanceof ParseException) {
            {if (true) throw (ParseException)jjte000;}
          }
          {if (true) throw (Error)jjte000;}
    } finally {
          if (jjtc000) {
            jjtree.closeNodeScope(jjtn000,  2);
          }
    }
  }

  final public void positiveConcatExpr() throws ParseException {
    term();
  }

  final public void negativeConcatExpr() throws ParseException {
 /*@bgen(jjtree) #NEGCONCAT( 2) */
  SimpleNode jjtn000 = new SimpleNode(JJTNEGCONCAT);
  boolean jjtc000 = true;
  jjtree.openNodeScope(jjtn000);
    try {
      jj_consume_token(NOT);
    jjtn000.jjtSetValue("NOT");
      term();
      jj_consume_token(CONCAT);
      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
      case OPENPAR:
      case CONSTANT:
        term();
        break;
      case NOT:
        negativeConcatExpr();
        break;
      default:
        jj_la1[5] = jj_gen;
        jj_consume_token(-1);
        throw new ParseException();
      }
    } catch (Throwable jjte000) {
      if (jjtc000) {
        jjtree.clearNodeScope(jjtn000);
        jjtc000 = false;
      } else {
        jjtree.popNode();
      }
      if (jjte000 instanceof RuntimeException) {
        {if (true) throw (RuntimeException)jjte000;}
      }
      if (jjte000 instanceof ParseException) {
        {if (true) throw (ParseException)jjte000;}
      }
      {if (true) throw (Error)jjte000;}
    } finally {
      if (jjtc000) {
        jjtree.closeNodeScope(jjtn000,  2);
      }
    }
  }

  final public void choiceExpr() throws ParseException {
 /*@bgen(jjtree) #CHOICE( 2) */
  SimpleNode jjtn000 = new SimpleNode(JJTCHOICE);
  boolean jjtc000 = true;
  jjtree.openNodeScope(jjtn000);
    try {
      jj_consume_token(CHOICE);
          jjtn000.jjtSetValue("CHOICE");
      term();
    } catch (Throwable jjte000) {
          if (jjtc000) {
            jjtree.clearNodeScope(jjtn000);
            jjtc000 = false;
          } else {
            jjtree.popNode();
          }
          if (jjte000 instanceof RuntimeException) {
            {if (true) throw (RuntimeException)jjte000;}
          }
          if (jjte000 instanceof ParseException) {
            {if (true) throw (ParseException)jjte000;}
          }
          {if (true) throw (Error)jjte000;}
    } finally {
          if (jjtc000) {
            jjtree.closeNodeScope(jjtn000,  2);
          }
    }
  }

  final public void term() throws ParseException {
    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
    case CONSTANT:
      finalTerm();
      break;
    case OPENPAR:
      nestedExpr();
      break;
    default:
      jj_la1[6] = jj_gen;
      jj_consume_token(-1);
      throw new ParseException();
    }
  }

  final public void finalTerm() throws ParseException {
 /*@bgen(jjtree) TERM */
  SimpleNode jjtn000 = new SimpleNode(JJTTERM);
  boolean jjtc000 = true;
  jjtree.openNodeScope(jjtn000);
    try {
      element();
    jjtn000.jjtSetValue ("UNARY");
      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
      case PLUS:
        jj_consume_token(PLUS);
            jjtn000.jjtSetValue ("PLUS");
        break;
      default:
        jj_la1[7] = jj_gen;
        ;
      }
    } catch (Throwable jjte000) {
    if (jjtc000) {
      jjtree.clearNodeScope(jjtn000);
      jjtc000 = false;
    } else {
      jjtree.popNode();
    }
    if (jjte000 instanceof RuntimeException) {
      {if (true) throw (RuntimeException)jjte000;}
    }
    if (jjte000 instanceof ParseException) {
      {if (true) throw (ParseException)jjte000;}
    }
    {if (true) throw (Error)jjte000;}
    } finally {
    if (jjtc000) {
      jjtree.closeNodeScope(jjtn000, true);
    }
    }
  }

  final public void nestedExpr() throws ParseException {
    jj_consume_token(OPENPAR);
    expr();
    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
    case COLON:
      aliasExpr();
      break;
    default:
      jj_la1[8] = jj_gen;
      ;
    }
    jj_consume_token(CLOSEPAR);
  }

  final public void aliasExpr() throws ParseException {
 /*@bgen(jjtree) #ALIAS( 2) */
  SimpleNode jjtn000 = new SimpleNode(JJTALIAS);
  boolean jjtc000 = true;
  jjtree.openNodeScope(jjtn000);
    try {
     jjtn000.jjtSetValue("ALIAS");
      jj_consume_token(COLON);
      element();
    } catch (Throwable jjte000) {
    if (jjtc000) {
      jjtree.clearNodeScope(jjtn000);
      jjtc000 = false;
    } else {
      jjtree.popNode();
    }
    if (jjte000 instanceof RuntimeException) {
      {if (true) throw (RuntimeException)jjte000;}
    }
    if (jjte000 instanceof ParseException) {
      {if (true) throw (ParseException)jjte000;}
    }
    {if (true) throw (Error)jjte000;}
    } finally {
    if (jjtc000) {
      jjtree.closeNodeScope(jjtn000,  2);
    }
    }
  }

/* void notExpr() #NOT :
{
}
{
  < NOT > { jjtThis.jjtSetValue ("NOT"); }
  term()
} */
  final public void element() throws ParseException {
 /*@bgen(jjtree) ELEMENT */
        SimpleNode jjtn000 = new SimpleNode(JJTELEMENT);
        boolean jjtc000 = true;
        jjtree.openNodeScope(jjtn000);Token t;
    try {
      t = jj_consume_token(CONSTANT);
          jjtree.closeNodeScope(jjtn000, true);
          jjtc000 = false;
                jjtn000.jjtSetValue(t.image);
    } finally {
          if (jjtc000) {
            jjtree.closeNodeScope(jjtn000, true);
          }
    }
  }

  /** Generated Token Manager. */
  public regExpGrammar2TokenManager token_source;
  SimpleCharStream jj_input_stream;
  /** Current token. */
  public Token token;
  /** Next token. */
  public Token jj_nt;
  private int jj_ntk;
  private int jj_gen;
  final private int[] jj_la1 = new int[9];
  static private int[] jj_la1_0;
  static {
      jj_la1_init_0();
   }
   private static void jj_la1_init_0() {
      jj_la1_0 = new int[] {0x280,0x280,0x4c00,0x4c00,0x4c00,0x4c00,0x4800,0x40,0x2000,};
   }

  /** Constructor with InputStream. */
  public regExpGrammar2(java.io.InputStream stream) {
     this(stream, null);
  }
  /** Constructor with InputStream and supplied encoding */
  public regExpGrammar2(java.io.InputStream stream, String encoding) {
    try { jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
    token_source = new regExpGrammar2TokenManager(jj_input_stream);
    token = new Token();
    jj_ntk = -1;
    jj_gen = 0;
    for (int i = 0; i < 9; i++) jj_la1[i] = -1;
  }

  /** Reinitialise. */
  public void ReInit(java.io.InputStream stream) {
     ReInit(stream, null);
  }
  /** Reinitialise. */
  public void ReInit(java.io.InputStream stream, String encoding) {
    try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
    token_source.ReInit(jj_input_stream);
    token = new Token();
    jj_ntk = -1;
    jjtree.reset();
    jj_gen = 0;
    for (int i = 0; i < 9; i++) jj_la1[i] = -1;
  }

  /** Constructor. */
  public regExpGrammar2(java.io.Reader stream) {
    jj_input_stream = new SimpleCharStream(stream, 1, 1);
    token_source = new regExpGrammar2TokenManager(jj_input_stream);
    token = new Token();
    jj_ntk = -1;
    jj_gen = 0;
    for (int i = 0; i < 9; i++) jj_la1[i] = -1;
  }

  /** Reinitialise. */
  public void ReInit(java.io.Reader stream) {
    jj_input_stream.ReInit(stream, 1, 1);
    token_source.ReInit(jj_input_stream);
    token = new Token();
    jj_ntk = -1;
    jjtree.reset();
    jj_gen = 0;
    for (int i = 0; i < 9; i++) jj_la1[i] = -1;
  }

  /** Constructor with generated Token Manager. */
  public regExpGrammar2(regExpGrammar2TokenManager tm) {
    token_source = tm;
    token = new Token();
    jj_ntk = -1;
    jj_gen = 0;
    for (int i = 0; i < 9; i++) jj_la1[i] = -1;
  }

  /** Reinitialise. */
  public void ReInit(regExpGrammar2TokenManager tm) {
    token_source = tm;
    token = new Token();
    jj_ntk = -1;
    jjtree.reset();
    jj_gen = 0;
    for (int i = 0; i < 9; i++) jj_la1[i] = -1;
  }

  private Token jj_consume_token(int kind) throws ParseException {
    Token oldToken;
    if ((oldToken = token).next != null) token = token.next;
    else token = token.next = token_source.getNextToken();
    jj_ntk = -1;
    if (token.kind == kind) {
      jj_gen++;
      return token;
    }
    token = oldToken;
    jj_kind = kind;
    throw generateParseException();
  }

/** Get the next Token. */
  final public Token getNextToken() {
    if (token.next != null) token = token.next;
    else token = token.next = token_source.getNextToken();
    jj_ntk = -1;
    jj_gen++;
    return token;
  }

/** Get the specific Token. */
  final public Token getToken(int index) {
    Token t = token;
    for (int i = 0; i < index; i++) {
      if (t.next != null) t = t.next;
      else t = t.next = token_source.getNextToken();
    }
    return t;
  }

  private int jj_ntk() {
    if ((jj_nt=token.next) == null)
      return (jj_ntk = (token.next=token_source.getNextToken()).kind);
    else
      return (jj_ntk = jj_nt.kind);
  }

  private java.util.List<int[]> jj_expentries = new java.util.ArrayList<int[]>();
  private int[] jj_expentry;
  private int jj_kind = -1;

  /** Generate ParseException. */
  public ParseException generateParseException() {
    jj_expentries.clear();
    boolean[] la1tokens = new boolean[15];
    if (jj_kind >= 0) {
      la1tokens[jj_kind] = true;
      jj_kind = -1;
    }
    for (int i = 0; i < 9; i++) {
      if (jj_la1[i] == jj_gen) {
        for (int j = 0; j < 32; j++) {
          if ((jj_la1_0[i] & (1<<j)) != 0) {
            la1tokens[j] = true;
          }
        }
      }
    }
    for (int i = 0; i < 15; i++) {
      if (la1tokens[i]) {
        jj_expentry = new int[1];
        jj_expentry[0] = i;
        jj_expentries.add(jj_expentry);
      }
    }
    int[][] exptokseq = new int[jj_expentries.size()][];
    for (int i = 0; i < jj_expentries.size(); i++) {
      exptokseq[i] = jj_expentries.get(i);
    }
    return new ParseException(token, exptokseq, tokenImage);
  }

  /** Enable tracing. */
  final public void enable_tracing() {
  }

  /** Disable tracing. */
  final public void disable_tracing() {
  }

}


text:
'''
@author Luke Campbell <LCampbell@ASAScience.com>
@file ingestion_management_service_a.py
@date 06/21/12 17:43
@description DESCRIPTION
'''
from pyon.public import PRED, RT
from pyon.util.arg_check import validate_is_instance, validate_true
from interface.services.dm.iingestion_management_service import BaseIngestionManagementService
from interface.objects import IngestionConfiguration, IngestionQueue, ProcessSchedule, ProcessRestartMode, ProcessQueueingMode
from pyon.core.exception import BadRequest
from pyon.util.log import log
from pyon.util.containers import DotDict
from interface.services.dm.iingestion_worker import IngestionWorkerClient

class IngestionManagementService(BaseIngestionManagementService):

    def create_ingestion_configuration(self,name='', exchange_point_id='', queues=None):
        validate_is_instance(queues,list,'The queues parameter is not a proper list.')
        validate_true(len(queues)>0, 'Ingestion needs at least one queue to ingest from')
        for queue in queues:
            validate_is_instance(queue, IngestionQueue)

        ingestion_config = IngestionConfiguration()

        ingestion_config.name = name
        ingestion_config.exchange_point = exchange_point_id
        ingestion_config.queues = queues

        config_id, rev = self.clients.resource_registry.create(ingestion_config)

        return config_id

    def read_ingestion_configuration(self, ingestion_configuration_id=''):
        return self.clients.resource_registry.read(ingestion_configuration_id)

    def update_ingestion_configuration(self, ingestion_configuration=None):
        return self.clients.resource_registry.update(ingestion_configuration)

    def delete_ingestion_configuration(self, ingestion_configuration_id=''):
        assocs = self.clients.resource_registry.find_associations(subject=ingestion_configuration_id, predicate=PRED.hasSubscription, id_only=False)
        for assoc in assocs:
            self.clients.resource_registry.delete_association(assoc)
            self.clients.pubsub_management.delete_subscription(assoc.o)
        return self.clients.resource_registry.delete(ingestion_configuration_id)

    def list_ingestion_configurations(self, id_only=False):
        resources, _  = self.clients.resource_registry.find_resources(restype=RT.IngestionConfiguration,id_only=id_only)
        return resources

    # ---

    def persist_data_stream(self, stream_id='', ingestion_configuration_id='', dataset_id='', config=None):
        #--------------------------------------------------------------------------------
        # Validate that the method call was indeed valid
        #--------------------------------------------------------------------------------
        config = config or {}
        validate_is_instance(stream_id,basestring, 'stream_id %s is not a valid string' % stream_id)
        validate_true(dataset_id,'Clients must specify the dataset to persist')
        log.info('Persisting stream %s to dataset %s.', stream_id, dataset_id)

        ingestion_config = self.read_ingestion_configuration(ingestion_configuration_id)
        if self.is_persisted(stream_id):
            raise BadRequest('This stream is already being persisted')
        #--------------------------------------------------------------------------------
        # Set up the stream subscriptions and associations for this stream and its ingestion_type
        #--------------------------------------------------------------------------------
        if self.setup_queues(ingestion_config, stream_id, dataset_id, config):
            self.clients.pubsub_management.persist_stream(stream_id)

        return dataset_id

    def setup_queues(self, ingestion_config, stream_id, dataset_id, config):
        #--------------------------------------------------------------------------------
        # Iterate through each queue, check to make sure it's a supported type
        # and it's the queue we're trying to set up
        #--------------------------------------------------------------------------------
        for queue in ingestion_config.queues:
            # Make the subscription from the stream to this queue
            queue_name = queue.name + '_' + dataset_id
            subscription_id = self.clients.pubsub_management.create_subscription(name=queue_name, stream_ids=[stream_id], exchange_name=queue_name)
            self.clients.pubsub_management.activate_subscription(subscription_id=subscription_id)

            # Associate the subscription with the ingestion config which ensures no dangling resources
            self.clients.resource_registry.create_association(
                subject=ingestion_config._id,
                predicate=PRED.hasSubscription,
                object=subscription_id
            )
            self._existing_dataset(stream_id, dataset_id)
            self.launch_worker(queue_name, config)

            return True

        return False

    def launch_worker(self, queue_name, config):
        config = DotDict(config or {})
        config.process.queue_name = queue_name
        config.process.buffer_limit = self.CFG.get_safe('service.ingestion_management.buffer_limit', 10)
        config.process.time_limit = self.CFG.get_safe('service.ingestion_management.time_limit', 10)

        process_definition_id, _  = self.clients.resource_registry.find_resources(restype=RT.ProcessDefinition, name='ingestion_worker_process', id_only=True)
        validate_true(len(process_definition_id), 'No process definition for ingestion workers could be found')
        process_definition_id = process_definition_id[0]

        process_id = self.clients.process_dispatcher.create_process(process_definition_id=process_definition_id)

        xn_ids, _ = self.clients.resource_registry.find_resources(restype=RT.ExchangeName, name=queue_name, id_only=True)
        for xn_id in xn_ids:
            self.clients.resource_registry.create_association(xn_id, PRED.hasIngestionWorker, process_id)

        schedule = ProcessSchedule()
        schedule.restart_mode = ProcessRestartMode.ABNORMAL
        schedule.queueing_mode = ProcessQueueingMode.ALWAYS

        self.clients.process_dispatcher.schedule_process(process_definition_id=process_definition_id,schedule=schedule,process_id=process_id, configuration=config)

    def kill_worker(self, subscription_id):
        for xn_obj in self.clients.resource_registry.find_subjects(object=subscription_id, predicate=PRED.hasSubscription, id_only=False)[0]:
            for process in self.clients.resource_registry.find_objects(subject=xn_obj, predicate=PRED.hasIngestionWorker, id_only=False)[0]:
                if process.process_id.startswith('ingestion_worker'):
                    self.clients.process_dispatcher.cancel_process(process._id)

    def pause_worker(self, subscription_id):
        for client in self.ingestion_worker_rpc(subscription_id):
            client.pause()

    def resume_worker(self, subscription_id):
        for client in self.ingestion_worker_rpc(subscription_id):
            client.resume()

    def ingestion_worker_rpc(self, subscription_id):
        for xn_obj in self.clients.resource_registry.find_subjects(object=subscription_id, predicate=PRED.hasSubscription, id_only=False)[0]:
            for process in self.clients.resource_registry.find_objects(subject=xn_obj, predicate=PRED.hasIngestionWorker, id_only=False)[0]:
                if process.process_id.startswith('ingestion_worker'):
                    rpc_client = IngestionWorkerClient(to_name=process.process_id)
                    yield rpc_client

    def pause_data_stream(self, stream_id='', ingestion_configuration_id=''):
        subscription_ids = self.get_subscriptions(stream_id, ingestion_configuration_id)
        for sub_id in subscription_ids:
            self.pause_worker(sub_id)

    def resume_data_stream(self, stream_id='', ingestion_configuration_id=''):
        subscription_ids = self.get_subscriptions(stream_id, ingestion_configuration_id)
        for sub_id in subscription_ids:
            self.resume_worker(sub_id)

    def get_subscriptions(self, stream_id='', ingestion_configuration_id=''):
        sub_ids, _ = self.clients.resource_registry.find_objects(subject=ingestion_configuration_id, predicate=PRED.hasSubscription, id_only=True)
        sub2_ids, _ = self.clients.resource_registry.find_subjects(object=stream_id, predicate=PRED.hasStream, id_only=True, subject_type=RT.Subscription)
        return [i for i in sub_ids if i in sub2_ids]

    def unpersist_data_stream(self, stream_id='', ingestion_configuration_id=''):

        subscriptions, assocs = self.clients.resource_registry.find_objects(subject=ingestion_configuration_id, predicate=PRED.hasSubscription, id_only=True)

        self.clients.pubsub_management.unpersist_stream(stream_id)

        for i in xrange(len(subscriptions)):
            subscription = subscriptions[i]
            assoc = assocs[i]
            # Check if this subscription is the one with the stream_id

            if len(self.clients.resource_registry.find_associations(subject=subscription, object=stream_id))>0: # this subscription has this stream
                self.kill_worker(subscription)

                self.clients.pubsub_management.deactivate_subscription(subscription_id=subscription)
                self.clients.resource_registry.delete_association(assoc)
                self.clients.pubsub_management.delete_subscription(subscription)

        datasets, _ = self.clients.resource_registry.find_subjects(subject_type=RT.Dataset,predicate=PRED.hasStream,object=stream_id,id_only=True)
        for dataset_id in datasets:
            self.clients.dataset_management.remove_stream(dataset_id, stream_id)

    def is_persisted(self, stream_id=''):
        return self.clients.pubsub_management.is_persisted(stream_id)

    def _determine_queue(self,stream_id='', queues=[]):
        # For now just return the first queue until stream definition is defined
        return queues[0]

    def _existing_dataset(self,stream_id='', dataset_id=''):
        assocs = self.clients.resource_registry.find_associations(subject=dataset_id, predicate=PRED.hasStream)
        if not assocs:
            self.clients.dataset_management.add_stream(dataset_id,stream_id)


text:
package com.example.dynamodb;

// snippet-start:[dynamodb.java2.mapping.querykey.import]
// snippet-end:[dynamodb.java2.mapping.querykey.import]

/*
 *This example is depreciated, see the Scenario example.
 */
public class EnhancedQueryRecordsWithSortKey {

    public static void main(String[] args) {

        System.out.println("This example is depreciated, see the Scenario example");
    }

    // snippet-start:[dynamodb.java2.mapping.querykey.main]
    public static void queryTableSort() {

        System.out.println("This example is depreciated, see the Scenario example");
    }
    // snippet-end:[dynamodb.java2.mapping.querykey.main]
}


text:
package talecraft.invoke;

public interface IScriptInvoke extends IInvoke {
	public String getScriptName();
	public String getScript();
	public void reloadScript();
}


text:
let Toast = {}

Toast.install = function(Vue, options) {
  let opt = {
    // this.$toast()
    defaultType: 'bottom',
    duration: '2500'
  }

  for(let property in options) {
    opt[property] = options[property]
  }

  Vue.prototype.$msg = 'Hello Vue Plugin'

  Vue.prototype.$toast = function(tips, type) {
    if(type) {
      opt.defaultType = type
    }

    if(document.getElementsByClassName('vue-toast').length) {
      // toast 是否存在
      return
    }

    let toastTpl = Vue.extend({
        templates: `<div class="vue-toast toast-${type}">${tips}</div>`
    })
    let tpl = new toastTpl().$mount().$el // 挂载到app挂载处
    document.body.appendChild(tpl)
    setTimeout(function() {
        document.body.removeChild(tpl)
    }, opt.duration)
  }

  ['bottom', 'center', 'top',].forEach(type => {
    Vue.prototype.$toast[type] = function(tips) {
      return Vue.prototype.$toast(tips, type)
    }
  })
}

// window.Toast = Toast

// module.exports = Toast


text:
This module manages Cloud Identity Groups and Memberships using the
[Cloud Identity Group API](https://cloud.google.com/identity/docs/groups).

## Usage

Basic usage of this module is as follows:

```hcl
# Required if using User ADCs (Application Default Credentials) for Cloud Identity API.
provider "google-beta" {
  user_project_override = true
  billing_project       = "<PROJECT_ID>"
}

module "group" {
  source  = "terraform-google-modules/group/google"
  version = "~> 0.1"

  id           = "example-group@example.com"
  display_name = "example-group"
  description  = "Example group"
  domain       = "example.com"
  owners       = ["foo@example.com"]
  managers     = ["example-sa@my-project.iam.gserviceaccount.com"]
  members      = ["another-group@example.com"]
}
```

Functional examples are included in the [examples](./examples/) directory.

<!-- BEGINNING OF PRE-COMMIT-TERRAFORM DOCS HOOK -->
## Inputs

| Name | Description | Type | Default | Required |
|------|-------------|------|---------|:--------:|
| customer\_id | Customer ID of the organization to create the group in. One of domain or customer\_id must be specified | `string` | `""` | no |
| description | Description of the group | `string` | `""` | no |
| display\_name | Display name of the group | `string` | `""` | no |
| domain | Domain of the organization to create the group in. One of domain or customer\_id must be specified | `string` | `""` | no |
| id | ID of the group. For Google-managed entities, the ID must be the email address the group | `any` | n/a | yes |
| initial\_group\_config | The initial configuration options for creating a Group. See the API reference for possible values. Possible values are INITIAL\_GROUP\_CONFIG\_UNSPECIFIED, WITH\_INITIAL\_OWNER, and EMPTY. | `string` | `"EMPTY"` | no |
| managers | Managers of the group. Each entry is the ID of an entity. For Google-managed entities, the ID must be the email address of an existing group, user or service account | `list` | `[]` | no |
| members | Members of the group. Each entry is the ID of an entity. For Google-managed entities, the ID must be the email address of an existing group, user or service account | `list` | `[]` | no |
| owners | Owners of the group. Each entry is the ID of an entity. For Google-managed entities, the ID must be the email address of an existing group, user or service account | `list` | `[]` | no |

## Outputs

| Name | Description |
|------|-------------|
| id | ID of the group. For Google-managed entities, the ID is the email address the group |
| resource\_name | Resource name of the group in the format: groups/{group\_id}, where group\_id is the unique ID assigned to the group. |

<!-- END OF PRE-COMMIT-TERRAFORM DOCS HOOK -->

## Limitations

The provider is still under development, the following are known issues or
limitations:

* Updating a `google_cloud_identity_group_membership` to remove a role fails
    with an error
    ([link](https://github.com/hashicorp/terraform-provider-google/issues/7616)).

* Updating a `google_cloud_identity_group_membership` to change the role of a
    member fails with the following error due to Terraform trying to create the
    new role assignment before/at the same time as the old one is removed.
    Rerunning the same deployment twice might resolve the issue.

    ```bash
    Error: Error creating GroupMembership: googleapi: Error 409: Error(4003): Cannot create membership 'user@example.com' in 'groups/xxx' because it already exists.
    Details:
    [
      {
        "@type": "type.googleapis.com/google.rpc.ResourceInfo",
        "description": "Error(4003): Cannot create membership 'user@example.com' in 'groups/xxx' because it already exists.",
        "owner": "domain:cloudidentity.googleapis.com",
        "resourceType": "cloudidentity.googleapis.com/Membership"
      },
      {
        "@type": "type.googleapis.com/google.rpc.DebugInfo",
        "detail": "[ORIGINAL ERROR] generic::already_exists: Error(4003): Cannot create membership 'user@example.com' in 'groups/xxx' because it already exists.\ncom.google.ccc.hosted.api.oneplatform.cloudidentity.error.exceptions.OpAlreadyExistsException: Error(4003): Cannot create membership 'user@example.com' in 'groups/xxx' because it already exists. [google.rpc.error_details_ext] { message: \"Error(4003): Cannot create membership \\'user@example.com\\' in \\'groups/xxx\\' because it already exists.\" details { [type.googleapis.com/google.rpc.ResourceInfo] { resource_type: \"cloudidentity.googleapis.com/Membership\" owner: \"domain:cloudidentity.googleapis.com\" description: \"Error(4003): Cannot create membership \\'user@example.com\\' in \\'groups/xxx\\' because it already exists.\" } } }"
      }
    ]
    ```

* Only
    [Google Groups](https://cloud.google.com/identity/docs/groups#group_properties)
    are supported.

* Last `OWNER` cannot be removed from a Google Group.

## Requirements

These sections describe requirements for using this module.

### Software

The following dependencies must be available:

* [Terraform][terraform] v0.13
* [Terraform Provider for GCP][terraform-provider-gcp] plugin v2.0

### Permissions

A service account or user account needs the following roles to provision the
resources of this module:

#### Google Cloud IAM roles

* Service Usage Consumer: `roles/serviceusage.serviceUsageConsumer` on the
    billing project
* Organization Viewer: `roles/resourcemanager.organizationViewer` if using
    `domain` instead of `customer_id`

The [Project Factory module][project-factory-module] and the
[IAM module][iam-module] may be used in combination to provision a service
account with the necessary roles applied.

#### Google Workspace (formerly known as G Suite) roles

* [Group Admin role](https://support.google.com/a/answer/2405986?hl=en)

To make the service account a Group Admin, you must have Google Workspace Super
Admin access for your domain. Follow
[Assigning an admin role to the service account](https://cloud.google.com/identity/docs/how-to/setup#assigning_an_admin_role_to_the_service_account)
for instructions.

To create groups as an end user, the caller is required to authenticate as a
member of the domain, i.e. you cannot use this module to create a group under
`bar.com` with a `foo.com` user identity.

After the groups have been created, the organization's Super Admin, Group Admin
or any custom role with Groups privilege can always modify and delete the groups
and their memberships. In addition, the group's OWNER and MANAGER can edit
membership, and OWNER can delete the group. Documentation around the three group
default roles (OWNER, MANAGER and MEMBER) can be found
[here](https://support.google.com/a/answer/167094?hl=en).

### APIs

A project with the following APIs enabled must be used to host the resources of
this module:

* Cloud Identity API: `cloudidentity.googleapis.com`

The [Project Factory module][project-factory-module] can be used to provision a
project with the necessary APIs enabled.

To use the Cloud Identity Groups API, you must have Google Groups for Business
enabled for your domain and allow end users to create groups.

## Contributing

Refer to the [contribution guidelines](./CONTRIBUTING.md) for information on
contributing to this module.

[iam-module]: https://registry.terraform.io/modules/terraform-google-modules/iam/google
[project-factory-module]: https://registry.terraform.io/modules/terraform-google-modules/project-factory/google
[terraform-provider-gcp]: https://www.terraform.io/docs/providers/google/index.html
[terraform]: https://www.terraform.io/downloads.html


text:
<?php

namespace Scrutinizer\Workflow\RabbitMq\Transport;

use JMS\Serializer\Annotation as Serializer;

class StartActivity
{
    /** @Serializer\Type("string") */
    public $executionId;

    /** @Serializer\Type("string") */
    public $taskId;

    /** @Serializer\Type("string") */
    public $machineIdentifier;

    /** @Serializer\Type("string") */
    public $workerIdentifier;
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>待办任务</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta content="width=device-width, initial-scale=1" name="viewport" />
    <meta content="" name="description" />
    <meta content="" name="author" />

    <link href="./assets/global/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
    <link href="./assets/global/plugins/simple-line-icons/simple-line-icons.min.css" rel="stylesheet" type="text/css" />
    <link href="./assets/global/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

    <link href="./assets/global/plugins/bootstrap-toastr/toastr.min.css" rel="stylesheet" type="text/css" />

    <link href="./assets/global/css/components.css" rel="stylesheet" id="style_components" type="text/css" />
    <link href="./assets/global/css/plugins.css" rel="stylesheet" type="text/css" />

    <link href="./assets/layouts/layout2/css/layout.min.css" rel="stylesheet" type="text/css" />
    <link href="./assets/layouts/layout2/css/themes/blue.min.css" rel="stylesheet" type="text/css" id="style_color" />
    <link href="./assets/layouts/layout2/css/custom.css" rel="stylesheet" type="text/css" />

    <link rel="shortcut icon" href="favicon.ico" />
    <link href="./assets/pages/css/index.css" rel="stylesheet" />

                Farecode

                                 管理员

                            运价管理

                                    运价查询

                            产品管理

                                    产品查询

                                    新建产品

                            系统管理

                                    角色管理

                                    数据角色

                                    用户管理

                            审批管理

                                        待办任务

                                        已办任务

                             待办任务

                                            产品编号
                                            <input id="search_code" type="text" placeholder="产品编号" class="form-control">

                                            产品名称
                                            <input id="search_name" type="text" placeholder="产品名称" class="form-control">

                                            产品类型
                                            <select id="search_type" class="form-control">
                                                <option value="">全部</option>
                                                <option value="公布">公布</option>
                                                <option value="销售">销售</option>
                                                <option value="中转">中转</option>
                                                <option value="其他">其他</option>
                                            </select>

                                            营业部
                                            <select id="search_part" class="form-control">
                                                <option value="">全部</option>
                                                <option value="济南">济南</option>
                                                <option value="首尔">首尔</option>
                                                <option value="曼谷">曼谷</option>
                                            </select>

                                                <button id="btn_see" class="btn blue">
                                                    查看详情

                                                </button>

                                                <button id="btn_search" class="btn blue">
                                                    查询

                                                </button>

                                                每页显示 <select name="sample_editable_1_length" aria-controls="sample_editable_1" class="form-control input-sm input-xsmall input-inline"><option value="5">5</option><option value="15">15</option><option value="20">20</option><option value="-1">All</option></select> 记录

                                                 <input type="checkbox" data-id="{{vv.id}}" class="ck_all" />
                                                 序号
                                                 产品编号
                                                 产品名称
                                                 产品类型
                                                 审批环节
                                                 生效日期
                                                 失效日期
                                                 销售范围
                                                 营业部
                                                 创建时间

                Farecode Copyrighs 2015-2016


text:
To list all users in the application, use `ws.allUsers()`.

```js
ws.allUsers().on('success', function(data, response) {
  // data will contain a map of all user objects, indexed by user id; including all public data attached to
  // the user objects.
});
```

If you know the ID of a specific user, use `ws.getUser(id)`.

```js
// Lets say we had a user with id A2938BC9220DAEF03949
ws.getUser('A2938BC9220DAEF03949').on('success', function(data, response) {
  // data['A2938BC9220DAEF03949'] will have the public user object for the given user.
});
```

{{jsEvents 'success.ok' 'error.unauthorized.notfound' 'complete'}}


text:
package edu.american.student.stonewall.display.css.property;

import edu.american.student.stonewall.display.css.framework.CSSProperty;
import edu.american.student.stonewall.display.css.util.BulletType;
import edu.american.student.stonewall.display.css.util.ListStylePosition;
import edu.american.student.stonewall.util.ResourceFinder;

/**
 * The list-style shorthand property sets all the list properties in one
 * declaration.

 *
 * The properties that can be set, are (in order): list-style-type,
 * list-style-position, list-style-image.

 *
 * If one of the values above are missing, e.g. "list-style:circle inside;", the
 * default value for the missing property will be inserted, if any.

 *
 * Default value: disc outside none

 * Inherited: yes

 * Version: CSS1

 * JavaScript syntax: object.style.listStyle="decimal inside"

 *
 * @author ckcook
 *
 */
public class ListStyleProperty extends CSSProperty
{

	/**
	 * The list-style-image property replaces the list-item marker with an
	 * image.

	 *
	 * Note: Always specify the list-style-type property in addition. This
	 * property is used if the image for some reason is unavailable.

	 *
	 * Default value: none

	 * Inherited: yes

	 * Version: CSS1

	 * JavaScript syntax:
	 * object.style.listStyleImage="url('/images/blueball.gif')"

	 *
	 * @param resource
	 *            the image of the list-item marker (bullet)
	 * @return the ListStyleProperty instance
	 */
	public ListStyleProperty setImage(ResourceFinder resource)
	{

		this.clearAttribute("list-style-image");
		this.putAttribute("list-style-image", "url('" + resource.toString() + "')");
		return this;
	}

	/**
	 * The list-style-position property specifies if the list-item markers
	 * should appear inside or outside the content flow.

	 *
	 * Default value: outside

	 * Inherited: yes

	 * Version: CSS1

	 * JavaScript syntax: object.style.listStylePosition="inside"

	 *
	 * @param pos
	 *            The position of the bullet
	 * @return the ListStyleProperty instance
	 */
	public ListStyleProperty setPosition(ListStylePosition pos)
	{

		this.clearAttribute("list-style-position");
		this.putAttribute("list-style-position", pos.toString());
		return this;
	}

	/**
	 * The list-style-type specifies the type of list-item marker in a list.

	 *
	 * Default value: "disc" for ul and "decimal" for ol

	 * Inherited: yes

	 * Version: CSS1

	 * JavaScript syntax: object.style.listStyleType="square"

	 *
	 * @param type
	 *            the bullet type
	 * @return the ListStyleProperty instance
	 */
	public ListStyleProperty setType(BulletType type)
	{

		this.clearAttribute("list-style-type");
		this.putAttribute("list-style-type", type.toString());
		return this;
	}
}


text:
    {{ exercise?.id }}

    <fa-icon *ngIf="exercise && exercise.type" [icon]="getIcon(exercise.type)"></fa-icon>

    {{ exercise?.title }}

    <ng-container class="score" *ngIf="result && result.score != undefined && exercise && exercise.maxPoints; else scoreNotDefined">
        {{ roundScoreSpecifiedByCourseSettings((result.score * exercise.maxPoints) / 100, course) }}
    </ng-container>
    <ng-template #scoreNotDefined>
        {{ 'N/A' }}
    </ng-template>

    {{ exercise?.maxPoints }}

    {{ exercise?.bonusPoints }}

    <ng-container *ngIf="result?.assessor; else noAssessor">
        {{ result.assessor?.name }}
    </ng-container>
    <ng-template #noAssessor></ng-template>

    <ng-template #noComplaint>

    </ng-template>

                <fa-icon [fixedWidth]="true" [icon]="faFolderOpen"></fa-icon>

                <fa-icon [fixedWidth]="true" [icon]="faFolderOpen"></fa-icon>
                {{ 'artemisApp.assessment.dashboard.actions.assess' | artemisTranslate }}

                <fa-icon [fixedWidth]="true" [icon]="faFolderOpen"></fa-icon>
                {{ 'artemisApp.examManagement.assessmentDashboard' | artemisTranslate }}


text:
package org.cache2k.benchmark.prototype;

/**
 * A cached entry holds a key and value.
 *
 * @author Jens Wilke
 */
public class Entry<K, V> {

	private K key;
	private V value;

	public Entry(final K _key, final V _value) {
		key = _key;
		value = _value;
	}

	public K getKey() {
		return key;
	}

	public V getValue() {
		return value;
	}

}


text:
namespace RequestReduce.Api
{
    public interface IFilter
    {
        bool IgnoreTarget(IFilterContext context);
    }
}


text:
package com.zaradai.kunzite.optimizer.data.dataset.driver.memory;

import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import com.zaradai.kunzite.optimizer.data.dataset.DataSetContext;
import com.zaradai.kunzite.optimizer.data.dataset.driver.DataSetDriver;
import com.zaradai.kunzite.optimizer.model.InputRow;
import com.zaradai.kunzite.optimizer.model.Row;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public final class InMemoryDataSetDriver implements DataSetDriver {
    private final Map<InputRow, Row> data;
    private final DataSetContext context;
    private final ReadWriteLock dataLock;

    private InMemoryDataSetDriver(DataSetContext context) {
        this.data = createDataMap();
        this.context = context;
        this.dataLock = createDataLock();
    }

    private ReadWriteLock createDataLock() {
        return new ReentrantReadWriteLock();
    }

    private Map<InputRow, Row> createDataMap() {
        return Maps.newConcurrentMap();
    }

    public static InMemoryDataSetDriver createWithContext(DataSetContext context) {
        Preconditions.checkNotNull(context, "Invalid context");

        return new InMemoryDataSetDriver(context);
    }

    @Override
    public void close() {
        data.clear();
    }

    @Override
    public void add(Row row) {
        Preconditions.checkNotNull(row, "Its invalid to add null rows to a DataSet");
        Preconditions.checkNotNull(row.getInput(), "Its invalid to add rows with invalid input row to a DataSet");
        Preconditions.checkNotNull(row.getOutput(), "Its invalid to add rows with invalid output row to a DataSet");

        dataLock.writeLock().lock();
        try {
            data.put(row.getInput(), row);
        } finally {
            dataLock.writeLock().unlock();
        }
    }

    @Override
    public Row get(InputRow key) {
        Row res = null;

        dataLock.readLock().lock();
        try {
            res = data.get(key);
        } finally {
            dataLock.readLock().unlock();
        }

        return res;
    }

    @Override
    public long getRowCount() {
        dataLock.readLock().lock();
        try {
            return data.size();
        } finally {
            dataLock.readLock().unlock();
        }
    }

    @Override
    public Iterator<Row> iterator() {
        return data.values().iterator();
    }
}


text:
import * as ko from "knockout";
import {QuestionBase} from "../questionbase";

export class QuestionImplementorBase {
    koVisible: any; koErrors: any; koMarginLeft: any; koPaddingRight: any; koRenderWidth: any; koTemplateName: any;
    constructor(public question: QuestionBase) {
        var self = this;
        question.visibilityChangedCallback = function () { self.onVisibilityChanged(); };
        question.renderWidthChangedCallback = function () { self.onRenderWidthChanged(); };
        this.koTemplateName = ko.pureComputed(function () { return self.getTemplateName(); });
        this.koVisible = ko.observable(this.question.isVisible);
        this.koRenderWidth = ko.observable(this.question.renderWidth);
        this.koErrors = ko.observableArray();
        this.koMarginLeft = ko.pureComputed(function () { self.koRenderWidth(); return self.getIndentSize(self.question.indent); });
        this.koPaddingRight = ko.observable(self.getIndentSize(self.question.rightIndent));
        this.question["koTemplateName"] = this.koTemplateName;
        this.question["koVisible"] = this.koVisible;
        this.question["koRenderWidth"] = this.koRenderWidth;
        this.question["koErrors"] = this.koErrors;
        this.question["koMarginLeft"] = this.koMarginLeft;
        this.question["koPaddingRight"] = this.koPaddingRight;
        this.question["updateQuestion"] = function () { self.updateQuestion(); }
    }
    protected updateQuestion() {  }
    protected onVisibilityChanged() {
        this.koVisible(this.question.isVisible);
    }
    protected onRenderWidthChanged() {
        this.koRenderWidth(this.question.renderWidth);
        this.koPaddingRight(this.getIndentSize(this.question.rightIndent));
    }
    private getIndentSize(indent: number): string {
        if (indent < 1) return "";
        if (!this.question["data"]) return "";
        var css = this.question["data"]["css"];
        if (!css) return "";
        return indent * css.question.indent + "px";
    }
    private getTemplateName(): string {
        if (this.question.customWidget && !this.question.customWidget.widgetJson.isDefaultRender)
            return "survey-widget-" + this.question.customWidget.name;
        return "survey-question-" + this.question.getType();
    }
}


text:
<?php

namespace socialCocktail;

use Illuminate\Database\Eloquent\Model;

class Publicacion extends Model
{
    protected $table='publicaciones';
    protected $fillable=['contenido','usuario_id'];

    //Devuelve el usuario autor
    public function usuario(){
        return $this->belongsTo('socialCocktail\User');
    }

    //Devuelve todos los comentarios
    public function comentarios(){
        return $this->hasMany('socialCocktail\Comentario');
    }
}


text:
GTFS Analyst
========

A client for displaying data from the AVAILabs GeoGTFS API.

### Demo:
http://gtfs.availabs.org

### Features:
* Display interactive GTFS Maps
* Load and display date dependent Schedule Data
* Fullscreen mobile-friendly map template with responsive Navbar and modal placeholders
* Integration of Bootstrap tables into Leaflet popups
* Responsive sidebar functionality via the [leaflet-sidebar](https://github.com/turbo87/leaflet-sidebar/) plugin


text:
package com.arpnetworking.metrics.impl;

import com.arpnetworking.metrics.Counter;
import com.arpnetworking.metrics.Quantity;
import com.arpnetworking.metrics.Unit;

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

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Implementation of Counter.  This class is thread safe.
 *
 * @author Ville Koskela (vkoskela at groupon dot com)
 */
final class TsdCounter implements Counter, Quantity {
    /**
     * Package private constructor. All TsdCounter instances should
     * be created through the TsdMetrics instance.
     *
     * @param name The name of the counter.
     * @param isOpen Reference to state of containing TsdMetrics
     * instance. This is provided as a separate parameter to avoid creating a
     * cyclical dependency between TsdMetrics and
     * TsdCounter which could cause garbage collection delays.
     */
    /* package private */static TsdCounter newInstance(final String name, final AtomicBoolean isOpen) {
        return new TsdCounter(name, isOpen, DEFAULT_LOGGER);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void increment() {
        increment(1L);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void decrement() {
        increment(-1L);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void increment(final long value) {
        assertIsOpen();
        _value.addAndGet(value);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void decrement(final long value) {
        increment(-1L * value);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String toString() {
        return String.format(
                "TsdCounter{id=%s, Name=%s, Value=%s, IsOpen=%s}",
                Integer.toHexString(System.identityHashCode(this)),
                _name,
                _value,
                _isOpen);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Number getValue() {
        return Long.valueOf(_value.get());
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Unit getUnit() {
        return null;
    }

    private boolean assertIsOpen() {
        final boolean isOpen = _isOpen.get();
        if (!isOpen) {
            // This is in place of an exception
            _logger.warn(String.format("Counter manipulated after metrics instance closed; counter=%s", this));
        }
        return isOpen;
    }

    // NOTE: Package private for testing.
    /* package private */TsdCounter(final String name, final AtomicBoolean isOpen, final Logger logger) {
        _name = name;
        _isOpen = isOpen;
        _logger = logger;
        _value = new AtomicLong(0L);
    }

    private final String _name;
    private final AtomicBoolean _isOpen;
    private final Logger _logger;
    private final AtomicLong _value;

    private static final Logger DEFAULT_LOGGER = LoggerFactory.getLogger(TsdCounter.class);
}


text:
"""
    fabcloudkit

    :copyright: (c) 2013 by Rick Bohrer.
    :license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import

# standard
import os
import posixpath

# pypi
import boto.ec2
from fabric.api import env
import yaml

# package
from fabcloudkit import cfg
from .dotdict import dotdict
from .role import Role

class Context(dotdict):
    _contexts = []

    @classmethod
    def current(cls):
        return cls._contexts[0] if cls._contexts else None

    def __init__(self, file_path=None, is_current=True):
        super(Context,self).__init__()
        self._real_prop('_roles', [])
        self._real_prop('_instances', {})

        if file_path:
            self.load(file_path)
        if is_current:
            self.set_current(True)

    def add_instance(self, inst):
        self._instances[inst.public_dns_name] = inst

    def aws_sync(self):
        conn = boto.ec2.EC2Connection(Context.current().aws_key, Context.current().aws_secret)
        result = conn.get_all_instances()

        self._instances = []
        for reservation in result:
            for instance in reservation.instances:
                if instance.state not in ('terminated', 'shutting-down'):
                    self.add_instance(instance)

    def get_host_in_role(self, role_name):
        for inst in self._instances.itervalues():
            instance_role_name = inst.tags.get(cfg().fck_role, None)
            if instance_role_name == role_name:
                return inst, self.get_role(role_name)
        raise RuntimeError('No instance in role "{0}" is available.'.format(role_name))

    def all_hosts_in_role(self, role_name):
        hosts = []
        for inst in self._instances.itervalues():
            if role_name == inst.tags.get(cfg().fck_role, None):
                hosts.append(inst)
        return hosts, self.get_role(role_name)

    def builds_root(self):
        return posixpath.join(cfg().deploy_root, self.name, cfg().builds_dir)

    def build_path(self, file_or_dir_name):
        return posixpath.join(self.builds_root(), file_or_dir_name)

    def repos_root(self):
        return posixpath.join(cfg().deploy_root, self.name, cfg().repos_dir)

    def repo_path(self, file_or_dir_name):
        return posixpath.join(self.repos_root(), file_or_dir_name)

    def get_key(self, name):
        key = self.get('keys', {}).get(name, None)
        if not key:
            raise RuntimeError('Key "{0}" is not defined.'.format(name))
        return key

    def keys(self):
        return [self.get_key(name) for name in self.get('keys', {}).keys()]

    def load(self, file_path):
        with open(file_path, 'r') as f:
            # note: calling safe_load() disables the "!env" extension tag.
            self._set_dct(yaml.load(f))

        # load roles.
        dir = os.path.dirname(file_path)
        del self._roles[:]
        for file_name in self.get('roles', []):
            self._roles.append(Role(os.path.join(dir, file_name)))

    def get_role(self, name):
        for role in self._roles:
            if role.name == name:
                return role
        raise RuntimeError('No role available named "{0}"'.format(name))

    def roles(self):
        # return a copy of the roles list.
        return list(self._roles)

    def get_repo(self, name):
        repo = self.get('repos', {}).get(name, None)
        if not repo:
            raise RuntimeError('Repo "{0}" is not defined.'.format(name))

        # if no explicit dir or dir is None, extract it from the url.
        if not repo.get('dir', None):
            repo.dir = repo.url.rsplit('/', 1)[1].rsplit('.')[0]

        # if no explicit package_name is given, default to the dir.
        if not repo.get('package_name', None):
            repo.package_name = repo.dir

        return repo

    def repos(self):
        return [self.get_repo(name) for name in self.get('repos', {}).keys()]

    def set_current(self, is_current=True):
        changed = False
        if not is_current and self.current() is self:
            # pop ourselves off the context stack.
            self._contexts.pop(0)
            changed = True
        elif is_current:
            # push ourselves onto the top of the context stack.
            self._contexts.insert(0, self)
            changed = True

        if changed:
            # configure the fabric environment for this context.
            ctx = self.current()
            env.key_filename = ctx.key_filename if ctx else ''
            env.warn_only = True


text:
    <form id='bulk-create-form' class="form-inline">

                insert text here, one key per line, no spaces

            <textarea></textarea>

            <button type='submit' class="btn btn-primary pull-right bulkcreate">
                Bulk create keys
            </button>

    </form>


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE134_Uncontrolled_Format_String__char_environment_vfprintf_84_bad.cpp
Label Definition File: CWE134_Uncontrolled_Format_String.vasinks.label.xml
Template File: sources-vasinks-84_bad.tmpl.cpp
*/
/*
 * @description
 * CWE: 134 Uncontrolled Format String
 * BadSource: environment Read input from an environment variable
 * GoodSource: Copy a fixed string into data
 * Sinks: vfprintf
 *    GoodSink: vfprintf with a format string
 *    BadSink : vfprintf without a format string
 * Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use
 *
 * */
#ifndef OMITBAD

#include <stdarg.h>
#include "std_testcase.h"
#include "CWE134_Uncontrolled_Format_String__char_environment_vfprintf_84.h"

#define ENV_VARIABLE "ADD"

#ifdef _WIN32
#define GETENV getenv
#else
#define GETENV getenv
#endif

namespace CWE134_Uncontrolled_Format_String__char_environment_vfprintf_84
{
CWE134_Uncontrolled_Format_String__char_environment_vfprintf_84_bad::CWE134_Uncontrolled_Format_String__char_environment_vfprintf_84_bad(char * dataCopy)
{
    data = dataCopy;
    {
        /* Append input from an environment variable to data */
        size_t dataLen = strlen(data);
        char * environment = GETENV(ENV_VARIABLE);
        /* If there is data in the environment variable */
        if (environment != NULL)
        {
            /* POTENTIAL FLAW: Read data from an environment variable */
            strncat(data+dataLen, environment, 100-dataLen-1);
        }
    }
}

static void badVaSink(char * data, ...)
{
    {
        va_list args;
        va_start(args, data);
        /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */
        vfprintf(stdout, data, args);
        va_end(args);
    }
}

CWE134_Uncontrolled_Format_String__char_environment_vfprintf_84_bad::~CWE134_Uncontrolled_Format_String__char_environment_vfprintf_84_bad()
{
    badVaSink(data, data);
}
}
#endif /* OMITBAD */