text:
package resource

import (
	"encoding/json"
	"io/ioutil"
	"net/http"

	"github.com/nuclio/nuclio/pkg/common"
	"github.com/nuclio/nuclio/pkg/dashboard"
	"github.com/nuclio/nuclio/pkg/opa"
	"github.com/nuclio/nuclio/pkg/platform"
	"github.com/nuclio/nuclio/pkg/restful"

	"github.com/google/uuid"
	"github.com/nuclio/errors"
	"github.com/nuclio/nuclio-sdk-go"
)

type functionEventResource struct {
	*resource
}

type functionEventInfo struct {
	Meta *platform.FunctionEventMeta `json:"metadata,omitempty"`
	Spec *platform.FunctionEventSpec `json:"spec,omitempty"`
}

func (fer *functionEventResource) ExtendMiddlewares() error {
	fer.resource.addAuthMiddleware(nil)
	return nil
}

// GetAll returns all function events
func (fer *functionEventResource) GetAll(request *http.Request) (map[string]restful.Attributes, error) {
	ctx := request.Context()
	response := map[string]restful.Attributes{}

	// get namespace
	namespace := fer.getNamespaceFromRequest(request)
	if namespace == "" {
		return nil, nuclio.NewErrBadRequest("Namespace must exist")
	}

	getFunctionEventOptions := platform.GetFunctionEventsOptions{
		Meta: platform.FunctionEventMeta{
			Name:      request.Header.Get("x-nuclio-function-event-name"),
			Namespace: fer.getNamespaceFromRequest(request),
		},
		AuthSession: fer.getCtxSession(ctx),
		PermissionOptions: opa.PermissionOptions{
			MemberIds:           opa.GetUserAndGroupIdsFromAuthSession(fer.getCtxSession(ctx)),
			OverrideHeaderValue: request.Header.Get(opa.OverrideHeader),
		},
	}

	// get function name
	functionName := fer.getFunctionNameFromRequest(request)
	if functionName != "" {
		getFunctionEventOptions.Meta.Labels = map[string]string{
			"nuclio.io/function-name": functionName,
		}
	}

	functionEvents, err := fer.getPlatform().GetFunctionEvents(ctx, &getFunctionEventOptions)

	if err != nil {
		return nil, errors.Wrap(err, "Failed to get function events")
	}

	// create a map of attributes keyed by the function event id (name)
	for _, functionEvent := range functionEvents {
		response[functionEvent.GetConfig().Meta.Name] = fer.functionEventToAttributes(functionEvent)
	}

	return response, nil
}

// GetByID returns a specific function event by id
func (fer *functionEventResource) GetByID(request *http.Request, id string) (restful.Attributes, error) {
	ctx := request.Context()

	// get namespace
	namespace := fer.getNamespaceFromRequest(request)
	if namespace == "" {
		return nil, nuclio.NewErrBadRequest("Namespace must exist")
	}

	functionEvent, err := fer.getPlatform().GetFunctionEvents(ctx, &platform.GetFunctionEventsOptions{
		Meta: platform.FunctionEventMeta{
			Name:      id,
			Namespace: fer.getNamespaceFromRequest(request),
		},
		AuthSession: fer.getCtxSession(ctx),
		PermissionOptions: opa.PermissionOptions{
			MemberIds:           opa.GetUserAndGroupIdsFromAuthSession(fer.getCtxSession(ctx)),
			RaiseForbidden:      true,
			OverrideHeaderValue: request.Header.Get(opa.OverrideHeader),
		},
	})

	if err != nil {
		return nil, errors.Wrap(err, "Failed to get function event")
	}

	if len(functionEvent) == 0 {
		return nil, nuclio.NewErrNotFound("Function event not found")
	}

	return fer.functionEventToAttributes(functionEvent[0]), nil
}

// Create deploys a function event
func (fer *functionEventResource) Create(request *http.Request) (id string, attributes restful.Attributes, responseErr error) {

	functionEventInfo, responseErr := fer.getFunctionEventInfoFromRequest(request, false)
	if responseErr != nil {
		return
	}

	// if the name wasn't specified, generate something
	if functionEventInfo.Meta.Name == "" {
		functionEventInfo.Meta.Name = uuid.New().String()
	}

	newFunctionEvent, err := fer.storeAndDeployFunctionEvent(request, functionEventInfo)
	if err != nil {
		return "", nil, nuclio.WrapErrInternalServerError(err)
	}

	// set attributes
	attributes = fer.functionEventToAttributes(newFunctionEvent)

	return
}

// returns a list of custom routes for the resource
func (fer *functionEventResource) GetCustomRoutes() ([]restful.CustomRoute, error) {

	// since delete and update by default assume /resource/{id} and we want to get the id/namespace from the body
	// we need to register custom routes
	return []restful.CustomRoute{
		{
			Pattern:   "/",
			Method:    http.MethodPut,
			RouteFunc: fer.updateFunctionEvent,
		},
		{
			Pattern:   "/",
			Method:    http.MethodDelete,
			RouteFunc: fer.deleteFunctionEvent,
		},
	}, nil
}

func (fer *functionEventResource) storeAndDeployFunctionEvent(request *http.Request,
	functionEvent *functionEventInfo) (platform.FunctionEvent, error) {
	ctx := request.Context()

	// create a functionEvent config
	functionEventConfig := platform.FunctionEventConfig{
		Meta: *functionEvent.Meta,
		Spec: *functionEvent.Spec,
	}

	// create a functionEvent
	newFunctionEvent, err := platform.NewAbstractFunctionEvent(fer.Logger, fer.getPlatform(), functionEventConfig)
	if err != nil {
		return nil, err
	}

	// just deploy. the status is async through polling
	err = fer.getPlatform().CreateFunctionEvent(ctx, &platform.CreateFunctionEventOptions{
		FunctionEventConfig: *newFunctionEvent.GetConfig(),
		AuthSession:         fer.getCtxSession(ctx),
		PermissionOptions: opa.PermissionOptions{
			MemberIds:           opa.GetUserAndGroupIdsFromAuthSession(fer.getCtxSession(ctx)),
			OverrideHeaderValue: request.Header.Get(opa.OverrideHeader),
		},
	})
	if err != nil {
		return nil, err
	}

	return newFunctionEvent, nil
}

func (fer *functionEventResource) getFunctionEvents(request *http.Request, function platform.Function, namespace string) []platform.FunctionEvent {
	ctx := request.Context()

	getFunctionEventOptions := platform.GetFunctionEventsOptions{
		Meta: platform.FunctionEventMeta{
			Name:      "",
			Namespace: namespace,
			Labels: map[string]string{
				"nuclio.io/function-name": function.GetConfig().Meta.Name,
			},
		},
		AuthSession: fer.getCtxSession(ctx),
		PermissionOptions: opa.PermissionOptions{
			MemberIds:           opa.GetUserAndGroupIdsFromAuthSession(fer.getCtxSession(ctx)),
			OverrideHeaderValue: request.Header.Get(opa.OverrideHeader),
		},
	}

	functionEvents, err := fer.getPlatform().GetFunctionEvents(ctx, &getFunctionEventOptions)
	if err == nil {
		return functionEvents
	}

	return []platform.FunctionEvent{}
}

func (fer *functionEventResource) deleteFunctionEvent(request *http.Request) (*restful.CustomRouteFuncResponse, error) {
	ctx := request.Context()

	// get function event config and status from body
	functionEventInfo, err := fer.getFunctionEventInfoFromRequest(request, true)
	if err != nil {
		fer.Logger.WarnWithCtx(ctx, "Failed to get function event config and status from body", "err", err)

		return &restful.CustomRouteFuncResponse{
			Single:     true,
			StatusCode: http.StatusBadRequest,
		}, err
	}

	deleteFunctionEventOptions := platform.DeleteFunctionEventOptions{
		AuthSession: fer.getCtxSession(ctx),
		PermissionOptions: opa.PermissionOptions{
			MemberIds:           opa.GetUserAndGroupIdsFromAuthSession(fer.getCtxSession(ctx)),
			OverrideHeaderValue: request.Header.Get(opa.OverrideHeader),
		},
	}
	deleteFunctionEventOptions.Meta = *functionEventInfo.Meta

	err = fer.getPlatform().DeleteFunctionEvent(ctx, &deleteFunctionEventOptions)
	if err != nil {
		return &restful.CustomRouteFuncResponse{
			Single:     true,
			StatusCode: http.StatusInternalServerError,
		}, err
	}

	return &restful.CustomRouteFuncResponse{
		ResourceType: "functionEvent",
		Single:       true,
		StatusCode:   http.StatusNoContent,
	}, err
}

func (fer *functionEventResource) updateFunctionEvent(request *http.Request) (*restful.CustomRouteFuncResponse, error) {
	ctx := request.Context()
	statusCode := http.StatusNoContent

	// get function event config and status from body
	functionEventInfo, err := fer.getFunctionEventInfoFromRequest(request, true)
	if err != nil {
		fer.Logger.WarnWithCtx(ctx, "Failed to get function event config and status from body", "err", err)

		return &restful.CustomRouteFuncResponse{
			Single:     true,
			StatusCode: http.StatusBadRequest,
		}, err
	}

	functionEventConfig := platform.FunctionEventConfig{
		Meta: *functionEventInfo.Meta,
		Spec: *functionEventInfo.Spec,
	}

	if err = fer.getPlatform().UpdateFunctionEvent(ctx, &platform.UpdateFunctionEventOptions{
		FunctionEventConfig: functionEventConfig,
		AuthSession:         fer.getCtxSession(ctx),
		PermissionOptions: opa.PermissionOptions{
			MemberIds:           opa.GetUserAndGroupIdsFromAuthSession(fer.getCtxSession(ctx)),
			OverrideHeaderValue: request.Header.Get(opa.OverrideHeader),
		},
	}); err != nil {
		fer.Logger.WarnWith("Failed to update function event", "err", err)
		statusCode = common.ResolveErrorStatusCodeOrDefault(err, http.StatusInternalServerError)
	}

	// return the stuff
	return &restful.CustomRouteFuncResponse{
		ResourceType: "functionEvent",
		Single:       true,
		StatusCode:   statusCode,
	}, err
}

func (fer *functionEventResource) functionEventToAttributes(functionEvent platform.FunctionEvent) restful.Attributes {
	attributes := restful.Attributes{
		"metadata": functionEvent.GetConfig().Meta,
		"spec":     functionEvent.GetConfig().Spec,
	}

	return attributes
}

func (fer *functionEventResource) getNamespaceFromRequest(request *http.Request) string {
	return fer.getNamespaceOrDefault(request.Header.Get("x-nuclio-function-event-namespace"))
}

func (fer *functionEventResource) getFunctionNameFromRequest(request *http.Request) string {
	return request.Header.Get("x-nuclio-function-name")
}

func (fer *functionEventResource) getFunctionEventInfoFromRequest(request *http.Request, nameRequired bool) (*functionEventInfo, error) {

	// read body
	body, err := ioutil.ReadAll(request.Body)
	if err != nil {
		return nil, nuclio.WrapErrInternalServerError(errors.Wrap(err, "Failed to read body"))
	}

	functionEventInfoInstance := functionEventInfo{}
	err = json.Unmarshal(body, &functionEventInfoInstance)
	if err != nil {
		return nil, nuclio.WrapErrBadRequest(errors.Wrap(err, "Failed to parse JSON body"))
	}

	// override namespace if applicable
	if functionEventInfoInstance.Meta != nil {
		functionEventInfoInstance.Meta.Namespace = fer.getNamespaceOrDefault(functionEventInfoInstance.Meta.Namespace)
	}

	// meta must exist
	if functionEventInfoInstance.Meta == nil ||
		(nameRequired && functionEventInfoInstance.Meta.Name == "") ||
		functionEventInfoInstance.Meta.Namespace == "" {
		err := errors.New("Function event name must be provided in metadata")

		return nil, nuclio.WrapErrBadRequest(err)
	}

	return &functionEventInfoInstance, nil
}

