text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more contributor
license agreements.  See the NOTICE.txt file distributed with this work for
additional information regarding copyright ownership.  The ASF licenses this
file to you under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License.  You may obtain a copy of
the License at

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
License for the specific language governing permissions and limitations under
the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.apache.oodt</groupId>
    <artifactId>oodt-core</artifactId>
    <version>1.1-SNAPSHOT</version>
    <relativePath>core/pom.xml</relativePath>
  </parent>

  <artifactId>oodt</artifactId>
  <packaging>pom</packaging>
  <name>Apache OODT</name>
  <description>Apache OODT is middleware for metadata.</description>

  <modules>
    <module>core</module>
    <module>commons</module>
    <module>cli</module>
    <module>pcs/input</module>
    <module>metadata</module>
    <module>protocol/api</module>
    <module>protocol/ftp</module>
    <module>protocol/http</module>
    <module>protocol/imaps</module>
    <module>protocol/sftp</module>
    <module>xmlquery</module>
    <module>sso</module>
    <module>filemgr</module>
    <module>catalog</module>
    <module>workflow</module>
    <module>crawler</module>
    <module>resource</module>
    <module>curator/services</module>
    <module>curator/webapp</module>
    <module>pge</module>
    <module>mvn/plugins/cas-install</module>
    <module>mvn/archetypes</module>
    <module>pushpull</module>
    <module>product</module>
    <module>profile</module>
    <module>grid</module>
    <module>xmlps</module>
    <module>opendapps</module>
    <module>webapp/components</module>
    <module>webapp/fmbrowser</module>
    <module>webapp/fmprod</module>
    <module>webapp/wmonitor</module>
    <module>app/fmbrowser</module>
    <module>app/weditor</module>
    <module>pcs/core</module>
    <module>pcs/opsui</module>
    <module>pcs/services</module>
  </modules>

  <scm>
    <connection>scm:git:https://git-wip-us.apache.org/repos/asf/oodt.git</connection>
    <developerConnection>scm:git:https://git-wip-us.apache.org/repos/asf/oodt.git</developerConnection>
    <url>http://svn.apache.org/viewvc/oodt/trunk</url>
    <tag>HEAD</tag>
  </scm>
  <profiles>
    <profile>
      <id>audit</id>
      <activation>
        <activeByDefault>false</activeByDefault>
      </activation>
      <build>
        <plugins>
          <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>rat-maven-plugin</artifactId>
            <configuration>
              <numUnapprovedLicenses>11</numUnapprovedLicenses>
            </configuration>
            <executions>
              <execution>
                <goals>
                  <goal>check</goal>
                </goals>
                <phase>verify</phase>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>
  </profiles>
</project>


text:
require 'spec_helper'

describe RabbitMQSpec::DSL::Builder::Base do
  context 'using provided dsl' do
    specify 'I can define scalar values' do
      options = Class.new(RabbitMQSpec::DSL::Builder::Base) do
        define_dsl_attribute :attr1
        define_dsl_attribute :attr2
        define_dsl_attribute :attr3

        def build_entity
          @builded_attributes
        end
      end.build(default_attribute: 'myvalue') do
        attr1 'at1'
        attr3 4
      end

      expect(options[:attr1]).to eq('at1')
      expect(options[:attr2]).to be_nil
      expect(options[:attr3]).to be(4)
      expect(options[:default_attribute]).to eq('myvalue')
    end

    specify 'I can define hash values using a block' do
      options = Class.new(RabbitMQSpec::DSL::Builder::Base) do
        define_dsl_attribute :attr1

        def build_entity
          @builded_attributes
        end
      end.build(default_attribute: 'myvalue') do
        attr1 do
          option1 'test1'
          option2 do
            option21 21
            option22 22
          end
          option3 'test3'
        end
      end

      expect(options[:default_attribute]).to eq('myvalue')
      expect(options[:attr1][:option1]).to eq('test1')
      expect(options[:attr1][:option2][:option21]).to eq(21)
      expect(options[:attr1][:option2][:option22]).to eq(22)
      expect(options[:attr1][:option3]).to eq('test3')
    end

    it 'raises an error if I try to set a non declared attribute' do
      expect do
        options = Class.new(RabbitMQSpec::DSL::Builder::Base) do
          define_dsl_attribute :attr1
          define_dsl_attribute :attr2

          def build_entity
          end

          def to_s
            'test_builder'
          end
        end.build(default_attribute: 'myvalue') do
          attr5 'at1'
        end
      end.to raise_error("Configuration 'attr5' is not allowed for test_builder")
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
import 'jest-extended';
import { promisify } from 'util';
import {
    Collector,
    DataEntity,
    times
} from '../src';

const delay = promisify(setTimeout);

describe('Collector', () => {
    let collector: Collector<DataEntity>;
    const config = {
        size: 100,
        wait: 100,
    };

    function getQueue(): DataEntity[] {
        // @ts-ignore
        return collector._queue;
    }

    beforeEach(() => {
        collector = new Collector(config);
    });

    describe('when given a batch equal to the target size', () => {
        it('should immeditially return the batch, nothing should be queued', () => {
            const data = times(config.size, (n) => ({ n }));
            const input = DataEntity.makeArray(data);
            collector.add(input);
            const result = collector.getBatch();

            expect(result).toEqual(input);
            expect(getQueue()).toBeArrayOfSize(0);
        });
    });

    describe('when given a batch less than the target size', () => {
        it('should eventually return the batch', () => {
            const data1 = times(config.size / 2, (n) => ({ n }));
            const input1 = DataEntity.makeArray(data1);
            collector.add(input1);

            const result1 = collector.getBatch();

            expect(result1).toBeNull();
            expect(getQueue()).toBeArrayOfSize(50);

            const data2 = times(config.size / 2, (n) => ({ n }));
            const input2 = DataEntity.makeArray(data2);
            collector.add(input2);

            const result2 = collector.getBatch();

            expect(result2).toBeArrayOfSize(config.size);
            expect(getQueue()).toBeArrayOfSize(0);
        });
    });

    describe('when given a more than the target size', () => {
        it('should immediately return the batch, the remainder should be queued', () => {
            const data1 = times(config.size * 1.5, (n) => ({ n }));
            const input1 = DataEntity.makeArray(data1);
            collector.add(input1);

            const result1 = collector.getBatch();

            expect(result1).toBeArrayOfSize(config.size);
            expect(getQueue()).toBeArrayOfSize(50);

            const data2 = times(config.size / 2, (n) => ({ n }));
            const input2 = DataEntity.makeArray(data2);
            collector.add(input2);

            const result2 = collector.getBatch();

            expect(result2).toBeArrayOfSize(config.size);
            expect(getQueue()).toBeArrayOfSize(0);
        });
    });

    describe('when a batch is partially enqueued and too much time passes', () => {
        it('should immediately return the batch, the remainder should be queued', async () => {
            const data1 = times(config.size / 2, (n) => ({ n }));
            const input1 = DataEntity.makeArray(data1);
            collector.add(input1);

            const result1 = collector.getBatch();

            expect(result1).toBeNull();
            expect(getQueue()).toBeArrayOfSize(50);

            await delay(150);

            collector.add([]);

            const result2 = collector.getBatch();

            expect(result2).toBeArrayOfSize(input1.length);
            expect(getQueue()).toBeArrayOfSize(0);
        });
    });

    describe('when calling flushAll', () => {
        it('should return all of the records', () => {
            const input = DataEntity.makeArray(times(config.size * 2, (n) => ({ n })));
            collector.add(input);

            const result = collector.flushAll();
            expect(result).toBeArrayOfSize(input.length);

            expect(getQueue()).toBeArrayOfSize(0);
        });
    });
});


text:
all: monochart

