text:
package com.zgrannan.crewandroid;

import java.util.ArrayList;

import android.content.Context;

import com.zgrannan.crewandroid.Consumables.Fastener;
import com.zgrannan.crewandroid.Consumables.Sheet;
import com.zgrannan.crewandroid.Consumables.WoodStick;
import com.zgrannan.crewandroid.Geometry.Vertex;
import com.zgrannan.crewandroid.Pieces.RectPiece;
import com.zgrannan.crewandroid.Util.CompleteInstruction;
import com.zgrannan.crewandroid.Util.Dimension;
import com.zgrannan.crewandroid.Util.Instruction;

/**
 * This is a fragment for a door frame. Note that doorframes only ever have one
 * fragment.
 *
 * @author Zack Grannan
 * @version 0.96
 *
 */
public class DoorFrag extends Frag {

	/**
	 * This is the amount of space between the bottom of the door and the
	 * ground.
	 */
	public static final double HEIGHT_SPACER = 0.5;

	/**
	 * This is the amount of space between the sides of the door and the door
	 * itself.
	 */
	public static final double WIDTH_SPACER = 0.25;

	/**
	 * A double representing the width of the door frame.
	 */
	private double doorWidthD;

	/**
	 * A double representing the height of the door frame.
	 */
	private double doorHeightD;

	@Override
	public Dimension minWidth() {
		return new Dimension(4 * super.woodstick.getWidth().toDouble()
				+ doorWidthD + WIDTH_SPACER);
	}

	@Override
	public Dimension maxWidth() {
		return new Dimension(96);
	}

	@Override
	public Dimension minLength() {
		return new Dimension(2 * super.woodstick.getWidth().toDouble()
				+ doorHeightD + HEIGHT_SPACER);
	}

	@Override
	public Dimension maxLength() {
		return new Dimension(96);
	}

	@Override
	protected void setInstructions(Context context) {
		instructions = new ArrayList<Instruction>();
		Fastener frameFastener = woodstick.getFastener(woodstick);
		CompleteInstruction one = new CompleteInstruction(
				context.getString(
						R.string.attach_topmost_piece_to_the_side_pieces_using_frameFasteners,
						frameFastener), new int[] { C.SELECTED, C.SELECTED,
						C.SELECTED });
		CompleteInstruction two = new CompleteInstruction(
				context.getString(
						R.string.attach_bottommost_pieces_to_side_pieces_using_frameFasteners,
						frameFastener), new int[] { C.VISIBLE, C.VISIBLE,
						C.VISIBLE, C.INVISIBLE, C.INVISIBLE, C.INVISIBLE,
						C.INVISIBLE, C.SELECTED, C.SELECTED });
		CompleteInstruction three = new CompleteInstruction(
				context.getString(
						R.string.attach_inner_side_pieces_to_bottom_pieces_using_frameFasteners,
						frameFastener), new int[] { C.VISIBLE, C.VISIBLE,
						C.VISIBLE, C.SELECTED, C.SELECTED, C.INVISIBLE,
						C.INVISIBLE, C.VISIBLE, C.VISIBLE });

		CompleteInstruction four = new CompleteInstruction(
				context.getString(
						R.string.attach_inner_top_piece_to_outer_and_inner_side_pieces_using_frameFasteners,
						frameFastener), new int[] { C.VISIBLE, C.VISIBLE,
						C.VISIBLE, C.VISIBLE, C.VISIBLE, C.SELECTED,
						C.INVISIBLE, C.VISIBLE, C.VISIBLE });

		CompleteInstruction five = new CompleteInstruction(
				context.getString(R.string.attach_outer_and_inner_side_pieces_using_toggles),
				new int[] { C.VISIBLE, C.VISIBLE, C.VISIBLE, C.VISIBLE,
						C.VISIBLE, C.VISIBLE, C.INVISIBLE, C.VISIBLE,
						C.VISIBLE, C.SELECTED, C.SELECTED });

		CompleteInstruction six = new CompleteInstruction(
				context.getString(R.string.attach_inner_top_piece_to_outer_top_piece_using_a_toggle),
				new int[] { C.VISIBLE, C.VISIBLE, C.VISIBLE, C.VISIBLE,
						C.VISIBLE, C.VISIBLE, C.SELECTED, C.VISIBLE, C.VISIBLE,
						C.VISIBLE, C.VISIBLE });

		CompleteInstruction seven = null;
		if (sheet != Consumables.noSheet) {
			if (width.toDouble() <= 48) {
				seven = new CompleteInstruction(
						context.getString(R.string.attach_lid_to_door_frame_and_route_out_the_door),
						new int[] { C.UNDER, C.UNDER, C.UNDER, C.UNDER,
								C.UNDER, C.UNDER, C.UNDER, C.UNDER, C.UNDER,
								C.UNDER, C.UNDER, C.SELECTED });
			} else {
				seven = new CompleteInstruction(
						context.getString(R.string.attach_lid_to_door_frame_and_route_out_the_door),
						new int[] { C.UNDER, C.UNDER, C.UNDER, C.UNDER,
								C.UNDER, C.UNDER, C.UNDER, C.UNDER, C.UNDER,
								C.UNDER, C.UNDER, C.SELECTED, C.SELECTED });
			}
		}

		setNextInstruction(one);
		setNextInstruction(two);
		setNextInstruction(three);
		setNextInstruction(four);
		setNextInstruction(five);
		setNextInstruction(six);
		if (sheet != Consumables.noSheet && !(width.toDouble() > 96)
				&& !(length.toDouble() > 96)) {
			setNextInstruction(seven);
		}

	}

	@Override
	public BuildResult make(Context context) {

		// Start making pieces
		if (width.toDouble() <= 48) {
			pieces = new RectPiece[12];
		} else {
			pieces = new RectPiece[13];
		}

		pieces[0] = new RectPiece(Geometry.origin, widthD, woodstick,
				C.HORIZONTAL, C.ABOVE);

		/*
		 * Top pieces
		 */

		// Pieces 1 and 2 are the outer side pieces of the doorframe
		pieces[1] = new RectPiece(new Vertex(widthD - woodThicknessD,
				woodThicknessD), lengthD - 2 * woodThicknessD, woodstick,
				C.VERTICAL);
		pieces[2] = new RectPiece(new Vertex(0, woodThicknessD), lengthD - 2
				* woodThicknessD, woodstick, C.VERTICAL, C.LEFT);

		// Pieces 3 and 4 are the inner side pieces of the doorframe
		pieces[3] = new RectPiece(new Vertex(widthD
				- (widthD - doorWidthD - WIDTH_SPACER) / 2, lengthD
				- doorHeightD - HEIGHT_SPACER), doorHeightD - woodThicknessD
				+ HEIGHT_SPACER, woodstick, C.VERTICAL, C.LEFT);
		pieces[4] = new RectPiece((RectPiece) pieces[3]);
		pieces[4].move(new Dimension(0 - doorWidthD - WIDTH_SPACER
				- woodThicknessD), new Dimension(0));
		((RectPiece) pieces[4]).setDimLinePos(C.RIGHT);

		// Piece 5 is the lower horizontal top pieces
		pieces[5] = new RectPiece(new Vertex(woodThicknessD, lengthD
				- doorHeightD - HEIGHT_SPACER - woodThicknessD), widthD - 2
				* woodThicknessD, woodstick, C.HORIZONTAL);

		// Piece 6 connects the bottom horizontal pieces to the top one
		pieces[6] = new RectPiece(new Vertex(widthD / 2 - woodThicknessD / 2,
				woodThicknessD), lengthD - doorHeightD - HEIGHT_SPACER - 2
				* woodThicknessD, woodstick, C.VERTICAL);

		// Piece 7 and 8 are the pieces touching the floor
		pieces[7] = new RectPiece(new Vertex(0, lengthD - woodThicknessD),
				(widthD - doorWidthD - WIDTH_SPACER) / 2, woodstick,
				C.HORIZONTAL);
		pieces[8] = new RectPiece((RectPiece) pieces[7]);
		pieces[8].move(new Dimension(((RectPiece) pieces[7]).e.getLength()
				+ doorWidthD + WIDTH_SPACER), new Dimension(0));

		// Piece 9 and 10 are the midpieces for the sides of the doorframe
		pieces[9] = new RectPiece(new Vertex(woodThicknessD,
				((RectPiece) pieces[4]).f.getMidpoint().y.toDouble()),
				((RectPiece) pieces[8]).e.getLength() - 2 * woodThicknessD,
				woodstick, C.HORIZONTAL);
		pieces[10] = new RectPiece((RectPiece) pieces[9]);
		pieces[10].move(new Dimension(((RectPiece) pieces[9]).e.getLength()
				+ doorWidthD + WIDTH_SPACER + 2 * woodThicknessD),
				new Dimension(0));

		// Piece 11 is the pieces for the doorframe lid.
		if (width.toDouble() > 48) {
			pieces[11] = new RectPiece(Geometry.origin, new Dimension(48),
					length, sheet, C.INVISIBLE);
			pieces[12] = new RectPiece(Geometry.origin, new Dimension(
					width.toDouble() - 48), length, sheet, C.INVISIBLE);
			pieces[12].move(new Dimension(48), new Dimension(0));
		}else{
			pieces[11] = new RectPiece(Geometry.origin, new Dimension(width),
					length, sheet, C.INVISIBLE);
		}
		setInstructions(context);
		return new BuildResult(context, true);
	}

	/**
	 * Loads {@link doorWidth} and {@link doorHeight} into this doorFrag, and
	 * then calls the generic {@link Frag} function to load the rest of the
	 * data.
	 *
	 * @param length
	 * @param width
	 * @param doorHeight
	 * @param doorWidth
	 * @param woodstick
	 * @param sheet
	 *
	 * @return
	 */
	public BuildResult make(Context context, Dimension length, Dimension width,
			Dimension doorHeight, Dimension doorWidth, WoodStick woodstick,
			Sheet sheet) {
		doorWidthD = doorWidth.toDouble();
		doorHeightD = doorHeight.toDouble();
		return super.make(context, length, width, woodstick, sheet);
	}
}


text:
import { Component, OnInit, Input, OnDestroy, ChangeDetectorRef } from '@angular/core';
import { ShapeLayer } from '../../map.models';
import { Store } from '@ngrx/store';
import { addFilter, removeFilter } from 'src/app/home/store/actions';
import { environment } from 'src/environments/environment';
import { FormQueryResult } from 'src/app/home/home.models';
import { constants } from 'src/constants';

