text:
package net.autosauler.ballance.client.gui;

import net.autosauler.ballance.client.Services;

import com.allen_sauer.gwt.log.client.Log;
import com.extjs.gxt.ui.client.GXT;
import com.extjs.gxt.ui.client.Style.Scroll;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.widget.HtmlContainer;
import com.extjs.gxt.ui.client.widget.Window;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.i18n.client.LocaleInfo;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class HelpDialog extends Window {
	/**
	 * Button constant that displays a single OK button.
	 */
	public static final String OK = "ok";

	/**
	 * Button constant that displays a single CLOSE button.
	 */
	public static final String CLOSE = "close";

	/**
	 * The OK button text (defaults to 'OK');
	 */
	public String okText = GXT.MESSAGES.messageBox_ok();

	private final HtmlContainer hc;

	/**
	 * The Close button text (defaults to 'Close').
	 */
	public String closeText = GXT.MESSAGES.messageBox_close();

	private boolean hideOnButtonClick = false;
	private String buttons;

	private final SelectionListener<ButtonEvent> l = new SelectionListener<ButtonEvent>() {
		@Override
		public void componentSelected(ButtonEvent ce) {
			onButtonPressed(ce.getButton());
		}
	};

	public HelpDialog(String title) {
		setButtons(OK);
		setHeading("Help: " + title);
		setSize(500, 400);
		setHideOnButtonClick(true);
		setModal(true);
		setResizable(true);
		setBlinkModal(true);

		hc = new HtmlContainer();
		this.add(hc);
		setScrollMode(Scroll.AUTO);
	}

	/**
	 * Creates the buttons based on button creation constant
	 */
	protected void createButtons() {
		getButtonBar().removeAll();
		setFocusWidget(null);
		if (buttons.indexOf(OK) != -1) {
			Button okBtn = new Button(okText);
			okBtn.setItemId(OK);
			okBtn.addSelectionListener(l);
			setFocusWidget(okBtn);
			addButton(okBtn);
		}

		if (buttons.indexOf(CLOSE) != -1) {
			Button closeBtn = new Button(closeText);
			closeBtn.setItemId(CLOSE);
			closeBtn.addSelectionListener(l);
			addButton(closeBtn);
		}

	}

	public Button getButtonById(String string) {
		return (Button) fbar.getItemByItemId(string);
	}

	/**
	 * Returns the button's.
	 *
	 * @return the buttons the buttons
	 */
	public String getButtons() {
		return buttons;
	}

	/**
	 * Returns true if the dialog will be hidden on any button click.
	 *
	 * @return the hide on button click state
	 */
	public boolean isHideOnButtonClick() {
		return hideOnButtonClick;
	}

	public void loadHelpText(String url) {
		MainPanel.setCommInfo(true);
		try {
			new RequestBuilder(RequestBuilder.GET, url).sendRequest("",
					new RequestCallback() {
						@Override
						public void onError(Request res, Throwable throwable) {
							MainPanel.setCommInfo(false);
							Log.error(throwable.getMessage());
						}

						@Override
						public void onResponseReceived(Request request,
								Response response) {
							MainPanel.setCommInfo(false);
							String text = response.getText();
							setHelpText(text);

						}
					});
		} catch (RequestException e) {
			MainPanel.setCommInfo(false);
			Log.error(e.getMessage());
		}

	}

	public void loadHelpText(String folderurl, String filename) {
		String locale = LocaleInfo.getCurrentLocale().getLocaleName();
		String url = folderurl + "/" + locale + "/" + filename;
		MainPanel.setCommInfo(true);
		try {
			new RequestBuilder(RequestBuilder.GET, url).sendRequest("",
					new RequestCallback() {
						@Override
						public void onError(Request res, Throwable throwable) {
							MainPanel.setCommInfo(false);
							Log.error(throwable.getMessage());
						}

						@Override
						public void onResponseReceived(Request request,
								Response response) {
							MainPanel.setCommInfo(false);
							String text = response.getText();
							setHelpText(text);

						}
					});
		} catch (RequestException e) {
			MainPanel.setCommInfo(false);
			Log.error(e.getMessage());
		}

	}

	public void loadStructureHelp(String structname) {
		String locale = LocaleInfo.getCurrentLocale().getLocaleName();

		MainPanel.setCommInfo(true);
		Services.structure.getHelp(locale, structname,
				new AsyncCallback<String>() {

					@Override
					public void onFailure(Throwable caught) {
						MainPanel.setCommInfo(false);
						new AlertDialog(caught).show();
					}

					@Override
					public void onSuccess(String result) {
						MainPanel.setCommInfo(false);
						setHelpText(result);
					}
				});
	}

	/**
	 * Called after a button in the button bar is selected. If
	 * {@link #setHideOnButtonClick(boolean)} is true, hides the dialog when any
	 * button is pressed.
	 *
	 * @param button
	 *            the button
	 */
	protected void onButtonPressed(Button button) {

		if ((button == getButtonBar().getItemByItemId(CLOSE))
				|| hideOnButtonClick) {
			hide(button);
		} else if (button == getButtonBar().getItemByItemId(OK)) {
			hide(button);
		}
	}

	/**
	 * Sets the buttons to display (defaults to OK). Must be one of:
	 *
	 * <pre>
	 * FileUploadDialog.OK
	 * FileUploadDialog.CANCEL
	 * FileUploadDialog.OKCANCEL
	 * </pre>
	 */
	public void setButtons(String buttons) {
		this.buttons = buttons;
		createButtons();
	}

	public void setHelpText(String htmltext) {
		hc.setHtml(htmltext);
		show();
	}

	/**
	 * True to hide the dialog on any button click.
	 *
	 * @param hideOnButtonClick
	 *            true to hide
	 */
	public void setHideOnButtonClick(boolean hideOnButtonClick) {
		this.hideOnButtonClick = hideOnButtonClick;
	}
}


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

import com.facebook.presto.hive.HiveClientConfig;
import com.facebook.presto.hive.HiveColumnHandle;
import com.facebook.presto.hive.HivePageSourceFactory;
import com.facebook.presto.hive.HivePartitionKey;
import com.facebook.presto.hive.parquet.predicate.ParquetPredicate;
import com.facebook.presto.hive.parquet.reader.ParquetMetadataReader;
import com.facebook.presto.hive.parquet.reader.ParquetReader;
import com.facebook.presto.spi.ConnectorPageSource;
import com.facebook.presto.spi.ConnectorSession;
import com.facebook.presto.spi.PrestoException;
import com.facebook.presto.spi.predicate.TupleDomain;
import com.facebook.presto.spi.type.StandardTypes;
import com.facebook.presto.spi.type.TypeManager;
import com.facebook.presto.spi.type.TypeSignature;
import com.google.common.collect.ImmutableSet;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.joda.time.DateTimeZone;
import parquet.hadoop.metadata.BlockMetaData;
import parquet.hadoop.metadata.FileMetaData;
import parquet.hadoop.metadata.ParquetMetadata;
import parquet.schema.MessageType;

import javax.inject.Inject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;

import static com.facebook.presto.hive.HiveErrorCode.HIVE_CANNOT_OPEN_SPLIT;
import static com.facebook.presto.hive.HiveErrorCode.HIVE_MISSING_DATA;
import static com.facebook.presto.hive.HiveSessionProperties.isParquetOptimizedReaderEnabled;
import static com.facebook.presto.hive.HiveSessionProperties.isParquetPredicatePushdownEnabled;
import static com.facebook.presto.hive.HiveUtil.getDeserializerClassName;
import static com.facebook.presto.hive.parquet.HdfsParquetDataSource.buildHdfsParquetDataSource;
import static com.facebook.presto.hive.parquet.ParquetTypeUtils.getParquetType;
import static com.facebook.presto.hive.parquet.predicate.ParquetPredicateUtils.buildParquetPredicate;
import static com.facebook.presto.hive.parquet.predicate.ParquetPredicateUtils.predicateMatches;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toList;

