text:
package com.crawljax.plugins.testilizer.casestudies.wolfcms.instrumentedtests;

import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class TestEnableAndUninstallPlugin {

    private WebDriver driver;

    private String baseUrl;

    private boolean acceptNextAlert = true;

    private StringBuffer verificationErrors = new StringBuffer();

    @Before
    public void setUp() throws Exception {
        driver = new FirefoxDriver();
        baseUrl = "http://localhost/";
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    }

    @Test
    public void testEnableAndUninstallPlugin() throws Exception {
        driver.get("http://localhost:8888/wolfcms/?/admin");
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.assertionModeOn();
        assertEquals("Login - Wolf CMS", driver.getTitle());
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.getAssertion("assertEquals(\"Login - Wolf CMS\", driver.getTitle())");
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.assertionModeOff();
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.getWebElement(driver.findElement(com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.getBy(By.id("login-username"))), "clear", "").clear();
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.getWebElement(driver.findElement(com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.getBy(By.id("login-username"))), "sendKeys", "admin").sendKeys("admin");
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.getWebElement(driver.findElement(com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.getBy(By.id("login-password"))), "clear", "").clear();
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.getWebElement(driver.findElement(com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.getBy(By.id("login-password"))), "sendKeys", "admin").sendKeys("admin");
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.getWebElement(driver.findElement(com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.getBy(By.xpath("//input[@value='Login']"))), "click", "").click();
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.getWebElement(driver.findElement(com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.getBy(By.linkText("Administration"))), "click", "").click();
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.assertionModeOn();
        assertEquals("Settings | Wolf CMS", driver.getTitle());
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.getAssertion("assertEquals(\"Settings | Wolf CMS\", driver.getTitle())");
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.assertionModeOff();
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.assertionModeOn();
        assertEquals("Settings | Wolf CMS", driver.getTitle());
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.getAssertion("assertEquals(\"Settings | Wolf CMS\", driver.getTitle())");
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.assertionModeOff();
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.assertionModeOn();
        assertEquals("Settings | Wolf CMS", driver.getTitle());
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.getAssertion("assertEquals(\"Settings | Wolf CMS\", driver.getTitle())");
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.assertionModeOff();
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.getWebElement(driver.findElement(com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.getBy(By.xpath("//div[@id='plugins']/table/tbody/tr/td/input[@value='backup_restore']"))), "click", "").click();
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.assertionModeOn();
        assertEquals("Settings | Wolf CMS", driver.getTitle());
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.getAssertion("assertEquals(\"Settings | Wolf CMS\", driver.getTitle())");
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.assertionModeOff();
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.assertionModeOn();
        assertEquals("Settings | Wolf CMS", driver.getTitle());
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.getAssertion("assertEquals(\"Settings | Wolf CMS\", driver.getTitle())");
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.assertionModeOff();
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.assertionModeOn();
        assertEquals("Settings | Wolf CMS", driver.getTitle());
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.getAssertion("assertEquals(\"Settings | Wolf CMS\", driver.getTitle())");
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.assertionModeOff();
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.assertionModeOn();
        assertTrue(isElementPresent(By.xpath("//li[@id='backup_restore-plugin']/a[text()='Backup Restore']")));
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.getAssertion("assertTrue(isElementPresent(By.xpath(\"//li[@id='backup_restore-plugin']/a[text()='Backup Restore']\")))");
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.assertionModeOff();
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.assertionModeOn();
        assertTrue(isElementPresent(By.xpath("//li[@id='backup_restore-plugin']/a[text()='Backup Restore']")));
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.getAssertion("assertTrue(isElementPresent(By.xpath(\"//li[@id='backup_restore-plugin']/a[text()='Backup Restore']\")))");
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.assertionModeOff();
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.getWebElement(driver.findElement(com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.getBy(By.xpath("//div[@id='plugins']/table/tbody/tr/td/a[@name='uninstall_backup_restore']"))), "click", "").click();
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.assertionModeOn();
        assertTrue(closeAlertAndGetItsText().matches("^Are you sure you wish to uninstall this plugin[\\s\\S]$"));
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.getAssertion("assertTrue(closeAlertAndGetItsText().matches(\"^Are you sure you wish to uninstall this plugin[\\\\s\\\\S]$\"))");
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.assertionModeOff();
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.assertionModeOn();
        assertEquals("Settings | Wolf CMS", driver.getTitle());
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.getAssertion("assertEquals(\"Settings | Wolf CMS\", driver.getTitle())");
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.assertionModeOff();
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.assertionModeOn();
        assertEquals("Settings | Wolf CMS", driver.getTitle());
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.getAssertion("assertEquals(\"Settings | Wolf CMS\", driver.getTitle())");
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.assertionModeOff();
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.assertionModeOn();
        assertEquals("Settings | Wolf CMS", driver.getTitle());
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.getAssertion("assertEquals(\"Settings | Wolf CMS\", driver.getTitle())");
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.assertionModeOff();
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.assertionModeOn();
        assertTrue(isElementPresent(By.xpath("//li[@id='backup_restore-plugin']/a[text()='Backup Restore']")));
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.getAssertion("assertTrue(isElementPresent(By.xpath(\"//li[@id='backup_restore-plugin']/a[text()='Backup Restore']\")))");
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.assertionModeOff();
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.assertionModeOn();
        assertTrue(isElementPresent(By.xpath("//li[@id='backup_restore-plugin']/a[text()='Backup Restore']")));
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.getAssertion("assertTrue(isElementPresent(By.xpath(\"//li[@id='backup_restore-plugin']/a[text()='Backup Restore']\")))");
        com.crawljax.plugins.testilizer.seleniuminstrumentor.SeleniumInstrumentor.assertionModeOff();
    }

    @After
    public void tearDown() throws Exception {
        driver.quit();
        String verificationErrorString = verificationErrors.toString();
        if (!"".equals(verificationErrorString)) {
            fail(verificationErrorString);
        }
    }

    private boolean isElementPresent(By by) {
        try {
            driver.findElement(by);
            return true;
        } catch (NoSuchElementException e) {
            return false;
        }
    }

    private boolean isAlertPresent() {
        try {
            driver.switchTo().alert();
            return true;
        } catch (NoAlertPresentException e) {
            return false;
        }
    }

    private String closeAlertAndGetItsText() {
        try {
            Alert alert = driver.switchTo().alert();
            String alertText = alert.getText();
            if (acceptNextAlert) {
                alert.accept();
            } else {
                alert.dismiss();
            }
            return alertText;
        } finally {
            acceptNextAlert = true;
        }
    }
}


text:
<resources>
    <string name="app_name">AndroidFilePreferences</string>
</resources>

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;

using NSubstitute;

using NUnit.Framework;

using Tauco.Dicom.Network;
using Tauco.Dicom.Shared;
using Tauco.Tests;
using Tauco.Tests.Fakes;

namespace Tauco.Dicom.Tests.Network
{
    [TestFixture]
    [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")]
    public class DicomRequestFactoryTests
    {
        [Test]
        public void Constructor_ArgumentsCombinations()
        {
            var mockProvider = new MockProvider();
            TestUtilities.TestConstructorArgumentsNullCombinations(typeof(DicomRequestFactory), null, new List<Func<object>>
            {
                mockProvider.GetSettingsProviderFake
            });
        }

        [Test]
        public void CreateDicomFindRequest_NullWhereCollection_ThrowsException()
        {
            // Arrange
            var mockProvider = new MockProvider();
            var dicomRequestFactory = new DicomRequestFactory(mockProvider.GetSettingsProviderFake());

            // Act + Assert
            Assert.That(() => dicomRequestFactory.CreateDicomFindRequest<TestInfo>(null, item =>{}), Throws.TypeOf<ArgumentNullException>());
        }

        [Test]
        public void CreateDicomFindRequest_NullResponseCallback_ThrowsException()
        {
            // Arrange
            var mockProvider = new MockProvider();
            var dicomRequestFactory = new DicomRequestFactory(mockProvider.GetSettingsProviderFake());

            // Act + Assert
            Assert.That(() => dicomRequestFactory.CreateDicomFindRequest<TestInfo>(mockProvider.GetDicomWhereCollectionFake(), null), Throws.TypeOf<ArgumentNullException>());
        }

        [Test]
        public void CreateDicomFindRequest_CorrectRequestIsCreated()
        {
            // Arrange
            var mockProvider = new MockProvider();
            var dicomRequestFactory = new DicomRequestFactory(mockProvider.GetSettingsProviderFake());

            var dicomWhereCollection = mockProvider.GetDicomWhereCollectionFake();
            Action<TestInfo> responseCallback = item => {};

            // Act
            var request = dicomRequestFactory.CreateDicomFindRequest(dicomWhereCollection, responseCallback);

            // Assert
            Assert.That(request.ResponseCallback, Is.SameAs(responseCallback));
            Assert.That(request.DicomWhereCollection, Is.SameAs(dicomWhereCollection));
        }

        [Test]
        public void CreateDicomMoveRequest_NullInfoIdentifier_ThrowsException()
        {
            // Arrange
            var mockProvider = new MockProvider();
            var dicomRequestFactory = new DicomRequestFactory(mockProvider.GetSettingsProviderFake());

            // Act + Assert
            Assert.That(() => dicomRequestFactory.CreateDicomMoveRequest(null), Throws.TypeOf<ArgumentNullException>());
        }

        [Test]
        public void CreateDicomMoveRequest_CorrectRequestIsCreated()
        {
            // Arrange
            var mockProvider = new MockProvider();
            var settingsProvider = mockProvider.GetSettingsProviderFake();
            settingsProvider.DestinationApplicationEntity.Returns("DestinationAE");
            var identifier = new InfoIdentifier("identifier");

            var dicomRequestFactory = new DicomRequestFactory(settingsProvider);

            // Act
            var request = dicomRequestFactory.CreateDicomMoveRequest(identifier);

            // Assert
            Assert.That(request.DestinationAE, Is.EqualTo("DestinationAE"));
            Assert.That(request.Identifier, Is.SameAs(identifier));
        }
    }
}


text:
#import "UAApplicationMetrics+Internal.h"
#import "UAPreferenceDataStore.h"

@interface UAApplicationMetrics()
@property (nonatomic, strong) UAPreferenceDataStore *dataStore;
@end

@implementation UAApplicationMetrics
NSString *const UAApplicationMetricLastOpenDate = @"UAApplicationMetricLastOpenDate";

- (instancetype)initWithDataStore:(UAPreferenceDataStore *)dataStore {
    self = [super init];
    if (self) {
        // App inactive/active for incoming calls, notification center, and taskbar
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(didBecomeActive)
                                                     name:UIApplicationDidBecomeActiveNotification
                                                   object:nil];
    }

    return self;
}

+ (instancetype)applicationMetricsWithDataStore:(UAPreferenceDataStore *)dataStore {
    UAApplicationMetrics *metrics = [[UAApplicationMetrics alloc] init];
    metrics.dataStore = dataStore;

    [metrics.dataStore migrateUnprefixedKeys:@[UAApplicationMetricLastOpenDate]];

    return metrics;
}

- (void)didBecomeActive {
    self.lastApplicationOpenDate = [NSDate date];
}

- (NSDate *)lastApplicationOpenDate {
    return [self.dataStore objectForKey:UAApplicationMetricLastOpenDate];
}

