text:
namespace rpixel {

/// Macro for referencing flags
#define FLAG(name) FLAGS_##name

/// Macros for declaring flags
#define DECLARE_bool(name) extern bool FLAG(name)
#define DECLARE_uint16(name) extern uint16 FLAG(name)
#define DECLARE_int32(name) extern int32 FLAG(name)
#define DECLARE_float(name) extern float FLAG(name)
#define DECLARE_double(name) extern double FLAG(name)
#define DECLARE_string(name) extern std::string FLAG(name)

/// Macros for defining flags
#define DEFINE_bool(name, def_val, doc) bool FLAG(name)          = (def_val)
#define DEFINE_uint16(name, def_val, doc) uint16 FLAG(name)      = (def_val)
#define DEFINE_int32(name, def_val, doc) int32 FLAG(name)        = (def_val)
#define DEFINE_float(name, def_val, doc) float FLAG(name)        = (def_val)
#define DEFINE_double(name, def_val, doc) double FLAG(name)      = (def_val)
#define DEFINE_string(name, def_val, doc) std::string FLAG(name) = (def_val)

namespace base {

/// Parses |str| for a 16-bit unsigned integer and writes the result to |value|,
/// if successful.
bool ParseUInt16(const std::string &src, const char *str, uint16 *value);

/// Parses |str| for a 32-bit signed integer and writes the result to |value|,
/// if successful.
bool ParseInt32(const std::string &src, const char *str, int32 *value);

/// Parses a string for a bool flag in the form of '--flag=value' or '--flag'.
/// In the former case, the value is taken as true, as long as it does not start
/// with '0', 'f', or 'F'. In the latter case, the value is taken as true.
bool ParseBoolFlag(const char *str, const char *flag, bool *value);

/// Parses a string for an int32 flag, in the form of '--flag=value'.
/// On success it stores the value of the flag in |value|.
bool ParseInt32Flag(const char *str, const char *flag, int32 *value);

/// Parses a string for an uint16 flag, in the form of '--flag=value'.
/// On success it stores the value of the flag in |value|.
bool ParseUInt16Flag(const char *str, const char *flag, uint16 *value);

/// Parses a string for a double flag, in the form of '--flag=value'.
/// On success it stores the value of the flag in |value|.
bool ParseDoubleFlag(const char *str, const char *flag, double *value);

/// Parses a string for a string flag, in the form of '--flag=value'.
/// On success it stores the value of the flag in |value|.
bool ParseStringFlag(const char *str, const char *flag, std::string *value);

/// Returns true, if the string matches the |flag|.
bool IsFlag(const char *str, const char *flag);
}
}

#endif // RPIXEL_CMDLINE_FLAGS_H


text:
package org.apache.derby.impl.sql.execute;

import org.apache.derby.shared.common.error.StandardException;
import org.apache.derby.iapi.sql.Activation;
import org.apache.derby.iapi.sql.conn.LanguageConnectionContext;
import org.apache.derby.iapi.sql.depend.DependencyManager;
import org.apache.derby.iapi.sql.dictionary.DataDictionary;
import org.apache.derby.iapi.sql.dictionary.SequenceDescriptor;
import org.apache.derby.iapi.sql.dictionary.SchemaDescriptor;
import org.apache.derby.iapi.store.access.TransactionController;
import org.apache.derby.shared.common.reference.SQLState;

/**
 * This class  describes actions that are ALWAYS performed for a
 * DROP SEQUENCE Statement at Execution time.
 */

class DropSequenceConstantAction extends DDLConstantAction {

    private final String sequenceName;
    private final SchemaDescriptor schemaDescriptor;

    // CONSTRUCTORS

    /**
     * Make the ConstantAction for a DROP SEQUENCE statement.
     *
     * @param sequenceName sequence name to be dropped
     */
    DropSequenceConstantAction(SchemaDescriptor sd, String sequenceName) {
        this.sequenceName = sequenceName;
        this.schemaDescriptor = sd;
    }

    ///////////////////////////////////////////////
    //
    // OBJECT SHADOWS
    //
    ///////////////////////////////////////////////

    public String toString() {
        // Do not put this under SanityManager.DEBUG - it is needed for
        // error reporting.
        return "DROP SEQUENCE " + sequenceName;
    }

    // INTERFACE METHODS