public class ParquetPageSourceFactory
        implements HivePageSourceFactory
{
    private static final Set<String> PARQUET_SERDE_CLASS_NAMES = ImmutableSet.<String>builder()
            .add("org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe")
            .add("parquet.hive.serde.ParquetHiveSerDe")
            .build();

    private final TypeManager typeManager;
    private final boolean useParquetColumnNames;

    @Inject
    public ParquetPageSourceFactory(TypeManager typeManager, HiveClientConfig config)
    {
        this(typeManager, requireNonNull(config, "hiveClientConfig is null").isUseParquetColumnNames());
    }

    public ParquetPageSourceFactory(TypeManager typeManager, boolean useParquetColumnNames)
    {
        this.typeManager = requireNonNull(typeManager, "typeManager is null");
        this.useParquetColumnNames = useParquetColumnNames;
    }

    @Override
    public Optional<? extends ConnectorPageSource> createPageSource(
            Configuration configuration,
            ConnectorSession session,
            Path path,
            long start,
            long length,
            Properties schema,
            List<HiveColumnHandle> columns,
            List<HivePartitionKey> partitionKeys,
            TupleDomain<HiveColumnHandle> effectivePredicate,
            DateTimeZone hiveStorageTimeZone)
    {
        if (!isParquetOptimizedReaderEnabled(session)) {
            return Optional.empty();
        }

        if (!PARQUET_SERDE_CLASS_NAMES.contains(getDeserializerClassName(schema))) {
            return Optional.empty();
        }

        if (!columnTypeSupported(columns)) {
            return Optional.empty();
        }

        return Optional.of(createParquetPageSource(
                configuration,
                path,
                start,
                length,
                schema,
                columns,
                partitionKeys,
                useParquetColumnNames,
                typeManager,
                isParquetPredicatePushdownEnabled(session),
                effectivePredicate));
    }

    public static ParquetPageSource createParquetPageSource(
            Configuration configuration,
            Path path,
            long start,
            long length,
            Properties schema,
            List<HiveColumnHandle> columns,
            List<HivePartitionKey> partitionKeys,
            boolean useParquetColumnNames,
            TypeManager typeManager,
            boolean predicatePushdownEnabled,
            TupleDomain<HiveColumnHandle> effectivePredicate)
    {
        ParquetDataSource dataSource = buildHdfsParquetDataSource(path, configuration, start, length);
        try {
            ParquetMetadata parquetMetadata = ParquetMetadataReader.readFooter(configuration, path);
            FileMetaData fileMetaData = parquetMetadata.getFileMetaData();
            MessageType fileSchema = fileMetaData.getSchema();

            List<parquet.schema.Type> fields = columns.stream()
                    .filter(column -> !column.isPartitionKey())
                    .map(column -> getParquetType(column, fileSchema, useParquetColumnNames))
                    .filter(Objects::nonNull)
                    .collect(toList());

            MessageType requestedSchema = new MessageType(fileSchema.getName(), fields);

            List<BlockMetaData> blocks = new ArrayList<>();
            for (BlockMetaData block : parquetMetadata.getBlocks()) {
                long firstDataPage = block.getColumns().get(0).getFirstDataPageOffset();
                if (firstDataPage >= start && firstDataPage < start + length) {
                    blocks.add(block);
                }
            }

            if (predicatePushdownEnabled) {
                ParquetPredicate parquetPredicate = buildParquetPredicate(columns, effectivePredicate, fileMetaData.getSchema(), typeManager);
                blocks = blocks.stream()
                        .filter(block -> predicateMatches(parquetPredicate, block, configuration, dataSource, requestedSchema, effectivePredicate))
                        .collect(toList());
            }

            ParquetReader parquetReader = new ParquetReader(
                    fileMetaData.getSchema(),
                    fileMetaData.getKeyValueMetaData(),
                    requestedSchema,
                    blocks,
                    configuration,
                    dataSource);

            return new ParquetPageSource(
                    parquetReader,
                    fileSchema,
                    requestedSchema,
                    path,
                    length,
                    schema,
                    columns,
                    partitionKeys,
                    effectivePredicate,
                    typeManager,
                    useParquetColumnNames);
        }
        catch (Exception e) {
            try {
                dataSource.close();
            }
            catch (IOException ignored) {
            }
            if (e instanceof PrestoException) {
                throw (PrestoException) e;
            }
            String message = format("Error opening Hive split %s (offset=%s, length=%s): %s", path, start, length, e.getMessage());
            if (e.getClass().getSimpleName().equals("BlockMissingException")) {
                throw new PrestoException(HIVE_MISSING_DATA, message, e);
            }
            throw new PrestoException(HIVE_CANNOT_OPEN_SPLIT, message, e);
        }
    }

    // TODO: support complex types
    private static boolean columnTypeSupported(List<HiveColumnHandle> columns)
    {
        List<String> fields = columns.stream()
                .map(HiveColumnHandle::getTypeSignature)
                .map(TypeSignature::getBase)
                .filter(base -> StandardTypes.ARRAY.equals(base) || StandardTypes.MAP.equals(base) || StandardTypes.ROW.equals(base))
                .collect(toList());
        return fields.isEmpty();
    }
}

redpajama_set_name: RedPajamaGithub


text:
/* $Id$ */

package org.apache.fop.fonts;

import java.util.BitSet;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.fop.util.CharUtilities;

/**
 * Provides methods to get font information.
 * Naming:
 * glyph index: original index of the glyph in the non-subset font (!= unicode index)
 * character selector: index into a set of glyphs. For subset CID fonts, this starts at 0. For non-subset
 * fonts, this is the same as the glyph index.
 * Unicode index: The Unicode codepoint of a character.
 * Glyph name: the Adobe glyph name (as found in Glyphs.java)
 */
public class CIDSubset implements CIDSet {

    /**
     * usedGlyphs contains orginal, new glyph index (glyph index -> char selector)
     */
    private Map<Integer, Integer> usedGlyphs = new LinkedHashMap<Integer, Integer>();

    /**
     * usedGlyphsIndex contains new glyph, original index (char selector -> glyph index)
     */
    private Map<Integer, Integer> usedGlyphsIndex = new HashMap<Integer, Integer>();
    private int usedGlyphsCount;

    /**
     * usedCharsIndex contains new glyph, original char (char selector -> Unicode)
     */
    private Map<Integer, Character> usedCharsIndex = new HashMap<Integer, Character>();

    /**
     * A map between the original character and it's GID in the original font.
     */
    private Map<Character, Integer> charToGIDs = new HashMap<Character, Integer>();

    private final MultiByteFont font;

    public CIDSubset(MultiByteFont mbf) {
        font = mbf;
        // The zeroth value is reserved for .notdef
        usedGlyphs.put(0, 0);
        usedGlyphsIndex.put(0, 0);
        usedGlyphsCount++;
    }

    /** {@inheritDoc} */
    public int getOriginalGlyphIndex(int index) {
        Integer glyphIndex = usedGlyphsIndex.get(index);
        if (glyphIndex != null) {
            return glyphIndex;
        } else {
            return -1;
        }
    }

    /** {@inheritDoc} */
    public char getUnicode(int index) {
        Character mapValue = usedCharsIndex.get(index);
        if (mapValue != null) {
            return mapValue;
        } else {
            return CharUtilities.NOT_A_CHARACTER;
        }
    }

    /** {@inheritDoc} */
    public int mapChar(int glyphIndex, char unicode) {
        // Reencode to a new subset font or get the reencoded value
        // IOW, accumulate the accessed characters and build a character map for them
        Integer subsetCharSelector = usedGlyphs.get(glyphIndex);
        if (subsetCharSelector == null) {
            int selector = usedGlyphsCount;
            usedGlyphs.put(glyphIndex, selector);
            usedGlyphsIndex.put(selector, glyphIndex);
            usedCharsIndex.put(selector, unicode);
            charToGIDs.put(unicode, glyphIndex);
            usedGlyphsCount++;
            return selector;
        } else {
            return subsetCharSelector;
        }
    }

    /** {@inheritDoc} */
    public Map<Integer, Integer> getGlyphs() {
        return Collections.unmodifiableMap(this.usedGlyphs);
    }

    /** {@inheritDoc} */
    public char getUnicodeFromGID(int glyphIndex) {
        int selector = usedGlyphs.get(glyphIndex);
        return usedCharsIndex.get(selector);
    }

    /** {@inheritDoc} */
    public int getGIDFromChar(char ch) {
        return charToGIDs.get(ch);
    }

    /** {@inheritDoc} */
    public char[] getChars() {
        char[] charArray = new char[usedGlyphsCount];
        for (int i = 0; i < usedGlyphsCount; i++) {
            charArray[i] = getUnicode(i);
        }
        return charArray;
    }

    /** {@inheritDoc} */
    public int getNumberOfGlyphs() {
        return this.usedGlyphsCount;
    }

    /** {@inheritDoc} */
    public BitSet getGlyphIndices() {
        BitSet bitset = new BitSet();
        for (Integer cid : usedGlyphs.keySet()) {
            bitset.set(cid);
        }
        return bitset;
    }

    /** {@inheritDoc} */
    public int[] getWidths() {
        int[] widths = font.getWidths();
        int[] tmpWidth = new int[getNumberOfGlyphs()];
        for (int i = 0, c = getNumberOfGlyphs(); i < c; i++) {
            int nwx = Math.max(0, getOriginalGlyphIndex(i));
            tmpWidth[i] = widths[nwx];
        }
        return tmpWidth;
    }

}


text:
package com.stumbleupon.async;

/**
 * Exception raised when too many callbacks are chained together.
 * <p>
 * You are not encouraged to catch this exception.  That is why it
 * inherits from {@link StackOverflowError}, because it generally
 * indicates a programming error that would have led to an actual
 * stack overflow had the code been written with sequential code
 * (without callbacks).
 * @since 1.3
 */
public final class CallbackOverflowError extends StackOverflowError {

  public CallbackOverflowError(final String msg) {
    super(msg);
  }

  private static final long serialVersionUID = 1350030042;
}


text:
from flask import Flask, render_template_string
from flask.ext.upcdn import UPCDN

app = Flask(__name__)

app.config['CDN_DOMAIN'] = 'mycdnname.cloudfront.net'
app.config['CDN_DEBUG'] = True
app.config['CDN_HTTPS'] = True

UPCDN(app)

@app.route('/')
def index():
    template_str = """{{ url_for('static', filename="logo.png") }}"""
    return render_template_string(template_str)

if __name__ == '__main__':
    app.run(debug=True)


text:
package org.hl7.fhir.dstu3.model.codesystems;

// Generated on Tue, Dec 6, 2016 09:42-0500 for FHIR v1.8.0

import org.hl7.fhir.exceptions.FHIRException;

public enum ResearchSubjectStatus {

        /**
         * The subject has been identified as a potential participant in the study but has not yet agreed to participate
         */
        CANDIDATE,
        /**
         * The subject has agreed to participate in the study but has not yet begun performing any action within the study
         */
        ENROLLED,
        /**
         * The subject is currently being monitored and/or subject to treatment as part of the study
         */
        ACTIVE,
        /**
         * The subject has temporarily discontinued monitoring/treatment as part of the study
         */
        SUSPENDED,
        /**
         * The subject has permanently ended participation in the study prior to completion of the intended monitoring/treatment
         */
        WITHDRAWN,
        /**
         * All intended monitoring/treatment of the subject has been completed and their engagement with the study is now ended
         */
        COMPLETED,
        /**
         * added to help the parsers
         */
        NULL;
        public static ResearchSubjectStatus fromCode(String codeString) throws FHIRException {
            if (codeString == null || "".equals(codeString))
                return null;
        if ("candidate".equals(codeString))
          return CANDIDATE;
        if ("enrolled".equals(codeString))
          return ENROLLED;
        if ("active".equals(codeString))
          return ACTIVE;
        if ("suspended".equals(codeString))
          return SUSPENDED;
        if ("withdrawn".equals(codeString))
          return WITHDRAWN;
        if ("completed".equals(codeString))
          return COMPLETED;
        throw new FHIRException("Unknown ResearchSubjectStatus code '"+codeString+"'");
        }
        public String toCode() {
          switch (this) {
            case CANDIDATE: return "candidate";
            case ENROLLED: return "enrolled";
            case ACTIVE: return "active";
            case SUSPENDED: return "suspended";
            case WITHDRAWN: return "withdrawn";
            case COMPLETED: return "completed";
            default: return "?";
          }
        }
        public String getSystem() {
          return "http://hl7.org/fhir/research-subject-status";
        }
        public String getDefinition() {
          switch (this) {
            case CANDIDATE: return "The subject has been identified as a potential participant in the study but has not yet agreed to participate";
            case ENROLLED: return "The subject has agreed to participate in the study but has not yet begun performing any action within the study";
            case ACTIVE: return "The subject is currently being monitored and/or subject to treatment as part of the study";
            case SUSPENDED: return "The subject has temporarily discontinued monitoring/treatment as part of the study";
            case WITHDRAWN: return "The subject has permanently ended participation in the study prior to completion of the intended monitoring/treatment";
            case COMPLETED: return "All intended monitoring/treatment of the subject has been completed and their engagement with the study is now ended";
            default: return "?";
          }
        }
        public String getDisplay() {
          switch (this) {
            case CANDIDATE: return "Candidate";
            case ENROLLED: return "Enrolled";
            case ACTIVE: return "Active";
            case SUSPENDED: return "Suspended";
            case WITHDRAWN: return "Withdrawn";
            case COMPLETED: return "Completed";
            default: return "?";
          }
    }

}