// register the resource
var functionEventResourceInstance = &functionEventResource{
	resource: newResource("api/function_events", []restful.ResourceMethod{
		restful.ResourceMethodGetList,
		restful.ResourceMethodGetDetail,
		restful.ResourceMethodCreate,
	}),
}

func init() {
	functionEventResourceInstance.Resource = functionEventResourceInstance
	functionEventResourceInstance.Register(dashboard.DashboardResourceRegistrySingleton)
}


text:
'use strict';

describe('Service: departamento', function () {

  // load the service's module
  beforeEach(module('administracionRemotaApp'));

  // instantiate service
  var departamento;
  beforeEach(inject(function (_departamento_) {
    departamento = _departamento_;
  }));

  it('should do something', function () {
    expect(!!departamento).to.be.true;
  });

});

redpajama_set_name: RedPajamaGithub


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

namespace tool_monitor\event;

defined('MOODLE_INTERNAL') || die();

/**
 * The tool_monitor subscription deleted event class.
 *
 * @package    tool_monitor
 * @since      Moodle 2.8
 * @copyright  2014 Mark Nelson <markn@moodle.com>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class subscription_deleted extends \core\event\base {

    /**
     * Init method.
     *
     * @return void
     */
    protected function init() {
        $this->data['objecttable'] = 'tool_monitor_subscriptions';
        $this->data['crud'] = 'd';
        $this->data['edulevel'] = self::LEVEL_TEACHING;
    }

    /**
     * Return localised event name.
     *
     * @return string
     */
    public static function get_name() {
        return get_string('eventsubdeleted', 'tool_monitor');
    }

    /**
     * Returns description of what happened.
     *
     * @return string
     */
    public function get_description() {
        return "The user with id '$this->userid' deleted the event monitor subscription with id '$this->objectid'.";
    }

    public static function get_objectid_mapping() {
        // No mapping required for this event because event monitor subscriptions are not backed up.
        return array('db' => 'tool_monitor_subscriptions', 'restore' => \core\event\base::NOT_MAPPED);
    }
}


text:
<?php

/**
 * Virtual Widget
 */
class VirtualWidget	extends	Widget{

	static $has_one = array(
		"ActualWidget" => "Widget"
	);

	static $title = null; //don't show a title for this widget
	static $cmsTitle = "Virtual";
	static $description = "Display an exact copy of an existing widget";

	function getCMSFields(){
		$widgets = Widget::get()->map()->toArray();
		return new FieldList(
			DropdownField::create("ActualWidgetID","Existing Widget",$widgets)
		);
	}

	function WidgetHolder(){
		if($widget = $this->ActualWidget()){
			$widget->ID = $this->ID;
			return $widget->WidgetHolder();
		}
		return parent::WidgetHolder();
	}

}


text:
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/renderer/chrome_render_frame_observer.h"

#include <string>
#include <tuple>

#include "base/bind.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/run_loop.h"
#include "base/strings/strcat.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/chrome_render_view_test.h"
#include "components/no_state_prefetch/renderer/no_state_prefetch_helper.h"
#include "components/optimization_guide/content/renderer/page_text_agent.h"
#include "components/translate/content/common/translate.mojom.h"
#include "components/translate/content/renderer/translate_agent.h"
#include "components/translate/core/common/translate_constants.h"
#include "components/translate/core/common/translate_util.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_view.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "mojo/public/cpp/bindings/receiver_set.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/blink/public/common/browser_interface_broker_proxy.h"
#include "third_party/blink/public/web/web_frame_widget.h"
#include "third_party/blink/public/web/web_local_frame.h"
#include "third_party/blink/public/web/web_view.h"

namespace {

class FakeContentTranslateDriver
    : public translate::mojom::ContentTranslateDriver {
 public:
  FakeContentTranslateDriver() = default;
  ~FakeContentTranslateDriver() override = default;

  void BindHandle(mojo::ScopedMessagePipeHandle handle) {
    receivers_.Add(
        this, mojo::PendingReceiver<translate::mojom::ContentTranslateDriver>(
                  std::move(handle)));
  }

  // translate::mojom::ContentTranslateDriver implementation.
  void RegisterPage(
      mojo::PendingRemote<translate::mojom::TranslateAgent> translate_agent,
      const translate::LanguageDetectionDetails& details,
      bool page_level_translation_critiera_met) override {
    called_new_page_ = true;
    page_level_translation_critiera_met_ = page_level_translation_critiera_met;
  }
  void GetLanguageDetectionModel(
      GetLanguageDetectionModelCallback callback) override {}

  bool called_new_page_ = false;
  bool page_level_translation_critiera_met_ = false;

 private:
  mojo::ReceiverSet<translate::mojom::ContentTranslateDriver> receivers_;
};

class TestOptGuideConsumer
    : public optimization_guide::mojom::PageTextConsumer {
 public:
  TestOptGuideConsumer() = default;
  ~TestOptGuideConsumer() override = default;

  std::u16string text() const { return base::StrCat(chunks_); }
  bool on_chunks_end_called() const { return on_chunks_end_called_; }
  size_t num_chunks() const { return chunks_.size(); }

  void Bind(mojo::PendingReceiver<optimization_guide::mojom::PageTextConsumer>
                pending_receiver) {
    receiver_.Bind(std::move(pending_receiver));
  }

  // optimization_guide::mojom::PageTextConsumer:
  void OnTextDumpChunk(const std::u16string& chunk) override {
    ASSERT_FALSE(on_chunks_end_called_);
    chunks_.push_back(chunk);
  }

  void OnChunksEnd() override { on_chunks_end_called_ = true; }

 private:
  mojo::Receiver<optimization_guide::mojom::PageTextConsumer> receiver_{this};
  std::vector<std::u16string> chunks_;
  bool on_chunks_end_called_ = false;
};

}  // namespace

// Constants for UMA statistic collection.
static const char kTranslateCaptureText[] = "Translate.CaptureText";

class ChromeRenderFrameObserverTest : public ChromeRenderViewTest {
 public:
  void SetUp() override {
    ChromeRenderViewTest::SetUp();

    GetMainRenderFrame()->GetBrowserInterfaceBroker()->SetBinderForTesting(
        translate::mojom::ContentTranslateDriver::Name_,
        base::BindRepeating(&FakeContentTranslateDriver::BindHandle,
                            base::Unretained(&fake_translate_driver_)));
  }

  void TearDown() override {
    GetMainRenderFrame()->GetBrowserInterfaceBroker()->SetBinderForTesting(
        translate::mojom::ContentTranslateDriver::Name_, {});

    ChromeRenderViewTest::TearDown();
  }

  content::RenderFrame* render_frame() { return GetMainRenderFrame(); }

 protected:
  FakeContentTranslateDriver fake_translate_driver_;
};

// The "Translate.CapturePageText" histogram is used to check whether the
// |CapturePageText| method was run. It should have 2 samples: one for
// preliminary capture, one for final capture.

TEST_F(ChromeRenderFrameObserverTest, CapturePageTextCalled) {
  base::HistogramTester histogram_tester;
  LoadHTML("foo");

  histogram_tester.ExpectTotalCount(kTranslateCaptureText, 2);

  base::RunLoop().RunUntilIdle();
  ASSERT_TRUE(fake_translate_driver_.called_new_page_);
  EXPECT_TRUE(fake_translate_driver_.page_level_translation_critiera_met_);
}

TEST_F(ChromeRenderFrameObserverTest, CapturePageTextNotCalledForSubframe) {
  base::HistogramTester histogram_tester;
  LoadHTML(
      "<!DOCTYPE html>"
      "This is a main document"
      ""
      "");

  histogram_tester.ExpectTotalCount(kTranslateCaptureText, 2);

  base::RunLoop().RunUntilIdle();
  ASSERT_TRUE(fake_translate_driver_.called_new_page_);
  EXPECT_TRUE(fake_translate_driver_.page_level_translation_critiera_met_);
}

TEST_F(ChromeRenderFrameObserverTest,
       CapturePageTextNotCalledForUpcomingNavigation) {
  base::HistogramTester histogram_tester;
  LoadHTML(
      ""
      "<meta http-equiv=\"refresh\" content=\"1\">"
      "foo");

  histogram_tester.ExpectTotalCount(kTranslateCaptureText, 0);

  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(fake_translate_driver_.called_new_page_);
  EXPECT_FALSE(fake_translate_driver_.page_level_translation_critiera_met_);
}

TEST_F(ChromeRenderFrameObserverTest,
       CapturePageTextNotCalledForViewSourceMode) {
  base::HistogramTester histogram_tester;
  render_frame()->GetWebFrame()->EnableViewSourceMode(true);

  LoadHTML("foo");

  histogram_tester.ExpectTotalCount(kTranslateCaptureText, 0);

  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(fake_translate_driver_.called_new_page_);
  EXPECT_FALSE(fake_translate_driver_.page_level_translation_critiera_met_);
}

TEST_F(ChromeRenderFrameObserverTest,
       CapturePageTextNotCalledForUnreachableURL) {
  base::HistogramTester histogram_tester;

  render_frame()->LoadHTMLStringForTesting("foo",
                                           GURL("data:text/html,"), "UTF-8",
                                           GURL("http://unreachable.com"),
                                           /*replace_current_item=*/false);

  histogram_tester.ExpectTotalCount(kTranslateCaptureText, 0);

  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(fake_translate_driver_.called_new_page_);
  EXPECT_FALSE(fake_translate_driver_.page_level_translation_critiera_met_);
}

TEST_F(ChromeRenderFrameObserverTest,
       CapturePageTextNotCalledForNoStatePrefetch) {
  base::HistogramTester histogram_tester;

  prerender::NoStatePrefetchHelper helper(render_frame(), "");

  LoadHTML("foo");

  histogram_tester.ExpectTotalCount(kTranslateCaptureText, 0);

  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(fake_translate_driver_.called_new_page_);
  EXPECT_FALSE(fake_translate_driver_.page_level_translation_critiera_met_);
}

TEST_F(ChromeRenderFrameObserverTest, OptGuideGetsText) {
  optimization_guide::PageTextAgent* agent =
      optimization_guide::PageTextAgent::Get(render_frame());
  ASSERT_TRUE(agent);
  render_frame()->GetRemoteAssociatedInterfaces()->OverrideBinderForTesting(
      optimization_guide::mojom::PageTextService::Name_,
      base::BindRepeating(
          [&](optimization_guide::PageTextAgent* agent,
              mojo::ScopedInterfaceEndpointHandle handle) {
            agent->Bind(mojo::PendingAssociatedReceiver<
                        optimization_guide::mojom::PageTextService>(
                std::move(handle)));
          },
          agent));

  mojo::PendingRemote<optimization_guide::mojom::PageTextConsumer>
      consumer_remote;
  TestOptGuideConsumer consumer;
  consumer.Bind(consumer_remote.InitWithNewPipeAndPassReceiver());

  auto request = optimization_guide::mojom::PageTextDumpRequest::New();
  request->max_size = 123;
  request->event = optimization_guide::mojom::TextDumpEvent::kFirstLayout;

  mojo::AssociatedRemote<optimization_guide::mojom::PageTextService>
      text_service;
  render_frame()->GetRemoteAssociatedInterfaces()->GetInterface(&text_service);
  text_service->RequestPageTextDump(std::move(request),
                                    std::move(consumer_remote));
  base::RunLoop().RunUntilIdle();

  base::HistogramTester histogram_tester;
  LoadHTML("foo");
  histogram_tester.ExpectTotalCount(kTranslateCaptureText, 2);

  base::RunLoop().RunUntilIdle();

  EXPECT_EQ(u"foo", consumer.text());
  EXPECT_TRUE(consumer.on_chunks_end_called());
}