@Component({
  selector: 'scm-shape-layer',
  templateUrl: './shape-layer.component.html',
  styleUrls: ['./shape-layer.component.scss']
})
export class ShapeLayerComponent implements OnInit, OnDestroy {

  polygons: google.maps.Polygon[] = [];

  _layer: ShapeLayer;
  @Input('layer')
  set layer(value: ShapeLayer) {
    this._layer = value;
    this.drawPolygons();
    this.store.dispatch(addFilter({
      filterIdentifier: this._layer.name,
      filter: (formQueryResult) => {
        const filteredFormQueryResult: any = {};
        if ('upstream' in formQueryResult) {
          const UPSTREAM_COLS = constants.bigQuery.datasets.route.tables.UPSTREAM.columns;
          filteredFormQueryResult.upstream = formQueryResult.upstream.filter(upstream => {
            for (const p of this.polygons) {
              if (google.maps.geometry.poly.containsLocation(
                new google.maps.LatLng(upstream[UPSTREAM_COLS.MFG_LAT], upstream[UPSTREAM_COLS.MFG_LONG]),
                p
              )) {
                return true;
              }
            }
            return false;
          });
        }

        const CM_COLS = constants.bigQuery.datasets.route.tables.CM.columns;
        filteredFormQueryResult.cm = formQueryResult.cm.filter(cm => {
          for (const p of this.polygons) {
            if (google.maps.geometry.poly.containsLocation(
              new google.maps.LatLng(cm[CM_COLS.CM_LAT], cm[CM_COLS.CM_LONG]),
              p
            )) {
              return true;
            }
          }
          return false;
        });

        if ('downstream' in formQueryResult) {
          const DOWNSTREAM_COLS = constants.bigQuery.datasets.route.tables.DOWNSTREAM.columns;
          filteredFormQueryResult.downstream = formQueryResult.downstream.filter(downstream => {
            for (const p of this.polygons) {
              if (google.maps.geometry.poly.containsLocation(
                new google.maps.LatLng(downstream[DOWNSTREAM_COLS.GDC_LAT], downstream[DOWNSTREAM_COLS.GDC_LONG]),
                p
              )) {
                return true;
              }
            }
            return false;
          });
        }
        return filteredFormQueryResult;
      },
      isActive: false
    }));
  }

  _map: google.maps.Map;
  @Input('map')
  set map(value: google.maps.Map) {
    this._map = value;
    this.drawPolygons();
  }

  infoWindowData: {
    latitude: number,
    longitude: number,
    data: object
  }[] = [];

  constructor(private store: Store, private changeDetector: ChangeDetectorRef) {
  }

  ngOnInit(): void {
  }

  ngOnDestroy(): void {
    for (const p of this.polygons) {
      p.setMap(null);
    }
    this.store.dispatch(removeFilter({ filterIdentifier: this._layer.name }));
  }

  layerClick($event) {
    this.infoWindowData.push({
      latitude: $event.latLng.lat(),
      longitude: $event.latLng.lng(),
      data: $event.feature.getProperty('data')
    });
  }

  private drawPolygons() {
    if (this._layer !== undefined && this._map !== undefined) {
      this.polygons = [];
      for (const shape of this._layer.shapes) {
        const p = new google.maps.Polygon({
          ...shape.shapeOpts,
          zIndex: -1,
          map: this._map
        });
        p.addListener('click', (event) => {
          this.infoWindowData.push({
            latitude: event.latLng.lat(),
            longitude: event.latLng.lng(),
            data: shape.data
          });
          this.changeDetector.detectChanges();
        });
        this.polygons.push(p);
      }
    }
  }

}

redpajama_set_name: RedPajamaGithub


text:
media
=======================

This directory is used for uploads.

It's available via /media/ url when DEBUG=True.


text:
TubeTK Tubes to Density Image Application
=========================================

