text:
> Backpack map component.

Requires **React 16.8+**

## Installation

Check the main [Readme](https://github.com/skyscanner/backpack#usage) for a complete installation guide.

## Usage

```js
import React from 'react';
import BpkText from '@skyscanner/backpack-web/bpk-component-text';
import { withRtlSupport } from '@skyscanner/backpack-web/bpk-component-icon';
import LandmarkIconSm from '@skyscanner/backpack-web/bpk-component-icon/sm/landmark';
import BpkMap, {
  BpkIconMarker,
  BpkOverlayView,
} from '@skyscanner/backpack-web/bpk-component-map';

const AlignedLandmarkIconSm = withRtlSupport(LandmarkIconSm);

export default () => (
  <BpkMap
    zoom={15}
    showControls={false}
    panEnabled={false}
    center={{
      latitude: 27.9881,
      longitude: 86.925,
    }}
  >
    <BpkIconMarker
      icon={<AlignedLandmarkIconSm />}
      position={{ latitude: 27.9881, longitude: 86.925 }}
      onClick={() => {}}
    />
    <BpkIconMarker
      icon={<AlignedLandmarkIconSm />}
      position={{ latitude: 27.9881, longitude: 86.925 }}
      onClick={() => {}}
      selected
    />
    <BpkIconMarker
      icon={<AlignedLandmarkIconSm />}
      position={{ latitude: 27.9881, longitude: 86.927 }}
      onClick={() => {}}
      disabled
    />
    <BpkOverlayView position={{ latitude: 27.9881, longitude: 86.925 }}>
      <BpkText>Shibuya Crossing</BpkText>
    </BpkOverlayView>
  </BpkMap>
);
```

### BpkPriceMarker

Price markers are used to display clickable prices on a map.

```js
import React from 'react';
import BpkMap, { BpkPriceMarker, PRICE_MARKER_STATUSES } from '@skyscanner/backpack-web/bpk-component-map';

export default () => (
  <BpkMap
    zoom={15}
    showControls={false}
    panEnabled={false}
    center={{
      latitude: 27.9881,
      longitude: 86.925,
    }}
  >
    <BpkPriceMarker
      label="£120"
      position={{ latitude: 27.9881, longitude: 86.925 }}
      onClick={() => {
        console.log("Price marker pressed.")
      }}
      status={PRICE_MARKER_STATUSES.focused}
    />
    <BpkPriceMarker
      label="£120"
      position={{ latitude: 27.9881, longitude: 86.925 }}
      onClick={() => {
        console.log("Price marker pressed.")
      }}
      status={PRICE_MARKER_STATUSES.viewed}
    />
  </BpkMap>
);
```

## Accompanying HOCs

### withGoogleMapsScript

`withGoogleMapsScript` is a HOC that loads the Google Maps JavaScript, then loads the map. This is useful for when you don't already have the Google Maps JavaScript loaded.

If you intend to include multiple maps on one page, it's better to load the Google Maps JavaScript in this HOC, as it ensures that script will not be re-downloaded every time it's used.

```js
import React from 'react';
import BpkMap, { withGoogleMapsScript } from '@skyscanner/backpack-web/bpk-component-map';

const BpkMapWithScript = withGoogleMapsScript(BpkMap);

export default () => (
  <BpkMapWithScript
    googleMapsApiKey='YOUR_API_KEY'
    zoom={15}
    center={{
      latitude: 27.9881,
      longitude: 86.925,
    }}
    showControls={false}
    panEnabled={false}
  />
);
```

## Props

### BpkMap

| Property              | PropType                                                                                | Required | Default Value                    |
| --------------------- | ----------------------------------------------------------------- | -------- | -------------------------------- |
| bounds                | shape({north: number, east: number, south: number, west: number}) | false    | null                             |
| center                | shape({latitude: number, longitude: number})                      | false    | null                             |
| className             | string                                                            | false    | null                             |
| greedyGestureHandling | bool                                                              | false    | false                            |
| mapOptionStyles       | array                                                             | false    | null                             |
| mapRef                | func                                                              | false    | null                             |
| onRegionChange        | func                                                              | false    | null                             |
| onZoom                | func                                                              | false    | null                             |
| onTilesLoaded         | func                                                              | false    | null                             |
| panEnabled            | bool                                                              | false    | true                             |
| showControls          | bool                                                              | false    | true                             |
| zoom                  | number                                                            | false    | 15                               |

Note: One of `bounds` and `center` must be provided.

#### withGoogleMapsScript

When using `withGoogleMapsScript`, some additional props are available:

| Property                  | PropType | Required | Default Value                     |
| ------------------------- | -------- | -------- | --------------------------------- |
| googleMapsApiKey          | string   | true     | -                                 |
| libraries                 | array    | false    | ['geometry', 'drawing', 'places'] |
| loadingElement            | node     | false    | BpkSpinner                        |
| preventGoogleFontsLoading | bool     | false    | false                             |

### BpkIconMarker

| Property       | PropType                                     | Required | Default Value        |
| -------------- | -------------------------------------------- | -------- | -------------------- |
| icon           | node                                         | true     | -                    |
| position       | shape({latitude: number, longitude: number}) | true     | -                    |
| className      | string                                       | false    | null                 |
| disabled       | bool                                         | false    | false                |
| onClick        | func                                         | false    | null                 |
| selected       | bool                                         | false    | false                |
| buttonProps    | object                                       | false    | null                 |

#### `icon`

`BpkIconMarker` only supports small icons from the Backpack icon set. Large icons should not be used with `BpkIconMarker`.

### BpkPriceMarker

| Property       | PropType                                     | Required | Default Value |
| -------------- | -------------------------------------------- | -------- | ------------- |
| label          | string                                       | true     | -             |
| position       | shape({latitude: number, longitude: number}) | true     | -             |
| arrowClassName | string                                       | false    | null          |
| className      | string                                       | false    | null          |
| disabled       | bool                                         | false    | false         |
| onClick        | func                                         | false    | null          |
| status         | oneOf(`PRICE_MARKER_STATUSES.default`, `PRICE_MARKER_STATUSES.focused`, `PRICE_MARKER_STATUSES.viewed`)                                        | false    | `PRICE_MARKER_STATUSES.default`             |
| buttonProps    | object                                       | false    | null          |

### BpkOverlayView

| Property | PropType                                     | Required | Default Value |
| -------- | -------------------------------------------- | -------- | ------------- |
| children | node                                         | true     | -             |
| position | shape({latitude: number, longitude: number}) | true     | -             |

## Theme Props

Icon markers:

- `iconMarkerDefaultBackgroundColor`
- `iconMarkerDefaultSelectedColor`
- `iconMarkerDefaultDisabledBackgroundColor`
- `iconMarkerDefaultDisabledColor`

Price markers:

- `priceMarkerBackgroundColor`

- `priceMarkerSelectedBorderColor`
- `priceMarkerSelectedColor`

- `priceMarkerViewedBackgroundColor`
- `priceMarkerViewedBorderColor`
- `priceMarkerViewedColor`


text:
$(document).ready(function(){
    if(!$('#tokenatt').children().length ) {
        alert(attributesMappedText);
    }
    var height = $(document).height();
    var width = $(document).width();
    var tokencurrentarray = {};
    if($("#overwrite").is(':checked')) {var attoverwrite=true;} else {var attoverwrite=false;}
    if($("#overwriteman").is(':checked')) {var attoverwriteman=true;} else {var attoverwriteman=false;}
    if($("#createautomap").is(':checked')) {var attcreateautomap=true;} else {var attcreateautomap=false;}

    var headingHeight = 0;
    $('.attribute-column .heading').each(function(i) {
        if($(this).height() > headingHeight) {
            headingHeight = $(this).height();
        }
    });
    $('.attribute-column .heading').height(headingHeight);

    function adjustHeights() {
        $('.attribute-column, .droppable').css({ 'height': 'auto' });
        $('.attribute-column').height($('.draggable-container').height());

        var ncHeadingHeight = $('#newcreated .heading').outerHeight();
        $('.newcreate').css({
            'height':$('#newcreated').height()-ncHeadingHeight-5
        });
        var taHeadingHeight = $('#tokenattribute .heading').outerHeight();
        $('#tokenatt').css({
            'height':$('#tokenattribute').height()-taHeadingHeight-5
        });
    }

    adjustHeights();

    // Make the items draggable
    $('.draggable').draggable({
        revert: "invalid",
        appendTo: "body",
        containment: $('.draggable-container'),
        zindex: 150,
        opacity: 0.75
    });

    // Set the targets for the draggables
    $('.droppable').droppable({
        hoverClass: 'target-hover',
        accept: '.draggable',
        over: function(event, ui) {
            adjustHeights();
        },
        drop: function(event, ui) {

            // Physically  move the draggable to the target (the plugin just visually moves it)
            // Need to use a clone for this to fake out iPad
            var newDraggable = $(ui.draggable).clone();
            $(newDraggable).appendTo(this);
            $(ui.draggable).remove();

            // Clean up the new clone
            $(newDraggable).removeClass('ui-draggable-dragging').css({
                'left':'0',
                'z-index': '',
                'opacity': 1
            }).animate({
                top: ''
            }, 300).draggable({
                revert: "invalid",
                appendTo: "body",
                containment: $('.draggable-container'),
                opacity: 0.75
            });

            // Remove the text input if dropped out of the new attributes column
            if(!$(this).hasClass('newcreate') && $('input[type="text"]', newDraggable).length > 0) {
                $('input[type="text"]', newDraggable).remove();
                $(newDraggable).text($(newDraggable).attr('data-name'));
            }
            // Dropped in new attributes
            if($(this).hasClass('newcreate')) {
                $(newDraggable).html($(newDraggable).attr('id').replace('t_',''));
                $(newDraggable).prepend('<input type="text" id="td_'+$(newDraggable).attr('id')+'" value=\"'+$(newDraggable).attr('data-name')+'\">');
            }
            // Reset the mappable attribute classes
            $('.mappable-attribute-wrapper').removeClass('paired');
            $('.mappable-attribute-wrapper .token-attribute').closest('.mappable-attribute-wrapper').addClass('paired');
            $('.mappable-attribute-wrapper').droppable('enable');
            $('.mappable-attribute-wrapper.paired').droppable('disable');

            adjustHeights();
        }
    });

    $("#back").click(function(){
        var backURL = document.URL.replace(/participants\/sa\/attributeMapToken\/sid\//, 'tokens/sa/browse/surveyid/');
        window.location = backURL;
    });
    $("#overwrite").click(function(){
        if($("#overwrite").is(':checked')) {attoverwrite=true;} else {attoverwrite=false;}
    });
    $("#overwriteman").click(function(){
        if($("#overwriteman").is(':checked')) {attoverwriteman=true;} else {attoverwriteman=false;}
    });
    $("#createautomap").click(function(){
        if($("#createautomap").is(':checked')) {attcreateautomap=true;} else {attcreateautomap=false;}
    });
    $('#attmap').click(function(){
        var anewcurrentarray = {};
        newcurrentarray = new Array();
        $('#newcreated .attribute-item').each(function(i) {
            newcurrentarray.push($(this).attr('id'));
        });
        $.each(newcurrentarray, function(index,value) {
            if(value[0]=='t') {
                anewcurrentarray[value.substring(2)] = $("#td_"+value).val();
            }
        });
        var mappedarray = {};
        tokencurrentarray = new Array();
        $('#centralattribute .attribute-item').each(function(i) {
            tokencurrentarray.push($(this).attr('id'));
        });
        $.each(tokencurrentarray, function(index,value) {
            if(value[0]=='t') {
                mappedarray[encodeURI(tokencurrentarray[index-1].substring(2))] = value.substring(2);
            }
        });

        /* $("#processing").dialog({
            height: 90,
            width: 50,
            modal: true
        }); */

        $("#processing").load(copyUrl, {
            mapped: mappedarray,
            newarr: anewcurrentarray,
            surveyid: surveyId,
            overwriteauto: attoverwrite,
            overwriteman: attoverwriteman,
            createautomap: attcreateautomap
        }, function(msg){
            alert(msg);
            //$(this).dialog("close");
            $(location).attr('href',redUrl);
        });
    });
});

redpajama_set_name: RedPajamaGithub


text:
using UIKit;

namespace MultipleViews
{
	[IBObject]
	public class DetailViewController: UIViewController
	{
		public this withLanguage(Language! language) : base withNibName("DetailView") bundle(null)
		{
			this.language = language;
		}

		private Language! language;

		public override void viewDidLoad()
		{
			base.viewDidLoad();
			imageView.image = language.image;
			title = language.displayName;
		}

		public override void didReceiveMemoryWarning()
		{
			base.didReceiveMemoryWarning();

			// Dispose of any resources that can be recreated.
		}

		[IBOutlet] public UIImageView imageView { get; set; }

		[IBAction]
		public void learnMore(id sender)
		{
			// using  a new UINavigationController forces the popuo
			var popover = new UINavigationController withRootViewController(new SafariServices.SFSafariViewController withURL(language.URL));
			presentViewController(popover) animated(true) completion(null);
		}
	}
}


text:
using System.Configuration;
using System.Reflection;
using System.Threading;
using System.Web.Http;
using log4net;

namespace RightpointLabs.ConferenceRoom.Web.Controllers
{
    /// <summary>
    /// Operations dealing with settings
    /// </summary>
    [RoutePrefix("api/settings")]
    public class SettingsController : BaseController
    {
        private static readonly ILog __log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        public SettingsController()
            : base(__log)
        { }

        /// <summary>
        /// Checks that the supplied code is correct.
        /// </summary>
        /// <param name="code">The code to check</param>
        [Route("checkCode")]
        public bool PostCheckCode(string code)
        {
            var realCode = ConfigurationManager.AppSettings["settingsSecurityCode"];
            if (string.IsNullOrEmpty(realCode) || code == realCode)
            {
                return true;
            }
            Thread.Sleep(1000);
            return false;
        }
    }
}


text:
package org.radargun.stages.helpers;

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

public final class Range {

   private long start;
   private long end;

   private Range() {}

   public Range(long start, long end) {
      this.start = start;
      this.end = end;
   }

   public long getStart() {
      return start;
   }
   public long getEnd() {
      return end;
   }
   public long getSize() {
      return end - start;
   }

   public Range shift(long shift) {
      return new Range(start + shift, end + shift);
   }

   @Override
   public int hashCode() {
      return (int)(start + 31*(end - 1));
   }

   @Override
   public boolean equals(Object other) {
      if (other == null || !(other instanceof Range)) return false;
      Range otherRange = (Range) other;
      return start == otherRange.getStart() && end == otherRange.getEnd();
   }

   @Override
   public String toString() {
      return "[" + start + ", " + end + "]";
   }

   /**
    *
    * Returns pair [startKey, endKey] that specifies a subrange { startKey, ..., endKey-1 } of key
    * range { 0, 1, ..., numKeys-1 } divideRange divides the keyset evenly to numParts parts with
    * difference of part lengths being max 1.
    *
    * @param numKeys
    *           Total number of keys
    * @param numParts
    *           Number of parts we're dividing to
    * @param partIdx
    *           Index of part we want to get
    * @return The pair [startKey, endKey]
    */
   public static Range divideRange(long numKeys, int numParts, int partIdx) {
      long base = (numKeys / numParts) + 1;
      long mod = numKeys % numParts;
      if (partIdx < mod) {
         long startKey = partIdx * base;
         return new Range(startKey, startKey + base);
      } else {
         long startKey = base * mod + (partIdx - mod) * (base - 1);
         return new Range(startKey, startKey + base - 1);
      }
   }

   public static List<List<Range>> balance(List<Range> ranges, int numParts) {
      int totalSize = 0;
      for (Range range : ranges) {
         totalSize += range.getSize();
      }
      Iterator<Range> iterator = ranges.iterator();
      Range currentRange;
      if (iterator.hasNext()) {
         currentRange = iterator.next();
      } else {
         currentRange = new Range(0, 0);
      }

      List<List<Range>> balanced = new ArrayList<List<Range>>(numParts);

      for (int i = 0; i < numParts; ++i) {
         long myRangeSize = divideRange(totalSize, numParts, i).getSize();
         List<Range> myRanges = new ArrayList<Range>();

         while (currentRange.getSize() <= myRangeSize) {
            myRanges.add(currentRange);
            myRangeSize -= currentRange.getSize();
            if (iterator.hasNext()) {
               currentRange = iterator.next();
            } else {
               break; // this should happen only for the last range
            }
         }
         if (myRangeSize != 0) {
            myRanges.add(new Range(currentRange.getStart(), currentRange.getStart() + myRangeSize));
            currentRange = new Range(currentRange.getStart() + myRangeSize, currentRange.getEnd());
         }
         balanced.add(myRanges);
      }
      return balanced;
   }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Astrothelium varium var. varium Eschw.

### Remarks
null


text:
<!DOCTYPE html>

     {% block head %}
    <meta charset="UTF-8">
    <title>{% block title %}The Matrix{% endblock title %}</title>

    <link rel="stylesheet" href="{{ url_for('static', filename='css/base.css') }}" />
    <link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap.min.css') }}" />
    {% endblock head %}

{% block content %}{% endblock %}

        {% block footer %}
        {% endblock footer%}


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

// This file is autogenerated by
//     weex_core_debug/Source/WeexCore/platform/android/jniprebuild/jni_generator.py
// For
//     com/taobao/weex/layout/MeasureMode

#ifndef com_taobao_weex_layout_MeasureMode_JNI
#define com_taobao_weex_layout_MeasureMode_JNI

#include <jni.h>

//#include "base/android/jni_int_wrapper.h"

// Step 1: forward declarations.
namespace {
const char kMeasureModeClassPath[] = "com/taobao/weex/layout/MeasureMode";
// Leaking this jclass as we cannot use LazyInstance from some threads.
jclass g_MeasureMode_clazz = NULL;
#define MeasureMode_clazz(env) g_MeasureMode_clazz

}  // namespace

// Step 2: method stubs.

static intptr_t g_MeasureMode_getEXACTLY = 0;
static jint Java_MeasureMode_getEXACTLY(JNIEnv* env) {
  /* Must call RegisterNativesImpl()  */
  //CHECK_CLAZZ(env, MeasureMode_clazz(env),
  //    MeasureMode_clazz(env), 0);
  jmethodID method_id =
      base::android::GetMethod(
      env, MeasureMode_clazz(env),
      base::android::STATIC_METHOD,
      "getEXACTLY",

"("
")"
"I",
      &g_MeasureMode_getEXACTLY);

  jint ret =
      env->CallStaticIntMethod(MeasureMode_clazz(env),
          method_id);
  base::android::CheckException(env);
  return ret;
}

static intptr_t g_MeasureMode_getUNSPECIFIED = 0;
static jint Java_MeasureMode_getUNSPECIFIED(JNIEnv* env) {
  /* Must call RegisterNativesImpl()  */
  //CHECK_CLAZZ(env, MeasureMode_clazz(env),
  //    MeasureMode_clazz(env), 0);
  jmethodID method_id =
      base::android::GetMethod(
      env, MeasureMode_clazz(env),
      base::android::STATIC_METHOD,
      "getUNSPECIFIED",

"("
")"
"I",
      &g_MeasureMode_getUNSPECIFIED);

  jint ret =
      env->CallStaticIntMethod(MeasureMode_clazz(env),
          method_id);
  base::android::CheckException(env);
  return ret;
}

// Step 3: RegisterNatives.

static bool RegisterNativesImpl(JNIEnv* env) {

  g_MeasureMode_clazz = reinterpret_cast<jclass>(env->NewGlobalRef(
      base::android::GetClass(env, kMeasureModeClassPath).Get()));

  return true;
}

#endif  // com_taobao_weex_layout_MeasureMode_JNI


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Animation;
using EDEngineer.Localization;
using EDEngineer.Models;
using EDEngineer.Utils;
using EDEngineer.Utils.System;
using EDEngineer.Utils.UI;
using EDEngineer.Views.Popups;
using Application = System.Windows.Application;
using Button = System.Windows.Controls.Button;
using DataGridCell = System.Windows.Controls.DataGridCell;

namespace EDEngineer.Views
{
    public partial class MainWindow
    {
        private readonly MainWindowViewModel viewModel;
        private readonly ServerBridge serverBridge;

        public MainWindow()
        {
            var procName = Process.GetCurrentProcess().ProcessName;
            var processes = Process.GetProcessesByName(procName);

            if (processes.Length > 1)
            {
                System.Windows.Forms.MessageBox.Show($"EDEngineer already running, you can bring it up with your shortcut ({SettingsManager.Shortcut}).",
                    "Oops", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                Application.Current.Shutdown();
                return;
            }
            SettingsManager.Init();

            try
            {
                ReleaseNotesManager.ShowReleaseNotesIfNecessary();
            }
            catch
            {
                // silently fail if release notes can't be shown
            }

            Languages.InitLanguages();

            InitializeComponent();

            if (Properties.Settings.Default.WindowUnlocked)
            {
                AllowsTransparency = false;
                WindowStyle = WindowStyle.SingleBorderWindow;
                Topmost = false;
                ShowInTaskbar = true;
            }
            else
            {
                AllowsTransparency = true;
                WindowStyle = WindowStyle.None;
                Topmost = true;
                ShowInTaskbar = false;
            }

            viewModel = new MainWindowViewModel(Languages.Instance);
            DataContext = viewModel;

            RefreshCargoSources();
            viewModel.PropertyChanged += (o, e) =>
                                         {
                                             if (e.PropertyName == "ShowOnlyForFavorites" ||
                                                 e.PropertyName == "ShowZeroes" ||
                                                 e.PropertyName == "CurrentCommander")
                                             {
                                                 RefreshCargoSources();
                                             }
                                         };
            serverBridge = new ServerBridge(viewModel, SettingsManager.AutoRunServer);

            if (SettingsManager.SilentLaunch)
            {
                if (Properties.Settings.Default.WindowUnlocked)
                {
                    WindowState = WindowState.Minimized;
                }
                else
                {
                    Opacity = 0.001;
                }
            }
        }

        public void RefreshCargoSources()
        {
            var commander = viewModel.CurrentCommander.Value;

            var blueprintSource = new CollectionViewSource { Source = commander.State.Blueprints };
            commander.Filters.Monitor(blueprintSource, commander.State.Cargo.Select(c => c.Value), commander.HighlightedEntryData);
            Blueprints.ItemsSource = blueprintSource.View;

            // COMMODITY REMOVED
            //Commodities.ItemsSource = commander.FilterView(viewModel, Kind.Commodity, new CollectionViewSource { Source = commander.State.Cargo });

            Materials.ItemsSource = commander.FilterView(viewModel, Kind.Material, new CollectionViewSource { Source = commander.State.Cargo });
            Data.ItemsSource = commander.FilterView(viewModel, Kind.Data, new CollectionViewSource { Source = commander.State.Cargo });
        }

        private void MainWindowLoaded(object sender, RoutedEventArgs args)
        {
            var dimensions = SettingsManager.Dimensions;

            Width = dimensions.Width;
            Left = dimensions.Left;
            Top = dimensions.Top;
            Height = dimensions.Height;

            if (dimensions.LeftSideWidth != 1 || dimensions.RightSideWidth != 1)
            {
                ContentGrid.ColumnDefinitions[0].Width = new GridLength(dimensions.LeftSideWidth, GridUnitType.Star);
                ContentGrid.ColumnDefinitions[2].Width = new GridLength(dimensions.RightSideWidth, GridUnitType.Star);
            }

            if (AllowsTransparency)
            {
                ToggleEditMode.Content = viewModel.Languages.Translate("Unlock Window");
                MainSplitter.Visibility = Visibility.Hidden;
            }
            else
            {
                ToggleEditMode.Content = viewModel.Languages.Translate("Lock Window");
                ResetWindowPositionButton.Visibility = Visibility.Visible;
            }

            icon = TrayIconManager.Init((o, e) => ShowWindow(),
                (o, e) => Close(),
                ConfigureShortcut,
                (o, e) => ToggleEditModeChecked(o, null),
                (o, e) => ResetWindowPositionButtonClicked(o, null),
                (o, e) => Languages.PromptLanguage(viewModel.Languages),
                () => serverBridge.Toggle(),
                serverBridge.Running,
                (o, e) =>
                {
                    HideWindow();
                    ReleaseNotesManager.ShowReleaseNotes();
                },
                Properties.Settings.Default.CurrentVersion,
                (o, e) =>
                {
                    HideWindow();
                    ThresholdsManagerWindow.ShowThresholds(viewModel.Languages, viewModel.CurrentCommander.Value.State.Cargo, viewModel.CurrentCommander.Key);
                });

            try
            {
                var shortcut = SettingsManager.Shortcut;
                var hotKey = (Keys) new KeysConverter().ConvertFromString(shortcut);

                HotkeyManager.RegisterHotKey(this, hotKey);
            }
            catch
            {
                SettingsManager.Shortcut = null;
                ConfigureShortcut(this, EventArgs.Empty);
                ShowWindow();
            }

            Blueprints.UpdateLayout();
            ShoppingList.UpdateLayout();
        }

        private void ConfigureShortcut(object sender, EventArgs e)
        {
            string shortcut;
            ignoreShortcut = true;
            if (Math.Abs(Opacity) > 0.99)
            {
                HideWindow();
            }

            HotkeyManager.UnregisterHotKey(this);
            if (ShortcutPrompt.ShowDialog(SettingsManager.Shortcut, out shortcut))
            {
                SettingsManager.Shortcut = shortcut;
                HotkeyManager.UnregisterHotKey(this);
                HotkeyManager.RegisterHotKey(this, (Keys) new KeysConverter().ConvertFromString(shortcut));
            }
            else
            {
                HotkeyManager.RegisterHotKey(this, (Keys) new KeysConverter().ConvertFromString(SettingsManager.Shortcut));
            }

            ignoreShortcut = false;
        }

        private readonly Regex forbiddenCharacters = new Regex("[^0-9.-]+");
        private void EntryCountTextBoxOnPreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            if (forbiddenCharacters.IsMatch(e.Text))
            {
                e.Handled = true;
            }

        }

        private BindingBase binding;
        private void EntryCountTextBoxOnFocussed(object sender, RoutedEventArgs e)
        {
            var box = (System.Windows.Controls.TextBox)sender;
            binding = box.GetBindingExpression(System.Windows.Controls.TextBox.TextProperty).ParentBindingBase;
            BindingOperations.ClearBinding(box, System.Windows.Controls.TextBox.TextProperty);
            box.SelectAll();
        }

        private void EntryCountTextBoxOnLostFocus(object sender, RoutedEventArgs e)
        {
            var box = (System.Windows.Controls.TextBox)sender;

            int newCount;
            if (int.TryParse(box.Text, out newCount))
            {
                var entry = (Entry)box.Tag;
                viewModel.UserChange(entry, newCount - entry.Count);
            }

            BindingOperations.SetBinding(box, System.Windows.Controls.TextBox.TextProperty, binding);
        }

        private void IncrementButtonClicked(object sender, RoutedEventArgs e)
        {
            var entry = (Entry) ((Button) sender).Tag;
            viewModel.UserChange(entry, 1);
        }

        private void DecrementButtonClicked(object sender, RoutedEventArgs e)
        {
            var entry = (Entry) ((Button) sender).Tag;
            viewModel.UserChange(entry, -1);
        }

        private void ChangeFolderButtonClicked(object sender, RoutedEventArgs e)
        {
            viewModel.LoadState(true);
        }

        private void DataGridOnPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var toggleButton = FindVisualParent<Button>(Mouse.DirectlyOver as DependencyObject);
            if (toggleButton != null)
            {
                toggleButton.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent));
                e.Handled = true;
            }
        }

        private void PreviewMouseLeftButtonDownHandler(object sender, MouseButtonEventArgs e)
        {
            var cell = (DataGridCell) sender;
            if (cell.Column.Header == null)
            {
                var toggleButton = FindVisualParent<ToggleButton>(Mouse.DirectlyOver as DependencyObject);
                if (toggleButton?.IsChecked != null)
                {
                    toggleButton.IsChecked = !toggleButton.IsChecked.Value;
                }
                e.Handled = true;
            }
            else if (!cell.IsEditing)
            {
                var row = FindVisualParent<DataGridRow>(cell);
                if (row != null)
                {
                    row.IsSelected = !row.IsSelected;
                    e.Handled = true;
                }
            }
        }

        private static T FindVisualParent<T>(DependencyObject child) where T : DependencyObject
        {
            while (true)
            {
                if (child is Run)
                {
                    return null;
                }

                var parentObject = VisualTreeHelper.GetParent(child);

                if (parentObject == null)
                {
                    return null;
                }

                var parent = parentObject as T;
                if (parent != null)
                {
                    return parent;
                }

                child = parentObject;
            }
        }

        private void DataGridLoaded(object sender, RoutedEventArgs e)
        {
            var dataGrid = (System.Windows.Controls.DataGrid) sender;
            var newStyle = new Style
            {
                BasedOn = dataGrid.CellStyle,
                TargetType = typeof (DataGridCell)
            };

            newStyle.Setters.Add(new EventSetter(PreviewMouseLeftButtonDownEvent, new MouseButtonEventHandler(PreviewMouseLeftButtonDownHandler)));
            dataGrid.CellStyle = newStyle;
        }

        private bool transitionning = false;
        private void HideWindow()
        {
            if (!transitionning)
            {
                transitionning = true;
                var sb = (Storyboard)FindResource("WindowDeactivated");
                Storyboard.SetTarget(sb, this);
                sb.Begin();
            }
        }

        private void ShowWindow()
        {
            if (!transitionning)
            {
                Show();
                Focus();
                transitionning = true;
                var sb = (Storyboard) FindResource("WindowActivated");
                Storyboard.SetTarget(sb, this);
                sb.Begin();
            }
        }

        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);
            handle = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);
            handle?.AddHook(WndProc);
        }

        private HwndSource handle;
        private IDisposable icon;
        private bool ignoreShortcut = false;

        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            if (msg == HotkeyManager.WM_HOTKEY && !ignoreShortcut)
            {
                if (Math.Abs(Opacity) < 0.01)
                {
                    ShowWindow();
                }
                else
                {
                    HideWindow();
                }
            }

            return IntPtr.Zero;
        }

        protected override void OnClosed(EventArgs e)
        {
            HotkeyManager.UnregisterHotKey(this);
            handle?.RemoveHook(WndProc);
            icon?.Dispose();
            viewModel?.Dispose();
            serverBridge?.Dispose();
        }

        private void WindowActivatedCompleted(object sender, EventArgs e)
        {
            transitionning = false;
        }

        private void WindowDeactivatedCompleted(object sender, EventArgs e)
        {
            Hide();
            transitionning = false;
        }

        private void ToggleEditModeChecked(object sender, RoutedEventArgs e)
        {
            Properties.Settings.Default.WindowUnlocked = !Properties.Settings.Default.WindowUnlocked;
            Properties.Settings.Default.Save();

            var w = new MainWindow();
            Close();
            w.Show();
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            if (!bypassPositionSave)
            {
                var coords = PointToScreen(new Point(0, 0));
                var yModificator = AllowsTransparency ? 0 : SystemInformation.CaptionHeight + 8;
                var xModificator = AllowsTransparency ? 0 : 8;
                SettingsManager.Dimensions = new WindowDimensions()
                {
                    Height = ActualHeight,
                    Left = coords.X - xModificator,
                    Top = coords.Y - yModificator,
                    Width = ActualWidth,
                    LeftSideWidth = ContentGrid.ColumnDefinitions[0].Width.Value,
                    RightSideWidth = ContentGrid.ColumnDefinitions[2].Width.Value
                };
            }

            base.OnClosing(e);
        }

        private bool bypassPositionSave = false;

        private void ResetWindowPositionButtonClicked(object sender, RoutedEventArgs e)
        {
            SettingsManager.Dimensions.Reset();
            bypassPositionSave = true;

            Properties.Settings.Default.WindowUnlocked = false;
            Properties.Settings.Default.Save();

            var w = new MainWindow();
            Close();
            w.Show();
        }

        private void CheckAllButtonClicked(object sender, RoutedEventArgs e)
        {
            viewModel.ChangeAllFilters(true);
        }

        private void UncheckAllButtonClicked(object sender, RoutedEventArgs e)
        {
            viewModel.ChangeAllFilters(false);
        }

        private void UnhighlightAllButtonClicked(object sender, RoutedEventArgs e)
        {
            viewModel.UnhighlightAllIngredients();
        }

        private void IngredientOnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var dataContext = (KeyValuePair<string, Entry>) ((Grid) sender).DataContext;
            viewModel.ToggleHighlight(dataContext.Value);
        }

        private void IncrementShoppingList(object sender, RoutedEventArgs e)
        {
            var tag = ((Button) sender).Tag;
            viewModel.CurrentCommander.Value.ShoppingListChange((Blueprint) tag, 1);
        }

        private void DecrementShoppingList(object sender, RoutedEventArgs e)
        {
            var tag = ((Button)sender).Tag;
            viewModel.CurrentCommander.Value.ShoppingListChange((Blueprint)tag, -1);

            if (!viewModel.CurrentCommander.Value.ShoppingList.Composition.Any())
            {
                ShoppingListSplitterDoubleClicked(null, null);
            }
        }

        private void RemoveBlueprintShoppingList(object sender, RoutedEventArgs e)
        {
            var blueprint = (Blueprint) ((Button)sender).Tag;
            viewModel.CurrentCommander.Value.ShoppingListChange(blueprint, -1 * blueprint.ShoppingListCount);

            if (!viewModel.CurrentCommander.Value.ShoppingList.Composition.Any())
            {
                ShoppingListSplitterDoubleClicked(null, null);
            }
        }

        private void ShoppingListSplitterDoubleClicked(object sender, MouseButtonEventArgs e)
        {
            BlueprintsRow.Height = new GridLength(1, GridUnitType.Star);
            ShoppingListSplitterRow.Height = new GridLength(1, GridUnitType.Auto);
            ShoppingListRow.Height = new GridLength(1, GridUnitType.Auto);
        }
    }
}