text:
package com.craftmend.openaudiomc.generic.commands.subcommands;

import com.craftmend.openaudiomc.OpenAudioMc;
import com.craftmend.openaudiomc.generic.commands.interfaces.GenericExecutor;
import com.craftmend.openaudiomc.generic.commands.interfaces.SubCommand;
import com.craftmend.openaudiomc.generic.commands.objects.Argument;
import com.craftmend.openaudiomc.generic.networking.client.objects.player.ClientConnection;
import com.craftmend.openaudiomc.generic.platform.Platform;

public class ReloadSubCommand extends SubCommand {

    public ReloadSubCommand() {
        super("reload");
        registerArguments(new Argument("", "Reloads the config.yml and connection system"));
    }

    @Override
    public void onExecute(GenericExecutor sender, String[] args) {
        message(sender, Platform.makeColor("RED") + "Reloading OpenAudioMc data (config and account details)...");
        OpenAudioMc.getInstance().getConfiguration().reloadConfig();
        OpenAudioMc.getInstance().getPlusService().getPlusSettings();

        message(sender, Platform.makeColor("RED") + "Shutting down network service and logging out...");
        for (ClientConnection client : OpenAudioMc.getInstance().getNetworkingService().getClients()) {
            client.kick();
        }
        OpenAudioMc.getInstance().getNetworkingService().stop();

        message(sender, Platform.makeColor("RED") + "Re-activating account...");
        OpenAudioMc.getInstance().getNetworkingService().connectIfDown();

        message(sender, Platform.makeColor("GREEN") + "Reloaded system! Welcome back.");
    }
}


text:
<?php
	session_start();

	// Unset Cookies
	if (isset($_SERVER['HTTP_COOKIE'])) {
	    $cookies = explode(';', $_SERVER['HTTP_COOKIE']);
	    foreach($cookies as $cookie) {
	        $parts = explode('=', $cookie);
	        $name = trim($parts[0]);

	        //Delete every cookie except $_COOKIE['listar']
	        if($name !== "listar"){
		        setcookie($name, '', time()-1000);
		        setcookie($name, '', time()-1000, '/');
		    }
	    }
	}

	session_destroy();
	header("Location: admin");
	exit();


text:
import IDW from 'ol-ext/source/IDW';
import {Vector as VectorSource} from 'ol/source';
import {LoadingStrategy} from 'ol/source/Vector';
import colormap from 'colormap';
import {Feature} from 'ol';
import {GeoJSON} from 'ol/format';
import {Geometry} from 'ol/geom';
import {Projection} from 'ol/proj';
import {Subject} from 'rxjs';
import {containsExtent, equals} from 'ol/extent';

export const NORMALIZED_WEIGHT_PROPERTY_NAME = 'hs_normalized_IDW_value';

export interface InterpolatedSourceOptions {
  min?: number;
  max?: number;
  features?: Feature<Geometry>[];
  weight: string;
  loader?(params: any): Promise<Feature[]>;
  colorMap?: ((v: number) => number[]) | string;
  strategy?: LoadingStrategy;
  maxFeaturesInExtent?: number;
  maxFeaturesInCache?: number;
}

export class InterpolatedSource extends IDW {
  featureCache: VectorSource = new VectorSource({});
  cancelUrlRequest: Subject<void> = new Subject();
  colorMapChanged: Subject<void> = new Subject();
  geoJSONFeatures: string[] = [];

  constructor(public options: InterpolatedSourceOptions) {
    super({
      // Source that contains the data
      workers: false,
      source: new VectorSource({
        strategy:
          options.strategy != undefined
            ? options.strategy
            : (extent: number[], resolution) => {
                const extentCache = super
                  .getSource()
                  .loadedExtentsRtree_.getAll()
                  .map((item) => item.extent);
                const toRemove = extentCache.filter(
                  //Delete cached extents which contain this extent because they have their feature counts limited
                  (cachedExt) =>
                    !equals(cachedExt, extent) &&
                    containsExtent(cachedExt, extent)
                );
                for (const extToRemove of toRemove) {
                  super.getSource().removeLoadedExtent(extToRemove);
                }
                return [extent];
              },
        loader: async (extent, resolution, projection, success, failure) => {
          if (options.loader) {
            this.fillFeatures(
              await options.loader({
                extent,
                resolution,
                projection,
                success,
                failure,
              }),
              extent
            );
          }
        },
      }),
      weight: NORMALIZED_WEIGHT_PROPERTY_NAME,
      getColor: getColorMapFromOptions(options),
    });
    if (options.features) {
      this.fillFeatures(options.features);
    }
  }
  /**
   * Get Minimum boundary used in normalization. Values under this minimum are set to it (clamped)
   */
  get min(): number {
    return this.options.min;
  }

  /**
   * Set Minimum boundary used in normalization. Values under this minimum are set to it (clamped)
   */
  set min(value: number) {
    this.options.min = value;
    this.normalizeWeight(this.weight);
    super.changed();
  }

  /**
   * Get Maximum boundary used in normalization. Values over this minimum are set to it (clamped)
   */
  get max(): number {
    return this.options.max;
  }

  /**
   * Set Maximum boundary used in normalization. Values over this minimum are set to it (clamped)
   */
  set max(value: number) {
    this.options.max = value;
    this.normalizeWeight(this.weight);
    super.changed();
  }

  get colorMap() {
    return this.options.colorMap;
  }

  set colorMap(value: ((v: number) => number[]) | string) {
    this.options.colorMap = value;
    super.getColor = getColorMapFromOptions(this.options);
    this.colorMapChanged.next();
    super.changed();
  }

  /**
   * Get the feature attribute used to get the values interpolated
   */
  get weight(): string {
    return this.options.weight;
  }

  /**
   * Set the feature attribute used to get the values interpolated
   */
  set weight(value: string) {
    this.options.weight = value;
    this.normalizeWeight(this.weight);
    super.changed();
  }

  /**
   * Fill Interpolated source features
   * @param features - Parsed Ol features from get request
   * @param extent - Current map extent
   */
  fillFeatures(features: Feature<Geometry>[], extent?: number[]) {
    if (!features) {
      return;
    }
    const featsCached = this.featureCache.getFeatures();
    const cacheLimit = this.options.maxFeaturesInCache;
    if (cacheLimit < featsCached.length + features.length) {
      const cntToRemove = featsCached.length - (cacheLimit - features.length);
      featsCached
        .slice(0, cntToRemove)
        .forEach((f) => this.featureCache.removeFeature(f));
    }
    const countToAdd = cacheLimit ?? Number.MAX_VALUE;
    this.featureCache.addFeatures(features.slice(0, countToAdd));
    this.normalizeWeight(this.options.weight);
    const src = super.getSource();
    if (extent) {
      src.clear();
      const limitInExt = this.options.maxFeaturesInExtent ?? Number.MAX_VALUE;
      src.addFeatures(
        this.featureCache.getFeaturesInExtent(extent).slice(0, limitInExt)
      );
    } else {
      src.addFeatures(features);
    }
  }

  /**
   * Parse features from get request
   * @param collection - Get request response feature collection
   * @param mapProjection - Map projection
   */
  parseFeatures(collection: any, mapProjection: string | Projection): void {
    if (collection?.features?.length > 0) {
      const dataProj = (collection.crs || collection.srs) ?? 'EPSG:4326';
      collection.features = collection.features.filter(
        (f) => !this.geoJSONFeatures.includes(f)
      );
      this.geoJSONFeatures = this.geoJSONFeatures.concat(collection.features);
      collection.features = new GeoJSON().readFeatures(collection, {
        dataProjection: dataProj,
        featureProjection: mapProjection,
      });
      collection.features = collection.features.filter((f) => {
        const value = f.get(this.options.weight);
        if (value && !isNaN(parseInt(value))) {
          return f;
        }
      });
      return collection.features;
    }
  }

  /**
   * Create url for get request including current map extent
   * @param url - external source URL
   * @param extent - Current map extent
   */
  createIDWSourceUrl(url: string, extent: number[]): string {
    if (!url) {
      return;
    } else if (extent) {
      const extentObj = [
        {ref: 'minx', value: extent[0].toFixed(1)},
        {ref: 'miny', value: extent[1].toFixed(1)},
        {ref: 'maxx', value: extent[2].toFixed(1)},
        {ref: 'maxy', value: extent[3].toFixed(1)},
      ];
      const matches = url.match(/{.+?}/g);
      if (matches?.length > 0 && matches?.length <= 4) {
        for (const m of matches) {
          const ix = matches.indexOf(m);
          const key = m.replace(/[{}]/g, '').toLowerCase();
          const coord = extentObj.find((e) => e.ref === key) ?? extentObj[ix];
          url = url.replace(m, coord.value);
        }
      }
    }
    return url;
  }
  /**
   * Normalize weight values to be between 0 and 100
   * //https://www.statology.org/normalize-data-between-0-and-100/
   * @param weight - Weight property name
   */
  normalizeWeight(weight: string): void {
    const features = this.featureCache.getFeatures();
    const weightValues = features.map((f) => parseFloat(f.get(weight)));
    const min = this.options.min ?? Math.min(...weightValues);
    const max = this.options.max ?? Math.max(...weightValues);

    features.forEach((f) => {
      const val = Math.min(Math.max(f.get(weight), min), max); //https://www.webtips.dev/webtips/javascript/how-to-clamp-numbers-in-javascript
      const normalizedWeight = Math.ceil(((val - min) / (max - min)) * 99);
      f.set(NORMALIZED_WEIGHT_PROPERTY_NAME, normalizedWeight, true);
    });
  }
}