*This file is part of [TubeTK](http://www.tubetk.org). TubeTK is developed by [Kitware, Inc.](http://www.kitware.com) and licensed under the [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0).*

#### Overview:

Given a TRE file containing a set of tubes/vessels, this module generates a
density image highlighting the pixels.

#### Command line usage:

```
USAGE:
		ConvertTubesToDensityImage  [--returnparameterfile <std::string>]
												[--processinformationaddress <std::string>]
												[--xml] [--echo] [--useSquareDistance]
												[--outputSize <std::vector<int>>]
												[--outputSpacing <std::vector<double>>]
												[--inputTemplateImage <std::string>] [--]
												[--version] [-h] <std::string> <std::string>
												<std::string> <std::string>

Where:

   --returnparameterfile <std::string>
     Filename in which to write simple return parameters (int, float,
     int-vector, etc.) as opposed to bulk return parameters (image,
     geometry, transform, measurement, table).

   --processinformationaddress <std::string>
     Address of a structure to store process information (progress, abort,
     etc.). (default: 0)

   --xml
     Produce xml description of command line arguments (default: 0)

   --echo
     Echo the command line arguments (default: 0)

   --useSquareDistance (default: false)
     Use square distance value for the density image.

   --outputSize (optional)
     The image size of the output density, radius and tangent images.
		 User can specify a specific size or can provide a template image.

   --outputSpacing (optional)
     The image spacing of the output density, radius and tangent images.
		 User can specify a specific spacing or can provide a template image.

   --inputTemplateImage
     Template image for determining space and size constraints.

	 --version
     Displays version information and exits.

   -h,  --help
     Displays usage information and exits.

   <std::string>
     (required)  File containing the input tubes.

   <std::string>
     (required)  Density output image that is being generated.

   <std::string>
     (required)  Radius output image that is being generated.

   <std::string>
     (required)  Tangent output image that is being generated.

   Description: Computes a density image from tubes

   Author(s): Stephen R. Aylward, Roland Kwitt, Kitware

   Acknowledgements: This work is part of the TubeTK project at Kitware
```


text:
package org.uberfire.io.attribute;

import java.util.HashMap;
import java.util.Map;

import static org.uberfire.commons.validation.Preconditions.checkNotEmpty;
import static org.uberfire.io.attribute.DublinCoreView.CONTRIBUTOR;
import static org.uberfire.io.attribute.DublinCoreView.COVERAGE;
import static org.uberfire.io.attribute.DublinCoreView.CREATION_TIME;
import static org.uberfire.io.attribute.DublinCoreView.CREATOR;
import static org.uberfire.io.attribute.DublinCoreView.DESCRIPTION;
import static org.uberfire.io.attribute.DublinCoreView.FORMAT;
import static org.uberfire.io.attribute.DublinCoreView.IDENTIFIER;
import static org.uberfire.io.attribute.DublinCoreView.LANGUAGE;
import static org.uberfire.io.attribute.DublinCoreView.LAST_ACCESS_TIME;
import static org.uberfire.io.attribute.DublinCoreView.LAST_MODIFIED_TIME;
import static org.uberfire.io.attribute.DublinCoreView.PUBLISHER;
import static org.uberfire.io.attribute.DublinCoreView.RELATION;
import static org.uberfire.io.attribute.DublinCoreView.RIGHTS;
import static org.uberfire.io.attribute.DublinCoreView.SOURCE;
import static org.uberfire.io.attribute.DublinCoreView.SUBJECT;
import static org.uberfire.io.attribute.DublinCoreView.TITLE;
import static org.uberfire.io.attribute.DublinCoreView.TYPE;

/**
 *
 */
public final class DublinCoreAttributesUtil {

    private DublinCoreAttributesUtil() {

    }

    public static Map<String, Object> cleanup(final Map<String, Object> _attrs) {
        final Map<String, Object> attrs = new HashMap<String, Object>(_attrs);

        for (final String key : _attrs.keySet()) {
            if (key.startsWith(TITLE) || key.startsWith(CREATOR) ||
                    key.startsWith(SUBJECT) || key.startsWith(DESCRIPTION) ||
                    key.startsWith(PUBLISHER) || key.startsWith(CONTRIBUTOR) ||
                    key.startsWith(TYPE) || key.startsWith(FORMAT) ||
                    key.startsWith(IDENTIFIER) || key.startsWith(SOURCE) ||
                    key.startsWith(LANGUAGE) || key.startsWith(RELATION) ||
                    key.startsWith(COVERAGE) || key.startsWith(RIGHTS)) {
                attrs.put(key,
                          null);
            }
        }

        return attrs;
    }

    public static Map<String, Object> toMap(final DublinCoreAttributes attrs,
                                            final String... attributes) {

        return new HashMap<String, Object>() {{
            for (final String attribute : attributes) {
                checkNotEmpty("attribute",
                              attribute);

                if (attribute.equals("*") || attribute.equals(TITLE)) {
                    for (int i = 0; i < attrs.titles().size(); i++) {
                        final String content = attrs.titles().get(i);
                        put(buildAttrName(TITLE,
                                          i),
                            content);
                    }
                }
                if (attribute.equals("*") || attribute.equals(CREATOR)) {
                    for (int i = 0; i < attrs.creators().size(); i++) {
                        final String content = attrs.creators().get(i);
                        put(buildAttrName(CREATOR,
                                          i),
                            content);
                    }
                }
                if (attribute.equals("*") || attribute.equals(SUBJECT)) {
                    for (int i = 0; i < attrs.subjects().size(); i++) {
                        final String content = attrs.subjects().get(i);
                        put(buildAttrName(SUBJECT,
                                          i),
                            content);
                    }
                }
                if (attribute.equals("*") || attribute.equals(DESCRIPTION)) {
                    for (int i = 0; i < attrs.descriptions().size(); i++) {
                        final String content = attrs.descriptions().get(i);
                        put(buildAttrName(DESCRIPTION,
                                          i),
                            content);
                    }
                }
                if (attribute.equals("*") || attribute.equals(PUBLISHER)) {
                    for (int i = 0; i < attrs.publishers().size(); i++) {
                        final String content = attrs.publishers().get(i);
                        put(buildAttrName(PUBLISHER,
                                          i),
                            content);
                    }
                }
                if (attribute.equals("*") || attribute.equals(CONTRIBUTOR)) {
                    for (int i = 0; i < attrs.contributors().size(); i++) {
                        final String content = attrs.contributors().get(i);
                        put(buildAttrName(CONTRIBUTOR,
                                          i),
                            content);
                    }
                }

                if (attribute.equals("*") || attribute.equals(LAST_MODIFIED_TIME)) {
                    put(LAST_MODIFIED_TIME,
                        null);
                }
                if (attribute.equals("*") || attribute.equals(LAST_ACCESS_TIME)) {
                    put(LAST_ACCESS_TIME,
                        null);
                }
                if (attribute.equals("*") || attribute.equals(CREATION_TIME)) {
                    put(CREATION_TIME,
                        null);
                }

                if (attribute.equals("*") || attribute.equals(TYPE)) {
                    for (int i = 0; i < attrs.types().size(); i++) {
                        final String content = attrs.types().get(i);
                        put(buildAttrName(TYPE,
                                          i),
                            content);
                    }
                }
                if (attribute.equals("*") || attribute.equals(FORMAT)) {
                    for (int i = 0; i < attrs.formats().size(); i++) {
                        final String content = attrs.formats().get(i);
                        put(buildAttrName(FORMAT,
                                          i),
                            content);
                    }
                }
                if (attribute.equals("*") || attribute.equals(IDENTIFIER)) {
                    for (int i = 0; i < attrs.identifiers().size(); i++) {
                        final String content = attrs.identifiers().get(i);
                        put(buildAttrName(IDENTIFIER,
                                          i),
                            content);
                    }
                }
                if (attribute.equals("*") || attribute.equals(SOURCE)) {
                    for (int i = 0; i < attrs.sources().size(); i++) {
                        final String content = attrs.sources().get(i);
                        put(buildAttrName(SOURCE,
                                          i),
                            content);
                    }
                }
                if (attribute.equals("*") || attribute.equals(LANGUAGE)) {
                    for (int i = 0; i < attrs.languages().size(); i++) {
                        final String content = attrs.languages().get(i);
                        put(buildAttrName(LANGUAGE,
                                          i),
                            content);
                    }
                }
                if (attribute.equals("*") || attribute.equals(RELATION)) {
                    for (int i = 0; i < attrs.relations().size(); i++) {
                        final String content = attrs.relations().get(i);
                        put(buildAttrName(RELATION,
                                          i),
                            content);
                    }
                }
                if (attribute.equals("*") || attribute.equals(COVERAGE)) {
                    for (int i = 0; i < attrs.coverages().size(); i++) {
                        final String content = attrs.coverages().get(i);
                        put(buildAttrName(COVERAGE,
                                          i),
                            content);
                    }
                }
                if (attribute.equals("*") || attribute.equals(RIGHTS)) {
                    for (int i = 0; i < attrs.rights().size(); i++) {
                        final String content = attrs.rights().get(i);
                        put(buildAttrName(RIGHTS,
                                          i),
                            content);
                    }
                }
                if (attribute.equals("*")) {
                    break;
                }
            }
        }};
    }

    private static String buildAttrName(final String title,
                                        final int i) {
        return title + "[" + i + "]";
    }
}


text:
from django.conf.urls import patterns, url

urlpatterns = patterns('security.views',
  url(r'^$', 'hive', name='index'),
  url(r'^hive$', 'hive', name='hive'),
  url(r'^hive2$', 'hive2', name='hive2'),
  url(r'^solr$', 'solr', name='solr'),
  url(r'^hdfs$', 'hdfs', name='hdfs'),
)

urlpatterns += patterns('security.api.hdfs',
  url(r'^api/hdfs/list(?P<path>/.*)$', 'list_hdfs', name='list_hdfs'),
  url(r'^api/hdfs/get_acls$', 'get_acls', name='get_acls'),
  url(r'^api/hdfs/update_acls', 'update_acls', name='update_acls'),
  url(r'^api/hdfs/bulk_delete_acls', 'bulk_delete_acls', name='bulk_delete_acls'),
  url(r'^api/hdfs/bulk_add_acls', 'bulk_add_acls', name='bulk_add_acls'),
  url(r'^api/hdfs/bulk_sync_acls', 'bulk_sync_acls', name='bulk_sync_acls'),
)

urlpatterns += patterns('security.api.hive',
  url(r'^api/hive/fetch_hive_path', 'fetch_hive_path', name='fetch_hive_path'),

  url(r'^api/hive/list_sentry_roles_by_group', 'list_sentry_roles_by_group', name='list_sentry_roles_by_group'),
  url(r'^api/hive/list_sentry_privileges_by_role', 'list_sentry_privileges_by_role', name='list_sentry_privileges_by_role'),
  url(r'^api/hive/list_sentry_privileges_for_provider$', 'list_sentry_privileges_for_provider', name='list_sentry_privileges_for_provider'),
  url(r'^api/hive/list_sentry_privileges_by_authorizable', 'list_sentry_privileges_by_authorizable', name='list_sentry_privileges_by_authorizable'),
  url(r'^api/hive/create_sentry_role', 'create_sentry_role', name='create_sentry_role'),
  url(r'^api/hive/update_role_groups', 'update_role_groups', name='update_role_groups'),
  url(r'^api/hive/drop_sentry_role', 'drop_sentry_role', name='drop_sentry_role'),
  url(r'^api/hive/create_role$', 'create_role', name='create_role'),
  url(r'^api/hive/save_privileges$', 'save_privileges', name='save_privileges'),
  url(r'^api/hive/bulk_delete_privileges', 'bulk_delete_privileges', name='bulk_delete_privileges'),
  url(r'^api/hive/bulk_add_privileges', 'bulk_add_privileges', name='bulk_add_privileges'),
  url(r'^api/hive/grant_privilege', 'grant_privilege', name='grant_privilege'),

  # Unused: API is for blind bulk operations
  url(r'^api/hive/rename_sentry_privilege', 'rename_sentry_privilege', name='rename_sentry_privilege'),
)

# Generic API V2
urlpatterns += patterns('security.api.sentry',
  url(r'^api/sentry/fetch_authorizables', 'fetch_authorizables', name='fetch_authorizables'),

  url(r'^api/sentry/list_sentry_roles_by_group', 'list_sentry_roles_by_group', name='list_sentry_roles_by_group'),
  url(r'^api/sentry/list_sentry_privileges_by_role', 'list_sentry_privileges_by_role', name='list_sentry_privileges_by_role'),
  url(r'^api/sentry/list_sentry_privileges_for_provider$', 'list_sentry_privileges_for_provider', name='list_sentry_privileges_for_provider'),
  url(r'^api/sentry/list_sentry_privileges_by_authorizable', 'list_sentry_privileges_by_authorizable', name='list_sentry_privileges_by_authorizable'),
  url(r'^api/sentry/create_sentry_role', 'create_sentry_role', name='create_sentry_role'),
  url(r'^api/sentry/update_role_groups', 'update_role_groups', name='update_role_groups'),
  url(r'^api/sentry/drop_sentry_role', 'drop_sentry_role', name='drop_sentry_role'),
  url(r'^api/sentry/create_role$', 'create_role', name='create_role'),
  url(r'^api/sentry/save_privileges$', 'save_privileges', name='save_privileges'),
  url(r'^api/sentry/bulk_delete_privileges', 'bulk_delete_privileges', name='bulk_delete_privileges'),
  url(r'^api/sentry/bulk_add_privileges', 'bulk_add_privileges', name='bulk_add_privileges'),
  url(r'^api/sentry/grant_privilege', 'grant_privilege', name='grant_privilege'),

  # Unused: API is for blind bulk operations
  url(r'^api/sentry/rename_sentry_privilege', 'rename_sentry_privilege', name='rename_sentry_privilege'),
)


text:
	<title>Tasha Danvers's panel show appearances</title>

	<link rel="stylesheet" media="all" href="../style.css" type="text/css"/>

Tasha Danvers's panel show appearances

Tasha Danvers (born 1977-09-19[ref]) has appeared in 3 episodes between 2010-2011.  Tasha Danvers on Wikipedia.

2010

2011

2011-07-29 / A Question of Sport

2011-04-15 / A Question of Sport

2010-04-16 / A Question of Sport


text:
(function(){
    angular.module("anguComp.monacoEditor",[]);
})();


text:
<q style="display: table;">

<object style="display: table-header-group;"></object>
<object style="display: table;">


text:
"""Get column means grouped by kmer."""
import argparse as ap
import pandas as pd
import numpy as np

if __name__ == '__main__':
    parser = ap.ArgumentParser(
        prog='aggregate-kmer-stats.py', conflict_handler='resolve',
        description="Assess the results of all the simulations."
    )

    parser.add_argument('results', type=str, metavar="VALIDATION_OUTPUT",
                        help='Output the mean kmer stats of all simulations.')
    args = parser.parse_args()

    df = pd.read_csv(args.results, sep='\t')
    df.columns = ['Kmer', 'Total Samples', 'Expected TP', 'Expected TN',
                  'TP', 'FN', 'FP', 'TN', 'Accuracy', 'Precision',
                  'Specificity', 'Sensitivity', 'FPR']

    grouped = df.groupby(['Kmer'], as_index=False)
    means = grouped.aggregate(np.mean)

    output = args.results.replace('.txt', '-aggregated.txt')
    means.to_csv(output, sep='\t')


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('flatpages', '0003_auto_20160221_0250'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='flatpage',
            options={'verbose_name': 'Flatpage', 'verbose_name_plural': 'Flatpages'},
        ),
        migrations.AlterModelOptions(
            name='localflatpage',
            options={'ordering': ('language', 'flatpage__menu_index', 'title'), 'verbose_name': 'Local Flatpage', 'verbose_name_plural': 'Local Flatpages'},
        ),
        migrations.AlterModelOptions(
            name='sponsor',
            options={'ordering': ('name',), 'verbose_name': 'Sponsor', 'verbose_name_plural': 'Sponsors'},
        ),
        migrations.AlterField(
            model_name='flatpage',
            name='flatpage_type',
            field=models.IntegerField(choices=[(0, 'Page'), (1, 'Direct Link'), (2, 'Page with menu separator')], default=0, verbose_name='Flatpage type'),
        ),
        migrations.AlterField(
            model_name='flatpage',
            name='menu_category',
            field=models.IntegerField(choices=[(1, b'Association'), (2, b'Activities'), (0, b'(Top level)')], default=0, verbose_name='Menu category'),
        ),
        migrations.AlterField(
            model_name='flatpage',
            name='menu_index',
            field=models.IntegerField(default=0, help_text='Menus are sorted ascending by this value. The first menu item in a category is the category link itself. Note: The first menu item in the top level category should be the front page.', verbose_name='Menu index'),
        ),
        migrations.AlterField(
            model_name='flatpage',
            name='published',
            field=models.BooleanField(default=False, help_text='Published pages show up on the menu. Unpublished pages can be reached over direct link.', verbose_name='Published'),
        ),
        migrations.AlterField(
            model_name='localflatpage',
            name='content',
            field=models.TextField(help_text='Body text for pages, URL for direct links', verbose_name='Content'),
        ),
        migrations.AlterField(
            model_name='localflatpage',
            name='content_markup',
            field=models.CharField(choices=[(b'textile', b'Textile'), (b'none', b'None (no processing)'), (b'linebreaks', b'Linebreaks')], default=b'textile', max_length=20, verbose_name='Content markup'),
        ),
        migrations.AlterField(
            model_name='localflatpage',
            name='language',
            field=models.CharField(choices=[(b'fi', 'Finnish'), (b'en', 'English')], max_length=5, verbose_name='Language'),
        ),
        migrations.AlterField(
            model_name='localflatpage',
            name='menu_title',
            field=models.CharField(blank=True, help_text='Shorter title that fits in menu elements', max_length=40, verbose_name='Menu Title'),
        ),
        migrations.AlterField(
            model_name='localflatpage',
            name='title',
            field=models.CharField(max_length=100, verbose_name='Title'),
        ),
        migrations.AlterField(
            model_name='localflatpage',
            name='url',
            field=models.CharField(blank=True, db_index=True, help_text='The page is accessible on this path. Even external links have one.', max_length=100, verbose_name='URL'),
        ),
        migrations.AlterField(
            model_name='sponsor',
            name='is_active',
            field=models.BooleanField(default=True, verbose_name='Is active'),
        ),
        migrations.AlterField(
            model_name='sponsor',
            name='name',
            field=models.CharField(max_length=100, verbose_name='Name'),
        ),
        migrations.AlterField(
            model_name='sponsor',
            name='titletext',
            field=models.CharField(blank=True, max_length=255, verbose_name='Title text'),
        ),
        migrations.AlterField(
            model_name='sponsor',
            name='url',
            field=models.URLField(verbose_name='URL'),
        ),
    ]