- (void)setLastApplicationOpenDate:(NSDate *)date {
    [self.dataStore setObject:date forKey:UAApplicationMetricLastOpenDate];
}

@end


text:
import os
from sample import create_app, db, rdb
from sample.models import User, Client, Student
from flask_script import Manager, Shell
from flask_migrate import Migrate, MigrateCommand

app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
migrate = Migrate(app, db)

def make_shell_context():
    return dict(app=app, db=db, User=User, Client=Client, Student=Student, rdb=rdb)

manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)

if __name__ == '__main__':
    manager.run()


text:
using Documenter, Lasso, MLBase

makedocs(
    modules = [Lasso],
    format = Documenter.HTML(
        # Use clean URLs, unless built as a "local" build
        prettyurls = !("local" in ARGS),
        canonical = "https://juliastats.github.io/Lasso.jl/stable/",
    ),
    clean = false,
    sitename = "Lasso.jl",
    authors = "Simon Kornblith, Asaf Manela, and contributors.",
    linkcheck = !("skiplinks" in ARGS),
    pages = [
        "Home" => "index.md",
        "Lasso paths" => "lasso.md",
        "Fused Lasso and trend filtering" => "smoothing.md",
        "Index" => "api.md",
    ],
    )

deploydocs(
    repo = "github.com/JuliaStats/Lasso.jl.git",
    target = "build",
)


text:
package gw.plugin.ij.lang.psi.stubs.elements;

import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.stubs.IndexSink;
import com.intellij.psi.stubs.StubElement;
import com.intellij.psi.stubs.StubInputStream;
import com.intellij.psi.stubs.StubOutputStream;
import com.intellij.util.ArrayUtil;
import com.intellij.util.io.StringRef;
import gw.lang.parser.expressions.INameInDeclaration;
import gw.plugin.ij.lang.parser.GosuCompositeElement;
import gw.plugin.ij.lang.parser.GosuElementTypes;
import gw.plugin.ij.lang.psi.GosuStubElementType;
import gw.plugin.ij.lang.psi.api.statements.IGosuFieldProperty;
import gw.plugin.ij.lang.psi.impl.statements.GosuFieldPropertyImpl;
import gw.plugin.ij.lang.psi.stubs.GosuFieldPropertyStub;
import gw.plugin.ij.lang.psi.stubs.GosuStubUtils;
import gw.plugin.ij.lang.psi.stubs.impl.GosuFieldPropertyStubImpl;
import gw.plugin.ij.lang.psi.stubs.index.GosuAnnotatedMemberIndex;
import gw.plugin.ij.lang.psi.stubs.index.GosuFieldNameIndex;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;

public class GosuFieldPropertyElementType extends GosuStubElementType<GosuFieldPropertyStub, IGosuFieldProperty> {
  public GosuFieldPropertyElementType() {
    super("fieldProperty", INameInDeclaration.class);
  }

  @NotNull
  public PsiElement createElement(ASTNode node) {
    return new GosuFieldPropertyImpl((GosuCompositeElement) node);
  }

  @NotNull
  public IGosuFieldProperty createPsi(@NotNull GosuFieldPropertyStub stub) {
    return new GosuFieldPropertyImpl(stub);
  }

  @NotNull
  public GosuFieldPropertyStub createStub(@NotNull IGosuFieldProperty psi, StubElement parentStub) {
    String[] annNames = GosuTypeDefinitionElementType.getAnnotationNames(psi);

    String[] namedParametersArray = ArrayUtil.EMPTY_STRING_ARRAY;

    return new GosuFieldPropertyStubImpl(parentStub, StringRef.fromString(psi.getName()), annNames, namedParametersArray, psi.getElementType(), GosuFieldPropertyStubImpl.buildFlags( psi ));
  }

  public void serialize(@NotNull GosuFieldPropertyStub stub, @NotNull StubOutputStream dataStream) throws IOException {
    serializeFieldStub(stub, dataStream);
  }

  @NotNull
  public GosuFieldPropertyStub deserialize(@NotNull StubInputStream dataStream, StubElement parentStub) throws IOException {
    return deserializeFieldStub(dataStream, parentStub);
  }

  public void indexStub(@NotNull GosuFieldPropertyStub stub, @NotNull IndexSink sink) {
    indexFieldStub(stub, sink);
  }

  /*
   * ****************************************************************************************************************
   */

  static void serializeFieldStub(@NotNull GosuFieldPropertyStub stub, @NotNull StubOutputStream dataStream) throws IOException {
    dataStream.writeName(stub.getName());
    final String[] annotations = stub.getAnnotations();
    dataStream.writeByte(annotations.length);
    for (String s : annotations) {
      dataStream.writeName(s);
    }

    final String[] namedParameters = stub.getNamedParameters();
    GosuStubUtils.writeStringArray(dataStream, namedParameters);

    dataStream.writeByte(stub.getFlags());
  }

  @NotNull
  static GosuFieldPropertyStub deserializeFieldStub(@NotNull StubInputStream dataStream, StubElement parentStub) throws IOException {
    StringRef ref = dataStream.readName();
    final byte b = dataStream.readByte();
    final String[] annNames = new String[b];
    for (int i = 0; i < b; i++) {
      annNames[i] = dataStream.readName().toString();
    }

    final String[] namedParameters = GosuStubUtils.readStringArray(dataStream);
    byte flags = dataStream.readByte();
    return new GosuFieldPropertyStubImpl(parentStub, ref, annNames, namedParameters, GosuElementTypes.FIELD_PROPERTY, flags);
  }

  static void indexFieldStub(@NotNull GosuFieldPropertyStub stub, @NotNull IndexSink sink) {
    String name = stub.getName();
    if (name != null) {
      sink.occurrence(GosuFieldNameIndex.KEY, name);
    }
    for (String annName : stub.getAnnotations()) {
      if (annName != null) {
        sink.occurrence(GosuAnnotatedMemberIndex.KEY, annName);
      }
    }
  }
}


text:
@interface RACIndexSetSequence : RACSequence

+ (RACSequence *)sequenceWithIndexSet:(NSIndexSet *)indexSet;

@end


text:
package tech.wetech.cms.controller;

import javax.servlet.http.HttpSession;

import tech.wetech.cms.auth.AuthClass;
import tech.wetech.cms.auth.AuthMethod;
import tech.wetech.cms.web.CmsSessionContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@AuthClass("login")
public class AdminController {

	@RequestMapping("/admin")
	@AuthMethod
	public String main() {
		return "admin/main";
	}

	@AuthMethod
	@RequestMapping("/admin/logout")
	public String logout(HttpSession session) {
		CmsSessionContext.removeSession(session);
		session.invalidate();
		return "redirect:/login";
	}
}


text:
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orchard.FileSystem.AppData;
using Orchard.Parser;
using Orchard.Parser.Yaml;
using Orchard.Validation;
using System.Collections.Generic;
using System.IO;

namespace Orchard.Environment.Shell
{
    public class ShellSettingsManager : IShellSettingsManager
    {
        private readonly IAppDataFolder _appDataFolder;
        //private readonly ICache _cache;
        private readonly IOptions<ShellOptions> _optionsAccessor;
        private readonly ILogger _logger;

        private const string SettingsFileNameFormat = "Settings.{0}";

        public ShellSettingsManager(IAppDataFolder appDataFolder,
            //ICache cache,
            IOptions<ShellOptions> optionsAccessor,
            ILogger<ShellSettingsManager> logger)
        {
            _appDataFolder = appDataFolder;
            //_cache = cache;
            _optionsAccessor = optionsAccessor;
            _logger = logger;
        }

        IEnumerable<ShellSettings> IShellSettingsManager.LoadSettings()
        {
            var shellSettings = new List<ShellSettings>();

            foreach (var tenant in _appDataFolder.ListDirectories(_optionsAccessor.Value.Location))
            {
                if (_logger.IsEnabled(LogLevel.Information))
                {
                    _logger.LogInformation("ShellSettings found in '{0}', attempting to load.", tenant.Name);
                }
                var configurationContainer =
                    new ConfigurationBuilder()
                        .SetBasePath(_appDataFolder.RootPath)
                        .AddJsonFile(_appDataFolder.Combine(tenant.FullName, string.Format(SettingsFileNameFormat, "json")),
                            true)
                        .AddXmlFile(_appDataFolder.Combine(tenant.FullName, string.Format(SettingsFileNameFormat, "xml")),
                            true)
                        .AddYamlFile(_appDataFolder.Combine(tenant.FullName, string.Format(SettingsFileNameFormat, "txt")),
                            false);

                var config = configurationContainer.Build();
                var shellSetting = ShellSettingsSerializer.ParseSettings(config);
                shellSettings.Add(shellSetting);

                if (_logger.IsEnabled(LogLevel.Information))
                {
                    _logger.LogInformation("Loaded ShellSettings for tenant '{0}'", shellSetting.Name);
                }
            }

            return shellSettings;
        }

        void IShellSettingsManager.SaveSettings(ShellSettings shellSettings)
        {
            Argument.ThrowIfNull(shellSettings, nameof(shellSettings));
            Argument.ThrowIfNullOrWhiteSpace(shellSettings.Name,
                nameof(shellSettings.Name),
                "The Name property of the supplied ShellSettings object is null or empty; the settings cannot be saved.");

            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Saving ShellSettings for tenant '{0}'", shellSettings.Name);
            }
            var tenantPath = _appDataFolder.MapPath(
                _appDataFolder.Combine(
                    _optionsAccessor.Value.Location,
                    shellSettings.Name,
                    string.Format(SettingsFileNameFormat, "txt")));

            var configurationProvider = new YamlConfigurationProvider(new YamlConfigurationSource
            {
                Path = tenantPath,
                Optional = false
            });

            foreach (var key in shellSettings.Keys)
            {
                if (!string.IsNullOrEmpty(shellSettings[key]))
                {
                    configurationProvider.Set(key, shellSettings[key]);
                }
            }

            configurationProvider.Commit();

            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Saved ShellSettings for tenant '{0}'", shellSettings.Name);
            }
        }
    }
}


text:
/* Style rules for the Coyote toolbar dialog. */

@import "coyote-common.css";

#tabs-title {
  font-size: small;
}

#compare-button {
  height: 32px;
}

.text-align-center {
  text-align: center;
}

.tab-selection-list {
  margin-left: 8px;
  padding-left: 0px;
  float: left;
}

.tab-selection-list-item {
  cursor: pointer;
  list-style-type: none;
  border: 1px dashed #A6A6A6;
  border-radius: 2px;
  padding: 8px;
  margin-bottom: 8px;
  height: 48px;
  width: 162px;
}

.tab-selection-list-item:last-child {
  margin-bottom: 0px;
}

.tab-selection-icon {
  margin-right: 8px;
  height: 18px;
  width: 18px;
  float: left;
}

.tab-selection-item-content-container {
  position: relative;
  height: 48px;
  overflow: hidden;
}

.tab-selection-item-content {
  margin-left: 26px;
  overflow: hidden;
}

.tab-title {
  font-weight: bold;
}

.active-tab-selection {
  background-color: #80CCFF;
}

.display-index-badge {
  color: #0000CC;
  font-weight: bold;
  background-color: #FFFFFF;
  border-radius: 2px;
  text-align: center;
  height: 16px;
  width: 16px;
  position: absolute;
  top: 0px;
  right: 0px;
  z-index: 1;
}