class ChromeRenderFrameObserverNoTranslateNorPhishingTest
    : public ChromeRenderFrameObserverTest {
 public:
  ChromeRenderFrameObserverNoTranslateNorPhishingTest() {
    base::CommandLine::ForCurrentProcess()->AppendSwitch(
        switches::kDisableClientSidePhishingDetection);
    scoped_feature_list_.InitAndEnableFeature(translate::kTranslateSubFrames);
  }

 private:
  base::test::ScopedFeatureList scoped_feature_list_;
};

TEST_F(ChromeRenderFrameObserverNoTranslateNorPhishingTest,
       CapturePageTextNotCalled) {
  base::HistogramTester histogram_tester;
  LoadHTML("foo");

  histogram_tester.ExpectTotalCount(kTranslateCaptureText, 0);

  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(fake_translate_driver_.called_new_page_);
  EXPECT_FALSE(fake_translate_driver_.page_level_translation_critiera_met_);
}

TEST_F(ChromeRenderFrameObserverNoTranslateNorPhishingTest, OptGuideGetsText) {
  optimization_guide::PageTextAgent* agent =
      optimization_guide::PageTextAgent::Get(render_frame());
  ASSERT_TRUE(agent);
  render_frame()->GetRemoteAssociatedInterfaces()->OverrideBinderForTesting(
      optimization_guide::mojom::PageTextService::Name_,
      base::BindRepeating(
          [&](optimization_guide::PageTextAgent* agent,
              mojo::ScopedInterfaceEndpointHandle handle) {
            agent->Bind(mojo::PendingAssociatedReceiver<
                        optimization_guide::mojom::PageTextService>(
                std::move(handle)));
          },
          agent));

  mojo::PendingRemote<optimization_guide::mojom::PageTextConsumer>
      consumer_remote;
  TestOptGuideConsumer consumer;
  consumer.Bind(consumer_remote.InitWithNewPipeAndPassReceiver());

  auto request = optimization_guide::mojom::PageTextDumpRequest::New();
  request->max_size = 123;
  request->event = optimization_guide::mojom::TextDumpEvent::kFirstLayout;

  mojo::AssociatedRemote<optimization_guide::mojom::PageTextService>
      text_service;
  render_frame()->GetRemoteAssociatedInterfaces()->GetInterface(&text_service);
  text_service->RequestPageTextDump(std::move(request),
                                    std::move(consumer_remote));
  base::RunLoop().RunUntilIdle();

  base::HistogramTester histogram_tester;
  LoadHTML("foo");
  histogram_tester.ExpectTotalCount(kTranslateCaptureText, 1);

  base::RunLoop().RunUntilIdle();

  EXPECT_EQ(u"foo", consumer.text());
  EXPECT_TRUE(consumer.on_chunks_end_called());
}

#if BUILDFLAG(SAFE_BROWSING_AVAILABLE)

class ChromeRenderFrameObserverNoTranslateYesPhishingTest
    : public ChromeRenderFrameObserverTest {
 public:
  ChromeRenderFrameObserverNoTranslateYesPhishingTest() {
    scoped_feature_list_.InitAndEnableFeature(translate::kTranslateSubFrames);
  }

 private:
  base::test::ScopedFeatureList scoped_feature_list_;
};

TEST_F(ChromeRenderFrameObserverNoTranslateYesPhishingTest,
       CapturePageTextCalled) {
  base::HistogramTester histogram_tester;
  LoadHTML("foo");

  histogram_tester.ExpectTotalCount(kTranslateCaptureText, 2);

  // Translate should not be called since only the phishing logic ran.
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(fake_translate_driver_.called_new_page_);
  EXPECT_FALSE(fake_translate_driver_.page_level_translation_critiera_met_);
}

#else

class ChromeRenderFrameObserverNoTranslateTest
    : public ChromeRenderFrameObserverTest {
 public:
  ChromeRenderFrameObserverNoTranslateNorPhishingTest() {
    scoped_feature_list_.InitAndEnableFeature(translate::kTranslateSubFrames);
  }

 private:
  base::test::ScopedFeatureList scoped_feature_list_;
};

TEST_F(ChromeRenderFrameObserverNoTranslateTest, CapturePageTextNotCalled) {
  base::HistogramTester histogram_tester;
  LoadHTML("foo");

  histogram_tester.ExpectTotalCount(kTranslateCaptureText, 0);

  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(fake_translate_driver_.called_new_page_);
  EXPECT_FALSE(fake_translate_driver_.page_level_translation_critiera_met_);
}

#endif


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading;
using Microsoft.PythonTools.Analysis;
using Microsoft.VisualStudioTools;
using Microsoft.Win32;

namespace Microsoft.PythonTools.Interpreter {
    [Export(typeof(IPythonInterpreterFactoryProvider))]
    [PartCreationPolicy(CreationPolicy.Shared)]
    class CPythonInterpreterFactoryProvider : IPythonInterpreterFactoryProvider {
        private readonly List<IPythonInterpreterFactory> _interpreters;
        const string PythonPath = "Software\\Python";
        const string PythonCorePath = "Software\\Python\\PythonCore";

        public CPythonInterpreterFactoryProvider() {
            _interpreters = new List<IPythonInterpreterFactory>();
            DiscoverInterpreterFactories();

            StartWatching(RegistryHive.CurrentUser, RegistryView.Default);
            StartWatching(RegistryHive.LocalMachine, RegistryView.Registry32);
            if (Environment.Is64BitOperatingSystem) {
                StartWatching(RegistryHive.LocalMachine, RegistryView.Registry64);
            }
        }

        private void StartWatching(RegistryHive hive, RegistryView view) {
            var tag = RegistryWatcher.Instance.TryAdd(
                hive, view, PythonCorePath, Registry_PythonCorePath_Changed,
                recursive: true, notifyValueChange: true, notifyKeyChange: true
            ) ??
            RegistryWatcher.Instance.TryAdd(
                hive, view, PythonPath, Registry_PythonPath_Changed,
                recursive: false, notifyValueChange: false, notifyKeyChange: true
            ) ??
            RegistryWatcher.Instance.Add(
                hive, view, "Software", Registry_Software_Changed,
                recursive: false, notifyValueChange: false, notifyKeyChange: true
            );
        }

        #region Registry Watching

        private static bool Exists(RegistryChangedEventArgs e) {
            using (var root = RegistryKey.OpenBaseKey(e.Hive, e.View))
            using (var key = root.OpenSubKey(e.Key)) {
                return key != null;
            }
        }

        private void Registry_PythonCorePath_Changed(object sender, RegistryChangedEventArgs e) {
            if (!Exists(e)) {
                // PythonCore key no longer exists, so go back to watching
                // Python.
                e.CancelWatcher = true;
                StartWatching(e.Hive, e.View);
            } else {
                DiscoverInterpreterFactories();
            }
        }

        private void Registry_PythonPath_Changed(object sender, RegistryChangedEventArgs e) {
            if (Exists(e)) {
                if (RegistryWatcher.Instance.TryAdd(
                    e.Hive, e.View, PythonCorePath, Registry_PythonCorePath_Changed,
                    recursive: true, notifyValueChange: true, notifyKeyChange: true
                ) != null) {
                    // PythonCore key now exists, so start watching it,
                    // discover any interpreters, and cancel this watcher.
                    e.CancelWatcher = true;
                    DiscoverInterpreterFactories();
                }
            } else {
                // Python key no longer exists, so go back to watching
                // Software.
                e.CancelWatcher = true;
                StartWatching(e.Hive, e.View);
            }
        }

        private void Registry_Software_Changed(object sender, RegistryChangedEventArgs e) {
            Registry_PythonPath_Changed(sender, e);
            if (e.CancelWatcher) {
                // PythonCore key also exists and is now being watched, so just
                // return.
                return;
            }

            if (RegistryWatcher.Instance.TryAdd(
                e.Hive, e.View, PythonPath, Registry_PythonPath_Changed,
                recursive: false, notifyValueChange: false, notifyKeyChange: true
            ) != null) {
                // Python exists, but not PythonCore, so watch Python until
                // PythonCore is created.
                e.CancelWatcher = true;
            }
        }

        #endregion

        private static bool TryParsePythonVersion(string spec, out Version version, out ProcessorArchitecture? arch) {
            version = null;
            arch = null;

            if (string.IsNullOrEmpty(spec) || spec.Length < 3) {
                return false;
            }

            var m = Regex.Match(spec, @"^(?<ver>[23]\.[0-9]+)(?<suffix>.*)$");
            if (!m.Success) {
                return false;
            }

            if (!Version.TryParse(m.Groups["ver"].Value, out version)) {
                return false;
            }

            if (m.Groups["suffix"].Value == "-32") {
                arch = ProcessorArchitecture.X86;
            }

            return true;
        }

        private bool RegisterInterpreters(HashSet<string> registeredPaths, RegistryKey python, ProcessorArchitecture? arch) {
            bool anyAdded = false;

            string[] subKeyNames = null;
            for (int retries = 5; subKeyNames == null && retries > 0; --retries) {
                try {
                    subKeyNames = python.GetSubKeyNames();
                } catch (IOException) {
                    // Registry changed while enumerating subkeys. Give it a
                    // short period to settle down and try again.
                    // We are almost certainly being called from a background
                    // thread, so sleeping here is fine.
                    Thread.Sleep(100);
                }
            }
            if (subKeyNames == null) {
                return false;
            }

            foreach (var key in subKeyNames) {
                Version version;
                ProcessorArchitecture? arch2;
                if (TryParsePythonVersion(key, out version, out arch2)) {
                    if (version.Major == 2 && version.Minor <= 4) {
                        // 2.4 and below not supported.
                        continue;
                    }

                    var installPath = python.OpenSubKey(key + "\\InstallPath");
                    if (installPath != null) {
                        var basePathObj = installPath.GetValue("");
                        if (basePathObj == null) {
                            // http://pytools.codeplex.com/discussions/301384
                            // messed up install, we don't know where it lives, we can't use it.
                            continue;
                        }
                        string basePath = basePathObj.ToString();
                        if (!CommonUtils.IsValidPath(basePath)) {
                            // Invalid path in registry
                            continue;
                        }
                        if (!registeredPaths.Add(basePath)) {
                            // registered in both HCKU and HKLM
                            continue;
                        }

                        var actualArch = arch ?? arch2;
                        if (!actualArch.HasValue) {
                            actualArch = NativeMethods.GetBinaryType(Path.Combine(basePath, CPythonInterpreterFactoryConstants.ConsoleExecutable));
                        }

                        var id = CPythonInterpreterFactoryConstants.Guid32;
                        var description = CPythonInterpreterFactoryConstants.Description32;
                        if (actualArch == ProcessorArchitecture.Amd64) {
                            id = CPythonInterpreterFactoryConstants.Guid64;
                            description = CPythonInterpreterFactoryConstants.Description64;
                        }

                        if (!_interpreters.Any(f => f.Id == id && f.Configuration.Version == version)) {
                            _interpreters.Add(InterpreterFactoryCreator.CreateInterpreterFactory(
                                new InterpreterFactoryCreationOptions {
                                    LanguageVersion = version,
                                    Id = id,
                                    Description = string.Format("{0} {1}", description, version),
                                    InterpreterPath = Path.Combine(basePath, CPythonInterpreterFactoryConstants.ConsoleExecutable),
                                    WindowInterpreterPath = Path.Combine(basePath, CPythonInterpreterFactoryConstants.WindowsExecutable),
                                    LibraryPath = Path.Combine(basePath, CPythonInterpreterFactoryConstants.LibrarySubPath),
                                    PathEnvironmentVariableName = CPythonInterpreterFactoryConstants.PathEnvironmentVariableName,
                                    Architecture = actualArch ?? ProcessorArchitecture.None,
                                    WatchLibraryForNewModules = true
                                }
                            ));
                            anyAdded = true;
                        }
                    }
                }
            }

            return anyAdded;
        }