text:
<?php

  #starting session
  session_start();
  if ((isset($_SESSION['uname']) !=''))
  {
    if($_SESSION['type'] == 1)
    {
      header("location: pasu_profile.php");
    }
    elseif($_SESSION['type'] == 2)
    {
      header("location: head_profile.php");
    }
  }
  else
  {
    header("location: sign_in.php");
  }
  $qfinal;
  $quarter = $_SESSION['quarter'];
  if (is_null($quarter)) {
    header("location: pasu_redirect.php");
  }
  else{
    if ($quarter == 1) {
      $qfinal = '1st';
    }
    elseif ($quarter == 2) {
      $qfinal = '2nd';
    }
    elseif ($quarter == 3) {
      $qfinal = '3rd';
    }
    elseif ($quarter == 4) {
      $qfinal = '4th';
    }
  }

?>
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>PASuBIOMES | Focus Group Discussion</title>

    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">

    <link rel="stylesheet" href="../bootstrap/css/bootstrap.min.css">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">

    <link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">

    <link rel="stylesheet" href="../dist/css/AdminLTE.min.css">

    <link rel="stylesheet" href="../dist/css/skins/_all-skins.min.css">

      <?php include 'templates\pasu_header.php';?>

      <?php include 'templates\pasu_sidebar.php';?>

            Focus Group Discussion

<button type="button" class="btn btn-primary btn-sm pull-right" data-toggle="modal" data-target="#myModal">
  Add Focus Group Discussion
</button>

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Adding Focus Group Discussion

      <form role="form">

                      Protected Area Name
                      <input  class="form-control" id="exampleInputEmail1" placeholder="Enter Protected Area Name">

                      Method 1
                      <input  class="form-control" id="exampleInputPassword1" placeholder="Main Issue">

                      Method 2
                      <input class="form-control" id="exampleInputPassword1" placeholder="Sub-Issues">
                      <input class="form-control" id="exampleInputPassword1" placeholder="Description">

                      Method 3
                      <input class="form-control" id="exampleInputPassword1" placeholder="Matrix">

                </form>

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary data-toggle="modal data-target="my-submodal">Done</button>

        Sub modal content goes here

        <button class="btn btn-default" data-dismiss="submodal" aria-hidden="true">Cancel</button>
        <button class="btn btn-danger" data-dismiss="submodal">Close Account</button>

Name of Protected Area

«

1

2

3

»

ID

Year / Quarter

Main Issues Discussed (Method 1)

Matrix for Resource Uses (Method 2)

Matrix for Species Observed (Method 3)

Actions

                      <?php
                     include 'database/database.php';
                     $pdo = Database::connect();
                     $sql = 'SELECT tbl_fgd.fgd_id, tbl_fgd.fgd_quarter, tbl_fgd.fgd_year FROM tbl_fgd';

                     foreach ($pdo->query($sql) as $row) {
                              echo '
';
                              echo ''. $row['fgd_id'] . '	';
                              echo ''. $row['fgd_quarter'] . ' / ' . $row['fgd_year'] . '	';
                              echo '
                                <button class="btn btn-block center-block bg-purple btn-sm" style="width: 50%;" data-toggle="modal" data-target="#f1Modal" id="btnFormat1'. $row['fgd_id'] . '" onclick = getData("format1", '. $row['fgd_id'] . ');>View</button>

                                <button class="btn btn-block center-block bg-blue btn-sm" style="width: 50%;" data-toggle="modal" data-target="#f1Modal" id="btnFormat1'. $row['fgd_id'] . '" onclick = getData("format2", '. $row['fgd_id'] . ');>View</button>

                                <button class="btn btn-block center-block bg-green btn-sm" style="width: 50%;" data-toggle="modal" data-target="#f1Modal" id="btnFormat1'. $row['fgd_id'] . '" onclick = getData("format3", '. $row['fgd_id'] . ');>View</button>

                                <button type="text" class="btn btn-info" data-toggle="modal" data-target="#modal">Actions</button>
                                <button type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown">

                                  Toggle Dropdown
                                </button>

Add

Edit

Delete

                              	';
                              echo '
';
                     }
                     Database::disconnect();
                    ?>

            <button type="button" class="close" data-dismiss="modal">×</button>

Main Issues Discussed (Method 1)

Bgy. Morong, Mt. Kanlaon Natural Park

Bgy. Bundok

Bgy. Maahas

                              Main Topic 1

Resource uses chosen for monitoring:

Hunting of wild pigs,

hunting of wild deer,

freshwater fish catch,

use of household timber,

lobster catch.

The Group stated that hunting of wild pigs has decreased since last quarter but this
                            was attributed to seasonal changes and not to a decrease in the pig population. There
                            was no change in the number of people involved in hunting wild pigs since last quarter,
                            only normal seasonal changes. However, the number of wild pigs is still below what it
                            was in previous years. The barangay has therefore recently decided to establish a
                            closed season for hunting in December and January. Blasting of wild pigs is practised,
                            particularly in the fields, in order to prevent pigs eating the rice. There was a short
                            discussion of blasting around how to solve the fact that blasting is illegal according to
                            the law but considered important for the protection of the rice harvest. No solution
                            was found but the discussion will continue.

                            There are still very many traps. The Group discussed the need to limit the number of
                            traps; no agreement was reached within the Group but all agreed that over-hunting was
                            taking place. One of the Group members gave the example that it took 4 days to catch
                            one pig with 3 traps in the vicinity of lower Blos River.

                            All pigs are reported to have been consumed within the Barangay, with some of the pigs
                            being sold to other barangay members (should be continued with results on the other
                            resource uses, hunting of wild deer, catch of freshwater fish, use of household timber,
                            catch of lobster).

                              Main Topic 2

Resource uses chosen for monitoring:

Hunting of wild pigs,

hunting of wild deer,

freshwater fish catch,

use of household timber,

lobster catch.

The Group stated that hunting of wild pigs has decreased since last quarter but this
                            was attributed to seasonal changes and not to a decrease in the pig population. There
                            was no change in the number of people involved in hunting wild pigs since last quarter,
                            only normal seasonal changes. However, the number of wild pigs is still below what it
                            was in previous years. The barangay has therefore recently decided to establish a
                            closed season for hunting in December and January. Blasting of wild pigs is practised,
                            particularly in the fields, in order to prevent pigs eating the rice. There was a short
                            discussion of blasting around how to solve the fact that blasting is illegal according to
                            the law but considered important for the protection of the rice harvest. No solution
                            was found but the discussion will continue.

                            There are still very many traps. The Group discussed the need to limit the number of
                            traps; no agreement was reached within the Group but all agreed that over-hunting was
                            taking place. One of the Group members gave the example that it took 4 days to catch
                            one pig with 3 traps in the vicinity of lower Blos River.

                            All pigs are reported to have been consumed within the Barangay, with some of the pigs
                            being sold to other barangay members (should be continued with results on the other
                            resource uses, hunting of wild deer, catch of freshwater fish, use of household timber,
                            catch of lobster).

                              Main Topic 2

Resource uses chosen for monitoring:

Hunting of wild pigs,

hunting of wild deer,

freshwater fish catch,

use of household timber,

lobster catch.

The Group stated that hunting of wild pigs has decreased since last quarter but this
                            was attributed to seasonal changes and not to a decrease in the pig population. There
                            was no change in the number of people involved in hunting wild pigs since last quarter,
                            only normal seasonal changes. However, the number of wild pigs is still below what it
                            was in previous years. The barangay has therefore recently decided to establish a
                            closed season for hunting in December and January. Blasting of wild pigs is practised,
                            particularly in the fields, in order to prevent pigs eating the rice. There was a short
                            discussion of blasting around how to solve the fact that blasting is illegal according to
                            the law but considered important for the protection of the rice harvest. No solution
                            was found but the discussion will continue.

                            There are still very many traps. The Group discussed the need to limit the number of
                            traps; no agreement was reached within the Group but all agreed that over-hunting was
                            taking place. One of the Group members gave the example that it took 4 days to catch
                            one pig with 3 traps in the vicinity of lower Blos River.

                            All pigs are reported to have been consumed within the Barangay, with some of the pigs
                            being sold to other barangay members (should be continued with results on the other
                            resource uses, hunting of wild deer, catch of freshwater fish, use of household timber,
                            catch of lobster).

                              Main Topic 1