text:
/**
 * fadein: Fade from fully transparent to fully opaque.
 */
@keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}
@-moz-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}
@-webkit-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/**
 * fadeout: Fade from fully opaque to fully transparent.
 */
@keyframes fadeout {
    from { opacity: 1; }
    to   { opacity: 0; }
}
@-moz-keyframes fadeout {
    from { opacity: 1; }
    to   { opacity: 0; }
}
@-webkit-keyframes fadeout {
    from { opacity: 1; }
    to   { opacity: 0; }
}

/**
 * popin: Increase in size and opacity from invisibly tiny and transparent to
 * full size and opaque.
 */
@keyframes popin {
    from { transform: scale(0); opacity: 0; }
    to   { transform: scale(1); }
}


text:
extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.viewcode',
    'sphinx.ext.napoleon',
    'sphinx_autodoc_typehints',
    'sphinx.ext.extlinks',
    'sphinx.ext.intersphinx',
]

templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = 'ib_insync'
copyright = '2022, Ewald de Wit'
author = 'Ewald de Wit'

__version__ = ''
exec(open('../ib_insync/version.py').read())
version = '.'.join(__version__.split('.')[:2])
release = __version__

language = 'en'
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
pygments_style = 'sphinx'
todo_include_todos = False
html_theme = 'sphinx_rtd_theme'
html_theme_options = {
    'canonical_url': 'https://ib_insync.readthedocs.io',
    'logo_only': False,
    'display_version': True,
    'prev_next_buttons_location': 'bottom',
    'style_external_links': False,
    # Toc options
    'collapse_navigation': True,
    'sticky_navigation': True,
    'navigation_depth': 4,
    'includehidden': True,
    'titles_only': False
}

intersphinx_mapping = {
    'python': ('https://docs.python.org/3', None),
    'eventkit': ('https://eventkit.readthedocs.io/en/latest', None),
}

github_url = 'https://github.com/erdewit/ib_insync'

extlinks = {
    'issue': ('https://github.com/erdewit/ib_insync/issues/%s', 'issue '),
    'pull': ('https://github.com/erdewit/ib_insync/pull/%s', 'pull '),
}

autoclass_content = 'both'
autodoc_member_order = "bysource"
autodoc_default_options = {
    'members': True,
    'undoc-members': True
}

def onDocstring(app, what, name, obj, options, lines):
    if not lines:
        return
    if lines[0].startswith('Alias for field number'):
        # strip useless namedtuple number fields
        del lines[:]

def setup(app):
    app.connect('autodoc-process-docstring', onDocstring),


text:
<?php

namespace Bit3\GitPhp\Command;

/**
 * Reset command builder.
 */
class ResetCommandBuilder implements CommandBuilderInterface
{
    use CommandBuilderTrait;

    /**
     * {@inheritDoc}
     */
    protected function initializeProcessBuilder()
    {
        $this->arguments[] = 'reset';
    }

    /**
     * Add the quiet option to the command line.
     *
     * @return ResetCommandBuilder
     */
    public function quiet()
    {
        $this->arguments[] = '--quiet';
        return $this;
    }

    /**
     * Add the patch option to the command line.
     *
     * @return ResetCommandBuilder
     */
    public function patch()
    {
        $this->arguments[] = '--patch';
        return $this;
    }

    /**
     * Add the soft option to the command line.
     *
     * @return ResetCommandBuilder
     */
    public function soft()
    {
        $this->arguments[] = '--soft';
        return $this;
    }

    /**
     * Add the mixed option to the command line.
     *
     * @return ResetCommandBuilder
     */
    public function mixed()
    {
        $this->arguments[] = '--mixed';
        return $this;
    }

    /**
     * Add the hard option to the command line.
     *
     * @return ResetCommandBuilder
     */
    public function hard()
    {
        $this->arguments[] = '--hard';
        return $this;
    }

    /**
     * Add the merge option to the command line.
     *
     * @return ResetCommandBuilder
     */
    public function merge()
    {
        $this->arguments[] = '--merge';
        return $this;
    }

    /**
     * Add the keep option to the command line.
     *
     * @return ResetCommandBuilder
     */
    public function keep()
    {
        $this->arguments[] = '--keep';
        return $this;
    }

    /**
     * Add the commit to the command line.
     *
     * @param string $commit A commit hash.
     *
     * @return ResetCommandBuilder
     */
    public function commit($commit)
    {
        $this->arguments[] = $commit;
        return $this;
    }

    /**
     * Build the command and execute it.
     *
     * @param null|string $path Path to reset.
     *
     * @param null|string $_    More optional pathes to reset.
     *
     * @return string
     *
     * @SuppressWarnings(PHPMD.ShortVariableName)
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     * @SuppressWarnings(PHPMD.CamelCaseParameterName)
     */
    public function execute($path = null, $_ = null)
    {
        $this->arguments[] = '--';
        foreach (\func_get_args() as $path) {
            $this->arguments[] = $path;
        }
        return $this->run();
    }
}


text:
pyddl module
============

.. automodule:: pyddl
    :members:
    :undoc-members:
    :show-inheritance:


text:
<site-sections>

    <title lowercase="menus" handle="menus">Menus</title>
    <type lowercase="menu" handle="menu">Menu</type>
    <form method="post" action="" enctype="multipart/form-data">
      <input name="MAX_FILE_SIZE" type="hidden" value="5242880" />
      Title
        <input name="fields[title]" type="text" />

      Description
        <textarea name="fields[description]" rows="15" cols="50"></textarea>

      Deleted
        <input name="fields[deleted]" type="checkbox" />

      <input name="action[publish-menu]" type="submit" value="Submit" />
    </form>

    <title lowercase="sections" handle="sections">Sections</title>
    <type lowercase="section" handle="section">Section</type>
    <form method="post" action="" enctype="multipart/form-data">
      <input name="MAX_FILE_SIZE" type="hidden" value="5242880" />
      Title
        <input name="fields[title]" type="text" />

      Menu
        <select name="fields[menu]" class="section-link"/>

      URL
        <input name="fields[url]" type="text" />

      Sort
        <input name="fields[sort]" type="text" />

      Heading
        <input name="fields[heading]" type="text" />

      Description
        <textarea name="fields[description]" rows="8" cols="50"></textarea>

      Body
        <textarea name="fields[body]" rows="16" cols="50"></textarea>

      Deleted
        <input name="fields[deleted]" type="checkbox" />

      <input name="action[publish-section]" type="submit" value="Submit" />
    </form>

    <title lowercase="pages" handle="pages">Pages</title>
    <type lowercase="page" handle="page">Page</type>
    <form method="post" action="" enctype="multipart/form-data">
      <input name="MAX_FILE_SIZE" type="hidden" value="5242880" />
      Title
        <input name="fields[title]" type="text" />

      Section
        <select name="fields[section]" class="section-link"/>

      URL
        <input name="fields[url]" type="text" />

      Sort
        <input name="fields[sort]" type="text" />

      Heading
        <input name="fields[heading]" type="text" />

      Description
        <textarea name="fields[description]" rows="8" cols="50"></textarea>

      Body
        <textarea name="fields[body]" rows="16" cols="50"></textarea>

      Deleted
        <input name="fields[deleted]" type="checkbox" />

      <input name="action[publish-page]" type="submit" value="Submit" />
    </form>

</site-sections>


text:
namespace parquet {

class ColumnReader;
class FileMetaData;
class PageReader;
class RowGroupMetaData;

class PARQUET_EXPORT RowGroupReader {
 public:
  // Forward declare a virtual class 'Contents' to aid dependency injection and more
  // easily create test fixtures
  // An implementation of the Contents class is defined in the .cc file
  struct Contents {
    virtual ~Contents() {}
    virtual std::unique_ptr<PageReader> GetColumnPageReader(int i) = 0;
    virtual const RowGroupMetaData* metadata() const = 0;
    virtual const ReaderProperties* properties() const = 0;
  };

  explicit RowGroupReader(std::unique_ptr<Contents> contents);

  // Returns the rowgroup metadata
  const RowGroupMetaData* metadata() const;

  // Construct a ColumnReader for the indicated row group-relative
  // column. Ownership is shared with the RowGroupReader.
  std::shared_ptr<ColumnReader> Column(int i);

  // Construct a ColumnReader, trying to enable exposed encoding.
  //
  // For dictionary encoding, currently we only support column chunks that are fully
  // dictionary encoded, i.e., all data pages in the column chunk are dictionary encoded.
  // If a column chunk uses dictionary encoding but then falls back to plain encoding, the
  // encoding will not be exposed.
  //
  // The returned column reader provides an API GetExposedEncoding() for the
  // users to check the exposed encoding and determine how to read the batches.
  //
  // \note API EXPERIMENTAL
  std::shared_ptr<ColumnReader> ColumnWithExposeEncoding(
      int i, ExposedEncoding encoding_to_expose);

  std::unique_ptr<PageReader> GetColumnPageReader(int i);

 private:
  // Holds a pointer to an instance of Contents implementation
  std::unique_ptr<Contents> contents_;
};

class PARQUET_EXPORT ParquetFileReader {
 public:
  // Declare a virtual class 'Contents' to aid dependency injection and more
  // easily create test fixtures
  // An implementation of the Contents class is defined in the .cc file
  struct PARQUET_EXPORT Contents {
    static std::unique_ptr<Contents> Open(
        std::shared_ptr<::arrow::io::RandomAccessFile> source,
        const ReaderProperties& props = default_reader_properties(),
        std::shared_ptr<FileMetaData> metadata = NULLPTR);

    static ::arrow::Future<std::unique_ptr<Contents>> OpenAsync(
        std::shared_ptr<::arrow::io::RandomAccessFile> source,
        const ReaderProperties& props = default_reader_properties(),
        std::shared_ptr<FileMetaData> metadata = NULLPTR);

    virtual ~Contents() = default;
    // Perform any cleanup associated with the file contents
    virtual void Close() = 0;
    virtual std::shared_ptr<RowGroupReader> GetRowGroup(int i) = 0;
    virtual std::shared_ptr<FileMetaData> metadata() const = 0;
  };

  ParquetFileReader();
  ~ParquetFileReader();

  // Create a file reader instance from an Arrow file object. Thread-safety is
  // the responsibility of the file implementation
  static std::unique_ptr<ParquetFileReader> Open(
      std::shared_ptr<::arrow::io::RandomAccessFile> source,
      const ReaderProperties& props = default_reader_properties(),
      std::shared_ptr<FileMetaData> metadata = NULLPTR);

  // API Convenience to open a serialized Parquet file on disk, using Arrow IO
  // interfaces.
  static std::unique_ptr<ParquetFileReader> OpenFile(
      const std::string& path, bool memory_map = true,
      const ReaderProperties& props = default_reader_properties(),
      std::shared_ptr<FileMetaData> metadata = NULLPTR);

  // Asynchronously open a file reader from an Arrow file object.
  // Does not throw - all errors are reported through the Future.
  static ::arrow::Future<std::unique_ptr<ParquetFileReader>> OpenAsync(
      std::shared_ptr<::arrow::io::RandomAccessFile> source,
      const ReaderProperties& props = default_reader_properties(),
      std::shared_ptr<FileMetaData> metadata = NULLPTR);

  void Open(std::unique_ptr<Contents> contents);
  void Close();

  // The RowGroupReader is owned by the FileReader
  std::shared_ptr<RowGroupReader> RowGroup(int i);

