text:
package com.amazonaws.services.apigatewayv2.model.transform;

import java.util.Map;
import java.util.List;
import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.apigatewayv2.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * ApiMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class ApiMarshaller {

    private static final MarshallingInfo<String> APIENDPOINT_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("apiEndpoint").build();
    private static final MarshallingInfo<Boolean> APIGATEWAYMANAGED_BINDING = MarshallingInfo.builder(MarshallingType.BOOLEAN)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("apiGatewayManaged").build();
    private static final MarshallingInfo<String> APIID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("apiId").build();
    private static final MarshallingInfo<String> APIKEYSELECTIONEXPRESSION_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("apiKeySelectionExpression").build();
    private static final MarshallingInfo<StructuredPojo> CORSCONFIGURATION_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("corsConfiguration").build();
    private static final MarshallingInfo<java.util.Date> CREATEDDATE_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("createdDate").timestampFormat("iso8601").build();
    private static final MarshallingInfo<String> DESCRIPTION_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("description").build();
    private static final MarshallingInfo<Boolean> DISABLESCHEMAVALIDATION_BINDING = MarshallingInfo.builder(MarshallingType.BOOLEAN)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("disableSchemaValidation").build();
    private static final MarshallingInfo<Boolean> DISABLEEXECUTEAPIENDPOINT_BINDING = MarshallingInfo.builder(MarshallingType.BOOLEAN)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("disableExecuteApiEndpoint").build();
    private static final MarshallingInfo<List> IMPORTINFO_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("importInfo").build();
    private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("name").build();
    private static final MarshallingInfo<String> PROTOCOLTYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("protocolType").build();
    private static final MarshallingInfo<String> ROUTESELECTIONEXPRESSION_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("routeSelectionExpression").build();
    private static final MarshallingInfo<Map> TAGS_BINDING = MarshallingInfo.builder(MarshallingType.MAP).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("tags").build();
    private static final MarshallingInfo<String> VERSION_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("version").build();
    private static final MarshallingInfo<List> WARNINGS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("warnings").build();

    private static final ApiMarshaller instance = new ApiMarshaller();

    public static ApiMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(Api api, ProtocolMarshaller protocolMarshaller) {

        if (api == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(api.getApiEndpoint(), APIENDPOINT_BINDING);
            protocolMarshaller.marshall(api.getApiGatewayManaged(), APIGATEWAYMANAGED_BINDING);
            protocolMarshaller.marshall(api.getApiId(), APIID_BINDING);
            protocolMarshaller.marshall(api.getApiKeySelectionExpression(), APIKEYSELECTIONEXPRESSION_BINDING);
            protocolMarshaller.marshall(api.getCorsConfiguration(), CORSCONFIGURATION_BINDING);
            protocolMarshaller.marshall(api.getCreatedDate(), CREATEDDATE_BINDING);
            protocolMarshaller.marshall(api.getDescription(), DESCRIPTION_BINDING);
            protocolMarshaller.marshall(api.getDisableSchemaValidation(), DISABLESCHEMAVALIDATION_BINDING);
            protocolMarshaller.marshall(api.getDisableExecuteApiEndpoint(), DISABLEEXECUTEAPIENDPOINT_BINDING);
            protocolMarshaller.marshall(api.getImportInfo(), IMPORTINFO_BINDING);
            protocolMarshaller.marshall(api.getName(), NAME_BINDING);
            protocolMarshaller.marshall(api.getProtocolType(), PROTOCOLTYPE_BINDING);
            protocolMarshaller.marshall(api.getRouteSelectionExpression(), ROUTESELECTIONEXPRESSION_BINDING);
            protocolMarshaller.marshall(api.getTags(), TAGS_BINDING);
            protocolMarshaller.marshall(api.getVersion(), VERSION_BINDING);
            protocolMarshaller.marshall(api.getWarnings(), WARNINGS_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
using System;
using System.Threading.Tasks;
using TTMouseclickSimulator.Core.Actions;
using TTMouseclickSimulator.Core.Environment;

namespace TTMouseclickSimulator.Core.ToontownRewritten.Actions.Keyboard
{
    /// <summary>
    /// An action that writes the given string and a line break into the window.
    /// </summary>
    public class WriteTextAction : AbstractAction
    {

        private string text;
        private int? pauseDuration;

        /// <summary>
        ///
        /// </summary>
        /// <param name="text">The text to write.</param>
        /// <param name="pauseDuration">If not null, writes a single character
        /// and then pauses the specified time before writing the next one.
        /// Otherwise, all characters are written immediately.</param>
        public WriteTextAction(string text, int? pauseDuration = null)
        {
            if (text == null)
                throw new ArgumentNullException(nameof(text));

            this.text = text;
            this.pauseDuration = pauseDuration;
        }

        public override sealed async Task RunAsync(IInteractionProvider provider)
        {
            // write the text and presses enter.
            if (!this.pauseDuration.HasValue)
                provider.WriteText(this.text);
            else
            {
                for (int i = 0; i < this.text.Length; i++)
                {
                    provider.WriteText(this.text[i].ToString());
                    await provider.WaitAsync(this.pauseDuration.Value);
                }
            }

            // A CR LF (\r\n) in the above string would not have the desired effect;
            // instead we need to press the enter key.
            provider.PressKey(AbstractWindowsEnvironment.VirtualKeyShort.Enter);
            await provider.WaitAsync(100);
            provider.ReleaseKey(AbstractWindowsEnvironment.VirtualKeyShort.Enter);
        }

        public override string ToString() => $"Write Text – Text: \"{this.text}\""
            + (this.pauseDuration.HasValue ? "" : $", Pause Duration: {this.pauseDuration}");
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.intellij.psi.formatter;

import com.intellij.lang.xml.XMLLanguage;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiFile;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
import com.intellij.psi.formatter.xml.XmlCodeStyleSettings;
import com.intellij.util.SystemProperties;

public class XmlFormatterTest extends XmlFormatterTestBase {
  private static final String BASE_PATH = "psi/formatter/xml";

  public void test1() throws Exception {
    doTest();
  }

  public void test2() throws Exception {
    doTest();
  }

  public void test3() throws Exception {
    doTest();
  }

  public void test4() throws Exception {
    doTest();
  }

  public void test5() throws Exception {
    doTest();
  }

  public void test6() throws Exception {
    doTestKeepingWhitespacesStrictly(null);
  }

  public void test7() throws Exception {
    doTestKeepingWhitespacesStrictly(null);
  }

  public void test8() throws Exception {
    final CodeStyleSettings settings = getSettings();
    XmlCodeStyleSettings xmlSettings = getSettings().getCustomSettings(XmlCodeStyleSettings.class);
    xmlSettings.XML_TEXT_WRAP = CommonCodeStyleSettings.WRAP_AS_NEEDED;
    settings.setRightMargin(XMLLanguage.INSTANCE, 32);
    doTestDoNotKeepingWhitespaces();
  }

  public void test9() throws Exception {
    XmlCodeStyleSettings xmlSettings = getSettings().getCustomSettings(XmlCodeStyleSettings.class);
    xmlSettings.XML_TEXT_WRAP = CommonCodeStyleSettings.WRAP_AS_NEEDED;
    doTestDoNotKeepingWhitespaces();
  }

  public void test10() throws Exception {
    XmlCodeStyleSettings xmlSettings = getSettings().getCustomSettings(XmlCodeStyleSettings.class);
    xmlSettings.XML_ALIGN_TEXT = true;
    doTestDoNotKeepingWhitespacesKeepingLineBreaks();
  }

  public void test11() throws Exception {
    doTestDoNotWrap("DO_NOT_WRAP", true, 10);
    doTestWrapIfLong("WRAP_IF_LONG", true, 37);
    doChopDownIfLong("CHOP_IF_LONG", true, 37);
    doWrapAlways("WRAP_ALWAYS", true, 140);

    doTestDoNotWrap("ALIGN_DO_NOT_WRAP", false, 10);
    doTestWrapIfLong("ALIGN_WRAP_IF_LONG", false, 37);
    doChopDownIfLong("ALIGN_CHOP_IF_LONG", false, 37);
    doWrapAlways("ALIGN_WRAP_ALWAYS", false, 140);

  }

  public void test12() throws Exception {
    doTest();
  }

  public void test13() throws Exception {
    XmlCodeStyleSettings xmlSettings = getSettings().getCustomSettings(XmlCodeStyleSettings.class);
    xmlSettings.XML_KEEP_LINE_BREAKS = true;
    xmlSettings.XML_KEEP_BLANK_LINES = 2;
    doTestDoNotWrap(null, false, 140);
  }

  public void test14() throws Exception {
    doTest();
  }

  public void test15() throws Exception {
    doTest();
  }

  public void test16() throws Exception {
    doTestKeepingWhitespacesStrictly(null);
  }

  public void test17() throws Exception {

    CodeStyleSettings settings = getSettings();
    XmlCodeStyleSettings xmlSettings = settings.getCustomSettings(XmlCodeStyleSettings.class);
    xmlSettings.XML_SPACE_AROUND_EQUALITY_IN_ATTRIBUTE = true;
    xmlSettings.XML_SPACE_AFTER_TAG_NAME = true;

    try {
      doTest();
    }
    finally {
      xmlSettings.XML_SPACE_AROUND_EQUALITY_IN_ATTRIBUTE = false;
      xmlSettings.XML_SPACE_AFTER_TAG_NAME = false;
    }
  }

  public void testInvalid() throws Exception {
    doTest();
  }

  public void testComment() throws Exception {
    doTest();
  }

  public void testComment2() throws Exception {
    doTest("DO_NOT_KEEP_WHITESPACES");
    doTestKeepingWhitespacesStrictly("KEEP_WHITESPACES");
  }

  public void testComment3() throws Exception {
    doTest("DO_NOT_KEEP_WHITESPACES");
    doTestKeepingWhitespacesStrictly("KEEP_WHITESPACES");
  }

  public void testCDATA() throws Exception {
    doTest();
    doTestDoNotKeepingWhitespaces();
  }

  public void testKeepingSpacesAndWrapping() throws Exception {
    CodeStyleSettings settings = getSettings();
    XmlCodeStyleSettings xmlSettings = settings.getCustomSettings(XmlCodeStyleSettings.class);
    xmlSettings.XML_KEEP_WHITESPACES = true;

    doWrapAlways("ALIGN", true, 120);
    doWrapAlways("DO_NOT_ALIGN", false, 120);
  }

  public void testWhiteSpaceBeforeText() throws Exception {
    CodeStyleSettings settings = getSettings();
    XmlCodeStyleSettings xmlSettings = settings.getCustomSettings(XmlCodeStyleSettings.class);
    xmlSettings.XML_KEEP_WHITESPACES = false;
    doTest();
  }

  public void test18() throws Exception {
    checkFormattingDoesNotProduceException("18");
  }

  public void test19() throws Exception {
    myTextRange = new TextRange(31, 49);
    doTest();
  }

  public void test21() throws Exception {
    CodeStyleSettingsManager.getSettings(getProject()).setRightMargin(XMLLanguage.INSTANCE, 20);
    doTest();
  }

  public void test22() throws Exception {
    doTest();
  }

  public void testSCR1574() {
    XmlCodeStyleSettings xmlSettings = getSettings().getCustomSettings(XmlCodeStyleSettings.class);
    xmlSettings.XML_SPACE_INSIDE_EMPTY_TAG = true;
    doTextTest("<test/>", "<test />");

    xmlSettings.XML_SPACE_INSIDE_EMPTY_TAG = false;
    doTextTest("<test  />", "<test/>");
  }

  public void testSanity() throws Exception {
    doSanityTest(true);
  }

  public void testSCR1798() {
    XmlCodeStyleSettings xmlSettings = getSettings().getCustomSettings(XmlCodeStyleSettings.class);
    xmlSettings.XML_SPACE_INSIDE_EMPTY_TAG = true;
    doTextTest("", "");
  }

  public void testIDEA55230() {
    doTextTest("","");
  }

  public void testEa305257() throws Exception {
    doTest();
  }

  private static long currentFreeMemory() {
    Runtime runtime = Runtime.getRuntime();
    long maxMemory = runtime.maxMemory();
    return runtime.freeMemory() + (maxMemory - runtime.totalMemory());
  }

  public void excluded_testStressTest() throws Exception {
    if (!"lesya".equals(SystemProperties.getUserName())) return;
    String name = "stress.xml";
    final PsiFile file = createFile(name, loadFile(name, null));
    long memoryBefore = currentFreeMemory();
    long timeBefore = System.currentTimeMillis();
    CommandProcessor.getInstance().executeCommand(getProject(), () -> ApplicationManager.getApplication().runWriteAction(() -> performFormatting(file)), "", "");
    long memoryAfter = currentFreeMemory();
    long timeAfter = System.currentTimeMillis();

    System.out.println("\nMEMORY: " + (memoryAfter - memoryBefore));
    System.out.println("\nTIME: " + (timeAfter - timeBefore));
  }

  private void doWrapAlways(String resultNumber, boolean align, int rightMargin) throws Exception {
    CodeStyleSettings settings = getSettings();
    XmlCodeStyleSettings xmlSettings = getSettings().getCustomSettings(XmlCodeStyleSettings.class);
    xmlSettings.XML_ATTRIBUTE_WRAP = CommonCodeStyleSettings.WRAP_ALWAYS;
    settings.setRightMargin(XMLLanguage.INSTANCE, rightMargin);
    xmlSettings.XML_ALIGN_ATTRIBUTES = align;
    doTest(resultNumber);
  }

  private void doChopDownIfLong(String resultNumber, boolean align, int rightMargin) throws Exception {
    CodeStyleSettings settings = getSettings();
    XmlCodeStyleSettings xmlSettings = getSettings().getCustomSettings(XmlCodeStyleSettings.class);
    xmlSettings.XML_ATTRIBUTE_WRAP = CommonCodeStyleSettings.WRAP_ON_EVERY_ITEM;
    settings.setRightMargin(XMLLanguage.INSTANCE, rightMargin);
    xmlSettings.XML_ALIGN_ATTRIBUTES = align;
    doTest(resultNumber);
  }

  private void doTestWrapIfLong(String resultNumber, boolean align, int rightMargin) throws Exception {
    CodeStyleSettings settings = getSettings();
    XmlCodeStyleSettings xmlSettings = getSettings().getCustomSettings(XmlCodeStyleSettings.class);
    xmlSettings.XML_ATTRIBUTE_WRAP = CommonCodeStyleSettings.WRAP_AS_NEEDED;
    settings.setRightMargin(XMLLanguage.INSTANCE, rightMargin);
    xmlSettings.XML_ALIGN_ATTRIBUTES = align;
    doTest(resultNumber);
  }

  private void doTestDoNotWrap(String resultNumber, boolean align, int rightMargin) throws Exception {
    CodeStyleSettings settings = getSettings();
    XmlCodeStyleSettings xmlSettings = getSettings().getCustomSettings(XmlCodeStyleSettings.class);
    boolean oldValue = xmlSettings.XML_KEEP_WHITESPACES;
    xmlSettings.XML_ATTRIBUTE_WRAP = CommonCodeStyleSettings.DO_NOT_WRAP;
    xmlSettings.XML_KEEP_LINE_BREAKS = true;
    settings.setRightMargin(XMLLanguage.INSTANCE, rightMargin);
    xmlSettings.XML_ALIGN_ATTRIBUTES = align;
    try {
      doTest(resultNumber);
    }
    finally {
      xmlSettings.XML_KEEP_WHITESPACES = oldValue;
    }
  }

  private void doTestDoNotKeepingWhitespacesKeepingLineBreaks() throws Exception {
    XmlCodeStyleSettings xmlSettings = getSettings().getCustomSettings(XmlCodeStyleSettings.class);
    boolean oldValue = xmlSettings.XML_KEEP_WHITESPACES;
    xmlSettings.XML_KEEP_WHITESPACES = false;
    xmlSettings.XML_KEEP_LINE_BREAKS = true;
    try {
      doTest();
    }
    finally {
      xmlSettings.XML_KEEP_WHITESPACES = oldValue;
    }
  }

  private void doTestKeepingWhitespacesStrictly(String s) throws Exception {
    XmlCodeStyleSettings xmlSettings = getSettings().getCustomSettings(XmlCodeStyleSettings.class);
    boolean oldValue = xmlSettings.XML_KEEP_WHITESPACES;
    xmlSettings.XML_KEEP_WHITESPACES = true;
    try {
      doTest(s);
    }
    finally {
      xmlSettings.XML_KEEP_WHITESPACES = oldValue;
    }
  }

  private void doTestDoNotKeepingWhitespaces() throws Exception {
    XmlCodeStyleSettings xmlSettings = getSettings().getCustomSettings(XmlCodeStyleSettings.class);
    boolean oldValue = xmlSettings.XML_KEEP_WHITESPACES;
    xmlSettings.XML_KEEP_WHITESPACES = false;
    xmlSettings.XML_KEEP_LINE_BREAKS = false;
    xmlSettings.XML_KEEP_LINE_BREAKS_IN_TEXT = false;
    try {
      doTest();
    }
    finally {
      xmlSettings.XML_KEEP_WHITESPACES = oldValue;
    }
  }

  @Override
  protected void tearDown() throws Exception {
    try {
      defaultSettings();
    }
    finally {
      super.tearDown();
    }
  }

  @Override
  protected String getBasePath() {
    return BASE_PATH;
  }

  @Override
  protected String getFileExtension() {
    return "xml";
  }

  public void test20() throws Exception {
    doTest();
  }

  public void testPreserveSpace() throws Exception {
    doTest();
  }

  public void testIdea57965() throws Exception {
    doTest();
  }

  public void testIdea52549() {
    doTextTest(
      "<para>\n" +
      "  My <link>link</link> within text.\n" +
      "</para>",

      "<para>\n" +
      "    My <link>link</link> within text.\n" +
      "</para>"
    );
  }

  public void testDontKeepLineBreaksInText() {
    final CodeStyleSettings settings = getSettings();
    final XmlCodeStyleSettings xmlSettings = settings.getCustomSettings(XmlCodeStyleSettings.class);
    settings.setDefaultRightMargin(15);

    settings.HTML_KEEP_LINE_BREAKS_IN_TEXT = false;
    xmlSettings.XML_KEEP_LINE_BREAKS_IN_TEXT = false;
    doTextTest("<tag>aaa\nbbb\nccc\nddd\n</tag>", "<tag>aaa bbb\n    ccc ddd\n</tag>");

    settings.HTML_TEXT_WRAP = CommonCodeStyleSettings.DO_NOT_WRAP;
    xmlSettings.XML_TEXT_WRAP = CommonCodeStyleSettings.DO_NOT_WRAP;
    doTextTest("<tag>aaa\nbbb\nccc\nddd\n</tag>", "<tag>aaa bbb ccc ddd\n</tag>");
  }
}


text:
title: Github
layout: page
---

There are many viable ways of moving files between your computer and the server. We're going to use a program called `git`, because you'll have to learn it before too long anyway.

In general, `Git` lets you set up a folder on your computer as a `git repository`. It'll then let you keep track of any changes in that folder, `push` those changes to a copy of the git repository on another computer, or `pull` changes from there.

For our purposes, we'll be using the popular website GitHub as an intermediary between the server and your computer. If you edit a file on your computer, you'll push it to GitHub, log into the server, and `pull` it from GitHub.

This all sounds complicated, but we'll get through it.

## Create a GitHub account and set up Git

Go to [github.com](https://github.com/) and sign up for an account.

Once you've done that, follow their instructions for [setting up git](https://help.github.com/articles/set-up-git/). Since we're using SSH anyway, continue onto the article on [generating SSH keys](https://help.github.com/articles/generating-ssh-keys/).


text:
<?php
//error_reporting(-1);
session_start();

function get_config_no() {
  if (!isset($_SESSION['config_no'])) { $_SESSION['config_no'] = 0; }
  return $_SESSION['config_no'];
}
function set_config_no($config_no) {
  $_SESSION['config_no'] = $config_no;
}

require ('xajax/xajax_core/xajax.inc.php');
require_once('xml/Frame.php');

$xajax = new xajax();
//$xajax->setFlag('debug', true);
$xajax->configure('javascript URI', 'xajax');

function list_files($dir) {
  if (is_dir($dir) && $dentry = opendir($dir)) {
    while (false !== ($file = readdir($dentry))) {
      $path = $dir . DIRECTORY_SEPARATOR . $file;
      if (substr($file, 0, 1) == "." || is_dir($path)) { continue; } // if file starts with a . skip it
      $files[] = $file;
    }
    closedir($dentry);
    sort($files);
    return $files;
  }
}

function parse_config($dir, $config_no) {
  $configs = list_files($dir);
  $config  = $dir . DIRECTORY_SEPARATOR . $configs[$config_no];
  $c = simplexml_load_file($config);
  set_config_no($config_no);
  if (!isset($c->server->protocol))
    $c->server->protocol = "EPP";
  /*
  if (!isset $c->settings->templates)
    $c->settings->templates = array('.');
  */
  return $c;
}

function get_params() {
  $objResponse = new xajaxResponse();
  $objResponse->assign('command_params', 'innerHTML', 'n/a');
  return $objResponse;
}

function load_defaults($params, $command, $si) {
  $si = session_id();
  $command = str_replace(DIRECTORY_SEPARATOR, '_', $command);
  if (!file_exists('data' . DIRECTORY_SEPARATOR . $si . $command)) {
    $defaults['trid'] = time(); return $defaults;
  }
  $defaults = unserialize(join('', file('data' . DIRECTORY_SEPARATOR . $si . $command)));
  $defaults['trid'] = time();
  return $defaults;
}

function store_defaults($params, $command, $si) {
  $si = session_id();
  $command = str_replace(DIRECTORY_SEPARATOR, '_', $command);
  $fp = fopen('data' . DIRECTORY_SEPARATOR . $si . $command, 'w');
  fputs($fp, serialize($params));
  fclose($fp);
}

function switch_config($config_no) {
  $objResponse = new xajaxResponse();
  $configs = list_files('config');
  $config_list = 'Select Registrar ';
  $config_list .= '<select name="select_registrar" id="select_registrar"';
  $config_list .= ' onChange="xajax_event_toggle(this.value);return false;">';
  $i = 0;
  foreach ($configs as $config) {
    $config_list .= sprintf("<option value='%s'%s>%s</option>", $i, $i == $config_no ? ' selected' : '', $config);
    $i++;
  }
  $config_list .= '</select>
';

  $c = parse_config('config', $config_no);
  $info = sprintf("Host [%s], Protocol [%s] Port [%s], User [%s]",
      $c->server->host,
      $c->server->protocol,
      $c->server->port,
      $c->user->login);
  $config_list .= $info;
  $objResponse->assign('registrar_info', 'innerHTML',  $config_list);

  return $objResponse;
}

function get_commands() {
  $objResponse = new xajaxResponse();
  $c = parse_config('config', get_config_no());
  $disabled_commands = array();
  if (isset($c->settings->disabled_commands)) {
    foreach ($c->settings->disabled_commands as $disabled)
      $disabled_commands[] = $disabled;
  }
  $commands = array();
  foreach ($c->settings->templates as $template) {
    $path = 'templates' . DIRECTORY_SEPARATOR . $template;
    $files = list_files($path);
    if (count($files) < 1)
      $objResponse->alert("WARNING!\n\nNo templates found in $path\nCheck your <templates> settings in the current XML!\n");
    foreach ($commands as $o_dir => $o_files)
      $files = array_diff($files, $o_files); /* Prune already known commands */
    if (count($disabled_commands)) {
      $files = array_diff($files, $disabled_commands);
    }
    $commands["" . $path] = $files;
  }
  $command_list = '';
  foreach ($commands as $path => $cmds) {
    foreach ($cmds as $command)
      $command_list .= sprintf('%s
', $path, $command, $command);
  }
  $objResponse->assign('commands_list', 'innerHTML', $command_list);
  return $objResponse;
}

function format_params($params, $path, $p_command) {
  $ret = sprintf("
%s
\n", $p_command);
  $ret .= '<form id="params" onSubmit="return false">';
  $si = 0;
  $full_command = $path .DIRECTORY_SEPARATOR . $p_command;
  $defaults = load_defaults($params, $full_command, $si);

  foreach ($params as $p => $b) {
    $ret .= sprintf('%s <input type="text" name="%s" id="%s" value="%s">
', $p, $p, $p, $defaults[$p]);
  }
  $ret .= sprintf('<input type="hidden" name="p_command" id="p_command" value="%s" >
',
                   $full_command);
  $ret .= '<input type="button" name="submit" value="submit" onClick="set_class(\'command_out\', \'old_data\');xajax_dispatch_command(xajax.getFormValues(\'params\'));">';
  $ret .= '</form>';
  return $ret;
}
function print_params($path, $p_command) {
  $objResponse = new xajaxResponse();
  $frame = new xml_Frame();
  $params = $frame->get_params($path, $p_command);
  $fp = format_params($params, $path, $p_command);
  $objResponse->assign('command_params', 'innerHTML', $fp);
  return $objResponse;
}

function dispatch_command($params) {
  $si = 0;

  store_defaults($params, $params['p_command'], $si);
  $c = parse_config('config', get_config_no());
  if ($c->server->protocol == 'RRI') {
    return rri_command($params);
  } else {
    return epp_command($params);
  }
  $objResponse = new xajaxResponse();
  $objResponse->alert(sprintf("Unknown protocol '%s'\n", $c->server->protocol));
  return $objResponse;
}

function rri_command($params) {
  global $rri, $debug;
  $command = $params['p_command'];
  $c = parse_config('config', get_config_no());
  $host = $c->server->host;
  $port = (float)  $c->server->port;
  $timeout = (int) $c->server->timeout;
  $ssl = (boolean) $c->server->ssl;
//trigger_error(sprintf("host=%s, port=%s ssl=%s", $c->server->host, $c->server->port, $c->server->ssl));
  require ('Net/RRI/Client.php');
  $rri = new Net_RRI_Client();
  $greeting = $rri->connect($host, $port, $timeout, $ssl);
  $param[] = array(
      'login' => $c->user->login,
      'pw'    => $c->user->pw,
      'trid'  => $c->user->trid
  );
  send_rri_frame('login', $param);
  unset($param);

  $param[] = $params;
  $rri_return = send_rri_frame($command, $param);
  $rri->disconnect();

  $pr = sprintf("command: [%s]
", $params['p_command']);
  $objResponse = new xajaxResponse();
  if (00 && $rri_return->code >= 2000)
    $pr .= '
';
  $pr .= sprintf("code: [%s]
", $rri_return->code);
  $pr .= sprintf("msg:  [%s]
", $rri_return->msg);
  if (00 && $rri_return->code >= 2000)
    $pr .= '
';
  if ($rri_return->handle)
    $pr .= sprintf("handle:  [%s]
", $rri_return->handle);
  if (count($rri_return->error))
    $pr .= sprintf("\nError(s):
 [%s]

\n", print_r($rri_return->error, true));
  $pr .= "
" . print_r($params, true) . '
';
  $pr .= "
". htmlentities($rri_return->xml) . '
';
  $pr .= '
Request
';
  $pr .= sprintf("Request length: %u", $rri_return->request_len);
  $pr .= "
". htmlentities ($rri_return->request) . '
';
  $objResponse->assign('command_out', 'className', '');
  $objResponse->assign('command_out', 'innerHTML', $pr);
  return $objResponse;
}

function epp_command($params) {
  $objResponse = new xajaxResponse();
  $epp_return = send_epp_frame($params);
## $objResponse->alert("XXX:" . print_r($epp_return, true) . "\n");
  $pr = sprintf("command: [%s]
", $params['p_command']);
  if ($epp_return->code >= 2000)
    $pr .= '
';
  $pr .= sprintf("code: [%s]
", $epp_return->code);
  $pr .= sprintf("msg:  [%s]
", $epp_return->msg);
  if ($epp_return->code >= 2000)
    $pr .= '
';
  if ($epp_return->handle)
    $pr .= sprintf("handle:  [%s]
", $epp_return->handle);
  if (count($epp_return->error))
    $pr .= sprintf("\nError(s):
 [%s]

\n", print_r($epp_return->error, true));
  $pr .= "
" . print_r($params, true) . '
';
  $pr .= "
". htmlentities($epp_return->xml) . '
';
  $pr .= '
Request
';
  $pr .= sprintf("Request length: %u", $epp_return->request_len);
  $pr .= "
". htmlentities ($epp_return->request) . '
';
  $objResponse->assign('command_out', 'className', '');
  $objResponse->assign('command_out', 'innerHTML', $pr);
  return $objResponse;
}

function send_epp_frame($params) {
  $command = $params['p_command'];
  $c = parse_config('config', get_config_no());
  $host = $c->server->host;
  $port = (float)  $c->server->port;
  $timeout = (int) $c->server->timeout;
  $ssl = (boolean) $c->server->ssl;

  global $epp, $frame, $debug;

  //  $debug = (int) $c->DEBUG;
  // if ($debug == 1) {print_r($c);}
//trigger_error(sprintf("config_no=%s", get_config_no()));
//trigger_error(sprintf("host=%s, port=%s ssl=%s", $c->server->host, $c->server->port, $c->server->ssl));
  require ('Net/EPP/AT/Client.php');
  $epp = new Net_EPP_AT_Client();
  $greeting = $epp->connect($host, $port, $timeout, $ssl);
  $param[] = array(
      'login' => $c->user->login,
      'pw'    => $c->user->pw,
      'trid'  => $c->user->trid
  );
  $epp->command('login', $param);
  unset($param);

  $frame = new xml_Frame();

  $param[] = $params;

  $path = dirname($command);
  $command = basename($command);
  $epp_return = $epp->command($command, $param, $path);
  $epp->disconnect();
  return $epp_return;
}

function send_rri_frame($command, $param) {
    global $rri, $frame, $debug;
    unset($rri_return);
    $frame = new xml_Frame();
    $request = $frame->create($command, $param);
    $response = $rri->request($request);
    $rri_return->xml         = $response;
    $rri_return->code        = ''; /* silence warnings on error */
    $rri_return->msg         = ''; /* silence warnings on error */
    $rri_return->handle      = ''; /* silence warnings on error */
    $rri_return->request     = ''; /* silence warnings on error */
    $rri_return->request_len = ''; /* silence warnings on error */
    $len = strpos($response, '<');
    if ($len === false) {
	    $rri_return->error = "Response is not an XML.";
	    return $rri_return;
    }
    $len = strpos($request, '<');
    $hdr = "";

    for ($i = 0; $i <= $len; $i++) {
	    $hdr .= $request[$i];
    }
    $req_len = unpack('N', $hdr);
    $rri_return->request_len = $req_len[1];
    $request = substr($request, $len);
    $rri_return->request = $request;
    try {
	    $xml = new SimpleXMLElement($response);
    } catch (Exception $e) {
	    $rri_return->error = $e->getMessage();
	    trigger_error($response);
	    return $rri_return;
    }
    $this->xml = $xml;
    $rri_return->code    = $xml->response->result[0]->attributes();
    $rri_return->msg     = $xml->response->result->msg;
    $rri_return->handle  = '';
    $rri_return->error   = array();
    // do rri_return->code / error handling here...
    return $rri_return;
}

$req_print_params   =& $xajax->register(XAJAX_FUNCTION, 'print_params');
$req_dispatch_command =& $xajax->register(XAJAX_FUNCTION, 'dispatch_command', array('callback' => 'staleData'));
$req_toggle = $xajax->register(XAJAX_EVENT, 'toggle', array("mode" => "synchronous"));
$req_toggle->setParameter(0, XAJAX_JS_VALUE, get_config_no());
$xajax->register(XAJAX_EVENT_HANDLER, 'toggle', 'switch_config');
$xajax->register(XAJAX_EVENT_HANDLER, 'toggle', 'get_commands');
$xajax->register(XAJAX_EVENT_HANDLER, 'toggle', 'get_params');
$xajax->processRequest();

?>

  <link rel="stylesheet" href="epp-client.css" type="text/css" />
  <title>EPP client</title>
<?php
$xajax->printJavascript();
?>

<body onLoad='<?php $req_toggle->printScript(); ?>'>

Registrar Info

no data

EPP commands

no commands

Command parameters

no parameters

Command output

no output


text:
// Copyright NVIDIA Corporation 2011
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//  * Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//  * Neither the name of NVIDIA CORPORATION nor the names of its
//    contributors may be used to endorse or promote products derived
//    from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#pragma once

#include <test/testfw/core/inc/Config.h>
#include <test/testfw/core/MeasurementFunctor.h>
#include <string>
#include <vector>

namespace dp
{
  namespace testfw
  {
    namespace core
    {

      // template to determine #elements of an static array, usage sizeof array( yourarray );
      template< typename T, size_t N> char(&array(T(&)[N]))[N];

      class Test
      {
      public:
        DPTCORE_API Test();
        DPTCORE_API virtual ~Test();

      public:
          /*! \brief Virtual function called to initialize the Test.
           *  \return \c true if initialization was successful, otherwise \c false.
           *  \note The base implementation just returns \c true. */
          DPTCORE_API virtual bool onInit();

          /*! \brief Virtual function to check for the end of the sequence of test runs.
           *  \param i The index of the test to be run.
           *  \return \c true if the check was successful, otherwise \c false.
           *  \note The base implementation returns \c true for \a i == 0, otherwise \c false */
          DPTCORE_API virtual bool onRunCheck( unsigned int i );

          /*! \brief Virtual function to initialize one test run out of a sequence of test runs.
           *  \param i The index of the test to initialize.
           *  \return \c true if the test was initialized successfully, otherwise \c false.
           *  \note The base implementation always returns \c true. */
          DPTCORE_API virtual bool onRunInit( unsigned int i );

          /*! \brief Pure virtual function to run on test run out of a sequence of test runs.
           *  \param i The index of the test to run.
           *  \return \c true if the test was run successfully, otherwise \c false.
           *  \note There is no base implementation. */
          DPTCORE_API virtual bool onRun( unsigned int i = 0 ) = 0;

          /*! \brief Virtual function to clear one test run out of a sequence of test runs.
           *  \param i The index of the test run to clear.
           *  \return \c true if the test was cleared successfully, otherwise \c false.
           *  \note The base implementation always returns \c true. */
          DPTCORE_API virtual bool onRunClear( unsigned int i );

          /*! \brief Virtual function to clear the test.
           *  \return \c true if the test was cleared successfully, otherwise \c false.
           *  \note The base implementation just returns \c true. */
          DPTCORE_API virtual bool onClear();

          /*! \brief Check if measurement is allowed for this test.
           *  \return \c true if measurement is allowed for this test, otherwise \c false.
           *  \note The base implementation just returns \c false. */
          DPTCORE_API virtual bool allowMeasurement();

          /*! \brief Get the description for the test initialization.
           *  \return The description for the test initialization.
           *  \note The base implementation returns an empty string. */
          DPTCORE_API virtual const std::string & getDescriptionOnInit();

          /*! \brief Get the description for the initialization of one test run out of a sequence of test runs.
           *  \param i The index of the test run.
           *  \note The base implementation returns an empty string . */
          DPTCORE_API virtual const std::string & getDescriptionOnRunInit( unsigned int i );

          /*! \brief Get the description for the test run out of a sequence of test runs.
           *  \param i The index of the test run.
           *  \note The base implementation returns an empty string . */
          DPTCORE_API virtual const std::string & getDescriptionOnRun( unsigned int i );

          /*! \brief Get the description for the clearing of one test run out of a sequence of test runs.
           *  \param i The index of the test run.
           *  \note The base implementation returns an empty string . */
          DPTCORE_API virtual const std::string & getDescriptionOnRunClear( unsigned int i );

          /*! \brief Get the description for the test clearing.
           *  \return The description for the test clearing.
           *  \note The base implementation returns an empty string. */
          DPTCORE_API virtual const std::string & getDescriptionOnClear();

          /*! \brief This function can be overriden to process user defined command line options.
           *  \param optionString The unparsed options propagated from DPT.
           *  \return This function should return false only if there was input so invalid that the program must terminate. */
          DPTCORE_API virtual bool option( const std::vector<std::string>& optionString );

          /*! \brief Launch the test.
           *  \param mf The measurement functor to use in the test launch.
           *  \param name The test name to use in the launch.
           *  \return Returns true if the test passed, otherwise returns false. */
          DPTCORE_API virtual bool run( MeasurementFunctor & mf, const std::string& name );

      private:
        std::string m_curRunVal;

      };
    } //namespace core
  } //namespace testfw
} //namespace dp


text:
import * as cookie from 'cookie';
import {
  Cookie,
  CookieChangeListener,
  CookieChangeOptions,
  CookieGetOptions,
  CookieParseOptions,
  CookieSetOptions
} from './types';
import { hasDocumentCookie, parseCookies, readCookie } from './utils';

export default class Cookies {
  private cookies: { [name: string]: Cookie };
  private changeListeners: CookieChangeListener[] = [];

  private HAS_DOCUMENT_COOKIE: boolean = false;

  constructor(cookies?: string | object | null, options?: CookieParseOptions) {
    this.cookies = parseCookies(cookies, options);

    new Promise(() => {
      this.HAS_DOCUMENT_COOKIE = hasDocumentCookie();
    }).catch(() => {});
  }

  private _updateBrowserValues(parseOptions?: CookieParseOptions) {
    if (!this.HAS_DOCUMENT_COOKIE) {
      return;
    }

    this.cookies = cookie.parse(document.cookie, parseOptions);
  }

  private _emitChange(params: CookieChangeOptions) {
    for (let i = 0; i < this.changeListeners.length; ++i) {
      this.changeListeners[i](params);
    }
  }

  public get(name: string, options?: CookieGetOptions): any;
  public get<T>(name: string, options?: CookieGetOptions): T;
  public get(
    name: string,
    options: CookieGetOptions = {},
    parseOptions?: CookieParseOptions
  ) {
    this._updateBrowserValues(parseOptions);
    return readCookie(this.cookies[name], options);
  }

  public getAll(options?: CookieGetOptions): any;
  public getAll<T>(options?: CookieGetOptions): T;
  public getAll(
    options: CookieGetOptions = {},
    parseOptions?: CookieParseOptions
  ) {
    this._updateBrowserValues(parseOptions);
    const result: { [name: string]: any } = {};

    for (let name in this.cookies) {
      result[name] = readCookie(this.cookies[name], options);
    }

    return result;
  }

  public set(name: string, value: Cookie, options?: CookieSetOptions) {
    if (typeof value === 'object') {
      value = JSON.stringify(value);
    }

    this.cookies = { ...this.cookies, [name]: value };

    if (this.HAS_DOCUMENT_COOKIE) {
      document.cookie = cookie.serialize(name, value, options);
    }

    this._emitChange({ name, value, options });
  }

  public remove(name: string, options?: CookieSetOptions) {
    const finalOptions = (options = {
      ...options,
      expires: new Date(1970, 1, 1, 0, 0, 1),
      maxAge: 0
    });

    this.cookies = { ...this.cookies };
    delete this.cookies[name];

    if (this.HAS_DOCUMENT_COOKIE) {
      document.cookie = cookie.serialize(name, '', finalOptions);
    }

    this._emitChange({ name, value: undefined, options });
  }

  public addChangeListener(callback: CookieChangeListener) {
    this.changeListeners.push(callback);
  }

  public removeChangeListener(callback: CookieChangeListener) {
    const idx = this.changeListeners.indexOf(callback);
    if (idx >= 0) {
      this.changeListeners.splice(idx, 1);
    }
  }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>StatTests xref</title>
<link type="text/css" rel="stylesheet" href="../../../../stylesheet.css" />

View Javadoc

1   package net.sourceforge.pmd.stat;
2
3   import org.junit.runner.RunWith;
4   import org.junit.runners.Suite;
5   import org.junit.runners.Suite.SuiteClasses;
6
7
8   /**
9    * tests for the net.sourceforge.pmd.stat package
10   *
11   * @author Boris Gruschko ( boris at gruschko.org )
12   */
13  @RunWith(Suite.class)
14  @SuiteClasses({MetricTest.class, StatisticalRuleTest.class})
15  public class StatTests {
16  }

This page was automatically generated by Maven


text:
require "spec_helper"

describe User do
  it "has a valid username" do
    expect { User.make!(:username => nil) }.to raise_error
    expect { User.make!(:username => "") }.to raise_error
    expect { User.make!(:username => "*") }.to raise_error

    User.make!(:username => "test")
    expect { User.make!(:username => "test") }.to raise_error
  end

  it "has a valid email address" do
    User.make!(:email => "user@example.com")

    # duplicate
    expect { User.make!(:email => "user@example.com") }.to raise_error

    # bad address
    expect { User.make!(:email => "user@") }.to raise_error
  end

  it "authenticates properly" do
    u = User.make!(:password => "hunter2")

    u.password_digest.length.should > 20

    u.authenticate("hunter2").should == u
    u.authenticate("hunteR2").should == false
  end

  it "gets an error message after registering banned name" do
    expect { User.make!(:username => "admin") }.to raise_error("Validation failed: Username is not permitted")
  end

  it "shows a user is banned or not" do
    u = User.make!(:banned)
    user = User.make!
    u.is_banned?.should == true
    user.is_banned?.should == false
  end

  it "shows a user is active or not" do
    u = User.make!(:banned)
    user = User.make!
    u.is_active?.should == false
    user.is_active?.should == true
  end

  it "shows a user is recent or not" do
    user = User.make!(:created_at => Time.now)
    u = User.make!(:created_at => Time.now - 8.days)
    user.is_new?.should == true
    u.is_new?.should == false
  end

  it "unbans a user" do
    u = User.make!(:banned)
    u.unban_by_user!(User.first).should == true
  end
end


text:
BEGIN_INANITY_SHADERS

/// Генератор HLSL-кода по предоставленному определению шейдера.
class Hlsl11Generator : public ShaderGenerator
{
public:
	ptr<ShaderSource> Generate(Expression code, ShaderType shaderType);
};

END_INANITY_SHADERS

#endif


text:
var dtt_template_text = '
 \

 \

\

<input type="checkbox"/>Don\'t show me this again
 \
 \

';

function make_tooltip_text(element,popup_id,text,placement){
    placement = placement || 'auto';
    element.popover({
        html:true,
        content:text,
        placement:placement,
        template:dtt_template_text,
    }).popover('show');

    var id = element.attr('aria-describedby');
    console.log(id);
    $('#' + id).find('input[type=checkbox]').bind('change',function(e){
        $(this).closest('.popover').popover('destroy');
        console.log(popup_id);
        $.ajax({
            url:'/dtt/hide_popup',
            data:{p:popup_id}
        }).done(function(data){});
    });

}

$(function(){
    $('.dtt').each(function(){
        var us = $(this);
        var position =us.attr('data-position');
        var popup_id = us.attr('data-pid');
        var text = us.attr('data-content');
        make_tooltip_text(us,popup_id,text,position);
    });

    $(document).on('click','.dttclose',function(e){
        e.preventDefault();
        $(this).closest('.popover').popover('destroy');
    });

});


text:
./dpxdt/tools/site_diff.py \
    --release_server_prefix=http://localhost:5000/api \
    "$@"


text:
package com.cubitux.model.exception;

/**
 * Created by pierre on 2016-07-02.
 */
public class AccountNotActivatedException extends Exception {

    public AccountNotActivatedException(String message) {
        super(message);
    }
}


text:
package sun.management.jmxremote;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.UnknownHostException;
import java.rmi.NoSuchObjectException;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.Registry;
import java.rmi.server.RMIClientSocketFactory;
import java.rmi.server.RMIServerSocketFactory;
import java.rmi.server.RemoteObject;
import java.rmi.server.UnicastRemoteObject;
import java.security.KeyStore;
import java.security.Principal;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;

import javax.management.MBeanServer;
import javax.management.remote.JMXAuthenticator;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;
import javax.management.remote.rmi.RMIConnectorServer;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import javax.rmi.ssl.SslRMIClientSocketFactory;
import javax.rmi.ssl.SslRMIServerSocketFactory;
import javax.security.auth.Subject;

import com.sun.jmx.remote.internal.RMIExporter;
import com.sun.jmx.remote.security.JMXPluggableAuthenticator;
import com.sun.jmx.remote.util.ClassLogger;

import sun.management.Agent;
import sun.management.AgentConfigurationError;
import static sun.management.AgentConfigurationError.*;
import sun.management.ConnectorAddressLink;
import sun.management.FileSystem;
import sun.rmi.server.UnicastRef;
import sun.rmi.server.UnicastServerRef;
import sun.rmi.server.UnicastServerRef2;

/**
 * This class initializes and starts the RMIConnectorServer for JSR 163
 * JMX Monitoring.
 **/
public final class ConnectorBootstrap {

    /**
     * Default values for JMX configuration properties.
     **/
    public static interface DefaultValues {

        public static final String PORT = "0";
        public static final String CONFIG_FILE_NAME = "management.properties";
        public static final String USE_SSL = "true";
        public static final String USE_LOCAL_ONLY = "true";
        public static final String USE_REGISTRY_SSL = "false";
        public static final String USE_AUTHENTICATION = "true";
        public static final String PASSWORD_FILE_NAME = "jmxremote.password";
        public static final String ACCESS_FILE_NAME = "jmxremote.access";
        public static final String SSL_NEED_CLIENT_AUTH = "false";
    }

    /**
     * Names of JMX configuration properties.
     **/
    public static interface PropertyNames {

        public static final String PORT =
                "com.sun.management.jmxremote.port";
        public static final String RMI_PORT =
                "com.sun.management.jmxremote.rmi.port";
        public static final String CONFIG_FILE_NAME =
                "com.sun.management.config.file";
        public static final String USE_LOCAL_ONLY =
                "com.sun.management.jmxremote.local.only";
        public static final String USE_SSL =
                "com.sun.management.jmxremote.ssl";
        public static final String USE_REGISTRY_SSL =
                "com.sun.management.jmxremote.registry.ssl";
        public static final String USE_AUTHENTICATION =
                "com.sun.management.jmxremote.authenticate";
        public static final String PASSWORD_FILE_NAME =
                "com.sun.management.jmxremote.password.file";
        public static final String ACCESS_FILE_NAME =
                "com.sun.management.jmxremote.access.file";
        public static final String LOGIN_CONFIG_NAME =
                "com.sun.management.jmxremote.login.config";
        public static final String SSL_ENABLED_CIPHER_SUITES =
                "com.sun.management.jmxremote.ssl.enabled.cipher.suites";
        public static final String SSL_ENABLED_PROTOCOLS =
                "com.sun.management.jmxremote.ssl.enabled.protocols";
        public static final String SSL_NEED_CLIENT_AUTH =
                "com.sun.management.jmxremote.ssl.need.client.auth";
        public static final String SSL_CONFIG_FILE_NAME =
                "com.sun.management.jmxremote.ssl.config.file";
    }

    /**
     * JMXConnectorServer associated data.
     */
    private static class JMXConnectorServerData {

        public JMXConnectorServerData(
                JMXConnectorServer jmxConnectorServer,
                JMXServiceURL jmxRemoteURL) {
            this.jmxConnectorServer = jmxConnectorServer;
            this.jmxRemoteURL = jmxRemoteURL;
        }
        JMXConnectorServer jmxConnectorServer;
        JMXServiceURL jmxRemoteURL;
    }

    /**
     *
Prevents our RMI server objects from keeping the JVM alive.

     *
     *
We use a private interface in Sun's JMX Remote API implementation
     * that allows us to specify how to export RMI objects.  We do so using
     * UnicastServerRef, a class in Sun's RMI implementation.  This is all
     * non-portable, of course, so this is only valid because we are inside
     * Sun's JRE.

     *
     *
Objects are exported using {@link
     * UnicastServerRef#exportObject(Remote, Object, boolean)}.  The
     * boolean parameter is called permanent and means
     * both that the object is not eligible for Distributed Garbage
     * Collection, and that its continued existence will not prevent
     * the JVM from exiting.  It is the latter semantics we want (we
     * already have the former because of the way the JMX Remote API
     * works).  Hence the somewhat misleading name of this class.

     */
    private static class PermanentExporter implements RMIExporter {

        public Remote exportObject(Remote obj,
                int port,
                RMIClientSocketFactory csf,
                RMIServerSocketFactory ssf)
                throws RemoteException {

            synchronized (this) {
                if (firstExported == null) {
                    firstExported = obj;
                }
            }

            final UnicastServerRef ref;
            if (csf == null && ssf == null) {
                ref = new UnicastServerRef(port);
            } else {
                ref = new UnicastServerRef2(port, csf, ssf);
            }
            return ref.exportObject(obj, null, true);
        }

        // Nothing special to be done for this case
        public boolean unexportObject(Remote obj, boolean force)
                throws NoSuchObjectException {
            return UnicastRemoteObject.unexportObject(obj, force);
        }
        Remote firstExported;
    }

    /**
     * This JMXAuthenticator wraps the JMXPluggableAuthenticator and verifies
     * that at least one of the principal names contained in the authenticated
     * Subject is present in the access file.
     */
    private static class AccessFileCheckerAuthenticator
            implements JMXAuthenticator {

        public AccessFileCheckerAuthenticator(Map<String, Object> env) throws IOException {
            environment = env;
            accessFile = (String) env.get("jmx.remote.x.access.file");
            properties = propertiesFromFile(accessFile);
        }

        public Subject authenticate(Object credentials) {
            final JMXAuthenticator authenticator =
                    new JMXPluggableAuthenticator(environment);
            final Subject subject = authenticator.authenticate(credentials);
            checkAccessFileEntries(subject);
            return subject;
        }

        private void checkAccessFileEntries(Subject subject) {
            if (subject == null) {
                throw new SecurityException(
                        "Access denied! No matching entries found in " +
                        "the access file [" + accessFile + "] as the " +
                        "authenticated Subject is null");
            }
            final Set<Principal> principals = subject.getPrincipals();
            for (Principal p1: principals) {
                if (properties.containsKey(p1.getName())) {
                    return;
                }
            }

            final Set<String> principalsStr = new HashSet<>();
            for (Principal p2: principals) {
                principalsStr.add(p2.getName());
            }
            throw new SecurityException(
                    "Access denied! No entries found in the access file [" +
                    accessFile + "] for any of the authenticated identities " +
                    principalsStr);
        }

        private static Properties propertiesFromFile(String fname)
                throws IOException {
            Properties p = new Properties();
            if (fname == null) {
                return p;
            }
            try (FileInputStream fin = new FileInputStream(fname)) {
                p.load(fin);
            }
            return p;
        }
        private final Map<String, Object> environment;
        private final Properties properties;
        private final String accessFile;
    }

    // The variable below is here to support stop functionality
    // It would be overriten if you call startRemoteCommectionServer second
    // time. It's OK for now as logic in Agent.java forbids mutiple agents
    private static Registry registry = null;

    public static void unexportRegistry() {
        // Remove the entry from registry
        try {
            if (registry != null) {
                UnicastRemoteObject.unexportObject(registry, true);
                registry = null;
            }
        } catch(NoSuchObjectException ex) {
            // This exception can appears only if we attempt
            // to unexportRegistry second time. So it's safe
            // to ignore it without additional messages.
        }
    }

     /**
      * Initializes and starts the JMX Connector Server.
      * If the com.sun.management.jmxremote.port property is not defined,
      * simply return. Otherwise, attempts to load the config file, and
      * then calls {@link #startRemoteConnectorServer
      *                            (java.lang.String, java.util.Properties)}.
      *
      * This method is used by some jtreg tests.
      **/
      public static synchronized JMXConnectorServer initialize() {

         // Load a new management properties
         final Properties props = Agent.loadManagementProperties();
         if (props == null) {
              return null;
         }

         final String portStr = props.getProperty(PropertyNames.PORT);
         return startRemoteConnectorServer(portStr, props);
     }

    /**
     * This method is used by some jtreg tests.
     *
     * @see #startRemoteConnectorServer
     *             (String portStr, Properties props)
     */
    public static synchronized JMXConnectorServer initialize(String portStr, Properties props)  {
         return startRemoteConnectorServer(portStr, props);
    }

    /**
     * Initializes and starts a JMX Connector Server for remote
     * monitoring and management.
     **/
    public static synchronized JMXConnectorServer startRemoteConnectorServer(String portStr, Properties props) {

        // Get port number
        final int port;
        try {
            port = Integer.parseInt(portStr);
        } catch (NumberFormatException x) {
            throw new AgentConfigurationError(INVALID_JMXREMOTE_PORT, x, portStr);
        }
        if (port < 0) {
            throw new AgentConfigurationError(INVALID_JMXREMOTE_PORT, portStr);
        }

        // User can specify a port to be used to export rmi object,
        // in order to simplify firewall rules
        // if port is not specified random one will be allocated.
        int rmiPort = 0;
        String rmiPortStr = props.getProperty(PropertyNames.RMI_PORT);
        try {
            if (rmiPortStr != null) {
               rmiPort = Integer.parseInt(rmiPortStr);
            }
        } catch (NumberFormatException x) {
            throw new AgentConfigurationError(INVALID_JMXREMOTE_RMI_PORT, x, rmiPortStr);
        }
        if (rmiPort < 0) {
            throw new AgentConfigurationError(INVALID_JMXREMOTE_RMI_PORT, rmiPortStr);
        }

        // Do we use authentication?
        final String useAuthenticationStr =
                props.getProperty(PropertyNames.USE_AUTHENTICATION,
                DefaultValues.USE_AUTHENTICATION);
        final boolean useAuthentication =
                Boolean.valueOf(useAuthenticationStr).booleanValue();

        // Do we use SSL?
        final String useSslStr =
                props.getProperty(PropertyNames.USE_SSL,
                DefaultValues.USE_SSL);
        final boolean useSsl =
                Boolean.valueOf(useSslStr).booleanValue();

        // Do we use RMI Registry SSL?
        final String useRegistrySslStr =
                props.getProperty(PropertyNames.USE_REGISTRY_SSL,
                DefaultValues.USE_REGISTRY_SSL);
        final boolean useRegistrySsl =
                Boolean.valueOf(useRegistrySslStr).booleanValue();

        final String enabledCipherSuites =
                props.getProperty(PropertyNames.SSL_ENABLED_CIPHER_SUITES);
        String enabledCipherSuitesList[] = null;
        if (enabledCipherSuites != null) {
            StringTokenizer st = new StringTokenizer(enabledCipherSuites, ",");
            int tokens = st.countTokens();
            enabledCipherSuitesList = new String[tokens];
            for (int i = 0; i < tokens; i++) {
                enabledCipherSuitesList[i] = st.nextToken();
            }
        }

        final String enabledProtocols =
                props.getProperty(PropertyNames.SSL_ENABLED_PROTOCOLS);
        String enabledProtocolsList[] = null;
        if (enabledProtocols != null) {
            StringTokenizer st = new StringTokenizer(enabledProtocols, ",");
            int tokens = st.countTokens();
            enabledProtocolsList = new String[tokens];
            for (int i = 0; i < tokens; i++) {
                enabledProtocolsList[i] = st.nextToken();
            }
        }

        final String sslNeedClientAuthStr =
                props.getProperty(PropertyNames.SSL_NEED_CLIENT_AUTH,
                DefaultValues.SSL_NEED_CLIENT_AUTH);
        final boolean sslNeedClientAuth =
                Boolean.valueOf(sslNeedClientAuthStr).booleanValue();

        // Read SSL config file name
        final String sslConfigFileName =
                props.getProperty(PropertyNames.SSL_CONFIG_FILE_NAME);

        String loginConfigName = null;
        String passwordFileName = null;
        String accessFileName = null;

        // Initialize settings when authentication is active
        if (useAuthentication) {

            // Get non-default login configuration
            loginConfigName =
                    props.getProperty(PropertyNames.LOGIN_CONFIG_NAME);

            if (loginConfigName == null) {
                // Get password file
                passwordFileName =
                        props.getProperty(PropertyNames.PASSWORD_FILE_NAME,
                        getDefaultFileName(DefaultValues.PASSWORD_FILE_NAME));
                checkPasswordFile(passwordFileName);
            }

            // Get access file
            accessFileName = props.getProperty(PropertyNames.ACCESS_FILE_NAME,
                    getDefaultFileName(DefaultValues.ACCESS_FILE_NAME));
            checkAccessFile(accessFileName);
        }

        if (log.debugOn()) {
            log.debug("startRemoteConnectorServer",
                    Agent.getText("jmxremote.ConnectorBootstrap.starting") +
                    "\n\t" + PropertyNames.PORT + "=" + port +
                    "\n\t" + PropertyNames.RMI_PORT + "=" + rmiPort +
                    "\n\t" + PropertyNames.USE_SSL + "=" + useSsl +
                    "\n\t" + PropertyNames.USE_REGISTRY_SSL + "=" + useRegistrySsl +
                    "\n\t" + PropertyNames.SSL_CONFIG_FILE_NAME + "=" + sslConfigFileName +
                    "\n\t" + PropertyNames.SSL_ENABLED_CIPHER_SUITES + "=" +
                    enabledCipherSuites +
                    "\n\t" + PropertyNames.SSL_ENABLED_PROTOCOLS + "=" +
                    enabledProtocols +
                    "\n\t" + PropertyNames.SSL_NEED_CLIENT_AUTH + "=" +
                    sslNeedClientAuth +
                    "\n\t" + PropertyNames.USE_AUTHENTICATION + "=" +
                    useAuthentication +
                    (useAuthentication ? (loginConfigName == null ? ("\n\t" + PropertyNames.PASSWORD_FILE_NAME + "=" +
                    passwordFileName) : ("\n\t" + PropertyNames.LOGIN_CONFIG_NAME + "=" +
                    loginConfigName)) : "\n\t" +
                    Agent.getText("jmxremote.ConnectorBootstrap.noAuthentication")) +
                    (useAuthentication ? ("\n\t" + PropertyNames.ACCESS_FILE_NAME + "=" +
                    accessFileName) : "") +
                    "");
        }

        final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        JMXConnectorServer cs = null;
        JMXServiceURL url = null;
        try {
            final JMXConnectorServerData data = exportMBeanServer(
                    mbs, port, rmiPort, useSsl, useRegistrySsl,
                    sslConfigFileName, enabledCipherSuitesList,
                    enabledProtocolsList, sslNeedClientAuth,
                    useAuthentication, loginConfigName,
                    passwordFileName, accessFileName);
            cs = data.jmxConnectorServer;
            url = data.jmxRemoteURL;
            log.config("startRemoteConnectorServer",
                    Agent.getText("jmxremote.ConnectorBootstrap.ready",
                    url.toString()));
        } catch (Exception e) {
            throw new AgentConfigurationError(AGENT_EXCEPTION, e, e.toString());
        }
        try {
            // Export remote connector address and associated configuration
            // properties to the instrumentation buffer.
            Map<String, String> properties = new HashMap<>();
            properties.put("remoteAddress", url.toString());
            properties.put("authenticate", useAuthenticationStr);
            properties.put("ssl", useSslStr);
            properties.put("sslRegistry", useRegistrySslStr);
            properties.put("sslNeedClientAuth", sslNeedClientAuthStr);
            ConnectorAddressLink.exportRemote(properties);
        } catch (Exception e) {
            // Remote connector server started but unable to export remote
            // connector address and associated configuration properties to
            // the instrumentation buffer - non-fatal error.
            log.debug("startRemoteConnectorServer", e);
        }
        return cs;
    }

    /*
     * Creates and starts a RMI Connector Server for "local" monitoring
     * and management.
     */
    public static JMXConnectorServer startLocalConnectorServer() {
        // Ensure cryptographically strong random number generater used
        // to choose the object number - see java.rmi.server.ObjID
        System.setProperty("java.rmi.server.randomIDs", "true");

        // This RMI server should not keep the VM alive
        Map<String, Object> env = new HashMap<>();
        env.put(RMIExporter.EXPORTER_ATTRIBUTE, new PermanentExporter());

        // The local connector server need only be available via the
        // loopback connection.
        String localhost = "localhost";
        InetAddress lh = null;
        try {
            lh = InetAddress.getByName(localhost);
            localhost = lh.getHostAddress();
        } catch (UnknownHostException x) {
        }

        // localhost unknown or (somehow) didn't resolve to
        // a loopback address.
        if (lh == null || !lh.isLoopbackAddress()) {
            localhost = "127.0.0.1";
        }

        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        try {
            JMXServiceURL url = new JMXServiceURL("rmi", localhost, 0);
            // Do we accept connections from local interfaces only?
            Properties props = Agent.getManagementProperties();
            if (props ==  null) {
                props = new Properties();
            }
            String useLocalOnlyStr = props.getProperty(
                    PropertyNames.USE_LOCAL_ONLY, DefaultValues.USE_LOCAL_ONLY);
            boolean useLocalOnly = Boolean.valueOf(useLocalOnlyStr).booleanValue();
            if (useLocalOnly) {
                env.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE,
                        new LocalRMIServerSocketFactory());
            }
            JMXConnectorServer server =
                    JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
            server.start();
            return server;
        } catch (Exception e) {
            throw new AgentConfigurationError(AGENT_EXCEPTION, e, e.toString());
        }
    }

    private static void checkPasswordFile(String passwordFileName) {
        if (passwordFileName == null || passwordFileName.length() == 0) {
            throw new AgentConfigurationError(PASSWORD_FILE_NOT_SET);
        }
        File file = new File(passwordFileName);
        if (!file.exists()) {
            throw new AgentConfigurationError(PASSWORD_FILE_NOT_FOUND, passwordFileName);
        }

        if (!file.canRead()) {
            throw new AgentConfigurationError(PASSWORD_FILE_NOT_READABLE, passwordFileName);
        }

        FileSystem fs = FileSystem.open();
        try {
            if (fs.supportsFileSecurity(file)) {
                if (!fs.isAccessUserOnly(file)) {
                    final String msg = Agent.getText("jmxremote.ConnectorBootstrap.password.readonly",
                            passwordFileName);
                    log.config("startRemoteConnectorServer", msg);
                    throw new AgentConfigurationError(PASSWORD_FILE_ACCESS_NOT_RESTRICTED,
                            passwordFileName);
                }
            }
        } catch (IOException e) {
            throw new AgentConfigurationError(PASSWORD_FILE_READ_FAILED,
                    e, passwordFileName);
        }
    }

    private static void checkAccessFile(String accessFileName) {
        if (accessFileName == null || accessFileName.length() == 0) {
            throw new AgentConfigurationError(ACCESS_FILE_NOT_SET);
        }
        File file = new File(accessFileName);
        if (!file.exists()) {
            throw new AgentConfigurationError(ACCESS_FILE_NOT_FOUND, accessFileName);
        }

        if (!file.canRead()) {
            throw new AgentConfigurationError(ACCESS_FILE_NOT_READABLE, accessFileName);
        }
    }

    private static void checkRestrictedFile(String restrictedFileName) {
        if (restrictedFileName == null || restrictedFileName.length() == 0) {
            throw new AgentConfigurationError(FILE_NOT_SET);
        }
        File file = new File(restrictedFileName);
        if (!file.exists()) {
            throw new AgentConfigurationError(FILE_NOT_FOUND, restrictedFileName);
        }
        if (!file.canRead()) {
            throw new AgentConfigurationError(FILE_NOT_READABLE, restrictedFileName);
        }
        FileSystem fs = FileSystem.open();
        try {
            if (fs.supportsFileSecurity(file)) {
                if (!fs.isAccessUserOnly(file)) {
                    final String msg = Agent.getText(
                            "jmxremote.ConnectorBootstrap.file.readonly",
                            restrictedFileName);
                    log.config("startRemoteConnectorServer", msg);
                    throw new AgentConfigurationError(
                            FILE_ACCESS_NOT_RESTRICTED, restrictedFileName);
                }
            }
        } catch (IOException e) {
            throw new AgentConfigurationError(
                    FILE_READ_FAILED, e, restrictedFileName);
        }
    }

    /**
     * Compute the full path name for a default file.
     * @param basename basename (with extension) of the default file.
     * @return ${JRE}/lib/management/${basename}
     **/
    private static String getDefaultFileName(String basename) {
        final String fileSeparator = File.separator;
        return System.getProperty("java.home") + fileSeparator + "lib" +
                fileSeparator + "management" + fileSeparator +
                basename;
    }

    private static SslRMIServerSocketFactory createSslRMIServerSocketFactory(
            String sslConfigFileName,
            String[] enabledCipherSuites,
            String[] enabledProtocols,
            boolean sslNeedClientAuth) {
        if (sslConfigFileName == null) {
            return new SslRMIServerSocketFactory(
                    enabledCipherSuites,
                    enabledProtocols,
                    sslNeedClientAuth);
        } else {
            checkRestrictedFile(sslConfigFileName);
            try {
                // Load the SSL keystore properties from the config file
                Properties p = new Properties();
                try (InputStream in = new FileInputStream(sslConfigFileName)) {
                    BufferedInputStream bin = new BufferedInputStream(in);
                    p.load(bin);
                }
                String keyStore =
                        p.getProperty("javax.net.ssl.keyStore");
                String keyStorePassword =
                        p.getProperty("javax.net.ssl.keyStorePassword", "");
                String trustStore =
                        p.getProperty("javax.net.ssl.trustStore");
                String trustStorePassword =
                        p.getProperty("javax.net.ssl.trustStorePassword", "");

                char[] keyStorePasswd = null;
                if (keyStorePassword.length() != 0) {
                    keyStorePasswd = keyStorePassword.toCharArray();
                }

                char[] trustStorePasswd = null;
                if (trustStorePassword.length() != 0) {
                    trustStorePasswd = trustStorePassword.toCharArray();
                }

                KeyStore ks = null;
                if (keyStore != null) {
                    ks = KeyStore.getInstance(KeyStore.getDefaultType());
                    try (FileInputStream ksfis = new FileInputStream(keyStore)) {
                        ks.load(ksfis, keyStorePasswd);
                    }
                }
                KeyManagerFactory kmf = KeyManagerFactory.getInstance(
                        KeyManagerFactory.getDefaultAlgorithm());
                kmf.init(ks, keyStorePasswd);

                KeyStore ts = null;
                if (trustStore != null) {
                    ts = KeyStore.getInstance(KeyStore.getDefaultType());
                    try (FileInputStream tsfis = new FileInputStream(trustStore)) {
                        ts.load(tsfis, trustStorePasswd);
                    }
                }
                TrustManagerFactory tmf = TrustManagerFactory.getInstance(
                        TrustManagerFactory.getDefaultAlgorithm());
                tmf.init(ts);

                SSLContext ctx = SSLContext.getInstance("SSL");
                ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

                return new SslRMIServerSocketFactory(
                        ctx,
                        enabledCipherSuites,
                        enabledProtocols,
                        sslNeedClientAuth);
            } catch (Exception e) {
                throw new AgentConfigurationError(AGENT_EXCEPTION, e, e.toString());
            }
        }
    }

    private static JMXConnectorServerData exportMBeanServer(
            MBeanServer mbs,
            int port,
            int rmiPort,
            boolean useSsl,
            boolean useRegistrySsl,
            String sslConfigFileName,
            String[] enabledCipherSuites,
            String[] enabledProtocols,
            boolean sslNeedClientAuth,
            boolean useAuthentication,
            String loginConfigName,
            String passwordFileName,
            String accessFileName)
            throws IOException, MalformedURLException {

        /* Make sure we use non-guessable RMI object IDs.  Otherwise
         * attackers could hijack open connections by guessing their
         * IDs.  */
        System.setProperty("java.rmi.server.randomIDs", "true");

        JMXServiceURL url = new JMXServiceURL("rmi", null, rmiPort);

        Map<String, Object> env = new HashMap<>();

        PermanentExporter exporter = new PermanentExporter();

        env.put(RMIExporter.EXPORTER_ATTRIBUTE, exporter);

        if (useAuthentication) {
            if (loginConfigName != null) {
                env.put("jmx.remote.x.login.config", loginConfigName);
            }
            if (passwordFileName != null) {
                env.put("jmx.remote.x.password.file", passwordFileName);
            }

            env.put("jmx.remote.x.access.file", accessFileName);

            if (env.get("jmx.remote.x.password.file") != null ||
                    env.get("jmx.remote.x.login.config") != null) {
                env.put(JMXConnectorServer.AUTHENTICATOR,
                        new AccessFileCheckerAuthenticator(env));
            }
        }

        RMIClientSocketFactory csf = null;
        RMIServerSocketFactory ssf = null;

        if (useSsl || useRegistrySsl) {
            csf = new SslRMIClientSocketFactory();
            ssf = createSslRMIServerSocketFactory(
                    sslConfigFileName, enabledCipherSuites,
                    enabledProtocols, sslNeedClientAuth);
        }

        if (useSsl) {
            env.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE,
                    csf);
            env.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE,
                    ssf);
        }

        JMXConnectorServer connServer = null;
        try {
            connServer =
                    JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
            connServer.start();
        } catch (IOException e) {
            if (connServer == null) {
                throw new AgentConfigurationError(CONNECTOR_SERVER_IO_ERROR,
                        e, url.toString());
            } else {
                throw new AgentConfigurationError(CONNECTOR_SERVER_IO_ERROR,
                        e, connServer.getAddress().toString());
            }
        }

        if (useRegistrySsl) {
            registry =
                    new SingleEntryRegistry(port, csf, ssf,
                    "jmxrmi", exporter.firstExported);
        } else {
            registry =
                    new SingleEntryRegistry(port,
                    "jmxrmi", exporter.firstExported);
        }

        int registryPort =
            ((UnicastRef) ((RemoteObject) registry).getRef()).getLiveRef().getPort();
        String jmxUrlStr =  String.format("service:jmx:rmi:///jndi/rmi://%s:%d/jmxrmi",
                                           url.getHost(), registryPort);
        JMXServiceURL remoteURL = new JMXServiceURL(jmxUrlStr);

        /* Our exporter remembers the first object it was asked to
        export, which will be an RMIServerImpl appropriate for
        publication in our special registry.  We could
        alternatively have constructed the RMIServerImpl explicitly
        and then constructed an RMIConnectorServer passing it as a
        parameter, but that's quite a bit more verbose and pulls in
        lots of knowledge of the RMI connector.  */

        return new JMXConnectorServerData(connServer, remoteURL);
    }

    /**
     * This class cannot be instantiated.
     **/
    private ConnectorBootstrap() {
    }

    private static final ClassLogger log =
        new ClassLogger(ConnectorBootstrap.class.getPackage().getName(),
                        "ConnectorBootstrap");
}


text:
* C18 compiler
* pkg-config
* SDL2

## macOS

Install pkg-config using brew, or use `-LSDL2` in the Makefile instead of using pkg-config.


text:
package com.twitter.algebird
package benchmark

import org.openjdk.jmh.annotations._

object BloomFilterDistanceBenchmark {

  def toSparse[A](bf: BF[A]): BFSparse[A] = bf match {
    case BFZero(hashes, width) => BFSparse(hashes, RichCBitSet(), width)
    case BFItem(item, hashes, width) =>
      BFSparse(hashes, RichCBitSet.fromArray(hashes(item)), width)
    case bfs @ BFSparse(_, _, _) => bfs
    case BFInstance(hashes, bitset, width) =>
      BFSparse(hashes, RichCBitSet.fromBitSet(bitset), width)
  }

  def toDense[A](bf: BF[A]): BFInstance[A] = bf match {
    case BFZero(hashes, width) => BFInstance.empty[A](hashes, width)
    case BFItem(item, hashes, width) =>
      val bs = LongBitSet.empty(width)
      bs += hashes(item)
      BFInstance(hashes, bs.toBitSetNoCopy, width)
    case bfs @ BFSparse(hashes, bitset, width)   => bfs.dense
    case bfi @ BFInstance(hashes, bitset, width) => bfi
  }

  @State(Scope.Benchmark)
  class BloomFilterState {

    val nbrOfElements: Int = 1000
    val falsePositiveRate = 0.01

    def randomElements =
      BloomFilterCreateBenchmark.createRandomString(nbrOfElements, 10)

    val emptyBF1: BF[String] =
      BloomFilter[String](nbrOfElements, falsePositiveRate).zero
    val emptyBF2: BF[String] =
      BloomFilter[String](nbrOfElements, falsePositiveRate).zero

    val sparseBF1: BF[String] =
      toSparse(
        BloomFilter[String](nbrOfElements, falsePositiveRate)
          .create(randomElements: _*))
    val sparesBF2: BF[String] =
      toSparse(
        BloomFilter[String](nbrOfElements, falsePositiveRate)
          .create(randomElements: _*))

    val denseBF1: BF[String] = toDense(
      BloomFilter[String](nbrOfElements, falsePositiveRate)
        .create(randomElements: _*))
    val denseBF2: BF[String] = toDense(
      BloomFilter[String](nbrOfElements, falsePositiveRate)
        .create(randomElements: _*))

  }
}

class BloomFilterDistanceBenchmark {

  import BloomFilterDistanceBenchmark._

  @Benchmark
  def distanceOfEmptyVsEmpty(bloomFilterState: BloomFilterState): Int =
    bloomFilterState.emptyBF1.hammingDistance(bloomFilterState.emptyBF2)

  @Benchmark
  def distanceOfEmptyVsSparse(bloomFilterState: BloomFilterState): Int =
    bloomFilterState.emptyBF1.hammingDistance(bloomFilterState.sparseBF1)

  @Benchmark
  def distanceOfEmptyVsDense(bloomFilterState: BloomFilterState): Int =
    bloomFilterState.emptyBF1.hammingDistance(bloomFilterState.denseBF1)

  @Benchmark
  def distanceOfSparseVsSparse(bloomFilterState: BloomFilterState): Int =
    bloomFilterState.sparseBF1.hammingDistance(bloomFilterState.sparesBF2)

  @Benchmark
  def distanceOfSparseVsDense(bloomFilterState: BloomFilterState): Int =
    bloomFilterState.sparseBF1.hammingDistance(bloomFilterState.denseBF1)

  @Benchmark
  def distanceOfDenseVsDense(bloomFilterState: BloomFilterState): Int =
    bloomFilterState.denseBF1.hammingDistance(bloomFilterState.denseBF1)

}


text:
<?xml version='1.0' encoding='ISO-8859-1' ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
  <appender name="CONSOLE-WARN" class="org.apache.log4j.ConsoleAppender">
    <param name="target" value="System.err"/>
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="[%7r] %6p - %30.30c - %m \n"/>
    </layout>
    <filter class="org.apache.log4j.varia.LevelRangeFilter">
      <param name="LevelMin" value="WARN"/>
    </filter>
  </appender>

  <appender name="CONSOLE-DEBUG" class="org.apache.log4j.ConsoleAppender">
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="[%7r] %6p - %30.30c - %m \n"/>
    </layout>
    <filter class="org.apache.log4j.varia.LevelRangeFilter">
      <param name="LevelMin" value="DEBUG"/>
      <param name="LevelMax" value="DEBUG"/>
    </filter>
  </appender>

  <appender name="CONSOLE-ALL" class="org.apache.log4j.ConsoleAppender">
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="[%7r] %6p - %30.30c - %m \n"/>
    </layout>
  </appender>

  <appender name="DIALOG" class="com.intellij.diagnostic.DialogAppender">
      <filter class="org.apache.log4j.varia.LevelRangeFilter">
        <param name="LevelMin" value="INFO"/>
      </filter>
  </appender>

  <appender name="FILE" class="org.apache.log4j.RollingFileAppender">
    <param name="MaxFileSize" value="1Mb"/>
    <param name="MaxBackupIndex" value="12"/>
    <param name="file" value="$LOG_DIR$/idea.log"/>
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="%d [%7r] %6p - %30.30c - %m \n"/>
    </layout>
  </appender>

  <appender name="INCOMING_CHANGES_FILE" class="org.apache.log4j.RollingFileAppender">
    <param name="MaxFileSize" value="1Mb"/>
    <param name="MaxBackupIndex" value="12"/>
    <param name="file" value="$LOG_DIR$/incoming.log"/>
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="%d [%7r] %6p - %30.30c - %m \n"/>
    </layout>
  </appender>

  <root>
    <priority value="INFO"/>
    <appender-ref ref="DIALOG"/>
    <appender-ref ref="CONSOLE-WARN"/>    <!-- $COMMENT_LINE_FOR_TEST_MODE$ If a line contains such macro, it will be deleted then we start IDEA in JUnit Test mode -->
    <appender-ref ref="FILE"/>
  </root>
</log4j:configuration>


text:
#include <iostream>
#include <fstream>
#include <sstream>
#include <conio.h>
#include <boost/program_options.hpp>
#include "input_data.h"

namespace po = boost::program_options;

struct ParamIsNotSet {
    std::string param;
    ParamIsNotSet (std::string param)
        : param(param) {}
};

struct ParamIsNotPositive {
    std::string param;
    ParamIsNotPositive (std::string param)
        : param(param) {}
};

void get_double_param (const po::variables_map &vm, const char *param,
    real_t &val)
{
    if (vm.count(param))
        val = vm[param].as<double>();
    else
        throw ParamIsNotSet(param);
}

void get_positive_double_param (const po::variables_map &vm,
    const char *param, real_t &val)
{
    if (vm.count(param)) {
        val = vm[param].as<double>();
        if (val < 0)
            throw ParamIsNotPositive(param);
    }
    else
        throw ParamIsNotSet(param);
}

void get_int_param (const po::variables_map &vm, const char *param, int &val)
{
    if (vm.count(param)) {
        val = vm[param].as<int>();
        if (val < 0)
            throw ParamIsNotPositive(param);
    }
    else
        throw ParamIsNotSet(param);
}

void get_range (const po::variables_map &vm, const char *param,
    ParamRange &range)
{
    std::string s = vm[param].as<std::string>();
    std::istringstream iss(s);
    std::string str;
    iss >> range.left >> str >> range.right;
    if (str != "..")
        throw "Incorrect range";

   /*
    std::string param_name = std::string(param) + "_left";
    get_double_param(vm, param_name.c_str(), range.left);
    param_name = std::string(param) + "_right";
    get_double_param(vm, param_name.c_str(), range.right);
    */

    std::string param_name = std::string(param) + "_eps";
    get_positive_double_param(vm, param_name.c_str(), range.eps);
}

void get_positive_range (const po::variables_map &vm, const char *param,
    ParamRange &range)
{
    get_range(vm, param, range);
    if (range.left < 0 || range.right < 0)
        throw ParamIsNotPositive(param);
}

void print_error (const std::string msg)
{
    std::cerr << msg << "\n";
    getch();
    exit(1);
}

real_t calc_z (const ModelParameters& model_parameters)
{
    return model_parameters.nu * (1 + 3.762 * 28. / 32.);
}

InputParam read_input_param ()
{
    try {
        po::options_description desc("Input parameters");
        desc.add_options()
            ("T0", po::value<double>(), "T0")
            ("D", po::value<double>(), "D")
            ("nu", po::value<double>(), "nu")
            ("A", po::value<std::string>(), "A")
            ("A_eps", po::value<double>(), "A_eps")
            ("E/R", po::value<std::string>(), "E/R")
            ("E/R_eps", po::value<double>(), "E/R_eps")
            ("alpha", po::value<std::string>(), "alpha")
            ("alpha_eps", po::value<double>(), "alpha_eps")
            ("beta", po::value<std::string>(), "beta")
            ("beta_eps", po::value<double>(), "beta_eps")
            ("n", po::value<std::string>(), "n")
            ("n_eps", po::value<double>(), "n_eps")
            ("F_min", po::value<double>(), "F_min")
        ;

        po::variables_map vm;
        std::ifstream ifs(file_input_param.c_str());
        if (!ifs)
            print_error("Can not open input file: " + file_input_param);
        else {
            po::store(parse_config_file(ifs, desc), vm);
            po::notify(vm);
        }

        InputParam input_param;
        get_positive_double_param(vm, "T0", input_param.model_parameters.T0);
        get_positive_double_param(vm, "D", input_param.model_parameters.D);
        get_positive_double_param(vm, "nu", input_param.model_parameters.nu);
        get_positive_range(vm, "A", input_param.params_ranges[0]);
        get_positive_range(vm, "E/R", input_param.params_ranges[1]);
        get_range(vm, "alpha", input_param.params_ranges[2]);
        get_range(vm, "beta", input_param.params_ranges[3]);
        get_range(vm, "n", input_param.params_ranges[4]);
        get_positive_double_param(vm, "F_min", input_param.F_min);
        return input_param;
    }
    catch (ParamIsNotSet e) {
        print_error("Parameter \"" + e.param + "\" is not specified");
    }
    catch (ParamIsNotPositive e) {
        print_error("Parameter \"" + e.param + "\" is not positive");
    }
    catch(std::exception& e) {
        print_error(std::string("error: ") + e.what());
    }
    catch(...) {
        print_error("Exception of unknown type!");
    }
}

Config read_config ()
{
    try {
        po::options_description desc("Configuration parameters");
        desc.add_options()
            ("delta_A", po::value<double>(), "delta_A")
            ("delta_E/R", po::value<double>(), "delta_E/R")
            ("delta_alpha", po::value<double>(), "delta_alpha")
            ("delta_beta", po::value<double>(), "delta_beta")
            ("delta_n", po::value<double>(), "delta_n")
            ("N_trapezoid", po::value<int>(), "N_trapezoid")
            ("u_eps", po::value<double>(), "u_eps")
            ("u_init", po::value<double>(), "u_init")
            ("max_u", po::value<double>(), "max_u")
            ("max_speed", po::value<double>(), "max_speed")
            ("lambda_threshold", po::value<int>(), "lambda_threshold")
            ("lambda_decr_max", po::value<int>(), "lambda_decr_max")
            ("gradient_descent_step_size", po::value<double>(), "gradient_descent_step_size")
            ("gradient_descent_steps", po::value<int>(), "gradient_descent_steps")
        ;

        po::variables_map vm;
        std::ifstream ifs(file_config.c_str());
        if (!ifs)
            print_error("Can not open input file: " + file_config);
        else {
            po::store(parse_config_file(ifs, desc), vm);
            po::notify(vm);
        }

        Config config;
        get_positive_double_param(vm, "delta_A", config.delta_A);
        get_positive_double_param(vm, "delta_E/R", config.delta_E_div_R);
        get_positive_double_param(vm, "delta_alpha", config.delta_alpha);
        get_positive_double_param(vm, "delta_beta", config.delta_beta);
        get_positive_double_param(vm, "delta_n", config.delta_n);
        get_int_param(vm, "N_trapezoid", config.N_trapezoid);
        get_positive_double_param(vm, "u_eps", config.u_eps);
        get_positive_double_param(vm, "u_init", config.u_init);
        get_positive_double_param(vm, "max_u", config.max_u);
        get_positive_double_param(vm, "max_speed", config.max_speed);
        get_int_param(vm, "lambda_threshold", config.lambda_threshold);
        get_int_param(vm, "lambda_decr_max", config.lambda_decr_max);
        get_positive_double_param(vm, "gradient_descent_step_size",
            config.gradient_descent_step_size);
        get_int_param(vm, "gradient_descent_steps", config.gradient_descent_steps);
        return config;
    }
    catch (ParamIsNotSet e) {
        print_error("Parameter \"" + e.param + "\" is not specified");
    }
    catch (ParamIsNotPositive e) {
        print_error("Parameter \"" + e.param + "\" is not positive");
    }
    catch(std::exception& e) {
        print_error(std::string("error: ") + e.what());
    }
    catch(...) {
        print_error("Exception of unknown type!");
    }
}


text:
package com.dd.plist;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

/**
 * Represents a date.
 *
 * @author Daniel Dreibrodt
 */
public class NSDate extends NSObject {

    private Date date;

    // EPOCH = new SimpleDateFormat("yyyy MM dd zzz").parse("2001 01 01 GMT").getTime();
    // ...but that's annoying in a static initializer because it can throw exceptions, ick.
    // So we just hardcode the correct value.
    private final static long EPOCH = 978307200000L;

    private static final SimpleDateFormat sdfDefault = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    private static final SimpleDateFormat sdfGnuStep = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");

    static {
        sdfDefault.setTimeZone(TimeZone.getTimeZone("GMT"));
        sdfGnuStep.setTimeZone(TimeZone.getTimeZone("GMT"));
    }

    /**
     * Parses the XML date string and creates a Java Date object from it.
     * This function is synchronized as SimpleDateFormat is not thread-safe.
     *
     * @param textRepresentation The date string as found in the XML property list
     * @return The parsed Date
     * @throws java.text.ParseException If the given string cannot be parsed.
     * @see java.text.SimpleDateFormat#parse(String)
     */
    private static synchronized Date parseDateString(String textRepresentation) throws ParseException {
        try {
            return sdfDefault.parse(textRepresentation);
        } catch (ParseException ex) {
            return sdfGnuStep.parse(textRepresentation);
        }
    }

    /**
     * Generates a String representation of a Java Date object. The string
     * is formatted according to the specification for XML property list dates.
     *
     * @param date The date which should be represented.
     * @return The string representation of the date.
     */
    private static synchronized String makeDateString(Date date) {
        return sdfDefault.format(date);
    }

    /**
     * Generates a String representation of a Java Date object. The string
     * is formatted according to the specification for GnuStep ASCII property
     * list dates.
     *
     * @param date The date which should be represented.
     * @return The string representation of the date.
     */
    private static synchronized String makeDateStringGnuStep(Date date) {
        return sdfGnuStep.format(date);
    }

    /**
     * Creates a date from its binary representation.
     *
     * @param bytes The date bytes
     */
    public NSDate(byte[] bytes) {
        //dates are 8 byte big-endian double, seconds since the epoch
        date = new Date(EPOCH + (long) (1000 * BinaryPropertyListParser.parseDouble(bytes)));
    }

    /**
     * Parses a date from its textual representation.
     * That representation has the following pattern: yyyy-MM-dd'T'HH:mm:ss'Z'
     *
     * @param textRepresentation The textual representation of the date (ISO 8601 format)
     * @throws java.text.ParseException When the date could not be parsed, i.e. it does not match the expected pattern.
     */
    public NSDate(String textRepresentation) throws ParseException {
        date = parseDateString(textRepresentation);
    }

    /**
     * Creates a NSDate from a Java Date
     *
     * @param d The date
     */
    public NSDate(Date d) {
        if (d == null)
            throw new IllegalArgumentException("Date cannot be null");
        date = d;
    }

    /**
     * Gets the date.
     *
     * @return The date.
     */
    public Date getDate() {
        return date;
    }

    @Override
    public boolean equals(Object obj) {
        return obj.getClass().equals(getClass()) && date.equals(((NSDate) obj).getDate());
    }

    @Override
    public int hashCode() {
        return date.hashCode();
    }

    @Override
    void toXML(StringBuilder xml, int level) {
        indent(xml, level);
        xml.append("<date>");
        xml.append(makeDateString(date));
        xml.append("</date>");
    }

    @Override
    public void toBinary(BinaryPropertyListWriter out) throws IOException {
        out.write(0x33);
        out.writeDouble((date.getTime() - EPOCH) / 1000.0);
    }

    /**
     * Generates a string representation of the date.
     *
     * @return A string representation of the date.
     * @see java.util.Date#toString()
     */
    @Override
    public String toString() {
        return date.toString();
    }

    @Override
    protected void toASCII(StringBuilder ascii, int level) {
        indent(ascii, level);
        ascii.append("\"");
        ascii.append(makeDateString(date));
        ascii.append("\"");
    }

    @Override
    protected void toASCIIGnuStep(StringBuilder ascii, int level) {
        indent(ascii, level);
        ascii.append("<*D");
        ascii.append(makeDateStringGnuStep(date));
        ascii.append(">");
    }
}


text:
/* This is stub file for gapi.client.{{=it.name}} definition tests */
/* IMPORTANT.
* This file was automatically generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually.
* In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator
**/
gapi.load('client', () => {
    /** now we can use gapi.client */
    gapi.client.load('searchconsole', 'v1', () => {
        /** now we can use gapi.client.searchconsole */

        run();
    });

    async function run() {
    }
});


text:
.. _alexa-reply:

The ``AlexaReply`` Object
=========================

.. js:class:: AlexaReply()

  ``AlexaReply`` object is used by the framework to render Alexa responses, it takes all of your ``statements``, ``cards`` and ``directives`` and generates a proper json response for Alexa

  .. js:function:: Reply.fulfillIntent(canFulfill)

    Fulfills the request in the response object

    :param canFulfill: A string with possible values: YES | NO | MAYBE to fulfill request

  .. js:function:: Reply.fulfillSlot(slotName, canUnderstand, canFulfill)

    Fulfills the slot with fulfill and understand values

    :param slotName: A string with the slot to fulfill
    :param canUnderstand: A string with possible values: YES | NO | MAYBE that indicates slot understanding
    :param canFulfill: A string with possible values: YES | NO that indicates slot fulfillment


text:
from api.models import *
from api.serializers import *
from django.contrib.auth.models import User
from django.shortcuts import render
from rest_framework import viewsets
from rest_framework.views import APIView
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.response import Response
from rest_framework.views import APIView
from django.contrib.auth import authenticate, login, logout
from rest_framework import status
from rest_framework_json_api.views import RelationshipView
from rest_framework_json_api import serializers

class ChallengeViewSet(viewsets.ModelViewSet):
  """
  Challenge APIView
  """
  # TODO: Update permissions
  permission_classes = (AllowAny,)
  queryset = Challenge.objects.all()
  serializer_class = ChallengeSerializer


text:
	<button class="btn btn-default dropdown-toggle navbar-btn" type="button" id="dd-btn-download" data-toggle="dropdown">Downloads </button>

Android SDK

AngularJS

iOS SDK

Javascript SDK

Titanium

Windows Phone