# Test incubator repo
monochart: HELM_CHART_REPO_URL ?= https://charts.cloudposse.com
monochart: HELM_CHART_VERSION ?= $(shell yq r ../incubator/monochart/Chart.yaml version)
monochart:
	@echo "Testing for monochart $(HELM_CHART_VERSION)..."
	  helm repo add test-incubator $(HELM_CHART_REPO_URL)/incubator
	  helm repo update
	  helm search repo test-incubator/monochart -l -o table --version $(HELM_CHART_VERSION) | grep -qv "No results found"
	  helm pull test-incubator/monochart --version $(HELM_CHART_VERSION)
	@echo "Success!"


text:
<?php

namespace gries\MControl\Server\Command;

use gries\MControl\Server\Command\Teleport;
use gries\MControl\Server\Command\ResponseParser\LocatePlayerParser;

class LocatePlayer extends Teleport
{
    public function getResponseParser()
    {
        return new LocatePlayerParser($this->parameters['subjects'][0]);
    }
}


text:
import { EventConfig } from '../flow';
import { PointerFlow } from './pointer';

export const MSPointerConfig = {
  start: new EventConfig('MSPointerDown'),
  update: new EventConfig('MSPointerMove'),
  end: new EventConfig('MSPointerUp'),
  cancel: new EventConfig('MSPointerCancel', 'dragstart')
};
export class MSPointerFlow extends PointerFlow {
  constructor(element: Element | Document) {
    super(element, MSPointerConfig);
  }
}


text:
package org.iternine.jeppetto.dao;

import org.iternine.jeppetto.dao.id.BaseNIdGenerator;

import org.junit.Assert;
import org.junit.Test;

import java.util.List;

public class DAOBuilderTest {

    //-------------------------------------------------------------
    // Tests
    //-------------------------------------------------------------

    @Test
    public void checkBuilder() {
        SampleDAO sampleDAO = DAOBuilder.buildDAO(Sample.class,
                                                  SampleDAO.class,
                                                  PartialSampleDAOImplementation.class,
                                                  null);

        // TODO: reflect on sampleDAO for concrete implementations of methods found in SampleDAO
        // TODO: can check sampleDAO's real class type
        List<Sample> t = sampleDAO.getMany(0);

        Assert.assertTrue(t.size() > 1);
        sampleDAO.findByFieldOne(0);
        sampleDAO.findByFieldOneGreaterThan(1);
    }