  // Returns the file metadata. Only one instance is ever created
  std::shared_ptr<FileMetaData> metadata() const;

  /// Pre-buffer the specified column indices in all row groups.
  ///
  /// Readers can optionally call this to cache the necessary slices
  /// of the file in-memory before deserialization. Arrow readers can
  /// automatically do this via an option. This is intended to
  /// increase performance when reading from high-latency filesystems
  /// (e.g. Amazon S3).
  ///
  /// After calling this, creating readers for row groups/column
  /// indices that were not buffered may fail. Creating multiple
  /// readers for the a subset of the buffered regions is
  /// acceptable. This may be called again to buffer a different set
  /// of row groups/columns.
  ///
  /// If memory usage is a concern, note that data will remain
  /// buffered in memory until either \a PreBuffer() is called again,
  /// or the reader itself is destructed. Reading - and buffering -
  /// only one row group at a time may be useful.
  ///
  /// This method may throw.
  void PreBuffer(const std::vector<int>& row_groups,
                 const std::vector<int>& column_indices,
                 const ::arrow::io::IOContext& ctx,
                 const ::arrow::io::CacheOptions& options);

  /// Wait for the specified row groups and column indices to be pre-buffered.
  ///
  /// After the returned Future completes, reading the specified row
  /// groups/columns will not block.
  ///
  /// PreBuffer must be called first. This method does not throw.
  ::arrow::Future<> WhenBuffered(const std::vector<int>& row_groups,
                                 const std::vector<int>& column_indices) const;

 private:
  // Holds a pointer to an instance of Contents implementation
  std::unique_ptr<Contents> contents_;
};

// Read only Parquet file metadata
std::shared_ptr<FileMetaData> PARQUET_EXPORT
ReadMetaData(const std::shared_ptr<::arrow::io::RandomAccessFile>& source);

/// \brief Scan all values in file. Useful for performance testing
/// \param[in] columns the column numbers to scan. If empty scans all
/// \param[in] column_batch_size number of values to read at a time when scanning column
/// \param[in] reader a ParquetFileReader instance
/// \return number of semantic rows in file
PARQUET_EXPORT
int64_t ScanFileContents(std::vector<int> columns, const int32_t column_batch_size,
                         ParquetFileReader* reader);

}  // namespace parquet


text:
package foundation

import "C"

/*
* Provide interface for data encryption.
 */
type Encrypt interface {
	context

	/*
	 * Encrypt given data.
	 */
	Encrypt(data []byte) ([]byte, error)

	/*
	 * Calculate required buffer length to hold the encrypted data.
	 */
	EncryptedLen(dataLen uint) uint

	/*
	 * Precise length calculation of encrypted data.
	 */
	PreciseEncryptedLen(dataLen uint) uint

	/*
	 * Release underlying C context.
	 */
	Delete()
}


text:
package com.google.samples.apps.ourstreets.data;

import androidx.annotation.NonNull;
import android.util.Log;

import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;

import java.util.ArrayList;
import java.util.List;

/**
 * Base class for data presentation.
 *
 * @param <T> The data type which will be displayed.
 */
abstract class DataPresenter<T> {

    private static final String TAG = "DataPresenter";

    private final Firebase mFirebase;
    private final ValueEventListener mValueEventListener;
    private final List<T> mData;
    private final DataView<T> mDataView;

    /**
     * Creates a data presenter.
     *
     * @param dataView The view which will display the data.
     * @param configUrl The firebase endpoint url.
     */
    DataPresenter(@NonNull DataView<T> dataView, @NonNull String configUrl) {
        mFirebase = new Firebase(configUrl);
        mData = new ArrayList<>();
        mDataView = dataView;

        mValueEventListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                mData.clear();
                for (DataSnapshot data : dataSnapshot.getChildren()) {
                    // Data parsing is being done within the extending classes.
                    mData.add(parseData(data));
                }
                mDataView.showData(mData);
            }

            @Override
            public void onCancelled(FirebaseError firebaseError) {
                Log.d(TAG, "onCancelled: " + firebaseError.getMessage());
                // Deliberately swallow the firebase error here.
                mDataView.showError();
            }
        };
    }

    @NonNull
    protected abstract T parseData(DataSnapshot data);

    /**
     * Asynchronously gets data to display.
     * Once the data is available one of {@link DataView}'s methods will be invoked.
     */
    public final void getData() {
        mFirebase.removeEventListener(mValueEventListener);
        mFirebase.addValueEventListener(mValueEventListener);
    }

}


text:
/* Desc: Bullet motion state class.
 * Author: Nate Koenig
 * Date: 25 May 2009
 */

#ifndef __BULLETMOTIONSTATE_HH__
#define __BULLETMOTIONSTATE_HH__

#include "physics/bullet/bullet_inc.h"
#include "math/MathTypes.hh"
#include "physics/PhysicsTypes.hh"
#include "math/Pose.hh"

namespace gazebo
{
  namespace physics
  {
    class Link;

    class BulletMotionState : public btMotionState
    {
      /// \brief Constructor
      public: BulletMotionState(Link *_link);

      /// \brief Constructor
      // public: BulletMotionState(const math::Pose &initPose);

      /// \brief Destructor
      public: virtual ~BulletMotionState();

      /// \brief Get the pose
      public: math::Pose GetWorldPose() const;

      /// \brief Set the position of the body
      /// \param pos math::Vector position
      public: virtual void SetWorldPosition(const math::Vector3 &_pos);

      /// \brief Set the rotation of the body
      /// \param rot Quaternion rotation
      public: virtual void SetWorldRotation(const math::Quaternion &_rot);

      /// \brief Set the pose
      public: void SetWorldPose(const math::Pose &_pose);

      /// \brief Set the center of mass offset
      public: void SetCoG(const math::Vector3 &_cog);

      /// \brief Get the world transform
      public: virtual void getWorldTransform(btTransform &_worldTrans) const;

      /// \brief Set the world transform
      public: virtual void setWorldTransform(const btTransform &_worldTrans);

      private: math::Pose worldPose;
      private: math::Vector3 cog;
      private: Link *link;
    };
  }
}
#endif


text:
package gov.va.isaac.classifier;

import gov.vha.isaac.ochre.collections.NidSet;

import org.ihtsdo.otf.tcc.api.concept.ConceptFetcherBI;
import org.ihtsdo.otf.tcc.api.concept.ProcessUnfetchedConceptDataBI;

/**
 * SnomedClassifier.
 */
public class SnomedClassifier implements ProcessUnfetchedConceptDataBI {

  @Override
  public boolean continueWork() {
    // TODO Auto-generated method stub
    return false;
  }

  @Override
  public boolean allowCancel() {
    // TODO Auto-generated method stub
    return false;
  }

  @Override
  public NidSet getNidSet() {
    // TODO Auto-generated method stub
    return null;
  }

  @Override
  public String getTitle() {
    // TODO Auto-generated method stub
    return null;
  }