        private void DiscoverInterpreterFactories() {
            bool anyAdded = false;
            HashSet<string> registeredPaths = new HashSet<string>();
            var arch = Environment.Is64BitOperatingSystem ? null : (ProcessorArchitecture?)ProcessorArchitecture.X86;
            using (var baseKey = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Default))
            using (var python = baseKey.OpenSubKey(PythonCorePath)) {
                if (python != null) {
                    anyAdded |= RegisterInterpreters(registeredPaths, python, arch);
                }
            }

            using (var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32))
            using (var python = baseKey.OpenSubKey(PythonCorePath)) {
                if (python != null) {
                    anyAdded |= RegisterInterpreters(registeredPaths, python, ProcessorArchitecture.X86);
                }
            }

            if (Environment.Is64BitOperatingSystem) {
                using (var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
                using (var python64 = baseKey.OpenSubKey(PythonCorePath)) {
                    if (python64 != null) {
                        anyAdded |= RegisterInterpreters(registeredPaths, python64, ProcessorArchitecture.Amd64);
                    }
                }
            }

            if (anyAdded) {
                OnInterpreterFactoriesChanged();
            }
        }

        #region IPythonInterpreterProvider Members

        public IEnumerable<IPythonInterpreterFactory> GetInterpreterFactories() {
            return _interpreters;
        }

        public event EventHandler InterpreterFactoriesChanged;

        private void OnInterpreterFactoriesChanged() {
            var evt = InterpreterFactoriesChanged;
            if (evt != null) {
                evt(this, EventArgs.Empty);
            }
        }

        #endregion
    }
}


text:
require 'spec_helper'

describe RailsRequestStats::Stats::RuntimeStats do
  describe '#add_stats' do
    it 'stores values' do
      view_runtime = 10.10
      db_runtime = 20.20

      subject.add_stats(view_runtime, db_runtime)

      expect(subject.view_runtime_collection).to eq([view_runtime])
      expect(subject.db_runtime_collection).to eq([db_runtime])
    end
  end
end


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
				 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<version>1.1-SNAPSHOT</version>
	<groupId>fi.seco</groupId>
	<artifactId>hfst</artifactId>
	<name>Thread safe version of Helsinki Finite State Transducers</name>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<!-- or whatever version you use -->
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
	<dependencies>
		<dependency>
			<groupId>com.carrotsearch</groupId>
			<artifactId>hppc</artifactId>
			<version>0.6.1</version>
		</dependency>
	</dependencies>
</project>


