text:
{% extends 'base.html' %}
{% from 'macros/users.html' import render_user_panel with context %}
{% from 'macros/tags.html' import render_tag %}
{% from 'macros/pastes.html' import render_source_code %}
{% from 'macros/pastes.html' import render_private %}
{% from 'macros/pastes.html' import like_paste_button %}
{% from 'macros/pastes.html' import edit_paste_button %}
{% from 'macros/pastes.html' import del_paste_button %}
{% from 'macros/pastes.html' import add_to_bookmark_form %}
{% from 'macros/pastes.html' import embed_paste_button with context  %}
{% from 'macros/common.html' import render_comments with context %}
{% from 'macros/users.html' import render_user_avatar -%}

{% block metatitle %}
<meta name="title" content="代码段 - {{ paste.title }}">
{% endblock %}
{% block metakeywords %}
<meta name="keywords" content="{% for tag in paste.tags %}{{ tag.name }}{% endfor %}">
{% endblock %}

{% block title %}{{ paste.title }}{% endblock %}

{% block content %}

      {{ paste.title }}
      {{ render_private(paste) }}

       {{ paste.views }}
       {{ paste.comments_count }}
      最后更新于 {{ paste.updated_at | time_passed }}

      {% if paste.is_user_owned(current_user.user) %}
        {{ edit_paste_button(paste) }}
        {{ del_paste_button(paste) }}
      {% endif %}
      {% if current_user.is_authenticated %}
        {{ like_paste_button(current_user.user, paste) }}

          {{ add_to_bookmark_form(paste, paste_lists) }}

      {% else %}

           喜欢 {{ paste.likes_count }}

      {% endif %}

         下载代码

      {% if current_user.is_authenticated %}

         复制到我的代码段

      {% endif %}

        {{ embed_paste_button(paste) }}

    {% for tag in paste.tags %}
      {{ render_tag(tag) }}
    {% endfor %}

  {% for code in paste.codes %}
    {{ render_source_code(code) }}
  {% endfor %}

  {{ render_comments(paste) }}

{% include 'shared/jiathis.html' %}
{% endblock %}

{% block sidebar %}
  {{ render_user_panel(paste.user) }}

同语言代码

      {% for paste in related_pastes %}

                {{ render_user_avatar(paste.user, size=22) }}

                    {{ paste.title | truncate(24) }}

      {% endfor %}

{% endblock %}


text:
package org.apache.druid.sql.http;

import com.opencsv.CSVWriter;

import javax.annotation.Nullable;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class CsvWriter implements ResultFormat.Writer
{
  private final OutputStream outputStream;
  private final CSVWriter writer;
  private final List<String> currentLine = new ArrayList<>();

  public CsvWriter(final OutputStream outputStream)
  {
    this.outputStream = outputStream;
    this.writer = new CSVWriter(new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8)));
  }

  @Override
  public void writeResponseStart()
  {
    // Do nothing.
  }

  @Override
  public void writeResponseEnd() throws IOException
  {
    writer.flush();

    // Write an extra blank line, so users can tell the response was not cut off.
    outputStream.write('\n');
    outputStream.flush();
  }

  @Override
  public void writeHeader(final List<String> columnNames)
  {
    writer.writeNext(columnNames.toArray(new String[0]), false);
  }

  @Override
  public void writeRowStart()
  {
    // Do nothing.
  }

  @Override
  public void writeRowField(final String name, @Nullable final Object value)
  {
    if (value == null) {
      // CSV cannot differentiate null and empty string.
      currentLine.add("");
    } else if (value instanceof String) {
      currentLine.add((String) value);
    } else {
      currentLine.add(value.toString());
    }
  }

  @Override
  public void writeRowEnd()
  {
    // Avoid writing blank lines, users may confuse them with the trailer.
    final boolean quoteEverything = currentLine.size() == 1 && currentLine.get(0).isEmpty();

    writer.writeNext(currentLine.toArray(new String[0]), quoteEverything);
    currentLine.clear();
  }

  @Override
  public void close() throws IOException
  {
    writer.close();
  }
}

redpajama_set_name: RedPajamaGithub


text:
#include <errno.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define SERVER_PORT_NUM 18080

#define STRERROR_BUF_SIZE 64
char strerror_buf[STRERROR_BUF_SIZE];