text:
namespace RPH.Utilities.AI
{
    // System
    using System;

    public abstract class BehaviorTask
    {
        public Guid Id { get; }

        protected BehaviorTask()
        {
            Id = Guid.NewGuid();
        }

        protected virtual void OnEnter(ref BehaviorTreeContext context) { }
        protected virtual void OnOpen(ref BehaviorTreeContext context) { }
        protected virtual BehaviorStatus OnBehave(ref BehaviorTreeContext context) => BehaviorStatus.Success;
        protected virtual void OnClose(ref BehaviorTreeContext context) { }
        protected virtual void OnExit(ref BehaviorTreeContext context) { }

        public BehaviorStatus Behave(ref BehaviorTreeContext context)
        {
            EnterInternal(ref context);

            if (!context.Agent.Blackboard.Get<bool>("isOpen", context.Tree.Id, this.Id))
            {
                OpenInternal(ref context);
            }

            BehaviorStatus status = BehaveInternal(ref context);

            if (status != BehaviorStatus.Running)
            {
                CloseInternal(ref context);
            }

            ExitInternal(ref context);

            return status;
        }

        internal void EnterInternal(ref BehaviorTreeContext context)
        {
            context.OnEnterNode(this.Id);
            OnEnter(ref context);
        }

        internal void OpenInternal(ref BehaviorTreeContext context)
        {
            context.OnOpenNode(this.Id);
            context.Agent.Blackboard.Set<bool>("isOpen", true, context.Tree.Id, this.Id);
            OnOpen(ref context);
        }