    /**
     * This is the guts of the Execution-time logic for DROP SEQUENCE.
     *
     * @see org.apache.derby.iapi.sql.execute.ConstantAction#executeConstantAction
     */
    public void executeConstantAction(Activation activation)
            throws StandardException {
        LanguageConnectionContext lcc =
                activation.getLanguageConnectionContext();
        DataDictionary dd = lcc.getDataDictionary();
        TransactionController tc = lcc.getTransactionExecute();

        /*
        ** Inform the data dictionary that we are about to write to it.
        ** There are several calls to data dictionary "get" methods here
        ** that might be done in "read" mode in the data dictionary, but
        ** it seemed safer to do this whole operation in "write" mode.
        **
        ** We tell the data dictionary we're done writing at the end of
        ** the transaction.
        */
        dd.startWriting(lcc);
        dd.clearSequenceCaches();

        SequenceDescriptor sequenceDescriptor = dd.getSequenceDescriptor(schemaDescriptor, sequenceName);

        if (sequenceDescriptor == null) {

            throw StandardException.newException(SQLState.LANG_OBJECT_NOT_FOUND_DURING_EXECUTION, "SEQUENCE",
                    (schemaDescriptor.getObjectName() + "." + sequenceName));
        }

        sequenceDescriptor.drop(lcc);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package uk.co.blackpepper.common.model;

public interface Identifiable<T> {

	T getId();

	void setId(T identifier);
}


text:
// Requires for Pebble.js modules
var UI = require('ui');
var Vibe = require('ui/vibe');

// Requires for our own custom modules
var config = require('./config');
var locationView = require('./location-view');
var previousLocationsView = require('./previous-locations-view');
var workingView = require('./working-view');
var aboutView = require('./about-view');
var ajaxLocations = require('./ajax-locations');
var geolocation = require('./geolocation');

// Create main menu
var main = new UI.Menu({
	fullscreen: config.fullscreen,
	sections: [{
		title: "Where?",
		items: [{
			title: 'Where Am I?',
			icon: 'images/mapPinDithered28.png',
			subtitle: 'Current location'
		}, {
			title: 'Where Was I?',
			icon: 'images/plainGlobe_small.png',
			subtitle: 'Previous locations'
		}, {
			title: 'About',
			icon: 'images/bluemixGlobe_small.png',
			subtitle: 'Info about the app'
		}]
	}]
});

// Show the main menu
main.show();

// Add select handler for main menu
main.on('select', function(e) {
	if (e.sectionIndex === 0) {
		if (e.itemIndex === 0) {
			// Where am I?
			handleCurrentLocation();
		} else if (e.itemIndex === 1) {
			// Where Was I?
			handlePreviousLocations();
		} else {
			// About
			handleAbout();
		}
	}
});

function handleCurrentLocation() {
	// Show indication to user we're retrieving data
	workingView.show(true);

	// Get current position, and if that is successful send it to server
	geolocation.getPosition(function(err, results) {
		if (!err) {
			ajaxLocations.postLocation(results, function(postErr, postResults) {
				if (postResults && !postErr) {
					// We've gotten good results, so hide the working indicator
					workingView.show(false);

					// Put the data on the screen
					locationView.show(postResults);

					// Send a long vibration
					Vibe.vibrate('long');
				}
			});
		}
	});
}

function handlePreviousLocations() {
	// Show indication to user we're retrieving data
	workingView.show(true);

	ajaxLocations.getLocations(function(err, results) {
		if (!err) {
			// We've gotten good results, so hide the working indicator
			workingView.show(false);

			// Put the data on the screen
			previousLocationsView.show(results);

			// Send a long vibration
			Vibe.vibrate('long');
		}
	});
}

function handleAbout() {
	aboutView.show();
}


text:
require 'spec_helper'

describe 'responseModel' do
  include_context 'this api'

  def app
    ThisApi::ResponseModelApi
  end

  subject do
    get '/swagger_doc/something'
    JSON.parse(last_response.body)
  end

  it 'documents index action' do
    expect(subject['paths']['/something']['get']['responses']).to eq(
      '200' => {
        'description' => 'OK',
        'schema' => {
          'type' => 'array',
          'items' => { '$ref' => '#/definitions/ThisApi_Entities_Something' }
        }
      }
    )
  end

  it 'should document specified models as show action' do
    expect(subject['paths']['/something/{id}']['get']['responses']).to eq(
      '200' => {
        'description' => 'OK',
        'schema' => { '$ref' => '#/definitions/ThisApi_Entities_Something' }
      },
      '403' => {
        'description' => 'Refused to return something',
        'schema' => { '$ref' => '#/definitions/ThisApi_Entities_Error' }
      }
    )
    expect(subject['definitions'].keys).to include 'ThisApi_Entities_Error'
    expect(subject['definitions']['ThisApi_Entities_Error']).to eq(
      'type' => 'object',
      'description' => 'This returns something or an error',
      'properties' => {
        'code' => { 'type' => 'string', 'description' => 'Error code' },
        'message' => { 'type' => 'string', 'description' => 'Error message' }
      }
    )

    expect(subject['definitions'].keys).to include 'ThisApi_Entities_Something'
    expect(subject['definitions']['ThisApi_Entities_Something']).to eq(
      'type' => 'object',
      'description' => 'This returns something',
      'properties' =>
          { 'text' => { 'type' => 'string', 'description' => 'Content of something.' },
            'colors' => { 'type' => 'array', 'items' => { 'type' => 'string' }, 'description' => 'Colors' },
            'kind' => { '$ref' => '#/definitions/ThisApi_Entities_Kind', 'description' => 'The kind of this something.' },
            'kind2' => { '$ref' => '#/definitions/ThisApi_Entities_Kind', 'description' => 'Secondary kind.' },
            'kind3' => { '$ref' => '#/definitions/ThisApi_Entities_Kind', 'description' => 'Tertiary kind.' },
            'tags' => { 'type' => 'array', 'items' => { '$ref' => '#/definitions/ThisApi_Entities_Tag' }, 'description' => 'Tags.' },
            'relation' => { '$ref' => '#/definitions/ThisApi_Entities_Relation', 'description' => 'A related model.' },
            'code' => { 'type' => 'string', 'description' => 'Error code' },
            'message' => { 'type' => 'string', 'description' => 'Error message' },
            'attr' => { 'type' => 'string', 'description' => 'Attribute' } },
      'required' => ['attr']
    )

    expect(subject['definitions'].keys).to include 'ThisApi_Entities_Kind'
    expect(subject['definitions']['ThisApi_Entities_Kind']).to eq(
      'type' => 'object', 'properties' => { 'title' => { 'type' => 'string', 'description' => 'Title of the kind.' }, 'content' => { 'description' => 'Content', 'type' => 'string', 'x-some' => 'stuff' } }
    )

    expect(subject['definitions'].keys).to include 'ThisApi_Entities_Relation'
    expect(subject['definitions']['ThisApi_Entities_Relation']).to eq(
      'type' => 'object', 'properties' => { 'name' => { 'type' => 'string', 'description' => 'Name' } }
    )

    expect(subject['definitions'].keys).to include 'ThisApi_Entities_Tag'
    expect(subject['definitions']['ThisApi_Entities_Tag']).to eq(
      'type' => 'object', 'properties' => { 'name' => { 'type' => 'string', 'description' => 'Name' } }
    )
  end
end

describe 'building definitions from given entities' do
  before :all do
    module TheseApi
      module Entities
        class Values < Grape::Entity
          expose :guid, documentation: { desc: 'Some values', values: %w[a b c], default: 'c' }
          expose :uuid, documentation: { desc: 'customer uuid', type: String, format: 'own',
                                         example: 'e3008fba-d53d-4bcc-a6ae-adc56dff8020' }
        end

        class Kind < Grape::Entity
          expose :id, documentation: { type: Integer, desc: 'id of the kind.', values: [1, 2], read_only: true }
          expose :title, documentation: { type: String, desc: 'Title of the kind.', read_only: 'false' }
          expose :type, documentation: { type: String, desc: 'Type of the kind.', read_only: 'true' }
        end

        class Relation < Grape::Entity
          expose :name, documentation: { type: String, desc: 'Name' }
        end
        class Tag < Grape::Entity
          expose :name, documentation: { type: 'string', desc: 'Name',
                                         example: -> { 'random_tag' } }
        end

        class Nested < Grape::Entity
          expose :nested, documentation: { type: Hash, desc: 'Nested entity' } do
            expose :some1, documentation: { type: 'String', desc: 'Nested some 1' }
            expose :some2, documentation: { type: 'String', desc: 'Nested some 2' }
          end
          expose :nested_with_alias, as: :aliased do
            expose :some1, documentation: { type: 'String', desc: 'Alias some 1' }
          end
          expose :deep_nested, documentation: { type: 'Object', desc: 'Deep nested entity' } do
            expose :level_1, documentation: { type: 'Object', desc: 'More deepest nested entity' } do
              expose :level_2, documentation: { type: 'String', desc: 'Level 2' }
            end
          end
          expose :nested_required do
            expose :some1, documentation: { required: true, desc: 'Required some 1' }
            expose :attr, as: :some2, documentation: { required: true, desc: 'Required some 2' }
            expose :some3, documentation: { desc: 'Optional some 3' }
          end

          expose :nested_array, documentation: { type: 'Array', desc: 'Nested array' } do
            expose :id, documentation: { type: 'Integer', desc: 'Collection element id' }
            expose :name, documentation: { type: 'String', desc: 'Collection element name' }
          end
        end

        class Polymorphic < Grape::Entity
          expose :obj, as: :kind, if: ->(instance, _) { instance.type == 'kind' }, using: Kind, documentation: { desc: 'Polymorphic Kind' }
          expose :obj, as: :values, if: ->(instance, _) { instance.type == 'values' }, using: Values, documentation: { desc: 'Polymorphic Values' }
          expose :not_using_obj, as: :str, if: ->(instance, _) { instance.instance_of?(String) }, documentation: { desc: 'Polymorphic String' }
          expose :not_using_obj, as: :num, if: ->(instance, _) { instance.instance_of?(Number) }, documentation: { desc: 'Polymorphic Number', type: 'Integer' }
        end

        class SomeEntity < Grape::Entity
          expose :text, documentation: { type: 'string', desc: 'Content of something.' }
          expose :kind, using: Kind, documentation: { type: 'TheseApi_Kind', desc: 'The kind of this something.' }
          expose :kind2, using: Kind, documentation: { desc: 'Secondary kind.' }
          expose :kind3, using: TheseApi::Entities::Kind, documentation: { desc: 'Tertiary kind.' }
          expose :tags, using: TheseApi::Entities::Tag, documentation: { desc: 'Tags.', is_array: true }
          expose :relation, using: TheseApi::Entities::Relation, documentation: { type: 'TheseApi_Relation', desc: 'A related model.' }
          expose :values, using: TheseApi::Entities::Values, documentation: { desc: 'Tertiary kind.' }
          expose :nested, using: TheseApi::Entities::Nested, documentation: { desc: 'Nested object.' }
          expose :polymorphic, using: TheseApi::Entities::Polymorphic, documentation: { desc: 'Polymorphic Model' }
          expose :merged_attribute, using: ThisApi::Entities::Nested, merge: true
        end
      end

      class ResponseEntityApi < Grape::API
        format :json
        desc 'This returns something',
             is_array: true,
             entity: Entities::SomeEntity
        get '/some_entity' do
          something = OpenStruct.new text: 'something'
          present something, with: Entities::SomeEntity
        end

        add_swagger_documentation
      end
    end
  end

  def app
    TheseApi::ResponseEntityApi
  end

  subject do
    get '/swagger_doc'
    JSON.parse(last_response.body)['definitions']
  end

  it 'prefers entity over other `using` values' do
    expect(subject['TheseApi_Entities_Values']).to eql(
      'type' => 'object',
      'properties' => {
        'guid' => { 'type' => 'string', 'enum' => %w[a b c], 'default' => 'c', 'description' => 'Some values' },
        'uuid' => { 'type' => 'string', 'format' => 'own', 'description' => 'customer uuid', 'example' => 'e3008fba-d53d-4bcc-a6ae-adc56dff8020' }
      }
    )
    expect(subject['TheseApi_Entities_Kind']).to eql(
      'type' => 'object',
      'properties' => {
        'id' => { 'type' => 'integer', 'format' => 'int32', 'description' => 'id of the kind.', 'enum' => [1, 2], 'readOnly' => true },
        'title' => { 'type' => 'string', 'description' => 'Title of the kind.', 'readOnly' => false },
        'type' => { 'type' => 'string', 'description' => 'Type of the kind.', 'readOnly' => true }
      }
    )
    expect(subject['TheseApi_Entities_Tag']).to eql(
      'type' => 'object', 'properties' => { 'name' => { 'type' => 'string', 'description' => 'Name', 'example' => 'random_tag' } }
    )
    expect(subject['TheseApi_Entities_Relation']).to eql(
      'type' => 'object', 'properties' => { 'name' => { 'type' => 'string', 'description' => 'Name' } }
    )
    expect(subject['TheseApi_Entities_Nested']).to eq(
      'properties' => {
        'nested' => {
          'type' => 'object',
          'properties' => {
            'some1' => { 'type' => 'string', 'description' => 'Nested some 1' },
            'some2' => { 'type' => 'string', 'description' => 'Nested some 2' }
          },
          'description' => 'Nested entity'
        },
        'aliased' => {
          'type' => 'object',
          'properties' => {
            'some1' => { 'type' => 'string', 'description' => 'Alias some 1' }
          }
        },
        'deep_nested' => {
          'type' => 'object',
          'properties' => {
            'level_1' => {
              'type' => 'object',
              'properties' => {
                'level_2' => { 'type' => 'string', 'description' => 'Level 2' }
              },
              'description' => 'More deepest nested entity'
            }
          },
          'description' => 'Deep nested entity'
        },
        'nested_required' => {
          'type' => 'object',
          'properties' => {
            'some1' => { 'type' => 'string', 'description' => 'Required some 1' },
            'some2' => { 'type' => 'string', 'description' => 'Required some 2' },
            'some3' => { 'type' => 'string', 'description' => 'Optional some 3' }
          },
          'required' => %w[some1 some2]
        },
        'nested_array' => {
          'type' => 'array',
          'items' => {
            'type' => 'object',
            'properties' => {
              'id' => { 'type' => 'integer', 'format' => 'int32', 'description' => 'Collection element id' },
              'name' => { 'type' => 'string', 'description' => 'Collection element name' }
            }
          },
          'description' => 'Nested array'
        }
      },
      'type' => 'object'
    )
    expect(subject['TheseApi_Entities_Polymorphic']).to eql(
      'type' => 'object',
      'properties' => {
        'kind' => { '$ref' => '#/definitions/TheseApi_Entities_Kind', 'description' => 'Polymorphic Kind' },
        'values' => { '$ref' => '#/definitions/TheseApi_Entities_Values', 'description' => 'Polymorphic Values' },
        'str' => { 'type' => 'string', 'description' => 'Polymorphic String' },
        'num' => { 'type' => 'integer', 'format' => 'int32', 'description' => 'Polymorphic Number' }
      }
    )

    expect(subject['TheseApi_Entities_SomeEntity']).to eql(
      'type' => 'object',
      'properties' => {
        'text' => { 'type' => 'string', 'description' => 'Content of something.' },
        'kind' => { '$ref' => '#/definitions/TheseApi_Entities_Kind', 'description' => 'The kind of this something.' },
        'kind2' => { '$ref' => '#/definitions/TheseApi_Entities_Kind', 'description' => 'Secondary kind.' },
        'kind3' => { '$ref' => '#/definitions/TheseApi_Entities_Kind', 'description' => 'Tertiary kind.' },
        'tags' => { 'type' => 'array', 'items' => { '$ref' => '#/definitions/TheseApi_Entities_Tag' }, 'description' => 'Tags.' },
        'relation' => { '$ref' => '#/definitions/TheseApi_Entities_Relation', 'description' => 'A related model.' },
        'values' => { '$ref' => '#/definitions/TheseApi_Entities_Values', 'description' => 'Tertiary kind.' },
        'nested' => { '$ref' => '#/definitions/TheseApi_Entities_Nested', 'description' => 'Nested object.' },
        'code' => { 'type' => 'string', 'description' => 'Error code' },
        'message' => { 'type' => 'string', 'description' => 'Error message' },
        'polymorphic' => { '$ref' => '#/definitions/TheseApi_Entities_Polymorphic', 'description' => 'Polymorphic Model' },
        'attr' => { 'type' => 'string', 'description' => 'Attribute' }
      },
      'required' => %w[attr],
      'description' => 'This returns something'
    )
  end
end


text:
date: 2017-10-01
title: September Recap
slug: progress-report-12
series: ["transparency"]
tags: ["company", "progress"]
---

Here is a short and sweet recap of September's metrics for Insomnia.

<!--more-->

_If you like this post, be sure to check out [the other recaps](/series/transparency/).
There's one every month!_

## Metrics Overview

Revenue growth is still looking healthy. There have been a lot more teams signing up lately,
which helps a lot. However, user growth is slowing down significantly from it's usual 15-20%
month-over-month.

| Metric                     | Value This Month | Change    |
| -------------------------- | ---------------- | --------- |
| Active App Users           | 40,837           | +4%       |
| New App Users              | 13,583           | -6%       |
| Monthly Recurring Revenue  | $1817            | +13%      |
| Recognized Revenue         | $2627            | +49%      |
| New Trial Customers        | 477              | +8%       |
| New Paying Customers       | 26               | -37%      |
| Subscription Churn         | $143             | +15%      |
| Subscription Cancellations | 13               | +44%      |

![Daily Active Users](/images/blog/dau-15.png)

![Monthly Recurring Revenue](/images/blog/mrr-15.png)

Be sure to stay tuned to see next month's recap!


text:
gnocchi
-------

.. autoprogram-cliff:: openstack.metric.v1


text:
package org.apache.hadoop.fs.http.server;

import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.security.token.delegation.web.DelegationTokenAuthenticator;
import org.apache.hadoop.security.token.delegation.web.KerberosDelegationTokenAuthenticationHandler;
import org.json.simple.JSONArray;
import org.junit.Assert;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.XAttrCodec;
import org.apache.hadoop.lib.server.Service;
import org.apache.hadoop.lib.server.ServiceException;
import org.apache.hadoop.lib.service.Groups;
import org.apache.hadoop.security.authentication.client.AuthenticatedURL;
import org.apache.hadoop.security.authentication.server.AuthenticationToken;
import org.apache.hadoop.security.authentication.util.Signer;
import org.apache.hadoop.test.HFSTestCase;
import org.apache.hadoop.test.HadoopUsersConfTestHelper;
import org.apache.hadoop.test.TestDir;
import org.apache.hadoop.test.TestDirHelper;
import org.apache.hadoop.test.TestHdfs;
import org.apache.hadoop.test.TestHdfsHelper;
import org.apache.hadoop.test.TestJetty;
import org.apache.hadoop.test.TestJettyHelper;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.junit.Test;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.webapp.WebAppContext;

import com.google.common.collect.Maps;
import java.util.Properties;
import org.apache.hadoop.security.authentication.server.AuthenticationFilter;
import org.apache.hadoop.security.authentication.util.StringSignerSecretProvider;

public class TestHttpFSServer extends HFSTestCase {

  @Test
  @TestDir
  @TestJetty
  public void server() throws Exception {
    String dir = TestDirHelper.getTestDir().getAbsolutePath();

    Configuration httpfsConf = new Configuration(false);
    HttpFSServerWebApp server = new HttpFSServerWebApp(dir, dir, dir, dir, httpfsConf);
    server.init();
    server.destroy();
  }

  public static class MockGroups implements Service,Groups {

    @Override
    public void init(org.apache.hadoop.lib.server.Server server) throws ServiceException {
    }

    @Override
    public void postInit() throws ServiceException {
    }

    @Override
    public void destroy() {
    }

    @Override
    public Class[] getServiceDependencies() {
      return new Class[0];
    }

    @Override
    public Class getInterface() {
      return Groups.class;
    }

    @Override
    public void serverStatusChange(org.apache.hadoop.lib.server.Server.Status oldStatus,
                                   org.apache.hadoop.lib.server.Server.Status newStatus) throws ServiceException {
    }

    @Override
    public List<String> getGroups(String user) throws IOException {
      return Arrays.asList(HadoopUsersConfTestHelper.getHadoopUserGroups(user));
    }

  }

  private void createHttpFSServer(boolean addDelegationTokenAuthHandler)
    throws Exception {
    File homeDir = TestDirHelper.getTestDir();
    Assert.assertTrue(new File(homeDir, "conf").mkdir());
    Assert.assertTrue(new File(homeDir, "log").mkdir());
    Assert.assertTrue(new File(homeDir, "temp").mkdir());
    HttpFSServerWebApp.setHomeDirForCurrentThread(homeDir.getAbsolutePath());

    File secretFile = new File(new File(homeDir, "conf"), "secret");
    Writer w = new FileWriter(secretFile);
    w.write("secret");
    w.close();

    //HDFS configuration
    File hadoopConfDir = new File(new File(homeDir, "conf"), "hadoop-conf");
    hadoopConfDir.mkdirs();
    String fsDefaultName = TestHdfsHelper.getHdfsConf().get(CommonConfigurationKeysPublic.FS_DEFAULT_NAME_KEY);
    Configuration conf = new Configuration(false);
    conf.set(CommonConfigurationKeysPublic.FS_DEFAULT_NAME_KEY, fsDefaultName);
    conf.setBoolean(DFSConfigKeys.DFS_NAMENODE_ACLS_ENABLED_KEY, true);
    conf.setBoolean(DFSConfigKeys.DFS_NAMENODE_XATTRS_ENABLED_KEY, true);
    File hdfsSite = new File(hadoopConfDir, "hdfs-site.xml");
    OutputStream os = new FileOutputStream(hdfsSite);
    conf.writeXml(os);
    os.close();

    //HTTPFS configuration
    conf = new Configuration(false);
    if (addDelegationTokenAuthHandler) {
     conf.set("httpfs.authentication.type",
              HttpFSKerberosAuthenticationHandlerForTesting.class.getName());
    }
    conf.set("httpfs.services.ext", MockGroups.class.getName());
    conf.set("httpfs.admin.group", HadoopUsersConfTestHelper.
      getHadoopUserGroups(HadoopUsersConfTestHelper.getHadoopUsers()[0])[0]);
    conf.set("httpfs.proxyuser." + HadoopUsersConfTestHelper.getHadoopProxyUser() + ".groups",
             HadoopUsersConfTestHelper.getHadoopProxyUserGroups());
    conf.set("httpfs.proxyuser." + HadoopUsersConfTestHelper.getHadoopProxyUser() + ".hosts",
             HadoopUsersConfTestHelper.getHadoopProxyUserHosts());
    conf.set("httpfs.authentication.signature.secret.file", secretFile.getAbsolutePath());
    conf.set("httpfs.hadoop.config.dir", hadoopConfDir.toString());
    File httpfsSite = new File(new File(homeDir, "conf"), "httpfs-site.xml");
    os = new FileOutputStream(httpfsSite);
    conf.writeXml(os);
    os.close();

    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    URL url = cl.getResource("webapp");
    WebAppContext context = new WebAppContext(url.getPath(), "/webhdfs");
    Server server = TestJettyHelper.getJettyServer();
    server.addHandler(context);
    server.start();
    if (addDelegationTokenAuthHandler) {
      HttpFSServerWebApp.get().setAuthority(TestJettyHelper.getAuthority());
    }
  }

  @Test
  @TestDir
  @TestJetty
  @TestHdfs
  public void instrumentation() throws Exception {
    createHttpFSServer(false);

    URL url = new URL(TestJettyHelper.getJettyURL(),
                      MessageFormat.format("/webhdfs/v1?user.name={0}&op=instrumentation", "nobody"));
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    Assert.assertEquals(conn.getResponseCode(), HttpURLConnection.HTTP_UNAUTHORIZED);

    url = new URL(TestJettyHelper.getJettyURL(),
                  MessageFormat.format("/webhdfs/v1?user.name={0}&op=instrumentation",
                                       HadoopUsersConfTestHelper.getHadoopUsers()[0]));
    conn = (HttpURLConnection) url.openConnection();
    Assert.assertEquals(conn.getResponseCode(), HttpURLConnection.HTTP_OK);
    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line = reader.readLine();
    reader.close();
    Assert.assertTrue(line.contains("\"counters\":{"));

    url = new URL(TestJettyHelper.getJettyURL(),
                  MessageFormat.format("/webhdfs/v1/foo?user.name={0}&op=instrumentation",
                                       HadoopUsersConfTestHelper.getHadoopUsers()[0]));
    conn = (HttpURLConnection) url.openConnection();
    Assert.assertEquals(conn.getResponseCode(), HttpURLConnection.HTTP_BAD_REQUEST);
  }

  @Test
  @TestDir
  @TestJetty
  @TestHdfs
  public void testHdfsAccess() throws Exception {
    createHttpFSServer(false);

    String user = HadoopUsersConfTestHelper.getHadoopUsers()[0];
    URL url = new URL(TestJettyHelper.getJettyURL(),
                      MessageFormat.format("/webhdfs/v1/?user.name={0}&op=liststatus", user));
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    Assert.assertEquals(conn.getResponseCode(), HttpURLConnection.HTTP_OK);
    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    reader.readLine();
    reader.close();
  }

  @Test
  @TestDir
  @TestJetty
  @TestHdfs
  public void testGlobFilter() throws Exception {
    createHttpFSServer(false);

    FileSystem fs = FileSystem.get(TestHdfsHelper.getHdfsConf());
    fs.mkdirs(new Path("/tmp"));
    fs.create(new Path("/tmp/foo.txt")).close();

    String user = HadoopUsersConfTestHelper.getHadoopUsers()[0];
    URL url = new URL(TestJettyHelper.getJettyURL(),
                      MessageFormat.format("/webhdfs/v1/tmp?user.name={0}&op=liststatus&filter=f*", user));
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    Assert.assertEquals(conn.getResponseCode(), HttpURLConnection.HTTP_OK);
    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    reader.readLine();
    reader.close();
  }

  /**
   * Talks to the http interface to create a file.
   *
   * @param filename The file to create
   * @param perms The permission field, if any (may be null)
   * @throws Exception
   */
  private void createWithHttp ( String filename, String perms )
          throws Exception {
    String user = HadoopUsersConfTestHelper.getHadoopUsers()[0];
    // Remove leading / from filename
    if ( filename.charAt(0) == '/' ) {
      filename = filename.substring(1);
    }
    String pathOps;
    if ( perms == null ) {
      pathOps = MessageFormat.format(
              "/webhdfs/v1/{0}?user.name={1}&op=CREATE",
              filename, user);
    } else {
      pathOps = MessageFormat.format(
              "/webhdfs/v1/{0}?user.name={1}&permission={2}&op=CREATE",
              filename, user, perms);
    }
    URL url = new URL(TestJettyHelper.getJettyURL(), pathOps);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.addRequestProperty("Content-Type", "application/octet-stream");
    conn.setRequestMethod("PUT");
    conn.connect();
    Assert.assertEquals(HttpURLConnection.HTTP_CREATED, conn.getResponseCode());
  }

  /**
   * Talks to the http interface to get the json output of a *STATUS command
   * on the given file.
   *
   * @param filename The file to query.
   * @param command Either GETFILESTATUS, LISTSTATUS, or ACLSTATUS
   * @return A string containing the JSON output describing the file.
   * @throws Exception
   */
  private String getStatus(String filename, String command)
          throws Exception {
    String user = HadoopUsersConfTestHelper.getHadoopUsers()[0];
    // Remove leading / from filename
    if ( filename.charAt(0) == '/' ) {
      filename = filename.substring(1);
    }
    String pathOps = MessageFormat.format(
            "/webhdfs/v1/{0}?user.name={1}&op={2}",
            filename, user, command);
    URL url = new URL(TestJettyHelper.getJettyURL(), pathOps);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.connect();
    Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());

    BufferedReader reader =
            new BufferedReader(new InputStreamReader(conn.getInputStream()));

    return reader.readLine();
  }

  /**
   * General-purpose http PUT command to the httpfs server.
   * @param filename The file to operate upon
   * @param command The command to perform (SETACL, etc)
   * @param params Parameters, like "aclspec=..."
   */
  private void putCmd(String filename, String command,
                      String params) throws Exception {
    String user = HadoopUsersConfTestHelper.getHadoopUsers()[0];
    // Remove leading / from filename
    if ( filename.charAt(0) == '/' ) {
      filename = filename.substring(1);
    }
    String pathOps = MessageFormat.format(
            "/webhdfs/v1/{0}?user.name={1}{2}{3}&op={4}",
            filename, user, (params == null) ? "" : "&",
            (params == null) ? "" : params, command);
    URL url = new URL(TestJettyHelper.getJettyURL(), pathOps);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("PUT");
    conn.connect();
    Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
  }

  /**
   * Given the JSON output from the GETFILESTATUS call, return the
   * 'permission' value.
   *
   * @param statusJson JSON from GETFILESTATUS
   * @return The value of 'permission' in statusJson
   * @throws Exception
   */
  private String getPerms ( String statusJson ) throws Exception {
    JSONParser parser = new JSONParser();
    JSONObject jsonObject = (JSONObject) parser.parse(statusJson);
    JSONObject details = (JSONObject) jsonObject.get("FileStatus");
    return (String) details.get("permission");
  }

  /**
   * Given the JSON output from the GETACLSTATUS call, return the
   * 'entries' value as a List<String>.
   * @param statusJson JSON from GETACLSTATUS
   * @return A List of Strings which are the elements of the ACL entries
   * @throws Exception
   */
  private List<String> getAclEntries ( String statusJson ) throws Exception {
    List<String> entries = new ArrayList<String>();
    JSONParser parser = new JSONParser();
    JSONObject jsonObject = (JSONObject) parser.parse(statusJson);
    JSONObject details = (JSONObject) jsonObject.get("AclStatus");
    JSONArray jsonEntries = (JSONArray) details.get("entries");
    if ( jsonEntries != null ) {
      for (Object e : jsonEntries) {
        entries.add(e.toString());
      }
    }
    return entries;
  }

  /**
   * Parse xAttrs from JSON result of GETXATTRS call, return xAttrs Map.
   * @param statusJson JSON from GETXATTRS
   * @return Map<String, byte[]> xAttrs Map
   * @throws Exception
   */
  private Map<String, byte[]> getXAttrs(String statusJson) throws Exception {
    Map<String, byte[]> xAttrs = Maps.newHashMap();
    JSONParser parser = new JSONParser();
    JSONObject jsonObject = (JSONObject) parser.parse(statusJson);
    JSONArray jsonXAttrs = (JSONArray) jsonObject.get("XAttrs");
    if (jsonXAttrs != null) {
      for (Object a : jsonXAttrs) {
        String name = (String) ((JSONObject)a).get("name");
        String value = (String) ((JSONObject)a).get("value");
        xAttrs.put(name, decodeXAttrValue(value));
      }
    }
    return xAttrs;
  }

  /** Decode xattr value from string */
  private byte[] decodeXAttrValue(String value) throws IOException {
    if (value != null) {
      return XAttrCodec.decodeValue(value);
    } else {
      return new byte[0];
    }
  }

  /**
   * Validate that files are created with 755 permissions when no
   * 'permissions' attribute is specified, and when 'permissions'
   * is specified, that value is honored.
   */
  @Test
  @TestDir
  @TestJetty
  @TestHdfs
  public void testPerms() throws Exception {
    createHttpFSServer(false);

    FileSystem fs = FileSystem.get(TestHdfsHelper.getHdfsConf());
    fs.mkdirs(new Path("/perm"));

    createWithHttp("/perm/none", null);
    String statusJson = getStatus("/perm/none", "GETFILESTATUS");
    Assert.assertTrue("755".equals(getPerms(statusJson)));

    createWithHttp("/perm/p-777", "777");
    statusJson = getStatus("/perm/p-777", "GETFILESTATUS");
    Assert.assertTrue("777".equals(getPerms(statusJson)));

    createWithHttp("/perm/p-654", "654");
    statusJson = getStatus("/perm/p-654", "GETFILESTATUS");
    Assert.assertTrue("654".equals(getPerms(statusJson)));

    createWithHttp("/perm/p-321", "321");
    statusJson = getStatus("/perm/p-321", "GETFILESTATUS");
    Assert.assertTrue("321".equals(getPerms(statusJson)));
  }

  /**
   * Validate XAttr get/set/remove calls.
   */
  @Test
  @TestDir
  @TestJetty
  @TestHdfs
  public void testXAttrs() throws Exception {
    final String name1 = "user.a1";
    final byte[] value1 = new byte[]{0x31, 0x32, 0x33};
    final String name2 = "user.a2";
    final byte[] value2 = new byte[]{0x41, 0x42, 0x43};
    final String dir = "/xattrTest";
    final String path = dir + "/file";

    createHttpFSServer(false);

    FileSystem fs = FileSystem.get(TestHdfsHelper.getHdfsConf());
    fs.mkdirs(new Path(dir));

    createWithHttp(path,null);
    String statusJson = getStatus(path, "GETXATTRS");
    Map<String, byte[]> xAttrs = getXAttrs(statusJson);
    Assert.assertEquals(0, xAttrs.size());

    // Set two xattrs
    putCmd(path, "SETXATTR", setXAttrParam(name1, value1));
    putCmd(path, "SETXATTR", setXAttrParam(name2, value2));
    statusJson = getStatus(path, "GETXATTRS");
    xAttrs = getXAttrs(statusJson);
    Assert.assertEquals(2, xAttrs.size());
    Assert.assertArrayEquals(value1, xAttrs.get(name1));
    Assert.assertArrayEquals(value2, xAttrs.get(name2));

    // Remove one xattr
    putCmd(path, "REMOVEXATTR", "xattr.name=" + name1);
    statusJson = getStatus(path, "GETXATTRS");
    xAttrs = getXAttrs(statusJson);
    Assert.assertEquals(1, xAttrs.size());
    Assert.assertArrayEquals(value2, xAttrs.get(name2));

    // Remove another xattr, then there is no xattr
    putCmd(path, "REMOVEXATTR", "xattr.name=" + name2);
    statusJson = getStatus(path, "GETXATTRS");
    xAttrs = getXAttrs(statusJson);
    Assert.assertEquals(0, xAttrs.size());
  }

  /** Params for setting an xAttr */
  public static String setXAttrParam(String name, byte[] value) throws IOException {
    return "xattr.name=" + name + "&xattr.value=" + XAttrCodec.encodeValue(
        value, XAttrCodec.HEX) + "&encoding=hex&flag=create";
  }

  /**
   * Validate the various ACL set/modify/remove calls.  General strategy is
   * to verify each of the following steps with GETFILESTATUS, LISTSTATUS,
   * and GETACLSTATUS:
   *

   *
Create a file with no ACLs

   *
Add a user + group ACL

   *
Add another user ACL

   *
Remove the first user ACL

   *
Remove all ACLs

   *

   */
  @Test
  @TestDir
  @TestJetty
  @TestHdfs
  public void testFileAcls() throws Exception {
    final String aclUser1 = "user:foo:rw-";
    final String aclUser2 = "user:bar:r--";
    final String aclGroup1 = "group::r--";
    final String aclSpec = "aclspec=user::rwx," + aclUser1 + ","
            + aclGroup1 + ",other::---";
    final String modAclSpec = "aclspec=" + aclUser2;
    final String remAclSpec = "aclspec=" + aclUser1;
    final String dir = "/aclFileTest";
    final String path = dir + "/test";
    String statusJson;
    List<String> aclEntries;

    createHttpFSServer(false);

    FileSystem fs = FileSystem.get(TestHdfsHelper.getHdfsConf());
    fs.mkdirs(new Path(dir));

    createWithHttp(path, null);

    /* getfilestatus and liststatus don't have 'aclBit' in their reply */
    statusJson = getStatus(path, "GETFILESTATUS");
    Assert.assertEquals(-1, statusJson.indexOf("aclBit"));
    statusJson = getStatus(dir, "LISTSTATUS");
    Assert.assertEquals(-1, statusJson.indexOf("aclBit"));

    /* getaclstatus works and returns no entries */
    statusJson = getStatus(path, "GETACLSTATUS");
    aclEntries = getAclEntries(statusJson);
    Assert.assertTrue(aclEntries.size() == 0);

    /*
     * Now set an ACL on the file.  (getfile|list)status have aclBit,
     * and aclstatus has entries that looks familiar.
     */
    putCmd(path, "SETACL", aclSpec);
    statusJson = getStatus(path, "GETFILESTATUS");
    Assert.assertNotEquals(-1, statusJson.indexOf("aclBit"));
    statusJson = getStatus(dir, "LISTSTATUS");
    Assert.assertNotEquals(-1, statusJson.indexOf("aclBit"));
    statusJson = getStatus(path, "GETACLSTATUS");
    aclEntries = getAclEntries(statusJson);
    Assert.assertTrue(aclEntries.size() == 2);
    Assert.assertTrue(aclEntries.contains(aclUser1));
    Assert.assertTrue(aclEntries.contains(aclGroup1));

    /* Modify acl entries to add another user acl */
    putCmd(path, "MODIFYACLENTRIES", modAclSpec);
    statusJson = getStatus(path, "GETACLSTATUS");
    aclEntries = getAclEntries(statusJson);
    Assert.assertTrue(aclEntries.size() == 3);
    Assert.assertTrue(aclEntries.contains(aclUser1));
    Assert.assertTrue(aclEntries.contains(aclUser2));
    Assert.assertTrue(aclEntries.contains(aclGroup1));

    /* Remove the first user acl entry and verify */
    putCmd(path, "REMOVEACLENTRIES", remAclSpec);
    statusJson = getStatus(path, "GETACLSTATUS");
    aclEntries = getAclEntries(statusJson);
    Assert.assertTrue(aclEntries.size() == 2);
    Assert.assertTrue(aclEntries.contains(aclUser2));
    Assert.assertTrue(aclEntries.contains(aclGroup1));

    /* Remove all acls and verify */
    putCmd(path, "REMOVEACL", null);
    statusJson = getStatus(path, "GETACLSTATUS");
    aclEntries = getAclEntries(statusJson);
    Assert.assertTrue(aclEntries.size() == 0);
    statusJson = getStatus(path, "GETFILESTATUS");
    Assert.assertEquals(-1, statusJson.indexOf("aclBit"));
    statusJson = getStatus(dir, "LISTSTATUS");
    Assert.assertEquals(-1, statusJson.indexOf("aclBit"));
  }

  /**
   * Test ACL operations on a directory, including default ACLs.
   * General strategy is to use GETFILESTATUS and GETACLSTATUS to verify:
   *

   *
Initial status with no ACLs

   *
The addition of a default ACL

   *
The removal of default ACLs

   *

   *
   * @throws Exception
   */
  @Test
  @TestDir
  @TestJetty
  @TestHdfs
  public void testDirAcls() throws Exception {
    final String defUser1 = "default:user:glarch:r-x";
    final String defSpec1 = "aclspec=" + defUser1;
    final String dir = "/aclDirTest";
    String statusJson;
    List<String> aclEntries;

    createHttpFSServer(false);

    FileSystem fs = FileSystem.get(TestHdfsHelper.getHdfsConf());
    fs.mkdirs(new Path(dir));

    /* getfilestatus and liststatus don't have 'aclBit' in their reply */
    statusJson = getStatus(dir, "GETFILESTATUS");
    Assert.assertEquals(-1, statusJson.indexOf("aclBit"));

    /* No ACLs, either */
    statusJson = getStatus(dir, "GETACLSTATUS");
    aclEntries = getAclEntries(statusJson);
    Assert.assertTrue(aclEntries.size() == 0);

    /* Give it a default ACL and verify */
    putCmd(dir, "SETACL", defSpec1);
    statusJson = getStatus(dir, "GETFILESTATUS");
    Assert.assertNotEquals(-1, statusJson.indexOf("aclBit"));
    statusJson = getStatus(dir, "GETACLSTATUS");
    aclEntries = getAclEntries(statusJson);
    Assert.assertTrue(aclEntries.size() == 5);
    /* 4 Entries are default:(user|group|mask|other):perm */
    Assert.assertTrue(aclEntries.contains(defUser1));

    /* Remove the default ACL and re-verify */
    putCmd(dir, "REMOVEDEFAULTACL", null);
    statusJson = getStatus(dir, "GETFILESTATUS");
    Assert.assertEquals(-1, statusJson.indexOf("aclBit"));
    statusJson = getStatus(dir, "GETACLSTATUS");
    aclEntries = getAclEntries(statusJson);
    Assert.assertTrue(aclEntries.size() == 0);
  }

  @Test
  @TestDir
  @TestJetty
  @TestHdfs
  public void testOpenOffsetLength() throws Exception {
    createHttpFSServer(false);

    byte[] array = new byte[]{0, 1, 2, 3};
    FileSystem fs = FileSystem.get(TestHdfsHelper.getHdfsConf());
    fs.mkdirs(new Path("/tmp"));
    OutputStream os = fs.create(new Path("/tmp/foo"));
    os.write(array);
    os.close();

    String user = HadoopUsersConfTestHelper.getHadoopUsers()[0];
    URL url = new URL(TestJettyHelper.getJettyURL(),
                      MessageFormat.format("/webhdfs/v1/tmp/foo?user.name={0}&op=open&offset=1&length=2", user));
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
    InputStream is = conn.getInputStream();
    Assert.assertEquals(1, is.read());
    Assert.assertEquals(2, is.read());
    Assert.assertEquals(-1, is.read());
  }

  @Test
  @TestDir
  @TestJetty
  @TestHdfs
  public void testPutNoOperation() throws Exception {
    createHttpFSServer(false);

    String user = HadoopUsersConfTestHelper.getHadoopUsers()[0];
    URL url = new URL(TestJettyHelper.getJettyURL(),
                      MessageFormat.format("/webhdfs/v1/foo?user.name={0}", user));
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setRequestMethod("PUT");
    Assert.assertEquals(conn.getResponseCode(), HttpURLConnection.HTTP_BAD_REQUEST);
  }

  @Test
  @TestDir
  @TestJetty
  @TestHdfs
  public void testDelegationTokenOperations() throws Exception {
    createHttpFSServer(true);

    URL url = new URL(TestJettyHelper.getJettyURL(),
                      "/webhdfs/v1/?op=GETHOMEDIRECTORY");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED,
                        conn.getResponseCode());

    AuthenticationToken token =
      new AuthenticationToken("u", "p",
          new KerberosDelegationTokenAuthenticationHandler().getType());
    token.setExpires(System.currentTimeMillis() + 100000000);
    StringSignerSecretProvider secretProvider = new StringSignerSecretProvider();
    Properties secretProviderProps = new Properties();
    secretProviderProps.setProperty(AuthenticationFilter.SIGNATURE_SECRET, "secret");
    secretProvider.init(secretProviderProps, null, -1);
    Signer signer = new Signer(secretProvider);
    String tokenSigned = signer.sign(token.toString());

    url = new URL(TestJettyHelper.getJettyURL(),
                  "/webhdfs/v1/?op=GETHOMEDIRECTORY");
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestProperty("Cookie",
                            AuthenticatedURL.AUTH_COOKIE  + "=" + tokenSigned);
    Assert.assertEquals(HttpURLConnection.HTTP_OK,
                        conn.getResponseCode());

    url = new URL(TestJettyHelper.getJettyURL(),
                  "/webhdfs/v1/?op=GETDELEGATIONTOKEN");
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestProperty("Cookie",
                            AuthenticatedURL.AUTH_COOKIE  + "=" + tokenSigned);
    Assert.assertEquals(HttpURLConnection.HTTP_OK,
                        conn.getResponseCode());

    JSONObject json = (JSONObject)
      new JSONParser().parse(new InputStreamReader(conn.getInputStream()));
    json = (JSONObject)
      json.get(DelegationTokenAuthenticator.DELEGATION_TOKEN_JSON);
    String tokenStr = (String)
        json.get(DelegationTokenAuthenticator.DELEGATION_TOKEN_URL_STRING_JSON);

    url = new URL(TestJettyHelper.getJettyURL(),
                  "/webhdfs/v1/?op=GETHOMEDIRECTORY&delegation=" + tokenStr);
    conn = (HttpURLConnection) url.openConnection();
    Assert.assertEquals(HttpURLConnection.HTTP_OK,
                        conn.getResponseCode());

    url = new URL(TestJettyHelper.getJettyURL(),
                  "/webhdfs/v1/?op=RENEWDELEGATIONTOKEN&token=" + tokenStr);
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("PUT");
    Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED,
                        conn.getResponseCode());