int main() {
    errno = 0;

    // ソケットの作成
    // See: https://manpages.debian.org/buster/manpages-ja-dev/socket.2.ja.html
    int listen_socket_descripter = socket(AF_INET, SOCK_STREAM, 0);
    if (listen_socket_descripter == -1) {
        strerror_r(errno, strerror_buf, STRERROR_BUF_SIZE);
        fprintf(stderr, "socket error: %d, %s.", errno, strerror_buf);
        exit(1);
    }

    // ソケットの設定
    struct sockaddr_in listen_address;
    listen_address.sin_family = AF_INET;
    listen_address.sin_port = htons(SERVER_PORT_NUM);
    listen_address.sin_addr.s_addr = INADDR_ANY;

    // 作成したソケットに、設定を適用
    // See: https://manpages.debian.org/buster/manpages-ja-dev/bind.2.ja.html
    int bind_result = bind(listen_socket_descripter,
            (struct sockaddr *)&listen_address,
            sizeof(listen_address));
    if (bind_result == -1) {
        strerror_r(errno, strerror_buf, STRERROR_BUF_SIZE);
        fprintf(stderr, "bind error: %d, %s.", errno, strerror_buf);
        exit(2);
    }

    // 待ち受け開始
    // See: https://manpages.debian.org/buster/manpages-ja-dev/listen.2.ja.html
    int listen_result = listen(listen_socket_descripter, 5);
    if (listen_result == -1) {
        strerror_r(errno, strerror_buf, STRERROR_BUF_SIZE);
        fprintf(stderr, "listen error: %d, %s.", errno, strerror_buf);
        exit(3);
    }

    // クライアントからのリクエスト情報を入れる変数を準備
    struct sockaddr_in client_request;
    int len = sizeof(client_request);

    // listen キューからリクエストを一つ取り出して処理開始
    // See: https://manpages.debian.org/buster/manpages-ja-dev/accept.2.ja.html
    int response_socket_descripter = accept(
            listen_socket_descripter,
            (struct sockaddr *)&client_request, &len);
    if (response_socket_descripter == -1) {
        strerror_r(errno, strerror_buf, STRERROR_BUF_SIZE);
        fprintf(stderr, "accept error: %d, %s.", errno, strerror_buf);
        exit(4);
    }

    // リクエスト情報確認

    // レスポンス返却
    // See: https://manpages.debian.org/buster/manpages-ja-dev/write.2.ja.html
    char hello[] = "HELLO";
    size_t write_size = write(response_socket_descripter,
            hello,
            sizeof(hello) - 1 /* `\0` は送信しない */);
    if (write_size == -1) {
        strerror_r(errno, strerror_buf, STRERROR_BUF_SIZE);
        fprintf(stderr, "write error: %d, %s.", errno, strerror_buf);
        exit(5);
    }

    // レスポンス用ソケットを閉じる
    // See: https://manpages.debian.org/buster/manpages-ja-dev/close.2.ja.html
    int response_socket_close_result = close(response_socket_descripter);
    if (response_socket_close_result == -1) {
        strerror_r(errno, strerror_buf, STRERROR_BUF_SIZE);
        fprintf(stderr, "response socket close error: %d, %s.", errno, strerror_buf);
        exit(6);
    }

    // listen 用 socket を閉じる
    // See: https://manpages.debian.org/buster/manpages-ja-dev/close.2.ja.html
    int listen_socket_close_result = close(listen_socket_descripter);
    if (listen_socket_close_result == -1) {
        strerror_r(errno, strerror_buf, STRERROR_BUF_SIZE);
        fprintf(stderr, "response socket close error: %d, %s.", errno, strerror_buf);
        exit(7);
    }

    return 0;
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>runtimeType property - PointNode class - path_finding library - Dart API</title>

    <base href="../..">

    <link href='https://fonts.googleapis.com/css?family=Source+Code+Pro|Roboto:500,400italic,300,400' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="static-assets/prettify.css">
    <link rel="stylesheet" href="static-assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="static-assets/styles.css">

    <meta name="description" content="API docs for the runtimeType property from the PointNode class, for the Dart programming language.">
    <link rel="icon" href="static-assets/favicon.png">

              <button id="sidenav-left-toggle" type="button"> </button>

path_finding

path_finding

PointNode

runtimeType

runtimeType

              <form class="search navbar-right" role="search">
                <input type="text" id="search-box" autocomplete="off" disabled class="form-control typeahead" placeholder="Loading search...">
              </form>

path_finding

path_finding

PointNode

runtimeType

property
 runtimeType

path_finding

path_finding

PointNode

Properties

hashCode

location

runtimeType

walkable

Constructors

PointNode

Operators

operator ==

Methods

noSuchMethod

toString

          Type
          runtimeType

A representation of the runtime type of the object.

                  path_finding 0.3.0

                •

                •

                  cc license


text:
module Rubygrep
  class FileSearcher
    attr_accessor :options, :found_file_names

    def initialize(options = {})
      @options = options
      @found_file_names = []
    end

    def search(file_names)
      search_with_options(file_names)
      found_file_names
    end

    private

    def search_with_options(file_names, current_folder = '.')
      file_names.each do |file_name|
        file_path = relative_path(file_name, current_folder)
        if File.directory?(file_path) && options[:recursive]
          search_with_options(inner_files(file_path), file_path)
        elsif text_file?(file_path)
          found_file_names << file_path
        elsif !File.exists?(file_path)
          puts "No such file or directory #{file_path}"
        end
      end
    end

    def inner_files(folder_name)
      Dir.entries(folder_name).select {|entry| entry != '.' and entry != '..'}
    end

    def relative_path(file_name, folder)
      if file_name =~ /^\\/ || folder == '.'
        file_name
      else
        "#{folder}/#{file_name}"
      end
    end

    def text_file?(file_name)
      File.file?(file_name)
    end

  end
end


text:
from collections import OrderedDict
import numpy as np
from pandas import Series, Panel, DataFrame, Panel4D

from trtools.core.column_panel import ColumnPanel

def box_data(keys, data=None):
    """
    Box Data into appropiate pandas object

    Parameters
    ----------
    keys : dict or iterable
        Either keys list or Result Dict
    data : iterable
        list of data
    """
    if isinstance(keys, dict):
        rdict = keys
    else:
        rdict = OrderedDict(list(zip(keys, data)))

    test = next(iter(rdict.values()))
    if np.isscalar(test):
        return Series(rdict)

    if isinstance(test, Series):
        return DataFrame(rdict)

    if isinstance(test, DataFrame):
        return Panel(rdict)

    if isinstance(test, ColumnPanel):
        data = OrderedDict([(k, v.to_panel()) for k, v  in rdict.items()])
        return Panel4D(data)

    if isinstance(test, Panel):
        return Panel4D(data)

    return rdict


text:
{% load i18n wagtailadmin_tags %}

{# The title field for a page in the page listing, when in 'explore' mode #}

    {% if page.is_site_root %}
        {% if perms.wagtailcore.add_site or perms.wagtailcore.change_site or perms.wagtailcore.delete_site %}

        {% endif %}
    {% endif %}

    {% if page_perms.can_edit %}
        {{ page.get_admin_display_title }}
    {% else %}
        {{ page.get_admin_display_title }}
    {% endif %}

    {% if show_locale_labels %}
        {{ page.locale.get_display_name }}
    {% endif %}

    {% block pages_listing_title_extra %}{% endblock pages_listing_title_extra %}

    {% include "wagtailadmin/pages/listing/_privacy_indicator.html" with page=page %}
    {% include "wagtailadmin/pages/listing/_locked_indicator.html" with page=page %}

    {% page_listing_buttons page page_perms %}


text:
namespace {

int ACMatchStyleToTagStyle(int styles) {
  int tag_styles = 0;
  if (styles & ACMatchClassification::URL)
    tag_styles |= app_list::SearchResult::Tag::URL;
  if (styles & ACMatchClassification::MATCH)
    tag_styles |= app_list::SearchResult::Tag::MATCH;
  if (styles & ACMatchClassification::DIM)
    tag_styles |= app_list::SearchResult::Tag::DIM;

  return tag_styles;
}

// Translates ACMatchClassifications into SearchResult tags.
void ACMatchClassificationsToTags(
    const string16& text,
    const ACMatchClassifications& text_classes,
    app_list::SearchResult::Tags* tags) {
  int tag_styles = app_list::SearchResult::Tag::NONE;
  size_t tag_start = 0;

  for (size_t i = 0; i < text_classes.size(); ++i) {
    const ACMatchClassification& text_class = text_classes[i];

    // Closes current tag.
    if (tag_styles != app_list::SearchResult::Tag::NONE) {
      tags->push_back(app_list::SearchResult::Tag(
          tag_styles, tag_start, text_class.offset));
      tag_styles = app_list::SearchResult::Tag::NONE;
    }

    if (text_class.style == ACMatchClassification::NONE)
      continue;

    tag_start = text_class.offset;
    tag_styles = ACMatchStyleToTagStyle(text_class.style);
  }

  if (tag_styles != app_list::SearchResult::Tag::NONE) {
    tags->push_back(app_list::SearchResult::Tag(
        tag_styles, tag_start, text.length()));
  }
}

const extensions::Extension* GetExtensionByURL(Profile* profile,
                                               const GURL& url) {
  ExtensionService* service = profile->GetExtensionService();
  // Need to explicitly get chrome app because it does not override new tab and
  // not having a web extent to include new tab url, thus GetInstalledApp does
  // not find it.
  return url.spec() == chrome::kChromeUINewTabURL ?
      service->extensions()->GetByID(extension_misc::kChromeAppId) :
      service->GetInstalledApp(url);
}

// SearchBuildResult is an app list SearchResult built from an
// AutocompleteMatch.
class SearchBuilderResult : public app_list::SearchResult,
                            public ImageLoadingTracker::Observer {
 public:
  SearchBuilderResult(Profile* profile,
                      const AutocompleteMatch& match)
      : profile_(profile),
        match_(match) {
    UpdateIcon();
    UpdateTitleAndDetails();
  }

  const AutocompleteMatch& match() const {
    return match_;
  }

 private:
  void UpdateIcon() {
    if (match_.type == AutocompleteMatch::EXTENSION_APP) {
      const extensions::Extension* extension =
          GetExtensionByURL(profile_, match_.destination_url);
      if (extension) {
        LoadExtensionIcon(extension);
        return;
      }
    }

    int resource_id = match_.starred ?
        IDR_OMNIBOX_STAR : AutocompleteMatch::TypeToIcon(match_.type);
    SetIcon(*ui::ResourceBundle::GetSharedInstance().GetBitmapNamed(
        resource_id));
  }

  void LoadExtensionIcon(const extensions::Extension* extension) {
    tracker_.reset(new ImageLoadingTracker(this));
    // TODO(xiyuan): Fix this for HD.
    tracker_->LoadImage(extension,
                        extension->GetIconResource(
                            ExtensionIconSet::EXTENSION_ICON_SMALL,
                            ExtensionIconSet::MATCH_BIGGER),
                        gfx::Size(ExtensionIconSet::EXTENSION_ICON_SMALL,
                                  ExtensionIconSet::EXTENSION_ICON_SMALL),
                        ImageLoadingTracker::DONT_CACHE);
  }

  void UpdateTitleAndDetails() {
    set_title(match_.contents);
    app_list::SearchResult::Tags title_tags;
    ACMatchClassificationsToTags(match_.contents,
                                 match_.contents_class,
                                 &title_tags);
    set_title_tags(title_tags);

    set_details(match_.description);
    app_list::SearchResult::Tags details_tags;
    ACMatchClassificationsToTags(match_.description,
                                 match_.description_class,
                                 &details_tags);
    set_details_tags(details_tags);
  }

  // Overridden from ImageLoadingTracker::Observer:
  virtual void OnImageLoaded(const gfx::Image& image,
                             const std::string& extension_id,
                             int tracker_index) OVERRIDE {
    if (!image.IsEmpty()) {
      SetIcon(*image.ToSkBitmap());
      return;
    }

    SetIcon(profile_->GetExtensionService()->GetOmniboxPopupIcon(extension_id));
  }

  Profile* profile_;
  AutocompleteMatch match_;
  scoped_ptr<ImageLoadingTracker> tracker_;

  DISALLOW_COPY_AND_ASSIGN(SearchBuilderResult);
};

}  // namespace

SearchBuilder::SearchBuilder(
    Profile* profile,
    app_list::SearchBoxModel* search_box,
    app_list::AppListModel::SearchResults* results)
    : profile_(profile),
      search_box_(search_box),
      results_(results) {
  search_box_->SetHintText(
      l10n_util::GetStringUTF16(IDS_SEARCH_BOX_HINT));
  search_box_->SetIcon(*ui::ResourceBundle::GetSharedInstance().
      GetImageSkiaNamed(IDR_OMNIBOX_SEARCH));

  if (CommandLine::ForCurrentProcess()->HasSwitch(
          app_list::switches::kAppListShowAppsOnly)) {
    // ExtensionAppProvider is a synchronous provider and does not really need a
    // listener.
    apps_provider_ = new ExtensionAppProvider(NULL, profile);
  } else {
    controller_.reset(new AutocompleteController(profile, this));
  }
}

SearchBuilder::~SearchBuilder() {
}

void SearchBuilder::StartSearch() {
  const string16& user_text = search_box_->text();

  if (controller_.get()) {
    // Omnibox features such as keyword selection/accepting and instant query
    // are not implemented.
    // TODO(xiyuan): Figure out the features that need to support here.
    controller_->Start(user_text, string16(), false, false, true,
        AutocompleteInput::ALL_MATCHES);
  } else {
    AutocompleteInput input(user_text, string16(), false, false, true,
        AutocompleteInput::ALL_MATCHES);
    apps_provider_->Start(input, false);

    // ExtensionAppProvider is a synchronous provider and results are ready
    // after returning from Start.
    AutocompleteResult ac_result;
    ac_result.AppendMatches(apps_provider_->matches());
    ac_result.SortAndCull(input);
    PopulateFromACResult(ac_result);
  }
}

void SearchBuilder::StopSearch() {
  if (controller_.get())
    controller_->Stop(true);
  else
    apps_provider_->Stop(true);
}

void SearchBuilder::OpenResult(const app_list::SearchResult& result,
                               int event_flags) {
  const SearchBuilderResult* builder_result =
      static_cast<const SearchBuilderResult*>(&result);
  const AutocompleteMatch& match = builder_result->match();

  if (match.type == AutocompleteMatch::EXTENSION_APP) {
    const extensions::Extension* extension =
        GetExtensionByURL(profile_, match.destination_url);
    if (extension)
      extension_utils::OpenExtension(profile_, extension, event_flags);
  } else {
    WindowOpenDisposition disposition =
        chrome::DispositionFromEventFlags(event_flags);
    Browser* browser = browser::FindOrCreateTabbedBrowser(profile_);

    if (disposition == CURRENT_TAB) {
      // If current tab is not NTP, change disposition to NEW_FOREGROUND_TAB.
      const GURL& url = chrome::GetActiveWebContents(browser) ?
          chrome::GetActiveWebContents(browser)->GetURL() : GURL();
      if (!url.SchemeIs(chrome::kChromeUIScheme) ||
          url.host() != chrome::kChromeUINewTabHost) {
        disposition = NEW_FOREGROUND_TAB;
      }
    }

    // TODO(xiyuan): What should we do for alternate url case?
    browser->OpenURL(
        content::OpenURLParams(match.destination_url,
                               content::Referrer(),
                               disposition,
                               match.transition,
                               false));
  }
}

void SearchBuilder::PopulateFromACResult(const AutocompleteResult& ac_result) {
  results_->DeleteAll();
  for (ACMatches::const_iterator it = ac_result.begin();
       it != ac_result.end();
       ++it) {
    results_->Add(new SearchBuilderResult(profile_, *it));
  }
}

void SearchBuilder::OnResultChanged(bool default_match_changed) {
  // TODO(xiyuan): Handle default match properly.
  const AutocompleteResult& ac_result = controller_->result();
  PopulateFromACResult(ac_result);
}


text:
import re
"""
Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.

If the last word does not exist, return 0.

Note: A word is defined as a character sequence consists of non-space characters only.

For example,
Given s = "Hello World",
return 5.
"""

class Solution(object):
    def lengthOfLastWord(self, s):
        if not re.search('[a-zA-Z]', s):
            return 0
        else:
            lst = s.split()
            return len(lst[-1])


text:
require "action_view"

module Sprockets
  module Helpers
    module RailsHelper
      extend ActiveSupport::Concern
      include ActionView::Helpers::AssetTagHelper

      def asset_paths
        @asset_paths ||= begin
          paths = RailsHelper::AssetPaths.new(config, controller)
          paths.asset_environment = asset_environment
          paths.asset_digests     = asset_digests
          paths.compile_assets    = compile_assets?
          paths.digest_assets     = digest_assets?
          paths
        end
      end

      def javascript_include_tag(*sources)
        options = sources.extract_options!
        debug = options.key?(:debug) ? options.delete(:debug) : debug_assets?
        body  = options.key?(:body)  ? options.delete(:body)  : false
        digest  = options.key?(:digest)  ? options.delete(:digest)  : digest_assets?

        sources.collect do |source|
          if debug && asset = asset_paths.asset_for(source, 'js')
            asset.to_a.map { |dep|
              super(dep.pathname.to_s, { :src => path_to_asset(dep, :ext => 'js', :body => true, :digest => digest) }.merge!(options))
            }
          else
            super(source.to_s, { :src => path_to_asset(source, :ext => 'js', :body => body, :digest => digest) }.merge!(options))
          end
        end.uniq.join("\n").html_safe
      end

      def stylesheet_link_tag(*sources)
        options = sources.extract_options!
        debug   = options.key?(:debug) ? options.delete(:debug) : debug_assets?
        body    = options.key?(:body)  ? options.delete(:body)  : false
        digest  = options.key?(:digest)  ? options.delete(:digest)  : digest_assets?

        sources.collect do |source|
          if debug && asset = asset_paths.asset_for(source, 'css')
            asset.to_a.map { |dep|
              super(dep.pathname.to_s, { :href => path_to_asset(dep, :ext => 'css', :body => true, :protocol => :request, :digest => digest) }.merge!(options))
            }
          else
            super(source.to_s, { :href => path_to_asset(source, :ext => 'css', :body => body, :protocol => :request, :digest => digest) }.merge!(options))
          end
        end.uniq.join("\n").html_safe
      end

      def asset_path(source, options = {})
        source = source.logical_path if source.respond_to?(:logical_path)
        path = asset_paths.compute_public_path(source, asset_prefix, options.merge(:body => true))
        options[:body] ? "#{path}?body=1" : path
      end
      alias_method :path_to_asset, :asset_path # aliased to avoid conflicts with an asset_path named route

      def image_path(source)
        path_to_asset(source)
      end
      alias_method :path_to_image, :image_path # aliased to avoid conflicts with an image_path named route

      def font_path(source)
        path_to_asset(source)
      end
      alias_method :path_to_font, :font_path # aliased to avoid conflicts with an font_path named route

      def javascript_path(source)
        path_to_asset(source, :ext => 'js')
      end
      alias_method :path_to_javascript, :javascript_path # aliased to avoid conflicts with an javascript_path named route

      def stylesheet_path(source)
        path_to_asset(source, :ext => 'css')
      end
      alias_method :path_to_stylesheet, :stylesheet_path # aliased to avoid conflicts with an stylesheet_path named route

    private
      def debug_assets?
        compile_assets? && (Rails.application.config.assets.debug || params[:debug_assets])
      rescue NameError
        false
      end

      # Override to specify an alternative prefix for asset path generation.
      # When combined with a custom +asset_environment+, this can be used to
      # implement themes that can take advantage of the asset pipeline.
      #
      # If you only want to change where the assets are mounted, refer to
      # +config.assets.prefix+ instead.
      def asset_prefix
        Rails.application.config.assets.prefix
      end

      def asset_digests
        Rails.application.config.assets.digests
      end

      def compile_assets?
        Rails.application.config.assets.compile
      end

      def digest_assets?
        Rails.application.config.assets.digest
      end

      # Override to specify an alternative asset environment for asset
      # path generation. The environment should already have been mounted
      # at the prefix returned by +asset_prefix+.
      def asset_environment
        Rails.application.assets
      end

      class AssetPaths < ::ActionView::AssetPaths #:nodoc:
        attr_accessor :asset_environment, :asset_prefix, :asset_digests, :compile_assets, :digest_assets

        class AssetNotPrecompiledError < StandardError; end

        def asset_for(source, ext)
          source = source.to_s
          return nil if is_uri?(source)
          source = rewrite_extension(source, nil, ext)
          asset_environment[source]
        rescue Sprockets::FileOutsidePaths
          nil
        end

        def digest_for(logical_path)
          if digest_assets && asset_digests && (digest = asset_digests[logical_path])
            return digest
          end

          if compile_assets
            if digest_assets && asset = asset_environment[logical_path]
              return asset.digest_path
            end
            return logical_path
          else
            raise AssetNotPrecompiledError.new("#{logical_path} isn't precompiled")
          end
        end

        def rewrite_asset_path(source, dir, options = {})
          if source[0] == ?/
            source
          else
            if digest_assets && options[:digest] != false
              source = digest_for(source)
            end
            source = File.join(dir, source)
            source = "/#{source}" unless source =~ /^\//
            source
          end
        end

        def rewrite_extension(source, dir, ext)
          source_ext = File.extname(source)
          if ext && source_ext != ".#{ext}"
            if !source_ext.empty? && (asset = asset_environment[source]) &&
                  asset.pathname.to_s =~ /#{source}\Z/
              source
            else
              "#{source}.#{ext}"
            end
          else
            source
          end
        end
      end
    end
  end
end


text:
import {InboxItem} from "./inbox-item";
import {Item} from "./item";
import {Address} from "./address";
import {Customer} from "./customer";

export class Order extends InboxItem {
  constructor() {
    super('Order');
    this.shippingAddress = new Address;
    this.billingAddress = new Address;
    this.orderDate = new Date();
    this.orderPlacedDate =  new Date();
    this.transitDate = new Date();
    this.completionDate = new Date();
    this.items = Array<Item>();
  }

  _id: string;
  orderDate:Date;
  orderPlacedDate: Date;
  transitDate: Date;
  completionDate:Date;
  status:string;
  orderType:string;
  remarks: string;
  customer: Customer;
  totalAmount: number;
  items: Array<Item>;
  shippingAddress: Address;
  billingAddress: Address;

  search(searchFor : string) : boolean{
    var item;
    /*this.items.forEach((item));*/
    //return this.items.toLowerCase().search(searchFor) !== -1;
    return false;
  }

}


text:
{% load staticfiles %}

        <link rel="stylesheet" type="text/css" href="{% static "bootstrap/css/bootstrap.min.css" %}">

            {% block content %}
            {% verbatim %}

{{ memo.title }}

                    <author class="pull-right">{{ memo.author }}</author>

                    Created Datetime: {{ memo.created }}

                    Message: {{ memo.message }}

                    Alarm: {{ memo.alarm }}

                    Alarm Datetime: {{ memo.datetime }}

                    Notebook: {{ memo.notebook }}

                    Recipients: {{ memo.recipients }}

            {% endverbatim %}
            {% endblock %}


text:
import java.util.stream.IntStream;

public class Main {
  private static long check(int start, int stop, double v) {
    return IntStream.range(start, stop).mapToDouble(x -> 1.0 / x).filter(x -> x < v).cou<caret>nt();
  }

  public static void main(String[] args) {
    System.out.println(check(1, 100, 0.04));
  }
}


text:
require "spec_helper"
require "app/jobs/buildable"
require "app/models/payload"
require "app/services/build_runner"
require "raven"

describe Buildable do
  class BuildableTestJob < ActiveJob::Base
    include Buildable
  end

  describe "perform" do
    it 'runs build runner' do
      stub_const("Owner", "foo")
      build_runner = double(:build_runner, run: nil)
      payload_data = "some data"
      payload = double("Payload")
      allow(Payload).to receive(:new).with(payload_data).and_return(payload)
      allow(BuildRunner).to receive(:new).and_return(build_runner)
      allow(Owner).to receive(:upsert)

      BuildableTestJob.perform_now(payload_data)

      expect(Payload).to have_received(:new).with(payload_data)
      expect(BuildRunner).to have_received(:new).with(payload)
      expect(build_runner).to have_received(:run)
    end
  end

  def payload_data(github_id: 1234, name: "test")
    {
      "repository" => {
        "owner" => {
          "id" => github_id,
          "login" => name,
          "type" => "Organization"
        }
      }
    }
  end
end


text:
public class oz {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		insertpicture mFrm = new insertpicture();
		mFrm.setVisible(true);
}}


text:
using System;
using System.Xml.Serialization;

namespace Aop.Api.Domain
{
    /// <summary>
    /// SupplierVO Data Structure.
    /// </summary>
    [Serializable]
    public class SupplierVO : AopObject
    {
        /// <summary>
        /// 生效状态,EFFECTIVE:生效,INVALID:失效。
        /// </summary>
        [XmlElement("biz_status")]
        public string BizStatus { get; set; }

        /// <summary>
        /// 快餐
        /// </summary>
        [XmlElement("business_desc")]
        public string BusinessDesc { get; set; }

        /// <summary>
        /// 供应商附加信息,LICENSE_NO:许可证号,LICENSE_DATE:营业执照有效期,PAYMENT_DAYS:账期
        /// </summary>
        [XmlElement("certificate_desc")]
        public string CertificateDesc { get; set; }

        /// <summary>
        /// 供货商简码
        /// </summary>
        [XmlElement("short_code")]
        public string ShortCode { get; set; }

        /// <summary>
        /// 供货商ID
        /// </summary>
        [XmlElement("supplier_id")]
        public string SupplierId { get; set; }

        /// <summary>
        /// 张三
        /// </summary>
        [XmlElement("supplier_name")]
        public string SupplierName { get; set; }
    }
}


text:
from module_base import ModuleBase
from module_mixins import FilenameViewModuleMixin
import module_utils
import vtk

class vtkStructPtsRDR(FilenameViewModuleMixin, ModuleBase):

    def __init__(self, module_manager):

        # call parent constructor
        ModuleBase.__init__(self, module_manager)

        self._reader = vtk.vtkStructuredPointsReader()

        # ctor for this specific mixin
        FilenameViewModuleMixin.__init__(
            self,
            'Select a filename',
            'VTK data (*.vtk)|*.vtk|All files (*)|*',
            {'vtkStructuredPointsReader': self._reader})

        module_utils.setup_vtk_object_progress(
            self, self._reader,
            'Reading vtk structured points data')

        # set up some defaults
        self._config.filename = ''
        self.sync_module_logic_with_config()

    def close(self):
        del self._reader
        FilenameViewModuleMixin.close(self)

    def get_input_descriptions(self):
        return ()

    def set_input(self, idx, input_stream):
        raise Exception

    def get_output_descriptions(self):
        return ('vtkStructuredPoints',)

    def get_output(self, idx):
        return self._reader.GetOutput()

    def logic_to_config(self):
        filename = self._reader.GetFileName()
        if filename == None:
            filename = ''

        self._config.filename = filename

    def config_to_logic(self):
        self._reader.SetFileName(self._config.filename)

    def view_to_config(self):
        self._config.filename = self._getViewFrameFilename()

    def config_to_view(self):
        self._setViewFrameFilename(self._config.filename)

    def execute_module(self):
        # get the vtkPolyDataReader to try and execute
        if len(self._reader.GetFileName()):
            self._reader.Update()


text:
<?php

namespace Vibius\AbstractTemplating\Engines;

use Vibius\AbstractTemplating\EngineInterface;

use Everzet\Jade\Dumper\PHPDumper as PHPDumper;
use Everzet\Jade\Visitor\AutotagsVisitor as AutotagsVisitor;
use Everzet\Jade\Filter\JavaScriptFilter as JavaScriptFilter;
use Everzet\Jade\Filter\CDATAFilter as CDATAFilter;
use Everzet\Jade\Filter\PHPFilter as PHPFilter;
use Everzet\Jade\Filter\CSSFilter as CSSFilter;

use Everzet\Jade\Parser as Parser;
use Everzet\Jade\Lexer\Lexer as Lexer;
use Everzet\Jade\Jade as JadeEngine;

class Jade implements EngineInterface{

	use \Vibius\AbstractTemplating\EngineHelpers;

	public $variables = [];

	public $htmlParseable = true;

	public $extensions = [
		'php', 'blade.php', 'html'
	];

	public $engine;

	public function __construct(){

		$dumper = new PHPDumper();
		$dumper->registerVisitor('tag', new AutotagsVisitor());
		$dumper->registerFilter('javascript', new JavaScriptFilter());
		$dumper->registerFilter('cdata', new CDATAFilter());
		$dumper->registerFilter('php', new PHPFilter());
		$dumper->registerFilter('style', new CSSFilter());

		// Initialize parser & Jade
		$parser = new Parser(new Lexer());
		$this->engine  = new JadeEngine($parser, $dumper);

	}

	public function assign($variables){
		$this->variables = $variables;
	}

	public function render($content){
		echo $this->engine->render($content);
	}

}


text:
# Moment-Generating Function

> [Bernoulli][bernoulli-distribution] distribution moment-generating function (MGF).

The [moment-generating function][mgf] for a [Bernoulli][bernoulli-distribution] random variable is

where `0 <= p <= 1` is the success probability.

## Usage

```javascript
var mgf = require( '@stdlib/stats/base/dists/bernoulli/mgf' );
```

#### mgf( t, p )

Evaluates the moment-generating function ([MGF][mgf]) of a [Bernoulli][bernoulli-distribution] distribution with success probability `p`.

```javascript
var y = mgf( 0.2, 0.5 );
// returns ~1.111

y = mgf( 0.4, 0.5 );
// returns ~1.246
```

If provided `NaN` as any argument, the function returns `NaN`.

```javascript
var y = mgf( NaN, 0.0 );
// returns NaN

y = mgf( 0.0, NaN );
// returns NaN
```

If provided a success probability `p` outside of the interval `[0,1]`, the function returns `NaN`.

```javascript
var y = mgf( -2.0, -1.0 );
// returns NaN

y = mgf( 0.2, 2.0 );
// returns NaN
```

#### mgf.factory( p )

Returns a function for evaluating the [moment-generating function][mgf] of a [Bernoulli][bernoulli-distribution] distribution with parameter `p` (success probability).

```javascript
var mymgf = mgf.factory( 0.8 );
var y = mymgf( -0.2 );
// returns ~0.855
```

## Examples

```javascript
var randu = require( '@stdlib/random/base/randu' );
var mgf = require( '@stdlib/stats/base/dists/bernoulli/mgf' );

var p;
var t;
var y;
var i;

for ( i = 0; i < 10; i++ ) {
    t = ( randu() * 4.0 ) - 2.0;
    p = randu();
    y = mgf( t, p );
    console.log( 't: %d, p: %d, M_X(t;p): %d', t, p.toFixed( 4 ), y.toFixed( 4 ) );
}
```

[bernoulli-distribution]: https://en.wikipedia.org/wiki/Bernoulli_distribution

[mgf]: https://en.wikipedia.org/wiki/Moment-generating_function


text:
@interface ViewController : UIViewController

@property (weak, nonatomic) IBOutlet UIView *view_color;

@end


text:
require 'vpsa/entity/base'

module Vpsa
  module Entity
    module Commercial
      class Installment < Base
        attr_accessor :"bloquearSemAnalise", :bloqueio, :"mensagemBloqueio", :"liberarValorExcedente", :"liberarBloqueioManual", :"venderSemAnalise"
        attr_accessor :"creditoMaximoPorCliente", :"valorCreditoMaximoPorCliente", :"calculoValorCredito", :"limiteMensalMaximo"
      end
    end
  end
end


text:
using System.Data.Common;
using System.Data.Entity.Core.Objects;
using System.Linq;

namespace EntityFramework.Future
{
    /// <summary>
    /// Interface for defering the future execution of a batch of queries.
    /// </summary>
    public interface IFutureQuery
    {
        /// <summary>
        /// Gets a value indicating whether this instance is loaded.
        /// </summary>
        /// <value><c>true</c> if this instance is loaded; otherwise, <c>false</c>.</value>
        bool IsLoaded { get; }

        /// <summary>
        /// Gets the query source to use when materializing.
        /// </summary>
        /// <value>The query source to use when materializing.</value>
        IQueryable Query { get; }

        /// <summary>
        /// Gets the data command for this query.
        /// </summary>
        /// <param name="dataContext">The data context to get the plan from.</param>
        /// <returns>The requested FuturePlan object.</returns>
        FuturePlan GetPlan(ObjectContext dataContext);

        /// <summary>
        /// Sets the underling value after the query has been executed.
        /// </summary>
        /// <param name="dataContext">The data context to translate the results with.</param>
        /// <param name="reader">The <see cref="DbDataReader"/> to get the result from.</param>
        void SetResult(ObjectContext dataContext, DbDataReader reader);
    }
}


text:
@implementation ABI42_0_0EXFaceDetectorManagerProvider

ABI42_0_0UM_REGISTER_MODULE();

+ (const NSArray<Protocol *> *)exportedInterfaces {
  return @[@protocol(ABI42_0_0EXFaceDetectorManagerProviderInterface)];
}

- (id<ABI42_0_0EXFaceDetectorManagerInterface>)createFaceDetectorManager {
  return [[ABI42_0_0EXFaceDetectorManager alloc] init];
}

@end


text:
int main(int argc, char** argv) {
	QApplication app(argc, argv);
	QGuiApplication::setApplicationDisplayName("ccnt - colony counter");
	QCommandLineParser commandLineParser;
	commandLineParser.addHelpOption();
	commandLineParser.addPositionalArgument("[file]", "Image file to open.");
	commandLineParser.process(QCoreApplication::arguments());
	ccnt::Window window;
	if (!commandLineParser.positionalArguments().isEmpty()) {
		window.loadImage(commandLineParser.positionalArguments().front());
	}
	window.showMaximized();
	return app.exec();
}


text:
define("dojox/calendar/StoreManager",["dojo/_base/declare","dojo/_base/array","dojo/_base/html","dojo/_base/lang","dojo/dom-class","dojo/Stateful","dojo/Evented","dojo/when"],function(_1,_2,_3,_4,_5,_6,_7,_8){
return _1("dojox.calendar.StoreManager",[_6,_7],{owner:null,store:null,_ownerItemsProperty:null,_getParentStoreManager:function(){
if(this.owner&&this.owner.owner){
return this.owner.owner.get("storeManager");
}
return null;
},_initItems:function(_9){
this.set("items",_9);
return _9;
},_itemsSetter:function(_a){
this.items=_a;
this.emit("dataLoaded",_a);
},_computeVisibleItems:function(_b){
var _c=_b.startTime;
var _d=_b.endTime;
var _e=null;
var _f=this.owner[this._ownerItemsProperty];
if(_f){
_e=_2.filter(_f,function(_10){
return this.owner.isOverlapping(_b,_10.startTime,_10.endTime,_c,_d);
},this);
}
return _e;
},_updateItems:function(_11,_12,_13){
var _14=true;
var _15=null;
var _16=this.owner.itemToRenderItem(_11,this.store);
_16._item=_11;
this.items=this.owner[this._ownerItemsProperty];
if(_12!==-1){
if(_13!==_12){
this.items.splice(_12,1);
if(this.owner.setItemSelected&&this.owner.isItemSelected(_16)){
this.owner.setItemSelected(_16,false);
this.owner.dispatchChange(_16,this.get("selectedItem"),null,null);
}
}else{
_15=this.items[_12];
var cal=this.owner.dateModule;
_14=cal.compare(_16.startTime,_15.startTime)!==0||cal.compare(_16.endTime,_15.endTime)!==0;
_4.mixin(_15,_16);
}
}else{
if(_13!==-1){
var l,i;
var _17=_11.temporaryId;
if(_17){
l=this.items?this.items.length:0;
for(i=l-1;i>=0;i--){
if(this.items[i].id===_17){
this.items[i]=_16;
break;
}
}
var _18=this._getItemStoreStateObj({id:_17});
this._cleanItemStoreState(_17);
this._setItemStoreState(_16,_18?_18.state:null);
}
var s=this._getItemStoreStateObj(_16);
if(s&&s.state==="storing"){
if(this.items&&this.items[_13]&&this.items[_13].id!==_16.id){
l=this.items.length;
for(i=l-1;i>=0;i--){
if(this.items[i].id===_16.id){
this.items.splice(i,1);
break;
}
}
this.items.splice(_13,0,_16);
}
_4.mixin(s.renderItem,_16);
}else{
this.items.splice(_13,0,_16);
}
this.set("items",this.items);
}
}
this._setItemStoreState(_16,"stored");
if(!this.owner._isEditing){
if(_14){
this.emit("layoutInvalidated");
}else{
this.emit("renderersInvalidated",_15);
}
}
},_storeSetter:function(_19){
var r;
var _1a=this.owner;
if(this._observeHandler){
this._observeHandler.remove();
this._observeHandler=null;
}
if(_19){
var _1b=_19.query(_1a.query,_1a.queryOptions);
if(_1b.observe){
this._observeHandler=_1b.observe(_4.hitch(this,this._updateItems),true);
}
_1b=_1b.map(_4.hitch(this,function(_1c){
var _1d=_1a.itemToRenderItem(_1c,_19);
_1d._item=_1c;
return _1d;
}));
r=_8(_1b,_4.hitch(this,this._initItems));
}else{
r=this._initItems([]);
}
this.store=_19;
return r;
},_getItemStoreStateObj:function(_1e){
var _1f=this._getParentStoreManager();
if(_1f){
return _1f._getItemStoreStateObj(_1e);
}
var _20=this.get("store");
if(_20!=null&&this._itemStoreState!=null){
var id=_1e.id===undefined?_20.getIdentity(_1e):_1e.id;
return this._itemStoreState[id];
}
return null;
},getItemStoreState:function(_21){
var _22=this._getParentStoreManager();
if(_22){
return _22.getItemStoreState(_21);
}
if(this._itemStoreState==null){
return "stored";
}
var _23=this.get("store");
var id=_21.id===undefined?_23.getIdentity(_21):_21.id;
var s=this._itemStoreState[id];
if(_23!=null&&s!==undefined){
return s.state;
}
return "stored";
},_cleanItemStoreState:function(id){
var _24=this._getParentStoreManager();
if(_24){
return _24._cleanItemStoreState(id);
}
if(!this._itemStoreState){
return;
}
var s=this._itemStoreState[id];
if(s){
delete this._itemStoreState[id];
return true;
}
return false;
},_setItemStoreState:function(_25,_26){
var _27=this._getParentStoreManager();
if(_27){
_27._setItemStoreState(_25,_26);
return;
}
if(this._itemStoreState===undefined){
this._itemStoreState={};
}
var _28=this.get("store");
var id=_25.id===undefined?_28.getIdentity(_25):_25.id;
var s=this._itemStoreState[id];
if(_26==="stored"||_26==null){
if(s!==undefined){
delete this._itemStoreState[id];
}
return;
}
if(_28){
this._itemStoreState[id]={id:id,item:_25,renderItem:this.owner.itemToRenderItem(_25,_28),state:_26};
}
}});
});


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>{{ title }}</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.6.0/styles/default.min.css">

{{ page_title }} version {{ page_version }}

      <form method="post">

         Json:
         <textarea required name="jsondata" class="form-control" rows="10">{{ json_string }}</textarea>
         <button type="submit" class="btn btn-primary">Submit</button>

      </form>

      {% if error_string %}

{{ error_string }}

      {% endif %}

      {% if not error_string and json_pretty %}

JSON is valid.

      {% endif %}

    {% if json_pretty %}

{{ json_pretty }}

    {% endif %}


text:
// Needed to avoid linking in libstdc++
#ifndef __STL_USE_EXCEPTIONS
#   include <java/lang/OutOfMemoryError.h>
#   define __THROW_BAD_ALLOC throw new java::lang::OutOfMemoryError()
#endif

#include <vector>

#include <X11/Xlib.h>
#include <gcj/cni.h>
#include <java/awt/Rectangle.h>
#include <gnu/gcj/xlib/Display.h>
#include <gnu/gcj/xlib/Window.h>
#include <gnu/gcj/xlib/WindowAttributes.h>
#include <gnu/gcj/xlib/Visual.h>
#include <gnu/gcj/xlib/XException.h>

jint gnu::gcj::xlib::Window::createChildXID(::java::awt::Rectangle* bounds,
					jint borderWidth,
					WindowAttributes* attributes,
					jint windowIOClass,
					Visual* visual)
{
  ::Window parentXID = xid;

  int x      = bounds->x;
  int y      = bounds->y;
  int width  = bounds->width;
  int height = bounds->height;

  long mask = attributes->mask;
  XSetWindowAttributes* attr = (XSetWindowAttributes*)
    attributes->getXSetWindowAttributesStructure();

  ::Visual* vis = CopyFromParent;
  int depth = CopyFromParent;
  if (visual != 0)
    {
      vis = (::Visual*) visual->getVisualStructure();
      depth = visual->getDepth();
    }

  ::Window childXID = XCreateWindow((::Display*) (display->display),
				    parentXID,
				    x, y, width, height,
				    borderWidth, depth, windowIOClass,
				    vis,
				    mask, attr);
  // no fast fail
  return childXID;
}

void gnu::gcj::xlib::Window::destroy()
{
  ::Display* dpy = (::Display*) (display->display);
  ::Window window = xid;
  XDestroyWindow(dpy, window);
  // no fast fail
}

void gnu::gcj::xlib::Window::setAttributes(WindowAttributes* attributes)
{
  ::Display* dpy = (::Display*) (display->display);
  ::Window window = xid;
  ::XSetWindowAttributes* attr = (::XSetWindowAttributes*)
      attributes->getXSetWindowAttributesStructure();

  XChangeWindowAttributes(dpy, window, attributes->mask, attr);
  // no fast fail
}

void gnu::gcj::xlib::Window::toBack()
{
  ::Display* dpy = (::Display*) (display->display);
  ::Window window = xid;
  XLowerWindow(dpy, window);
}

void gnu::gcj::xlib::Window::toFront()
{
  ::Display* dpy = (::Display*) (display->display);
  ::Window window = xid;
  XRaiseWindow(dpy, window);
}

void gnu::gcj::xlib::Window::map()
{
  ::Display* dpy = (::Display*) (display->display);
  ::Window window = xid;
  XMapWindow(dpy, window);
  // no fast fail
}

void gnu::gcj::xlib::Window::unmap()
{
  ::Display* dpy = (::Display*) (display->display);
  ::Window window = xid;
  XUnmapWindow(dpy, window);
  // no fast fail
}

void gnu::gcj::xlib::Window::setProperty(jint nameAtom, jint typeAtom,
					 jbyteArray data)
{
  ::Display* dpy = (::Display*) (display->display);
  int format = 8;
  int mode = PropModeReplace;
  unsigned char* pData = (unsigned char*) elements(data);
  int len = data->length;

  XChangeProperty(dpy, xid, nameAtom, typeAtom, format, mode,
		  pData, len);
  // no fast fail
}

void gnu::gcj::xlib::Window::setWMProtocols(jintArray atoms)
{
  ::Display* dpy = (::Display*) (display->display);

  size_t length = atoms->length;
  jint* atomsBegin = elements(atoms);
  jint* atomsEnd   = atomsBegin + length;

  // Avoid confusion between Xlib.h and Atom.java "Atom" types.
  typedef ::Atom XLibAtom;

  std::vector<XLibAtom> atomVector(atomsBegin, atomsEnd);
  XLibAtom* atomsArray = &(atomVector.front());

  XSetWMProtocols(dpy, xid, atomsArray, length);
  // no fail fast
}

jintArray gnu::gcj::xlib::Window::getWMProtocols()
{
  ::Display* dpy = (::Display*) (display->display);

  ::Atom* protocolsReturn;
  int countReturn;

  Status success = XGetWMProtocols(dpy, xid, &protocolsReturn,
				   &countReturn);

  if (!success)
    throw new XException(JvNewStringLatin1("cannot get "
					   "WM protocols "));

  jintArray atoms;
  try
    {
      ::Atom* protocolsBegin = protocolsReturn;
      ::Atom* protocolsEnd = protocolsBegin + countReturn;

      atoms = JvNewIntArray(countReturn);
      jint* atomsBegin = elements(atoms);

      std::copy(protocolsBegin, protocolsEnd, atomsBegin);

    }
  catch (...)
    {
      XFree(protocolsReturn);
      throw;
    }
  XFree(protocolsReturn);

  return atoms;
}

void gnu::gcj::xlib::Window::setBounds(jint x, jint y,
				       jint width, jint height)
{
  ::Display* dpy = (::Display*) (display->display);

  XMoveResizeWindow(dpy, xid, x, y, width, height);
  // no fast fail
}


text:
import { combineReducers } from 'redux';

const appReducer = (state = {}) => state;

export default combineReducers({
  app: appReducer,
});


text:
title: "Modify your account's information"
excerpt: "This page guides you to change your name, email address or password, as a user."
---
[block:callout]
{
  "type": "danger",
  "title": "This feature is only available for users!"
}
[/block]

[block:image]
{
  "images": [
    {
      "image": [
        "https://files.readme.io/990a3c3-profile_overview_201.png",
        "profile_overview_201.png",
        2550,
        1352,
        "#046cb4"
      ]
    }
  ]
}
[/block]

[block:api-header]
{
  "type": "basic",
  "title": "Modify your first or last name"
}
[/block]
1. Click :fa-pencil:. You enter in edition mode.
2. Modify your first or last name.
3. Click :fa-check: to validate your changes.
[block:callout]
{
  "type": "success",
  "title": "You have successfully modified your name!"
}
[/block]

[block:api-header]
{
  "type": "basic",
  "title": "Modify your email address"
}
[/block]
1. Click :fa-pencil:. You enter in edition mode.
2. Update your email address.
3. Click :fa-check: to validate your changes.
[block:callout]
{
  "type": "success",
  "title": "You have successfully updated your email address!"
}
[/block]

[block:api-header]
{
  "type": "basic",
  "title": "Modify your password"
}
[/block]
1. Click :fa-pencil:. You enter in edition mode.
2. Modify your password.
3. Click :fa-check: to validate your changes.
[block:callout]
{
  "type": "success",
  "title": "You have successfully modified your password!"
}
[/block]


text:
<?php

namespace LengthOfRope\JSONLD\Schema;

/**
 * A part of a successively published publication such as a periodical or publication volume, often numbered, usually containing a grouping of works such as articles.

See also blog post.
 *
 * @author LengthOfRope, Bas de Kort <bdekort@gmail.com>
 **/
class PublicationIssueSchema extends CreativeWorkSchema
{
    public static function factory()
    {
        return new PublicationIssueSchema('http://schema.org/', 'PublicationIssue');
    }

    /**
     * Identifies the issue of publication; for example, "iii" or "2".
     *
     * @param $issueNumber IntegerSchema|TextSchema
     **/
    public function setIssueNumber($issueNumber) {
        $this->properties['issueNumber'] = $issueNumber;

        return $this;
    }

    /**
     * @return IntegerSchema|TextSchema
     **/
    public function getIssueNumber() {
        return $this->properties['issueNumber'];
    }

    /**
     * The page on which the work ends; for example "138" or "xvi".
     *
     * @param $pageEnd IntegerSchema|TextSchema
     **/
    public function setPageEnd($pageEnd) {
        $this->properties['pageEnd'] = $pageEnd;

        return $this;
    }

    /**
     * @return IntegerSchema|TextSchema
     **/
    public function getPageEnd() {
        return $this->properties['pageEnd'];
    }

    /**
     * The page on which the work starts; for example "135" or "xiii".
     *
     * @param $pageStart IntegerSchema|TextSchema
     **/
    public function setPageStart($pageStart) {
        $this->properties['pageStart'] = $pageStart;

        return $this;
    }

    /**
     * @return IntegerSchema|TextSchema
     **/
    public function getPageStart() {
        return $this->properties['pageStart'];
    }

    /**
     * Any description of pages that is not separated into pageStart and pageEnd; for example, "1-6, 9, 55" or "10-12, 46-49".
     *
     * @param $pagination TextSchema
     **/
    public function setPagination($pagination) {
        $this->properties['pagination'] = $pagination;

        return $this;
    }

    /**
     * @return TextSchema
     **/
    public function getPagination() {
        return $this->properties['pagination'];
    }

}


text:
- [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry


text:
package com.streamsets.datacollector.usagestats;

import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.Multimap;
import com.streamsets.datacollector.usagestats.TestStatsInfo.TestModelStatsExtension;
import org.junit.Assert;
import org.junit.Test;

public class TestStatsBean {

  @Test
  public void testReported() {
    StatsBean bean = new StatsBean();

    // not reported on creation
    Assert.assertFalse(bean.isReported());

    bean.setReported();
    Assert.assertTrue(bean.isReported());

  }
  @Test
  public void testCreationFromActiveStats() {
    TestModelStatsExtension ext = new TestModelStatsExtension();
    StatsInfo si = new StatsInfo(ImmutableList.of(ext));
    ext.setStatsInfo(si);

    ActiveStats as = new ActiveStats(ImmutableList.of(ext));
    as.setStatsInfo(si);
    as.setDpmEnabled(true);
    as.setDataCollectorVersion("version");
    as.setUpTime(new UsageTimer().setName("upTime").setAccumulatedTime(1));
    as.setStartTime(1);
    as.setEndTime(3);
    as.setRecordCount(1000);
    as.setPipelineStats(ImmutableMap.of(
        "p1", new PipelineStats().setRuns(ImmutableList.of(
            new PipelineRunStats()
                .setStartTime(19)
                .setTimer(new UsageTimer().setName("p1").setAccumulatedTime(1))
                .setRunnerCount(10)
                .setExecutionMode("execMode1")
        )),
        "p2", new PipelineStats().setRuns(ImmutableList.of(
            new PipelineRunStats()
                .setStartTime(10)
                .setTimer(new UsageTimer().setName("p2").setAccumulatedTime(2))
                .setRunnerCount(100)
                .setExecutionMode("execMode2.1")
                .setFinalState("finalState2.1"),
            new PipelineRunStats()
                .setStartTime(16)
                .setTimer(new UsageTimer().setName("p2").setAccumulatedTime(4))
                .setRunnerCount(1000)
                .setExecutionMode("execMode2.2")
        ))
    ));
    String hashedP1 = ext.hashPipelineId("p1");
    String hashedP2 = ext.hashPipelineId("p2");
    Multimap<String, PipelineRunReport> expectedRunReports = ImmutableSetMultimap.of(
        hashedP1, new PipelineRunReport()
            .setHashedId(hashedP1)
            .setStartTime(19)
            .setRunMillis(1)
            .setRunnerCount(10)
            .setExecutionMode("execMode1"),
        hashedP2, new PipelineRunReport()
            .setHashedId(hashedP2)
            .setStartTime(10)
            .setRunMillis(2)
            .setRunnerCount(100)
            .setExecutionMode("execMode2.1")
            .setFinalState("finalState2.1"),
        hashedP2, new PipelineRunReport()
            .setHashedId(hashedP2)
            .setStartTime(16)
            .setRunMillis(4)
            .setRunnerCount(1000)
            .setExecutionMode("execMode2.2")
    );
    as.setStages(ImmutableList.of(
        new UsageTimer().setName("s1").setAccumulatedTime(1),
        new UsageTimer().setName("s2").setAccumulatedTime(2)
    ));
    FirstPipelineUse preview1 = new FirstPipelineUse().setCreatedOn(1).setFirstUseOn(2);
    FirstPipelineUse preview2 = new FirstPipelineUse().setCreatedOn(1);
    as.setCreateToPreview(ImmutableMap.of("p1", preview1, "p2", preview2));
    FirstPipelineUse run1 = new FirstPipelineUse().setCreatedOn(10).setFirstUseOn(20).setStageCount(30);
    FirstPipelineUse run2 = new FirstPipelineUse().setCreatedOn(10);
    as.setCreateToRun(ImmutableMap.of("r1", run1, "r2", run2));

    ext.startPipelines = 5;
    ext.stopPipelines = 2;

    StatsBean sb = new StatsBean("sdcid", as);

    Assert.assertEquals("sdcid", sb.getSdcId());
    Assert.assertEquals("version", sb.getDataCollectorVersion());
    Assert.assertEquals(true, sb.isDpmEnabled());
    Assert.assertEquals(1, sb.getUpTime());
    Assert.assertEquals(1, sb.getStartTime());
    Assert.assertEquals(3, sb.getEndTime());
    Assert.assertEquals(3, sb.getRecordsOM());
    Assert.assertEquals(2, sb.getActivePipelines());
    Assert.assertEquals(7, sb.getPipelineMilliseconds());
    Assert.assertEquals((Long) 1L, sb.getStageMilliseconds().get("s1"));
    Assert.assertEquals((Long) 2L, sb.getStageMilliseconds().get("s2"));
    Assert.assertEquals(1, sb.getCreateToPreview().size());
    Assert.assertEquals(1, sb.getCreateToRun().size());
    Assert.assertEquals(preview1.getCreatedOn(), sb.getCreateToPreview().get(0).getCreatedOn());
    Assert.assertEquals(preview1.getFirstUseOn(), sb.getCreateToPreview().get(0).getFirstUseOn());
    Assert.assertEquals(run1.getCreatedOn(), sb.getCreateToRun().get(0).getCreatedOn());
    Assert.assertEquals(run1.getFirstUseOn(), sb.getCreateToRun().get(0).getFirstUseOn());

    Multimap<String, PipelineRunReport> actualRunReports = HashMultimap.create();
    sb.getPipelineRunReports().forEach(r -> {
      actualRunReports.put(r.getHashedId(), r);
    });
    Assert.assertEquals(expectedRunReports, actualRunReports);

    Assert.assertEquals(1, sb.getExtensions().size());
    Assert.assertEquals(TestModelStatsBeanExtension.class, sb.getExtensions().get(0).getClass());
    TestModelStatsBeanExtension sbExt = (TestModelStatsBeanExtension) sb.getExtensions().get(0);
    Assert.assertEquals(5, sbExt.getStartPipelines());
    Assert.assertEquals(2, sbExt.getStopPipelines());
    Assert.assertEquals(3, sbExt.getNetPipelineStarts());
  }

  @Test
  public void testCreationFromActiveStatsV1_1() {
    ActiveStats as = new ActiveStats(ImmutableList.of());
    as.setDpmEnabled(true);
    as.setDataCollectorVersion("version");
    as.setUpTime(new UsageTimer().setName("upTime").setAccumulatedTime(1));
    as.setStartTime(1);
    as.setEndTime(3);
    as.setRecordCount(1000);
    as.setDeprecatedPipelines(ImmutableList.of(
        new UsageTimer().setName("p1").setAccumulatedTime(1),
        new UsageTimer().setName("p2").setAccumulatedTime(2)
    ));
    as.setStages(ImmutableList.of(
        new UsageTimer().setName("s1").setAccumulatedTime(1),
        new UsageTimer().setName("s2").setAccumulatedTime(2)
    ));
    FirstPipelineUse preview1 = new FirstPipelineUse().setCreatedOn(1).setFirstUseOn(2);
    FirstPipelineUse preview2 = new FirstPipelineUse().setCreatedOn(1);
    as.setCreateToPreview(ImmutableMap.of("p1", preview1, "p2", preview2));
    FirstPipelineUse run1 = new FirstPipelineUse().setCreatedOn(10).setFirstUseOn(20).setStageCount(30);
    FirstPipelineUse run2 = new FirstPipelineUse().setCreatedOn(10);
    as.setCreateToRun(ImmutableMap.of("r1", run1, "r2", run2));

    StatsBean sb = new StatsBean("sdcid", as);

    Assert.assertEquals("sdcid", sb.getSdcId());
    Assert.assertEquals("version", sb.getDataCollectorVersion());
    Assert.assertEquals(true, sb.isDpmEnabled());
    Assert.assertEquals(1, sb.getUpTime());
    Assert.assertEquals(1, sb.getStartTime());
    Assert.assertEquals(3, sb.getEndTime());
    Assert.assertEquals(3, sb.getRecordsOM());
    Assert.assertEquals(2, sb.getActivePipelines());
    Assert.assertEquals(3, sb.getPipelineMilliseconds());
    Assert.assertEquals((Long) 1L, sb.getStageMilliseconds().get("s1"));
    Assert.assertEquals((Long) 2L, sb.getStageMilliseconds().get("s2"));
    Assert.assertEquals(1, sb.getCreateToPreview().size());
    Assert.assertEquals(1, sb.getCreateToRun().size());
    Assert.assertEquals(preview1.getCreatedOn(), sb.getCreateToPreview().get(0).getCreatedOn());
    Assert.assertEquals(preview1.getFirstUseOn(), sb.getCreateToPreview().get(0).getFirstUseOn());
    Assert.assertEquals(run1.getCreatedOn(), sb.getCreateToRun().get(0).getCreatedOn());
    Assert.assertEquals(run1.getFirstUseOn(), sb.getCreateToRun().get(0).getFirstUseOn());
    Assert.assertEquals(0, sb.getExtensions().size());
  }

  // just adds one more field to serialize and overwrites version, but otherwise re-uses TestModelStatsExtension
  public static class TestModelStatsBeanExtension extends TestModelStatsExtension implements StatsBeanExtension {
    public static final String VERSION = "TestModelStatsBeanExtension Version";
    private long netPipelineStarts;

    public long getNetPipelineStarts() {
      return netPipelineStarts;
    }

    public void setNetPipelineStarts(long netPipelineStarts) {
      this.netPipelineStarts = netPipelineStarts;
    }

    @Override
    public String getVersion() {
      return VERSION;
    }

    @Override
    public void setVersion(String version) {
      if (!VERSION.equals(version)) {
        throw new RuntimeException("unexpected version: " + version);
      }
    }
  }
}


text:
package org.auraframework.impl.css.parser.plugin;

import org.auraframework.Aura;
import org.auraframework.impl.AuraImplTestCase;

import com.salesforce.omakase.ast.declaration.UrlFunctionValue;

public class UrlCacheBustingPluginTest extends AuraImplTestCase {

    public UrlCacheBustingPluginTest(String name) {
        super(name);
    }

    private void assertBustedUrl(String expectedFormat, String initialValue) throws Exception {
        UrlCacheBustingPlugin acb = new UrlCacheBustingPlugin(true);
        UrlFunctionValue ufv = new UrlFunctionValue(initialValue);
        String buster = "" + Aura.getConfigAdapter().getBuildTimestamp();
        String expected = String.format(expectedFormat, buster);

        acb.rework(ufv);
        String actual = ufv.url();
        assertEquals(expected, actual);

        //
        // And check that we don't change it when disabled.
        //
        acb = new UrlCacheBustingPlugin(false);
        ufv = new UrlFunctionValue(initialValue);
        acb.rework(ufv);
        actual = ufv.url();
        assertEquals(initialValue, actual);
    }

    /**
     * [FAILING] Test that aura.cb can be in a URL.
     */
    public void _testAddCacheBusterToAuracb() throws Exception {
        assertBustedUrl("/aura.cb?aura.cb=%s", "/aura.cb");
    }

    /**
     * Empty URL string should still have the buster returned.
     */
    public void testAddCacheBusterToEmptyString() throws Exception {
        assertBustedUrl("/?aura.cb=%s", "/");
    }

    /**
     * Basic URL, without query or hash, has buster simply appended as query.
     */
    public void testAddCacheBusterWithoutQueryOrHash() throws Exception {
        assertBustedUrl("/something?aura.cb=%s", "/something");
    }

    /**
     * URL with query will have buster appended to query.
     */
    public void testAddCacheBusterWithQuery() throws Exception {
        assertBustedUrl("/something?is=fishy&aura.cb=%s", "/something?is=fishy");
    }

    /**
     * URL with hash will have buster appended as query (before the hash).
     */
    public void testAddCacheBusterWithHash() throws Exception {
        assertBustedUrl("/something?aura.cb=%s#toremember", "/something#toremember");
    }

    /**
     * URL with hash with query will have buster appended as query (before the hash).
     */
    public void testAddCacheBusterWithHashQuery() throws Exception {
        assertBustedUrl("/something?aura.cb=%s#layout?option=value", "/something#layout?option=value");
    }

    /**
     * URL with query and hash will have buster appended to query (before the hash).
     */
    public void testAddCacheBusterWithQueryAndHash() throws Exception {
        assertBustedUrl("/something?is=fishy&aura.cb=%s#inside", "/something?is=fishy#inside");
    }

    /**
     * URL with query and hash with query will have buster appended to query (before the hash).
     */
    public void testAddCacheBusterWithQueryAndHashQuery() throws Exception {
        assertBustedUrl("/something?is=fishy&aura.cb=%s#inside?where=fridge", "/something?is=fishy#inside?where=fridge");
    }
}


text:
"""
This script fixes links that contain common spelling mistakes.

This is only possible on wikis that have a template for these misspellings.

Command line options:

   -always:XY  instead of asking the user what to do, always perform the same
               action. For example, XY can be "r0", "u" or "2". Be careful with
               this option, and check the changes made by the bot. Note that
               some choices for XY don't make sense and will result in a loop,
               e.g. "l" or "m".

   -start:XY   goes through all misspellings in the category on your wiki
               that is defined (to the bot) as the category containing
               misspelling pages, starting at XY. If the -start argument is not
               given, it starts at the beginning.

   -main       only check pages in the main namespace, not in the talk,
               wikipedia, user, etc. namespaces.
"""
# (C) Daniel Herding, 2007
# (C) Pywikibot team, 2007-2015
#
# Distributed under the terms of the MIT license.
#
from __future__ import unicode_literals

__version__ = '$Id$'
#

import pywikibot
from pywikibot import i18n, pagegenerators
from pywikibot.tools import PY2
from solve_disambiguation import DisambiguationRobot

if not PY2:
    basestring = (str, )

HELP_MSG = """\n
mispelling.py does not support site {site}.

Help Pywikibot team to provide support for your wiki by submitting
a bug to:
https://phabricator.wikimedia.org/maniphest/task/create/?projects=pywikibot-core
with category containing misspelling pages or a template for
these misspellings.\n"""

class MisspellingRobot(DisambiguationRobot):

    """Spelling bot."""

    misspellingTemplate = {
        'de': ('Falschschreibung', 'Obsolete Schreibung'),
    }

    # Optional: if there is a category, one can use the -start
    # parameter.
    misspellingCategory = {
        'da': u'Omdirigeringer af fejlstavninger',  # only contains date redirects at the moment
        'de': ('Kategorie:Wikipedia:Falschschreibung',
               'Kategorie:Wikipedia:Obsolete Schreibung'),
        'en': u'Redirects from misspellings',
        'hu': u'Átirányítások hibás névről',
        'nl': u'Categorie:Wikipedia:Redirect voor spelfout',
    }

    def __init__(self, always, firstPageTitle, main_only):
        """Constructor."""
        super(MisspellingRobot, self).__init__(
            always, [], True, False, None, False, main_only)
        self.generator = self.createPageGenerator(firstPageTitle)

    def createPageGenerator(self, firstPageTitle):
        """
        Generator to retrieve misspelling pages or misspelling redirects.

        @rtype: generator
        """
        mylang = self.site.code
        if mylang in self.misspellingCategory:
            categories = self.misspellingCategory[mylang]
            if isinstance(categories, basestring):
                categories = (categories, )
            generators = (
                pagegenerators.CategorizedPageGenerator(
                    pywikibot.Category(self.site, misspellingCategoryTitle),
                    recurse=True, start=firstPageTitle)
                for misspellingCategoryTitle in categories)
        elif mylang in self.misspellingTemplate:
            templates = self.misspellingTemplate[mylang]
            if isinstance(templates, basestring):
                templates = (templates, )
            generators = (
                pagegenerators.ReferringPageGenerator(
                    pywikibot.Page(self.site, misspellingTemplateName, ns=10),
                    onlyTemplateInclusion=True)
                for misspellingTemplateName in templates)
            if firstPageTitle:
                pywikibot.output(
                    u'-start parameter unsupported on this wiki because there '
                    u'is no category for misspellings.')
        else:
            pywikibot.output(HELP_MSG.format(site=self.site))

            empty_gen = (i for i in [])
            return empty_gen
        generator = pagegenerators.CombinedPageGenerator(generators)
        preloadingGen = pagegenerators.PreloadingGenerator(generator)
        return preloadingGen

    def findAlternatives(self, disambPage):
        """
        Append link target to a list of alternative links.

        Overrides the DisambiguationRobot method.

        @return: True if alternate link was appended
        @rtype: bool or None
        """
        if disambPage.isRedirectPage():
            self.alternatives.append(disambPage.getRedirectTarget().title())
            return True
        if self.misspellingTemplate.get(disambPage.site.code) is not None:
            for template, params in disambPage.templatesWithParams():
                if (template.title(withNamespace=False) ==
                        self.misspellingTemplate[disambPage.site.code]):
                    # The correct spelling is in the last paramter.
                    correctSpelling = params[-1]
                    # On de.wikipedia, there are some cases where the
                    # misspelling is ambigous, see for example:
                    # https://de.wikipedia.org/wiki/Buthan
                    for match in self.linkR.finditer(correctSpelling):
                        self.alternatives.append(match.group('title'))

                    if not self.alternatives:
                        # There were no links in the parameter, so there is
                        # only one correct spelling.
                        self.alternatives.append(correctSpelling)
                    return True

    def setSummaryMessage(self, disambPage, *args, **kwargs):
        """
        Setup the summary message.

        Overrides the DisambiguationRobot method.
        """
        # TODO: setSummaryMessage() in solve_disambiguation now has parameters
        # new_targets and unlink. Make use of these here.
        self.comment = i18n.twtranslate(self.site, 'misspelling-fixing',
                                        {'page': disambPage.title()})

def main(*args):
    """
    Process command line arguments and invoke bot.

    If args is an empty list, sys.argv is used.

    @param args: command line arguments
    @type args: list of unicode
    """
    # the option that's always selected when the bot wonders what to do with
    # a link. If it's None, the user is prompted (default behaviour).
    always = None
    main_only = False
    firstPageTitle = None

    for arg in pywikibot.handle_args(args):
        if arg.startswith('-always:'):
            always = arg[8:]
        elif arg.startswith('-start'):
            if len(arg) == 6:
                firstPageTitle = pywikibot.input(
                    u'At which page do you want to start?')
            else:
                firstPageTitle = arg[7:]
        elif arg == '-main':
            main_only = True

    bot = MisspellingRobot(always, firstPageTitle, main_only)
    bot.run()

if __name__ == "__main__":
    main()


text:
Imports System
Imports System.Text

Namespace Rogue.Lib

  ''' <summary>
  ''' Encode all aspects for a specific room
  '''
  ''' Initialize
  ''' Ensures that the object has all properties set
  '''
  '''
  '''
  ''' </summary>
  Public Class LevelRoom
    ReadOnly m_localRandom As New Random()

    Private ReadOnly m_ErrorHandler As New ErrorHandler
    Private m_CurrentObject As String = "LevelRoom"

#Region "Public Properties"

#Region "Private Properties"

    ''' <summary>
    ''' Set this value to true to test displaying a sample screen
    ''' </summary>
    Private ReadOnly m_TestMode As Boolean = False

    Private m_EntryStairLocation As String
  Private m_ExitStairLocation As String
  Private m_CurrentMapLevel As Integer
  Private m_MapGridRowLocation As Integer
  Private m_MapGridColumnLocation As Integer
    Private m_MapTopLocation As Integer
    Private m_MapLeftLocation As Integer
    Private m_ActualMapTopLocation As Integer
    Private m_ActualMapLeftLocation As Integer
    Private m_CurrentHeight As Integer
    Private m_CurrentWidth As Integer
  Private m_Row As Integer = 0
  Private m_Column As Integer = 0
  Private m_RoomNumber As Integer = 0 ' 1-9 to position room within grid of 3x3
  Private m_RoomDoors As List(Of String) = New List(Of String)  ' keep track of which doors exist for this room

#End Region

  ''' <summary>
  ''' Hold a pointer to the level of the current map
  ''' Bigger numbers means further down into the dungeon.
  ''' 0=not any level, 1=first or beginning level.
  ''' </summary>
  ''' <returns></returns>
  Public Property CurrentMapLevel() As Integer
    Get
        Return Me.m_CurrentMapLevel
      End Get
      Set(ByVal value As Integer)
        Me.m_CurrentMapLevel = value
      End Set
    End Property

    Public Property MapGridRowLocation() As Integer
      Get
        Return Me.m_MapGridRowLocation
      End Get
      Set(ByVal value As Integer)
        Me.m_MapGridRowLocation = value
      End Set
    End Property

    Public Property MapGridColumnLocation() As Integer
      Get
        Return Me.m_MapGridColumnLocation
      End Get
      Set(ByVal value As Integer)
        Me.m_MapGridColumnLocation = value
      End Set
    End Property

    Public Property MapTopLocation() As Integer
      Get
        Return Me.m_MapTopLocation
      End Get
      Set(ByVal value As Integer)
        Me.m_MapTopLocation = value
      End Set
    End Property

    Public Property MapLeftLocation() As Integer
      Get
        Return Me.m_MapLeftLocation
      End Get
      Set(ByVal value As Integer)
        Me.m_MapLeftLocation = value
      End Set
    End Property

    Public Property ActualMapTopLocation() As Integer
      Get
        Me.m_ActualMapTopLocation = Me.m_MapTopLocation + ((Me.m_MapGridRowLocation - 1) * EnumsAndConsts.MapGridCellHeight)
        Return Me.m_ActualMapTopLocation
      End Get
      Set(ByVal value As Integer)
        Me.m_ActualMapTopLocation = value
      End Set
    End Property

    Public Property ActualMapLeftLocation() As Integer
      Get
        Me.m_ActualMapLeftLocation = Me.m_MapLeftLocation + ((Me.m_MapGridColumnLocation - 1) * EnumsAndConsts.MapGridCellWidth)
        Return Me.m_ActualMapLeftLocation
      End Get
      Set(ByVal value As Integer)
        Me.m_ActualMapLeftLocation = value
      End Set
    End Property

    Public Property CurrentHeight() As Integer
      Get
        Return Me.m_CurrentHeight
      End Get
      Set(ByVal value As Integer)
        Me.m_CurrentHeight = value
      End Set
    End Property

    Public Property CurrentWidth() As Integer
      Get
        Return Me.m_CurrentWidth
      End Get
      Set(ByVal value As Integer)
        Me.m_CurrentWidth = value
      End Set
    End Property

    ''' <summary>
    ''' Hold a pointer to where on the level the player will come down the stairs
    ''' There must be a room here when level is generated
    ''' Number is YYXX
    ''' YY being the row as two digits which may be zero padded
    ''' XX being the column as two digits which may be zero padded
    ''' </summary>
    ''' <returns></returns>
    Public Property EntryStairLocation() As String
      Get
        Return Me.m_EntryStairLocation
      End Get
      Set(ByVal value As String)
        Me.m_EntryStairLocation = value
      End Set
    End Property

    ''' <summary>
    ''' Hold a pointer to where on the level the player will go down to the next level
    ''' There must be a room here when level is generated
    ''' Number is YYXX
    ''' YY being the row as two digits which may be zero padded
    ''' XX being the column as two digits which may be zero padded
    ''' </summary>
    ''' <returns></returns>
    Public Property ExitStairLocation() As String
      Get
        Return Me.m_ExitStairLocation
      End Get
      Set(ByVal value As String)
        Me.m_ExitStairLocation = value
      End Set
    End Property

    Public Property RoomNumber() As Integer
      Get
        Return Me.m_RoomNumber
      End Get
      Set(ByVal value As Integer)
        Me.m_RoomNumber = value
      End Set
    End Property

    Public Property RoomDoors() As List(Of String)
      Get
        Return Me.m_RoomDoors
      End Get
      Set(ByVal value As List(Of String))
        Me.m_RoomDoors = value
      End Set
    End Property

#End Region

#Region "Public Methods"

    Public Sub New()
      Me.Initialize() 'Sets the room to empty
    End Sub

    Public Sub New(ByVal whatEntryStairLocation As String, ByVal whatExitStairLocation As String)
      Me.Initialize() 'Sets the room to empty
      Me.EntryStairLocation = whatEntryStairLocation
      Me.ExitStairLocation = whatExitStairLocation
    End Sub

    ''' <summary>
    ''' Load all properties and variables with default values
    ''' </summary>
    Public Sub Initialize()
      Dim currentMethod As String = "Initialize"
      Dim currentData As String = ""

      Try
        'TODO for testing set these values
        'normally they will be set by the calling routine prior to creating the random level
        Me.EntryStairLocation = "1831"
        Me.ExitStairLocation = "0470"

        Me.m_CurrentMapLevel = 0
        Me.m_MapGridRowLocation = 0
        Me.m_MapGridColumnLocation = 0
        Me.m_MapTopLocation = 0
        Me.m_MapLeftLocation = 0
        Me.m_ActualMapTopLocation = 0
        Me.m_ActualMapLeftLocation = 0
        Me.m_CurrentHeight = 0
        Me.m_CurrentWidth = 0
        Me.m_Row = 0
        Me.m_Column = 0
        Me.m_RoomNumber = 0
        Me.m_RoomDoors = New List(Of String)

      Catch ex As Exception
        Me.m_ErrorHandler.NotifyError(Me.m_CurrentObject, currentMethod, ex.Message, Now, ex)
      End Try
    End Sub

    Public Function CreateRandomEntryRoom(ByVal whatMapGridRow As Integer, ByVal whatMapGridColumn As Integer, ByVal whatEntryRow As Integer, ByVal whatEntryColumn As Integer, ByVal whatHeight As Integer, ByVal whatWidth As Integer) As LevelRoom
      Dim currentMethod As String = "CreateRandomEntryRoom"
      Dim currentData As String = ""
      Dim aReturnValue As New LevelRoom
      Dim X As Integer = 0 ' left to right
      Dim Y As Integer = 0 ' top to bottom
      Dim X1 As Integer = 0 ' left to right
      Dim Y1 As Integer = 0 ' top to bottom
      Dim entryX As Integer = whatEntryColumn - ((whatMapGridColumn - 1) * 26)
      Dim entryY As Integer = whatEntryRow - ((whatMapGridRow - 1) * 7)
      Dim xOFF As Integer = (entryX - whatWidth) + 1
      Dim yOFF As Integer = (entryY - whatHeight) + 1
      Dim dataArray() As String = {""}
      Dim newX As Integer = 0
      Dim newY As Integer = 0
      Dim newType As Integer = 0

      Try
        aReturnValue = Me.CreateRandomRoom(whatMapGridRow, whatMapGridColumn, whatHeight, whatWidth)

        X = aReturnValue.m_MapLeftLocation
        Y = aReturnValue.m_MapTopLocation
        If aReturnValue.m_MapTopLocation > entryY - 1 Then
          'aReturnValue.m_MapTopLocation = entryY - 1
          Y = entryY - 1
        End If
        If aReturnValue.m_MapTopLocation + aReturnValue.m_CurrentHeight < entryY + 2 Then
          'aReturnValue.m_MapTopLocation = (entryY - aReturnValue.m_CurrentHeight) + 2
          Y = (entryY - aReturnValue.m_CurrentHeight) + 2
        End If
        If aReturnValue.m_MapLeftLocation > entryX - 1 Then
          'aReturnValue.m_MapLeftLocation = entryX - 1
          X = entryX - 1
        End If
        If aReturnValue.m_MapLeftLocation + aReturnValue.m_CurrentWidth < entryX + 2 Then
          'aReturnValue.m_MapLeftLocation = (entryX - aReturnValue.m_CurrentWidth) + 2
          X = (entryX - aReturnValue.m_CurrentWidth) + 2
        End If

        'X1 = (whatWidth) - 1
        'X = Me.m_localRandom.Next(X1) + xOFF + 1

        'If X >= entryX Then
        '  X = entryX - 1
        'End If
        'If X <= (entryX - (whatWidth - 1)) Then
        '  X = (entryX - (whatWidth - 1)) + 1
        'End If
        'If X < 2 Then
        '  X = 2
        'End If
        'If X > EnumsAndConsts.MapGridCellWidth - whatWidth Then
        '  X = EnumsAndConsts.MapGridCellWidth - whatWidth
        'End If
        'Y1 = (whatHeight) - 1
        'Y = Me.m_localRandom.Next(Y1) + xOFF + 1

        'If Y >= entryY Then
        '  Y = entryY - 1
        'End If
        'If Y <= (entryY - (whatHeight - 1)) Then
        '  Y = (entryY - (whatHeight - 1)) + 1
        'End If
        'If Y < 2 Then
        '  Y = 2
        'End If
        'If Y > EnumsAndConsts.MapGridCellHeight - whatHeight Then
        '  Y = EnumsAndConsts.MapGridCellHeight - whatHeight
        'End If

        xOFF = aReturnValue.MapLeftLocation - X
        yOFF = aReturnValue.MapTopLocation - Y
        aReturnValue.MapTopLocation = Y
        aReturnValue.MapLeftLocation = X
        For dptr As Integer = 0 To aReturnValue.RoomDoors.Count - 1
          dataArray = aReturnValue.RoomDoors(dptr).Split("|")
          Integer.TryParse(dataArray(0), newY)
          Integer.TryParse(dataArray(1), newX)
          Integer.TryParse(dataArray(2), newType)
          newY = newY - yOFF
          newX = newX - xOFF
          If newX < aReturnValue.MapLeftLocation + 1 Then
            newX = aReturnValue.MapLeftLocation + 1
          End If
          If newY < aReturnValue.MapTopLocation + 1 Then
            newY = aReturnValue.MapTopLocation + 1
          End If
          aReturnValue.RoomDoors(dptr) = newY.ToString & "|" & newX.ToString & "|" & newType.ToString
        Next
        'aReturnValue.MapGridRowLocation = whatMapGridRow
        'aReturnValue.MapGridColumnLocation = whatMapGridColumn
        'aReturnValue.CurrentHeight = whatHeight
        'aReturnValue.CurrentWidth = whatWidth
        'aReturnValue.RoomNumber = ((whatMapGridRow - 1) * 3) + whatMapGridColumn
        ' aReturnValue.CreateRandomDoors()

      Catch ex As Exception
        Me.m_ErrorHandler.NotifyError(Me.m_CurrentObject, currentMethod, ex.Message, Now, ex)
      End Try

      Return aReturnValue
    End Function

    Public Function CreateRandomExitRoom(ByVal whatMapGridRow As Integer, ByVal whatMapGridColumn As Integer, ByVal whatExitRow As Integer, ByVal whatExitColumn As Integer, ByVal whatHeight As Integer, ByVal whatWidth As Integer) As LevelRoom
      Dim currentMethod As String = "CreateRandomExitRoom"
      Dim currentData As String = ""
      Dim aReturnValue As New LevelRoom
      Dim X As Integer = 0 ' left to right
      Dim Y As Integer = 0 ' top to bottom
      Dim X1 As Integer = 0 ' left to right
      Dim Y1 As Integer = 0 ' top to bottom
      Dim exitX As Integer = whatExitColumn - ((whatMapGridColumn - 1) * 26)
      Dim exitY As Integer = whatExitRow - ((whatMapGridRow - 1) * 7)
      Dim xOFF As Integer = (exitX - whatWidth) + 1
      Dim yOFF As Integer = (exitY - whatHeight) + 1
      Dim dataArray() As String = {""}
      Dim newX As Integer = 0
      Dim newY As Integer = 0
      Dim newType As Integer = 0

      Try
        aReturnValue = Me.CreateRandomRoom(whatMapGridRow, whatMapGridColumn, whatHeight, whatWidth)

        X1 = (whatWidth) - 1
        X = Me.m_localRandom.Next(X1) + xOFF + 1

        If X >= exitX Then
          X = exitX - 1
        End If
        If X <= (exitX - (whatWidth - 1)) Then
          X = (exitX - (whatWidth - 1)) + 1
        End If
        If X < 2 Then
          X = 2
        End If
        If X > EnumsAndConsts.MapGridCellWidth - whatWidth Then
          X = EnumsAndConsts.MapGridCellWidth - whatWidth
        End If

        If Y >= exitY Then
          Y = exitY - 1
        End If
        If Y <= (exitY - (whatHeight - 1)) Then
          Y = (exitY - (whatHeight - 1)) + 1
        End If
        If Y < 2 Then
          Y = 2
        End If
        If Y > EnumsAndConsts.MapGridCellHeight - whatHeight Then
          Y = EnumsAndConsts.MapGridCellHeight - whatHeight
        End If

        xOFF = aReturnValue.MapLeftLocation - X
        yOFF = aReturnValue.MapTopLocation - Y
        aReturnValue.MapTopLocation = Y
        aReturnValue.MapLeftLocation = X
        For dptr As Integer = 0 To aReturnValue.RoomDoors.Count - 1
          dataArray = aReturnValue.RoomDoors(dptr).Split("|")
          Integer.TryParse(dataArray(0), newY)
          Integer.TryParse(dataArray(1), newX)
          Integer.TryParse(dataArray(2), newType)
          newY = newY - yOFF
          newX = newX - xOFF
          aReturnValue.RoomDoors(dptr) = newY.ToString & "|" & newX.ToString & "|" & newType.ToString
        Next
        '        aReturnValue.MapTopLocation = Y
        '        aReturnValue.MapLeftLocation = X
        'aReturnValue.MapGridRowLocation = whatMapGridRow
        'aReturnValue.MapGridColumnLocation = whatMapGridColumn
        'aReturnValue.CurrentHeight = whatHeight
        'aReturnValue.CurrentWidth = whatWidth
        'aReturnValue.RoomNumber = ((whatMapGridRow - 1) * 3) + whatMapGridColumn
        '   aReturnValue.CreateRandomDoors()

      Catch ex As Exception
        Me.m_ErrorHandler.NotifyError(Me.m_CurrentObject, currentMethod, ex.Message, Now, ex)
      End Try

      Return aReturnValue
    End Function

    Public Function CreateRandomRoom(ByVal whatMapGridRow As Integer, ByVal whatMapGridColumn As Integer, ByVal whatHeight As Integer, ByVal whatWidth As Integer) As LevelRoom
      Dim currentMethod As String = "CreateRandomRoom"
      Dim currentData As String = ""
      Dim aReturnValue As New LevelRoom
      Dim X As Integer = 0 ' left to right
      Dim Y As Integer = 0 ' top to bottom
      Dim isDoorTop As Boolean = False
      Dim isDoorLeft As Boolean = False
      Dim isDoorRight As Boolean = False
      Dim isDoorBottom As Boolean = False
      Dim isAnyDoor As Boolean = False
      Dim rNumber As Integer = 0
      Dim xNumber As Integer = 0
      Dim aCellType As Integer = 0
      Dim rPtr As Integer = 0
      Dim cPtr As Integer = 0

      Try

        'determine offset of top left corner of room based on size of room and random distance from top left of map grid
        X = Me.m_localRandom.Next(EnumsAndConsts.MapGridCellWidth - whatWidth) + 1
        Y = Me.m_localRandom.Next(EnumsAndConsts.MapGridCellHeight - whatHeight) + 1
        If whatMapGridRow = 3 AndAlso Y < 2 Then
          Y = 2
        End If
        'see if there is a door on the top
        rNumber = Me.m_localRandom.Next(10) + 1
        If rNumber < 3 Then
          xNumber = Me.m_localRandom.Next(whatWidth - 2) + 1
          isDoorTop = True
          isAnyDoor = True
          aCellType = EnumsAndConsts.CellType.StructureDoorTopBottom
          rPtr = (Y + ((whatMapGridRow - 1) * EnumsAndConsts.MapGridCellHeight))
          cPtr = (X + ((whatMapGridColumn - 1) * EnumsAndConsts.MapGridCellWidth) + xNumber)
          If cPtr < X - 1 Then
            cPtr = X + 1
          End If
          If rPtr < Y - 1 Then
            rPtr = Y + 1
          End If
          currentData = rPtr.ToString & "|" & cPtr.ToString & "|" & aCellType.ToString & "|" & "T"
          aReturnValue.RoomDoors.Add(currentData)
          Debug.Print("top door=" & currentData)
        End If

        'see if there is a door on the left
        rNumber = Me.m_localRandom.Next(10) + 1
        If rNumber < 3 Then
          xNumber = Me.m_localRandom.Next(whatHeight - 2) + 1
          isDoorLeft = True
          isAnyDoor = True
          aCellType = EnumsAndConsts.CellType.StructureDoorSide
          cPtr = (X + ((whatMapGridColumn - 1) * EnumsAndConsts.MapGridCellWidth))
          rPtr = (Y + ((whatMapGridRow - 1) * EnumsAndConsts.MapGridCellHeight) + xNumber)
          If cPtr < X - 1 Then
            cPtr = X + 1
          End If
          If rPtr < Y - 1 Then
            rPtr = Y + 1
          End If
          currentData = rPtr.ToString & "|" & cPtr.ToString & "|" & aCellType.ToString & "|" & "L"
          aReturnValue.RoomDoors.Add(currentData)
          Debug.Print("Left door=" & currentData)
        End If

        'see if there is a door on the right
        rNumber = Me.m_localRandom.Next(10) + 1
        If rNumber < 3 Then
          xNumber = Me.m_localRandom.Next(whatHeight - 2) + 1
          isDoorRight = True
          isAnyDoor = True
          aCellType = EnumsAndConsts.CellType.StructureDoorSide
          cPtr = (X + ((whatMapGridColumn - 1) * EnumsAndConsts.MapGridCellWidth) + whatWidth - 1)
          rPtr = (Y + ((whatMapGridRow - 1) * EnumsAndConsts.MapGridCellHeight) + xNumber)
          If cPtr < X - 1 Then
            cPtr = X + 1
          End If
          If rPtr < Y - 1 Then
            rPtr = Y + 1
          End If
          currentData = rPtr.ToString & "|" & cPtr.ToString & "|" & aCellType.ToString & "|" & "R"
          aReturnValue.RoomDoors.Add(currentData)
          Debug.Print("right door=" & currentData)
        End If

        'see if there is a door on the bottom
        rNumber = Me.m_localRandom.Next(10) + 1
        If rNumber < 3 Then
          xNumber = Me.m_localRandom.Next(whatWidth - 2) + 1
          isDoorBottom = True
          isAnyDoor = True
          aCellType = EnumsAndConsts.CellType.StructureDoorTopBottom
          cPtr = (X + ((whatMapGridColumn - 1) * EnumsAndConsts.MapGridCellWidth) + xNumber)
          rPtr = (Y + ((whatMapGridRow - 1) * EnumsAndConsts.MapGridCellHeight) + whatHeight - 1)
          If cPtr < X - 1 Then
            cPtr = X + 1
          End If
          If rPtr < Y - 1 Then
            rPtr = Y + 1
          End If
          currentData = rPtr.ToString & "|" & cPtr.ToString & "|" & aCellType.ToString & "|" & "B"
          aReturnValue.RoomDoors.Add(currentData)
          Debug.Print("bottom door=" & currentData)
        End If

        If isAnyDoor = False Then
          rNumber = Me.m_localRandom.Next(4) + 1
          Select Case rNumber
            Case 1 'top
              xNumber = Me.m_localRandom.Next(whatWidth - 2) + 1
              isDoorTop = True
              isAnyDoor = True
              aCellType = EnumsAndConsts.CellType.StructureDoorTopBottom
              cPtr = (X + (whatMapGridColumn - 1) * EnumsAndConsts.MapGridCellWidth) + xNumber
              rPtr = (Y + ((whatMapGridRow - 1) * EnumsAndConsts.MapGridCellHeight))
              If cPtr < X - 1 Then
                cPtr = X + 1
              End If
              If rPtr < Y - 1 Then
                rPtr = Y + 1
              End If
              currentData = rPtr.ToString & "|" & cPtr.ToString & "|" & aCellType.ToString & "|" & "T"
              aReturnValue.RoomDoors.Add(currentData)
            Case 2 'left
              xNumber = Me.m_localRandom.Next(whatHeight - 2) + 1
              isDoorLeft = True
              isAnyDoor = True
              aCellType = EnumsAndConsts.CellType.StructureDoorSide
              cPtr = (X + ((whatMapGridColumn - 1) * EnumsAndConsts.MapGridCellWidth))
              rPtr = (Y + ((whatMapGridRow - 1) * EnumsAndConsts.MapGridCellHeight) + xNumber)
              If cPtr < X - 1 Then
                cPtr = X + 1
              End If
              If rPtr < Y - 1 Then
                rPtr = Y + 1
              End If
              currentData = rPtr.ToString & "|" & cPtr.ToString & "|" & aCellType.ToString & "|" & "L"
              aReturnValue.RoomDoors.Add(currentData)
            Case 3 'right
              xNumber = Me.m_localRandom.Next(whatHeight - 2) + 1
              isDoorRight = True
              isAnyDoor = True
              aCellType = EnumsAndConsts.CellType.StructureDoorSide
              cPtr = (X + ((whatMapGridColumn - 1) * EnumsAndConsts.MapGridCellWidth) + whatWidth - 1)
              rPtr = (Y + ((whatMapGridRow - 1) * EnumsAndConsts.MapGridCellHeight) + xNumber)
              If cPtr < X - 1 Then
                cPtr = X + 1
              End If
              If rPtr < Y - 1 Then
                rPtr = Y + 1
              End If
              currentData = rPtr.ToString & "|" & cPtr.ToString & "|" & aCellType.ToString & "|" & "R"
              aReturnValue.RoomDoors.Add(currentData)
            Case Else 'bottom
              xNumber = Me.m_localRandom.Next(whatWidth - 2) + 1
              isDoorBottom = True
              isAnyDoor = True
              aCellType = EnumsAndConsts.CellType.StructureDoorTopBottom
              cPtr = (X + ((whatMapGridColumn - 1) * EnumsAndConsts.MapGridCellWidth) + xNumber)
              rPtr = (Y + ((whatMapGridRow - 1) * EnumsAndConsts.MapGridCellHeight) + whatHeight - 1)
              If cPtr < X - 1 Then
                cPtr = X + 1
              End If
              If rPtr < Y - 1 Then
                rPtr = Y + 1
              End If
              currentData = rPtr.ToString & "|" & cPtr.ToString & "|" & aCellType.ToString & "|" & "B"
              aReturnValue.RoomDoors.Add(currentData)
          End Select
          Debug.Print("Forced  door=" & rNumber.ToString & "==" & currentData)
        End If

        'aReturnValue = Y.ToString & "-" & X.ToString
        aReturnValue.MapTopLocation = Y
        aReturnValue.MapLeftLocation = X
        aReturnValue.MapGridRowLocation = whatMapGridRow
        aReturnValue.MapGridColumnLocation = whatMapGridColumn
        aReturnValue.CurrentHeight = whatHeight
        aReturnValue.CurrentWidth = whatWidth
        aReturnValue.RoomNumber = ((whatMapGridRow - 1) * 3) + whatMapGridColumn
        Debug.Print("room number: " & aReturnValue.RoomNumber.ToString & " door count=" & aReturnValue.RoomDoors.Count.ToString)

        '     aReturnValue.CreateRandomDoors()
      Catch ex As Exception
        Me.m_ErrorHandler.NotifyError(Me.m_CurrentObject, currentMethod, ex.Message, Now, ex)
      End Try

      Return aReturnValue
    End Function

    Public Function GetConnectionNumber(ByVal whatFromDoorRow As Integer, ByVal whatFromDoorColumn As Integer, ByVal whatToDoorRow As Integer, ByVal whatToDoorColumn As Integer) As String
      Dim currentMethod As String = "GetConnectionNumber"
      Dim currentData As String = ""
      Dim aReturnValue As String = ""
      Dim X As Integer = 0 ' left to right
      Dim Y As Integer = 0 ' top to bottom
      Dim aGridRowCtr As Integer = 0
      Dim aGridColumnCtr As Integer = 0
      Dim aCellPtr As Integer = 0

      Try
        'Determine the mapgridNumber from the row/column information
        Y = whatFromDoorRow
        aGridRowCtr = 1
        Do While Y > EnumsAndConsts.MapGridCellHeight
          Y = Y - EnumsAndConsts.MapGridCellHeight
          aGridRowCtr = aGridRowCtr + 1
        Loop
        X = whatFromDoorColumn
        aGridColumnCtr = 1
        Do While X > EnumsAndConsts.MapGridCellWidth
          X = X - EnumsAndConsts.MapGridCellWidth
          aGridColumnCtr = aGridColumnCtr + 1
        Loop
        'now agridxx will point to proper grid cell
        aCellPtr = (aGridRowCtr - 1) * EnumsAndConsts.MapLevelGridRowMax + aGridColumnCtr

        aReturnValue = aCellPtr.ToString & "|"

        Y = whatToDoorRow
        aGridRowCtr = 1
        Do While Y > EnumsAndConsts.MapGridCellHeight
          Y = Y - EnumsAndConsts.MapGridCellHeight
          aGridRowCtr = aGridRowCtr + 1
        Loop
        X = whatToDoorColumn
        aGridColumnCtr = 1
        Do While X > EnumsAndConsts.MapGridCellWidth
          X = X - EnumsAndConsts.MapGridCellWidth
          aGridColumnCtr = aGridColumnCtr + 1
        Loop
        'now agridxx will point to proper grid cell
        aCellPtr = (aGridRowCtr - 1) * EnumsAndConsts.MapLevelGridRowMax + aGridColumnCtr

        aReturnValue = aReturnValue & aCellPtr.ToString

      Catch ex As Exception
        Me.m_ErrorHandler.NotifyError(Me.m_CurrentObject, currentMethod, ex.Message, Now, ex)
      End Try

      Return aReturnValue
    End Function

    Public Overrides Function ToString() As String
      Dim aReturnValue As String = ""

      aReturnValue = Me.RoomNumber.ToString & "=" & Me.MapTopLocation.ToString & "-" & Me.MapLeftLocation.ToString & "|" & Me.CurrentHeight.ToString & "-" & Me.CurrentWidth.ToString

      Return aReturnValue
  End Function

#End Region

#Region "Private Methods"

#End Region

  End Class
End Namespace


text:
# enforce a maximum depth that callbacks can be nested (max-nested-callbacks)

Many JavaScript libraries use the callback pattern to manage asynchronous operations. A program of any complexity will most likely need to manage several asynchronous operations at various levels of concurrency. A common pitfall that is easy to fall into is nesting callbacks, which makes code more difficult to read the deeper the callbacks are nested.

```js
foo(function () {
    bar(function () {
        baz(function() {
            qux(function () {

            });
        });
    });
});
```

## Rule Details

This rule enforces a maximum depth that callbacks can be nested to increase code clarity.

## Options

This rule has a number or object option:

* `"max"` (default `10`) enforces a maximum depth that callbacks can be nested

**Deprecated:** The object property `maximum` is deprecated; please use the object property `max` instead.

### max

Examples of **incorrect** code for this rule with the `{ "max": 3 }` option:

```js
/*eslint max-nested-callbacks: ["error", 3]*/

foo1(function() {
    foo2(function() {
        foo3(function() {
            foo4(function() {
                // Do something
            });
        });
    });
});
```

Examples of **correct** code for this rule with the `{ "max": 3 }` option:

```js
/*eslint max-nested-callbacks: ["error", 3]*/

foo1(handleFoo1);

function handleFoo1() {
    foo2(handleFoo2);
}

function handleFoo2() {
    foo3(handleFoo3);
}

function handleFoo3() {
    foo4(handleFoo4);
}

function handleFoo4() {
    foo5();
}
```

## Further Reading

* [Control flow in Node.js](http://book.mixu.net/node/ch7.html)
* [Control Flow in Node](https://howtonode.org/control-flow)
* [Control Flow in Node Part II](https://howtonode.org/control-flow-part-ii)

## Related Rules

* [complexity](complexity.md)
* [max-depth](max-depth.md)
* [max-len](max-len.md)
* [max-lines](max-lines.md)
* [max-lines-per-function](max-lines-per-function.md)
* [max-params](max-params.md)
* [max-statements](max-statements.md)