        internal BehaviorStatus BehaveInternal(ref BehaviorTreeContext context)
        {
            context.OnBehaveNode(this.Id);
            return OnBehave(ref context);
        }

        internal void CloseInternal(ref BehaviorTreeContext context)
        {
            context.OnCloseNode(this.Id);
            context.Agent.Blackboard.Set<bool>("isOpen", false, context.Tree.Id, this.Id);
            OnClose(ref context);
        }

        internal void ExitInternal(ref BehaviorTreeContext context)
        {
            context.OnExitNode(this.Id);
            OnExit(ref context);
        }

        public virtual BehaviorTask GetTaskById(Guid id)
        {
            return Id == id ? this : null;
        }
    }
}


text:
function CodeError(message,code) {
  var errorFn = Error.apply(this,arguments);
  this.code = code || 1;
  this.message = errorFn.message;
}
util.inherits(CodeError,Error);

var ce = new CodeError('a',1);
console.log(ce.code); // 1
console.log(ce.message); // a


text:
/* */
if (System._nodeRequire)
  module.exports = System._nodeRequire('child_process');
else
  throw "Node child_process module not supported in browsers.";


text:
// https://github.com/soliantconsulting/tagmanager/blob/master/tagmanager.js

!function ( $ ) {

  'use strict' // jshint ;_;

  var Tag = function ( element, options ) {
    this.element = $(element)
    this.options = $.extend(true, {}, $.fn.tag.defaults, options)
    this.values = $.grep($.map(this.element.val().split(','), $.trim), function ( value ) { return value.length > 0 })
    this.show()
  }

  Tag.prototype = {
    constructor: Tag

  , show: function () {
      var that = this

      that.element.parent().prepend(that.element.detach().attr('type', 'hidden'))
      that.element
        .wrap($('
'))
        .parent()
        .on('click', function () {
          that.input.focus()
        })

      if (that.values.length) {
        $.each(that.values, function () {
          that.createBadge(this)
        })
      }

      that.input = $('<input type="text">')
        .attr('placeholder', that.options.placeholder)
        .insertAfter(that.element)
        .on('focus', function () {
          that.element.parent().addClass('tags-hover')
        })
        .on('blur', function () {
          that.process()
          that.element.parent().removeClass('tags-hover')
          that.element.siblings('.tag').removeClass('tag-important')
        })
        .on('keydown', function ( event ) {
          if ( event.keyCode == 188 || event.keyCode == 13 || event.keyCode == 9 ) {
            if ( $.trim($(this).val()) && ( !that.element.siblings('.typeahead').length || that.element.siblings('.typeahead').is(':hidden') ) ) {
              if ( event.keyCode != 9 ) event.preventDefault()
              that.process()
            } else if ( event.keyCode == 188 ) {
              if ( !that.element.siblings('.typeahead').length || that.element.siblings('.typeahead').is(':hidden') ) {
                event.preventDefault()
              } else {
                that.input.data('typeahead').select()
                event.stopPropagation()
                event.preventDefault()
              }
            }
          } else if ( !$.trim($(this).val()) && event.keyCode == 8 ) {
            var count = that.element.siblings('.tag').length
            if (count) {
              var tag = that.element.siblings('.tag:eq(' + (count - 1) + ')')
              if (tag.hasClass('tag-important')) that.remove(count - 1)
              else tag.addClass('tag-important')
            }
          } else {
            that.element.siblings('.tag').removeClass('tag-important')
          }
        })
        .typeahead({
          source: that.options.source
        , matcher: function ( value ) {
            return ~value.toLowerCase().indexOf(this.query.toLowerCase()) && (that.inValues(value) == -1 || that.options.allowDuplicates)
          }
        , updater: $.proxy(that.add, that)
        })
    }
  , inValues: function ( value ) {
      if (this.options.caseInsensitive) {
        var index = -1
        $.each(this.values, function (indexInArray, valueOfElement) {
          if ( valueOfElement.toLowerCase() == value.toLowerCase() ) {
            index = indexInArray
            return false
          }
        })
        return index
      } else {
        return $.inArray(value, this.values)
      }
    }
  , createBadge: function ( value ) {
    var that = this

    $('')
      .text(value)
      .append($('<button type="button" class="close">×</button>')
        .on('click', function () {
          that.remove(that.element.siblings('.tag').index($(this).closest('.tag')))
        })
      )
      .insertBefore(that.element)
  }
  , add: function ( value ) {
      var that = this

      if ( !that.options.allowDuplicates ) {
        var index = that.inValues(value)
        if ( index != -1 ) {
          var badge = that.element.siblings('.tag:eq(' + index + ')')
          badge.addClass('tag-warning')
          setTimeout(function () {
            $(badge).removeClass('tag-warning')
          }, 500)
          return
        }
      }

      this.values.push(value)
      this.createBadge(value)

      this.element.val(this.values.join(', '))
    }
  , remove: function ( index ) {
      if ( index >= 0 ) {
        this.values.splice(index, 1)
        this.element.siblings('.tag:eq(' + index + ')').remove()
        this.element.val(this.values.join(', '))
      }
    }
  , process: function () {
      var values = $.grep($.map(this.input.val().split(','), $.trim), function ( value ) { return value.length > 0 }),
          that = this
      $.each(values, function() {
        that.add(this)
      })
      this.input.val('')
    }
  }

  var old = $.fn.tag

  $.fn.tag = function ( option ) {
    return this.each(function () {
      var that = $(this)
        , data = that.data('tag')
        , options = typeof option == 'object' && option
      if (!data) that.data('tag', (data = new Tag(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  $.fn.tag.defaults = {
    allowDuplicates: false
  , caseInsensitive: true
  , placeholder: ''
  , source: []
  }

  $.fn.tag.Constructor = Tag

  $.fn.tag.noConflict = function () {
    $.fn.tag = old
    return this
  }

  $(window).on('load', function () {
    $('[data-provide="tag"]').each(function () {
      var that = $(this)
      if (that.data('tag')) return
      that.tag(that.data())
    })
  })
}(window.jQuery)


text:
OThreadPoolRef oThreadPool;

namespace onut
{
    OThreadPoolRef OThreadPool::create()
    {
        return std::shared_ptr<ThreadPool>(new ThreadPool());
    }

    void ThreadPool::workerThread(ThreadPool::WorkerRef pWorker)
    {
        std::unique_lock<std::mutex> lock(pWorker->mutex);
        while (pWorker->isRunning)
        {
            pWorker->waitForWork.wait(lock);
            if (!pWorker->isRunning)
            {
                break;
            }
            pWorker->pDispatcher->processQueue();
        }
    }

    ThreadPool::ThreadPool()
        : m_nextWorker(0)
    {
        auto threadCount = std::thread::hardware_concurrency();
        for (decltype(threadCount) i = 0; i < threadCount; ++i)
        {
            WorkerRef pWorker = OMake<Worker>();
            pWorker->pDispatcher = OMake<ODispatcher>();
            pWorker->thread = std::thread(workerThread, pWorker);
            m_workers.push_back(pWorker);
        }
    }

    ThreadPool::~ThreadPool()
    {
        for (auto& pWorker : m_workers)
        {
            {
                std::unique_lock<std::mutex> lock(pWorker->mutex);
                pWorker->isRunning = false;
                pWorker->waitForWork.notify_all();
            }
            pWorker->thread.join();
        }
    }

    void ThreadPool::wait()
    {
        for (auto& pWorker : m_workers)
        {
            std::unique_lock<std::mutex> lock(pWorker->mutex);
        }
        m_nextWorker = 0;
    }
}


text:
package org.openspaces.admin.internal.space.events;

import org.openspaces.admin.internal.admin.InternalAdmin;
import org.openspaces.admin.internal.support.GroovyHelper;
import org.openspaces.admin.space.events.SpaceStatisticsChangedEvent;
import org.openspaces.admin.space.events.SpaceStatisticsChangedEventListener;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author kimchy
 */
public class DefaultSpaceStatisticsChangedEventManager implements InternalSpaceStatisticsChangedEventManager {

    private final InternalAdmin admin;

    private final List<SpaceStatisticsChangedEventListener> listeners = new CopyOnWriteArrayList<SpaceStatisticsChangedEventListener>();

    public DefaultSpaceStatisticsChangedEventManager(InternalAdmin admin) {
        this.admin = admin;
    }

    public void spaceStatisticsChanged(final SpaceStatisticsChangedEvent event) {
        for (final SpaceStatisticsChangedEventListener listener : listeners) {
            admin.raiseEvent(listener, new Runnable() {
                public void run() {
                    listener.spaceStatisticsChanged(event);
                }
            });
        }
    }

    public void add(SpaceStatisticsChangedEventListener eventListener) {
        listeners.add(eventListener);
    }

    public void remove(SpaceStatisticsChangedEventListener eventListener) {
        listeners.remove(eventListener);
    }

    public void plus(Object eventListener) {
        if (GroovyHelper.isClosure(eventListener)) {
            add(new ClosureSpaceStatisticsChangedEventListener(eventListener));
        } else {
            add((SpaceStatisticsChangedEventListener) eventListener);
        }
    }

    public void leftShift(Object eventListener) {
        plus(eventListener);
    }

    public void minus(Object eventListener) {
        if (GroovyHelper.isClosure(eventListener)) {
            remove(new ClosureSpaceStatisticsChangedEventListener(eventListener));
        } else {
            remove((SpaceStatisticsChangedEventListener) eventListener);
        }
    }

    public void rightShift(Object eventListener) {
        minus(eventListener);
    }
}


text:
package org.jboss.jbossts.qa.astests.taskdefs;

import java.io.File;
import java.io.IOException;
import java.io.FileWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;

import org.w3c.dom.*;
import org.xml.sax.SAXException;

/**
 * Helper class to read a JBoss AS bindings file
 */
public class ServerBindingConfig
{
    private static final String BINDING_MANAGER_NAME = "jboss.system:service=ServiceBindingManager";
    private static final String BINDING_MANAGER_CLASS = "org.jboss.services.binding.ServiceBindingManager";
    private static final String STORE_FACTORY_CLASS = "org.jboss.services.binding.XMLServicesStoreFactory";
    public static final String DEFAULT_BINDING = "ports-01";

    /**
     * Configure an AS to start up with a non-default set of bindings.
     *
     * An mbean entry will be inserted into xmlFile with a name specified by bindingName.
     * The file bindingXml will contain an entry with the name bindingName.
     *
     * @param xmlFile   The file that is to recieve the binding service specification
     * @param bindingName The name of the binding definition to use
     * @param bindingXml file name of the file that contains a group of binding definitions
     * @throws IOException
     * @throws ParserConfigurationException
     * @throws org.xml.sax.SAXException
     * @throws TransformerException
     */
    public static void setBinding(String xmlFile, String bindingName, String bindingXml) throws IOException, ParserConfigurationException,
            org.xml.sax.SAXException, TransformerException
    {
        String xmlFileName = Utils.toFile(xmlFile).getAbsolutePath();

        System.out.println("update bindings:");
        System.out.println("\tConf File: " + xmlFileName);
        System.out.println("\tBinding File: " + bindingXml);
        System.out.println("\tBinding Name: " + bindingName);

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        documentBuilderFactory.setValidating(false);

        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document doc1 = documentBuilder.parse(xmlFileName);
        Document doc2 = documentBuilder.newDocument();

        doc2.appendChild(doc2.createElement("server"));

        NodeList children = doc1.getDocumentElement().getChildNodes();
        Node server2 = doc2.getDocumentElement();

        // add an mbean entry for the server binding
        server2.appendChild(createBinding(doc2, bindingName, bindingXml));

        for (int i=0; i< children.getLength(); i++)
        {
            Node child = children.item(i);

            if ("mbean".equals(child.getNodeName()))
            {
                String name = ((Element) child).getAttribute("name");

                // ignore the original binding since we are creating a new one
                if (BINDING_MANAGER_NAME.equals(name))
                    continue;
            }

            // take a detached copy of the node and add it to the new document
            Node copy = doc2.importNode(child, true).cloneNode(true);

            server2.appendChild(copy);
        }

        printDocument(doc2, xmlFileName);
    }

    private static Element createBinding(Document document, String binding, String bindingXml)
    {
        Element mbean = document.createElement("mbean");

        mbean.setAttribute("code", BINDING_MANAGER_CLASS);
        mbean.setAttribute("name", BINDING_MANAGER_NAME);

        mbean.appendChild(createMbeanAttribute(document, "ServerName", binding));
        mbean.appendChild(createMbeanAttribute(document, "StoreURL", bindingXml));
        mbean.appendChild(createMbeanAttribute(document, "StoreFactoryClassName", STORE_FACTORY_CLASS));

        return mbean;
    }

    private static Element createMbeanAttribute(Document document, String name, String cdata)
    {
        Element element = document.createElement("attribute");

        element.setAttribute("name", name);
        element.setTextContent(cdata);

        return element;
    }

    public static void printDocument(Document document, String fname){
        try{

            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            DOMSource source = new DOMSource(document);
            StreamResult result;

            if (fname == null)
                result = new StreamResult(System.out);
            else
                result = new StreamResult(new FileWriter(fname));

            transformer.transform(source, result);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    private static Document getDocument(String xmlFile)
    {
        Document doc = null;
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

        documentBuilderFactory.setNamespaceAware(true);
        documentBuilderFactory.setValidating(false);

        try
        {
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            doc = documentBuilder.parse(xmlFile);
        }
        catch (ParserConfigurationException e)
        {
            System.out.println("Unable to locate an XML doc builder: " + e.getMessage());
        }
        catch (Exception e)
        {
            System.out.println("Error parsing " + xmlFile + ' ' + e.getMessage());
        }

        return doc;
    }

    public static Node findServiceConfig(String bindingsFile, String server, String service)
    {
        Document doc = getDocument(bindingsFile);

        if (doc == null)
            return null;

        Node node = findNode(doc.getDocumentElement(), "server", "name", server);

        return (node != null ? findNode(node, "service-config", "name", service) : null);
    }

    public static String findBindingPort(Node node)
    {
        node = findNode(node, "binding", "port", null);

        return (node != null ? ((Element) node).getAttribute("port") : null);
    }

    private static int parseInt(String intValue, int defValue, String errMsg)
    {
        try
        {
            return (intValue != null ? Integer.parseInt(intValue) : defValue);
        }
        catch (NumberFormatException e)
        {
            if (errMsg != null)
                System.out.println(errMsg);

            return defValue;
        }
    }

    public static int lookupHttpPort(String bindingsFile, String server, int defValue)
    {
        Node node = findServiceConfig(bindingsFile, server, "jboss:service=invoker,type=http");
        String port = findBindingPort(node);

        return parseInt(port, defValue, "Invalid port found in service-config for binding " + server);
    }

    public static int lookupRmiPort(String bindingsFile, String server, int defValue)
    {
        Node node = findServiceConfig(bindingsFile, server, "jboss:service=Naming");
        String port = findBindingPort(node);

        return parseInt(port, defValue, "Invalid port found in service-config for binding " + server);
    }

    /**
     * Find a node with a given name and having a specified attribute
     * @param node the node to start the search from
     * @param nodeName the name of the xml node to look for the attribute
     * @param attrName the name of the attribute to match against
     * @param attrValue the value of the attribute to match against. If null
     *  the first matching node with an attribute called attrName is returned
     * @return the matching node
     */
    private static Node findNode(Node node, String nodeName, String attrName, String attrValue)
    {
        if (node != null)
        {
            NodeList children = node.getChildNodes();

            for (int i = 0; i < children.getLength(); i++)
            {
                Node child = children.item(i);

                if (nodeName.equals(child.getNodeName()))
                {
                    // found a node of the correct type - now see if it has the given attribute
                    String value = ((Element) child).getAttribute(attrName);

                    if (attrName == null || attrValue == null || value.equals(attrValue))
                        return child;
                }
            }

            System.out.println("Node of type " + nodeName + " with " + attrName + '=' + attrValue + " not found");
        }

        return null;
    }

    public static void main(String[] args) throws IOException, ParserConfigurationException,
            org.xml.sax.SAXException, TransformerException
    {
        if (args.length >= 3) {
            setBinding(args[0], args[1], args[2]);
        } else if (args.length == 2) {
            System.out.println("Rmi port: " + lookupRmiPort(args[0], args[1], -1));
            System.out.println("Http port: " + lookupHttpPort(args[0], args[1], -1));
        } else {
            System.out.println("syntax: ServerBindingConfig <conf file path> <server binding name> <path of bindings file>");
        }
    }
}


text:
import os
import argparse
import numpy as np
import healpy as hp
from scipy.stats import ks_2samp
import pandas as pd

import comptools as comp
import comptools.anisotropy.anisotropy as anisotropy

if __name__ == "__main__":

    p = argparse.ArgumentParser(
        description='Extracts and saves desired information from simulation/data .i3 files')
    p.add_argument('--infiles_sample_0', dest='infiles_sample_0', nargs='*',
                   help='Input reference map files')
    p.add_argument('--infiles_sample_1', dest='infiles_sample_1', nargs='*',
                   help='Input reference map files')
    p.add_argument('--outfile', dest='outfile',
                   help='Output DataFrame file')
    p.add_argument('--overwrite', dest='overwrite',
                   default=False, action='store_true',
                   help='Option to overwrite reference map file, '
                        'if it alreadu exists')
    args = p.parse_args()

    if args.infiles_sample_0 is None or args.infiles_sample_1 is None:
        raise ValueError('Input files must be specified')
    elif len(args.infiles_sample_0) != len(args.infiles_sample_1):
        raise ValueError('Both samples of input files must be the same length')

    if args.outfile is None:
        raise ValueError('Outfile must be specified')
    else:
        comp.check_output_dir(args.outfile)

    data_dict = {'ks_statistic': [], 'pval': []}
    # Read in all the input maps
    kwargs_relint = {'smooth': 20, 'scale': None, 'decmax': -55}
    for file_0, file_1 in zip(args.infiles_sample_0, args.infiles_sample_1):

        relint_0 = anisotropy.get_map(files=file_0, name='relint', **kwargs_relint)
        relint_1 = anisotropy.get_map(files=file_1, name='relint', **kwargs_relint)

        ri_0, ra, ra_err = anisotropy.get_proj_relint(relint_0, n_bins=100)
        ri_1, ra, ra_err = anisotropy.get_proj_relint(relint_1, n_bins=100)

        print('Comparing:')
        print('ri_0 = {}'.format(ri_0))
        print('ri_1 = {}\n'.format(ri_1))
        ks_statistic, pval = ks_2samp(ri_0, ri_1)
        print('ks_statistic = {}'.format(ks_statistic))
        print('pval = {}\n\n'.format(pval))
        data_dict['ks_statistic'].append(ks_statistic)
        data_dict['pval'].append(pval)

    with pd.HDFStore(args.outfile) as output_store:
        dataframe = pd.DataFrame(data_dict)
        output_store.put('dataframe', dataframe, format='table', data_columns=True)