  @Override
  public void processUnfetchedConceptData(int arg0, ConceptFetcherBI arg1)
    throws Exception {
    // TODO Auto-generated method stub

  }
  /**
   * For later private static final Logger LOG = LoggerFactory
   * .getLogger(SnomedClassifier.class);
   *
   * private static String ROLE_GROUP = "19657985-279a-4713-83be-e3d1a884b50d";
   *
   * private static UUID CONCEPT_ATTRIBUTE =
   * UUID.fromString("6155818b-09ed-388e-82ce-caa143423e99");
   *
   * private static TerminologyStoreDI dataStore = ExtendedAppContext
   * .getDataStore();
   *
   * private Map<String, Concept> concepts = new HashMap<String, Concept>();
   *
   * private Map<String, Role> roles = new HashMap<String, Role>();
   *
   * private Set<Axiom> axioms = new HashSet<Axiom>();
   *
   * private int count = 0;
   *
   * private int pathNid;
   *
   * protected Logger getLogger() { return LOG; }
   *
   * public SnomedClassifier() { }
   *
   * public void classify(int pathNid) throws Exception { this.pathNid =
   * pathNid; getRole(ROLE_GROUP); LOG.info("Building axioms ");
   * dataStore.iterateConceptDataInSequence(this); LOG.info("Axioms " +
   * axioms.size()); addRoleAxioms(CONCEPT_ATTRIBUTE); LOG.info("Total Axioms "
   * + axioms.size()); IReasoner reasoner = new SnorocketReasoner();
   * reasoner.loadAxioms(axioms); long startTime = System.currentTimeMillis();
   * LOG.info("Running Classifier"); reasoner.classify();
   * LOG.info("Time to classify (ms): " + (System.currentTimeMillis() -
   * startTime)); Ontology ontology = reasoner.getClassifiedOntology();
   * Map<String,Set<String>> equivalentMap = new HashMap<String, Set<String>>();
   * for(String id : ontology.getNodeMap().keySet()) { Node node =
   * ontology.getNode(id); if(node.getEquivalentConcepts().size() == 1 &&
   * node.getEquivalentConcepts().contains(id)) { continue; }
   * equivalentMap.put(id, node.getEquivalentConcepts()); } for(String id :
   * equivalentMap.keySet()) { LOG.warn(id + " equivalents " +
   * equivalentMap.get(id)); } LOG.info("Inferred Axioms " +
   * ontology.getInferredAxioms().size()); for(Axiom axiom :
   * ontology.getInferredAxioms()) { LOG.info(axiom.toString()); } }
   *
   * private void addRoleAxioms(UUID parent) throws IOException,
   * ContradictionException { ArrayList<ConceptVersionBI> children =
   * OTFUtility.getAllChildrenOfConcept(OTFUtility.getConceptVersion(parent),
   * false); if(children.isEmpty()) return; Role[] rlhs = new
   * Role[children.size()]; int i=0; for(ConceptVersionBI child : children) {
   * addRoleAxioms(child.getPrimordialUuid()); rlhs[i++] =
   * getRole(child.getPrimordialUuid().toString()); }
   * axioms.add(Factory.createRoleInclusion(rlhs, getRole(parent.toString())));
   * }
   * @Override public boolean continueWork() { return true; }
   * @Override public boolean allowCancel() { return false; }
   * @Override public void processUnfetchedConceptData(int cNid,
   *           ConceptFetcherBI fetcher) throws Exception { ConceptVersionBI
   *           concept = fetcher.fetch(OTFUtility.getViewCoordinate()); if
   *           (concept.getPathNid() == pathNid) { count++;
   *           convertToOntologyObjects(concept); } }
   *
   *           private void convertToOntologyObjects(ConceptVersionBI concept)
   *           throws IOException, ContradictionException {
   *           ConceptAttributeVersionBI<?> attributes =
   *           ConceptViewerHelper.getConceptAttributes(concept); //
   *           Set<Integer> relGroups Collection<? extends
   *           RelationshipVersionBI<?>> relationships =
   *           concept.getRelationshipsOutgoingActive(); Map<Integer, Concept>
   *           mapRoleGroup = mapToRoleGroup(relationships); List<Concept>
   *           parentConcepts = getParentConcepts(relationships); // Root
   *           Concept ? if (parentConcepts.isEmpty()) return; if
   *           (mapRoleGroup.isEmpty() && parentConcepts.size() == 1) { //
   *           Single Parent and no role relationships
   *           axioms.add(Factory.createConceptInclusion(getConcept(concept
   *           .getPrimordialUuid().toString()), parentConcepts.get(0))); } else
   *           { List<Concept> definition = new ArrayList<Concept>();
   *           definition.addAll(parentConcepts);
   *           definition.addAll(mapRoleGroup.values());
   *           axioms.add(Factory.createConceptInclusion(getConcept(concept
   *           .getPrimordialUuid().toString()), Factory
   *           .createConjunction((definition.toArray(new Concept[0]))))); if
   *           (attributes.isDefined()) {
   *           axioms.add(Factory.createConceptInclusion(
   *           Factory.createConjunction(definition.toArray(new Concept[0])),
   *           getConcept(concept.getPrimordialUuid().toString()))); }
   *
   *           }
   *
   *           }
   *
   *           private List<Concept> getParentConcepts( Collection<? extends
   *           RelationshipVersionBI<?>> relationships) throws
   *           ValidationException, IOException { List<Concept> parentConcepts =
   *           new ArrayList<Concept>(); for (RelationshipVersionBI<?>
   *           relationship : relationships) { if (relationship.getTypeNid() ==
   *           Snomed.IS_A.getNid()) { parentConcepts.add(getConcept(OTFUtility
   *           .getConceptVersion(relationship.getDestinationNid())
   *           .getPrimordialUuid().toString())); } } return parentConcepts; }
   *
   *           private Map<Integer, Concept> mapToRoleGroup( Collection<?
   *           extends RelationshipVersionBI<?>> relationships) throws
   *           ValidationException, IOException { Map<Integer, List<Concept>>
   *           map = new HashMap<>(); Map<Concept, Integer> conceptToRoleNid =
   *           new HashMap<>(); // map roleGroup -> Concepts for
   *           (RelationshipVersionBI<?> relationship : relationships) { if
   *           (relationship.getGroup() == Snomed.IS_A.getNid()) continue;
   *
   *           List<Concept> concepts = new ArrayList<Concept>();
   *
   *           if (map.containsKey(relationship.getGroup())) concepts =
   *           map.get(relationship.getGroup()); else
   *           map.put(relationship.getGroup(), concepts);
   *
   *           Concept existentialConcept = Factory.createExistential(
   *           getRole(OTFUtility.getConceptVersion(relationship.getTypeNid())
   *           .getPrimordialUuid().toString()), getConcept(OTFUtility
   *           .getConceptVersion(relationship.getDestinationNid())
   *           .getPrimordialUuid().toString()));
   *           concepts.add(existentialConcept);
   *           conceptToRoleNid.put(existentialConcept,
   *           relationship.getTypeNid()); } // map roleGroup ->
   *           Conjunction/Concept Map<Integer, Concept> roles = new
   *           HashMap<Integer, Concept>(); for (Integer group : map.keySet()) {
   *           List<Concept> concepts = map.get(group); if (concepts.size() ==
   *           1) { if (group != 0) throw new
   *           IOException("Unexpected single grouped rel."); if
   *           (isNonGroupingRole(conceptToRoleNid.get(concepts.get(0)))) {
   *           roles.put(group, concepts.get(0)); } else { roles.put(group,
   *           Factory.createExistential(getRole(ROLE_GROUP), concepts.get(0)));
   *           } } else { if (group == 0) { for (Concept concept : concepts) {
   *           if (isNonGroupingRole(conceptToRoleNid.get(concept))) {
   *           roles.put(group, concept); } else { roles.put(group,
   *           Factory.createExistential(getRole(ROLE_GROUP),concept)); } } }
   *           else { roles.put(group,
   *           Factory.createExistential(getRole(ROLE_GROUP),
   *           Factory.createConjunction(concepts.toArray(new Concept[0])))); }
   *           } } return roles; }
   *
   *           private boolean isNonGroupingRole(int nid) throws
   *           ValidationException, IOException { // $nevergrouped{"123005000"}
   *           = "T"; # part-of is never grouped // //
   *           $nevergrouped{"272741003"} = "T"; # laterality is never grouped
   *           // // $nevergrouped{"127489000"} = "T"; # has-active-ingredient
   *           is never // grouped // // $nevergrouped{"411116001"} = "T"; #
   *           has-dose-form is never grouped return (nid ==
   *           Snomed.PART_OF.getNid() || nid == Snomed.LATERALITY.getNid()
   *           ||nid == Snomed.HAS_ACTIVE_INGREDIENT.getNid() || nid ==
   *           Snomed.HAS_DOSE_FORM.getNid()); }
   *
   *           private Concept getConcept(String id) { if
   *           (!concepts.containsKey(id)) { concepts.put(id,
   *           Factory.createNamedConcept(id)); } return concepts.get(id); }
   *
   *           private Role getRole(String id) { if (!roles.containsKey(id)) {
   *           roles.put(id, Factory.createNamedRole(id)); } return
   *           roles.get(id); }
   * @Override public NativeIdSetBI getNidSet() throws IOException { return
   *           dataStore.getAllConceptNids(); }
   * @Override public String getTitle() { return this.getClass().getName(); }
   **/
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;

using Autodesk.Revit.DB.Mechanical;

namespace Revit.SDK.Samples.AddSpaceAndZone.CS
{
    /// <summary>
    /// The SpaceManager class is used to manage the Spaces elements in the current document.
    /// </summary>
    class SpaceManager
    {
        ExternalCommandData m_commandData;
        Dictionary<int, List<Space>> m_spaceDictionary;

        /// <summary>
        /// The constructor of SpaceManager class.
        /// </summary>
        /// <param name="data">The ExternalCommandData</param>
        /// <param name="spaceData">The spaceData contains all the Space elements in different level.</param>
        public SpaceManager(ExternalCommandData data, Dictionary<int,List<Space>> spaceData)
        {
            m_commandData = data;
            m_spaceDictionary = spaceData;
        }

        /// <summary>
        /// Get the Spaces elements in a specified level.
        /// </summary>
        /// <param name="level"></param>
        /// <returns>Return a space list</returns>
        public List<Space> GetSpaces(Level level)
        {
            return m_spaceDictionary[level.Id.IntegerValue];
        }

        /// <summary>
        /// Create the space for each closed wall loop or closed space separation in the active view.
        /// </summary>
        /// <param name="level">The level in which the spaces is to exist.</param>
        /// <param name="phase">The phase in which the spaces is to exist.</param>
        public void CreateSpaces(Level level, Phase phase)
        {
            try
            {
                ElementSet elements = m_commandData.Application.ActiveUIDocument.Document.Create.NewSpaces(level, phase, this.m_commandData.Application.ActiveUIDocument.Document.ActiveView);
                foreach (Element elem in elements)
                {
                    Space space = elem as Space;
                    if (space != null)
                    {
                        m_spaceDictionary[level.Id.IntegerValue].Add(space);
                    }
                }
                if (elements == null || elements.Size == 0)
                {
                    System.Windows.Forms.MessageBox.Show("There is no enclosed loop in " + level.Name);
                }

            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
        }
    }
}


text:
"""tensor_util tests."""

# pylint: disable=unused-import
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from tensorflow.contrib.framework.python.ops import ops as ops_lib
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import ops
from tensorflow.python.platform import test

class OpsTest(test.TestCase):

  def testGetGraphFromEmptyInputs(self):
    with ops.Graph().as_default() as g0:
      self.assertIs(g0, ops_lib.get_graph_from_inputs([]))

  def testGetGraphFromValidInputs(self):
    g0 = ops.Graph()
    with g0.as_default():
      values = [constant_op.constant(0.0), constant_op.constant(1.0)]
    self.assertIs(g0, ops_lib.get_graph_from_inputs(values))
    self.assertIs(g0, ops_lib.get_graph_from_inputs(values, g0))
    with ops.Graph().as_default():
      self.assertIs(g0, ops_lib.get_graph_from_inputs(values))
      self.assertIs(g0, ops_lib.get_graph_from_inputs(values, g0))

  def testGetGraphFromInvalidInputs(self):
    g0 = ops.Graph()
    with g0.as_default():
      values = [constant_op.constant(0.0), constant_op.constant(1.0)]
    g1 = ops.Graph()
    with self.assertRaisesRegexp(ValueError, "not from the passed-in graph"):
      ops_lib.get_graph_from_inputs(values, g1)
    with g1.as_default():
      values.append(constant_op.constant(2.0))
    with self.assertRaisesRegexp(ValueError, "must be from the same graph"):
      ops_lib.get_graph_from_inputs(values)
    with self.assertRaisesRegexp(ValueError, "not from the passed-in graph"):
      ops_lib.get_graph_from_inputs(values, g0)
    with self.assertRaisesRegexp(ValueError, "not from the passed-in graph"):
      ops_lib.get_graph_from_inputs(values, g1)

if __name__ == "__main__":
  test.main()


text:
from .protocol import Point, Range, Notification, Request
from .typing import Optional, Dict, Any
from .url import filename_to_uri
from .url import uri_to_filename
import linecache
import os
import sublime
import tempfile

def get_line(window: Optional[sublime.Window], file_name: str, row: int) -> str:
    '''
    Get the line from the buffer if the view is open, else get line from linecache.
    row - is 0 based. If you want to get the first line, you should pass 0.
    '''
    if not window:
        return ''

    view = window.find_open_file(file_name)
    if view:
        # get from buffer
        point = view.text_point(row, 0)
        return view.substr(view.line(point)).strip()
    else:
        # get from linecache
        # linecache row is not 0 based, so we increment it by 1 to get the correct line.
        return linecache.getline(file_name, row + 1).strip()

def get_storage_path() -> str:
    """
    The "Package Storage" is a way to store server data without influencing the behavior of Sublime Text's "catalog".
    Its path is '$DATA/Package Storage', where $DATA means:

    - on macOS: ~/Library/Application Support/Sublime Text 3
    - on Windows: %AppData%/Sublime Text 3/Roaming
    - on Linux: $XDG_CONFIG_DIR/sublime-text-3
    """
    return os.path.abspath(os.path.join(sublime.cache_path(), "..", "Package Storage"))

def extract_variables(window: sublime.Window) -> Dict[str, str]:
    variables = window.extract_variables()
    variables["storage_path"] = get_storage_path()
    variables["cache_path"] = sublime.cache_path()
    variables["temp_dir"] = tempfile.gettempdir()
    variables["home"] = os.path.expanduser('~')
    return variables

def point_to_offset(point: Point, view: sublime.View) -> int:
    return view.text_point(
        point.row,
        # @see https://microsoft.github.io/language-server-protocol/specifications/specification-3-15/#position
        # If the character value is greater than the line length it defaults back to the line length.
        min(point.col, len(view.line(view.text_point(point.row, 0))))
    )

def offset_to_point(view: sublime.View, offset: int) -> Point:
    return Point(*view.rowcol(offset))

def range_to_region(range: Range, view: sublime.View) -> sublime.Region:
    return sublime.Region(point_to_offset(range.start, view), point_to_offset(range.end, view))

def region_to_range(view: sublime.View, region: sublime.Region) -> Range:
    return Range(
        offset_to_point(view, region.begin()),
        offset_to_point(view, region.end())
    )

def location_to_encoded_filename(location: Dict[str, Any]) -> str:
    if "targetUri" in location:
        uri = location["targetUri"]
        position = location["targetSelectionRange"]["start"]
    else:
        uri = location["uri"]
        position = location["range"]["start"]
    # WARNING: Cannot possibly do UTF-16 conversion :) Oh well.
    return '{}:{}:{}'.format(uri_to_filename(uri), position['line'] + 1, position['character'] + 1)

class MissingFilenameError(Exception):