/**
 * Gets predefined colorMap array based on name and number of shades.
 * If you want to reverse defined color map add '-reverse' to the map name
 * @param name Predefined color map name [https://github.com/bpostlethwaite/colormap]
 * @param nshades Number of shades [default = 100]
 * @returns Array of colors
 */
function generateColormap(name: string, nshades: number = 100): number[] {
  const reverse = name.includes('-reverse');
  name = reverse ? name.split('-')[0] : name;
  const cmap = colormap({
    colormap: name,
    nshades,
    format: 'rgb',
    alpha: 255,
  }).map((v) => {
    v[3] = 255;
    return v;
  });
  return reverse ? cmap.reverse() : cmap;
}

/**
 * Creates a function to return value from predefined color maps if name of color map is provided
 */
function getColorMap(mapName: string): (v: number) => number | number[] {
  const clrMap = generateColormap(mapName);
  return (v) => {
    const black = [0, 0, 0, 255];
    if (isNaN(v)) {
      return black;
    }
    if (v > 99) {
      v = 99;
    }
    if (v < 0) {
      v = 0;
    }
    v = Math.floor(v);
    return clrMap[v];
  };
}

/**
 * Assingns colorMap function based on colorMap option used.
 * Predefined color maps if name of color map is provided
 * or uses the passed function directly.
 * @param options
 */
function getColorMapFromOptions(
  options: InterpolatedSourceOptions
): (v: number) => number | number[] {
  let getColor;
  if (typeof options.colorMap == 'string') {
    getColor = getColorMap(options.colorMap);
  } else {
    getColor = options.colorMap;
  }
  return getColor;
}

export default InterpolatedSource;


text:
using System;
using System.Web;
using System.Diagnostics;
using System.IO;

namespace ACG.EA.AppCentre.Web.Utils
{

    public sealed class ExceptionHandler: AC_Base
    {

        private ExceptionHandler() { }

        private const string _APPSOURCE = "ACG.EA.AppCentre.Web";
        private const string _LOGFILE = "Utils/ErrorLog.txt";

        public static void LogException(Exception ex, string source)
        {
            try
            {
                if (!EventLog.SourceExists(_APPSOURCE))
                    EventLog.CreateEventSource(_APPSOURCE, "Application");

                EventLog.WriteEntry(_APPSOURCE, "Source: \n" + ex.ToString(), EventLogEntryType.Error);

                // Include enterprise logic for logging exceptions
                // Get the absolute path to the log file
                string logFile;
                logFile = HttpContext.Current.Server.MapPath(_LOGFILE);

                // Open the log file for append and write the log
                if (logFile != string.Empty)
                {
                    using (StreamWriter sw = new StreamWriter(logFile, true))
                    {
                        sw.WriteLine("********** {0} **********", DateTime.Now);
                        if (ex.InnerException != null)
                        {
                            sw.Write("Inner Exception Type: ");
                            sw.WriteLine(ex.InnerException.GetType().ToString());
                            sw.Write("Inner Exception: ");
                            sw.WriteLine(ex.InnerException.Message);
                            sw.Write("Inner Source: ");
                            sw.WriteLine(ex.InnerException.Source);
                            if (ex.InnerException.StackTrace != null)
                            {
                                sw.WriteLine("Inner Stack Trace: ");
                                sw.WriteLine(ex.InnerException.StackTrace);
                            }
                        }
                        sw.Write("Exception Type: ");
                        sw.WriteLine(ex.GetType().ToString());
                        sw.WriteLine("Exception: " + ex.Message);
                        sw.WriteLine("Source: " + source);
                        sw.WriteLine("Stack Trace: ");
                        if (ex.StackTrace != null)
                        {
                            sw.WriteLine(ex.StackTrace);
                            sw.WriteLine();
                        }
                        //sw.Close();
                    }
                }
            }
            catch
            {
            }
        }

        // Notify System Operators about an exception
        public static void NotifySystemOps(Exception exc)
        {
            // Include code for notifying IT system operators
        }

    }

}


text:
/**
 * ArrayIterator provides simple external iteration for flat Arrays.
 */
var ArrayIterator = function(items) {
  this.items = items;
  this.index = 0;
  this._current = null;
}

ArrayIterator.prototype.next = function() {
  this._ensureNext();
  return this._current = this.items[this.index++];
}

ArrayIterator.prototype.hasNext = function() {
  return this.index < this.items.length;
}

ArrayIterator.prototype.peek = function() {
  this._ensureNext();
  return this.items[this.index];
}

ArrayIterator.prototype.current = function() {
  return this._current;
}

ArrayIterator.prototype._ensureNext = function() {
  if (!this.hasNext()) throw 'Iterator.next called but no more items are available.';
}

exports.ArrayIterator = ArrayIterator;


text:
@implementation UAASDeleteLaunchConfigurationResponse

+ (NSString *)XPathPrefix
{
    return @"./AutoScaling:DeleteLaunchConfigurationResponse/AutoScaling:DeleteLaunchConfigurationResult/";
}

@end

#pragma clang diagnostic pop


text:
A small wrapper for integrating lodash to Vuejs
(Inspired by vue-axios plugin by imcvampire)

## How to install:
### CommonJS:
```
npm install --save lodash vue-lodash
```

And in your entry file:
```
import Vue from 'vue'
import lodash from 'lodash'
import VueLodash from 'vue-lodash/dist/vue-lodash.min'

Vue.use(VueLodash, lodash)
```

### Script:
Just add 3 scripts in order: `vue`, `lodash` and `vue-lodash` to your `document`.

## Usage:
This wrapper bind `lodash` to `Vue` or `this` if you're using single file component.

You can `lodash` like this:
```
Vue._.random(20)

this._.random(20)
```


text:
import collections

from dashboard.common import namespaced_stored_object
from dashboard.services import gitiles_service

_REPOSITORIES_KEY = 'repositories'

class NonLinearError(Exception):
  """Raised when trying to find the midpoint of Changes that are not linear."""

class Change(collections.namedtuple('Change',
                                    ('base_commit', 'deps', 'patch'))):
  """A particular set of Deps with or without an additional patch applied.

  For example, a Change might sync to src@9064a40 and catapult@8f26966,
  then apply patch 2423293002.
  """

  def __new__(cls, base_commit, deps=frozenset(), patch=None):
    """Create a Change.

    Args:
      base_commit: A Dep representing the initial commit to sync to. The DEPS
          file at that commit implies the default commits for any dependencies.
      deps: An optional iterable of Deps to override the dependencies implied
          by base_commit.
      patch: An optional Patch to apply to the Change.
    """
    return super(Change, cls).__new__(cls, base_commit, frozenset(deps), patch)

  def __str__(self):
    string = ' '.join(str(dep) for dep in self.all_deps)
    if self.patch:
      string += ' + ' + str(self.patch)
    return string

  @property
  def id_string(self):
    string = ' '.join(dep.id_string for dep in self.all_deps)
    if self.patch:
      string += ' + ' + self.patch.id_string
    return string

  @property
  def all_deps(self):
    return tuple([self.base_commit] + sorted(self.deps))

  @classmethod
  def FromDict(cls, data):
    base_commit = Dep.FromDict(data['base_commit'])

    kwargs = {}
    if 'deps' in data:
      kwargs['deps'] = tuple(Dep.FromDict(dep) for dep in data['deps'])
    if 'patch' in data:
      kwargs['patch'] = Patch.FromDict(data['patch'])

    return cls(base_commit, **kwargs)

  @classmethod
  def Midpoint(cls, change_a, change_b):
    """Return a Change halfway between the two given Changes.

    A NonLinearError is raised if the Changes are not linear. The Changes are
    not linear if any of the following is true:
      * They have different base repositories.
      * They have different patches.
      * Their repositories differ even after expanding DEPS rolls.
    See change_test.py for examples of linear and nonlinear Changes.

    The behavior is undefined if either of the Changes have multiple Deps with
    the same repository.

    Args:
      change_a: The first Change in the range.
      change_b: The last Change in the range.

    Returns:
      A new Change representing the midpoint.
      The commit before the midpoint if the range has an even number of commits.
      None if the range is empty, or the Changes are given in the wrong order.

    Raises:
      NonLinearError: The Changes are not linear.
    """
    if change_a.base_commit.repository != change_b.base_commit.repository:
      raise NonLinearError(
          'Change A has base repo "%s" and Change B has base repo "%s".' %
          (change_a.base_commit.repository, change_b.base_commit.repository))

    if change_a.patch != change_b.patch:
      raise NonLinearError(
          'Change A has patch "%s" and Change B has patch "%s".' %
          (change_a.patch, change_b.patch))

    if change_a == change_b:
      return None

    # Find the midpoint of every pair of Deps, expanding DEPS rolls as we go.
    midpoint_deps = {}

    repositories_a = {dep.repository: dep for dep in change_a.all_deps}
    repositories_b = {dep.repository: dep for dep in change_b.all_deps}

    # Match up all the Deps by repository.
    while frozenset(repositories_a.iterkeys()).intersection(
        frozenset(repositories_b.iterkeys())):
      # Choose an arbitrary pair of Deps with the same repository.
      shared_repositories = set(repositories_a.iterkeys()).intersection(
          set(repositories_b.iterkeys()))
      repository = shared_repositories.pop()
      dep_a = repositories_a.pop(repository)
      dep_b = repositories_b.pop(repository)

      if dep_a == dep_b:
        # The Deps are the same.
        midpoint_deps[repository] = dep_a
        continue

      midpoint_dep = Dep.Midpoint(dep_a, dep_b)
      if midpoint_dep:
        # The Deps are not adjacent.
        midpoint_deps[repository] = midpoint_dep
        continue

      # The Deps are adjacent. Figure out if it's a DEPS roll.
      deps_a = dep_a.Deps()
      deps_b = dep_b.Deps()
      if deps_a == deps_b:
        # Not a DEPS roll. The Changes really are adjacent.
        return None

      # DEPS roll! Expand the roll.
      for dep in deps_a.difference(deps_b):
        if dep.repository in midpoint_deps:
          raise NonLinearError('Tried to take the midpoint across a DEPS roll, '
                               'but the underlying Dep is already overriden in '
                               'both Changes.')
        if dep.repository not in repositories_a:
          repositories_a[dep.repository] = dep
      for dep in deps_b.difference(deps_a):
        if dep.repository in midpoint_deps:
          raise NonLinearError('Tried to take the midpoint across a DEPS roll, '
                               'but the underlying Dep is already overriden in '
                               'both Changes.')
        if dep.repository not in repositories_b:
          repositories_b[dep.repository] = dep
      midpoint_deps[repository] = dep_a

    # Now that the DEPS are expanded, check to see if the repositories differ.
    if repositories_a or repositories_b:
      raise NonLinearError(
          'Repositories differ between Change A and Change B: %s' %
          ', '.join(sorted(repositories_a.keys() + repositories_b.keys())))

    # Create our new Change!
    base_commit = midpoint_deps.pop(change_a.base_commit.repository)
    return cls(base_commit, midpoint_deps.itervalues(), change_a.patch)