    url = new URL(TestJettyHelper.getJettyURL(),
                  "/webhdfs/v1/?op=RENEWDELEGATIONTOKEN&token=" + tokenStr);
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("PUT");
    conn.setRequestProperty("Cookie",
                            AuthenticatedURL.AUTH_COOKIE  + "=" + tokenSigned);
    Assert.assertEquals(HttpURLConnection.HTTP_OK,
                        conn.getResponseCode());

    url = new URL(TestJettyHelper.getJettyURL(),
                  "/webhdfs/v1/?op=CANCELDELEGATIONTOKEN&token=" + tokenStr);
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("PUT");
    Assert.assertEquals(HttpURLConnection.HTTP_OK,
                        conn.getResponseCode());

    url = new URL(TestJettyHelper.getJettyURL(),
                  "/webhdfs/v1/?op=GETHOMEDIRECTORY&delegation=" + tokenStr);
    conn = (HttpURLConnection) url.openConnection();
    Assert.assertEquals(HttpURLConnection.HTTP_FORBIDDEN,
                        conn.getResponseCode());
  }

}


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2017] EMBL-European Bioinformatics Institute

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=cut

=head1 CONTACT

 Please email comments or questions to the public Ensembl
 developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.

 Questions may also be sent to the Ensembl help desk at
 <http://www.ensembl.org/Help/Contact>.