text:
"""Common utilities for the labeling."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from absl import logging
from absl import flags
import tensorflow as tf
import tensorflow_hub as hub
from tensorflow.contrib.cluster_resolver import TPUClusterResolver

import preprocess as preprocess_lib

FLAGS = flags.FLAGS

def _int64_feature(value):
  return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))

def _float_feature(value):
  return tf.train.Feature(float_list=tf.train.FloatList(value=value))

def _bytes_feature(value):
  return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))

def into_batch_dim(x, keep_last_dims=-3):
  """Turns (B,M,...,H,W,C) into (BM...,H,W,C) if `keep_last_dims` is -3."""
  last_dims = x.get_shape().as_list()[keep_last_dims:]
  return tf.reshape(x, shape=[-1] + last_dims)

def split_batch_dim(x, split_dims):
  """Turns (BMN,H,...) into (B,M,N,H,...) if `split_dims` is [-1, M, N]."""
  last_dims = x.get_shape().as_list()[1:]
  logging.info("split_dims: %s", split_dims)
  logging.info("last_dims: %s", last_dims)
  return tf.reshape(x, list(split_dims) + last_dims)

def make_transform(mod, model_signature, representation_name):
  """Function to transfrom the input to a dict of results."""

  def transform_batch(input_tuple):
    """Transform a batch of input batch to a dictionary of embeddings."""
    num_crops = input_tuple["image_normalized"].get_shape().as_list()[1]
    num_rotations = input_tuple["image_normalized"].get_shape().as_list()[2]
    images = into_batch_dim(input_tuple["image_normalized"])
    outputs = mod(inputs=images, signature=model_signature, as_dict=True)
    outputs = outputs[representation_name]
    outputs = split_batch_dim(outputs, [-1, num_crops, num_rotations])
    logging.info("outputs after split batch dim: %s", outputs)
    logits = outputs[:, 0, 0, :]

    logits_avg_croprot = tf.reduce_mean(outputs, axis=[1, 2])
    return {
        "logits": logits,
        "outputs": outputs,
        "logits_avg_croprot": logits_avg_croprot,
        "filename": input_tuple["filename"],
        "original_label": input_tuple["original_label"],
        "jpeg_str": input_tuple["jpeg_str"],
    }

  return transform_batch

def parse_imagenet(image_data,
                   image_key="image",
                   file_name_key="file_name",
                   label_key="label"):
  """Parses imagenet record to input of sklearn pipeline."""
  value = tf.parse_single_example(
      image_data,
      features={
          image_key: tf.FixedLenFeature([], tf.string),
          file_name_key: tf.FixedLenFeature([], tf.string),
          label_key: tf.FixedLenFeature([], tf.int64)
      })
  jpeg_str = value[image_key]
  image = tf.image.decode_jpeg(jpeg_str, channels=3)
  data = {
      "image": image,
      "filename": value[file_name_key],
      "label": value[label_key]
  }
  data = preprocess_lib.get_resize_small(256)(data)
  data = preprocess_lib.get_multi_crop((224, 224))(data)
  data = preprocess_lib.get_rotate_preprocess(create_labels=False)(data)
  image_normalized = preprocess_lib.get_value_range_preprocess(-1,
                                                               1)(data)["image"]

  return {
      "image_normalized": image_normalized,
      "filename": data["filename"],
      "original_label": data["label"],
      "jpeg_str": jpeg_str,
  }

def write_imagenet_labels(writer,
                          results,
                          target_label,
                          label_offset=0,
                          image_key="image",
                          file_name_key="file_name",
                          label_key="label",
                          original_label_key="original_label",
                          label_flag_key="label_flag",
                          logits_key="logits"):
  """Writes sample from next node to writer with the provided label."""
  filenames = results["filenames"]
  jpeg_str = results["jpeg_str"]

  if target_label == "predicted_labels":
    # ImageNet class label offset.
    labels = results["predicted_labels"] + label_offset
  elif target_label == "original_labels":
    original_labels = results["original_labels"]
    flags = results["flags"]
    labels = []
    for i in range(len(flags)):
      labels.append(original_labels[i] if flags[i] else -1)
  elif target_label == "logits":
    labels = results["logits"]
  elif target_label == "all":
    predicted_labels = results["predicted_labels"] + label_offset
    predicted_labels_avg_croprot = results[
        "predicted_labels_avg_croprot"] + label_offset

    original_labels = results["original_labels"]
    flags = results["flags"]
    logits = results["logits"]
    logits_avg_croprot = results["logits_avg_croprot"]
  else:
    raise NotImplementedError("Unsupported mode: %s" % target_label)

  for i in range(len(filenames)):
    jpeg = _bytes_feature(jpeg_str[i])
    if target_label == "all":
      predicted_label = _int64_feature(int(predicted_labels[i]))
      original_label = _int64_feature(original_labels[i])
      label_flag = _int64_feature(flags[i])
      logit = _float_feature(logits[i])
      logit_avg_croprot = _float_feature(logits_avg_croprot[i])

      predicted_label_avg_croprot = _int64_feature(
          int(predicted_labels_avg_croprot[i]))

    elif target_label == "logits":
      label_i = _float_feature(labels[i])
    elif (target_label == "predicted_labels" or
          target_label == "original_labels"):
      label_i = _int64_feature(int(labels[i]))

    if target_label == "all":
      example = tf.train.Example(
          features=tf.train.Features(
              feature={
                  image_key: jpeg,
                  file_name_key: _bytes_feature(filenames[i]),
                  label_key: predicted_label,
                  original_label_key: original_label,
                  label_flag_key: label_flag,
                  logits_key: logit,
                  "logit_avg_croprot": logit_avg_croprot,
                  "predicted_labels_avg_croprot": predicted_label_avg_croprot,
              }))
    else:
      example = tf.train.Example(
          features=tf.train.Features(
              feature={
                  image_key: jpeg,
                  file_name_key: _bytes_feature(filenames[i]),
                  label_key: label_i,
              }))
    writer.write(example.SerializeToString())

def create_labels(input_tfrecord_path,
                  output_tfrecord_path,
                  dataset_preprocess_fn,
                  embedding_fn,
                  label_fn,
                  write_fn=None,
                  batch_size=64,
                  parallel_calls=1):
  """Creates a new set of labels for a single chunk.

  Args:
    input_tfrecord_path: String with input TF Record file.
    output_tfrecord_path: String with input TF Record file.
    dataset_preprocess_fn: Preprocessing function applied to dataset.
    embedding_fn: Embedding function applied to the dataset tensor.
    label_fn: Label function applied to the (after sess.run).
    write_fn: Function to write TF Record to TF Record writer.
    batch_size: Optional integer with batch_size.
  """
  tf.logging.info("Input: {}\nOutput: {}".format(
      input_tfrecord_path, output_tfrecord_path))
  if write_fn is None:
    write_fn = write_imagenet

  if FLAGS.tpu_name:
    cluster = TPUClusterResolver(tpu=[FLAGS.tpu_name])
  else:
    cluster = None
  config = tf.contrib.tpu.RunConfig(cluster=cluster)

  # Load the data in the chunk.
  input_dataset = tf.data.TFRecordDataset(input_tfrecord_path)
  input_dataset = input_dataset.map(
          dataset_preprocess_fn, parallel_calls)
  input_dataset = input_dataset.batch(batch_size)
  next_node = input_dataset.make_one_shot_iterator().get_next()
  embedding = embedding_fn(next_node)
  with tf.Session(cluster.get_master(), config=config.session_config) as sess:
    with tf.python_io.TFRecordWriter(output_tfrecord_path) as writer:
      sess.run(tf.global_variables_initializer())
      while True:
        try:
          embedded = sess.run(embedding)
          results = label_fn(embedded)
          write_fn(writer, results)
        except tf.errors.OutOfRangeError:
          break

def write_imagenet(writer, labels):
  """Writes sample from next node to writer with the provided label."""
  for label in labels:
    example = tf.train.Example(
        features=tf.train.Features(
            feature={
                "image/encoded": _bytes_feature(""),
                "image/class/label": _int64_feature(int(label)),
            }))
    writer.write(example.SerializeToString())


text: <!DOCTYPE html>


text:
using System;
using NUnit.Framework;
using SFA.DAS.CommitmentsV2.Extensions;
using SFA.DAS.CommitmentsV2.Types;
using PaymentStatus = SFA.DAS.CommitmentsV2.Types.PaymentStatus;

namespace SFA.DAS.CommitmentsV2.UnitTests.Models.Apprenticeship
{
    [TestFixture]
    [Parallelizable]

    public class WhenStatusIsDetermined
    {
        private ApprenticeshipStatusTestsFixture _fixture;

        [SetUp]
        public void Arrange()
        {
            _fixture = new ApprenticeshipStatusTestsFixture();
        }

        [Test]
        public void Future_Starts_Show_As_WaitingToStart()
        {
            _fixture.WithFutureStartDate().VerifyStatus(ApprenticeshipStatus.WaitingToStart);
        }

        [Test]
        public void Past_Starts_Show_As_Live()
        {
            _fixture.WithPastStartDate().VerifyStatus(ApprenticeshipStatus.Live);
        }

        [Test]
        public void Stopped_Apprenticeships_Show_As_Stopped()
        {
            _fixture.WithPaymentStatus(PaymentStatus.Withdrawn).VerifyStatus(ApprenticeshipStatus.Stopped);
        }

        [Test]
        public void Paused_Apprenticeships_Show_As_Paused()
        {
            _fixture.WithPaymentStatus(PaymentStatus.Paused).VerifyStatus(ApprenticeshipStatus.Paused);
        }

        [Test]
        public void Completed_Apprenticeships_Show_As_Completed()
        {
            _fixture.WithPaymentStatus(PaymentStatus.Completed).VerifyStatus(ApprenticeshipStatus.Completed);
        }

        [Test]
        public void All_PaymentStatus_Are_Mapped()
        {
            _fixture.VerifyAllPaymentStatusAreMappedToApprenticeshipStatus();
        }

        private class ApprenticeshipStatusTestsFixture
        {
            private readonly CommitmentsV2.Models.Apprenticeship _apprenticeship;

            public ApprenticeshipStatusTestsFixture()
            {
                _apprenticeship = new CommitmentsV2.Models.Apprenticeship();

                _apprenticeship = new CommitmentsV2.Models.Apprenticeship
                {
                    StartDate = DateTime.UtcNow.AddMonths(-1),
                    EndDate = DateTime.UtcNow.AddYears(1),
                    PaymentStatus = PaymentStatus.Active
                };
            }

            public ApprenticeshipStatusTestsFixture WithFutureStartDate()
            {
                _apprenticeship.StartDate = DateTime.UtcNow.AddMonths(1);
                _apprenticeship.EndDate = _apprenticeship.StartDate.Value.AddYears(1);
                return this;
            }

            public ApprenticeshipStatusTestsFixture WithPastStartDate()
            {
                _apprenticeship.StartDate = DateTime.UtcNow.AddMonths(-1);
                _apprenticeship.EndDate = _apprenticeship.StartDate.Value.AddYears(1);
                return this;
            }

            public ApprenticeshipStatusTestsFixture WithPaymentStatus(PaymentStatus paymentStatus)
            {
                _apprenticeship.PaymentStatus = paymentStatus;
                return this;
            }

            public void VerifyStatus(ApprenticeshipStatus expectedStatus)
            {
                Assert.AreEqual(expectedStatus, _apprenticeship.GetApprenticeshipStatus(DateTime.UtcNow));
            }

            internal void VerifyAllPaymentStatusAreMappedToApprenticeshipStatus()
            {
                foreach (PaymentStatus paymentStatus in Enum.GetValues(typeof(PaymentStatus)))
                {
                    _apprenticeship.PaymentStatus = paymentStatus;
                    Assert.AreNotEqual(ApprenticeshipStatus.Unknown, _apprenticeship.GetApprenticeshipStatus(DateTime.UtcNow), $"PaymentStatus : {paymentStatus.ToString()} is not mapped to Apprenticeship status");
                }
            }
        }
    }
}


text:
[![Javadocs][javadoc-image]][javadoc-url]

This artifact provides Java Service Provider Interfaces (SPI) for controlling [SDK autoconfiguration](../autoconfigure).
Visit the autoconfigure module for more information on how to use autoconfiguration.

[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-sdk-extension-autoconfigure-spi.svg
[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-sdk-extension-autoconfigure-spi


text:
package org.apache.camel.component.leveldb;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.camel.AggregationStrategy;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.test.spring.junit5.CamelSpringTestSupport;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.springframework.context.support.AbstractXmlApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import static org.apache.camel.test.junit5.TestSupport.deleteDirectory;

@DisabledOnOs({ OS.AIX, OS.OTHER })
public class LevelDBSpringAggregateRecoverWithRedeliveryPolicyTest extends CamelSpringTestSupport {

    private static AtomicInteger counter = new AtomicInteger();

    @Override
    protected AbstractXmlApplicationContext createApplicationContext() {
        return new ClassPathXmlApplicationContext(
                "org/apache/camel/component/leveldb/LevelDBSpringAggregateRecoverWithRedeliveryPolicyTest.xml");
    }

    @Override
    @BeforeEach
    public void setUp() throws Exception {
        deleteDirectory("target/data");
        super.setUp();
    }

    @Test
    public void testLevelDBAggregateRecover() throws Exception {
        getMockEndpoint("mock:aggregated").setResultWaitTime(20000);
        getMockEndpoint("mock:result").setResultWaitTime(20000);

        // should fail the first 3 times and then recover
        getMockEndpoint("mock:aggregated").expectedMessageCount(4);
        getMockEndpoint("mock:result").expectedBodiesReceived("ABCDE");
        // should be marked as redelivered
        getMockEndpoint("mock:result").message(0).header(Exchange.REDELIVERED).isEqualTo(Boolean.TRUE);
        // on the 2nd redelivery attempt we success
        getMockEndpoint("mock:result").message(0).header(Exchange.REDELIVERY_COUNTER).isEqualTo(3);

        template.sendBodyAndHeader("direct:start", "A", "id", 123);
        template.sendBodyAndHeader("direct:start", "B", "id", 123);
        template.sendBodyAndHeader("direct:start", "C", "id", 123);
        template.sendBodyAndHeader("direct:start", "D", "id", 123);
        template.sendBodyAndHeader("direct:start", "E", "id", 123);

        assertMockEndpointsSatisfied(30, TimeUnit.SECONDS);
    }

    public static class MyFailProcessor implements Processor {

        @Override
        public void process(Exchange exchange) {
            int count = counter.incrementAndGet();
            if (count <= 3) {
                throw new IllegalArgumentException("Damn");
            }
        }
    }

    public static class MyAggregationStrategy implements AggregationStrategy {

        @Override
        public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
            if (oldExchange == null) {
                return newExchange;
            }
            String body1 = oldExchange.getIn().getBody(String.class);
            String body2 = newExchange.getIn().getBody(String.class);

            oldExchange.getIn().setBody(body1 + body2);
            return oldExchange;
        }
    }
}


text:
package io.circe

import algebra.Eq
import cats.std.list._

trait Error extends Exception

case class ParsingFailure(message: String, underlying: Throwable) extends Error {
  override def getMessage: String = message
}

case class DecodingFailure(message: String, history: List[HistoryOp]) extends Error {
  override def getMessage: String =
    if (history.isEmpty) message else s"$message: ${ history.mkString(",") }"

  def withMessage(message: String): DecodingFailure = copy(message = message)
}

object ParsingFailure {
  implicit val eqParsingFailure: Eq[ParsingFailure] = Eq.instance {
    case (ParsingFailure(m1, t1), ParsingFailure(m2, t2)) => m1 == m2 && t1 == t2
  }
}

object DecodingFailure {
  implicit val eqDecodingFailure: Eq[DecodingFailure] = Eq.instance {
    case (DecodingFailure(m1, h1), DecodingFailure(m2, h2)) =>
      m1 == m2 && Eq[List[HistoryOp]].eqv(h1, h2)
  }
}

object Error {
  implicit val eqError: Eq[Error] = Eq.instance {
    case (ParsingFailure(m1, u1), ParsingFailure(m2, u2)) =>
      m1 == m2 && u1 == u2
    case (DecodingFailure(m1, h1), DecodingFailure(m2, h2)) =>
      m1 == m2 && Eq[List[HistoryOp]].eqv(h1, h2)
    case (_, _) => false
  }
}


text:
class Redis
  # Base error for all redis-rb errors.
  class BaseError < RuntimeError
  end

  # Raised by the connection when a protocol error occurs.
  class ProtocolError < BaseError
    def initialize(reply_type)
      super(<<-EOS.gsub(/(?:^|\n)\s*/, " "))
        Got '#{reply_type}' as initial reply byte.
        If you're in a forking environment, such as Unicorn, you need to
        connect to Redis after forking.
      EOS
    end
  end

  # Raised by the client when command execution returns an error reply.
  class CommandError < BaseError
  end

  # Base error for connection related errors.
  class BaseConnectionError < BaseError
  end

  # Raised when connection to a Redis server cannot be made.
  class CannotConnectError < BaseConnectionError
  end

  # Raised when connection to a Redis server is lost.
  class ConnectionError < BaseConnectionError
  end

  # Raised when performing I/O times out.
  class TimeoutError < BaseConnectionError
  end
end


text:
'use strict';

const
  Bluebird = require('bluebird'),
  Models = require('./db');

const commentLeave = ({leave, comment, companyId}) => {
  return Models.Comment.create({
    entityType: Models.Comment.getEntityTypeLeave(),
    entityId: leave.id,
    comment,
    companyId,
    byUserId: leave.userId,
  });
};

const getCommentsForLeave = ({leave}) => {
  return Models.Comment.findAll({
    raw: true,
    where : {
      entityType: Models.Comment.getEntityTypeLeave(),
      entityId: leave.id,
    },
  });
};

module.exports = {
  commentLeave,
  getCommentsForLeave,
};


text:
/// <reference path="WorldModel.ts" />
/// <reference path="RobotModel.ts" />
/// <reference path="Settings.ts" />
/// <reference path="../../../implementations/robotModel/TwoDRobotModel.ts" />

interface Model {
    getWorldModel() : WorldModel;
    getRobotModels() : RobotModel[];
    getSetting() : Settings;
    addRobotModel(robotModel: TwoDRobotModel): void;
    deserialize(xml): void;
    getTimeline(): Timeline;
}


text:
require "minitest/autorun"
require "sprockets"
require "sprockets/environment"
require "fileutils"

old_verbose, $VERBOSE = $VERBOSE, false
Encoding.default_external = 'UTF-8'
Encoding.default_internal = 'UTF-8'
$VERBOSE = old_verbose

def silence_warnings
  old_verbose, $VERBOSE = $VERBOSE, false
  yield
ensure
  $VERBOSE = old_verbose
end

# Popular extensions for testing but not part of Sprockets core

Sprockets.register_dependency_resolver "rand" do
  rand(2**100)
end

NoopProcessor = proc { |input| input[:data] }
Sprockets.register_mime_type 'text/haml', extensions: ['.haml']
Sprockets.register_transformer 'text/haml', 'text/html', NoopProcessor

Sprockets.register_mime_type 'text/mustache', extensions: ['.mustache']
Sprockets.register_transformer 'text/mustache', 'application/javascript+function', NoopProcessor

Sprockets.register_mime_type 'text/x-handlebars-template', extensions: ['.handlebars']
Sprockets.register_transformer 'text/x-handlebars-template', 'application/javascript+function', NoopProcessor

Sprockets.register_mime_type 'application/dart', extensions: ['.dart']
Sprockets.register_transformer 'application/dart', 'application/javascript', NoopProcessor

require 'nokogiri'

HtmlBuilderProcessor = proc { |input|
  instance_eval <<-EOS
    builder = Nokogiri::HTML::Builder.new do |doc|
      #{input[:data]}
    end
    builder.to_html
  EOS
}
Sprockets.register_mime_type 'application/html+builder', extensions: ['.html.builder']
Sprockets.register_transformer 'application/html+builder', 'text/html', HtmlBuilderProcessor

XmlBuilderProcessor = proc { |input|
  instance_eval <<-EOS
    builder = Nokogiri::XML::Builder.new do |xml|
      #{input[:data]}
    end
    builder.to_xml
  EOS
}
Sprockets.register_mime_type 'application/xml+builder', extensions: ['.xml.builder']
Sprockets.register_transformer 'application/xml+builder', 'application/xml', XmlBuilderProcessor

SVG2PNG = proc { |input|
  "\x89\x50\x4e\x47\xd\xa\x1a\xa#{input[:data]}"
}
Sprockets.register_transformer 'image/svg+xml', 'image/png', SVG2PNG

PNG2GIF = proc { |input|
  "\x47\x49\x46\x38\x37\61#{input[:data]}"
}
Sprockets.register_transformer 'image/png', 'image/gif', PNG2GIF

CSS2HTMLIMPORT = proc { |input|
  "<style>#{input[:data]}</style>"
}
Sprockets.register_transformer 'text/css', 'text/html', CSS2HTMLIMPORT

JS2HTMLIMPORT = proc { |input|
  "<script>#{input[:data]}</script>"
}
Sprockets.register_transformer 'application/javascript', 'text/html', JS2HTMLIMPORT

Sprockets.register_bundle_metadata_reducer 'text/css', :selector_count, :+

Sprockets.register_postprocessor 'text/css', proc { |input|
  { selector_count: input[:data].scan(/\{/).size }
}

class Sprockets::TestCase < MiniTest::Test
  FIXTURE_ROOT = File.join(__dir__, "fixtures")

  def self.test(name, &block)
    define_method("test_#{name.inspect}", &block)
  end

  def fixture(path)
    IO.read(fixture_path(path))
  end

  def fixture_path(path)
    if path.match(FIXTURE_ROOT)
      path
    else
      File.join(FIXTURE_ROOT, path)
    end
  end

  def sandbox(*paths)
    backup_paths = paths.select { |path| File.exist?(path) }
    remove_paths = paths.select { |path| !File.exist?(path) }

    begin
      backup_paths.each do |path|
        FileUtils.cp(path, "#{path}.orig")
      end

      yield
    ensure
      backup_paths.each do |path|
        if File.exist?("#{path}.orig")
          FileUtils.mv("#{path}.orig", path)
        end

        assert !File.exist?("#{path}.orig")
      end

      remove_paths.each do |path|
        if File.exist?(path)
          FileUtils.rm_rf(path)
        end

        assert !File.exist?(path)
      end
    end
  end

  def write(filename, contents, mtime = nil)
    if File.exist?(filename)
      mtime ||= [Time.now.to_i, File.stat(filename).mtime.to_i].max + 1
      File.open(filename, 'w') do |f|
        f.write(contents)
      end
      File.utime(mtime, mtime, filename)
    else
      File.open(filename, 'w') do |f|
        f.write(contents)
      end
      File.utime(mtime, mtime, filename) if mtime
    end
  end

  def normalize_uri(uri)
    uri.sub(/id=\w+/, 'id=xxx')
  end

  def normalize_uris(uris)
    uris.to_a.map { |uri| normalize_uri(uri) }.sort
  end
end


text:
<?php namespace Modules\Webcontact\Repositories\Eloquent;

use Modules\Webcontact\Repositories\WebContactRepository;
use Modules\Core\Repositories\Eloquent\EloquentBaseRepository;

class EloquentWebContactRepository extends EloquentBaseRepository implements WebContactRepository
{
}


text:
import { Router } from 'express';

import * as UserController from './UserController';

export const router = Router();

router.get('/me', UserController.getUser);


text:
class SpreePaypalExpressHooks < Spree::ThemeSupport::HookListener
  # custom hooks go here
end


text:
package adasim.agent;

import static org.junit.Assert.*;

import java.io.File;
import java.io.FileNotFoundException;

import org.junit.Before;
import org.junit.Test;

import adasim.LoggingTest;
import adasim.agent.RoadClosureAgent;
import adasim.model.ConfigurationException;
import adasim.model.RoadSegment;
import adasim.model.TrafficSimulator;
import adasim.model.internal.SimulationXMLReader;

/**
 * @author Jochen Wuttke - wuttkej@gmail.com
 *
 */
public class RoadClosureAgentTest extends LoggingTest {

	private RoadClosureAgent agent;

	@Before
	public void setUp() {
		agent = new RoadClosureAgent( "0.0:0", 27L );
	}

	@Test
	public void validParams() {
		agent.setParameters( "0.01:42" );
		assertEquals( 0.01, agent.getClosureProbability(), 1e-10 );
		assertEquals(42, agent.getClosureDuration() );
	}

	@Test
	public void validParamsWithSpaces() {
		agent.setParameters( " \t0.01 :42 " );
		assertEquals( 0.01, agent.getClosureProbability(), 1e-10 );
		assertEquals(42, agent.getClosureDuration() );
	}

	@Test(expected=IllegalArgumentException.class)
	public void tooManyParams() {
		agent.setParameters( "0.01:42:222" );
		fail( "Should throw IllegalArgumentException" );
	}

	@Test(expected=IllegalArgumentException.class)
	public void tooFewParams() {
		agent.setParameters( "0.01" );
		fail( "Should throw IllegalArgumentException" );
	}

	@Test(expected=IllegalArgumentException.class)
	public void invalidFirstParamType() {
		agent.setParameters( "hugo:23" );
		fail( "Should throw IllegalArgumentException" );
	}

	@Test(expected=IllegalArgumentException.class)
	public void invalidSecondParamType() {
		agent.setParameters( "0.111:hugo" );
		fail( "Should throw IllegalArgumentException" );
	}

	@Test
	public void closureTest() throws FileNotFoundException, ConfigurationException {
		TrafficSimulator sim = SimulationXMLReader.buildSimulator( new File( "resources/test/closure-test.xml" ) );
		agent.setSimulation(sim);
		agent.setParameters( "1.0:2" );
		RoadSegment node = sim.getMap().getRoadSegment( 0 );
		assertFalse( "Node is closed", node.isClosed() );
		agent.takeSimulationStep(1);
		assertTrue( "Node is open", node.isClosed() );
		agent.takeSimulationStep(2);
		assertTrue( "Node is open", node.isClosed() );
		agent.takeSimulationStep(3);
		assertTrue( "Node is open", node.isClosed() );
		agent.takeSimulationStep(4);
		assertFalse( "Node is closed", node.isClosed() );
	}
}


text:
All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

**Potentially Breaking Changes**
* Return additional information with the errors on changesets
  * This generally shouldn't break anything, but if the code is using
    `Ecto.Changeset.traverse_errors/2` and looking at the `additional_info` it could.

Improvements:
* Add the ability to customize error messages by passing `messages` to a validator

## 0.4.1 (2020-11-11)

* Bump dependencies used for development and testing
* No user-visible changes

## 0.4.0 (2019-09-02)

**Breaking Changes**
* Extract `PasswordValidator.Validators.ZXCVBNValidator` to a separate (compatible) repository: https://github.com/axelson/password-validator-zxcvbn
* Increased minimum Elixir version to 1.7
  * Please file an issue if this is too high

## 0.3.0 (2019-04-05)

* Fix: Use a better exception message for invalid length validator configurations
* Feature: Add support for zxcvbn via https://github.com/techgaun/zxcvbn-elixir
  * Adds zxcvbn as a dependency
  * Enabled by default (use `[zxcvbn: :disabled]` to disable**
* Fix: Bump dev dependencies

**Breaking Changes**
* `PasswordValidator.Validators.ZXCVBNValidator` is enabled by default (with a
  minimum score of 2) which in many ways is more strict than the existing
  validators.
  * Pass `[zxcvbn: :disabled]` to disable ZXCVBNValidator. e.g.
    `PasswordValidator.validate_password("some password", zxcvbn: :disabled)`

## 0.2.1 (2019-01-23)

* Fix compilation warning on Elixir 1.8
** https://github.com/axelson/password-validator/pull/3
* Update dependencies

## 0.2.0 (2018-03-19)

* Handle the case when a nil password is passed in
** https://github.com/axelson/password-validator/pull/1
* Update internal dependencies

Potentially breaking changes:
* Update formatting of returned errors
** https://github.com/axelson/password-validator/pull/1

## 0.1.2 (2017-07-31)

* Add a missing typespec and this changelog

## 0.1.1 (2017-07-31)

* Doc fixes
* Upgrade elixir and dependencies

## 0.1.0 (2017-07-31)

* Initial public release 🎉


text:
/**
 * Spring Framework configuration files.
 */
package com.upscale.front.config;


text:
<?php

/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */

// LICENSE AGREEMENT. If folded, press za here to unfold and read license {{{

/**
* +-----------------------------------------------------------------------------+
* | Copyright (c) 2004-2006 Sergio Goncalves Carvalho                                |
* +-----------------------------------------------------------------------------+
* | This file is part of XML_RPC2.                                              |
* |                                                                             |
* | XML_RPC2 is free software; you can redistribute it and/or modify            |
* | it under the terms of the GNU Lesser General Public License as published by |
* | the Free Software Foundation; either version 2.1 of the License, or         |
* | (at your option) any later version.                                         |
* |                                                                             |
* | XML_RPC2 is distributed in the hope that it will be useful,                 |
* | but WITHOUT ANY WARRANTY; without even the implied warranty of              |
* | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the               |
* | GNU Lesser General Public License for more details.                         |
* |                                                                             |
* | You should have received a copy of the GNU Lesser General Public License    |
* | along with XML_RPC2; if not, write to the Free Software                     |
* | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA                    |
* | 02111-1307 USA                                                              |
* +-----------------------------------------------------------------------------+
* | Author: Sergio Carvalho <sergio.carvalho@portugalmail.com>                  |
* +-----------------------------------------------------------------------------+
*
* @category   XML
* @package    XML_RPC2
* @author     Sergio Carvalho <sergio.carvalho@portugalmail.com>
* @copyright  2004-2006 Sergio Carvalho
* @license    http://www.gnu.org/copyleft/lesser.html  LGPL License 2.1
* @version    CVS: $Id: Class.php,v 1.5 2006/01/22 01:54:48 fab Exp $
* @link       http://pear.php.net/package/XML_RPC2
*/

// }}}

// dependencies {{{
require_once 'XML/RPC2/Exception.php';
require_once 'XML/RPC2/Server/Method.php';
require_once 'XML/RPC2/Server/CallHandler.php';
// }}}

/**
 * This class is a server call handler which exposes a classe's static public methods.
 *
 * XML_RPC2_Server_Callhandler_Class is the preferred call handler to use when you are
 * designing your XML-RPC server from the ground up. Usage is quite simple:
 *  - Create a class holding all of the XML-RPC server's exported procedures as public static methods (the interface class).
 *  - PhpDoc the classes' methods, including at least method signature (params and return types) and short description.
 *  - Use the XML_RPC2 factory method to create a server based on the interface class.
 * A simple example:
 * <code>
 * /**
 *  * echoecho echoes the message received
 *  *
 *  * @param string  Message
 *  * @return string The echo
 *  {@*}
 * class EchoServer {
 *     public static function echoecho($string)
 *     {
 *         return $string;
 *     }
 * }
 *
 * require_once 'XML/RPC2/Server.php';
 * $server = XML_RPC2_Server::create('EchoServer');
 * $server->handleCall();
 * </code>
 *
 * Use this call handler if you have designed your xml-rpc external interface as a set of
 * public class methods on a given class. If, on the other hand, you intend to export an
 * already existing class, it may be that not all of the methods you want to export are static.
 * In that case, it is probably best to use XML_RPC2_Server_Callhandler_Instance instead.
 *
 * @category   XML
 * @package    XML_RPC2
 * @author     Sergio Carvalho <sergio.carvalho@portugalmail.com>
 * @copyright  2004-2006 Sergio Carvalho
 * @license    http://www.gnu.org/copyleft/lesser.html  LGPL License 2.1
 * @link       http://pear.php.net/package/XML_RPC2
 * @see XML_RPC2_Server::create
 * @see XML_RPC2_Server_Callhandler_Instance
 */
class XML_RPC2_Server_Callhandler_Class extends XML_RPC2_Server_CallHandler
{

    // {{{ properties

    /**
     * name of target class
     *
     * @var string
     */
    private $_className;

    // }}}
    // {{{ constructor

    /**
     * XML_RPC2_Server_Callhandler_Class Constructor. Creates a new call handler exporting the give static class' methods
     *
     * Before using this constructor, take a look at XML_RPC2_Server::create. The factory
     * method is usually a quicker way of instantiating the server and its call handler.
     *
     * @see XML_RPC2_Server::create()
     * @param string The Target class. Calls will be made on this class
     * @param string Default prefix to prepend to all exported methods (defaults to '')
     */
    public function __construct($className, $defaultPrefix)
    {
        $this->_className = $className;
        $reflection = new ReflectionClass($className);
        foreach ($reflection->getMethods() as $method) {
            if ($method->isStatic() && $method->isPublic() && !$method->isAbstract() && !$method->isConstructor())
            {
                $candidate = new XML_RPC2_Server_Method($method, $defaultPrefix);
                if (!$candidate->isHidden()) $this->addMethod($candidate);
            }
        }
    }

    // }}}
    // {{{ __call()

    /**
     * __call catchall. Delegate the method call to the target class, and return its result
     *
     * @param string Name of method to call
     * @param array  Array of parameters for call
     * @return mixed Whatever the target method returned
     */
    public function __call($methodName, $parameters)
    {
        if (!array_key_exists($methodName, $this->getMethods())) {
            throw new XML_RPC2_UnknownMethodException("Method $methodName is not exported by this server");
        }
        return call_user_func_array(array($this->_className, $this->getMethod($methodName)->getInternalMethod()), $parameters);
    }

    // }}}

}

?>


text:
function include(filename, onload) {        //thanks http://stackoverflow.com/a/8139909/7314005
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.src = filename;
    script.type = 'text/javascript';
    script.onload = script.onreadystatechange = function() {
        if (script.readyState) {
            if (script.readyState === 'complete' || script.readyState === 'loaded') {
                script.onreadystatechange = null;
                onload();
            }
        }
        else {
            onload();
        }
    };
    head.appendChild(script);
}

function typeOf (obj) {     //thanks http://stackoverflow.com/a/28475765/7314005
  return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}

// PRODUCTION PATHS
var breakStuffPath = "https://rawgit.com/panxzz/NN-blackout/master/lib/break-stuff.js";
var displayModalPath = "https://rawgit.com/panxzz/NN-blackout/master/lib/modal-display.js";
// DEVELOPMENT PATHS
breakStuffPath = "/lib/break-stuff.js";
displayModalPath = "/lib/modal-display.js";

include("https://code.jquery.com/jquery-3.2.1.min.js", function(){
    $(document).ready(function() {
        //check the date/time to see if the blackout is currently going on
        $.getScript("http://novanetllc.org/datetime.php", function(data, textStatus, jqxhr){
            if(jqxhr.status == 200 && textStatus == "success")
            {
                //current blackout set to 2017-05-19 (month is zero based)
                var serverTime = new Date(parseInt(data));
                //if it is blackout time then "break" the page
                if(true)
                {
                    $.getScript(breakStuffPath, function(data, textStatus, jqxhr){
                        if(jqxhr.status == 200 && textStatus == "success")
                        {
                            breakStuff();
                        }
                        //after 10 seconds or any click on the page pop the modal
                        window.setTimeout(popModal, 10000);
                    });
                }
                else
                {
                    //console.log("don't blackout!");
                }
            }

            var popModal = function(){
                $.getScript(displayModalPath, function(data, textStatus, jqxhr){
                    if(jqxhr.status == 200 && textStatus == "success")
                    {
                        displayMessage(); //function from modal-display.js that displays a popup with the NN message
                    }
                });
            }
        });
    });
});


text:
package com.datawizards.dmg.dialects

trait Dialect {
  override def toString: String = this.getClass.getSimpleName.stripSuffix("$")
}


text:
Merchants Bank Status

                    <select name="filter-status" id="filter-status" class="cs-select cs-skin-slide">
                        <option value="">All</option>
                        <option value="<?php echo CONST_BANK_STATUS_VERIFIED; ?>">Verified</option>
                        <option value="<?php echo CONST_BANK_STATUS_NOT_VERIFIED; ?>">Not Verified</option>
                        <option value="<?php echo CONST_TXT_BANK_STATUS_NO_DETAIL; ?>">No Bank Details</option>
                    </select>

                        Merchant ID
                        Name
                        Email

                        Last Checked
                        Status


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Harmony Class Library Porting: modules/portlib/src/main/native/port/windows/hymmap.c File Reference</title>
<link href="hydoxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Modules

Data Structures

Files

Related Pages

modules/portlib/src/main/native/port/windows/hymmap.c File Reference

Detailed Description

Memory map.

This module provides memory mapping facilities that allow a user to map files into the virtual address space of the process. There are various options that can be used when mapping a file into memory, such as copy on write. Not all of these options are available on all platforms, hymmap_capabilities provides the list of supported options. Note also that on some platforms memory mapping facilites do not exist at all. On these platforms the API will still be available, but will simply read the file into allocated memory.

#include <windows.h>

#include "hyport.h"

Functions

void *VMCALL 	hymmap_map_file (struct HyPortLibrary *portLibrary, const char *path, void **handle)

 	Map a file into memory.

void VMCALL 	hymmap_unmap_file (struct HyPortLibrary *portLibrary, void *handle)

 	UnMap previously mapped memory.

void VMCALL 	hymmap_shutdown (struct HyPortLibrary *portLibrary)

 	PortLibrary shutdown.

I_32 VMCALL 	hymmap_startup (struct HyPortLibrary *portLibrary)

 	PortLibrary startup.

I_32 VMCALL 	hymmap_capabilities (struct HyPortLibrary *portLibrary)

 	Check the capabilities available for HYMMAP at runtime for the current platform.

Function Documentation

          I_32 VMCALL hymmap_capabilities
          (
          struct HyPortLibrary *
           portLibrary
           )

Check the capabilities available for HYMMAP at runtime for the current platform.

Parameters:

<tt>[in]</tt> 	portLibrary 	The port library

Returns:

a bit map containing the capabilites supported by the hymmap sub component of the port library. Possible bit values: HYPORT_MMAP_CAPABILITY_COPYONWRITE - if not present, platform is not capable of "copy on write" memory mapping.

          void* VMCALL hymmap_map_file
          (
          struct HyPortLibrary *
           portLibrary,

          const char *
           path,

          void **
           handle

          )

Map a file into memory.

Parameters:

<tt>[in]</tt> 	portLibrary 	The port library

<tt>[in]</tt> 	path 	- the path of the file to mapped into memory.

<tt>[out]</tt> 	handle 	- updates *handle with the memory map handle, this handle is later passed to unmap.

Returns:

pointer to newly mapped memory on success, NULL on error.

          void VMCALL hymmap_shutdown
          (
          struct HyPortLibrary *
           portLibrary
           )

PortLibrary shutdown.

Parameters:

<tt>[in]</tt> 	portLibrary 	The port library

This function is called during shutdown of the portLibrary. Any resources that were created by hymmap_startup should be destroyed here.

          I_32 VMCALL hymmap_startup
          (
          struct HyPortLibrary *
           portLibrary
           )

PortLibrary startup.

This function is called during startup of the portLibrary. Any resources that are required for the memory mapping operations may be created here. All resources created here should be destroyed in hymmap_shutdown.

Parameters:

<tt>[in]</tt> 	portLibrary 	The port library

Returns:

0 on success, negative error code on failure. Error code values returned are

HYPORT_ERROR_STARTUP_MMAP

Note:

Most implementations will simply return success.

          void VMCALL hymmap_unmap_file
          (
          struct HyPortLibrary *
           portLibrary,

          void *
           handle

          )

UnMap previously mapped memory.

Parameters:

<tt>[in]</tt> 	portLibrary 	The port library

<tt>[in]</tt> 	handle 	- the handle from the mmap_map_file.

<address style="text-align: center;">

Genereated on Tue Dec 9 14:12:59 2008 by Doxygen.

(c) Copyright 2005, 2008 The Apache Software Foundation or its licensors, as applicable.

</address>


text:
package fr.liglab.jlcm.internals.transactions;

public interface TransactionsList extends Iterable<IterableTransaction>, Cloneable {

	void startWriting();

	int beginTransaction(int transactionSupport);

	void addItem(int item);

	void compress(int coreItem);

	/**
	 * @return how many distinct transactions are stored
	 */
	int size();

	TransactionIterator getIterator();

	public TransactionsList clone();
}


text:
APT_PPA_REPOSITORIES=(neovim-ppa/stable)

APT_PACKAGES=(tmux htop aria2 fasd keychain \
  exuberant-ctags neovim python-dev python-pip python3-dev python3-pip atool)

NIX_PACKAGES=()

SNAP_PACKAGES=()
SNAP_CLASSIC_PACKAGES=(ripgrep)

LOGIN_SHELL="zsh"

# -----------------------------------------------------------------------------------

sudo echo

header "Installing software..."

task "Updating repositories" "sudo apt -q update"
install_packages "APT"

if [ ! -z $NIX_PACKAGES ]; then
  # task "Installing nix package manager" "bash <(curl -s https://nixos.org/nix/install)" "/nix"
  # source $HOME/.nix-profile/etc/profile.d/nix.sh

  install_packages "NIX"
fi

install_packages "SNAP"
install_packages "SNAP-CLASSIC"

task "Set ripgrep symlink" "sudo snap alias ripgrep.rg rg" "$(snap aliases | grep -c ripgrep.rg)" "1"

task "Downloading zplug" "git clone https://github.com/zplug/zplug.git $HOME/.zplug" "$HOME/.zplug"
task "Downloading base16 colors" "git clone https://github.com/chriskempson/base16-shell.git $HOME/.config/base16-shell" "$HOME/.config/base16-shell"
task "Downloading gruvbox colors" "git clone https://github.com/morhetz/gruvbox-contrib $HOME/.config/gruvbox-contrib" "$HOME/.config/gruvbox-contrib"

header "Configure system..."
task "Link config files" "$SCRIPT_DIR/link_config.sh"

task "Set $LOGIN_SHELL as default shell" "sudo chsh -s $(which $LOGIN_SHELL) $USERNAME" "$(getent passwd $USERNAME | cut -d: -f7)" "$(which $LOGIN_SHELL)"

task "Install or upgrade neovim python plugin..." "sudo pip3 install --upgrade neovim"


text:
<?php

  $name = $_POST['name'];
  $email = $_POST['email'];
  $message = $_POST['text'];
  $formErrors = false;

  // is "Name" filled out?
  if ($name === '') {
    echo "
Please enter your name.
";
    $formErrors = true;
  }

  // Is "Email" valid
  if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "E-mail is not valid";
    $formErrors = true;
  }

  // Does "Message" field have at least 25 characters?
  if (strlen($message) < 25) {
    echo "
Your Message must be at least 25 characters.
";
    $formErrors = true;
  }

  // If the form has no errors, send out the form email...
  if ($formErrors === false) {

    $to = "kai.gittens@gmail.com";
    $subject = "Contact form submitted from kaidez.com";
    $headers = 'From: ' . $email . "\r\n" .
    'Reply-To: ' . $email . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

    /*
     * $cleanUpmessage: a variable that tests to see if the message field is
     * clean. i.e., make sure that it doesn't contain HTML characters.
     */
    $cleanUpMessage = filter_var($_POST['text'], FILTER_SANITIZE_STRING);
    $message = "NAME: " . $name . "\r\n\n" . $cleanUpMessage;

    if(mail($to, $subject, $message, $headers)) {
      echo "
Thank You For Contacting Us!!!
";
    }
  }

?>


text:
var lightwallet = require('eth-lightwallet');
var Web3 = require('web3');
var fs = require('fs');
var keystoreFile = "./wallet.json";

var localcoincontract = require('../app/contracts/MyToken.json');
var localcoincontractaddress = '0xe94a4e5615E5d1BAfbDBc8a221D9b0995f67A752';

var myArgs = require('optimist').argv;
var HookedWeb3Provider = require("hooked-web3-provider");

var host = "http://faucet.ma.cx:8545";

var request = require('request');

var global_keystore;
var account;
var web3;
var web3_monitor;
var pwd = "test";

// Add 0x to address
function fixaddress(address) {
  //console.log("Fix address", address);
  if (!strStartsWith(address, '0x')) {
    return ('0x' + address);
  }
  return address;
}

function strStartsWith(str, prefix) {
  return str.indexOf(prefix) === 0;
}

if (!fs.existsSync(keystoreFile)) {

	console.log('file', keystoreFile, 'not found.. Create new wallet');

	// maak nieuwe wallet en exit
	var secretSeed = lightwallet.keystore.generateRandomSeed();
	global_keystore = new lightwallet.keystore(secretSeed, pwd);
	global_keystore.generateNewAddress(pwd, 2);
	var keyStoreString = global_keystore.serialize();

	fs.writeFileSync(keystoreFile, keyStoreString);
	console.log("The keystore was saved! ==> ", keystoreFile);

	account = global_keystore.getAddresses()[0];
	console.log('Your main account is ', account);

	console.log('Putting some ETH on this account via our Faucet ', account);

	request('http://faucet.ma.cx:3000/donate/' + account, function(error, response, body) {
		if (!error && response.statusCode == 200) {
			console.log(body) // Show the HTML for the Google homepage.

			console.log('now please add this account to the whitelist of the coin contract: ', account);
			console.log("Goodbye!");
			process.exit();
		}
	})

} else {

	console.log('Keystore file found.');
	var contents = fs.readFileSync(keystoreFile, 'utf8');
	var global_keystore = lightwallet.keystore.deserialize(contents);

	global_keystore.passwordProvider = function(callback) {
		callback(null, pwd);
	};

	account = global_keystore.getAddresses()[0];
	console.log('Your account is ', account);

	web3 = new Web3();
	var provider = new HookedWeb3Provider({
		host: host,
		transaction_signer: global_keystore
	});
	web3.setProvider(provider);

	web3_monitor = new Web3();
	web3_monitor.setProvider(new web3.providers.HttpProvider(host));

  account = fixaddress(account);
  var etherbalance = parseFloat(web3.fromWei(web3.eth.getBalance(account).toNumber(), 'ether'));

  //  var etherbalance = web3.fromWei(web3.eth.getBalance(account), 'ether').toNumber(10);
  console.log('Account', account, 'has Ξ', etherbalance);

	var gasPrice;

	web3.eth.getGasPrice(function(err, result) {

		var gasPrice = result.toNumber(10);
		console.log('gasprice is ', gasPrice);

		console.log('command:' , myArgs._[0]);
		var command = myArgs._[0];
		switch (command) {
			case 'getlc':
				var to = fixaddress(myArgs._[1]);

				console.log('sending 50 LC from',account,'to',to);

				// creation of contract object
				var MyContract = web3.eth.contract(localcoincontract.abi);
				var myContractInstance = MyContract.at(localcoincontractaddress);

				var options = {
					from: account,
					value: 0,
					gas: 3141590,
					gasPrice: gasPrice,
					nonce: Math.floor(Math.random(999999)) + new Date().getTime(),
				};

				var result = myContractInstance.mintToken(to, 50,options,
					function(err, result) {
						if (err != null) {
							console.log(err);
							console.log("ERROR: Transaction didn't go through. See console.");
						} else {
							console.log("Transaction Successful!");
							console.log('TXhash=',result);
						}
					}
				);
				break;
			default:
				console.log('please provide command : ');
				console.log('getlc <address> ( Get localcoin )')
				process.exit();
			break;

		}
	});

}


text:
<?php
namespace Craft;

class SystemSettingsService extends BaseApplicationComponent
{
	// Properties
	// =========================================================================

	/**
	 * @var
	 */
	public $defaults;

	/**
	 * @var
	 */
	private $_settingsRecords;

	// Public Methods
	// =========================================================================

	/**
	 * Returns the system settings for a category.
	 *
	 * @param string $category
	 *
	 * @return array
	 */
	public function getSettings($category)
	{
		$record = $this->_getSettingsRecord($category);

		if ($record && is_array($record->settings))
		{
			$settings = $record->settings;
		}
		else
		{
			$settings = array();
		}

		if (isset($this->defaults[$category]))
		{
			$settings = array_merge($this->defaults[$category], $settings);
		}

		return $settings;
	}

	/**
	 * Return the DateTime for when the category was last updated.
	 *
	 * @param $category
	 *
	 * @return null|DateTime
	 */
	public function getCategoryTimeUpdated($category)
	{
		// Ensure fresh data.
		unset($this->_settingsRecords[$category]);

		$record = $this->_getSettingsRecord($category);

		if ($record)
		{
			return $record->dateUpdated;
		}
		else
		{
			return null;
		}

	}

	/**
	 * Returns an individual system setting.
	 *
	 * @param string $category
	 * @param string $key
	 *
	 * @return mixed
	 */
	public function getSetting($category, $key)
	{
		$settings = $this->getSettings($category);

		if (isset($settings[$key]))
		{
			return $settings[$key];
		}
	}

	/**
	 * Saves the system settings for a category.
	 *
	 * @param string $category
	 * @param array  $settings
	 *
	 * @return bool Whether the new settings saved
	 */
	public function saveSettings($category, $settings = null)
	{
		$record = $this->_getSettingsRecord($category);

		if (!$record)
		{
			// If there are no new settings, we're already done
			if (!$settings)
			{
				return true;
			}

			// Create a new SystemSettings record, and save a reference to it
			$record = new SystemSettingsRecord();
			$record->category = $category;
			$this->_settingsRecords[$category] = $record;
		}
		else if (!$settings)
		{
			// Delete the record
			$record->delete();
			$this->_settingsRecords[$category] = false;

			return true;
		}

		$record->settings = $settings;
		$record->save();

		return !$record->hasErrors();
	}

	// Private Methods
	// =========================================================================

	/**
	 * Returns a SystemSettings record by its category.
	 *
	 * @param string $category
	 *
	 * @return mixed The SystemSettings record or false
	 */
	private function _getSettingsRecord($category)
	{
		if (!isset($this->_settingsRecords[$category]))
		{
			$record = SystemSettingsRecord::model()->findByAttributes(array(
				'category' => $category
			));

			if ($record)
			{
				$this->_settingsRecords[$category] = $record;
			}
			else
			{
				$this->_settingsRecords[$category] = false;
			}
		}

		return $this->_settingsRecords[$category];
	}
}


text:
using System;
using System.ComponentModel;
using System.Threading.Tasks;

using Microsoft.VisualStudio.ConnectedServices;

using Microsoft.TeamFoundation.Client;
using VSOnlineConnectedService.ViewModels;
using VSOnlineConnectedService.Utilities;
using EnvDTE;

namespace VSOnlineConnectedService.ViewModels
{
    internal class ServiceWizard : ConnectedServiceWizard
    {
        TeamProjectSelectionViewModel _projectSelection = new TeamProjectSelectionViewModel();
        RuntimeAuthSelectionPageViewModel _authSelection = new RuntimeAuthSelectionPageViewModel();
        OptionsViewModel _options = new OptionsViewModel();

        public ServiceWizard()
        {
            // Add the ViewModels that represent the pages of the wizard
            this.Pages.Add(_projectSelection);
            this.Pages.Add(_authSelection);
            this.Pages.Add(_options);

            foreach (var page in this.Pages)
            {
                page.PropertyChanged += this.PageViewModel_PropertyChangd;
            }
        }

        internal void Initialize()
        {
            _options.ServiceName = "VSOnline";
        }
        public ConnectedServiceProviderContext Context { get; set; }
        private void PageViewModel_PropertyChangd(object sender, PropertyChangedEventArgs e)
        {
            // Is the Server configured?
            //Ensure that a valid TFS server, project collection and project are selected before allowing the user to continue through the wizard
            if (!string.IsNullOrEmpty(this._projectSelection.VSOnlineURI) &&
               !string.IsNullOrEmpty(this._projectSelection.TeamProjectCollectionName) &&
               !string.IsNullOrEmpty(this._projectSelection.TeamProjectName))
            {
                this._authSelection.IsEnabled = true;
            }

            // Should the Finish button be enabled?
            if (!string.IsNullOrWhiteSpace(this._projectSelection.VSOnlineURI) &&
                this._projectSelection.IsEnabled &&
                this._authSelection.RuntimeAuthOptions != RuntimeAuthOptions.None)
            {
                this.IsFinishEnabled = true;
            }
        }

        public override Task<ConnectedServiceInstance> GetFinishedServiceInstanceAsync()
        {
            Instance instance = new Instance();
            instance.VSOnlineUri = this._projectSelection.VSOnlineURI;
            instance.TeamProjectName = this._projectSelection.TeamProjectName;
            instance.TeamProjectCollectionName = this._projectSelection.TeamProjectCollectionName;
            instance.Name = this._options.ServiceName;
            instance.RuntimeAuthOption = this._authSelection.RuntimeAuthOptions;
            return Task.FromResult<ConnectedServiceInstance>(instance);
        }

        /// <summary>
        /// Cleanup object references
        /// </summary>
        /// <param name="disposing"></param>
        protected override void Dispose(bool disposing)
        {
            // free up the property changed events
            foreach (var page in this.Pages)
            {
                page.PropertyChanged -= this.PageViewModel_PropertyChangd;
            }
            base.Dispose(disposing);
        }
    }
}