class Dep(collections.namedtuple('Dep', ('repository', 'git_hash'))):
  """A git repository pinned to a particular commit."""

  def __str__(self):
    return self.repository + '@' + self.git_hash[:7]

  @property
  def id_string(self):
    return self.repository + '@' + self.git_hash

  @property
  def repository_url(self):
    """The HTTPS URL of the repository as passed to `git clone`."""
    repositories = namespaced_stored_object.Get(_REPOSITORIES_KEY)
    return repositories[self.repository]['repository_url']

  def Deps(self):
    """Return the DEPS of this Dep as a frozenset of Deps."""
    # Download and execute DEPS file.
    deps_file_contents = gitiles_service.FileContents(
        self.repository_url, self.git_hash, 'DEPS')
    deps_data = {'Var': lambda variable: deps_data['vars'][variable]}
    exec deps_file_contents in deps_data  # pylint: disable=exec-used

    # Pull out deps dict, including OS-specific deps.
    deps_dict = deps_data['deps']
    for deps_os in deps_data.get('deps_os', {}).itervalues():
      deps_dict.update(deps_os)

    # Convert deps strings to Dep objects.
    deps = []
    for dep_string in deps_dict.itervalues():
      dep_string_parts = dep_string.split('@')
      if len(dep_string_parts) < 2:
        continue  # Dep is not pinned to any particular revision.
      if len(dep_string_parts) > 2:
        raise NotImplementedError('Unknown DEP format: ' + dep_string)

      repository_url, git_hash = dep_string_parts
      repository = _Repository(repository_url)
      if not repository:
        _AddRepository(repository_url)
        repository = _Repository(repository_url)
      deps.append(Dep(repository, git_hash))

    return frozenset(deps)

  @classmethod
  def FromDict(cls, data):
    """Create a Dep from a dict.

    If the repository is a repository URL, it will be translated to its short
    form name.

    Raises:
      KeyError: The repository name is not in the local datastore,
                or the git hash is not valid.
    """
    repository = data['repository']

    # Translate repository if it's a URL.
    repository_from_url = _Repository(repository)
    if repository_from_url:
      repository = repository_from_url

    dep = cls(repository, data['git_hash'])

    try:
      gitiles_service.CommitInfo(dep.repository_url, dep.git_hash)
    except gitiles_service.NotFoundError as e:
      raise KeyError(e)

    return dep

  @classmethod
  def Midpoint(cls, dep_a, dep_b):
    """Return a Dep halfway between the two given Deps.

    Uses Gitiles to look up the commit range.

    Args:
      dep_a: The first Dep in the range.
      dep_b: The last Dep in the range.

    Returns:
      A new Dep representing the midpoint.
      The commit before the midpoint if the range has an even number of commits.
      None if the range is empty, or the Deps are given in the wrong order.

    Raises:
      ValueError: The Deps are in different repositories.
    """
    if dep_a.repository != dep_b.repository:
      raise ValueError("Can't find the midpoint of Deps in differing "
                       'repositories: "%s" and "%s"' % (dep_a, dep_b))

    commits = gitiles_service.CommitRange(dep_a.repository_url,
                                          dep_a.git_hash, dep_b.git_hash)
    # We don't handle NotFoundErrors because we assume that all Deps either came
    # from this method or were already validated elsewhere.
    if len(commits) <= 1:
      return None
    commits = commits[1:]  # Remove dep_b from the range.

    return cls(dep_a.repository, commits[len(commits) / 2]['commit'])

class Patch(collections.namedtuple('Patch', ('server', 'issue', 'patchset'))):
  """A patch in Rietveld."""
  # TODO: Support Gerrit.
  # https://github.com/catapult-project/catapult/issues/3599

  def __str__(self):
    return self.id_string

  @property
  def id_string(self):
    return '%s/%d/%d' % (self.server, self.issue, self.patchset)

  @classmethod
  def FromDict(cls, data):
    # TODO: Validate to ensure the patch exists on the server.
    return cls(data['server'], data['issue'], data['patchset'])

def _Repository(repository_url):
  repositories = namespaced_stored_object.Get(_REPOSITORIES_KEY)
  for repo_label, repo_info in repositories.iteritems():
    if repository_url == repo_info['repository_url']:
      return repo_label

  return None

def _AddRepository(repository_url):
  repositories = namespaced_stored_object.Get(_REPOSITORIES_KEY)
  repository = repository_url.split('/')[-1]
  if repository.endswith('.git'):
    repository = repository[:-4]

  if repository in repositories:
    raise AssertionError("Attempted to add a repository that's already in the "
                         'Datastore: %s: %s' % (repository, repository_url))

  repositories[repository] = {'repository_url': repository_url}
  namespaced_stored_object.Set(_REPOSITORIES_KEY, repositories)


text:
package org.hawkular.integrated.inventory;

import org.hawkular.inventory.api.Interest;
import org.hawkular.inventory.api.Inventory;
import org.hawkular.inventory.api.PartiallyApplied;
import org.hawkular.inventory.api.model.Environment;
import org.hawkular.inventory.api.model.MetricType;
import org.hawkular.inventory.api.model.MetricUnit;
import org.hawkular.inventory.api.model.ResourceType;
import org.hawkular.inventory.api.model.Tenant;
import org.hawkular.inventory.cdi.ObservableInventoryInitialized;
import rx.Observable;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Observes;

import static org.hawkular.inventory.api.Action.created;

/**
 * @author Lukas Krejci
 * @since 0.0.2
 */
@ApplicationScoped
public class TemporaryHacks {

    public void install(@Observes ObservableInventoryInitialized event) {
        Inventory.Mixin.Observable inventory = event.getInventory();

        Observable<Tenant> tenantCreation = inventory.observable(Interest.in(Tenant.class).being(created()));
        tenantCreation.subscribe(PartiallyApplied.method(this::createTenantMetadata).second(inventory),
                Log.LOGGER::failedToAutoCreateEntities);
        tenantCreation.subscribe(PartiallyApplied.method(this::createTestEnvironment).second(inventory),
                Log.LOGGER::failedToAutoCreateEntities);
    }

    private void createTestEnvironment(Tenant tenant, Inventory inventory) {
        inventory.inspect(tenant).environments().create(Environment.Blueprint.builder().withId("test").build());
        Log.LOGGER.autoCreatedEntity("environment", "test", tenant.getId());
    }

    private void createTenantMetadata(Tenant tenant, Inventory inventory) {
        inventory.inspect(tenant).resourceTypes().create(ResourceType.Blueprint.builder().withId("URL")
                .withVersion("1.0").build());
        Log.LOGGER.autoCreatedEntity("resource type", "URL", tenant.getId());

        inventory.inspect(tenant).metricTypes().create(MetricType.Blueprint.builder().withId("status.code.type")
                .withUnit(MetricUnit.NONE).build());
        Log.LOGGER.autoCreatedEntity("metric type", "status.code.type", tenant.getId());

        inventory.inspect(tenant).metricTypes().create(MetricType.Blueprint.builder().withId("status.duration.type")
                .withUnit(MetricUnit.MILLI_SECOND).build());
        Log.LOGGER.autoCreatedEntity("metric type", "status.duration.type", tenant.getId());
    }

}


text:
{% extends "base.html" %}
{% load tz %}

{% block content %}

            Start a project!

                Projects
                Actions

            {% for project in projects %}

                        {{ project.name }}

               Delete

            {% endfor %}

{% endblock %}


text:
var models = require("../../app/models");
var wmiCrypto = require('../../app/utils/wmi-crypto');

var obj = {};
obj.name = 'Document seeder';

obj.seed = function(callback){
    models.User.findOne().then(function(user){
        models.Schema.findOne().then(function(schema){
            models.Document.create({
                SchemaId: schema.id,
                UserId: user.id,
                meta: {
                    meta: 'Hello'
                },
                data: wmiCrypto.encryptObject({
                    json: "True dat"
                })
            }).then(function(document){
                console.log(obj.name + " completed.");
                callback({
                    name: 'DocumentId',
                    value: document.id
                });
            });
        });
    });
};

module.exports = obj;


text:
layout: post
date: 2017-03-26
title: "Moonlight Style J6314"
category: Moonlight
tags: [Moonlight]
---
### Moonlight Style J6314
Just **$369.99**
###

BRANDS	Moonlight