=cut

#
# Ensembl module for Bio::EnsEMBL::Variation::DBSQL::SampleGenotypeAdaptor
#
#

=head1 NAME

Bio::EnsEMBL::Variation::DBSQL::SampleGenotypeAdaptor

=head1 SYNOPSIS

  my $registry = 'Bio::EnsEMBL::Registry';
  $registry->load_registry_from_db(-host => 'ensembldb.ensembl.org', -user => 'anonymous');

  my $sa = $registry->get_adaptor('human', 'core', 'slice');
  my $sgta = $registry->get_adaptor('human', 'variation', 'samplegenotype');

  # Fetch region for which we want to get all sample genotypes
  my $slice = $sa->fetch_by_region('chromosome', '3', 52_786_960, 52_786_970);
  my $sample_genotypes = $sgta->fetch_all_by_Slice($slice);

  foreach my $sgt (@$sample_genotypes) {
    my $variation_name = $sgt->variation()->name;
    my $genotype = $sgt->genotype_string;
    my $sample_name = $sgt->sample()->name;
    print "$variation_name\t$genotype\t$sample_name\n";
  }

=head1 DESCRIPTION

This adaptor provides database connectivity for IndividualGenotype objects.
IndividualGenotypes may be retrieved from the Ensembl variation database by
several means using this module.