Resource uses chosen for monitoring:

Hunting of wild pigs,

hunting of wild deer,

freshwater fish catch,

use of household timber,

lobster catch.

The Group stated that hunting of wild pigs has decreased since last quarter but this
                            was attributed to seasonal changes and not to a decrease in the pig population. There
                            was no change in the number of people involved in hunting wild pigs since last quarter,
                            only normal seasonal changes. However, the number of wild pigs is still below what it
                            was in previous years. The barangay has therefore recently decided to establish a
                            closed season for hunting in December and January. Blasting of wild pigs is practised,
                            particularly in the fields, in order to prevent pigs eating the rice. There was a short
                            discussion of blasting around how to solve the fact that blasting is illegal according to
                            the law but considered important for the protection of the rice harvest. No solution
                            was found but the discussion will continue.

                            There are still very many traps. The Group discussed the need to limit the number of
                            traps; no agreement was reached within the Group but all agreed that over-hunting was
                            taking place. One of the Group members gave the example that it took 4 days to catch
                            one pig with 3 traps in the vicinity of lower Blos River.

                            All pigs are reported to have been consumed within the Barangay, with some of the pigs
                            being sold to other barangay members (should be continued with results on the other
                            resource uses, hunting of wild deer, catch of freshwater fish, use of household timber,
                            catch of lobster).

                              Main Topic 2

Resource uses chosen for monitoring:

Hunting of wild pigs,

hunting of wild deer,

freshwater fish catch,

use of household timber,

lobster catch.

The Group stated that hunting of wild pigs has decreased since last quarter but this
                            was attributed to seasonal changes and not to a decrease in the pig population. There
                            was no change in the number of people involved in hunting wild pigs since last quarter,
                            only normal seasonal changes. However, the number of wild pigs is still below what it
                            was in previous years. The barangay has therefore recently decided to establish a
                            closed season for hunting in December and January. Blasting of wild pigs is practised,
                            particularly in the fields, in order to prevent pigs eating the rice. There was a short
                            discussion of blasting around how to solve the fact that blasting is illegal according to
                            the law but considered important for the protection of the rice harvest. No solution
                            was found but the discussion will continue.

                            There are still very many traps. The Group discussed the need to limit the number of
                            traps; no agreement was reached within the Group but all agreed that over-hunting was
                            taking place. One of the Group members gave the example that it took 4 days to catch
                            one pig with 3 traps in the vicinity of lower Blos River.

                            All pigs are reported to have been consumed within the Barangay, with some of the pigs
                            being sold to other barangay members (should be continued with results on the other
                            resource uses, hunting of wild deer, catch of freshwater fish, use of household timber,
                            catch of lobster).

                              Main Topic 2

Resource uses chosen for monitoring:

Hunting of wild pigs,

hunting of wild deer,

freshwater fish catch,

use of household timber,

lobster catch.

The Group stated that hunting of wild pigs has decreased since last quarter but this
                            was attributed to seasonal changes and not to a decrease in the pig population. There
                            was no change in the number of people involved in hunting wild pigs since last quarter,
                            only normal seasonal changes. However, the number of wild pigs is still below what it
                            was in previous years. The barangay has therefore recently decided to establish a
                            closed season for hunting in December and January. Blasting of wild pigs is practised,
                            particularly in the fields, in order to prevent pigs eating the rice. There was a short
                            discussion of blasting around how to solve the fact that blasting is illegal according to
                            the law but considered important for the protection of the rice harvest. No solution
                            was found but the discussion will continue.

                            There are still very many traps. The Group discussed the need to limit the number of
                            traps; no agreement was reached within the Group but all agreed that over-hunting was
                            taking place. One of the Group members gave the example that it took 4 days to catch
                            one pig with 3 traps in the vicinity of lower Blos River.

                            All pigs are reported to have been consumed within the Barangay, with some of the pigs
                            being sold to other barangay members (should be continued with results on the other
                            resource uses, hunting of wild deer, catch of freshwater fish, use of household timber,
                            catch of lobster).

                              Main Topic 1

Resource uses chosen for monitoring:

Hunting of wild pigs,

hunting of wild deer,

freshwater fish catch,

use of household timber,

lobster catch.

The Group stated that hunting of wild pigs has decreased since last quarter but this
                            was attributed to seasonal changes and not to a decrease in the pig population. There
                            was no change in the number of people involved in hunting wild pigs since last quarter,
                            only normal seasonal changes. However, the number of wild pigs is still below what it
                            was in previous years. The barangay has therefore recently decided to establish a
                            closed season for hunting in December and January. Blasting of wild pigs is practised,
                            particularly in the fields, in order to prevent pigs eating the rice. There was a short
                            discussion of blasting around how to solve the fact that blasting is illegal according to
                            the law but considered important for the protection of the rice harvest. No solution
                            was found but the discussion will continue.

                            There are still very many traps. The Group discussed the need to limit the number of
                            traps; no agreement was reached within the Group but all agreed that over-hunting was
                            taking place. One of the Group members gave the example that it took 4 days to catch
                            one pig with 3 traps in the vicinity of lower Blos River.

                            All pigs are reported to have been consumed within the Barangay, with some of the pigs
                            being sold to other barangay members (should be continued with results on the other
                            resource uses, hunting of wild deer, catch of freshwater fish, use of household timber,
                            catch of lobster).

                              Main Topic 2

Resource uses chosen for monitoring:

Hunting of wild pigs,

hunting of wild deer,

freshwater fish catch,

use of household timber,

lobster catch.

The Group stated that hunting of wild pigs has decreased since last quarter but this
                            was attributed to seasonal changes and not to a decrease in the pig population. There
                            was no change in the number of people involved in hunting wild pigs since last quarter,
                            only normal seasonal changes. However, the number of wild pigs is still below what it
                            was in previous years. The barangay has therefore recently decided to establish a
                            closed season for hunting in December and January. Blasting of wild pigs is practised,
                            particularly in the fields, in order to prevent pigs eating the rice. There was a short
                            discussion of blasting around how to solve the fact that blasting is illegal according to
                            the law but considered important for the protection of the rice harvest. No solution
                            was found but the discussion will continue.

                            There are still very many traps. The Group discussed the need to limit the number of
                            traps; no agreement was reached within the Group but all agreed that over-hunting was
                            taking place. One of the Group members gave the example that it took 4 days to catch
                            one pig with 3 traps in the vicinity of lower Blos River.

                            All pigs are reported to have been consumed within the Barangay, with some of the pigs
                            being sold to other barangay members (should be continued with results on the other
                            resource uses, hunting of wild deer, catch of freshwater fish, use of household timber,
                            catch of lobster).

                              Main Topic 2

Resource uses chosen for monitoring:

Hunting of wild pigs,

hunting of wild deer,

freshwater fish catch,

use of household timber,

lobster catch.

The Group stated that hunting of wild pigs has decreased since last quarter but this
                            was attributed to seasonal changes and not to a decrease in the pig population. There
                            was no change in the number of people involved in hunting wild pigs since last quarter,
                            only normal seasonal changes. However, the number of wild pigs is still below what it
                            was in previous years. The barangay has therefore recently decided to establish a
                            closed season for hunting in December and January. Blasting of wild pigs is practised,
                            particularly in the fields, in order to prevent pigs eating the rice. There was a short
                            discussion of blasting around how to solve the fact that blasting is illegal according to
                            the law but considered important for the protection of the rice harvest. No solution
                            was found but the discussion will continue.

                            There are still very many traps. The Group discussed the need to limit the number of
                            traps; no agreement was reached within the Group but all agreed that over-hunting was
                            taking place. One of the Group members gave the example that it took 4 days to catch
                            one pig with 3 traps in the vicinity of lower Blos River.

                            All pigs are reported to have been consumed within the Barangay, with some of the pigs
                            being sold to other barangay members (should be continued with results on the other
                            resource uses, hunting of wild deer, catch of freshwater fish, use of household timber,
                            catch of lobster).

      <?php include 'templates\pasu_footer.php';?>


text:
PLUGIN_NAME=		pppoe
PLUGIN_VERSION=		1.8
PLUGIN_DEPENDS=		clog mpd5
PLUGIN_COMMENT=		End of life, no replacement
PLUGIN_MAINTAINER=	franco@opnsense.org

.include "../../Mk/plugins.mk"


text:
Inrepoconfig is a Prow feature that allows versioning Presubmit and Postsubmit
jobs in the same repository that also holds the code (with a `.prow` directory
or `.prow.yaml` file, akin to a `.travis.yaml` file). So instead of having all
your jobs defined centrally, you could instead define the jobs in a distributed
manner, coupled closely with the source code repos that they work on.

If enabled, Prow will use both the centrally-defined jobs and the ones defined
in the code repositories. The latter ones are dynamically loaded on-demand.

## Why use Inrepoconfig?

### Pros

- Coupling the jobs with the source code allows you to update both the job and
  the source code at the same time.

### Cons

- Inrepoconfig jobs are loaded on-demand, so it takes some extra setup to check
  that a misconfigured Inrepoconfig job is not blocking a PR. See "Config
  verification job" below.

## Basic usage

To enable it, add the following to your Prow's `config.yaml`:

```
in_repo_config:
  enabled:
    # The key can be one of "*" for "globally", "org" or "org/repo".
    # The narrowest match is used. Here the key is "kubernetes/kubernetes".
    kubernetes/kubernetes: true

  # Clusters must be allowed before they can be used. Here we allow the "default"
  # cluster globally. This setting also allows using "*" for "globally", "org" or "org/repo" as key.
  # All clusters that are allowed for the specific repo, its org or
  # globally can be used.
  allowed_clusters:
    "*": ["default"]
```

Additionally, `Deck` must be configured with a GitHub token if that is not already the case. To do
so, the `--github-token-path=` flag must be set and point to a valid token file that has permissions
to read all your repositories. Also, in order for Deck to serve content from storage locations not
defined in the default locations or centrally-defined jobs, those buckets must be listed
in `deck.additional_allowed_buckets`.

### Config verification job

Afterwards, you need to add a config verification job to make sure people people get told about
mistakes in their Inrepoconfig rather than the PR being stuck. It makes sense to define this
job in the central repository rather than the code repository, so the `checkconfig` version used
stays in sync with the Prow version used. It looks like this:

```
presubmits:
  kubernetes/kubernetes:
  - name: pull-kubernetes-validate-prow-yaml
    always_run: true
    decorate: true
    extra_refs:
    - org: kubernetes
      repo: test-infra
      base_ref: master
     spec:
       containers:
       - image: gcr.io/k8s-prow/checkconfig:v20191205-050b151d0
         command:
         - /app/prow/cmd/checkconfig/app.binary
         args:
         - --plugin-config=../test-infra/path/to/plugins.yaml
         - --config-path=../test-infra/path/to/config.yaml
         - --prow-yaml-repo-name=$(REPO_OWNER)/$(REPO_NAME)
```

After deploying the new config, the only step left is to create jobs. This is done by adding a file
named `.prow.yaml` to the root of the repository that holds your code:

```yaml
presubmits:
- name: pull-test-infra-yamllint
  always_run: true
  decorate: true
  spec:
    containers:
    - image: quay.io/kubermatic/yamllint:0.1
      command:
      - yamllint
      - -c
      - config/jobs/.yamllint.conf
      - config/jobs
      - config/prow/cluster

postsubmits:
- name: push-test-infra-yamllint
  always_run: true
  decorate: true
  spec:
    containers:
    - image: quay.io/kubermatic/yamllint:0.1
      command:
      - yamllint
      - -c
      - config/jobs/.yamllint.conf
      - config/jobs
      - config/prow/cluster
```

## Multiple config files

It is possible also to use multiple config files with this same format under a `.prow`
directory in the root of your repo. All the YAML files under the `.prow` directory will
be read and merged together recursively. This makes it easier to handle big repos with
a large number of jobs and allows fine-grained OWNERS control on them.

The `.prow` directory and `.prow.yaml` file are mutually exclusive; when both are present the `.prow` directory takes precedence.

For more detailed documentation of possible configuration parameters for jobs, please check the [job documentation](/prow/jobs.md)


text:
//Using loops write a program that converts a hexadecimal integer number to its decimal form.
//The input is entered as string. The output should be a variable of type long.
//Do not use the built-in .NET functionality.

using System;

class HexToDecimal
{
    static void Main()
    {
        string input = Console.ReadLine();

        long result = 0;
        long power = 1;
        for (int i = input.Length - 1; i >= 0; i--)
        {
            int number = 0;
            switch (input[i])
            {
                case 'A': number = 10; break;
                case 'B': number = 11; break;
                case 'C': number = 12; break;
                case 'D': number = 13; break;
                case 'E': number = 14; break;
                case 'F': number = 15; break;
                default: number = input[i] - '0'; break;
            }
            result += power * number;
            power *= 16;
        }
        Console.WriteLine(result);
    }
}


text:
Article 1728
----
Le preneur est tenu de deux obligations principales :

1° D'user de la chose louée raisonnablement, et suivant la destination qui lui a
été donnée par le bail, ou suivant celle présumée d'après les circonstances, à
défaut de convention ;

2° De payer le prix du bail aux termes convenus.