Buy it: [https://www.readybrides.com/en/moonlight/48098-moonlight-style-j6314.html](https://www.readybrides.com/en/moonlight/48098-moonlight-style-j6314.html)


text:
from __future__ import unicode_literals
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module

for module in getattr(settings, 'CMSPLUGIN_CASCADE_PLUGINS', []):
    try:
        # if a module was specified, load all plugins in module settings
        module_settings = import_module('{0}.settings'.format(module))
        module_plugins = getattr(module_settings, 'CASCADE_PLUGINS', [])
        for p in module_plugins:
            try:
                import_module('{0}.{1}'.format(module, p))
            except ImportError as err:
                raise ImproperlyConfigured("Plugin {0} as specified in {1}.settings.CMSPLUGIN_CASCADE_PLUGINS "
                                           "could not be loaded: {2}".format(p, module, err.message))
    except ImportError:
        try:
            # otherwise try with cms_plugins in the named module
            import_module('{0}.cms_plugins'.format(module))
        except ImportError:
            # otherwise just use the named module as plugin
            import_module('{0}'.format(module))


text:
package com.fionapet.business.service;

import com.fionapet.business.entity.ServiceDetail;
import org.dubbo.x.service.CURDService;
/**
 * 服务明细
* Created by tom on 2016-07-18 11:56:10.
 */
public interface ServiceDetailService extends CURDService<ServiceDetail> {

}


text:
#pragma once
#include <Arduino.h>
#include <time.h>

class SunMoonCalc {
public:
    typedef struct Sun {
        double azimuth;
        double elevation;
        double riseJd; // jd = Julian Day
        double setJd;
        double transitJd;
        time_t rise; // timestamp in UTC
        time_t set;
        time_t transit;
        double transitElevation;
        double distance;
    } Sun;

    typedef struct MoonPhase {
        uint8_t index;
        String name;
    } MoonPhase;

    typedef struct Moon {
        double azimuth;
        double elevation;
        double riseJd; // jd = Julian Day
        double setJd;
        double transitJd;
        time_t rise; // timestamp in UTC
        time_t set;
        time_t transit;
        double age;
        double transitElevation;
        double distance;
        double illumination;
        double axisPositionAngle;
        double brightLimbAngle;
        double paralacticAngle;
        MoonPhase phase;
    } Moon;

    typedef struct Result {
        Sun sun;
        Moon moon;
    } Result;

    SunMoonCalc(time_t timestamp, double lat, double lon);
    SunMoonCalc(int16_t year, uint8_t month, uint8_t day, uint8_t hour, uint8_t minute, uint8_t second, double lat,
                double lon);

    Result calculateSunAndMoonData();

private:
    enum TWILIGHT {
        /**
         * Event ID for calculation of rising and setting times for astronomical
         * twilight. In this case, the calculated time will be the time when the
         * center of the object is at -18 degrees of geometrical elevation below the
         * astronomical horizon. At this time astronomical observations are possible
         * because the sky is dark enough.
         */
         TWILIGHT_ASTRONOMICAL,
        /**
         * Event ID for calculation of rising and setting times for nautical
         * twilight. In this case, the calculated time will be the time when the
         * center of the object is at -12 degrees of geometric elevation below the
         * astronomical horizon.
         */
         TWILIGHT_NAUTICAL,
        /**
         * Event ID for calculation of rising and setting times for civil twilight.
         * In this case, the calculated time will be the time when the center of the
         * object is at -6 degrees of geometric elevation below the astronomical
         * horizon.
         */
         TWILIGHT_CIVIL,
        /**
         * The standard value of 34' for the refraction at the local horizon.
         */
         HORIZON_34arcmin
    };

    typedef struct PositionalData {
        double longitude;
        double latitude;
        double distance;
        double angularRadius;
    } PositionalData;

    double t;
    double jd_UT;
    double TTminusUT;
    double lat; // internal value is in radians!
    double lon; // internal value is in radians!
    double slongitude; // sun longitude
    double sanomaly; // sun anomaly
    double moonAge; // this is calculated as a by-product in getMoonPosition()
    TWILIGHT twilight = HORIZON_34arcmin;

    void setInternalTime(int16_t year, uint8_t month, uint8_t day, uint8_t hour, uint8_t minute, uint8_t second);
    void setUTDate(double jd);
    PositionalData getSunPosition();
    PositionalData getMoonPosition();
    double *doCalc(PositionalData position);
    double normalizeRadians(double r);
    double calculateTwilightAdjustment(PositionalData position) const;
    double obtainAccurateRiseSetTransit(double riseSetJd, int index, int niter, bool sun);
    double *getMoonDiskOrientationAngles(double lst, double sunRA, double sunDec, double moonLon, double moonLat,
                                         double moonRA, double moonDec);
    SunMoonCalc::MoonPhase calculateMoonPhase(double lunarAge) const;
    Result translateToHumanReadable(Result result) const;
    time_t fromJulian(double julianDays) const;
    double toJulian(int16_t year, uint8_t month, uint8_t day, uint8_t hour, uint8_t minute, uint8_t second) const;
};


text:
#ifndef VCOMPONENT_H
#include "vcomponent.h"
#endif

#ifndef ICALVALUE_CXX_H
#include "icalvalue_cxx.h"
#endif

#ifndef ICALPROPERTY_CXX_H
#include "icalproperty_cxx.h"
#endif

#ifndef ICALPARAMETER_CXX_H
#include "icalparameter_cxx.h"
#endif
#include <stdlib.h>
#include <string.h>

#include <exception>

VComponent::VComponent() throw(icalerrorenum) : imp(icalcomponent_new(ICAL_ANY_COMPONENT)) {
}
VComponent::VComponent(const VComponent& v) throw(icalerrorenum) {
  imp = icalcomponent_new_clone(v.imp);
  if (!imp) throw icalerrno;
}

VComponent& VComponent::operator=(const VComponent& v) throw(icalerrorenum) {
	if (this == &v) return *this;

	if (imp != NULL)
	{
		icalcomponent_free(imp);
		imp = icalcomponent_new_clone(v.imp);
	if (!imp) throw icalerrno;
	}

	return *this;
}

VComponent::~VComponent(){
	if (imp)
	   icalcomponent_free(imp);
}

VComponent::VComponent(icalcomponent* v) throw (icalerrorenum) : imp(v){
}

/* char* returned is in the ring buffer. caller doesn't have to free it */
char* VComponent::quote_ical_string(char *str){
    const char* p;
    size_t  buf_sz;
    buf_sz = strlen(str) * 2;	/* assume worse case scenarios. otherwise, we have to parse the string and count \ */
    char* out = (char*)icalmemory_new_buffer(buf_sz);    /* memory is from the ring buffer */
    char* pout;

    if (out == 0){
        return 0;
    }

    pout = out;

    for (p = str; *p!=0; p++){

        if( *p == '\\'){
            *pout++ = '\\';
	}
	*pout++ = *p;

    }
    *pout++ = '\0';

    return out;
}

/**
 * @brief Constructor
 *
 * Create a new VComponent from a string.
 *
 * @exception ICAL_MALFORMEDDATA_ERROR
 *            Catch this error if you
 *
 */
VComponent::VComponent(string str)  throw (icalerrorenum) {
	// Fix for BUG #15647, but breaks fix for BUG #15596.  Attempting a UI fix for cal-4.0.
	//char* quoted_str = quote_ical_string((char *)str);
	//imp = icalcomponent_new_from_string(quoted_str);
	imp = icalcomponent_new_from_string(str);

	if (!imp) throw icalerrno;
}

VComponent::VComponent(icalcomponent_kind kind)  throw(icalerrorenum) {
  imp = icalcomponent_new(kind);

  if (!imp) throw icalerrno;
}

string VComponent::as_ical_string()  throw(icalerrorenum) {
  char *str = icalcomponent_as_ical_string(imp);

  if (!str) throw icalerrno;

  return(str);
}

bool VComponent::is_valid(){
	if (imp == NULL) return false;
	return (icalcomponent_is_valid(imp) ? true : false);
}

icalcomponent_kind VComponent::isa(){
	return icalcomponent_isa(imp);
}

int VComponent::isa_component(void* component){
	return icalcomponent_isa_component(component);
}

void VComponent::new_from_string(string str){
	if (imp != NULL) icalcomponent_free(imp);
	imp = icalcomponent_new_from_string(str);
}

/* Working with properties */
void VComponent::add_property(ICalProperty* property){
	icalcomponent_add_property(imp, *property);
}
void VComponent::remove_property(ICalProperty* property){
	icalcomponent_remove_property(imp, *property);
	icalproperty_free(*property);
        property->detach();		// set imp to null, it's free already.
}
int VComponent::count_properties(icalproperty_kind kind){
	return icalcomponent_count_properties(imp, kind);
}

/* Iterate through the properties */
ICalProperty* VComponent::get_current_property(){
	icalproperty* t = icalcomponent_get_current_property(imp);
	return ((t != NULL) ? new ICalProperty(t) : NULL);
}

ICalProperty* VComponent::get_first_property(icalproperty_kind kind){
	icalproperty* t = icalcomponent_get_first_property(imp, kind);
	return ((t != NULL) ? new ICalProperty(t) : NULL);
}

ICalProperty* VComponent::get_next_property(icalproperty_kind kind){
	icalproperty* t = icalcomponent_get_next_property(imp, kind);
	return ((t != NULL) ? new ICalProperty(t) : NULL);
}

/* Working with components */
/* Return the first VEVENT, VTODO or VJOURNAL sub-component if it is one of those types */
VComponent* VComponent::get_inner(){
	return new VComponent(icalcomponent_get_inner(imp));
}

void VComponent::add_component(VComponent* child){
	icalcomponent_add_component(imp, *child);
}
void VComponent::remove_component(VComponent* child){
	icalcomponent_remove_component(imp, *child);
}
int VComponent::count_components(icalcomponent_kind kind){
	return 	icalcomponent_count_components(imp, kind);
}

/* Iteration Routines. There are two forms of iterators, internal and
   external. The internal ones came first, and are almost completely
   sufficient, but they fail badly when you want to construct a loop that
   removes components from the container.
*/

/* Iterate through components */
VComponent* VComponent::get_current_component(){
	icalcomponent* t = icalcomponent_get_current_component(imp);
	return ((t != NULL) ? new VComponent(t) : NULL);
}
VComponent* VComponent::get_first_component(icalcomponent_kind kind){
	VComponent* result = NULL;
	icalcomponent* t = icalcomponent_get_first_component(imp, kind);
	if (t != NULL) {
		switch (kind) {
			case ICAL_VALARM_COMPONENT:
				result = new VAlarm(t);
				break;
			case ICAL_VCALENDAR_COMPONENT:
				result = new VCalendar(t);
				break;
			case ICAL_VEVENT_COMPONENT:
				result = new VEvent(t);
				break;
			case ICAL_VQUERY_COMPONENT:
				result = new VQuery(t);
				break;
			case ICAL_VTODO_COMPONENT:
				result = new VToDo(t);
				break;
                        case ICAL_VAGENDA_COMPONENT:
                                result = new VAgenda(t);
                                break;
			default:
				result = new VComponent(t);
		}
	}

	return (result);
}
VComponent* VComponent::get_next_component(icalcomponent_kind kind){
	VComponent* result = NULL;
	icalcomponent* t = icalcomponent_get_next_component(imp, kind);
	if (t != NULL) {
		switch (kind) {
			case ICAL_VALARM_COMPONENT:
				result = new VAlarm(t);
				break;
			case ICAL_VCALENDAR_COMPONENT:
				result = new VCalendar(t);
				break;
			case ICAL_VEVENT_COMPONENT:
				result = new VEvent(t);
				break;
			case ICAL_VQUERY_COMPONENT:
				result = new VQuery(t);
				break;
			case ICAL_VTODO_COMPONENT:
				result = new VToDo(t);
				break;
                        case ICAL_VAGENDA_COMPONENT:
                                result = new VAgenda(t);
                                break;
			default:
				result = new VComponent(t);
		}
	}

	return (result);
}

/* Using external iterators */
icalcompiter VComponent::begin_component(icalcomponent_kind kind){
	return icalcomponent_begin_component(imp, kind);
}
icalcompiter VComponent::end_component(icalcomponent_kind kind){
	return icalcomponent_end_component(imp, kind);
}
VComponent* VComponent::next(icalcompiter* i){
	return (VComponent*)icalcompiter_next(i);
}
VComponent* VComponent::prev(icalcompiter* i){
	return (VComponent*)icalcompiter_prior(i);
}
VComponent* VComponent::current(icalcompiter* i){
	return (VComponent*)icalcompiter_deref(i);
}

/* Working with embedded error properties */
int VComponent::count_errors(){
	return icalcomponent_count_errors(imp);
}

/* Remove all X-LIC-ERROR properties*/
void VComponent::strip_errors(){
	icalcomponent_strip_errors(imp);
}

/* Convert some X-LIC-ERROR properties into RETURN-STATUS properties*/
void VComponent::convert_errors(){
	icalcomponent_convert_errors(imp);
}

/* Kind conversion routines */
icalcomponent_kind VComponent::string_to_kind(string str){
	return icalcomponent_string_to_kind(str);
}
string VComponent::kind_to_string(icalcomponent_kind kind){
	return (string)icalcomponent_kind_to_string(kind);
}

struct icaltimetype VComponent::get_dtstart(){
	return icalcomponent_get_dtstart(imp);
}
void VComponent::set_dtstart(struct icaltimetype v){
	icalcomponent_set_dtstart(imp, v);
}

/* For the icalcomponent routines only, dtend and duration are tied
   together. If you call the set routine for one and the other exists,
   the routine will calculate the change to the other. That is, if
   there is a DTEND and you call set_duration, the routine will modify
   DTEND to be the sum of DTSTART and the duration. If you call a get
   routine for one and the other exists, the routine will calculate
   the return value. If you call a set routine and neither exists, the
   routine will create the apcompriate comperty.
*/

struct icaltimetype VComponent::get_dtend(){
	return icalcomponent_get_dtend(imp);
}

void VComponent::set_dtend(struct icaltimetype v){
	icalcomponent_set_dtend(imp, v);
}

struct icaltimetype VComponent::get_due(){
        return icalcomponent_get_due(imp);
}
void VComponent::set_due(struct icaltimetype v){
        icalcomponent_set_due(imp, v);
}

struct icaldurationtype VComponent::get_duration(){
	return icalcomponent_get_duration(imp);
}
void VComponent::set_duration(struct icaldurationtype v){
	icalcomponent_set_duration(imp, v);
}

icalproperty_method VComponent::get_method(){
	return icalcomponent_get_method(imp);
}
void VComponent::set_method(icalproperty_method method){
	icalcomponent_set_method(imp, method);
}

struct icaltimetype VComponent::get_dtstamp(){
	return icalcomponent_get_dtstamp(imp);
}
void VComponent::set_dtstamp(struct icaltimetype v){
	icalcomponent_set_dtstamp(imp, v);
}

string VComponent::get_summary(){
	return (string)icalcomponent_get_summary(imp);
}
void VComponent::set_summary(string v){
	icalcomponent_set_summary(imp, v);
}

string VComponent::get_location(){
        return (string)icalcomponent_get_location(imp);
}
void VComponent::set_location(string v){
        icalcomponent_set_location(imp, v);
}

string VComponent::get_description(){
        return (string)icalcomponent_get_description(imp);
}
void VComponent::set_description(string v){
        icalcomponent_set_description(imp, v);
}
string VComponent::get_comment(){
	return (string)icalcomponent_get_comment(imp);
}
void VComponent::set_comment(string v){
	icalcomponent_set_comment(imp, v);
}

string VComponent::get_uid(){
	return (string)icalcomponent_get_uid(imp);
}
void VComponent::set_uid(string v){
	icalcomponent_set_uid(imp, v);
}

string VComponent::get_relcalid(){
	return (string)icalcomponent_get_relcalid(imp);
}
void VComponent::set_relcalid(string v){
	icalcomponent_set_relcalid(imp, v);
}

struct icaltimetype VComponent::get_recurrenceid(){
	return icalcomponent_get_recurrenceid(imp);
}
void VComponent::set_recurrenceid(struct icaltimetype v){
	icalcomponent_set_recurrenceid(imp, v);
}

int VComponent::get_sequence(){
        return (int)icalcomponent_get_sequence(imp);
}
void VComponent::set_sequence(int v){
        icalcomponent_set_sequence(imp, v);
}

int VComponent::get_status(){
        return (int)icalcomponent_get_status(imp);
}
void VComponent::set_status(enum icalproperty_status v){
        icalcomponent_set_status(imp, v);
}

/* For VCOMPONENT: Return a reference to the first VEVENT, VTODO, or VJOURNAL */
VComponent* VComponent::get_first_real_component(){
	return (VComponent*)icalcomponent_get_first_real_component(imp);
}

/* For VEVENT, VTODO, VJOURNAL and VTIMEZONE: report the start and end
   times of an event in UTC */
struct icaltime_span VComponent::get_span(){
	return icalcomponent_get_span(imp);
}

int VComponent::recurrence_is_excluded( struct icaltimetype *dtstart,
                                       struct icaltimetype *recurtime){
       return  icalproperty_recurrence_is_excluded(imp, dtstart, recurtime);
}

/* Internal operations. They are private, and you should not be using them. */
VComponent* VComponent::get_parent() {
	return new VComponent(icalcomponent_get_parent(imp));
}
void VComponent::set_parent(VComponent *parent){
	icalcomponent_set_parent(imp, *parent);
}

/* ignoreValue means remove properties even if the data doesn't match */
bool VComponent::remove(VComponent& fromVC, bool ignoreValue){

    /* the two components must be the same kind */
    if (this->isa() != fromVC.isa()) return false;

    /* properties first */
    ICalPropertyTmpPtr propToBeRemoved;
    for (propToBeRemoved=fromVC.get_first_property(ICAL_ANY_PROPERTY); propToBeRemoved != NULL;
         propToBeRemoved=fromVC.get_next_property(ICAL_ANY_PROPERTY)) {

        /* loop through properties from this component */
        ICalPropertyTmpPtr next;
        ICalPropertyTmpPtr p;
        for (p=this->get_first_property(propToBeRemoved->isa()); p != NULL; p=next) {
            next = this->get_next_property(propToBeRemoved->isa());
            if (ignoreValue)
                 this->remove_property(p);
            else {
                 if (*p == *propToBeRemoved) {
                     this->remove_property(p);
                     break;
                 }
            }
        }
    }

    /* components next - should remove by UID */
    VComponentTmpPtr comp;
    for (comp=fromVC.get_first_component(ICAL_ANY_COMPONENT); comp != NULL;
         comp=fromVC.get_next_component(ICAL_ANY_COMPONENT)) {
        const char* fromCompUid = comp->get_uid();
        VComponentTmpPtr c;
        for (c=this->get_first_component(comp->isa()); c != NULL;
             c=this->get_next_component(comp->isa())) {
            const char* thisCompUid = c->get_uid();
            if (strcmp(fromCompUid, thisCompUid) == 0) {
                // recursively go down the components
                c->remove(*comp, ignoreValue);
                    // if all properties are removed and there is no sub-components, then
                    // remove this compoent
                    if ((c->count_properties(ICAL_ANY_PROPERTY) == 0) &&
                        (c->count_components(ICAL_ANY_COMPONENT) == 0)) {
                        this->remove_component(c);
                    }
                break;
                }
            }
    }

    return true;
}
/* removeMissing == true: remove properties that are missing from fromC */
/* todo: only change the first occurence of the property */
/* todo: removeMissing is not implemented */
bool VComponent::update(VComponent& fromC, bool removeMissing){

    /* make sure they are the same kind */
    if (this->isa() != fromC.isa()) return false;

    /* property first */
    ICalPropertyTmpPtr prop;
    for (prop=fromC.get_first_property(ICAL_ANY_PROPERTY); prop != NULL;
    	 prop=fromC.get_next_property(ICAL_ANY_PROPERTY)) {
        ICalPropertyTmpPtr thisProp;
	thisProp = this->get_first_property(prop->isa());
    	if (thisProp == NULL) {
            thisProp = new ICalProperty(prop->isa());
            this->add_property(thisProp);
        }
        ICalValue *value = new ICalValue(*(prop->get_value())); // clone the value
        thisProp->set_value(*value);
    }

    /* recursively updating sub-components */
    VComponentTmpPtr comp;
    for (comp=fromC.get_first_component(ICAL_ANY_COMPONENT); comp != NULL;
         comp=fromC.get_next_component(ICAL_ANY_COMPONENT)) {
        VComponentTmpPtr thisComp;
        thisComp = this->get_first_component(comp->isa());
        if (thisComp == NULL) {
            thisComp = new VComponent(comp->isa());
            this->add_component(thisComp);
        }
        bool err = thisComp->update(*comp, removeMissing);
        if (!err) return false;
    }
    return true;
}
/* add components and property. recursively goes down child components */
bool VComponent::add(VComponent& fromC){
	/* make sure the kind are the same */
	if (this->isa() != fromC.isa()) return false;

	/* properties first */
    ICalPropertyTmpPtr prop;
	for (prop=fromC.get_first_property(ICAL_ANY_PROPERTY); prop != NULL;
		 prop=fromC.get_next_property(ICAL_ANY_PROPERTY)) {
		/* clone another property */
		ICalProperty *p = new ICalProperty(*prop);
		add_property(p);
	}

	/* sub-components next */
	bool err = false;
    VComponentTmpPtr comp;
	for (comp=fromC.get_first_component(ICAL_ANY_COMPONENT); comp != NULL;
		 comp=fromC.get_next_component(ICAL_ANY_COMPONENT)) {
		VComponent *c = new VComponent(comp->isa());
		err = c->add(*comp);
		add_component(c);
	}

	return true;
}

VCalendar::VCalendar() : VComponent(icalcomponent_new_vcalendar()){
}
VCalendar::VCalendar(const VCalendar& v) : VComponent(v) {}
VCalendar& VCalendar::operator=(const VCalendar& v){
	if (this == &v) return *this;
	VComponent::operator=(v);

	return *this;
}
VCalendar::~VCalendar(){}

VCalendar::VCalendar(icalcomponent* v) : VComponent(v){}
VCalendar::VCalendar(string str) : VComponent(str){}

/* VEvent */

VEvent::VEvent() : VComponent(icalcomponent_new_vevent()){}
VEvent::VEvent(const VEvent& v) : VComponent(v) {}
VEvent& VEvent::operator=(const VEvent& v){
	if (this == &v) return *this;
	VComponent::operator=(v);

	return *this;
}
VEvent::~VEvent(){}

VEvent::VEvent(icalcomponent* v) : VComponent(v){}
VEvent::VEvent(string str) : VComponent(str){}

/* VTodo */

VToDo::VToDo() : VComponent(icalcomponent_new_vtodo()){}
VToDo::VToDo(const VToDo& v) : VComponent(v) {}
VToDo& VToDo::operator=(const VToDo& v){
	if (this == &v) return *this;
	VComponent::operator=(v);

	return *this;
}
VToDo::~VToDo(){}

VToDo::VToDo(icalcomponent* v) : VComponent(v){}
VToDo::VToDo(string str) : VComponent(str){}

/* VAgenda */

VAgenda::VAgenda() : VComponent(icalcomponent_new_vagenda()){}
VAgenda::VAgenda(const VAgenda& v) : VComponent(v) {}
VAgenda& VAgenda::operator=(const VAgenda& v){
        if (this == &v) return *this;
        VComponent::operator=(v);

        return *this;
}
VAgenda::~VAgenda(){}

VAgenda::VAgenda(icalcomponent* v) : VComponent(v){}
VAgenda::VAgenda(string str) : VComponent(str){}

/* VQuery */

VQuery::VQuery() : VComponent(icalcomponent_new_vquery()){}
VQuery::VQuery(const VQuery& v) : VComponent(v) {}
VQuery& VQuery::operator=(const VQuery& v){
	if (this == &v) return *this;
	VComponent::operator=(v);

	return *this;
}
VQuery::~VQuery(){}

VQuery::VQuery(icalcomponent* v) : VComponent(v){}
VQuery::VQuery(string str) : VComponent(str){}

/* VJournal */

VJournal::VJournal() : VComponent(icalcomponent_new_vjournal()){}
VJournal::VJournal(const VJournal& v) : VComponent(v) {}
VJournal& VJournal::operator=(const VJournal& v){
	if (this == &v) return *this;
	VComponent::operator=(v);

	return *this;
}
VJournal::~VJournal(){}

VJournal::VJournal(icalcomponent* v) : VComponent(v){}
VJournal::VJournal(string str) : VComponent(str){}

/* VAlarm */

VAlarm::VAlarm() : VComponent(icalcomponent_new_valarm()){}
VAlarm::VAlarm(const VAlarm& v) : VComponent(v) {}
VAlarm& VAlarm::operator=(const VAlarm& v){
	if (this == &v) return *this;
	VComponent::operator=(v);

	return *this;
}
VAlarm::~VAlarm(){}

VAlarm::VAlarm(icalcomponent* v) : VComponent(v){}
VAlarm::VAlarm(string str) : VComponent(str){}

icalrequeststatus
VAlarm::getTriggerTime(VComponent &c, struct icaltriggertype *tr)
{
  struct icaltimetype tt;
  ICalParameter *related_param;

  ICalPropertyTmpPtr trigger_prop = this->get_first_property(ICAL_TRIGGER_PROPERTY);

  // all VALARMs must have a TRIGGER
  if (trigger_prop == NULL)
    return ICAL_3_1_INVPROPVAL_STATUS;

  *tr = trigger_prop->get_trigger();

  tt = icaltime_null_time();

  if (icaltime_is_null_time(tr->time)) {

    // relative time trigger

    // TRIGGER;RELATED=END:P5M 5 minutes after END
    // TRIGGER;RELATED=START:-P15M 15 minutes before START
    // get RELATED parameter

    related_param = trigger_prop->get_first_parameter(ICAL_RELATED_PARAMETER);

    if (related_param && related_param->is_valid()) {

        // get RELATED parameter value
        icalparameter_related related = related_param->get_related();

        if(related) {
            switch(related) {
                case ICAL_RELATED_END:
                    if (c.isa() == ICAL_VEVENT_COMPONENT) {
                        tt = c.get_dtend();

			// If a recurrenceid exists, use that to calculate the
			// dtend from the dtstart.
			struct icaltimetype recur_time = c.get_recurrenceid();
			if (!(icaltime_is_null_time(recur_time))) {
			    struct icaldurationtype dur = icaltime_subtract(c.get_dtstart(), tt);
			    tt = icaltime_add(recur_time, dur);
		        }
		    }
                    else if (c.isa() == ICAL_VTODO_COMPONENT) {
                        tt = c.get_due();
			struct icaltimetype recur_time = c.get_recurrenceid();
			if (!(icaltime_is_null_time(recur_time))) {
			    tt = recur_time;
			}
		    }
                    // @@@ TODO: if not DTEND or DUE, then DTSTART and DURATION must be present
                break;
                case ICAL_RELATED_START:
                case ICAL_RELATED_X:
                case ICAL_RELATED_NONE:
                default:
                    tt = c.get_dtstart();
                    struct icaltimetype recur_time = c.get_recurrenceid();
                    if (!(icaltime_is_null_time(recur_time))) {
                        tt = recur_time;
                    }
                break;
            }

        }
    }
    else { // no RELATED explicity specified, the default is
           // relative to the start of an event or to-do, rfc2445
        // if no RELATED, we are forced to use dtstart for VEVENT,
        // due for VTODO to calculate trigger time.
	// If a recur time exists, use that. Recur time trumps dtstart or due.
        struct icaltimetype recur_time = c.get_recurrenceid();
	if (!(icaltime_is_null_time(recur_time))) {
	    tt = recur_time;
	}
	else if (c.isa() == ICAL_VEVENT_COMPONENT)
            tt = c.get_dtstart();
        else if (c.isa() == ICAL_VTODO_COMPONENT)
            tt = c.get_due();
    }

    // malformed? encapsulating VEVENT or VTODO MUST have DTSTART/DTEND
    if(icaltime_is_null_time(tt))
      return ICAL_3_1_INVPROPVAL_STATUS;;

    // now offset using tr.duration
    tr->time = icaltime_add(tt, tr->duration);
  }
  // else absolute time trigger

  return ICAL_2_0_SUCCESS_STATUS;
}

/* VFreeBusy */

VFreeBusy::VFreeBusy() : VComponent(icalcomponent_new_vfreebusy()){}
VFreeBusy::VFreeBusy(const VFreeBusy& v) : VComponent(v) {}
VFreeBusy& VFreeBusy::operator=(const VFreeBusy& v){
	if (this == &v) return *this;
	VComponent::operator=(v);

	return *this;
}
VFreeBusy::~VFreeBusy(){}

VFreeBusy::VFreeBusy(icalcomponent* v) : VComponent(v){}
VFreeBusy::VFreeBusy(string str) : VComponent(str){}

/* VTimezone */

VTimezone::VTimezone() : VComponent(icalcomponent_new_vtimezone()){}
VTimezone::VTimezone(const VTimezone& v) : VComponent(v) {}
VTimezone& VTimezone::operator=(const VTimezone& v){
	if (this == &v) return *this;
	VComponent::operator=(v);

	return *this;
}
VTimezone::~VTimezone(){}

VTimezone::VTimezone(icalcomponent* v) : VComponent(v){}
VTimezone::VTimezone(string str) : VComponent(str){}

/* XStandard */

XStandard::XStandard() : VComponent(icalcomponent_new_xstandard()){}
XStandard::XStandard(const XStandard& v) : VComponent(v) {}
XStandard& XStandard::operator=(const XStandard& v){
	if (this == &v) return *this;
	VComponent::operator=(v);

	return *this;
}
XStandard::~XStandard(){}

XStandard::XStandard(icalcomponent* v) : VComponent(v){}
XStandard::XStandard(string str) : VComponent(str){}

/* XDaylight */

XDaylight::XDaylight() : VComponent(icalcomponent_new_xdaylight()){}
XDaylight::XDaylight(const XDaylight& v) : VComponent(v) {}
XDaylight& XDaylight::operator=(const XDaylight& v){
	if (this == &v) return *this;
	VComponent::operator=(v);

	return *this;
}
XDaylight::~XDaylight(){}

XDaylight::XDaylight(icalcomponent* v) : VComponent(v){}
XDaylight::XDaylight(string str) : VComponent(str){}


text:
require('springbokjs');

App.init(__dirname);
App.start();