=head1 METHODS

=cut
package Bio::EnsEMBL::Variation::DBSQL::SampleGenotypeAdaptor;

use strict;
use warnings;

use vars qw(@ISA);

use Bio::EnsEMBL::Variation::DBSQL::BaseGenotypeAdaptor;
use Bio::EnsEMBL::Variation::SampleGenotype;
use Bio::EnsEMBL::Utils::Exception qw(throw warning);
use Bio::EnsEMBL::Utils::Sequence qw(reverse_comp);

use Scalar::Util qw(weaken);

our $CACHE_SIZE = 5;

@ISA = ('Bio::EnsEMBL::Variation::DBSQL::BaseGenotypeAdaptor');

# stores a listref of sample genotype objects
sub store {
	my ($self, $gts, $merge) = @_;

	throw("First argument to store is not a listref") unless ref($gts) eq 'ARRAY';

	# sort genotypes into rows by variation
	my %by_var;
	push @{$by_var{($_->{_variation_id} || $_->variation->dbID).'_'.($_->{subsnp} ? $_->{subsnp} : '')}}, $_ for @$gts;

	# get unique genotypes and codes
	my %unique_gts = map {$_->genotype_string().'|'.(defined($_->phased) ? $_->phased : 'NULL') => 1} @$gts;

  foreach my $gt_key(keys %unique_gts) {
    my @split = split /\|/, $gt_key;
    my $phased = pop @split;
    $unique_gts{$gt_key} = $self->_genotype_code(\@split, $phased);
  }

	# get variation objects
	my %var_objs = $merge ? map {($_->{_variation_id} || $_->variation->dbID) => $_->variation} @$gts : ();

	my $dbh = $self->dbc->db_handle;

	my $sth = $dbh->prepare_cached(qq{
		INSERT INTO compressed_genotype_var(
			variation_id,
			subsnp_id,
			genotypes
		) VALUES (?,?,?)
	});

	my $update_sth = $dbh->prepare(qq{
		UPDATE compressed_genotype_var
		SET genotypes = ?
		WHERE variation_id = ?
		AND subsnp_id = ?
	});

	my $rows_added = 0;

	foreach my $combo_id (keys %by_var) {
		my $genotype_string = '';

		my ($var_id, $subsnp_id) = split /\_/, $combo_id;
		$subsnp_id = undef if $subsnp_id eq '';

		# check for existing genotypes
		my @existing_gts = ($merge ?
			grep {
				(defined($_->{subsnp}) && defined($subsnp_id) && $_->{subsnp} eq $subsnp_id) ||
				(!defined($_->{subsnp}) && !defined($subsnp_id))
			} @{$self->fetch_all_by_Variation($var_objs{$var_id})} : ());

		# update if existing
		if (@existing_gts) {

			# refresh unique_gts
			%unique_gts = map {$_->genotype_string().'|'.(defined($_->phased) ? $_->phased : 'NULL') => 1} (@existing_gts, @$gts);

      foreach my $gt_key(keys %unique_gts) {
        my @split = split /\|/, $gt_key;
        my $phased = pop @split;
        $unique_gts{$gt_key} = $self->_genotype_code(\@split, $phased);
      }

			# make sure we don't put in duplicates
			my %by_sample = map {$_->sample->dbID => $_} (@existing_gts, @$gts);

			$genotype_string .= pack("ww", $_->sample->dbID, $unique_gts{$_->genotype_string.'|'.(defined($_->phased) ? $_->phased : 'NULL')}) for values %by_sample;

			$update_sth->execute(
				$genotype_string,
				$var_id,
				$subsnp_id
			);
		}

		else {
			$genotype_string .= pack("ww", $_->sample->dbID, $unique_gts{$_->genotype_string.'|'.(defined($_->phased) ? $_->phased : 'NULL')}) for @$gts;

			$sth->execute(
				$var_id,
				$subsnp_id,
				$genotype_string
			);

			$rows_added++;
		}

	}

	$sth->finish;
	$update_sth->finish;

  # reset cache
  delete $self->{_cache} if $self->{_cache};

	return $rows_added;
}

# similar to store above but writes to old-style non-compressed table
# defaults to sample_genotype_multiple_bp since
# tmp_sample_genotype_single_bp will only accept single nucleotide genotypes
sub store_uncompressed {
	my ($self, $gts, $table) = @_;

	$table ||= 'sample_genotype_multiple_bp';

	throw("First argument to store is not a listref") unless ref($gts) eq 'ARRAY';

	my $dbh = $self->dbc->db_handle;

	my $q_string = join ",", map {'(?,?,?,?,?)'} @$gts;

	my @args = map {
		$_->{_variation_id} || $_->variation->dbID,
		$_->{subsnp},
		$_->allele1,
		$_->allele2,
		$_->sample ? $_->sample->dbID : undef,
	} @$gts;

	# Store the sample genotype entry, only if the array contains at least one element

	if (@args > 0) {
		my $sth = $dbh->prepare_cached(qq{
			INSERT INTO $table(
				variation_id,
				subsnp_id,
				allele_1,
				allele_2,
				sample_id
			) VALUES $q_string
		});

		$sth->execute(@args);

		$sth->finish;
	}

  # reset cache
  delete $self->{_cache} if $self->{_cache};

	return scalar @$gts;
}

=head2 fetch_all_by_Variation

  Arg [1]    : Bio::EnsEMBL::Variation $variation
  Example    : my $var = $variation_adaptor->fetch_by_name( "rs1121" )
               $sgtypes = $sgtype_adaptor->fetch_all_by_Variation( $var )
  Description: Retrieves a list of sample genotypes for the given Variation.
               If none are available an empty listref is returned.
  Returntype : listref Bio::EnsEMBL::Variation::SampleGenotype
  Exceptions : none
  Caller     : general
  Status     : Stable

=cut

sub fetch_all_by_Variation {
  my $self = shift;
  my $variation = shift;
  my $sample = shift;

  if(!ref($variation) || !$variation->isa('Bio::EnsEMBL::Variation::Variation')) {
    throw('Bio::EnsEMBL::Variation::Variation argument expected');
  }

  my $variation_id = $variation->dbID;

  if(!defined($variation_id)) {
    warning("Cannot retrieve genotypes for variation without dbID");
    return [];
  }

  my $results = [];

  # check cache
  # All sample GT objects for a variation are stored on the adaptor.
  # They are stored in an array of limited size so that the memory usage
  # doesn't go out of control for when the API requests genotypes for many
  # variations sequentially.
  my $cached;

  if (defined($self->{_cache})) {
    foreach my $stored(@{$self->{_cache}}) {
      my @keys = keys %{$stored};
      $cached = $stored->{$keys[0]} if $keys[0] eq $variation_id;
      last if defined($cached);
    }
  }

  if (!defined($cached)) {

    my $use_vcf = $self->db->use_vcf();

    if ($use_vcf) {
      my $vf = $variation->get_all_VariationFeatures->[0];

      @$cached = map {@{$_->get_all_SampleGenotypeFeatures_by_VariationFeature($vf)}}
                  @{$self->db->get_VCFCollectionAdaptor->fetch_all() || []} if $vf;
    }
    if ($use_vcf <= 1) {
      push @$cached, @{$self->generic_fetch("g.variation_id = " . $variation_id)};
    }
    for (@$cached) {
      $_->variation($variation);
      weaken($_->{'variation'});
    }

    # add genotypes for this variant to the cache
    push @{$self->{_cache}}, {$variation_id => $cached};

    # shift off first element to keep cache within size limit
    shift @{$self->{_cache}} if scalar @{$self->{_cache}} > $CACHE_SIZE;
  }

  if (defined $sample && defined $sample->dbID){
    if ($sample->isa('Bio::EnsEMBL::Variation::Sample')) {
      @$results = grep {$_->sample->dbID == $sample->dbID} @{$cached};
    }
    elsif ($sample->isa('Bio::EnsEMBL::Variation::Population')) {
      my %include = map {$_->dbID => 1} @{$sample->get_all_Samples};
      @$results = grep {$include{$_->sample->dbID}} @{$cached};
    }
    else {
      throw("Argument supplied is not of type Bio::EnsEMBL::Variation::Sample or Bio::EnsEMBL::Variation::Population");
    }
  }
  else {
    $results = $cached;
  }

  return $results;
}

sub fetch_all_by_Variation_dbID {
  my $self = shift;
  my $dbID = shift;
  return $self->generic_fetch('g.variation_id = '.$dbID);
}

sub fetch_all_by_Slice {
	my $self = shift;

	my $cga = $self->db->get_SampleGenotypeFeatureAdaptor();

	return $cga->fetch_all_by_Slice(@_);
}

sub _tables {
  my $self = shift;
  return (['compressed_genotype_var','g'],['failed_variation','fv']);
}

#Add a left join to the failed_variation table
sub _left_join { return ([ 'failed_variation', 'fv.variation_id = g.variation_id']); }

sub _columns {
  return qw(g.variation_id g.subsnp_id g.genotypes);
}