    def __init__(self, view_id: int) -> None:
        super().__init__("View {} has no filename".format(view_id))
        self.view_id = view_id

def uri_from_view(view: sublime.View) -> str:
    file_name = view.file_name()
    if file_name:
        return filename_to_uri(file_name)
    raise MissingFilenameError(view.id())

def text_document_identifier(view: sublime.View) -> Dict[str, Any]:
    return {"uri": uri_from_view(view)}

def entire_content(view: sublime.View) -> str:
    return view.substr(sublime.Region(0, view.size()))

def text_document_item(view: sublime.View, language_id: str) -> Dict[str, Any]:
    return {
        "uri": uri_from_view(view),
        "languageId": language_id,
        "version": view.change_count(),
        "text": entire_content(view)
    }

def versioned_text_document_identifier(view: sublime.View) -> Dict[str, Any]:
    return {"uri": uri_from_view(view), "version": view.change_count()}

def text_document_position_params(view: sublime.View, location: int) -> Dict[str, Any]:
    return {"textDocument": text_document_identifier(view), "position": offset_to_point(view, location).to_lsp()}

def did_open_text_document_params(view: sublime.View, language_id: str) -> Dict[str, Any]:
    return {"textDocument": text_document_item(view, language_id)}

def did_change_text_document_params(view: sublime.View) -> Dict[str, Any]:
    return {
        "textDocument": versioned_text_document_identifier(view),
        "contentChanges": [{"text": entire_content(view)}]
    }

def will_save_text_document_params(view: sublime.View, reason: int) -> Dict[str, Any]:
    return {"textDocument": text_document_identifier(view), "reason": reason}

def did_save_text_document_params(view: sublime.View, include_text: bool) -> Dict[str, Any]:
    result = {"textDocument": text_document_identifier(view)}  # type: Dict[str, Any]
    if include_text:
        result["text"] = entire_content(view)
    return result

def did_close_text_document_params(view: sublime.View) -> Dict[str, Any]:
    return {"textDocument": text_document_identifier(view)}

def did_open(view: sublime.View, language_id: str) -> Notification:
    return Notification.didOpen(did_open_text_document_params(view, language_id))

def did_change(view: sublime.View) -> Notification:
    return Notification.didChange(did_change_text_document_params(view))

def will_save(view: sublime.View, reason: int) -> Notification:
    return Notification.willSave(will_save_text_document_params(view, reason))

def will_save_wait_until(view: sublime.View, reason: int) -> Request:
    return Request.willSaveWaitUntil(will_save_text_document_params(view, reason))

def did_save(view: sublime.View, include_text: bool) -> Notification:
    return Notification.didSave(did_save_text_document_params(view, include_text))

def did_close(view: sublime.View) -> Notification:
    return Notification.didClose(did_close_text_document_params(view))

def formatting_options(settings: sublime.Settings) -> Dict[str, Any]:
    return {
        "tabSize": settings.get("tab_size", 4),
        "insertSpaces": settings.get("translate_tabs_to_spaces", False)
    }

def text_document_formatting(view: sublime.View) -> Request:
    return Request.formatting({
        "textDocument": text_document_identifier(view),
        "options": formatting_options(view.settings())
    })

def text_document_range_formatting(view: sublime.View, region: sublime.Region) -> Request:
    return Request.rangeFormatting({
        "textDocument": text_document_identifier(view),
        "options": formatting_options(view.settings()),
        "range": region_to_range(view, region).to_lsp()
    })

def make_link(href: str, text: str) -> str:
    return "{}".format(href, text.replace(' ', ' '))


text:
package com.google.cloud.tools.gradle.endpoints.framework;

import com.google.common.base.Charsets;
import com.google.common.io.CharStreams;
import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.util.zip.ZipFile;
import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

/** Test endpoints server plugin builds. */
public class EndpointsServerPluginTest {

  private static final String DEFAULT_HOSTNAME = "myapi.appspot.com";
  private static final String DEFAULT_BASEPATH = "/_ah/api";
  private static final String DEFAULT_URL = "https://" + DEFAULT_HOSTNAME + DEFAULT_BASEPATH;
  private static final String DEFAULT_URL_PREFIX = "public static final String DEFAULT_ROOT_URL = ";
  private static final String DEFAULT_URL_VARIABLE =
      DEFAULT_URL_PREFIX + "\"" + DEFAULT_URL + "/\";";
  private static final String CLIENT_LIB_PATH = "build/endpointsClientLibs/testApi-v1-java.zip";
  private static final String DISC_DOC_PATH =
      "build/endpointsDiscoveryDocs/testApi-v1-rest.discovery";
  private static final String API_JAVA_FILE_PATH =
      "testApi/src/main/java/com/example/testApi/TestApi.java";
  private static final String OPEN_API_DOC_PATH = "build/endpointsOpenApiDocs/openapi.json";

  @Rule public TemporaryFolder testProjectDir = new TemporaryFolder();

  @Test
  public void testClientLibs() throws IOException, URISyntaxException {
    new TestProject(testProjectDir.getRoot(), "projects/server")
        .gradleRunnerArguments("endpointsClientLibs")
        .build();

    assertClientLibGeneration(DEFAULT_URL_VARIABLE, null);
  }

  @Test
  public void testClientLibs_hostname() throws IOException, URISyntaxException {
    new TestProject(testProjectDir.getRoot(), "projects/server")
        .hostname("my.hostname.com")
        .gradleRunnerArguments("endpointsClientLibs", "--stacktrace")
        .build();

    assertClientLibGeneration(
        DEFAULT_URL_PREFIX + "\"https://my.hostname.com" + DEFAULT_BASEPATH + "/\";",
        DEFAULT_URL_VARIABLE);
  }

  @Test
  public void testClientLibs_basePath() throws IOException, URISyntaxException {
    new TestProject(testProjectDir.getRoot(), "projects/server")
        .basePath("/a/different/path")
        .gradleRunnerArguments("endpointsClientLibs")
        .build();

    assertClientLibGeneration(
        DEFAULT_URL_PREFIX + "\"https://" + DEFAULT_HOSTNAME + "/a/different/path/\";",
        DEFAULT_URL_VARIABLE);
  }

  @Test
  public void testClientLibs_application() throws IOException, URISyntaxException {
    new TestProject(testProjectDir.getRoot(), "projects/server")
        .applicationId("gradle-test")
        .gradleRunnerArguments("endpointsClientLibs")
        .build();

    assertClientLibGeneration(
        DEFAULT_URL_PREFIX + "\"https://gradle-test.appspot.com" + DEFAULT_BASEPATH + "/\";",
        DEFAULT_URL_VARIABLE);
  }

  private void assertClientLibGeneration(String expected, String unexpected) throws IOException {
    File clientLib = new File(testProjectDir.getRoot(), CLIENT_LIB_PATH);
    Assert.assertTrue(clientLib.exists());
    Assert.assertEquals(1, clientLib.getParentFile().listFiles().length);
    String apiJavaFile = getFileContentsInZip(clientLib, API_JAVA_FILE_PATH);
    Assert.assertThat(apiJavaFile, CoreMatchers.containsString(expected));
    if (unexpected != null) {
      Assert.assertThat(apiJavaFile, CoreMatchers.not(CoreMatchers.containsString(unexpected)));
    }
  }

  private String getFileContentsInZip(File zipFile, String path) throws IOException {
    try (ZipFile zip = new ZipFile(zipFile)) {
      InputStream is = zip.getInputStream(zip.getEntry(path));
      return CharStreams.toString(new InputStreamReader(is, Charsets.UTF_8));
    }
  }

  @Test
  public void testDiscoveryDocs() throws IOException, URISyntaxException {
    new TestProject(testProjectDir.getRoot(), "projects/server")
        .gradleRunnerArguments("endpointsDiscoveryDocs")
        .build();

    assertDiscoveryDocGeneration(DEFAULT_URL, null);
  }

  @Test
  public void testDiscoveryDocs_hostname() throws IOException, URISyntaxException {
    new TestProject(testProjectDir.getRoot(), "projects/server")
        .hostname("my.hostname.com")
        .gradleRunnerArguments("endpointsDiscoveryDocs")
        .build();

    assertDiscoveryDocGeneration("https://my.hostname.com/_ah/api", DEFAULT_URL);
  }

  @Test
  public void testDiscoveryDocs_basePath() throws IOException, URISyntaxException {
    new TestProject(testProjectDir.getRoot(), "projects/server")
        .basePath("/a/different/path")
        .gradleRunnerArguments("endpointsDiscoveryDocs")
        .build();

    assertDiscoveryDocGeneration("https://" + DEFAULT_HOSTNAME + "/a/different/path", DEFAULT_URL);
  }

  @Test
  public void testDiscoveryDocs_application() throws IOException, URISyntaxException {
    new TestProject(testProjectDir.getRoot(), "projects/server")
        .applicationId("gradle-test")
        .gradleRunnerArguments("endpointsDiscoveryDocs")
        .build();

    assertDiscoveryDocGeneration("https://gradle-test.appspot.com/_ah/api", DEFAULT_URL);
  }

  private void assertDiscoveryDocGeneration(String expected, String unexpected) throws IOException {
    File discoveryDoc = new File(testProjectDir.getRoot(), DISC_DOC_PATH);
    String discovery = Files.toString(discoveryDoc, Charsets.UTF_8);
    Assert.assertThat(discovery, CoreMatchers.containsString(expected));
    if (unexpected != null) {
      Assert.assertThat(discovery, CoreMatchers.not(CoreMatchers.containsString(unexpected)));
    }
  }

  @Test
  public void testOpenApiDocs() throws IOException, URISyntaxException {
    new TestProject(testProjectDir.getRoot(), "projects/server")
        .gradleRunnerArguments("endpointsOpenApiDocs", "--stacktrace")
        .build();

    assertOpenApiDocGeneration(DEFAULT_HOSTNAME, null);
  }

  @Test
  public void testOpenApiDocs_hostname() throws IOException, URISyntaxException {
    new TestProject(testProjectDir.getRoot(), "projects/server")
        .hostname("my.hostname.com")
        .gradleRunnerArguments("endpointsOpenApiDocs")
        .build();

    assertOpenApiDocGeneration("my.hostname.com", DEFAULT_HOSTNAME);
  }

  @Test
  public void testOpenApiDocs_basePath() throws IOException, URISyntaxException {
    new TestProject(testProjectDir.getRoot(), "projects/server")
        .basePath("/a/different/path")
        .gradleRunnerArguments("endpointsOpenApiDocs")
        .build();

    assertOpenApiDocGeneration("/a/different/path", DEFAULT_BASEPATH);
  }

  @Test
  public void testOpenApiDocs_application() throws IOException, URISyntaxException {
    new TestProject(testProjectDir.getRoot(), "projects/server")
        .applicationId("gradle-test")
        .gradleRunnerArguments("endpointsOpenApiDocs")
        .build();

    assertOpenApiDocGeneration("gradle-test.appspot.com", DEFAULT_HOSTNAME);
  }