text:
Install python, git & build-essential (build-essential is used for pip packages build)
```sh
sudo apt-get install python python-dev python-pip python-virtualenv git build-essential
```
Install requested libraries for pip
```sh
sudo apt-get install libffi-dev libssl-dev libav-tools
```
Install nginx & uWSGI which will be used to serve the python app
```sh
apt-get install nginx uwsgi uwsgi-plugin-python
```
Create a directory for the app (example: /home/pi/alexa_youtube)
```sh
mkdir /home/pi/alexa_youtube
# & change to that directory
cd /home/pi/alexa_youtube
```
Clone this repo in that directory (don't forget the last "." from this command to avoid creating a new directory)
```sh
git clone <repo_url> .
```
Go to [Google Developers console](https://console.developers.google.com/apis/credentials) and create a new app there (give it any name you like it doesn't matter). On the newly created app, go to `credentials` page and generate `Api Key` credentials. Copy the generated api key and paste it into `alexa/config.ini` file as the `api_key`
```sh
# open the file with pico and replace <api_key> with your api_key and <domain_name> with your domain
# for example, if you domain is example.com, replace <domain_name> with https://example.com
pico alexa/config.ini
# press ctrl + x, y and enter to save and close pico
```

Install python requirements and wait for this to finish. This could take a long time
```sh
pip install -r requirements.txt
```

## Configure uWSGI & nginx
The following commands are run as `pi` user on the raspberry pi.

### uWsgi Part
```sh
# change directory to uWSGI service
cd /etc/uwsgi/apps-available
# copy the file from helper/uWsgi/alexa.ini into that directory
sudo cp /home/pi/alexa_youtube/helper/uWsgi/alexa.ini ./
# change the file to resemble the location of your app
sudo pico alexa.ini
# change chdir = /home/pi/alexa_youtube
# if is not already this path
# press ctrl + x, y and enter to save and close pico
# create symlink to /etc/uwsgi/apps-enabled
cd ../apps-enabled
sudo ln -s ../apps-available/alexa.ini ./
# restart uWSGI
sudo /etc/init.d/uwsgi restart
```
### Nginx Part
```sh
# change directory to nginx
cd /etc/nginx/sites-available
# copy the file from helper/nginx/alexa into that directory
sudo cp /home/pi/alexa_youtube/helper/nginx/alexa ./
# change the server_name to your own domain
sudo pico alexa
# press ctrl + x, y and enter to save and close pico
# create symlink to /etc/nginx/sites-enabled
cd ../sites-enabled
sudo ln -s ../sites-available/alexa ./
# restart nginx
sudo /etc/init.d/nginx restart
```
If all the steps above are successfully, you can see your application up and running on your custom domain set in nginx `server_name`

# Amazon Part
In order for this skill to be available in alexa, you need to add it. Login into [Alexa Amazon Developers](https://developer.amazon.com/edw/home.html#/skills/list) website with the same credentials logged on you `echo dot`.

### Skill Information

- From the top right corner on Alexa skills kit page, click on `Add a New Skill`
- Check `Custom Interaction Model` on `Skill Type`
- Set the language to `English (U.S.)`
- Set the `Name` to whatever you want
- `Invocation Name` must be the word that Alexa uses when referees to your skill (if you choose, for example, `Pie` you will need to say to Alexa: `Ask pie to play <song from youtube>`
- Set `Audio Player` to `Yes`

### Interaction Model

- In `Intent Schema` add the content of the file `helper/amazon/intent.json` into the field
- In `Sample Utterances` add the content of the file `helper/amazon/utterance.txt` into the field
- Click `Save`
The interaction model will be build but you can continue with the next step

### Configuration

- Set `HTTPS` for `Service Endpoint Type`
- Choose `Europe` or `North America` which is close to your location
- Add the url of you domain setted in nginx `server_name` config file and append `/alexa` at the end and `https://` before (For example, if your domain is `example.com`, insert `https://example.com/alexa` into the field.
- Set `Account Linking` to `No`

### SSL Certificate

- Choose the second option: `My development endpoint is a sub-domain of a domain that has a wildcard certificate from a certificate authority `

### Publishing Information & Privacy & Compliance

Don`t check anything on this steps, we will not publish this, you are done :)


text:
<component name="libraryTable">
  <library name="transition-25.1.0">
    <CLASSES>
      <root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support/transition/25.1.0/jars/classes.jar!/" />
      <root url="file://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support/transition/25.1.0/res" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="jar:///run/media/pandax/E42409CB2409A1A2/Android_linux/extras/android/m2repository/com/android/support/transition/25.1.0/transition-25.1.0-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
//
//  PMPersistentObject.h
//  Created by Joan Martin.
//  Take a look to my repos at http://github.com/vilanovi
//
// Copyright (c) 2013 Joan Martin, vilanovi@gmail.com.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

#import <Foundation/Foundation.h>

/**
 * Persistent objects must implement this protocol to adopt the required schema: `key` (String), `type` (String), `lastUpdate` (Date) and `data` (BLOB).
 **/
@protocol PMPersistentObject <NSObject>

/**
 * Used to identify the model object.
 **/
@property (nonatomic, readonly) NSString *key;

/**
 * Used to identify the type of the model object.
 **/
@property (nonatomic, readonly) NSString *type;

/**
 * Used to retrieve the last update of the model object.
 **/
@property (nonatomic) NSDate *lastUpdate;

/**
 * Used to store the model object data.
 **/
@property (nonatomic) NSData *data;

@end


text:
namespace NPSharp.Master.Data
{
    /// <summary>
    ///     Represents keywords for a master server standard serverlist request.
    /// </summary>
    public enum MasterGetServersKeywords
    {
        Full = 0x01,
        Empty = 0x02
    }
}


text:
"""Abstract interfaces implemented by the different datastores."""
from __future__ import absolute_import
from __future__ import print_function

import abc
import array
import codecs
import enum
import itertools
import json
import math
import re
import threading

class Error(Exception):
    """Base class for all exceptions from this module."""

class RetryableError(Error):
    """Errors accessing Cassandra that could succeed if retried."""

class InvalidArgumentError(Error):
    """Callee did not follow requirements on the arguments."""

_UTF8_CODEC = codecs.getencoder('utf8')

_NAN = float("nan")

def _wait_async_call(async_function, *args, **kwargs):
    """Call async_function and synchronously wait for it to be done.

    Args:
      async_function: Function taking a on_done(e=None:Exception) callback.
      *args: Passed down to async_function
      **kwargs: Passed down to async_function
    """
    event = threading.Event()
    exception_box = [None]

    def on_done(exception):
        exception_box[0] = exception
        event.set()

    async_function(*args, on_done=on_done, **kwargs)
    event.wait()
    if exception_box[0]:
        raise exception_box[0]

def encode_metric_name(name):
    """Encode name as utf-8, raise UnicodeError if it can't.

    Args:
      name: The metric to encode, must be an instance of basestring.
        If it is an instance of string, it will be assumed to already have been
        encoded for performance reasons.

    Raises:
      UnicodeError: Couldn't encode.
    """
    if isinstance(name, str):
        return name
    # Next line may raise UnicodeError
    return _UTF8_CODEC(name)[0]

def round_down(rounded, divider):
    """Round down an integer to a multiple of divider."""
    return int(rounded) // divider * divider

def round_up(rounded, divider):
    """Round up an integer to a multiple of divider."""
    return int(rounded + divider - 1) // divider * divider

@enum.unique
class Aggregator(enum.Enum):
    """Represents one of the known aggregations.

    Name is BigGraphite name, chosen to avoid conflicts with Python's builtins.
    Value is Whisper name.
    """

    minimum = "min"
    maximum = "max"
    total = "sum"
    average = "average"
    last = "last"
    # TODO: Add avg_zero.

    def __init__(self, carbon_name):
        """Set attributes."""
        self.carbon_name = carbon_name
        self._downsample = getattr(self, "_downsample_" + self.name)
        self._merge = getattr(self, "_merge_" + self.name)

    def merge(self, values=[], counts=[], newest_first=False):
        """Merge aggregated values from a similar stage.

        Args:
          values: values to aggregate as float from oldest to most recent (unless
            newest_first is True).
          counts: counts associated with values as int.  when dealing with
            already aggregated values.
          newest_first: if True, values are in reverse order.

        Returns:
          The merged values and counts, NaN if values is empty or all values are NaN.
        """
        if not values:
            return _NAN
        if not counts:
            counts = [1] * len(values)
        return self._merge(values, counts, newest_first)

    def _merge_average(self, values, counts, values_newest_first):
        # Averages are simply sum+count. The actual average is computed
        # only during reads by dividing sum by count.
        total, count = self.__sum_and_count(values, counts)
        return total, count

    def _merge_last(self, values, counts, values_newest_first):
        if not values_newest_first:
            values = reversed(values)
        for v in values:
            if not math.isnan(v):
                return v, sum(counts)
        return _NAN, sum(counts)

    def _merge_maximum(self, values, counts, values_newest_first):
        _, maximum = self.__min_and_max(values)
        return maximum, sum(counts)

    def _merge_minimum(self, values, counts, values_newest_first):
        minimum, _ = self.__min_and_max(values)
        return minimum, sum(counts)

    def _merge_total(self, values, counts, values_newest_first):
        total, count = self.__sum_and_count(values, counts)
        return total, count

    def downsample(self, values=[], counts=[], newest_first=False):
        """Aggregate together values of a given stage.

        Args:
          values: values to aggregate as float from oldest to most recent (unless
            newest_first is True).
          counts: counts associated with values as int.  when dealing with
            already aggregated values.
          newest_first: if True, values are in reverse order.

        Returns:
          The downsampled value, NaN if values is empty or all values are NaN.
        """
        if not values:
            return _NAN
        if not counts:
            counts = [1] * len(values)
        return self._downsample(values, counts, newest_first)

    def _downsample_average(self, values, counts, values_newest_first):
        total, count = self.__sum_and_count(values, counts)
        return total / count

    def _downsample_last(self, values, counts, values_newest_first):
        if not values_newest_first:
            values = reversed(values)
        for v in values:
            if not math.isnan(v):
                return v
        return _NAN

    def _downsample_maximum(self, values, counts, values_newest_first):
        _, maximum = self.__min_and_max(values)
        return maximum

    def _downsample_minimum(self, values, counts, values_newest_first):
        minimum, _ = self.__min_and_max(values)
        return minimum

    def _downsample_total(self, values, counts, values_newest_first):
        total, _ = self.__sum_and_count(values, counts)
        return total

    @classmethod
    def from_carbon_name(cls, name):
        """Make an instance from a carbon-like name."""
        if not name:
            return None
        try:
            return cls(name)
        except ValueError:
            raise InvalidArgumentError("Unknown carbon aggregation: %s" % name)

    @classmethod
    def from_config_name(cls, name):
        """Make an instance from a BigGraphite name."""
        if not name:
            return None
        try:
            return cls[name]
        except KeyError:
            raise InvalidArgumentError("Unknown BG aggregator: %s" % name)

    @staticmethod
    def __sum_and_count(values, counts):
        total = 0.0
        count = 0
        for v, c in itertools.izip(values, counts):
            if math.isnan(v):
                continue
            total += v
            count += c
        if not count:
            return _NAN, _NAN
        return total, count

    @staticmethod
    def __min_and_max(values):
        minimum = None
        maximum = None
        for v in values:
            if math.isnan(v):
                continue
            if minimum is None:
                maximum = v
                minimum = v
            elif maximum < v:
                maximum = v
            elif minimum > v:
                minimum = v
        if minimum is None:
            assert maximum is None
            return _NAN, _NAN
        return minimum, maximum

class Stage(object):
    """One of the element of a retention policy.

    A stage means "keep that many points with that precision".
    Precision is the amount of time a point covers, measured in seconds.
    """

    __slots__ = ("duration", "points", "precision", )

    # Parses the values of as_string into points and precision group
    _STR_RE = re.compile(r"^(?P<points>[\d]+)\*(?P<precision>[\d]+)s$")

    def __init__(self, points, precision):
        """Set attributes."""
        self.points = int(points)
        self.precision = int(precision)
        self.duration = self.points * self.precision

    def __str__(self):
        return self.as_string

    def __repr__(self):
        return '<{0}.{1}({3}) object at {2}>'.format(
            self.__module__, type(self).__name__, hex(id(self)),
            self.as_string)

    def __eq__(self, other):
        if not isinstance(other, Stage):
            return False
        return self.points == other.points and self.precision == other.precision

    def __ne__(self, other):
        return not (self == other)

    def __hash__(self):
        return hash((self.points, self.precision))

    @property
    def as_string(self):
        """A string like "${POINTS}*${PRECISION}s"."""
        return "{}*{}s".format(self.points, self.precision)

    @property
    def duration_ms(self):
        """The duration in milliseconds."""
        return self.duration * 1000

    def epoch(self, timestamp):
        """Return time elapsed since Unix epoch in count of self.duration.

        A "stage epoch" is a range of timestamps: [N*stage_duration, (N+1)*stage_duration[
        This function returns N.

        Args:
          timestamp: A timestamp in seconds.
        """
        return int(timestamp // self.duration)

    @classmethod
    def from_string(cls, s):
        """Parse results of as_string into an instance."""
        match = cls._STR_RE.match(s)
        if not match:
            raise InvalidArgumentError("Invalid retention: '%s'" % s)
        groups = match.groupdict()
        return cls(
            points=int(groups['points']),
            precision=int(groups['precision']),
        )

    @property
    def precision_ms(self):
        """The precision of this stage in milliseconds."""
        return self.precision * 1000

    def round_down(self, timestamp):
        """Round down a timestamp to a multiple of the precision."""
        return round_down(timestamp, self.precision)

    def round_up(self, timestamp):
        """Round down a timestamp to a multiple of the precision."""
        return round_up(timestamp, self.precision)

    def step(self, timestamp):
        """Return time elapsed since Unix epoch in count of self.precision.

        A "stage step" is a range of timestamps: [N*stage_precision, (N+1)*stage_precision[
        This function returns N.

        Args:
          timestamp: A timestamp in seconds.
        """
        return int(timestamp // self.precision)

    def step_ms(self, timestamp_ms):
        """Return time elapsed since Unix epoch in count of self.precision_ms.

        A "stage step" is a range of timestamps: [N*stage_precision, (N+1)*stage_precision[
        This function returns N.

        Args:
          timestamp_ms: A timestamp in milliseconds.
        """
        return int(timestamp_ms // self.precision_ms)

class Retention(object):
    """A retention policy, made of 0 or more Stages."""

    __slots__ = ("stages", )

    def __init__(self, stages):
        """Set self.stages ."""
        prev = None
        if not stages:
            raise InvalidArgumentError("there must be at least one stage")
        for s in stages:
            if prev and s.precision % prev.precision:
                raise InvalidArgumentError("precision of %s must be a multiple of %s" % (s, prev))
            if prev and prev.duration >= s.duration:
                raise InvalidArgumentError("duration of %s must be lesser than %s" % (s, prev))
            prev = s
        self.stages = tuple(stages)

    def __getitem__(self, n):
        """Return the n-th stage."""
        return self.stages[n]

    def __hash__(self):
        return hash(self.stages)

    def __eq__(self, other):
        if not isinstance(other, Retention):
            return False
        return self.stages == other.stages

    def __ne__(self, other):
        return not (self == other)

    @property
    def as_string(self):
        """Return strings like "60*60s:24*3600s"."""
        return ":".join(s.as_string for s in self.stages)

    @classmethod
    def from_string(cls, string):
        """Parse results of as_string into an instance.

        Args:
          string: A string like "60*60s:24*3600s"
        """
        if string:
            stages = [Stage.from_string(s) for s in string.split(":")]
        else:
            stages = []
        return cls(stages=stages)

    @property
    def duration(self):
        """Return the maximum duration of all stages."""
        if not self.stages:
            return 0
        return self.stages[-1].duration

    @property
    def downsampled_stages(self):
        """An alias for stages[1:]."""
        return self.stages[1:]

    @classmethod
    def from_carbon(cls, l):
        """Make new instance from list of (precision, points).

        Note that precision is first, unlike in Stage.__init__
        """
        stages = [Stage(points=points, precision=precision)
                  for precision, points in l]
        return cls(stages)

    def find_stage_for_ts(self, searched, now):
        """Return the most precise stage that contains "searched".

        Args:
          searched: A timestamp to search, in seconds.
          now: The current timestamp, in seconds.
        """
        for stage in self.stages:
            if searched > now - stage.duration:
                return stage
        # There is always at least one stage.
        return self.stages[-1]

class MetricMetadata(object):
    """Represents all information about a metric except its name.

    Not meant to be mutated.
    """

    __slots__ = (
        "aggregator",
        "retention",
        "carbon_xfilesfactor",
    )

    _DEFAULT_AGGREGATOR = Aggregator.average
    _DEFAULT_RETENTION = Retention.from_string("86400*1s:10080*60s")
    _DEFAULT_XFILESFACTOR = 0.5

    def __init__(self, aggregator=None, retention=None, carbon_xfilesfactor=None):
        """Record its arguments."""
        self.aggregator = aggregator or self._DEFAULT_AGGREGATOR
        assert isinstance(self.aggregator, Aggregator), self.aggregator
        self.retention = retention or self._DEFAULT_RETENTION
        if carbon_xfilesfactor is None:
            self.carbon_xfilesfactor = self._DEFAULT_XFILESFACTOR
        else:
            self.carbon_xfilesfactor = carbon_xfilesfactor

    def __setattr__(self, name, value):
        # carbon_xfilesfactor is the last attribute __init__ sets.
        if hasattr(self, "carbon_xfilesfactor"):
            raise AttributeError("can't set attribute")
        super(MetricMetadata, self).__setattr__(name, value)

    def as_json(self):
        """Serialize MetricMetadata into a JSon string from_json() can parse."""
        return json.dumps(self.as_string_dict())

    def as_string_dict(self):
        """Turn an instance into a dict of string to string."""
        return {
            "aggregator": self.aggregator.name,
            "retention": self.retention.as_string,
            "carbon_xfilesfactor": "%f" % self.carbon_xfilesfactor,
        }

    @classmethod
    def from_json(cls, s):
        """Parse MetricMetadata from a JSon string produced by as_json()."""
        return cls.from_string_dict(json.loads(s))

    @classmethod
    def from_string_dict(cls, d):
        """Turn a dict of string to string into a MetricMetadata."""
        return cls(
            aggregator=Aggregator.from_config_name(d.get("aggregator")),
            retention=Retention.from_string(d.get("retention")),
            carbon_xfilesfactor=float(d.get("carbon_xfilesfactor")),
        )

class Metric(object):
    """Represents all information about a metric.

    This is not an instance of MetricMetadata: It cannot be serialized
    in JSON to minimise confusion in cache that expects few possible
    Metadata at any time.

    Not meant to be mutated.
    """

    __slots__ = (
        "name",
        "id",
        "metadata"
    )

    def __init__(self, name, id, metadata):
        """Record its arguments."""
        super(Metric, self).__init__()
        assert name, "Metric: name is None"
        assert id, "Metric: id is None"
        assert metadata, "Metric: metadata is None"
        self.name = encode_metric_name(name)
        self.id = id
        self.metadata = metadata

    def __getattr__(self, name):
        return getattr(self.metadata, name)

    def __dir__(self):
        res = dir(self.metadata)
        res.extend(self.__slots__)
        res.sort()
        return res

class Accessor(object):
    """Provides Read/Write accessors to BigGraphite.

    It is safe to fork() or start new process until connect() has been called.
    It is not safe to share a given accessor across threads.

    Calling other methods before connect() will raise NotConnectedError, unless
    noted otherwise.
    """

    __slots__ = ('is_connected', )

    __metaclass__ = abc.ABCMeta

    def __init__(self, backend_name):
        """Set internal variables."""
        self.backend_name = backend_name
        self.is_connected = False

    def __enter__(self):
        """Call connect()."""
        self.connect()
        return self

    def __exit__(self, _type, _value, _traceback):
        """Call shutdown()."""
        self.shutdown()
        return False

    @abc.abstractmethod
    def connect(self, skip_schema_upgrade=False):
        """Establish a connection, idempotent.

        This must be called AFTER creating subprocess with the multiprocessing module.
        """
        pass

    @abc.abstractmethod
    def create_metric(self, metric):
        """Create a metric from its definition as a Metric object.

        Parent directories are implicitly created.
        This can be expensive, it is worthwile to first check if the metric exists.

        Args:
          metric: definition as a Metric object.
        """
        if not isinstance(metric, Metric):
            raise InvalidArgumentError("%s is not a Metric instance" % metric)
        self._check_connected()

    def _check_connected(self):
        if not self.is_connected:
            raise Error("Accessor's connect() wasn't called")

    @abc.abstractmethod
    def drop_all_metrics(self):
        """Delete all metrics from the database."""
        self._check_connected()

    @abc.abstractmethod
    def fetch_points(self, metric, time_start, time_end, stage):
        """Fetch points from time_start included to time_end excluded.

        Args:
          metric: The metric definition as per get_metric.
          time_start: timestamp in seconds from the Unix Epoch as an int, inclusive,
            must be a multiple of stage.precision
          time_end: timestamp in seconds from the Unix Epoch as an int, exclusive,
            must be a multiple of stage.precision
          stage: the retention stage at which to fetch data

        Yields:
          pairs of (timestamp, value) to indicate value is an aggregate for the range
          [timestamp, timestamp+stage.precision[

        Raises:
          InvalidArgumentError: if time_start or time_end are not as per above
        """
        if not isinstance(metric, Metric):
            raise InvalidArgumentError("%s is not a Metric instance" % metric)
        if not isinstance(stage, Stage):
            raise InvalidArgumentError("%s is not a Stage instance" % stage)
        if time_start % stage.precision or time_start < 0:
            raise InvalidArgumentError(
                "time_start (%d) is not a multiple of the stage's precision (%s)" % (
                    time_start, stage.as_string))
        if time_end % stage.precision or time_end < 0:
            raise InvalidArgumentError(
                "time_end (%d) is not a multiple of the stage's precision (%s)" % (
                    time_end, stage.as_string))

    @abc.abstractmethod
    def has_metric(self, metric_name):
        """Return a True if this metric exists, else return False."""
        self._check_connected()

    @abc.abstractmethod
    def get_metric(self, metric_name):
        """Return a Metric for this metric_name, None if no such metric."""
        self._check_connected()

    @abc.abstractmethod
    def make_metric(self, name, metadata):
        """Create a Metric object from its definition as name and metadata.

        Args:
          name: metric name.
          metadadata: metric metadata.

        Returns: a Metric object with a valid id.
        """

    @abc.abstractmethod
    def glob_metric_names(self, glob):
        """Return a sorted list of metric names matching this glob."""
        self._check_connected()

    @abc.abstractmethod
    def glob_directory_names(self, glob):
        """Return a sorted list of metric directories matching this glob."""
        self._check_connected()

    def insert_points(self, metric, datapoints):
        """Insert points for a given metric.

        Args:
          metric: A Metric instance.
          datapoints: An iterable of (timestamp in seconds, values as double)
        """
        self._check_connected()
        _wait_async_call(self.insert_points_async, metric=metric, datapoints=datapoints)

    @abc.abstractmethod
    def insert_points_async(self, metric, datapoints, on_done=None):
        """Insert points for a given metric.

        Args:
          metric: The metric definition as per get_metric.
          downsampled: An iterable of (timestamp in seconds, values as double)
          on_done(e: Exception): called on done, with an exception or None if succesfull
        """
        if not isinstance(metric, Metric):
            raise InvalidArgumentError("%s is not a Metric instance" % metric)
        self._check_connected()

    def insert_downsampled_points(self, metric, downsampled):
        """Insert points for a given metric.

        Args:
          metric: The metric definition as per get_metric.
          downsampled: An iterable of (timestamp in seconds, values as double, count as int, stage)
        """
        self._check_connected()
        _wait_async_call(
            self.insert_downsampled_points_async, metric=metric, downsampled=downsampled)

    @abc.abstractmethod
    def insert_downsampled_points_async(self, metric, downsampled, on_done=None):
        """Insert points for a given metric.

        Args:
          metric: The metric definition as per get_metric.
          downsampled: An iterable of (timestamp in seconds, values as double, count as int, stage)
          on_done(e: Exception): called on done, with an exception or None if succesfull
        """
        if not isinstance(metric, Metric):
            raise InvalidArgumentError("%s is not a Metric instance" % metric)
        self._check_connected()

    @abc.abstractmethod
    def repair(self, start_key=None, end_key=None, shard=0, nshards=1):
        """Repair potential corruptions in the database.

        This operation can potentially be very slow.

        During the repair the keyspace is split in nshards and
        this function will only take car of 1/n th of the data
        as specified by shard. This allows the caller to parallelize
        the repair if needed.

        Args:
          start_key: string, start at key >= start_key.
          end_key: string, stop at key < end_key.
          shard: int, shard to repair.
          nshards: int, number of shards.
        """
        assert shard >= 0
        assert nshards > 0
        assert shard < nshards
        self._check_connected()

    @abc.abstractmethod
    def shutdown(self):
        """Close the connection.

        This is safe to call even if connect() was never called.
        """
        pass

class PointGrouper(object):
    """Helper for client-side aggregator.

    It hardcodes a knowledge of how Casssandra results are returned together, this should be
    abstracted away if more datastores do client-side agregation.
    """

    def __init__(self, metric, time_start_ms, time_end_ms, stage, query_results):
        """Constructor for PointGrouper.

        Args:
          metric: The metric for which to group values.
          time_start_ms: timestamp in second from the Epoch as an int,
            inclusive,  must be a multiple of stage.precision
          time_end_ms: timestamp in second from the Epoch as an int,
            exclusive, must be a multiple of stage.precision
          stage: the retention stage we are producing points for
          query_results: query results to fetch values from.
        """
        self.metric = metric
        self.time_start_ms = time_start_ms
        self.time_end_ms = time_end_ms
        self.stage = stage
        self.query_results = query_results

        self.current_values = array.array("d")
        self.current_counts = array.array("l")
        self.current_timestamp_ms = None

    def __iter__(self):
        return self.generate_values()

    def run_aggregator(self):
        """Aggregate values in current_values.

        This will skip the first point and return (None, None)
        if the function doesn't generate any aggregated point.
        """
        # This is the first point we encounter, do not emit it on its own,
        # rather wait until we have found values fitting in the next period.
        ret = (None, None)
        if self.current_timestamp_ms is None:
            return ret
        aggregate = self.metric.metadata.aggregator.downsample(
            values=self.current_values,
            counts=self.current_counts,
            newest_first=True,
        )
        if aggregate is not None:
            ret = (self.current_timestamp_ms / 1000.0, aggregate)
            del self.current_values[:]
            del self.current_counts[:]
        return ret

    def generate_values(self):
        """Generator function, consume query_results and produce values."""
        first_exc = None

        # TODO: This function is still quite Cassandra Specific.
        for successful, rows_or_exception in self.query_results:
            if first_exc:
                # A query failed, we still consume the results
                continue
            if not successful:
                first_exc = rows_or_exception
            for row in rows_or_exception:
                # row is (time_start_ms, offset, value, count)
                timestamp_ms = row.time_start_ms + row.offset * self.stage.precision_ms

                assert timestamp_ms >= self.time_start_ms
                assert timestamp_ms < self.time_end_ms
                timestamp_ms = round_down(timestamp_ms, self.stage.precision_ms)

                if self.current_timestamp_ms != timestamp_ms:
                    ts, point = self.run_aggregator()
                    if ts is not None:
                        yield (ts, point)

                    self.current_timestamp_ms = timestamp_ms

                self.current_values.append(row.value)
                self.current_counts.append(row.count)

        ts, point = self.run_aggregator()
        if ts is not None:
            yield (ts, point)

        if first_exc:
            raise RetryableError(first_exc)