sub _objs_from_sth {
	my $self = shift;
	my $sth = shift;

	my ($variation_id, $subsnp_id, $genotypes);

	$sth->bind_columns(\$variation_id, \$subsnp_id, \$genotypes);

	my (%sample_hash, %gt_code_hash, @results);
	my %done;
	while ($sth->fetch) {
		my @genotypes = unpack("(ww)*", $genotypes);

		while (@genotypes) {
			my $sample_id = shift @genotypes;
			my $gt_code = shift @genotypes;

      ## temp fix for duplicated 1KG data
      my $ss = $subsnp_id;
      $ss = 0 unless defined $ss  ;
      next if $done{$sample_id}{$gt_code}{$ss};
      $done{$sample_id}{$gt_code}{$ss} = 1;

			my $sgtype  = Bio::EnsEMBL::Variation::SampleGenotype->new_fast({
				_variation_id => $variation_id,
				subsnp        => $subsnp_id,
				adaptor       => $self,
			});

			$sample_hash{$sample_id} ||= [];
			push @{$sample_hash{$sample_id}}, $sgtype;

			$gt_code_hash{$gt_code} ||= [];
			push @{$gt_code_hash{$gt_code}}, $sgtype;

			push @results, $sgtype;
		}
	}

	# fetch samples
	my $sa = $self->db()->get_SampleAdaptor();
	my $samples = $sa->fetch_all_by_dbID_list([keys %sample_hash]);
	foreach my $s (@$samples) {
		foreach my $sgty (@{$sample_hash{$s->dbID()}}) {
			$sgty->{sample} = $s;
		}
	}

	# get all genotypes from codes
	my $gtca = $self->db->get_GenotypeCodeAdaptor();
	my $gtcs = $gtca->fetch_all_by_dbID_list([keys %gt_code_hash]);

	foreach my $gtc(@$gtcs) {
		foreach my $sgty(@{$gt_code_hash{$gtc->dbID}}) {
			$sgty->{genotype} = $gtc->genotype;
      $sgty->{phased}   = $gtc->phased;
		}
	}

	# check for defined genotype and sample
	@results = grep {defined $_->{genotype} && defined $_->{sample}} @results;

	return \@results;
}

1;


text:
angular.module('os.biospecimen.participant.visits', ['os.biospecimen.models'])
  .controller('ParticipantVisitsTreeCtrl', function(
    $scope, $state, $stateParams, $timeout,
    cpr, visits, specimens,
    Specimen) {

    if (!$stateParams.visitId && !$stateParams.eventId && visits && visits.length > 0) {
      $state.go(
        'participant-detail.visits',
        {visitId: visits[0].id, eventId: visits[0].eventId}
      );
      return;
    }

    $scope.cpr = cpr;
    $scope.visits = visits;
    $scope.errorCode = '';
    $scope.visit = {};
    for (var i = 0; i < visits.length; ++i) {
      if ((!!$stateParams.visitId && $stateParams.visitId == visits[i].id) ||
          (!$stateParams.visitId && !!$stateParams.eventId && $stateParams.eventId == visits[i].eventId)) {
        $scope.visit = visits[i];
        break;
      }
    }

    $scope.showVisitDetail = function(event, visitId, eventId) {
      event.preventDefault();
      event.stopPropagation();
      $state.go('visit-detail.overview', {visitId: visitId, eventId: eventId});
    };

    $scope.viewSpr = function(event, visitId, eventId) {
      event.preventDefault();
      event.stopPropagation();
      $state.go('visit-detail.spr', {visitId: visitId, eventId: eventId});
    }

    $scope.reload = function() {
      var visitDetail = {
        visitId: $stateParams.visitId,
        eventId: $stateParams.eventId
      };

      return Specimen.listFor($stateParams.cprId, visitDetail).then(
        function(specimens) {
          $scope.specimens = specimens;
        }
      );
    }

    $scope.specimens = specimens;
  });


text:
package org.droidparts.concurrent.service;

import android.os.Handler;
import android.os.Looper;
import android.os.ResultReceiver;

public class MainThreadResultReceiver extends ResultReceiver {

	public MainThreadResultReceiver() {
		super(new Handler(Looper.getMainLooper()));
	}

}


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

package com.sun.facelets.tag;

import com.sun.facelets.util.ParameterCheck;

/**
 * A TagDecorator that is composed of 1 or more TagDecorator instances. It uses
 * the chain of responsibility pattern to stop processing if any of the
 * TagDecorators return a value other than null.
 *
 * @author Jacob Hookom
 * @version $Id: CompositeTagDecorator.java,v 1.5 2008-07-13 19:01:35 rlubke Exp $
 */
public final class CompositeTagDecorator implements TagDecorator {

    private final TagDecorator[] decorators;

    public CompositeTagDecorator(TagDecorator[] decorators) {
        ParameterCheck.notNull("decorators", decorators);
        this.decorators = decorators;
    }

    /**
     * Uses the chain of responsibility pattern to stop processing if any of
     * the TagDecorators return a value other than null.
     *
     * @see com.sun.facelets.tag.TagDecorator#decorate(com.sun.facelets.tag.Tag)
     */
    public Tag decorate(Tag tag) {
        Tag t = null;
        for (int i = 0; i < this.decorators.length; i++) {
            t = this.decorators[i].decorate(tag);
            if (t != null) {
                return t;
            }
        }
        return tag;
    }

}


text:
=begin
module Stick
module Units

  def self.types;
    @types ||= []
  end

  def self.unit(name, symbol, type)
    system, name = *name.split(':')
    types << Type.new(system, name, :symbol => symbol, :type => type )
  end

  # The Converter class handles the Measure#to method.
  # It's methods are dynamically defined by the
  # base units.

  class Converter

    def ft(measure)

    end

  end

end
end
=end


text:
<component name="ArtifactManager">
  <artifact type="war" name="web-a:war">
    <output-path>$PROJECT_DIR$/playground/web-playground/web-a/target</output-path>
    <root id="archive" name="web-a.war">
      <element id="artifact" artifact-name="web-a:war exploded" />
    </root>
  </artifact>
</component>


text:
package stroom.explorer.client.presenter;

import stroom.alert.client.event.AlertEvent;
import stroom.data.client.event.DataSelectionEvent;
import stroom.data.client.event.DataSelectionEvent.DataSelectionHandler;
import stroom.data.client.event.HasDataSelectionHandlers;
import stroom.dispatch.client.RestFactory;
import stroom.docref.DocRef;
import stroom.explorer.shared.DocumentTypes;
import stroom.explorer.shared.ExplorerNode;
import stroom.explorer.shared.ExplorerTreeFilter;
import stroom.ui.config.client.UiConfigCache;
import stroom.widget.dropdowntree.client.view.DropDownTreeUiHandlers;
import stroom.widget.dropdowntree.client.view.DropDownTreeView;
import stroom.widget.dropdowntree.client.view.QuickFilterTooltipUtil;
import stroom.widget.popup.client.event.HidePopupEvent;
import stroom.widget.popup.client.event.ShowPopupEvent;
import stroom.widget.popup.client.presenter.PopupSize;
import stroom.widget.popup.client.presenter.PopupType;
import stroom.widget.util.client.SelectionType;

import com.google.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
import com.google.web.bindery.event.shared.HandlerRegistration;
import com.gwtplatform.mvp.client.MyPresenterWidget;