  private void assertOpenApiDocGeneration(String expected, String unexpected) throws IOException {
    File openApiDoc = new File(testProjectDir.getRoot(), OPEN_API_DOC_PATH);
    String openApi = Files.toString(openApiDoc, Charsets.UTF_8);
    Assert.assertThat(openApi, CoreMatchers.containsString(expected));
    if (unexpected != null) {
      Assert.assertThat(openApi, CoreMatchers.not(CoreMatchers.containsString(unexpected)));
    }
  }
}


text:
var url = require('url'),
  util = require('util'),
  crypto = require('crypto');

var Request = require('request');

var debug = false;

function mergeOptions(defaults, options) {
  var keys = Object.keys(defaults)
  , i = keys.length
  , k ;

  options = options || {};

  while (i--) {
    k = keys[i];
    if (!(k in options)) {
      options[k] = defaults[k];
    }
  }

  return options;
};

function rawrequest(rurl, data, options, callback) {
  var curl = url.parse(rurl);
  var secure = curl.protocol === 'https:';
  var host = curl.hostname;
  var port = parseInt(curl.port, 10);
  var path = [curl.pathname || '/', curl.search || '', curl.hash || ''].join('');
  var method = data ? "POST" : "GET";
  var headers = {
    //text/html,application/xhtml+xml,application/xml,text/xml;q=0.9,*/*;q=0.8
    "Accept" : "application/json",
    'Content-Type': "application/json",
    "Accept-Encoding": "none",
    "Accept-Charset": "utf-8",
    "Connection": "close",
    "Host": host + (isNaN(port) ? "" : ":" + port)
  };

  if (options && options["username"] && options["token"]) {
    var userpass = options["username"] + ':';
    headers['Authorization'] = "Basic " + new Buffer(userpass).toString("base64");
    headers['jaasToken'] = options["token"];
  } else if (options && options["username"] && options["password"]) {
    var userpass = options["username"] + ':' + options["password"];
    headers['Authorization'] = "Basic " + new Buffer(userpass).toString("base64");
  } else if (options && options["userpass"]) {
    var userpass = options["userpass"];
    headers['Authorization'] = "Basic " + new Buffer(userpass).toString("base64");
  }

  var attr;

  if (typeof data === 'string') {
    headers["Content-Length"] = Buffer.byteLength(data, 'utf8');
    headers["Content-Type"] = "application/x-www-form-urlencoded";
  } else {
    data = JSON.stringify(data);
  }

  var options = {
    uri: curl,
    method: method,
    headers: headers
  };

  var request = Request(options, function (error, res, body) {

    if (debug) {
      console.log('Request: ', error, res, body);
    }

    if (res.statusCode == 401 && !error) {
      error = {
        statusCode: res.statusCode,
        statusMessage: res.statusMessage
      }
    }

    if (error) {
      callback(error);
    } else {
      if (typeof body === "string") {
      }
      request.on('error', callback);
      callback(null, res, body);
    }
  });
  request.end(data);

  return request;
}

function Adyen(options) {
  if (!(this instanceof Adyen))
    return new Adyen(options);

    this.options = mergeOptions({
      host: "https://pal-live.adyen.com",
      userpass: '',
      merchantAccount: ''
    }, options);
}

/*
https://pal-live.adyen.com/pal/servlet/Payment/V9
PALURL="${PALPROTOCOL}://${PALHOST}/${WEBAPP}${SERVICE}/$METHOD"
SERVICE="/servlet/Payment/V9"
WEBAPP="pal"
METHOD="authorise"
*/
Adyen.prototype.request = function(webapp, service, method, data, callback) {
  var url = this.options.host + '/' + webapp + '/servlet/' + service + '/V9/' + method;

  if (debug) {
    console.log("Requesting", url);

  }
  console.log("Requesting with Data", data);

  return rawrequest(url, data, this.options, function(err, response, body) {
    if (typeof body === "string") {

      try {
        body = JSON.parse(body)
      } catch (e) {
        console.log("Body parse err", body)
        body = {
          data: body
        }
      }
    }

    callback(err, body);
  });
}

Adyen.prototype.authoriseApplePay = function(reference, token, currency, value,  options, callback) {
  var data = {
    additionalData: {
      'payment.token': token
    },
    amount: {
      currency: currency,
      value: value
    },
    merchantAccount: this.options.merchantAccount,
    reference: reference
  }

  // PayPal_ECS hack
  if (!token) {
    return callback('Bad token', null, null);
  }

  var buf = new Buffer(token, 'base64');

  if (!buf) {
    return callback('Token cant be processed', null, null);
  }

  var paymentToken = JSON.parse(buf.toString());
  if (paymentToken.version == 'adyen-ec_v1') {
    data.selectedBrand = 'paypal_ecs';
  } else if (paymentToken.version == 'Adyen_Test') {
    this.options.host = Adyen.endpoint('test');
  }

  if (options && options.hasOwnProperty('captureDelayHours')) {
    data.captureDelayHours = options['captureDelayHours'];
  }

  console.log('Sending to Adyen', data);

  this.request('pal', 'Payment', 'authorise', data, function(err, res){
    console.log("err", err);
    console.log("res", res);
    callback(err, res, data);
  })
}

Adyen.parseNotifications = function(data) {
  var notes = [];
  if (!data.notificationItems) {
    return notes;
  }

  data.notificationItems.forEach(function(item){
    if (item.NotificationRequestItem) {
      notes.push(item.NotificationRequestItem);
    }
  });
  return notes;
};

Adyen.endpoint = function(platform) {
  if (platform == 'test') {
    return "https://pal-test.adyen.com";
  }
  return "https://pal-live.adyen.com";
}

Adyen.hmac = function(text, key) {
  var hmac = crypto.createHmac('sha1', key);
  hmac.setEncoding('base64');
  hmac.write(text);
  hmac.end();
  return hmac.read();
}

Adyen.amount2minorUnits = function(amount) {
  var amount_minor_units = amount * 100;
  return String(amount_minor_units.toFixed(0))
}

Adyen.responses = {
  notification: {
    notificationResponse: "[accepted]"
  }
}

module.exports = exports = Adyen;

if (require.main === module) {
    console.log("use require('adyen')");
}


text:
  <link rel="stylesheet" href="maven-theme.css">
  <title>AppSecInc. MSI Extensions</title>

Main Page

Related Pages

Namespaces

Classes

Files

Class List

Class Hierarchy

Class Members

Static Public Member Functions |
List of all members

FormatterImpl< T > Class Template Reference

#include <FormatterImpl.h>

Static Public Member Functions

static int 	FormatTemplate (std::basic_string< T > &s, const std::map< std::basic_string< T >, std::basic_string< T >> &variables, const std::basic_string< T > &left, const std::basic_string< T > &right)

Member Function Documentation

template<class T >

          static int FormatterImpl< T >::FormatTemplate
          (
          std::basic_string< T > &
          s,

          const std::map< std::basic_string< T >, std::basic_string< T >> &
          variables,

          const std::basic_string< T > &
          left,

          const std::basic_string< T > &
          right

          )

inlinestatic

The documentation for this class was generated from the following file:

src/Common/String/FormatterImpl.h

     © Application Security Inc. - All Rights Reserved

     http://msiext.codeplex.com

  <link href="tabs.css" rel="stylesheet" type="text/css">


text:
using UnityEngine;
using UnityEngine.UI;

// This script is the artificial intelligence for character Lu

public class PersonLuAI : MonoBehaviour {

    private float moveY = 0.1f;
    private float originalMoveY;

    public GameObject dialogBox;
    public GameObject segbox;

    private string[] dialog;
    private Text myText;
    private string msg;
    private bool amTalking = false;
    private Text hints;
    private GameObject messenger;

    // Use this for initialization
    void Start () {

        dialog = new string[]
        {
            "Sure",

            "Lu",

            "I am a teacher so I guess I am the one who makes the noise, haha!",

            "My house can be noisy sometimes. Specially when my kids are playing videogames.",

            "It feels like I am playing the games with them, when all I want is to quietly enjoy some wine with my husband.",

            "Sure!", // If person agrees to talk, show clipboard and ask interviewer to choose questions.

            // Answer to interview question one: How do you feel about...
            "I think it..."

        };
        myText = dialogBox.GetComponentInChildren<Text>();
        messenger = GameObject.FindGameObjectWithTag("Messenger");
        hints = messenger.GetComponent<Text>();

    }

    void OnTriggerStay(Collider coll)
    {
        if (coll.gameObject.tag == "MainCamera")
        {

            if (coll.gameObject.GetComponent<CameraController>().isTalking) // player is talking
            {

                //print("IsTalking OnTriggerStay by BossAI");
                switch (coll.gameObject.GetComponent<CameraController>().dialogIndex) // what did the player say?
                {
                    case (0):
                        if (!amTalking) // OnTriggerStay runs multiples times per second. This "if" statement makes sure each dialog msg appears only once.
                        {
                            amTalking = true;
                            coll.gameObject.GetComponent<CameraController>().isTalking = false; // I got your message, player. Now it's my turn to talk.

                            msg = dialog[1] + ": " + dialog[0];
                            Invoke("say", 3f);

                        }
                        break;
                    case (1):
                        {
                            amTalking = true;
                            coll.gameObject.GetComponent<CameraController>().isTalking = false;

                            // dialog[0] is a reference to the character's name
                            coll.gameObject.GetComponent<CameraController>().dialog[10] = dialog[0]; // update interlocutor's name on player's script
                                                                                // in this case, it means to save the boss name in the player's memory

                            msg = dialog[1] + ": I am " + dialog[1] + ".";
                            Invoke("say", 2f);

                        }
                        break;
                    case (2):
                        {
                            amTalking = true;
                            coll.gameObject.GetComponent<CameraController>().isTalking = false;

                            msg = dialog[1] + ": " + dialog[2];
                            Invoke("say", 2f);

                        }
                        break;
                    case (3):
                        {
                            amTalking = true;
                            coll.gameObject.GetComponent<CameraController>().isTalking = false;

                            msg = dialog[1] + ": " + dialog[3];
                            Invoke("say", 2f);

                        }
                        break;

                    case (4):
                        {
                            amTalking = true;
                            coll.gameObject.GetComponent<CameraController>().isTalking = false;

                            msg = dialog[1] + ": " + dialog[4];
                            Invoke("say", 2f);

                        }
                        break;

                    case (20): // check if player entered the correct interview data
                        {
                            amTalking = true;
                            coll.gameObject.GetComponent<CameraController>().isTalking = false;

                            if (coll.gameObject.GetComponent<CameraController>().dialog[11].Contains("Teacher") &&
                                coll.gameObject.GetComponent<CameraController>().dialog[12].Contains("People who live in a noisy environment"))
                            {

                                segbox = GameObject.FindGameObjectWithTag("segmentsbox");
                                Text segments = segbox.gameObject.GetComponent<Text>();
                                segments.text += "\n" + coll.gameObject.GetComponent<CameraController>().dialog[11] + ": " +
                                    coll.gameObject.GetComponent<CameraController>().dialog[12];

                                hints.text = "You Win!";
                                coll.gameObject.GetComponent<CameraController>().play("win");

                            }
                            else
                            {
                                hints.text = "Good start. Try again.";
                            }

                        }
                        break;
                }
            }
        }
    }

    void OnTriggerEnter (Collider coll)
    {
        //print("OnTriggerEnter by PersonAI");
        if(coll.gameObject.tag == "MainCamera")
        {
            //print("main camera detected OnTriggerEnter by PersonAI");
            originalMoveY = moveY;
            moveY = 0f;
        }
        else
        {
            //print("main camera NOT detected OnTriggerEnter by PersonAI");
            moveY *= -1;
        }
    }