    @Test
    public void idTest() {
        double base10 = (Math.log(10) / Math.log(2));
        double base16 = (Math.log(16) / Math.log(2));
        double base36 = (Math.log(36) / Math.log(2));
        double base62 = (Math.log(62) / Math.log(2));

        System.out.println(" c\t|  base10\t|  base16\t|  base36\t|  base64");
        System.out.println("---------------------------------------------------");
        for (int c = 1; c <= 64; c++) {
            System.out.println(String.format("%2d\t|  %6.2f\t|  %6.2f\t|  %6.2f\t|  %6.2f", c, c * base10, c * base16, c * base36, c * base62));
        }

//        BaseNIdGenerator baseNIdGenerator = new BaseNIdGenerator(128, BaseNIdGenerator.BASE36_CHARACTERS);
//
//        for (int i = 0; i < 100; i++) {
//            String id = baseNIdGenerator.generateId();
//
//            System.out.println(id);
//        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace Kooboo.CMS.ExtensionTemplate.Areas.BlogModule.ViewModels
{
    public class InstallationModel
    {
        [Required]
        [DisplayName("Connection string")]
        public string ConnectionString { get; set; }
    }
}


text:
New Fault Report

    <form method="post" id="add_fault" enctype="multipart/form-data">

                Beamline
                    Beamline where fault occured

                <select name="beamline" required></select>

                Start Date/Time
                    Time the fault started

                <input class="half datetime" type="text" name="start" required datetime />

                Visit ID
                    The visit during which the fault occured

                <select name="session" required></select>

                System
                    The overreaching system responsible for the fault

                <select name="system" required></select>

                Component
                    The component and sub-component at fault

                <select name="component" required></select>
                <select name="sub_component" required></select>

                Beamtime Lost
                Was beamtime lost as a result?

                <select name="beamtime_lost" required>
                    <option value='0'>No</option>
                    <option value='1'>Yes</option>
                </select>

                Beamtime Lost Between
                Time and date between which beamtime was lost

                <input class="half" type="text" name="blstart" required />
                <input class="half" type="text" name="blend" required />

                Summary
                    A short summart of the fault

                <input type="text" name="title" required />

                Description
                    Full description of the fault.
Markdown Supported

                <textarea name="desc" required></textarea>

                Attachment
                    Attachment to add to the report

                <input type="file" name="userfile1" />

                Assignee
                    An optional assignee for the fault

                <input class="half" type="text" name="assignee" />

                Fault Resolved
                Has the fault been resolved?

                <select name="resolved" required>
                    <option value="0">No</option>
                    <option value="1">Yes</option>
                    <option value="2">Partially</option>
                </select>

                End Date/Time
                    Time the fault was resolved

                <input class="half" type="text" name="end" required/>

                Resolution / Workaround
                    How the fault was resolved.
Markdown Supported

                <textarea name="resolution" required></textarea>

            <button name="submit" value="1" type="submit" class="submit">Submit Report</button>

    </form>


text:
/*
 code assumes that plainText contains ONLY LOWER CASE ALPHABETS
 */

Number.prototype.mod = function (n) {
  return ((this % n) + n) % n;
};

var keys = {a: 5, b: 7},
  N = 26;

function encrypt(plainText) {
  var cypherText = '';

  function cryptAlpha(alpha) {
    var index = alpha.charCodeAt(0) - 'a'.charCodeAt(0);
    var result = ((keys.a * index) + keys.b).mod(N);

    logger._print('Index of ' + alpha + ' = ' + index);

    result += 'a'.charCodeAt(0);
    return String.fromCharCode(result);
  }

  logger._print('Beginning Affine Encryption');
  logger._print('Encryption formula: ((keys.a * index_of_alphabet) + keys.b) % N');
  logger._print('keys.a=' + keys.a + ', keys.b=' + keys.b + ', N=' + N);

  for (var i in plainText) {
    ptTracer._select(i)._wait();
    ptTracer._deselect(i);

    cypherText += cryptAlpha(plainText [i]);

    ptTracer._notify(i, cypherText.slice(-1))._wait();
    ptTracer._denotify(i);
  }

  return cypherText;
}

function decrypt(cypherText) {
  var plainText = '';
  var aInverse = (function () {
    for (var i = 1; i < N; i++) {
      if (((keys.a * i).mod(N)) === 1) {
        return i;
      }
    }
  })();

  logger._print('a-1 = ' + aInverse);

  function decryptAlpha(alpha) {
    var index = alpha.charCodeAt(0) - 'a'.charCodeAt(0);
    var result = (aInverse * (index - keys.b)).mod(N);

    logger._print('Index of ' + alpha + ' = ' + index);

    result += 'a'.charCodeAt(0);
    return String.fromCharCode(result);
  }

  logger._print('Beginning Affine Decryption');
  logger._print('Decryption formula: (a-1 * (index - keys.b)) % N');
  logger._print('keys.b=' + keys.b + ', N=' + N);

  for (var i in cypherText) {
    ctTracer._select(i)._wait();
    ctTracer._deselect(i)._wait();

    plainText += decryptAlpha(cypherText [i]);

    ctTracer._notify(i, plainText.slice(-1))._wait();
    ctTracer._denotify(i)._wait();
  }

  return plainText;
}

var cipherText = encrypt(plainText);
ctTracer._setData(cipherText);
decrypt(cipherText);


text:
package com.twentyfive.death_list.Data;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.item.ItemStack;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

public class DeathData {

    private boolean           _has_items = false;
    private ArrayList<String> _messages  = new ArrayList<String>();
    private String            _player_name;
    private int               _player_levels;

    public DeathData(EntityPlayer player) {
        _player_levels = player.experienceLevel;
        _player_name = player.getDisplayNameString();
        this.process_inventory(player.inventory);
    }

    public String getBanner()
    {
        return _player_name + "(" + _player_levels + "): ";
    }

    public boolean hasItems() {
        return _has_items;
    }

    public Iterator<String> getItems()
    {
        return _messages.iterator();
    }

    private void flatten_hash(
        HashMap<String, Integer> item_list,
        HashMap<String, ItemStack> item_lookup
    )  {

        for( String key : item_list.keySet() )
        {
            StringBuilder item_line = new StringBuilder();
            Integer   count = item_list.get(key);
            ItemStack items = item_lookup.get(key);
            item_line.append(count);
            item_line.append(" - ");

            item_line.append( items.getChatComponent().getFormattedText() );

            _messages.add(item_line.toString());
        }

    }

    private void process_inventory(InventoryPlayer inventory)
    {
        int inventory_size = inventory.getSizeInventory();
        int list_index = 0;
        HashMap<String, Integer>    item_count  = new HashMap<String, Integer>();
        HashMap<String, ItemStack>  item_lookup = new HashMap<String, ItemStack>();

        for(int i = 0; i < inventory_size; ++i)
        {
            ItemStack items = inventory.getStackInSlot(i);

            //TODO: Next, break out the items by NBT data/Meta data.
            if(items != null) {
                String item_name = items.getUnlocalizedName();

                item_lookup.put(item_name, items);

                _has_items = true;

                if( item_count.containsKey( item_name ) )
                {
                    Integer temp = item_count.get( item_name ) + items.stackSize;
                    item_count.put( item_name, temp );
                }
                else
                {
                    item_count.put( item_name, items.stackSize );
                }

            }

        }

        if(_has_items) {
            flatten_hash(item_count, item_lookup);
        }

    }

}


text:
<!DOCTYPE html>

	<title>NLB Chatbot</title>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<meta http-equiv="X-UA-Compatible" content="IE=7">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1">

	<meta name="application-name" content="NLB Chatbot">
	<meta name="description" content="JS chatbot plugin">
	<meta name="author" content="Zoran Panev">
	<meta name="distribution" content="web">

	<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
	<link rel="stylesheet" type="text/css" href="dist/jquery.convform.min.css">
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
	  crossorigin="anonymous">
	<link rel="stylesheet" href="./css/style.min.css" />

								<form action="" method="GET" class="hidden">
									<select name="intro" conv-question="Здраво! Јас сум Вашиот НЛБ водич. Изберете некоја од следниве опции!">
										<option value="term" callback="nlbTerm">Закажи термин</option>
										<option value="creditinfo" callback="nlbCreditInfo">Инфорамции за кредит</option>
										<option value="continue">Продолжи</option>
									</select>

									<input type="text" name="name" conv-question="Супер! Кажете ми го вашето име!">
									<input type="text" conv-question="Здраво {name}:0! Задоволство ми е што разговараме." no-answer="true" />

									<select name="option" conv-question="Дали сте физичко или правно лице?">
										<option value="yes">Физичко</option>
										<option value="no">Правно</option>
									</select>

											<select name="creditorder" conv-question="Сакате да подигнете кредит?">
												<option value="yes" callback="nlbCredit">Да</option>
												<option value="no">Не</option>
											</select>

											<select name="courselist" conv-question="Сакате да ја видите денешната курсна листа?">
												<option value="yes" callback="nlbCourseList">Да</option>
												<option value="no">Не</option>
											</select>

									<input type="text" conv-question="Oдлично соработуваме!" no-answer="true">

									<input conv-question="Кажете ми го Вачиот Е-mail" pattern="^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$"
									  id="email" type="email" name="email" required placeholder="Кој е Вашиот Е-mail?">

									<input type="text" conv-question="{name}:0! Благодариме на посетата.">
								</form>


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Vestris.ResourceLib;
using System.Reflection;
using System.Web;
using NUnit.Framework;
using System.ComponentModel;

namespace Vestris.ResourceLibUnitTests
{
    [TestFixture]
    public class VersionResourceTests
    {
        [TestCase("atl.dll")]
        public void TestLoadVersionResource(string binaryName)
        {
            Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
            string filename = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Binaries\\" + binaryName);
            Assert.IsTrue(File.Exists(filename));
            VersionResource versionResource = new VersionResource();
            versionResource.Language = ResourceUtil.USENGLISHLANGID;
            versionResource.LoadFrom(filename);
            DumpResource.Dump(versionResource);
            AssertOneVersionResource(filename);
        }

        [TestCase("atl.dll")]
        public void TestLoadVersionResourceStrings(string binaryName)
        {
            Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
            string filename = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Binaries\\" + binaryName);
            Assert.IsTrue(File.Exists(filename));
            VersionResource versionResource = new VersionResource();
            versionResource.Language = ResourceUtil.USENGLISHLANGID;
            versionResource.LoadFrom(filename);
            DumpResource.Dump(versionResource);
            AssertOneVersionResource(filename);
        }

        [TestCase("atl.dll")]
        public void TestLoadAndSaveVersionResource(string binaryName)
        {
            Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
            string filename = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Binaries\\" + binaryName);
            Assert.IsTrue(File.Exists(filename));

            VersionResource versionResource = new VersionResource();
            versionResource.Language = ResourceUtil.USENGLISHLANGID;
            versionResource.LoadFrom(filename);
            DumpResource.Dump(versionResource);

            versionResource.FileVersion = "1.2.3.4";
            versionResource.ProductVersion = "5.6.7.8";
            versionResource.FileFlags = 0x2 | 0x8;  // private and prerelease

            StringFileInfo stringFileInfo = (StringFileInfo)versionResource["StringFileInfo"];
            stringFileInfo["Comments"] = string.Format("{0}\0", Guid.NewGuid());
            stringFileInfo["NewValue"] = string.Format("{0}\0", Guid.NewGuid());

            VarFileInfo varFileInfo = (VarFileInfo)versionResource["VarFileInfo"];
            varFileInfo[ResourceUtil.USENGLISHLANGID] = 1300;

            string targetFilename = Path.Combine(Path.GetTempPath(), "test.dll");
            File.Copy(filename, targetFilename, true);
            Console.WriteLine(targetFilename);
            versionResource.SaveTo(targetFilename);

            VersionResource newVersionResource = new VersionResource();
            newVersionResource.Language = ResourceUtil.USENGLISHLANGID;
            newVersionResource.LoadFrom(targetFilename);
            DumpResource.Dump(versionResource);

            AssertOneVersionResource(targetFilename);
            Assert.AreEqual(newVersionResource.FileVersion, versionResource.FileVersion);
            Assert.AreEqual(newVersionResource.ProductVersion, versionResource.ProductVersion);
            Assert.AreEqual(newVersionResource.FileFlags, versionResource.FileFlags);

            StringFileInfo testedStringFileInfo = (StringFileInfo)newVersionResource["StringFileInfo"];
            foreach (KeyValuePair<string, StringTableEntry> stringResource in testedStringFileInfo.Default.Strings)
            {
                Console.WriteLine("{0} = {1}", stringResource.Value.Key, stringResource.Value.StringValue);
                Assert.AreEqual(stringResource.Value.Value, stringFileInfo[stringResource.Key]);
            }

            VarFileInfo newVarFileInfo = (VarFileInfo)newVersionResource["VarFileInfo"];
            foreach (KeyValuePair<UInt16, UInt16> varResource in newVarFileInfo.Default.Languages)
            {
                Console.WriteLine("{0} = {1}", varResource.Key, varResource.Value);
                Assert.AreEqual(varResource.Value, varFileInfo[varResource.Key]);
            }
        }

        [TestCase("atl.dll")]
        public void TestDeleteVersionResource(string binaryName)
        {
            Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
            string filename = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Binaries\\" + binaryName);
            Assert.IsTrue(File.Exists(filename));
            string targetFilename = Path.Combine(Path.GetTempPath(), "testDeleteVersionResource.dll");
            File.Copy(filename, targetFilename, true);
            Console.WriteLine(targetFilename);
            VersionResource versionResource = new VersionResource();
            versionResource.Language = ResourceUtil.USENGLISHLANGID;
            versionResource.LoadFrom(targetFilename);
            Console.WriteLine("Name: {0}", versionResource.Name);
            Console.WriteLine("Type: {0}", versionResource.Type);
            Console.WriteLine("Language: {0}", versionResource.Language);
            versionResource.DeleteFrom(targetFilename);
            try
            {
                versionResource.LoadFrom(targetFilename);
                Assert.Fail("Expected that the deleted resource cannot be found");
            }
            catch (Win32Exception ex)
            {
                // expected exception
                Console.WriteLine("Expected exception: {0}", ex.Message);
            }

            AssertNoVersionResource(targetFilename);

            using (ResourceInfo ri = new ResourceInfo())
            {
                ri.Load(targetFilename);
                DumpResource.Dump(ri);
            }
        }

        [TestCase("atl.dll")]
        public void TestDeepCopyBytes(string binaryName)
        {
            Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
            string filename = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Binaries\\" + binaryName);
            Assert.IsTrue(File.Exists(filename));
            VersionResource existingVersionResource = new VersionResource();
            existingVersionResource.Language = ResourceUtil.USENGLISHLANGID;
            Console.WriteLine("Loading {0}", filename);
            existingVersionResource.LoadFrom(filename);
            DumpResource.Dump(existingVersionResource);

            VersionResource versionResource = new VersionResource();
            versionResource.FileVersion = existingVersionResource.FileVersion;
            versionResource.ProductVersion = existingVersionResource.ProductVersion;

            StringFileInfo existingVersionResourceStringFileInfo = (StringFileInfo)existingVersionResource["StringFileInfo"];
            VarFileInfo existingVersionResourceVarFileInfo = (VarFileInfo)existingVersionResource["VarFileInfo"];

            // copy string resources, data only
            StringFileInfo stringFileInfo = new StringFileInfo();
            versionResource["StringFileInfo"] = stringFileInfo;
            {
                Dictionary<string, StringTable>.Enumerator enumerator = existingVersionResourceStringFileInfo.Strings.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    StringTable stringTable = new StringTable(enumerator.Current.Key);
                    stringFileInfo.Strings.Add(enumerator.Current.Key, stringTable);
                    Dictionary<string, StringTableEntry>.Enumerator resourceEnumerator = enumerator.Current.Value.Strings.GetEnumerator();
                    while (resourceEnumerator.MoveNext())
                    {
                        StringTableEntry stringResource = new StringTableEntry(resourceEnumerator.Current.Key);
                        stringResource.Value = resourceEnumerator.Current.Value.Value;
                        stringTable.Strings.Add(resourceEnumerator.Current.Key, stringResource);
                    }
                }
            }

            // copy var resources, data only
            VarFileInfo varFileInfo = new VarFileInfo();
            versionResource["VarFileInfo"] = varFileInfo;
            {
                Dictionary<string, VarTable>.Enumerator enumerator = existingVersionResourceVarFileInfo.Vars.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    VarTable varTable = new VarTable(enumerator.Current.Key);
                    varFileInfo.Vars.Add(enumerator.Current.Key, varTable);
                    Dictionary<UInt16, UInt16>.Enumerator translationEnumerator = enumerator.Current.Value.Languages.GetEnumerator();
                    while (translationEnumerator.MoveNext())
                    {
                        varTable.Languages.Add(translationEnumerator.Current.Key, translationEnumerator.Current.Value);
                    }
                }
            }

            ByteUtils.CompareBytes(existingVersionResource.WriteAndGetBytes(), versionResource.WriteAndGetBytes());
        }

        [TestCase("atl.dll")]
        public void TestDeleteDeepCopyAndSaveVersionResource(string binaryName)
        {
            Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
            string filename = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Binaries\\" + binaryName);
            Assert.IsTrue(File.Exists(filename));
            string targetFilename = Path.Combine(Path.GetTempPath(), binaryName);
            File.Copy(filename, targetFilename, true);
            Console.WriteLine(targetFilename);
            VersionResource existingVersionResource = new VersionResource();
            existingVersionResource.Language = ResourceUtil.USENGLISHLANGID;
            existingVersionResource.LoadFrom(targetFilename);
            DumpResource.Dump(existingVersionResource);
            existingVersionResource.DeleteFrom(targetFilename);

            VersionResource versionResource = new VersionResource();
            versionResource.FileVersion = existingVersionResource.FileVersion;
            versionResource.ProductVersion = existingVersionResource.ProductVersion;

            StringFileInfo existingVersionResourceStringFileInfo = (StringFileInfo)existingVersionResource["StringFileInfo"];
            VarFileInfo existingVersionResourceVarFileInfo = (VarFileInfo)existingVersionResource["VarFileInfo"];

            // copy string resources, data only
            StringFileInfo stringFileInfo = new StringFileInfo();
            versionResource["StringFileInfo"] = stringFileInfo;
            {
                Dictionary<string, StringTable>.Enumerator enumerator = existingVersionResourceStringFileInfo.Strings.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    StringTable stringTable = new StringTable(enumerator.Current.Key);
                    stringFileInfo.Strings.Add(enumerator.Current.Key, stringTable);
                    Dictionary<string, StringTableEntry>.Enumerator resourceEnumerator = enumerator.Current.Value.Strings.GetEnumerator();
                    while (resourceEnumerator.MoveNext())
                    {
                        StringTableEntry stringResource = new StringTableEntry(resourceEnumerator.Current.Key);
                        stringResource.Value = resourceEnumerator.Current.Value.Value;
                        stringTable.Strings.Add(resourceEnumerator.Current.Key, stringResource);
                    }
                }
            }

            // copy var resources, data only
            VarFileInfo varFileInfo = new VarFileInfo();
            versionResource["VarFileInfo"] = varFileInfo;
            {
                Dictionary<string, VarTable>.Enumerator enumerator = existingVersionResourceVarFileInfo.Vars.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    VarTable varTable = new VarTable(enumerator.Current.Key);
                    varFileInfo.Vars.Add(enumerator.Current.Key, varTable);
                    Dictionary<UInt16, UInt16>.Enumerator translationEnumerator = enumerator.Current.Value.Languages.GetEnumerator();
                    while (translationEnumerator.MoveNext())
                    {
                        varTable.Languages.Add(translationEnumerator.Current.Key, translationEnumerator.Current.Value);
                    }
                }
            }