class ExplorerDropDownTreePresenter
        extends MyPresenterWidget<DropDownTreeView>
        implements DropDownTreeUiHandlers, HasDataSelectionHandlers<ExplorerNode> {

    private final ExtendedExplorerTree explorerTree;
    private boolean allowFolderSelection;
    private String caption = "Choose item";
    private ExplorerNode selectedExplorerNode;

    @Inject
    ExplorerDropDownTreePresenter(final EventBus eventBus,
                                  final DropDownTreeView view,
                                  final RestFactory restFactory,
                                  final UiConfigCache uiConfigCache) {
        super(eventBus, view);
        getView().setUiHandlers(this);

        explorerTree = new ExtendedExplorerTree(this, restFactory);
        setIncludeNullSelection(true);

        // Add views.
        view.setCellTree(explorerTree);

        uiConfigCache.get()
                .onSuccess(uiConfig ->
                        view.setQuickFilterTooltipSupplier(() -> QuickFilterTooltipUtil.createTooltip(
                                "Choose Item Quick Filter",
                                ExplorerTreeFilter.FIELD_DEFINITIONS,
                                uiConfig.getHelpUrlQuickFilter())));
    }

    public void show() {
        getView().clearFilter();
        refresh();
        final PopupSize popupSize = PopupSize.resizable(400, 550);
        ShowPopupEvent.builder(this)
                .popupType(PopupType.OK_CANCEL_DIALOG)
                .popupSize(popupSize)
                .caption(caption)
                .onShow(e -> getView().focus())
                .onHideRequest(e -> {
                    if (e.isOk()) {
                        final ExplorerNode selected = getSelectedEntityData();
                        if (isSelectionAllowed(selected)) {
                            DataSelectionEvent.fire(ExplorerDropDownTreePresenter.this, selected, false);
                            selectedExplorerNode = selected;
                            e.hide();
                        } else {
                            AlertEvent.fireError(ExplorerDropDownTreePresenter.this,
                                    "You must choose a valid item.", null);
                        }
                    } else {
                        e.hide();
                    }
                })
                .fire();
    }

    protected void setIncludeNullSelection(final boolean includeNullSelection) {
        explorerTree.getTreeModel().setIncludeNullSelection(includeNullSelection);
    }

    protected void setSelectedTreeItem(final ExplorerNode selectedItem,
                                       final SelectionType selectionType,
                                       final boolean initial) {
        // Is the selection type valid?
        if (isSelectionAllowed(selectedItem)) {
            // Drop down presenters need to know what the initial selection was so that they can
            // update the name of their selected item properly.
            if (initial) {
                DataSelectionEvent.fire(this, selectedItem, false);
            } else if (selectionType.isDoubleSelect()) {
                DataSelectionEvent.fire(this, selectedItem, true);
                this.selectedExplorerNode = selectedItem;
                HidePopupEvent.builder(this).fire();
            }
        }
    }

    private boolean isSelectionAllowed(final ExplorerNode selected) {
        if (selected == null) {
            return true;
        }
        if (allowFolderSelection) {
            return true;
        }

        return !DocumentTypes.isFolder(selected.getType());
    }

    @Override
    public void nameFilterChanged(final String text) {
        explorerTree.changeNameFilter(text);
    }

    public void refresh() {
        explorerTree.setSelectedItem(selectedExplorerNode);
        explorerTree.getTreeModel().reset();
        explorerTree.getTreeModel().setEnsureVisible(selectedExplorerNode);
        explorerTree.getTreeModel().refresh();
    }

    public void setIncludedTypes(final String... includedTypes) {
        explorerTree.getTreeModel().setIncludedTypes(includedTypes);
    }

    public void setTags(final String... tags) {
        explorerTree.getTreeModel().setTags(tags);
    }

    public void setRequiredPermissions(final String... requiredPermissions) {
        explorerTree.getTreeModel().setRequiredPermissions(requiredPermissions);
    }

    public DocRef getSelectedEntityReference() {
        final ExplorerNode explorerNode = getSelectedEntityData();
        if (explorerNode == null) {
            return null;
        }
        return explorerNode.getDocRef();
    }

    public void setSelectedEntityReference(final DocRef docRef) {
        setSelectedEntityData(ExplorerNode.create(docRef));
    }

    private ExplorerNode getSelectedEntityData() {
        return resolve(explorerTree.getSelectionModel().getSelected());
    }

    private void setSelectedEntityData(final ExplorerNode explorerNode) {
        this.selectedExplorerNode = explorerNode;
        refresh();
    }

    public void setAllowFolderSelection(final boolean allowFolderSelection) {
        this.allowFolderSelection = allowFolderSelection;
    }

    @Override
    public HandlerRegistration addDataSelectionHandler(final DataSelectionHandler<ExplorerNode> handler) {
        return addHandlerToSource(DataSelectionEvent.getType(), handler);
    }

    private static ExplorerNode resolve(final ExplorerNode selection) {
        if (selection == ExplorerTreeModel.NULL_SELECTION) {
            return null;
        }

        return selection;
    }

    public void setCaption(final String caption) {
        this.caption = caption;
    }

    private static class ExtendedExplorerTree extends ExplorerTree {

        private final ExplorerDropDownTreePresenter explorerDropDownTreePresenter;

        public ExtendedExplorerTree(final ExplorerDropDownTreePresenter explorerDropDownTreePresenter,
                                    final RestFactory restFactory) {
            super(restFactory, false);
            this.explorerDropDownTreePresenter = explorerDropDownTreePresenter;
        }

        @Override
        protected void setInitialSelectedItem(final ExplorerNode selection) {
            super.setInitialSelectedItem(selection);
            explorerDropDownTreePresenter.setSelectedTreeItem(resolve(selection),
                    new SelectionType(false, false),
                    true);
        }

        @Override
        protected void doSelect(final ExplorerNode row, final SelectionType selectionType) {
            super.doSelect(row, selectionType);
            explorerDropDownTreePresenter.setSelectedTreeItem(resolve(row), selectionType, false);
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Mirza Baig-FRONT END NINJA</title>
    <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Lato:100,300,400,700,900,100italic,300italic,400italic,700italic,900italic&subset=latin,latin-ext">

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

Mirza Baig

Front-end Ninja

Featured Work

Appify

Link to project

Appify

Link to project

Appify

Link to project

Appify

Link to project

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

Portfolio 1

Appify

Link to project

                        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam lacinia neque quis lectus hendrerit, nec pellentesque mauris ultrices. Donec mattis elementum metus at gravida. Aliquam imperdiet libero mi, nec vehicula leo suscipit a. Integer consectetur semper lorem id vulputate. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aliquam erat volutpat. Aenean ut dignissim orci.

                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

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

Portfolio 2

Appify

Link to project

                        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam lacinia neque quis lectus hendrerit, nec pellentesque mauris ultrices. Donec mattis elementum metus at gravida. Aliquam imperdiet libero mi, nec vehicula leo suscipit a. Integer consectetur semper lorem id vulputate. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aliquam erat volutpat. Aenean ut dignissim orci.

                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

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

Portfolio 3

Appify

Link to project

                        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam lacinia neque quis lectus hendrerit, nec pellentesque mauris ultrices. Donec mattis elementum metus at gravida. Aliquam imperdiet libero mi, nec vehicula leo suscipit a. Integer consectetur semper lorem id vulputate. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aliquam erat volutpat. Aenean ut dignissim orci.

                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

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

Portfolio 4

Appify

Link to project

                        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam lacinia neque quis lectus hendrerit, nec pellentesque mauris ultrices. Donec mattis elementum metus at gravida. Aliquam imperdiet libero mi, nec vehicula leo suscipit a. Integer consectetur semper lorem id vulputate. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aliquam erat volutpat. Aenean ut dignissim orci.

                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>


text:
"""
Build a simple bare-minimum quantum circuit that starts with a single
qubit (by default, in state 0), runs the experiment 1000 times, and
finally prints the total count of the states finally observed.
Qiskit Docs: https://qiskit.org/documentation/getting_started.html
"""

import qiskit

def single_qubit_measure(
    qubits: int, classical_bits: int
) -> qiskit.result.counts.Counts:
    """
    >>> single_qubit_measure(1, 1)
    {'0': 1000}
    """
    # Use Aer's simulator
    simulator = qiskit.Aer.get_backend("aer_simulator")

    # Create a Quantum Circuit acting on the q register
    circuit = qiskit.QuantumCircuit(qubits, classical_bits)

    # Map the quantum measurement to the classical bits
    circuit.measure([0], [0])

    # Execute the circuit on the simulator
    job = qiskit.execute(circuit, simulator, shots=1000)

    # Return the histogram data of the results of the experiment.
    return job.result().get_counts(circuit)

if __name__ == "__main__":
    print(f"Total count for various states are: {single_qubit_measure(1, 1)}")


text:
package main;

public class Solution {
	//MVP, Stretch 1
	public String reverse(String string) {
		return "";
	}

	//Stretch 2
	public String reverseInPlace(String string) {
		return "";
	}

	//Stretch 3
	public String advancedReverse(String string) {
		return "";
	}

}


text:
'use strict';
var assert = require('assert');

describe('outer suite', function() {
  var runOrder = [];
  before(function() {
    runOrder.push('outer before');
    this.skip();
  });

  it('should never run this outer test', function() {
    throw new Error('outer suite test should not run');
  });

  describe('inner suite', function() {
    before(function() { runOrder.push('no inner before'); });
    before(function(done) { runOrder.push('no inner before'); done(); });
    before(async function() { runOrder.push('no inner before'); });
    before(function() { return Promise.resolve(runOrder.push('no inner before')) });

    after(function() { runOrder.push('no inner after'); });
    after(function(done) { runOrder.push('no inner after'); done(); });
    after(async function() { runOrder.push('no inner after'); });
    after(function() { return Promise.resolve(runOrder.push('no inner after')) });

    it('should never run this inner test', function() {
      throw new Error('inner suite test should not run');
    });
  });

  after(function() {
    runOrder.push('outer after');
    assert.deepStrictEqual(runOrder, [
      'outer before', 'outer after'
    ]);
    throw new Error('should throw this error');
  });
});


text:
$(document).ready(function() {
	frappe.assets.check();
	frappe.provide('frappe.app');
	$.extend(frappe.app, new frappe.Application());
});

frappe.Application = Class.extend({
	init: function() {
		this.load_startup();
	},

	load_startup: function() {
		var me = this;
		if(window.app) {
			return frappe.call({
				method: 'startup',
				callback: function(r, rt) {
					frappe.provide('frappe.boot');
					frappe.boot = r;
					if(frappe.boot.user.name==='Guest' || frappe.boot.user.user_type==="Website User") {
						window.location = 'index';
						return;
					}
					me.startup();
				}
			});
		} else {
			this.startup();
		}
	},
	startup: function() {
		// load boot info
		this.load_bootinfo();

		// page container
		this.make_page_container();

		// navbar
		this.make_nav_bar();

		// favicon
		this.set_favicon();

		if(user!="Guest") this.set_user_display_settings();

		this.setup_keyboard_shortcuts();

		// control panel startup code
		this.run_startup_js();

		if(frappe.boot) {
			if(localStorage.getItem("session_lost_route")) {
				window.location.hash = localStorage.getItem("session_lost_route");
				localStorage.removeItem("session_lost_route");
			}

			// route to home page
			frappe.route();
		}

		// trigger app startup
		$(document).trigger('startup');

		this.start_notification_updates();

		$(document).trigger('app_ready');
	},

	set_user_display_settings: function() {
		frappe.ui.set_user_background(frappe.boot.user.background_image, null,
			frappe.boot.user.background_style);
	},

	load_bootinfo: function() {
		if(frappe.boot) {
			frappe.modules = frappe.boot.modules;
			this.check_metadata_cache_status();
			this.set_globals();
			this.sync_pages();
			if(frappe.boot.timezone_info) {
				moment.tz.add(frappe.boot.timezone_info);
			}
			if(frappe.boot.print_css) {
				frappe.dom.set_style(frappe.boot.print_css)
			}
		} else {
			this.set_as_guest();
		}
	},

	check_metadata_cache_status: function() {
		if(frappe.boot.metadata_version != localStorage.metadata_version) {
			localStorage.clear();
			console.log("Cleared Cache - New Metadata");
			frappe.assets.init_local_storage();
		}
	},

	start_notification_updates: function() {
		var me = this;
		setInterval(function() {
			me.refresh_notifications();
		}, 30000);

		// first time loaded in boot
		$(document).trigger("notification-update");

		// refresh notifications if user is back after sometime
		$(document).on("session_alive", function() {
			me.refresh_notifications();
		})
	},

	refresh_notifications: function() {
		if(frappe.session_alive) {
			return frappe.call({
				method: "frappe.core.doctype.notification_count.notification_count.get_notifications",
				callback: function(r) {
					if(r.message) {
						$.extend(frappe.boot.notification_info, r.message);
						$(document).trigger("notification-update");
					}
				},
				no_spinner: true
			});
		}
	},

	set_globals: function() {
		// for backward compatibility
		user = frappe.boot.user.name;
		user_fullname = frappe.user_info(user).fullname;
		user_defaults = frappe.boot.user.defaults;
		user_roles = frappe.boot.user.roles;
		user_email = frappe.boot.user.email;
		sys_defaults = frappe.boot.sysdefaults;
	},
	sync_pages: function() {
		// clear cached pages if timestamp is not found
		if(localStorage["page_info"]) {
			frappe.boot.allowed_pages = [];
			page_info = JSON.parse(localStorage["page_info"]);
			$.each(frappe.boot.page_info, function(name, p) {
				if(!page_info[name] || (page_info[name].modified != p.modified)) {
					delete localStorage["_page:" + name];
				}
				frappe.boot.allowed_pages.push(name);
			});
		} else {
			frappe.boot.allowed_pages = keys(frappe.boot.page_info);
		}
		localStorage["page_info"] = JSON.stringify(frappe.boot.page_info);
	},
	set_as_guest: function() {
		// for backward compatibility
		user = {name:'Guest'};
		user = 'Guest';
		user_fullname = 'Guest';
		user_defaults = {};
		user_roles = ['Guest'];
		user_email = '';
		sys_defaults = {};
	},
	make_page_container: function() {
		if($("#body_div").length) {
			$(".splash").remove();
			frappe.temp_container = $("<div id='temp-container' style='display: none;'>")
				.appendTo("body");
			frappe.container = new frappe.views.Container();
		}
	},
	make_nav_bar: function() {
		// toolbar
		if(frappe.boot) {
			frappe.container.frappe_toolbar = new frappe.ui.toolbar.Toolbar();
		}
	},
	logout: function() {
		var me = this;
		me.logged_out = true;
		return frappe.call({
			method:'logout',
			callback: function(r) {
				if(r.exc) {
					console.log(r.exc);
					return;
				}
				me.redirect_to_login();
			}
		})
	},
	redirect_to_login: function() {
		window.location.href = '/';
	},
	set_favicon: function() {
		var link = $('link[type="image/x-icon"]').remove().attr("href");
		$('<link rel="shortcut icon" href="' + link + '" type="image/x-icon">').appendTo("head");
		$('<link rel="icon" href="' + link + '" type="image/x-icon">').appendTo("head");
	},

	setup_keyboard_shortcuts: function() {
		$(document)
			.keydown("meta+g ctrl+g", function(e) {
				frappe.ui.toolbar.search.show();
				return false;
			})
			.keydown("meta+s ctrl+s", function(e) {
				e.preventDefault();
				if(cur_frm) {
					cur_frm.save_or_update();
				} else if(frappe.container.page.save_action) {
					frappe.container.page.save_action();
				}
				return false;
			})
			.keydown("esc", function(e) {
				var open_row = $(".grid-row-open");
				if(open_row.length) {
					var grid_row = open_row.data("grid_row");
					grid_row.toggle_view(false);
				}
				return false;
			})
			.keydown("ctrl+down meta+down", function(e) {
				var open_row = $(".grid-row-open");
				if(open_row.length) {
					var grid_row = open_row.data("grid_row");
					grid_row.toggle_view(false, function() { grid_row.open_next() });
					return false;
				}
			})
			.keydown("ctrl+up meta+up", function(e) {
				var open_row = $(".grid-row-open");
				if(open_row.length) {
					var grid_row = open_row.data("grid_row");
					grid_row.toggle_view(false, function() { grid_row.open_prev() });
					return false;
				}
			})
			.keydown("ctrl+n meta+n", function(e) {
				var open_row = $(".grid-row-open");
				if(open_row.length) {
					var grid_row = open_row.data("grid_row");
					grid_row.toggle_view(false, function() { grid_row.grid.add_new_row(grid_row.doc.idx, null, true); });
					return false;
				}
			})

	},

	run_startup_js: function() {
		if(frappe.boot.startup_js)
			eval(frappe.boot.startup_js);
	}
})


text:
using UnityEngine;
using System.Collections;

public static class Noise
{
	// Lacunarity currently has to be NOT an integer value or it fucks up.
	public static float[,] GenerateNoiseMap(int mapWidth, int mapHeight, int seed, float scale, int octaves, float persistance, float lacunarity, Vector2 offset) {
		float[,] noiseMap = new float[mapWidth,mapHeight];

		System.Random prng = new System.Random (seed);
		Vector2[] octaveOffsets = new Vector2[octaves];
		for (int i = 0; i < octaves; i++) {
			float offsetX = prng.Next (-100000, 100000) + offset.x;
			float offsetY = prng.Next (-100000, 100000) + offset.y;
			octaveOffsets [i] = new Vector2 (offsetX, offsetY);
		}

		if (scale <= 0) {
			scale = 0.0001f;
		}

		// I'm making inverse scale to multiply by this value later instead of dividing by scale.
		// multiplication is cheaper
		float inverseScale = 1 / scale;
		// These values are used so that changing the scale value will "zoom" the noise in/out of the middle.
		// Without these it zooms in the top right corner.
		float halfWidth = mapWidth / 2f;
		float halfHeight = mapHeight / 2f;

		float maxNoiseHeight = float.MinValue;
		float minNoiseHeight = float.MaxValue;

		for (int y = 0; y < mapHeight; y++) {
			for (int x = 0; x < mapWidth; x++) {

				float amplitude = 1;
				float frequency = 1;
				float noiseHeight = 0;

				for (int i = 0; i < octaves; i++) {
					float perlinX = ((x - halfWidth) * inverseScale) * frequency + octaveOffsets[i].x;
					float perlinY = ((y - halfHeight) * inverseScale) * frequency + octaveOffsets[i].y;

					float perlinValue = Mathf.PerlinNoise (perlinX, perlinY) * 2 - 1;
					noiseHeight += perlinValue * amplitude;

					amplitude *= persistance;
					frequency *= lacunarity;
				}

				if (noiseHeight > maxNoiseHeight) {
					maxNoiseHeight = noiseHeight;
				} else if (noiseHeight < minNoiseHeight) {
					minNoiseHeight = noiseHeight;
				}

				noiseMap [x, y] = noiseHeight;
			}
		}

		for (int y = 0; y < mapHeight; y++) {
			for (int x = 0; x < mapWidth; x++) {
				noiseMap [x, y] = Mathf.InverseLerp (minNoiseHeight, maxNoiseHeight, noiseMap [x, y]);
			}
		}

		return noiseMap;
	}

}


text:
===================
python-gerritclient
===================

This is a CLI tool and Python API wrapper for
`Gerrit Code Review <https://www.gerritcodereview.com/>`_.

User Documentation
------------------

.. toctree::
   :maxdepth: 3

   cli/index


text:
// @flow
import SourceLocation from "./SourceLocation";

/**
 * Interface required to break circular dependency between Token, Lexer, and
 * ParseError.
 */
export interface LexerInterface {input: string, pos: number}

/**
 * The resulting token returned from `lex`.
 *
 * It consists of the token text plus some position information.
 * The position information is essentially a range in an input string,
 * but instead of referencing the bare input string, we refer to the lexer.
 * That way it is possible to attach extra metadata to the input string,
 * like for example a file name or similar.
 *
 * The position information is optional, so it is OK to construct synthetic
 * tokens if appropriate. Not providing available position information may
 * lead to degraded error reporting, though.
 */
export class Token {
    text: string;
    loc: ?SourceLocation;

    constructor(
        text: string,           // the text of this token
        loc: ?SourceLocation,
    ) {
        this.text = text;
        this.loc = loc;
    }

    /**
     * Given a pair of tokens (this and endToken), compute a `Token` encompassing
     * the whole input range enclosed by these two.
     */
    range(
        endToken: Token,  // last token of the range, inclusive
        text: string,     // the text of the newly constructed token
    ) {
        return new Token(text, SourceLocation.range(this, endToken));
    }
}


text:
#region License

#endregion

#region Imports

using System;
using System.Reflection;

#endregion

namespace Spring.Aop.Support
{
	///
	/// Various utility methods relating to the composition of
	/// <see cref="Spring.Aop.IMethodMatcher"/>s.
	///
	/// <remarks>
	///

	/// A method matcher may be evaluated statically (based on method and target
	/// class) or need further evaluation dynamically (based on arguments at
	/// the time of method invocation).
	///

	/// </remarks>
	/// <author>Rod Johnson</author>
	/// <author>Aleksandar Seovic (.NET)</author>
    public sealed class MethodMatchers
	{
		///
		/// Creates a new <see cref="Spring.Aop.IMethodMatcher"/> that is the
		/// union of the two supplied <see cref="Spring.Aop.IMethodMatcher"/>s.
		///
		/// <remarks>
		///

		/// The newly created matcher will match all the methods that either of the two
		/// supplied matchers would match.
		///

		/// </remarks>
		/// <param name="firstMatcher">The first method matcher.</param>
		/// <param name="secondMatcher">The second method matcher.</param>
		/// <returns>
		/// A new <see cref="Spring.Aop.IMethodMatcher"/> that is the
		/// union of the two supplied <see cref="Spring.Aop.IMethodMatcher"/>s
		/// </returns>
		public static IMethodMatcher Union(
			IMethodMatcher firstMatcher, IMethodMatcher secondMatcher)
		{
			return new UnionMethodMatcher(firstMatcher, secondMatcher);
		}

		///
		/// Creates a new <see cref="Spring.Aop.IMethodMatcher"/> that is the
		/// intersection of the two supplied <see cref="Spring.Aop.IMethodMatcher"/>s.
		///
		/// <remarks>
		///

		/// The newly created matcher will match only those methods that both
		/// of the supplied matchers would match.
		///

		/// </remarks>
		/// <param name="firstMatcher">The first method matcher.</param>
		/// <param name="secondMatcher">The second method matcher.</param>
		/// <returns>
		/// A new <see cref="Spring.Aop.IMethodMatcher"/> that is the
		/// intersection of the two supplied <see cref="Spring.Aop.IMethodMatcher"/>s
		/// </returns>
		public static IMethodMatcher Intersection(
			IMethodMatcher firstMatcher, IMethodMatcher secondMatcher)
		{
			return new IntersectionMethodMatcher(firstMatcher, secondMatcher);
		}

		#region Inner Class : UnionMethodMatcher

        [Serializable]
        private sealed class UnionMethodMatcher : IMethodMatcher
		{
			private IMethodMatcher a;
			private IMethodMatcher b;

			public UnionMethodMatcher(IMethodMatcher a, IMethodMatcher b)
			{
				this.a = a;
				this.b = b;
			}

			public bool IsRuntime
			{
				get { return a.IsRuntime || b.IsRuntime; }
			}

			public bool Matches(MethodInfo m, Type targetType)
			{
				return a.Matches(m, targetType) || b.Matches(m, targetType);
			}

			public bool Matches(MethodInfo m, Type targetType, object[] args)
			{
				return a.Matches(m, targetType, args) || b.Matches(m, targetType, args);
			}
		}

		#endregion

		#region Inner Class : IntersectionMethodMatcher

        [Serializable]
        private sealed class IntersectionMethodMatcher : IMethodMatcher
		{
			private IMethodMatcher a;
			private IMethodMatcher b;

			public IntersectionMethodMatcher(IMethodMatcher a, IMethodMatcher b)
			{
				this.a = a;
				this.b = b;
			}

			public bool IsRuntime
			{
				get { return a.IsRuntime || b.IsRuntime; }
			}

			public bool Matches(MethodInfo m, Type targetType)
			{
				return a.Matches(m, targetType) && b.Matches(m, targetType);
			}

			public bool Matches(MethodInfo m, Type targetType, object[] args)
			{
				// Because a dynamic intersection may be composed of a static and dynamic part,
				// we must avoid calling the 3-arg matches method on a dynamic matcher, as
				// it will probably be an unsupported operation.
				bool aMatches = a.IsRuntime ? a.Matches(m, targetType, args) : a.Matches(m, targetType);
				bool bMatches = b.IsRuntime ? b.Matches(m, targetType, args) : b.Matches(m, targetType);
				return aMatches && bMatches;
			}
		}

		#endregion

		#region Constructor (s) / Destructor

		// CLOVER:OFF

		///
		/// Creates a new instance of the
		/// <see cref="Spring.Aop.Support.MethodMatchers"/> class.
		///
		/// <remarks>
		///

		/// This is a utility class, and as such has no publicly
		/// visible constructors.
		///

		/// </remarks>
		private MethodMatchers()
		{
		}

		// CLOVER:ON

		#endregion
	}
}


text:
import os
import logging

from django.conf import settings
from django.conf.urls.defaults import *
from django.contrib import admin

from webapp.introspection import prosthetics

admin.autodiscover()

handler500 = 'djangotoolbox.errorviews.server_error'

raw_patterns = [

    (r'^accounts/', include('gaeauth.urls')),

    (r'^admin/accesstoken_action/(\d+)/$', 'webapp.admin.admin_action'),
    (r'^admin/accesstoken_blog/(\d+)/$', 'webapp.admin.view_blog'),
    (r'^admin/', include(admin.site.urls)),

    (r'^login/$', 'django.contrib.auth.views.login'),
    (r'^logout/$', 'django.contrib.auth.views.logout'),

    (r'^start_authorizing/(\w+)/$', "webapp.views.start_authorizing"),
    (r'^oauth_callback/$', "webapp.views.oauth_callback"),

    (r'^$', "webapp.views.home"),
    (r'^call/(.*?)/$', "webapp.views.call"),
    (r'^prosthetic/$', "webapp.views.prosthetics"),
    (r'^prosthetic/(\w+)/$', "webapp.views.prosthetic"),

    (r'^runner/run_cron/$', "webapp.views.cron"),
    (r'^runner/run_task/$', "webapp.views.task"),
    (r'^runner/ping_phloor/$', 'webapp.views.ping'),

    (r'^callback/$', "webapp.views.callback"),

    (r'^errormon/', include('errormon.urls')),
]

# this is for backwards-compatibility. Pity.
if "dreamer" in settings.INSTALLED_APPS:
    raw_patterns.append((r'^dreamImage/(.*?)/$', "dreamer.views.dreamImage"))

for name in prosthetics:
    if os.path.exists(os.path.join(os.path.dirname(__file__), name, "urls.py")):
        __import__("%s.urls"%name)
        raw_patterns.append( ('^%s/'%name, include(name+".urls")) )

#logging.info("raw_patterns is %s"%(repr(raw_patterns)))

urlpatterns = patterns('', *raw_patterns)


text:
using System.Runtime.InteropServices;

namespace System.Diagnostics
{
    /// <summary>
    /// Indicates the code following the attribute is to be executed in run, not step, mode.
    /// </summary>
    [SerializableAttribute]
    [AttributeUsageAttribute(AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
    [ComVisible(true)]
	public sealed class DebuggerStepperBoundaryAttribute : Attribute
	{
	}
}


text:
package datamodeling

import ()

/*	Consistent read behavior.
	CONSISTANT
	EVENTUAL */
type ConsistentReads uint

const (
	EVENTUAL ConsistentReads = iota
	CONSISTANT
)

/*	Behaviors for the save operation.
	APPEND_SET Treats scalar attributes (String, Number, Binary) the same as UPDATE_SKIP_NULL_ATTRIBUTES does.
	CLOBBER Will clear and replace all attributes, included unmodeled ones, (delete and recreate) on save.
	UPDATE Will not affect unmodeled attributes on a save operation and a null value for the modeled attribute will remove it from that item in DynamoDB.
	UPDATE_SKIP_NULL_ATTRIBUTES Is similar to UPDATE, except that it ignores any null value attribute(s) and will NOT remove them from that item in DynamoDB. */
type SaveBehavior uint

const (
	UPDATE SaveBehavior = iota
	CLOBBER
	UPDATE_SKIP_NULL_ATTRIBUTES
)

/*	Pagination loading strategy.
	EAGER_LOADING Paginated list will eagerly load all the paginated results from DynamoDB as soon as the list is initialized.
	ITERATION_ONLY Only supports using iterator to read from the paginated list.
	LAZY_LOADING Paginated list is lazily loaded when possible, and all loaded results are kept in the memory. */
type PaginationLoadingStrategy uint

const (
	LAZY_LOADING PaginationLoadingStrategy = iota
	EAGER_LOADING
	ITERATION_ONLY
)

// Configuration struct for service call behavior. An instance of this configuration is supplied to every DynamoDBMapper at construction;
// if not provided explicitly, DEFAULT is used. New instances can be given to the mapper object on individual save, load, and delete
// operations to override the defaults.
type DynamoDBMapperConfig struct {
	ConsistentReads           ConsistentReads           // Defaults to EVENTUAL
	SaveBehavior              SaveBehavior              // Defaults to UPDATE
	PaginationLoadingStrategy PaginationLoadingStrategy // Defaults to LAZY_LOADING
}