    void OnTriggerExit (Collider coll)
    {
        //print("OnTriggerExit by PersonAI");
        if (coll.gameObject.tag == "MainCamera")
        {
            //print("main camera detected OnTriggerExit by PersonAI");
            moveY = originalMoveY;
        }

    }

    void say() // adds linebreaks to keep dialog visible
    {
        myText.text += "\n" + msg + "\n";
        amTalking = false;
    }

    // Update is called once per frame
    void FixedUpdate () {

        gameObject.transform.position += new Vector3(0f, 0f, moveY);

	}
}


text:
from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA

def generate_rsa_key_pair(modulus_bit_length=2048, passphrase=None):
    key = RSA.generate(modulus_bit_length)
    public_key = key.publickey().exportKey('PEM')
    private_key = key.exportKey('PEM', passphrase=passphrase)
    return public_key, private_key

def encrypt_secret_with_rsa_key(secret, public_key):
    public_key = RSA.importKey(public_key)
    cipher = PKCS1_OAEP.new(public_key)
    return cipher.encrypt(secret)

def decrypt_secret_with_rsa_key(ciphertext, private_key, passphrase=None):
    private_key = RSA.importKey(private_key, passphrase=passphrase)
    cipher = PKCS1_OAEP.new(private_key)
    return cipher.decrypt(ciphertext)


text:
<?php

require_once('BaseTModels.class.php');

class Class_Model_TReminders extends BaseTModels
{
	/**
     * @var string 対応テーブル名
     */
	protected $_name   = 't_reminders';

	public function selectFromStatus($status)
	{
		$select = $this->select();
		$select->where('status = ?', $status);
		return $this->fetchAll($select);
	}

	public function selectFromReserveId($t_reserve_id)
	{
		$select = $this->select();
		$select->where('t_reserve_id = ?', $t_reserve_id);
		return $this->fetchRow($select);
	}

	public function deleteFromReserveId($t_reserve_id)
	{
		$where = $this->getAdapter()->quoteInto('t_reserve_id = ?' , $t_reserve_id);

		return $this->delete($where);
	}

}


text:
from BeautifulSoup import BeautifulSoup
import feedparser

usdan_rss = "http://legacy.cafebonappetit.com/rss/menu/332"
# summerfields_rss = 'http://legacy.cafebonappetit.com/rss/menu/337'

def fetch_all():
    usdan_meals = fetch_meals(usdan_rss)
    # summerfields_meals = fetch_meals(summerfields_rss)
    return {"Usdan": usdan_meals}

def fetch_meals(source):
    fp = feedparser.parse(source)
    items = fp['items']
    parsed_items = []
    for item in items:
        parsed_items.append(parse_day_item(item))
    return parsed_items

def parse_day_item(item):
    summary_text = item.summary
    soup = BeautifulSoup(summary_text)
    meal_tags = soup.findAll('h3')
    item_time = item.title
    meals = {"time": item_time}

    for i in meal_tags:
        meals[i.text.lower()] = get_food_items(i)

    return meals

def get_food_items(bs_obj):
    items = []
    tags = bs_obj.fetchNextSiblings()
    i = 0
    while i < len(tags):
        current_tag = tags[i]
        if current_tag.name == "h3":
            # this means we found a meal tag, probably, so end.
            break

        h4_text = current_tag.text.replace("&nbsp", "")
        p_text = tags[i + 1].text.replace("&nbsp", "")

        # get the food category and title
        category, title = h4_text.split('[')[1].split(']')

        items.append([category, title, p_text])
        i += 2

    return items

fetch_all()


text:
package kafka.tools

import joptsimple.OptionParser
import org.I0Itec.zkclient.ZkClient
import kafka.utils.{Logging, ZKGroupTopicDirs, ZkUtils, ZKStringSerializer}

object VerifyConsumerRebalance extends Logging {
  def main(args: Array[String]) {
    val parser = new OptionParser()

    val zkConnectOpt = parser.accepts("zk.connect", "ZooKeeper connect string.").
      withRequiredArg().defaultsTo("localhost:2181").ofType(classOf[String]);
    val groupOpt = parser.accepts("group", "Consumer group.").
      withRequiredArg().ofType(classOf[String])
    parser.accepts("help", "Print this message.")

    val options = parser.parse(args : _*)

    if (options.has("help")) {
      parser.printHelpOn(System.out)
      System.exit(0)
    }

    for (opt <- List(groupOpt))
      if (!options.has(opt)) {
        System.err.println("Missing required argument: %s".format(opt))
        parser.printHelpOn(System.err)
        System.exit(1)
      }

    val zkConnect = options.valueOf(zkConnectOpt)
    val group = options.valueOf(groupOpt)

    var zkClient: ZkClient = null
    try {
      zkClient = new ZkClient(zkConnect, 30000, 30000, ZKStringSerializer)

      debug("zkConnect = %s; group = %s".format(zkConnect, group))

      // check if the rebalancing operation succeeded.
      try {
        if(validateRebalancingOperation(zkClient, group))
          println("Rebalance operation successful !")
        else
          println("Rebalance operation failed !")
      } catch {
        case e2: Throwable => error("Error while verifying current rebalancing operation", e2)
      }
    }
    finally {
      if (zkClient != null)
        zkClient.close()
    }
  }

  private def validateRebalancingOperation(zkClient: ZkClient, group: String): Boolean = {
    info("Verifying rebalancing operation for consumer group " + group)
    var rebalanceSucceeded: Boolean = true
    /**
     * A successful rebalancing operation would select an owner for each available partition
     * This means that for each partition registered under /brokers/topics/[topic]/[broker-id], an owner exists
     * under /consumers/[consumer_group]/owners/[topic]/[broker_id-partition_id]
     */
    val consumersPerTopicMap = ZkUtils.getConsumersPerTopic(zkClient, group)
    val partitionsPerTopicMap = ZkUtils.getPartitionsForTopics(zkClient, consumersPerTopicMap.keySet.toSeq)

    partitionsPerTopicMap.foreach { partitionsForTopic =>
      val topic = partitionsForTopic._1
      val partitions = partitionsForTopic._2
      val topicDirs = new ZKGroupTopicDirs(group, topic)
      info("Alive partitions for topic %s are %s ".format(topic, partitions.toString))
      info("Alive consumers for topic %s => %s ".format(topic, consumersPerTopicMap.get(topic)))
      val partitionsWithOwners = ZkUtils.getChildrenParentMayNotExist(zkClient, topicDirs.consumerOwnerDir)
      if(partitionsWithOwners.size == 0) {
        error("No owners for any partitions for topic " + topic)
        rebalanceSucceeded = false
      }
      debug("Children of " + topicDirs.consumerOwnerDir + " = " + partitionsWithOwners.toString)
      val consumerIdsForTopic = consumersPerTopicMap.get(topic)

      // for each available partition for topic, check if an owner exists
      partitions.foreach { partition =>
      // check if there is a node for [partition]
        if(!partitionsWithOwners.exists(p => p.equals(partition))) {
          error("No owner for topic %s partition %s".format(topic, partition))
          rebalanceSucceeded = false
        }
        // try reading the partition owner path for see if a valid consumer id exists there
        val partitionOwnerPath = topicDirs.consumerOwnerDir + "/" + partition
        val partitionOwner = ZkUtils.readDataMaybeNull(zkClient, partitionOwnerPath)._1 match {
          case Some(m) => m
          case None => null
        }
        if(partitionOwner == null) {
          error("No owner for topic %s partition %s".format(topic, partition))
          rebalanceSucceeded = false
        }
        else {
          // check if the owner is a valid consumer id
          consumerIdsForTopic match {
            case Some(consumerIds) =>
              if(!consumerIds.contains(partitionOwner)) {
                error("Owner %s for topic %s partition %s is not a valid member of consumer " +
                  "group %s".format(partitionOwner, topic, partition, group))
                rebalanceSucceeded = false
              }
              else
                info("Owner of topic %s partition %s is %s".format(topic, partition, partitionOwner))
            case None => {
              error("No consumer ids registered for topic " + topic)
              rebalanceSucceeded = false
            }
          }
        }
      }

    }

    rebalanceSucceeded
  }
}


text:
from django.shortcuts import render
from mezzanine.pages.page_processors import processor_for
from .models import FlexiPage
from .utils import get_flexi_template_location, get_flexi_forms

from django.conf import settings

try:
    FLEXI_PREFIX = settings.VARIABLE_PREFIX
except AttributeError:
    VARIABLE_PREFIX = 'flexi_'

try:
    FLEXI_FORMS = settings.FLEXI_FORMS
except AttributeError:
    FLEXI_FORMS = None

def get_flexi_variables_context(page):
    variables_context = {}
    variables_context['page'] = page
    # Get every FlexiContent model fk'd to the FlexiPage
    # TODO potentially should introspect the template and only retrieve FlexiContent models
    # that exist on the page rather than just getting everything fk'd to the page
    flexi_contents = page.flexipage.flexi_content.all()
    # Use the name of the FlexiContent and inject that into the context
    for fc in flexi_contents:
        variables_context[fc.name] = fc
    return variables_context

def get_flexi_forms_context(page):
    forms_context = {}
    template_path = get_flexi_template_location(page.flexipage.template_name)
    template_forms = get_flexi_forms(template_path)
    for form_name, form_class in template_forms.iteritems():
        forms_context[form_name] = form_class(prefix=form_name)
    return forms_context

@processor_for(FlexiPage)
def flexi_page_view(request, page):
    # Get the template from the flexipage model, or raise exception
    template_path = get_flexi_template_location(page.flexipage.template_name)
    if request.user.is_staff:
        # Calling save ensures that the FlexiContent models are created
        page.flexipage.save()

    variables_context = get_flexi_variables_context(page)
    forms_context = get_flexi_forms_context(page)

    if request.method == "POST":
        # Get all forms on the page
        # Check each form for integrity
        # If each form is_valid() then save everything
        # If a form fails validation, re-render all bound forms
        template_forms = get_flexi_forms(template_path)
        bound_forms_success = {}
        bound_forms_errors = {}
        for form_name, form_class in template_forms.iteritems():
            bound_form = form_class(request.POST, prefix=form_name)
            if bound_form.is_valid():
                bound_forms_success[form_name] = bound_form
                bound_form.save()
            else:
                bound_forms_errors[form_name] = bound_form

        # If there are errors, re-render with bound forms
        # If there are no errors
        #  1. Check each form for an flexi_intermediate() method
        #  1. re-render with success markings on forms
        if bound_forms_errors:
            context = dict(variables_context.items() +
                           bound_forms_success.items() + bound_forms_errors.items())
            return render(request, template_name=template_path, dictionary=context)
        else: # All forms saved successfully
            for form_name, form_class in bound_forms_success.iteritems():
                # Try calling the forms intermediate method
                if hasattr(form_class,'flexi_intermediate'):
                    return form_class.flexi_intermediate()
            # No flexi_intermediate methods found, render page as per normal GET request
            context = dict(variables_context.items() + forms_context.items())
            return render(request, template_name=template_path, dictionary=context)

    elif request.method == "GET":
        context = dict(variables_context.items() + forms_context.items())
        return render(request, template_name=template_path, dictionary=context)