            versionResource.SaveTo(targetFilename);
            Console.WriteLine("Reloading {0}", targetFilename);

            VersionResource newVersionResource = new VersionResource();
            newVersionResource.LoadFrom(targetFilename);
            DumpResource.Dump(newVersionResource);

            AssertOneVersionResource(targetFilename);
            Assert.AreEqual(newVersionResource.FileVersion, versionResource.FileVersion);
            Assert.AreEqual(newVersionResource.ProductVersion, versionResource.ProductVersion);

            StringFileInfo testedStringFileInfo = (StringFileInfo)newVersionResource["StringFileInfo"];
            foreach (KeyValuePair<string, StringTableEntry> stringResource in testedStringFileInfo.Default.Strings)
            {
                Assert.AreEqual(stringResource.Value.Value, stringFileInfo[stringResource.Key]);
            }

            VarFileInfo newVarFileInfo = (VarFileInfo)newVersionResource["VarFileInfo"];
            foreach (KeyValuePair<UInt16, UInt16> varResource in newVarFileInfo.Default.Languages)
            {
                Assert.AreEqual(varResource.Value, varFileInfo[varResource.Key]);
            }
        }

        [TestCase("atl.dll")]
        public void TestDeleteAndSaveVersionResource(string binaryName)
        {
            Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
            string filename = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Binaries\\" + binaryName);
            Assert.IsTrue(File.Exists(filename));
            string targetFilename = Path.Combine(Path.GetTempPath(), "testDeleteAndSaveVersionResource.dll");
            File.Copy(filename, targetFilename, true);
            Console.WriteLine(targetFilename);
            VersionResource existingVersionResource = new VersionResource();
            existingVersionResource.DeleteFrom(targetFilename);

            VersionResource versionResource = new VersionResource();
            versionResource.FileVersion = "1.2.3.4";
            versionResource.ProductVersion = "4.5.6.7";

            StringFileInfo stringFileInfo = new StringFileInfo();
            versionResource[stringFileInfo.Key] = stringFileInfo;
            StringTable stringFileInfoStrings = new StringTable(); // "040904b0"
            stringFileInfoStrings.LanguageID = 1033;
            stringFileInfoStrings.CodePage = 1200;
            Assert.AreEqual(1033, stringFileInfoStrings.LanguageID);
            Assert.AreEqual(1200, stringFileInfoStrings.CodePage);
            stringFileInfo.Strings.Add(stringFileInfoStrings.Key, stringFileInfoStrings);
            stringFileInfoStrings["ProductName"] = "ResourceLib";
            stringFileInfoStrings["FileDescription"] = "File updated by ResourceLib\0";
            stringFileInfoStrings["CompanyName"] = "Vestris Inc.";
            stringFileInfoStrings["LegalCopyright"] = "All Rights Reserved\0";
            stringFileInfoStrings["EmptyValue"] = "";
            stringFileInfoStrings["Comments"] = string.Format("{0}\0", Guid.NewGuid());
            stringFileInfoStrings["ProductVersion"] = string.Format("{0}\0", versionResource.ProductVersion);

            VarFileInfo varFileInfo = new VarFileInfo();
            versionResource[varFileInfo.Key] = varFileInfo;
            VarTable varFileInfoTranslation = new VarTable("Translation");
            varFileInfo.Vars.Add(varFileInfoTranslation.Key, varFileInfoTranslation);
            varFileInfoTranslation[ResourceUtil.USENGLISHLANGID] = 1300;

            versionResource.SaveTo(targetFilename);
            Console.WriteLine("Reloading {0}", targetFilename);

            VersionResource newVersionResource = new VersionResource();
            newVersionResource.LoadFrom(targetFilename);
            DumpResource.Dump(newVersionResource);

            AssertOneVersionResource(targetFilename);
            Assert.AreEqual(newVersionResource.FileVersion, versionResource.FileVersion);
            Assert.AreEqual(newVersionResource.ProductVersion, versionResource.ProductVersion);
        }

        [Test]
        public void TestLoadNeutralDeleteEnglishResource()
        {
            // the 6to4svc.dll has an English version info strings resource that is loaded via netural
            VersionResource vr = new VersionResource();
            string testDll = Path.Combine(Path.GetTempPath(), "testLoadNeutralDeleteEnglishResource.dll");
            Console.WriteLine(testDll);
            Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
            string dll = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Binaries\\6to4svc.dll");
            File.Copy(dll, testDll, true);
            vr.LoadFrom(testDll);
            Assert.AreEqual(1033, vr.Language);
            vr.DeleteFrom(testDll);
        }

        [Test]
        public void TestLoadDeleteGreekResource()
        {
            // the 6to4svcgreek.dll has a Greek version info strings resource
            VersionResource vr = new VersionResource();
            vr.Language = 1032;
            string testDll = Path.Combine(Path.GetTempPath(), "testLoadDeleteGreekResource.dll");
            Console.WriteLine(testDll);
            Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
            string dll = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Binaries\\6to4svcgreek.dll");
            File.Copy(dll, testDll, true);
            vr.LoadFrom(testDll);
            DumpResource.Dump(vr);
            Assert.AreEqual(1032, vr.Language);
            vr.DeleteFrom(testDll);
        }

        [Test]
        public void TestDoubleNullTerminator()
        {
            StringTableEntry sr = new StringTableEntry("dummy");
            string guid = Guid.NewGuid().ToString();
            sr.Value = guid;
            Assert.AreEqual(guid + '\0', sr.Value);
            Assert.AreEqual(guid, sr.StringValue);
            Assert.AreEqual(guid.Length + 1, sr.Header.wValueLength);
            sr.Value = guid + '\0';
            Assert.AreEqual(guid + '\0', sr.Value);
            Assert.AreEqual(guid, sr.StringValue);
            Assert.AreEqual(guid.Length + 1, sr.Header.wValueLength);
            sr.Value = guid + "\0\0";
            Assert.AreEqual(guid + "\0\0", sr.Value);
            Assert.AreEqual(guid + '\0', sr.StringValue);
            Assert.AreEqual(guid.Length + 2, sr.Header.wValueLength);
            sr.Value = '\0' + guid;
            Assert.AreEqual('\0' + guid + '\0', sr.Value);
            Assert.AreEqual('\0' + guid, sr.StringValue);
            Assert.AreEqual(guid.Length + 2, sr.Header.wValueLength);
        }

        #region Helper methods

        private static void AssertOneVersionResource(string fileName)
        {
            Assert.AreEqual(
                1,
                GetOccurrencesOf("StringFileInfo", fileName),
                "More than one StringFileInfo block found.");

            Assert.AreEqual(
                1,
                GetOccurrencesOf("VarFileInfo", fileName),
                "More than one VarFileInfo block found.");
        }

        private static void AssertNoVersionResource(string fileName)
        {
            Assert.AreEqual(
                0,
                GetOccurrencesOf("StringFileInfo", fileName),
                "StringFileInfo block found.");

            Assert.AreEqual(
                0,
                GetOccurrencesOf("VarFileInfo", fileName),
                "VarFileInfo block found.");
        }

        private static int GetOccurrencesOf(string text, string fileName)
        {
            byte[] contentData = File.ReadAllBytes(fileName);

            var chars = new char[contentData.Length / sizeof(char)];
            Buffer.BlockCopy(contentData, 0, chars, 0, contentData.Length);
            var content = new string(chars);

            int occurrences = 0;
            int index = -1;

            while ((index = content.IndexOf(text, index + 1, StringComparison.InvariantCulture)) != -1)
            {
                occurrences++;
            }

            return occurrences;
        }

        #endregion
    }
}


text:
"""
    stamps.services
    ~~~~~~~~~~~~~~~

    Stamps.com services.

    :copyright: 2014 by Jonathan Zempel.
    :license: BSD, see LICENSE for more details.
"""

from decimal import Decimal
from logging import getLogger
from re import compile
from suds import WebFault
from suds.bindings.document import Document
from suds.client import Client
from suds.plugin import MessagePlugin
from suds.sax.element import Element
from suds.sudsobject import asdict
from suds.xsd.sxbase import XBuiltin
from suds.xsd.sxbuiltin import Factory

PATTERN_HEX = r"[0-9a-fA-F]"
PATTERN_ID = r"{hex}{{8}}-{hex}{{4}}-{hex}{{4}}-{hex}{{4}}-{hex}{{12}}".format(
    hex=PATTERN_HEX)
RE_TRANSACTION_ID = compile(PATTERN_ID)

class AuthenticatorPlugin(MessagePlugin):
    """Handle message authentication.

    :param credentials: Stamps API credentials.
    :param wsdl: Configured service client.
    """

    def __init__(self, credentials, client):
        self.credentials = credentials
        self.client = client
        self.authenticator = None

    def marshalled(self, context):
        """Add an authenticator token to the document before it is sent.

        :param context: The current message context.
        """
        body = context.envelope.getChild("Body")
        operation = body[0]

        if operation.name in ("AuthenticateUser", "RegisterAccount"):
            pass
        elif self.authenticator:
            namespace = operation.namespace()
            element = Element("Authenticator", ns=namespace)
            element.setText(self.authenticator)
            operation.insert(element)
        else:
            document = Document(self.client.wsdl)
            method = self.client.service.AuthenticateUser.method
            parameter = document.param_defs(method)[0]
            element = document.mkparam(method, parameter, self.credentials)
            operation.insert(element)

    def unmarshalled(self, context):
        """Store the authenticator token for the next call.

        :param context: The current message context.
        """
        if hasattr(context.reply, "Authenticator"):
            self.authenticator = context.reply.Authenticator
            del context.reply.Authenticator
        else:
            self.authenticator = None

        return context

class BaseService(object):
    """Base service.

    :param configuration: API configuration.
    """

    def __init__(self, configuration):
        Factory.maptag("decimal", XDecimal)
        self.client = Client(configuration.wsdl)
        credentials = self.create("Credentials")
        credentials.IntegrationID = configuration.integration_id
        credentials.Username = configuration.username
        credentials.Password = configuration.password
        self.plugin = AuthenticatorPlugin(credentials, self.client)
        self.client.set_options(plugins=[self.plugin], port=configuration.port)
        self.logger = getLogger("stamps")

    def call(self, method, **kwargs):
        """Call the given web service method.

        :param method: The name of the web service operation to call.
        :param kwargs: Method keyword-argument parameters.
        """
        self.logger.debug("%s(%s)", method, kwargs)
        instance = getattr(self.client.service, method)

        try:
            ret_val = instance(**kwargs)
        except WebFault as error:
            self.logger.warning("Retry %s", method, exc_info=True)
            self.plugin.authenticator = None

            try:  # retry with a re-authenticated user.
                ret_val = instance(**kwargs)
            except WebFault as error:
                self.logger.exception("%s retry failed", method)
                self.plugin.authenticator = None
                raise error

        return ret_val

    def create(self, wsdl_type):
        """Create an object of the given WSDL type.

        :param wsdl_type: The WSDL type to create an object for.
        """
        return self.client.factory.create(wsdl_type)

class StampsService(BaseService):
    """Stamps.com service.
    """

    def add_postage(self, amount, transaction_id=None):
        """Add postage to the account.

        :param amount: The amount of postage to purchase.
        :param transaction_id: Default `None`. ID that may be used to retry the
            purchase of this postage.
        """
        account = self.get_account()
        control = account.AccountInfo.PostageBalance.ControlTotal

        return self.call("PurchasePostage", PurchaseAmount=amount,
                ControlTotal=control, IntegratorTxID=transaction_id)

    def create_add_on(self):
        """Create a new add-on object.
        """
        return self.create("AddOnV7")

    def create_address(self):
        """Create a new address object.
        """
        return self.create("Address")

    def create_purchase_status(self):
        """Create a new purchase status object.
        """
        return self.create("PurchaseStatus")

    def create_registration(self):
        """Create a new registration object.
        """
        ret_val = self.create("RegisterAccount")
        ret_val.IntegrationID = self.plugin.credentials.IntegrationID
        ret_val.UserName = self.plugin.credentials.Username
        ret_val.Password = self.plugin.credentials.Password

        return ret_val

    def create_shipping(self):
        """Create a new shipping object.
        """
        return self.create("RateV18")

    def get_address(self, address):
        """Get a shipping address.

        :param address: Address instance to get a clean shipping address for.
        """
        return self.call("CleanseAddress", Address=address)

    def get_account(self):
        """Get account information.
        """
        return self.call("GetAccountInfo")

    def get_label(self, from_address, to_address, rate, transaction_id,
            sample=False):
        """Get a shipping label.

        :param from_address: The shipping 'from' address.
        :param to_address: The shipping 'to' address.
        :param rate: A rate instance for the shipment.
        :param transaction_id: ID that may be used to retry/rollback the
            purchase of this label.
        :param sample: Default ``False``. Get a sample label without postage.
        """
        return self.call("CreateIndicium", IntegratorTxID=transaction_id,
                Rate=rate, From=from_address, To=to_address, SampleOnly=sample)

    def get_postage_status(self, transaction_id):
        """Get postage purchase status.

        :param transaction_id: The transaction ID returned by
            :meth:`add_postage`.
        """
        return self.call("GetPurchaseStatus", TransactionID=transaction_id)

    def get_rates(self, shipping):
        """Get shipping rates.

        :param shipping: Shipping instance to get rates for.
        """
        rates = self.call("GetRates", Rate=shipping)

        return [rate for rate in rates.Rates.Rate]

    def get_tracking(self, transaction_id):
        """Get tracking events for a shipment.

        :param transaction_id: The transaction ID (or tracking number) returned
            by :meth:`get_label`.
        """
        if RE_TRANSACTION_ID.match(transaction_id):
            arguments = dict(StampsTxID=transaction_id)
        else:
            arguments = dict(TrackingNumber=transaction_id)

        return self.call("TrackShipment", **arguments)

    def register_account(self, registration):
        """Register a new account.

        :param registration: Registration instance.
        """
        arguments = asdict(registration)

        return self.call("RegisterAccount", **arguments)

    def remove_label(self, transaction_id):
        """Cancel a shipping label.

        :param transaction_id: The transaction ID (or tracking number) returned
            by :meth:`get_label`.
        """
        if RE_TRANSACTION_ID.match(transaction_id):
            arguments = dict(StampsTxID=transaction_id)
        else:
            arguments = dict(TrackingNumber=transaction_id)

        return self.call("CancelIndicium", **arguments)

class XDecimal(XBuiltin):
    """Represents an XSD decimal type.
    """

    def translate(self, value, topython=True):
        """Translate between string and decimal values.

        :param value: The value to translate.
        :param topython: Default `True`. Determine whether to translate the
            value for python.
        """
        if topython:
            if isinstance(value, basestring) and len(value):
                ret_val = Decimal(value)
            else:
                ret_val = None
        else:
            if isinstance(value, (int, float, Decimal)):
                ret_val = str(value)
            else:
                ret_val = value

        return ret_val


text:
[![Thundra Foresight](https://thundra-assets-prod.s3.us-west-2.amazonaws.com/images/badges/thundra-foresight-badge-enabled.svg)](https://foresight.thundra.live/testRuns/5a49cc30-f063-11eb-9a03-0242ac130003)
[![Thundra Foresight Test Results](https://foresight.service.thundra.us/public/api/v1/badge/test/5a49cc30-f063-11eb-9a03-0242ac130003)](https://foresight.thundra.live/testRuns/5a49cc30-f063-11eb-9a03-0242ac130003)
[![Revved up by Gradle Enterprise](https://img.shields.io/badge/Revved%20up%20by-Gradle%20Enterprise-06A0CE?logo=Gradle&labelColor=02303A)](https://ge.testcontainers.org/scans)

> Testcontainers is a Java library that supports JUnit tests, providing lightweight, throwaway instances of common databases, Selenium web browsers, or anything else that can run in a Docker container.

![Testcontainers logo](docs/logo.png)

# [Read the documentation here](http://www.testcontainers.org)

## License

See [LICENSE](LICENSE).

## Copyright

Copyright (c) 2015 - 2021 Richard North and other authors.

MS SQL Server module is (c) 2017 - 2021 G DATA Software AG and other authors.

Hashicorp Vault module is (c) 2017 - 2021 Capital One Services, LLC and other authors.

See [contributors](https://github.com/testcontainers/testcontainers-java/graphs/contributors) for all contributors.


text:
enum class ServiceAccessType;

namespace password_manager {
class PasswordChangeSuccessTracker;
}  // namespace password_manager

namespace ios_web_view {

class WebViewBrowserState;

// Singleton that owns all PasswordChangeSuccessTracker and associates them with
// WebViewBrowserStates.
class WebViewPasswordChangeSuccessTrackerFactory
    : public BrowserStateKeyedServiceFactory {
 public:
  static password_manager::PasswordChangeSuccessTracker* GetForBrowserState(
      WebViewBrowserState* browser_state,
      ServiceAccessType access_type);

  static WebViewPasswordChangeSuccessTrackerFactory* GetInstance();

 private:
  friend class base::NoDestructor<WebViewPasswordChangeSuccessTrackerFactory>;

  WebViewPasswordChangeSuccessTrackerFactory();
  ~WebViewPasswordChangeSuccessTrackerFactory() override;

  // BrowserStateKeyedServiceFactory:
  std::unique_ptr<KeyedService> BuildServiceInstanceFor(
      web::BrowserState* context) const override;

  WebViewPasswordChangeSuccessTrackerFactory(
      const WebViewPasswordChangeSuccessTrackerFactory&) = delete;
  WebViewPasswordChangeSuccessTrackerFactory& operator=(
      const WebViewPasswordChangeSuccessTrackerFactory&) = delete;
};

}  // namespace ios_web_view

#endif  // IOS_WEB_VIEW_INTERNAL_PASSWORDS_WEB_VIEW_PASSWORD_CHANGE_SUCCESS_TRACKER_FACTORY_H_


text:
/*PLEASE DO NOT EDIT THIS CODE*/
/*This code was generated using the UMPLE 1.21.0.4666 modeling language!*/

import javax.swing.JFrame;
import javax.swing.JLabel;

// line 20 "ExternalInterface.ump"
public class HelloInternals extends JFrame
{

  //------------------------
  // MEMBER VARIABLES
  //------------------------

  //HelloInternals Attributes

  /**
   * messageLabel is a component of the frame; often we don't want sub-components
   * of a GUI unit to be settable/gettable. By making them internal Umple will avoid
   * generating setter/getter for messageLabel. Using lazy Umple will avoid adding a
   * constructor parameter for this component
   */
  private JLabel messageLabel;
  private String message;

  //------------------------
  // CONSTRUCTOR
  //------------------------

  public HelloInternals(String aMessage)
  {
    super();
    message = aMessage;
    // line 50 "ExternalInterface.ump"
    getContentPane().setLayout(null);

        messageLabel=new JLabel(message);
        messageLabel.setBounds(10, 10, 200, 20);
        add(messageLabel);

        pack();
        setSize(250, 200);
  }

  //------------------------
  // INTERFACE
  //------------------------

  public boolean setMessage(String aMessage)
  {
    boolean wasSet = false;
    message = aMessage;
    wasSet = true;
    // line 45 "ExternalInterface.ump"
    messageLabel.setText(message);
    return wasSet;
  }

  /**
   * the contents of messageLabel
   */
  public String getMessage()
  {
    // line 39 "ExternalInterface.ump"
    message=messageLabel.getText();
    return message;
  }

  public void delete()
  {}

  public String toString()
  {
	  String outputString = "";
    return super.toString() + "["+
            "message" + ":" + getMessage()+ "]"
     + outputString;
  }
}


text:
namespace partial_tweets {

using namespace rapidjson;

struct rapidjson_sax {
    using StringType=std::string_view;

    // 8 keys to parse for each tweet (in order of appearance): "created_at", "id", "text", "in_reply_status_id", "id"(user),
    // "screen_name"(user), "retweet_count" and "favorite_count".
    // Assume that the first valid key encountered will be the correct key to parse.
    // Assume that each tweet/retweet start with a key "metadata" and has a key "retweeted" towards the end
    // The previous assumption will be used to check for the beginning of a new tweet and the end of a retweet
    struct Handler {
        enum state {    // Bitset to store state of search
            key_date = (1<<0),
            key_id = (1<<1),
            key_text = (1<<2),
            key_reply = (1<<3),
            key_userid = (1<<4),
            key_screenname = (1<<5),
            key_rt = (1<<6),
            key_fav = (1<<7),
            found_date = (1<<8),
            found_id = (1<<9),
            found_text = (1<<10),
            found_reply = (1<<11),
            found_userid = (1<<12),
            found_screenname = (1<<13),
            found_rt = (1<<14),
            found_fav = (1<<15)
        };
        int values = state::key_date;
        bool userobject_id = false; // If in a user object (to find user.id)
        bool userobject_screen_name = false;    // If in a user object (to find user.screen_name)
        bool inretweet = false; // If in a retweet (all keys irrelevant in retweet object)
        // Fields to store partial tweet info
        uint64_t user_id;
        uint64_t id;
        uint64_t rt;
        uint64_t fav;
        uint64_t reply_status;
        std::string_view screen_name;
        std::string_view date;
        std::string_view text;
        std::vector<tweet<std::string_view>>& result;

        Handler(std::vector<tweet<std::string_view>> &r) : result(r) { }

        bool Key(const char* key, SizeType length, bool copy) {
            if (!inretweet) {   // If not in a retweet object, find relevant keys
                if ((length == 16) && (memcmp(key,"retweeted_status",16) == 0)) { inretweet = true; }   // Check if entering retweet
                else if ((length == 8) && (memcmp(key,"metadata",8) == 0)) { values = 0; }  // Reset
                // Check if key has been found and if key matches a valid key
                else if (!(values & found_date) && (length == 10) && (memcmp(key,"created_at",10) == 0)) { values |= (key_date); }
                // Must also check if not in a user object
                else if (!(values & found_id) && !userobject_id && (length == 2) && (memcmp(key,"id",2) == 0)) { values |= (key_id); }
                else if (!(values & found_text) && (length == 4) && (memcmp(key,"text",4) == 0)) { values |= (key_text); }
                else if (!(values & found_reply) && (length == 21) && (memcmp(key,"in_reply_to_status_id",21) == 0)) { values |= (key_reply); }
                // Check if entering user object
                else if ((length == 4) && (memcmp(key,"user",4) == 0)) { userobject_id = userobject_screen_name = true; }
                // Must also check if in a user object
                else if (!(values & found_userid) && userobject_id && (length == 2) && (memcmp(key,"id",2) == 0)) { values |= (key_userid); }
                // Must also check if in a user object
                else if (!(values & found_screenname) && userobject_screen_name && (length == 11) && (memcmp(key,"screen_name",11) == 0)) { values |= (key_screenname); }
                else if (!(values & found_rt) && (length == 13) && (memcmp(key,"retweet_count",13) == 0)) { values |= (key_rt); }
                else if (!(values & found_fav) && (length == 14) && (memcmp(key,"favorite_count",14) == 0)) { values |= (key_fav); }
            }
            else if ((length == 9) && (memcmp(key,"retweeted",9) == 0)) { inretweet = false; }  // Check if end of retweet
            return true;
        }
        bool Uint(unsigned i) {
            if (values & key_userid && !(values & found_userid)) {    // user.id
                user_id = i;
                userobject_id = false;
                values &= ~(key_userid);
                values |= (found_userid);
            }
            else if (values & key_rt && !(values & found_rt)) {   // retweet_count
                rt = i;
                values &= ~(key_rt);
                values |= (found_rt);
            }
            else if (values & key_fav && !(values & found_fav)) {   // favorite_count
                fav = i;
                values &= ~(key_fav);
                values |= (found_fav);
                // Assume that this is last key required, so add the partial_tweet to result
                result.emplace_back(partial_tweets::tweet<std::string_view>{
                date,id,text,reply_status,{user_id,screen_name},rt,fav});
            }
            return true;
        }
        bool Uint64(uint64_t i) {
            if (values & key_id && !(values & found_id)) {    // id
                id = i;
                values &= ~(key_id);
                values |= (found_id);
            }
            else if (values & key_reply && !(values & found_reply)) {   // in_reply_status_id
                reply_status = i;
                values &= ~(key_reply);
                values |= (found_reply);
            }
            return true;
        }
        bool String(const char* str, SizeType length, bool copy) {
            if (values & key_date && !(values & found_date)) {   //  created_at
                date = {str,length};
                values &= ~(key_date);
                values |= (found_date);
            }
            else if (values & key_text && !(values & found_text)) {   // text
                text = {str,length};
                values &= ~(key_text);
                values |= (found_text);
            }
            else if (values & key_screenname && !(values & found_screenname)) {    // user.screen_name
                screen_name = {str,length};
                userobject_screen_name = false;
                values &= ~(key_screenname);
                values |= (found_screenname);
            }
            return true;
        }
        bool Null() {
            if (values & key_reply && !(values & found_reply)) {    // in_reply_status (null case)
                reply_status = 0;
                values &= ~(key_reply);
                values |= (found_reply);
            }
            return true;
        }
        // Irrelevant events
        bool Bool(bool b) { return true; }
        bool Double(double d) { return true; }
        bool Int(int i) { return true; }
        bool Int64(int64_t i) { return true; }
        bool RawNumber(const char* str, SizeType length, bool copy) { return true; }
        bool StartObject() { return true; }
        bool EndObject(SizeType memberCount) { return true; }
        bool StartArray() { return true; }
        bool EndArray(SizeType elementCount) { return true; }
    }; // handler

    bool run(simdjson::padded_string &json, std::vector<tweet<std::string_view>> &result) {
        Reader reader;
        Handler handler(result);
        InsituStringStream ss(json.data());
        reader.Parse<kParseInsituFlag | kParseValidateEncodingFlag | kParseFullPrecisionFlag>(ss,handler);
        return true;
    }

}; // rapid_jason_sax
BENCHMARK_TEMPLATE(partial_tweets, rapidjson_sax)->UseManualTime();
} // namespace partial_tweets

#endif // SIMDJSON_COMPETITION_RAPIDJSON


text:
package com.example.ward.view;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.example.ward.R;

public class RefreshListView extends ListView {

    public static final int NORMAL = 0;
    public static final int PULL = 1;
    public static final int RELEASE = 2;
    public static final int REFRESHING = 3;

    private int state = PULL; //用于记录当前状态
    private int preState;//用于记录之前一次的状态

    private View mHeader;
    private ProgressBar mHeaderBar;
    private ImageView mHeaderArrow;
    private TextView mHeaderText;
    private TextView mHeaderDate;

    private Drawable mPullDraw;
    private Drawable mReleaseDraw;

    private Context mContext;
    private LayoutInflater mInflater;
    private OnRefreshListener mRefreshListener;

    private float mDownY;
    private float mMoveY;

    private SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public RefreshListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialize(context);
    }

    private void initialize(Context context) {
        mContext = context;
        mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        mHeader = mInflater.inflate(R.layout.refresh_lv_header, null);
        mHeaderBar = (ProgressBar) mHeader.findViewById(R.id.header_bar);
        mHeaderArrow = (ImageView) mHeader.findViewById(R.id.arrow);
        mHeaderText = (TextView) mHeader.findViewById(R.id.text);
        mHeaderDate = (TextView) mHeader.findViewById(R.id.date);

        mPullDraw = getResources().getDrawable(R.drawable.pull_refresh);
        mReleaseDraw = getResources().getDrawable(R.drawable.realease_refresh);

        //创建布局参数传递给对应的view
        ListView.LayoutParams params = new ListView.LayoutParams(ListView.LayoutParams.MATCH_PARENT, 100);
        mHeader.setLayoutParams(params);

        addHeaderView(mHeader);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mDownY = ev.getY();
                mHeaderDate.setText(mDateFormat.format(new Date()));
                break;
            case MotionEvent.ACTION_MOVE:
                mMoveY = ev.getY();
                if (state != REFRESHING) {
                    int instance = (int) ((mMoveY - mDownY) / 3);
                    if (getFirstVisiblePosition() > 0) {
                        mDownY = mMoveY;
                        state = NORMAL;
                        break;
                    }
                    if (instance < 0) break;
                    setPadding(0, -mHeader.getLayoutParams().height + instance, 0, 0);
                    if (state != NORMAL)
                        setSelection(0); //这一步相当重要 当数据的高度大于屏幕时 向上拉动时 lisview的滚动速度比setpadding要快 所以必须设置这一句使listview始终在第一行
                    if (instance > 100) {
                        state = RELEASE;
                        mHeaderText.setText("松手即可刷新");
                        mHeaderArrow.setImageDrawable(mReleaseDraw);
                    } else if ((state == NORMAL || state == RELEASE)) {
                        preState = state;
                        state = PULL;
                        if (preState == NORMAL && state == PULL && instance >= 18) mDownY = mMoveY;
                        else if (preState != RELEASE && instance < 20) state = NORMAL;
                        mHeaderText.setText("向下拖动刷新");
                        mHeaderArrow.setImageDrawable(mPullDraw);
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
                if (state == RELEASE) {
                    if (mRefreshListener != null) mRefreshListener.onRefresh();
                    else {
                        setPadding(0, -mHeader.getLayoutParams().height, 0, 0);
                        state = PULL;
                    }
                }
                if (state == PULL) setPadding(0, -mHeader.getLayoutParams().height, 0, 0);
                if (mMoveY == mDownY) state = NORMAL;
            default:
                break;
        }
        return super.onTouchEvent(ev);
    }

    @Override
    public void setAdapter(ListAdapter adapter) {
        super.setAdapter(adapter);
        setPadding(0, -mHeader.getLayoutParams().height, 0, 0);
    }

    public interface OnRefreshListener {
        public void onRefresh();
    }

    public void setOnRefreshListener(OnRefreshListener listener) {
        this.mRefreshListener = listener;
    }

    //使用改工具类时  开启线程进行耗时操作前必须调用该方法
    public void onPrepareRefresh() {
        setPadding(0, 0, 0, 0);
        state = REFRESHING;
        mHeaderArrow.setImageDrawable(mPullDraw);
        mHeaderText.setText("载入中......");
        mHeaderArrow.setVisibility(View.INVISIBLE);
        mHeaderBar.setVisibility(View.VISIBLE);
    }

    //使用改工具类时  开启线程进行耗时操作后必须调用该方法
    public void onCompleteRefresh() {
        setPadding(0, -mHeader.getLayoutParams().height, 0, 0);
        state = PULL;
        mHeaderText.setText("向下拖动刷新");
        mHeaderArrow.setVisibility(View.VISIBLE);
        mHeaderBar.setVisibility(View.INVISIBLE);
    }
}


text:
package me.tassoevan.cordova;

import android.content.Context;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.PluginResult;

public class CallStateListener extends PhoneStateListener {

    private static final String PHONE_STATE_IDLE = "idle";
    private static final String PHONE_STATE_OFFHOOK = "offhook";
    private static final String PHONE_STATE_RINGING = "ringing";
    private static final String PHONE_STATE_UNKNOWN = "unknown";

    public CallbackContext callbackContext;

    public void onCallStateChanged(int state, String incomingNumber) {
        super.onCallStateChanged(state, incomingNumber);

        if (this.callbackContext == null) {
            return;
        }

        String msg;

        switch (state) {
            case TelephonyManager.CALL_STATE_IDLE:
                msg = PHONE_STATE_IDLE;
                break;

            case TelephonyManager.CALL_STATE_OFFHOOK:
                msg = PHONE_STATE_OFFHOOK;
                break;

            case TelephonyManager.CALL_STATE_RINGING:
                msg = PHONE_STATE_RINGING;
                break;

            default:
                msg = PHONE_STATE_UNKNOWN;
        }

        PluginResult result = new PluginResult(PluginResult.Status.OK, msg);
        result.setKeepCallback(true);

        callbackContext.sendPluginResult(result);
    }
}