text:
import { SLOT } from '../priorities'

import {
  parseTemplate,
  cloneNode
} from '../../parsers/template'

import {
  extend,
  extractContent,
  replace,
  remove,
  isTemplate
} from '../../util/index'

// This is the elementDirective that handles <content>
// transclusions. It relies on the raw content of an
// instance being stored as `$options._content` during
// the transclude phase.

// We are exporting two versions, one for named and one
// for unnamed, because the unnamed slots must be compiled
// AFTER all named slots have selected their content. So
// we need to give them different priorities in the compilation
// process. (See #1965)

export const slot = {

  priority: SLOT,

  bind () {
    var host = this.vm
    var raw = host.$options._content
    if (!raw) {
      this.fallback()
      return
    }
    var context = host._context
    var slotName = this.params && this.params.name
    if (!slotName) {
      // Default slot
      this.tryCompile(extractFragment(raw.childNodes, raw, true), context, host)
    } else {
      // Named slot
      var selector = '[slot="' + slotName + '"]'
      var nodes = raw.querySelectorAll(selector)
      if (nodes.length) {
        this.tryCompile(extractFragment(nodes, raw), context, host)
      } else {
        this.fallback()
      }
    }
  },

  tryCompile (content, context, host) {
    if (content.hasChildNodes()) {
      this.compile(content, context, host)
    } else {
      this.fallback()
    }
  },

  compile (content, context, host) {
    if (content && context) {
      if (
        this.el.hasChildNodes() &&
        content.childNodes.length === 1 &&
        content.childNodes[0].nodeType === 1 &&
        content.childNodes[0].hasAttribute('v-if')
      ) {
        // if the inserted slot has v-if
        // inject fallback content as the v-else
        const elseBlock = document.createElement('template')
        elseBlock.setAttribute('v-else', '')
        elseBlock.innerHTML = this.el.innerHTML
        // the else block should be compiled in child scope
        elseBlock._context = this.vm
        content.appendChild(elseBlock)
      }
      const scope = host
        ? host._scope
        : this._scope
      this.unlink = context.$compile(
        content, host, scope, this._frag
      )
    }
    if (content) {
      replace(this.el, content)
    } else {
      remove(this.el)
    }
  },

  fallback () {
    this.compile(extractContent(this.el, true), this.vm)
  },

  unbind () {
    if (this.unlink) {
      this.unlink()
    }
  }
}

export const namedSlot = extend(extend({}, slot), {
  priority: slot.priority + 1,
  params: ['name']
})

/**
 * Extract qualified content nodes from a node list.
 *
 * @param {NodeList} nodes
 * @param {Element} parent
 * @param {Boolean} main
 * @return {DocumentFragment}
 */

function extractFragment (nodes, parent, main) {
  var frag = document.createDocumentFragment()
  for (var i = 0, l = nodes.length; i < l; i++) {
    var node = nodes[i]
    // if this is the main outlet, we want to skip all
    // previously selected nodes;
    // otherwise, we want to mark the node as selected.
    // clone the node so the original raw content remains
    // intact. this ensures proper re-compilation in cases
    // where the outlet is inside a conditional block
    if (main && !node.__v_selected) {
      append(node)
    } else if (!main && node.parentNode === parent) {
      node.__v_selected = true
      append(node)
    }
  }
  return frag

  function append (node) {
    if (isTemplate(node) &&
        !node.hasAttribute('v-if') &&
        !node.hasAttribute('v-for')) {
      node = parseTemplate(node)
    }
    node = cloneNode(node)
    frag.appendChild(node)
  }
}


text:
"""Custom swarming trigger script for ChromeOS device tests.

CrOS device tests are unique in that the device OS they prefer to run on is
continuously changing. The LKGM file, checked into src at
//chromeos/CHROMEOS_LKGM, represents the ChromeOS version Chrome's ToT aims
to be compatible with. Therefore, a CrOS test for Chrome ideally targets a
device running the LKGM.

Since the LKGM file gets updated frequently (~daily), we can't reasonably
hardcode the LKGM in the test specs. So this special trigger script will read
the current LKGM (at the time of trigger) and append that to the task's
dimensions. If such a device isn't available in time, the task will fallback
to one running any OS.
"""

import argparse
import os
import re
import sys

import base_test_triggerer

SRC_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(
  __file__))))
LKGM_FILE_PATH = os.path.join(SRC_DIR, 'chromeos', 'CHROMEOS_LKGM')
# Should match something that looks like "12345.0.0".
LKGM_RE = re.compile(r'\d+\.\d+\.\d+')

def read_current_lkgm():
  if not os.path.exists(LKGM_FILE_PATH):
    sys.stderr.write('LKGM file not present at %s\n' % LKGM_FILE_PATH)
    return None

  with open(LKGM_FILE_PATH) as f:
    lkgm = f.read().strip()

  if not LKGM_RE.match(lkgm):
    sys.stderr.write('Unknown format of LKGM: %s\n' % lkgm)
    return None

  # Just the major version should be sufficient.
  return lkgm.split('.')[0]

def parse_args(triggerer):
  # This script will do nothing but inspect and tweak the dimension args to
  # `swarming.py trigger`. So let's pull just those out.
  parser = argparse.ArgumentParser(description=__doc__)
  parser.add_argument(
      '-d', '--dimension', default=[], action='append', nargs=2,
      dest='dimensions',
      help='Dimensions to filter on. Duplicated from the `swarming.py trigger` '
           'command. Parsed here to ensure `device_os` is not added.'
  )
  parser.add_argument(
      '--optional-dimension', default=[], action='append', nargs=3,
      dest='optional_dimensions',
      help='Optional dimensions which will result in additional task slices. '
           'Duplicated from the `swarming.py trigger` command.')
  parser.add_argument(
      '--primary-expiration', type=int, default=600,
      help='How long to wait (in seconds) for an available bot in the primary '
           'task slice.')
  # BaseTestTriggerer's setup_parser_contract() takes care of adding needed
  # swarming.py args if they're not already present. But only do this if
  # '--shard-index' is passed in. (The exact usage of trigger scripts are
  # currently changing. See crbug.com/926987 for more info.)
  if '--shard-index' in sys.argv:
    base_test_triggerer.BaseTestTriggerer.setup_parser_contract(parser)
    args, additional_args = parser.parse_known_args()
    additional_args = triggerer.modify_args(
        additional_args, 0, args.shard_index, args.shards, args.dump_json)
  else:
    args, additional_args = parser.parse_known_args()

  if additional_args[0] != 'trigger':
    parser.error(
        'This script is only supported for `swarming.py trigger` invocations.')

  for k, _ in args.dimensions:
    if k == 'device_os':
      parser.error(
          'Must not specify the device_os dimension when using this script. '
          '(It will be added automatically.)')

  # It might be a valid use-case to include optional-dimensions in the initial
  # invocation. But it'd be difficult to integrate them into what we're doing
  # here. So let's just ensure there aren't any.
  if args.optional_dimensions:
    parser.error(
        'Must not specify optional dimensions when using this script.')

  return args, additional_args

def main():
  triggerer = base_test_triggerer.BaseTestTriggerer()
  args, additional_args = parse_args(triggerer)

  current_lkgm = read_current_lkgm()
  if not current_lkgm:
    return 1

  new_args = additional_args[:1]
  # Insert our modified dimension args in between the 1st and 2nd args of the
  # initial `swarming.py` invocation. This avoids the presence of the special
  # `--` arg from causing swarming.py to ignore them.
  needs_device_status = True
  for k, v in args.dimensions:
    new_args.extend(['--dimension', k, v])
    if k == 'device_status':
      needs_device_status = False

  # Only CrOS device bots with a device_status dimension of "available" should
  # run tests. So target those explicitly if we aren't already.
  if needs_device_status:
    new_args.extend(['--dimension', 'device_status', 'available'])

  new_args.extend([
      '--optional-dimension',
      'device_os',
      current_lkgm,
      str(args.primary_expiration),
  ])
  new_args += additional_args[1:]

  return triggerer.run_swarming(new_args, True)

if __name__ == '__main__':
  sys.exit(main())

redpajama_set_name: RedPajamaGithub


text:
package com.kauridev.lunarbase;

/**
 * An entity matcher that determines if an entity belongs to a group.
 *
 * @author Eric Fritz
 */
public class GroupEntityMatcher implements EntityMatcher
{
	/**
	 * The group manager.
	 */
	private GroupManager manager;

	/**
	 * The target group.
	 */
	private String group;

	/**
	 * Creates a new GroupEntityMatcher.
	 *
	 * @param groupManager The group manager.
	 * @param group        The target group.
	 */
	public GroupEntityMatcher(GroupManager groupManager, String group) {
		this.manager = groupManager;
		this.group = group;
	}

	@Override
	public boolean matches(Entity entity) {
		return manager.hasGroup(entity, group);
	}
}


text:
<?php

$path = ROOT_PATH . 'src/modules/admin/src/';

require $path . 'actions.php';
require $path . 'functions.php';


text:
package com.google.code.validationframework.base.rule.bool;

import com.google.code.validationframework.api.rule.Rule;

/**
 * Rule checking that the data is boolean whose value is false.
 *
 * @see Rule
 * @see IsTrueRule
 */
public class IsFalseRule implements Rule<Boolean, Boolean> {

    /**
     * Default result to be returned when a null value is checked.
     */
    private static final Boolean DEFAULT_RESULT_FOR_NULL_DATA = true;

    /**
     * Result to be returned when null value is checked.
     */
    private final Boolean resultForNullData;

    /**
     * Default constructor considering null data to be true.
     */
    public IsFalseRule() {
        this(DEFAULT_RESULT_FOR_NULL_DATA);
    }

    /**
     * Constructor specifying the result to be returned when a null value is checked.
     *
     * @param resultForNullData Result to be returned when null value is checked.
     */
    public IsFalseRule(boolean resultForNullData) {
        this.resultForNullData = resultForNullData;
    }

    /**
     * @see Rule#validate(Object)
     */
    @Override
    public Boolean validate(Boolean data) {
        Boolean result;

        if (data == null) {
            result = resultForNullData;
        } else {
            result = !data;
        }

        return result;
    }
}


text:
int init_str_primitive(object *env);

#endif


text:
"""Package containing fingerprinting for all runtimes.
"""

from gae_ext_runtime import ext_runtime

from googlecloudsdk.api_lib.app import ext_runtime_adapter
from googlecloudsdk.api_lib.app.runtimes import python
from googlecloudsdk.api_lib.app.runtimes import python_compat
from googlecloudsdk.core import exceptions
from googlecloudsdk.core import log

RUNTIMES = [
    # Note that ordering of runtimes here is very important and changes to the
    # relative positions need to be tested carefully.

    # Custom comes first, if we've got a Dockerfile this is a custom runtime.
    ext_runtime_adapter.CoreRuntimeLoader('custom', 'Custom',
                                          ['custom']),

    # Go's position is relatively flexible due to its orthogonal nature.
    ext_runtime_adapter.CoreRuntimeLoader('go', 'Go', ['go', 'custom']),

    ext_runtime_adapter.CoreRuntimeLoader('ruby', 'Ruby', ['ruby', 'custom']),
    ext_runtime_adapter.CoreRuntimeLoader('nodejs', 'Node.js',
                                          ['nodejs', 'custom']),
    ext_runtime_adapter.CoreRuntimeLoader('java', 'Java',
                                          ['java', 'java7', 'custom']),
    python_compat,

    # Python and PHP are last because they match if any .py or .php file is
    # present.
    ext_runtime_adapter.CoreRuntimeLoader('python', 'Python',
                                          ['python', 'custom']),
    ext_runtime_adapter.CoreRuntimeLoader('php', 'PHP', ['php', 'custom']),
]

class UnidentifiedDirectoryError(exceptions.Error):
  """Raised when GenerateConfigs() can't identify the directory."""

  def __init__(self, path):
    """Constructor.

    Args:
      path: (basestring) Directory we failed to identify.
    """
    super(UnidentifiedDirectoryError, self).__init__(
        'Unrecognized directory type: [{0}]'.format(path))
    self.path = path

class ExtRuntimeError(exceptions.Error):
  """ext_runtime.Error errors are converted to this."""

class ConflictingConfigError(exceptions.Error):
  """Property in app.yaml conflicts with params passed to fingerprinter."""

class AlterConfigFileError(exceptions.Error):
  """Error when attempting to update an existing config file (app.yaml)."""

  def __init__(self, inner_exception):
    super(AlterConfigFileError, self).__init__(
        'Could not alter app.yaml due to an internal error:\n{0}\n'
        'Please update app.yaml manually.'.format(inner_exception))

def IdentifyDirectory(path, params=None):
  """Try to identify the given directory.

  As a side-effect, if there is a config file in 'params' with a runtime of
  'custom', this sets params.custom to True.

  Args:
    path: (basestring) Root directory to identify.
    params: (ext_runtime.Params or None) Parameters passed through to the
      fingerprinters.  Uses defaults if not provided.

  Returns:
    (ext_runtime.Configurator or None) Returns a module if we've identified
    it, None if not.
  """
  if not params:
    params = ext_runtime.Params()

  # Parameter runtime has precedence
  if params.runtime:
    specified_runtime = params.runtime
  elif params.appinfo:
    specified_runtime = params.appinfo.GetEffectiveRuntime()
  else:
    specified_runtime = None

  if specified_runtime == 'custom':
    params.custom = True

  for runtime in RUNTIMES:

    # If we have an app.yaml, don't fingerprint for any runtimes that don't
    # allow the runtime name it specifies.
    if (specified_runtime and runtime.ALLOWED_RUNTIME_NAMES and
        specified_runtime not in runtime.ALLOWED_RUNTIME_NAMES):
      log.info('Not checking for [%s] because runtime is [%s]' %
               (runtime.NAME, specified_runtime))
      continue

    try:
      configurator = runtime.Fingerprint(path, params)
    except ext_runtime.Error as ex:
      raise ExtRuntimeError(ex.message)
    if configurator:
      return configurator
  return None

def _GetModule(path, params=None, config_filename=None):
  """Helper function for generating configs.

  Args:
    path: (basestring) Root directory to identify.
    params: (ext_runtime.Params or None) Parameters passed through to the
      fingerprinters.  Uses defaults if not provided.
    config_filename: (str or None) Filename of the config file (app.yaml).

  Raises:
    UnidentifiedDirectoryError: No runtime module matched the directory.
    ConflictingConfigError: Current app.yaml conflicts with other params.

  Returns:
    ext_runtime.Configurator, the configurator for the path
  """
  if not params:
    params = ext_runtime.Params()

  config = params.appinfo
  # An app.yaml exists, results in a lot more cases
  if config and not params.deploy:
    # Enforce --custom
    if not params.custom:
      raise ConflictingConfigError(
          'Configuration file already exists. This command generates an '
          'app.yaml configured to run an application on Google App Engine. '
          'To create the configuration files needed to run this '
          'application with docker, try `gcloud preview app gen-config '
          '--custom`.')
    # Check that current config is for MVM
    if not config.IsVm():
      raise ConflictingConfigError(
          'gen-config is only supported for App Engine Flexible.  Please '
          'use "vm: true" in your app.yaml if you would like to use App Engine '
          'Flexible to run your application.')
    # Check for conflicting --runtime and runtime in app.yaml
    if (config.GetEffectiveRuntime() != 'custom' and params.runtime is not None
        and params.runtime != config.GetEffectiveRuntime()):
      raise ConflictingConfigError(
          '[{0}] contains "runtime: {1}" which conficts with '
          '--runtime={2}.'.format(config_filename, config.GetEffectiveRuntime(),
                                  params.runtime))

  module = IdentifyDirectory(path, params)
  if not module:
    raise UnidentifiedDirectoryError(path)
  return module

def GenerateConfigs(path, params=None, config_filename=None):
  """Identify runtime and generate config files for a directory.

  If a runtime can be identified for the given directory, calls the runtime's
  GenerateConfigs method, which writes configs to the directory.

  Args:
    path: (basestring) Root directory to identify.
    params: (ext_runtime.Params or None) Parameters passed through to the
      fingerprinters.  Uses defaults if not provided.
    config_filename: (str or None) Filename of the config file (app.yaml).

  Raises:
    ExtRuntimeError: if there was an error generating configs

  Returns:
    (bool): True if files were written
  """
  module = _GetModule(path, params=params, config_filename=config_filename)

  try:
    return module.GenerateConfigs()
  except ext_runtime.Error as ex:
    raise ExtRuntimeError(ex.message)

def GenerateConfigData(path, params=None, config_filename=None):
  """Identify runtime and generate contents of config files for a directory.

  If a runtime can be identified for the given directory, calls the runtime's
  GenerateConfigData method, which generates the contents of config files.

  Args:
    path: (basestring) Root directory to identify.
    params: (ext_runtime.Params or None) Parameters passed through to the
      fingerprinters.  Uses defaults if not provided.
    config_filename: (str or None) Filename of the config file (app.yaml).

  Raises:
    ExtRuntimeError: if there was an error generating configs

  Returns:
    [ext_runtime.GeneratedFile] generated config files.
  """
  module = _GetModule(path, params=params, config_filename=config_filename)

  try:
    return module.GenerateConfigData()
  except ext_runtime.Error as ex:
    raise ExtRuntimeError(ex.message)


text:
class CreateFeeds < ActiveRecord::Migration
  def change
    create_table :feeds do |t|
      t.belongs_to :user, index: true
      t.string :action
      t.belongs_to :trackable, index: true
      t.string :trackable_type

      t.timestamps null: false
    end
    add_foreign_key :feeds, :users
    add_foreign_key :feeds, :trackables
  end
end


text:
class CreateDispatchingWorkflows < ActiveRecord::Migration
  def change
    create_table :dispatching_workflows do |t|
      t.integer :dispatching_id
      t.integer :workflow_id

      t.timestamps
    end
  end
end


text:
//
// Copyright 2018 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

#ifndef GRPC_CORE_EXT_XDS_XDS_API_H
#define GRPC_CORE_EXT_XDS_XDS_API_H

#include <grpc/support/port_platform.h>

#include <stddef.h>

#include <map>
#include <set>
#include <string>
#include <utility>
#include <vector>

#include "absl/status/status.h"
#include "absl/strings/string_view.h"
#include "envoy/admin/v3/config_dump_shared.upb.h"
#include "upb/arena.h"
#include "upb/def.hpp"

#include "src/core/ext/xds/xds_bootstrap.h"
#include "src/core/ext/xds/xds_client_stats.h"
#include "src/core/lib/debug/trace.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/gprpp/time.h"

namespace grpc_core {

class XdsClient;

// TODO(roth): When we have time, split this into multiple pieces:
// - ADS request/response handling
// - LRS request/response handling
// - CSDS response generation
class XdsApi {
 public:
  // Interface defined by caller and passed to ParseAdsResponse().
  class AdsResponseParserInterface {
   public:
    struct AdsResponseFields {
      std::string type_url;
      std::string version;
      std::string nonce;
      size_t num_resources;
    };

    virtual ~AdsResponseParserInterface() = default;

    // Called when the top-level ADS fields are parsed.
    // If this returns non-OK, parsing will stop, and the individual
    // resources will not be processed.
    virtual absl::Status ProcessAdsResponseFields(AdsResponseFields fields) = 0;

    // Called to parse each individual resource in the ADS response.
    virtual void ParseResource(upb_Arena* arena, size_t idx,
                               absl::string_view type_url,
                               absl::string_view serialized_resource) = 0;
  };

  struct ClusterLoadReport {
    XdsClusterDropStats::Snapshot dropped_requests;
    std::map<RefCountedPtr<XdsLocalityName>, XdsClusterLocalityStats::Snapshot,
             XdsLocalityName::Less>
        locality_stats;
    Duration load_report_interval;
  };
  using ClusterLoadReportMap = std::map<
      std::pair<std::string /*cluster_name*/, std::string /*eds_service_name*/>,
      ClusterLoadReport>;

  // The metadata of the xDS resource; used by the xDS config dump.
  struct ResourceMetadata {
    // Resource status from the view of a xDS client, which tells the
    // synchronization status between the xDS client and the xDS server.
    enum ClientResourceStatus {
      // Client requested this resource but hasn't received any update from
      // management server. The client will not fail requests, but will queue
      // them
      // until update arrives or the client times out waiting for the resource.
      REQUESTED = 1,
      // This resource has been requested by the client but has either not been
      // delivered by the server or was previously delivered by the server and
      // then subsequently removed from resources provided by the server.
      DOES_NOT_EXIST,
      // Client received this resource and replied with ACK.
      ACKED,
      // Client received this resource and replied with NACK.
      NACKED
    };

    // The client status of this resource.
    ClientResourceStatus client_status = REQUESTED;
    // The serialized bytes of the last successfully updated raw xDS resource.
    std::string serialized_proto;
    // The timestamp when the resource was last successfully updated.
    Timestamp update_time;
    // The last successfully updated version of the resource.
    std::string version;
    // The rejected version string of the last failed update attempt.
    std::string failed_version;
    // Details about the last failed update attempt.
    std::string failed_details;
    // Timestamp of the last failed update attempt.
    Timestamp failed_update_time;
  };
  using ResourceMetadataMap =
      std::map<std::string /*resource_name*/, const ResourceMetadata*>;
  using ResourceTypeMetadataMap =
      std::map<absl::string_view /*type_url*/, ResourceMetadataMap>;
  static_assert(static_cast<ResourceMetadata::ClientResourceStatus>(
                    envoy_admin_v3_REQUESTED) ==
                    ResourceMetadata::ClientResourceStatus::REQUESTED,
                "");
  static_assert(static_cast<ResourceMetadata::ClientResourceStatus>(
                    envoy_admin_v3_DOES_NOT_EXIST) ==
                    ResourceMetadata::ClientResourceStatus::DOES_NOT_EXIST,
                "");
  static_assert(static_cast<ResourceMetadata::ClientResourceStatus>(
                    envoy_admin_v3_ACKED) ==
                    ResourceMetadata::ClientResourceStatus::ACKED,
                "");
  static_assert(static_cast<ResourceMetadata::ClientResourceStatus>(
                    envoy_admin_v3_NACKED) ==
                    ResourceMetadata::ClientResourceStatus::NACKED,
                "");

  XdsApi(XdsClient* client, TraceFlag* tracer, const XdsBootstrap::Node* node,
         upb::SymbolTable* symtab);

  // Creates an ADS request.
  // Takes ownership of \a error.
  std::string CreateAdsRequest(const XdsBootstrap::XdsServer& server,
                               absl::string_view type_url,
                               absl::string_view version,
                               absl::string_view nonce,
                               const std::vector<std::string>& resource_names,
                               absl::Status status, bool populate_node);

  // Returns non-OK when failing to deserialize response message.
  // Otherwise, all events are reported to the parser.
  absl::Status ParseAdsResponse(const XdsBootstrap::XdsServer& server,
                                absl::string_view encoded_response,
                                AdsResponseParserInterface* parser);

  // Creates an initial LRS request.
  std::string CreateLrsInitialRequest(const XdsBootstrap::XdsServer& server);

  // Creates an LRS request sending a client-side load report.
  std::string CreateLrsRequest(ClusterLoadReportMap cluster_load_report_map);

  // Parses the LRS response and populates send_all_clusters,
  // cluster_names, and load_reporting_interval.
  absl::Status ParseLrsResponse(absl::string_view encoded_response,
                                bool* send_all_clusters,
                                std::set<std::string>* cluster_names,
                                Duration* load_reporting_interval);

  // Assemble the client config proto message and return the serialized result.
  std::string AssembleClientConfig(
      const ResourceTypeMetadataMap& resource_type_metadata_map);

 private:
  XdsClient* client_;
  TraceFlag* tracer_;
  const XdsBootstrap::Node* node_;  // Do not own.
  upb::SymbolTable* symtab_;        // Do not own.
  const std::string build_version_;
  const std::string user_agent_name_;
  const std::string user_agent_version_;
};

}  // namespace grpc_core

#endif  // GRPC_CORE_EXT_XDS_XDS_API_H


text:
using JetBrains.Annotations;
using UnityEditor;

namespace JetBrains.Rider.Unity.Editor
{
  // Do not rename this class while you don't rename startup command for dotTrace profiler
  [UsedImplicitly]
  public static class StartUpMethodExecutor
  {
    public static void EnterPlayMode()
    {
      EditorApplication.isPlaying = true;
    }
  }
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;

namespace Microsoft.VisualStudio.LanguageServices.ProjectSystem
{
    /// <summary>
    /// Factory to create a project context for a new Workspace project that can be initialized on a background thread.
    /// </summary>
    internal interface IWorkspaceProjectContextFactory
    {
        /// <summary>
        /// Creates and initializes a new Workspace project and returns a <see cref="IWorkspaceProjectContext"/> to lazily initialize the properties and items for the project.
        /// </summary>
        /// <param name="languageName">Project language.</param>
        /// <param name="projectUniqueName">Unique name for the project.</param>
        /// <param name="projectFilePath">Full path to the project file for the project.</param>
        /// <param name="projectGuid">Project guid.</param>
        /// <param name="hierarchy"><see cref="IVsHierarchy"/> for the project, an be null in deferred project load cases.</param>
        /// <param name="binOutputPath">Initial project binary output path.</param>
        IWorkspaceProjectContext CreateProjectContext(string languageName, string projectUniqueName, string projectFilePath, Guid projectGuid, object hierarchy, string binOutputPath);

        /// <summary>
        /// Creates and initializes a new Workspace project and returns a <see cref="IWorkspaceProjectContext"/> to lazily initialize the properties and items for the project.
        /// </summary>
        /// <param name="languageName">Project language.</param>
        /// <param name="projectUniqueName">Display name for the project.</param>
        /// <param name="projectFilePath">Full path to the project file for the project.</param>
        /// <param name="projectGuid">Project guid.</param>
        /// <param name="hierarchy"><see cref="IVsHierarchy"/> for the project, an be null in deferred project load cases.</param>
        /// <param name="binOutputPath">Initial project binary output path.</param>
        /// <param name="errorReporter">Error reporter object.</param>
        IWorkspaceProjectContext CreateProjectContext(string languageName, string projectUniqueName, string projectFilePath, Guid projectGuid, object hierarchy, string binOutputPath, ProjectExternalErrorReporter errorReporter);
    }
}


text:
using CommandLine;
using ContromeToOpenHAB.JSON;
using Newtonsoft.Json.Linq;
using RestSharp;
using RestSharp.Authenticators;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Runtime.Intrinsics.Arm;
using System.Text;
using System.Threading.Tasks;

namespace ContromeToOpenHAB
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Parser.Default.ParseArguments<Options>(args)
                 .WithParsed<Options>(Run);

            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed: " + ex.ToString());
            }
        }

        static void Run(Options options)
        {

            try
            {
                using (StreamWriter thingsFile = CreateConfigFile(options, Path.Combine("things", "controme.things")))
                {
                    using (StreamWriter itemsFile = CreateConfigFile(options, Path.Combine("items", "controme.items")))
                    {
                        using (StreamWriter sitemapFile = CreateSitemap(options))
                        {

                            Uri contromeBaseUrl = new Uri($"http://{options.ContromeURL}/");

                            RestRequest request = new RestRequest("get/json/v1/{HouseID}/{Method}");
                            request.AddUrlSegment("HouseID", options.HouseID.ToString());
                            request.AddUrlSegment("Method", "temps");

                            string strGetTemps = $"get/json/v1/{options.HouseID}/temps/";
                            string strSetTargetTemp = $"set/json/v1/{options.HouseID}/soll/";
                            string strGetOuts = $"get/json/v1/{options.HouseID}/outs/";

                            RestClient client = new RestClient(contromeBaseUrl);

                            var responseTemps = client.Execute(request);
                            JArray jsonTemps = JArray.Parse(responseTemps.Content);

                            IRestResponse responseRelays = null;
                            JArray jsonRelays = null;
                            if (options.ReleyStates)
                            {
                                request = new RestRequest("get/json/v1/{HouseID}/{Method}");
                                request.AddUrlSegment("HouseID", options.HouseID.ToString());
                                request.AddUrlSegment("Method", "outs");
                                responseRelays = client.Execute(request);
                                jsonRelays = JArray.Parse(responseRelays.Content);

                            }
                            else { }
                            string thingId = $"http:url:Controme_{GetDeterministicHashCode(options.ContromeURL):X}";
                            thingsFile.WriteLine($"Thing {thingId} \"Controme\" [ baseURL=\"{contromeBaseUrl.AbsoluteUri}\", refresh=3600,commandMethod=\"POST\", contentType=\"application/x-www-form-urlencoded\" ] {{");
                            thingsFile.WriteLine("\tChannels:");
                            foreach (JObject floor in jsonTemps)
                            {
                                string strFloorName = floor["etagenname"].Value<string>();

                                Console.WriteLine("Creating files for floor " + strFloorName);

                                sitemapFile.WriteLine($"Frame label=\"{strFloorName}\" {{");
                                string strFloorPrefix = new string(Escape(strFloorName).ToArray()) + "_";
                                JArray rooms = floor["raeume"].Value<JArray>();

                                Dictionary<string, JToken> relayState = null;

                                if (options.ReleyStates)
                                {

                                    relayState = jsonRelays
                                        .Where((o) => o["etagenname"].Value<string>() == strFloorName)
                                        .SelectMany((o) => o["raeume"].Value<JArray>())
                                        .ToDictionary((o) => o["id"].Value<string>());
                                }
                                else { }

                                foreach (var room in rooms)
                                {
                                    string strRoomName = room["name"].Value<string>();
                                    string strJpath;
                                    string strRoomID = room["id"].Value<string>();

                                    request = new RestRequest("get/json/v1/{HouseID}/{Method}/{Room}");
                                    request.AddUrlSegment("HouseID", options.HouseID.ToString());
                                    request.AddUrlSegment("Method", "rltemps");
                                    request.AddUrlSegment("Room", strRoomID);

                                    var ContromeRlTempResponse = client.Execute<List<ContromeRlTemp>>(request);

                                    string strEscapedName = strFloorPrefix + new string(Escape(strRoomName).ToArray());

                                    Console.WriteLine("Creating entries for  " + strRoomName);
                                    strJpath = $"$..raeume[?(@.id=={strRoomID})].temperatur";
                                    if (IsJPathValid(jsonTemps, strJpath))
                                    {
                                        thingsFile.WriteLine($"\t\tType number : {strEscapedName} \"{strRoomName}\" [stateExtension=\"{strGetTemps}\", stateTransformation=\"JSONPATH:{strJpath}\", mode=\"READONLY\" ] ");
                                    }
                                    else
                                        Debugger.Break();
                                    strJpath = $"$..raeume[?(@.id=={strRoomID})].solltemperatur";
                                    if (IsJPathValid(jsonTemps, strJpath))
                                    {
                                        thingsFile.WriteLine($"\t\tType number : {strEscapedName}_setpoint \"{strRoomName} soll\" [stateExtension=\"{strGetTemps}\", stateTransformation=\"JSONPATH:{strJpath}\", commandExtension=\"{strSetTargetTemp}{strRoomID}/\",commandTransformation=\"REGEX:s/(.+)/soll=$1&user={Uri.EscapeUriString(options.Username)}&password={Uri.EscapeUriString(options.Password)}/g\" ] ");
                                        //itemsFile.WriteLine($"Number Controme_Raw_{strEscapedName}_Soll {{http = \"<[{strCacheUrlTemp}:10000:JSONPATH({strJpath})]\"}}");
                                    }
                                    else
                                        Debugger.Break();

                                    itemsFile.WriteLine($"Group g{strEscapedName}Thermostat \"{strRoomName}\" <heating> [\"RadiatorControl\"] {{alexa = \"Endpoint.Thermostat\"}}");
                                    itemsFile.WriteLine($"Number:Temperature Controme_{strEscapedName} \"{strRoomName}\" <temperature> (g{strEscapedName}Thermostat) [\"Point\",\"Temperature\"] {{channel=\"{thingId}:{strEscapedName}\",alexa=\"TemperatureSensor.temperature\" }}");
                                    itemsFile.WriteLine($"Number:Temperature Controme_{strEscapedName}_setpoint \"{strRoomName} Soll\" <temperature> (g{strEscapedName}Thermostat) [\"Point\",\"Temperature\"] {{channel=\"{thingId}:{strEscapedName}_setpoint\",alexa=\"TemperatureSensor.targetSetpoint\" }}");

                                    var rlIds = ContromeRlTempResponse.Data.Select((r) => r.Name).ToHashSet();

                                    var sensors = room["sensoren"] as JArray;
                                    if (sensors != null)
                                    {
                                        int nRL = 1;
                                        int nRoom = 0;
                                        int nExternalTemp = 1;
                                        int nExternalHum = 1;
                                        for (int i = 0; i < sensors.Count; ++i)
                                        {
                                            var sensor = sensors[i];
                                            var sensorId = (sensor["name"] as JValue).Value<string>();

                                            string strSensorDescription = (sensor["beschreibung"] as JValue).Value<string>();
                                            string strSensorName = $"sensor{i}";
                                            bool blnIsExternalTemp = options.ExternalTempSensorIds.Any(externalSensorId => sensorId.StartsWith(externalSensorId, StringComparison.InvariantCultureIgnoreCase));
                                            bool blnIsExternalHumidity = options.ExternalHumiditySensorIds.Any(externalSensorId => sensorId.StartsWith(externalSensorId, StringComparison.InvariantCultureIgnoreCase));
                                            string strUnit = "Temperature";
                                            if (rlIds.Contains(sensorId))
                                            {
                                                strSensorDescription = $"{strRoomName} Rücklauf #{nRL}";
                                                strSensorName = $"RL_{nRL++}";

                                            }
                                            else if ((sensor["raumtemperatursensor"] as JValue).Value<bool>())
                                            {
                                                strSensorDescription = $"{strRoomName} Raumtemperatur";
                                                if (nRoom++ > 0)
                                                    strSensorName = $"room{nRoom}";
                                                else
                                                    strSensorName = "room";
                                            }
                                            else if (blnIsExternalTemp)
                                            {
                                                strSensorDescription = $"{strRoomName} external Temp";
                                                strSensorName = $"ext_temp_{nExternalTemp++}";
                                            }
                                            else if (blnIsExternalHumidity)
                                            {
                                                strSensorDescription = $"{strRoomName} external Humidity";
                                                strSensorName = $"ext_humi_{nExternalHum++}";
                                                strUnit = "Humidity";
                                            }
                                            else if (!string.IsNullOrWhiteSpace(strSensorDescription))
                                            {
                                                //keep
                                            }
                                            else
                                            {
                                                strSensorDescription = $"{strRoomName} sensor #{i}";
                                            }

                                            strJpath = $"$..raeume[?(@.id=={strRoomID})]..sensoren[?(@.name=='{sensorId}')].wert";

                                            thingsFile.Write($"\t\tType number : {strEscapedName}_{strSensorName} \"{strSensorDescription}\" [stateExtension=\"{strGetTemps}\", stateTransformation=\"JSONPATH:{strJpath}\"");
                                            if (blnIsExternalTemp)
                                            {
                                                thingsFile.Write($", commandExtension=\"set/{sensorId}/temperatur/%2$\", commandTransformation=\"JS:ContromeValue.js\" ");
                                            }
                                            else if(blnIsExternalHumidity)
                                            {
                                                thingsFile.Write($", commandExtension=\"set/{sensorId}/%2$.2f\" ");
                                            }
                                            else
                                            {
                                                thingsFile.Write(", mode=\"READONLY\" ");
                                            }

                                            thingsFile.WriteLine("] ");

                                            itemsFile.WriteLine($"Number:{((blnIsExternalHumidity) ? "Dimensionless" : "Temperature")} Controme_{strEscapedName}_{strSensorName} \"{strSensorDescription}\" <{strUnit.ToLower()}> (g{strEscapedName}Thermostat) [\"Measurement\",\"{strUnit}\"] {{channel=\"{thingId}:{strEscapedName}_{strSensorName}\"}}");
                                        }
                                    }
                                    else { }

                                    sitemapFile.WriteLine($"Text item=Controme_{strEscapedName} icon=\"TemperaturSensor\"");
                                    sitemapFile.WriteLine($"Setpoint item=Controme_{strEscapedName}_Soll step=0.5 minValue=15 maxValue=26 icon=\"TemperaturSensor\"");

                                    if (options.ReleyStates && relayState.ContainsKey(strRoomID))
                                    {
                                        var outs = relayState[strRoomID];

                                        var ausgang = outs["ausgang"];

                                        foreach (JProperty token in ausgang)
                                        {
                                            Console.WriteLine("Ausgang {0} = {1}", token.Name, token.Value.Value<int>());
                                            strJpath = $"$..raeume[?(@.id=={strRoomID})].ausgang.['{token.Name}']";
                                            var strRelayName = $"{strEscapedName}_Relay_{token.Name.Trim()}";

                                            if (IsJPathValid(jsonRelays, strJpath))
                                            {
                                                thingsFile.WriteLine($"\t\tType contact : {strRelayName} \"{strRoomName} Ausgang {token.Name.Trim()}\" [stateExtension=\"{strGetOuts}\", stateTransformation=\"JSONPATH:{strJpath}\",openValue=\"1\",closedValue=\"0\", mode=\"READONLY\" ] ");

                                                itemsFile.WriteLine($"Contact Controme_{strRelayName} \"{strRoomName} Ausgang {token.Name.Trim()}\" <fire> (g{strEscapedName}Thermostat) [\"OpenState\"] {{channel=\"{thingId}:{strRelayName}\"}}");

                                                sitemapFile.WriteLine($"Text item=Controme_{strRelayName}");
                                            }
                                            else
                                            {
                                                //Missing...
                                            }
                                        }

                                    }
                                    else { }

                                    itemsFile.WriteLine();
                                }

                                sitemapFile.WriteLine("}");
                            }

                            sitemapFile.WriteLine("}");
                        }
                        thingsFile.WriteLine("}");
                    }
                }
                CreateJSValueTransform(options);
                DirectoryInfo confDir = new DirectoryInfo(Path.Combine(options.OutputDir, "conf"));
                Console.WriteLine("Created config files at " + confDir.FullName);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed: " + ex.ToString());
            }
        }

        private static bool IsJPathValid(JToken json, string strJPath) => json.SelectTokens(strJPath).Any();

        private static IEnumerable<char> Escape(string strRoomName)
        {
            foreach (char c in strRoomName)
                if (!char.IsWhiteSpace(c))
                    if (char.IsLetterOrDigit(c))
                    {
                        switch (c)
                        {
                            case 'ü':
                                yield return 'u';
                                yield return 'e';
                                break;
                            case 'Ü':
                                yield return 'U';
                                yield return 'e';
                                break;
                            case 'ä':
                                yield return 'a';
                                yield return 'e';
                                break;
                            case 'Ä':
                                yield return 'A';
                                yield return 'e';
                                break;
                            case 'Ö':
                                yield return 'O';
                                yield return 'e';
                                break;
                            case 'ö':
                                yield return 'o';
                                yield return 'e';
                                break;
                            case 'ß':
                                yield return 's';
                                yield return 's';
                                break;
                            default:
                                yield return c;
                                break;
                        }
                    }
                    else
                        yield return '_';
        }
        private static void CreateJSValueTransform(Options options)
        {
            using(var file =CreateConfigFile(options,Path.Combine("transform","ContromeValue.js")))
            {
                file.Write(@"(function(T) {
    //https://community.openhab.org/t/controme-smart-heat/26797/22
    var temp_coarse= Math.floor(T*2)/2;     // T is true measured float temperature value
    var temp_fine= T-temp_coarse;
    var value = temp_coarse+ Math.floor(2.0*temp_fine + Math.floor(temp_fine*16) *6.25)/100;
    return value.toFixed(2);
})(value)");
            }
        }
        private static StreamWriter CreateConfigFile(Options options, string strName)
        {
            string strPath = Path.Combine(options.OutputDir, Path.Combine("conf", strName));
            FileInfo f = new FileInfo(strPath);
            if (!f.Directory.Exists)
                f.Directory.Create();

            Stream s = File.Open(strPath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read);
            return new StreamWriter(s);
        }

        private static int GetDeterministicHashCode(string str)
        {
            unchecked
            {
                int hash1 = (5381 << 16) + 5381;
                int hash2 = hash1;

                for (int i = 0; i < str.Length; i += 2)
                {
                    hash1 = ((hash1 << 5) + hash1) ^ str[i];
                    if (i == str.Length - 1)
                        break;
                    hash2 = ((hash2 << 5) + hash2) ^ str[i + 1];
                }

                return hash1 + (hash2 * 1566083941);
            }
        }
        private static StreamWriter CreateSitemap(Options options)
        {
            var writer = CreateConfigFile(options, Path.Combine("sitemaps", "controme.sitemap"));

            writer.WriteLine("sitemap controme label=\"Controme\" icon=\"heating\" {");

            return writer;
        }
    }
}


text:
<?xml version='1.0' encoding='UTF-8'?>

<server xmlns="urn:jboss:domain:2.0">
    <extensions>
        <extension module="org.jboss.as.clustering.infinispan"/>
        <extension module="org.jboss.as.clustering.jgroups"/>
        <extension module="org.jboss.as.connector"/>
        <extension module="org.jboss.as.deployment-scanner"/>
        <extension module="org.jboss.as.ee"/>
        <extension module="org.jboss.as.ejb3"/>
        <extension module="org.jboss.as.jaxrs"/>
        <extension module="org.jboss.as.jdr"/>
        <extension module="org.jboss.as.jmx"/>
        <extension module="org.jboss.as.jpa"/>
        <extension module="org.jboss.as.jsf"/>
        <extension module="org.jboss.as.logging"/>
        <extension module="org.jboss.as.mail"/>
        <extension module="org.jboss.as.modcluster"/>
        <extension module="org.jboss.as.naming"/>
        <extension module="org.jboss.as.pojo"/>
        <extension module="org.jboss.as.remoting"/>
        <extension module="org.jboss.as.sar"/>
        <extension module="org.jboss.as.security"/>
        <extension module="org.jboss.as.threads"/>
        <extension module="org.jboss.as.transactions"/>
        <extension module="org.jboss.as.webservices"/>
        <extension module="org.jboss.as.weld"/>
        <extension module="org.wildfly.extension.batch"/>
        <extension module="org.wildfly.extension.io"/>
        <extension module="org.wildfly.extension.undertow"/>
        <extension module="org.modeshape"/>
    </extensions>
    <management>
        <security-realms>
            <security-realm name="ManagementRealm">
                <authentication>
                    <local default-user="$local"/>
                    <properties path="mgmt-users.properties" relative-to="jboss.server.config.dir"/>
                </authentication>
                <authorization map-groups-to-roles="false">
                    <properties path="mgmt-groups.properties" relative-to="jboss.server.config.dir"/>
                </authorization>
            </security-realm>
            <security-realm name="ApplicationRealm">
                <authentication>
                    <local default-user="$local" allowed-users="*"/>
                    <properties path="application-users.properties" relative-to="jboss.server.config.dir"/>
                </authentication>
                <authorization>
                    <properties path="application-roles.properties" relative-to="jboss.server.config.dir"/>
                </authorization>
            </security-realm>
        </security-realms>
        <audit-log>
            <formatters>
                <json-formatter name="json-formatter"/>
            </formatters>
            <handlers>
                <file-handler name="file" formatter="json-formatter" relative-to="jboss.server.data.dir" path="audit-log.log"/>
            </handlers>
            <logger log-boot="true" log-read-only="false" enabled="false">
                <handlers>
                    <handler name="file"/>
                </handlers>
            </logger>
        </audit-log>
        <management-interfaces>
            <http-interface security-realm="ManagementRealm" http-upgrade-enabled="true">
                <socket-binding http="management-http"/>
            </http-interface>
        </management-interfaces>
        <access-control provider="simple">
            <role-mapping>
                <role name="SuperUser">
                    <include>
                        <user name="$local"/>
                    </include>
                </role>
            </role-mapping>
        </access-control>
    </management>
    <profile>
        <subsystem xmlns="urn:jboss:domain:logging:2.0">
            <console-handler name="CONSOLE">
                <level name="INFO"/>
                <formatter>
                    <named-formatter name="COLOR-PATTERN"/>
                </formatter>
            </console-handler>
            <periodic-rotating-file-handler name="FILE" autoflush="true">
                <formatter>
                    <named-formatter name="PATTERN"/>
                </formatter>
                <file relative-to="jboss.server.log.dir" path="server.log"/>
                <suffix value=".yyyy-MM-dd"/>
                <append value="true"/>
            </periodic-rotating-file-handler>
            <logger category="com.arjuna">
                <level name="WARN"/>
            </logger>
            <logger category="org.apache.tomcat.util.modeler">
                <level name="WARN"/>
            </logger>
            <logger category="org.jboss.as.config">
                <level name="DEBUG"/>
            </logger>
            <logger category="sun.rmi">
                <level name="WARN"/>
            </logger>
            <logger category="jacorb">
                <level name="WARN"/>
            </logger>
            <logger category="jacorb.config">
                <level name="ERROR"/>
            </logger>
            <root-logger>
                <level name="INFO"/>
                <handlers>
                    <handler name="CONSOLE"/>
                    <handler name="FILE"/>
                </handlers>
            </root-logger>
            <formatter name="PATTERN">
                <pattern-formatter pattern="%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n"/>
            </formatter>
            <formatter name="COLOR-PATTERN">
                <pattern-formatter pattern="%K{level}%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n"/>
            </formatter>
        </subsystem>
        <subsystem xmlns="urn:jboss:domain:batch:1.0">
            <job-repository>
                <in-memory/>
            </job-repository>
            <thread-pool>
                <max-threads count="10"/>
                <keepalive-time time="100" unit="milliseconds"/>
            </thread-pool>
        </subsystem>
        <subsystem xmlns="urn:jboss:domain:datasources:2.0">
            <datasources>
                <datasource jndi-name="java:jboss/datasources/ExampleDS" pool-name="ExampleDS" enabled="true" use-java-context="true">
                    <connection-url>jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE</connection-url>
                    <driver>h2</driver>
                    <security>
                        <user-name>sa</user-name>
                        <password>sa</password>
                    </security>
                </datasource>
                <drivers>
                    <driver name="h2" module="com.h2database.h2">
                        <xa-datasource-class>org.h2.jdbcx.JdbcDataSource</xa-datasource-class>
                    </driver>
                </drivers>
            </datasources>
        </subsystem>
        <subsystem xmlns="urn:jboss:domain:deployment-scanner:2.0">
            <deployment-scanner path="deployments" relative-to="jboss.server.base.dir" scan-interval="5000" runtime-failure-causes-rollback="${jboss.deployment.scanner.rollback.on.failure:false}"/>
        </subsystem>
        <subsystem xmlns="urn:jboss:domain:ee:2.0">
            <spec-descriptor-property-replacement>false</spec-descriptor-property-replacement>
            <jboss-descriptor-property-replacement>true</jboss-descriptor-property-replacement>
            <annotation-property-replacement>false</annotation-property-replacement>
            <concurrent>
                <context-services>
                    <context-service name="default" jndi-name="java:jboss/ee/concurrency/context/default" use-transaction-setup-provider="true"/>
                </context-services>
                <managed-executor-services>
                    <managed-executor-service name="default" jndi-name="java:jboss/ee/concurrency/executor/default" context-service="default" hung-task-threshold="60000" core-threads="5" max-threads="25" keepalive-time="5000"/>
                </managed-executor-services>
                <managed-scheduled-executor-services>
                    <managed-scheduled-executor-service name="default" jndi-name="java:jboss/ee/concurrency/scheduler/default" context-service="default" hung-task-threshold="60000" core-threads="2" keepalive-time="3000"/>
                </managed-scheduled-executor-services>
                <managed-thread-factories>
                    <managed-thread-factory name="default" jndi-name="java:jboss/ee/concurrency/factory/default" context-service="default"/>
                </managed-thread-factories>
            </concurrent>
        </subsystem>
        <subsystem xmlns="urn:jboss:domain:ejb3:2.0">
            <session-bean>
                <stateless>
                    <bean-instance-pool-ref pool-name="slsb-strict-max-pool"/>
                </stateless>
                <stateful default-access-timeout="5000" cache-ref="distributable" passivation-disabled-cache-ref="simple"/>
                <singleton default-access-timeout="5000"/>
            </session-bean>
            <pools>
                <bean-instance-pools>
                    <strict-max-pool name="slsb-strict-max-pool" max-pool-size="20" instance-acquisition-timeout="5" instance-acquisition-timeout-unit="MINUTES"/>
                    <strict-max-pool name="mdb-strict-max-pool" max-pool-size="20" instance-acquisition-timeout="5" instance-acquisition-timeout-unit="MINUTES"/>
                </bean-instance-pools>
            </pools>
            <caches>
                <cache name="simple"/>
                <cache name="distributable" aliases="passivating clustered" passivation-store-ref="infinispan"/>
            </caches>
            <passivation-stores>
                <passivation-store name="infinispan" cache-container="ejb" max-size="10000"/>
            </passivation-stores>
            <async thread-pool-name="default"/>
            <timer-service thread-pool-name="default" default-data-store="default-file-store">
                <data-stores>
                    <file-data-store name="default-file-store" path="timer-service-data" relative-to="jboss.server.data.dir"/>
                </data-stores>
            </timer-service>
            <remote connector-ref="http-remoting-connector" thread-pool-name="default"/>
            <thread-pools>
                <thread-pool name="default">
                    <max-threads count="10"/>
                    <keepalive-time time="100" unit="milliseconds"/>
                </thread-pool>
            </thread-pools>
            <default-security-domain value="other"/>
            <default-missing-method-permissions-deny-access value="true"/>
        </subsystem>
        <subsystem xmlns="urn:jboss:domain:io:1.0">
            <worker name="default" io-threads="3"/>
            <buffer-pool name="default" buffer-size="16384" buffers-per-slice="128"/>
        </subsystem>
        <subsystem xmlns="urn:jboss:domain:infinispan:2.0">
            <cache-container name="server" aliases="singleton cluster" default-cache="default" module="org.wildfly.clustering.server">
                <transport lock-timeout="60000"/>
                <replicated-cache name="default" mode="SYNC" batching="true">
                    <locking isolation="REPEATABLE_READ"/>
                </replicated-cache>
            </cache-container>
            <cache-container name="web" default-cache="dist" module="org.wildfly.clustering.web.infinispan">
                <transport lock-timeout="60000"/>
                <distributed-cache name="dist" mode="ASYNC" batching="true" l1-lifespan="0" owners="4">
                    <file-store/>
                </distributed-cache>
            </cache-container>
            <cache-container name="ejb" aliases="sfsb" default-cache="dist" module="org.wildfly.clustering.ejb.infinispan">
                <transport lock-timeout="60000"/>
                <distributed-cache name="dist" mode="ASYNC" batching="true" l1-lifespan="0" owners="4">
                    <file-store/>
                </distributed-cache>
            </cache-container>
            <cache-container name="hibernate" default-cache="local-query" module="org.hibernate">
                <transport lock-timeout="60000"/>
                <local-cache name="local-query">
                    <transaction mode="NONE"/>
                    <eviction strategy="LRU" max-entries="10000"/>
                    <expiration max-idle="100000"/>
                </local-cache>
                <invalidation-cache name="entity" mode="SYNC">
                    <transaction mode="NON_XA"/>
                    <eviction strategy="LRU" max-entries="10000"/>
                    <expiration max-idle="100000"/>
                </invalidation-cache>
                <replicated-cache name="timestamps" mode="ASYNC">
                    <transaction mode="NONE"/>
                    <eviction strategy="NONE"/>
                </replicated-cache>
            </cache-container>
            <cache-container name="modeshape" aliases="modeshape modeshape-cluster" default-cache="sample" module="org.modeshape">
                <transport lock-timeout="60000"/>
                <replicated-cache name="sample" mode="SYNC">
                    <transaction mode="NON_XA"/>
                    <file-store relative-to="jboss.server.data.dir" path="modeshape/store/sample-${jboss.node.name}" passivation="false" purge="false"/>
                </replicated-cache>
                <replicated-cache name="artifacts" mode="SYNC">
                    <transaction mode="NON_XA"/>
                    <file-store relative-to="jboss.server.data.dir" path="modeshape/store/artifacts-${jboss.node.name}" passivation="false" purge="false"/>
                </replicated-cache>
            </cache-container>
            <cache-container name="modeshape-binary-cache-container" aliases="modeshape-binary-cache" default-cache="binary-fs" module="org.modeshape">
                <transport lock-timeout="60000"/>
                <replicated-cache name="sample-binary-fs" mode="SYNC">
                    <transaction mode="NON_XA"/>
                    <file-store relative-to="jboss.server.data.dir" path="modeshape/binary-store/sample-binary-data-${jboss.node.name}" passivation="false" purge="false"/>
                </replicated-cache>
                <replicated-cache name="sample-binary-fs-meta" mode="SYNC">
                    <transaction mode="NON_XA"/>
                    <file-store relative-to="jboss.server.data.dir" path="modeshape/binary-store/sample-binary-metadata-${jboss.node.name}" passivation="false" purge="false"/>
                </replicated-cache>
                <replicated-cache name="artifacts-binary-fs" mode="SYNC">
                    <transaction mode="NON_XA"/>
                    <file-store relative-to="jboss.server.data.dir" path="modeshape/binary-store/artifacts-binary-data-${jboss.node.name}" passivation="false" purge="false"/>
                </replicated-cache>
                <replicated-cache name="artifacts-binary-fs-meta" mode="SYNC">
                    <transaction mode="NON_XA"/>
                    <file-store relative-to="jboss.server.data.dir" path="modeshape/binary-store/artifacts-binary-metadata-${jboss.node.name}" passivation="false" purge="false"/>
                </replicated-cache>
            </cache-container>
        </subsystem>
        <subsystem xmlns="urn:jboss:domain:modeshape:2.0">
            <!--The list of web applications that is packaged inside the kit and should be deployed when the subsystem starts up-->
            <webapp name="modeshape-rest.war"/>
            <webapp name="modeshape-webdav.war"/>

            <!-- A sample repository that uses the "sample" cache in the "modeshape" container. All content, binary values,
                 and indexes are stored within the server's data directory. This is the simplest way to configure a repository
                 that uses defaults for everything; feel free to change and specify other configuration options.  -->
            <repository name="sample" cache-name="sample" cache-container="modeshape" anonymous-roles="admin">
                <cache-binary-storage data-cache-name="sample-binary-fs" metadata-cache-name="sample-binary-fs-meta" cache-container="modeshape-binary-cache-container" />
            </repository>
            <!-- A second sample repository that defines additional non-default components such as extra workspaces and sequencers. -->
            <repository name="artifacts" cache-name="artifacts" cache-container="modeshape" anonymous-roles="admin">
                <cache-binary-storage data-cache-name="artifacts-binary-fs" metadata-cache-name="artifacts-binary-fs-meta" cache-container="modeshape-binary-cache-container"/>
                <!-- Define 3 workspaces to exist upon startup -->
                <workspaces default-workspace="default" allow-workspace-creation="false">
                    <workspace name="default">
                        <initial-content>initial-content-default.xml</initial-content>
                    </workspace>
                    <workspace name="other"/>
                    <workspace name="extra"/>
                </workspaces>
                <!--
                Define a bunch of sequencers. Carefully note the differences in the path expressions; some sequencers
                do not generate a node to represent a file, while other sequencers (e.g., XML, XSD, WSDL, ZIP) always
                generate a node based upon the filename.
                The sequencer names are unique identifiers within the configuration, and should not contain spaces.
                Also, some of the sequencer configurations use the fully-qualified classname, while other use the
                short alias (which only works for the sequencer provided by ModeShape). -->
                <sequencers>
                    <sequencer name="delimited-text-sequencer" classname="org.modeshape.sequencer.text.DelimitedTextSequencer"
                               module="org.modeshape.sequencer.text" splitPattern=",">
                        <path-expression>/files(//*.csv[*])/jcr:content[@jcr:data] => /derived/text/delimited/$1</path-expression>
                    </sequencer>
                    <sequencer name="fixed-width-text-sequencer"
                               classname="org.modeshape.sequencer.text.FixedWidthTextSequencer"
                               module="org.modeshape.sequencer.text" commentMarker="#">
                        <path-expression>/files(//*.txt[*])/jcr:content[@jcr:data] => /derived/text/fixedWidth/$1</path-expression>
                    </sequencer>
                    <sequencer name="ddl-sequencer" classname="org.modeshape.sequencer.ddl.DdlSequencer"
                               module="org.modeshape.sequencer.ddl">
                        <path-expression>/files(//*.ddl[*])/jcr:content[@jcr:data] => /derived/ddl/$1</path-expression>
                    </sequencer>
                    <!--
                        For the java & class sequencer we need to explicitly define the module, as it does not map 1-1 to the classname
                    -->
                    <sequencer name="java-source-sequencer" classname="org.modeshape.sequencer.javafile.JavaFileSequencer"
                               module="org.modeshape.sequencer.java">
                        <path-expression>/files//(*.java[*])/jcr:content[@jcr:data] => /derived/java</path-expression>
                    </sequencer>
                    <sequencer name="java-class-sequencer" classname="org.modeshape.sequencer.classfile.ClassFileSequencer"
                               module="org.modeshape.sequencer.java">
                        <path-expression>/files//(*.class[*])/jcr:content[@jcr:data] => /derived/class</path-expression>
                    </sequencer>
                    <sequencer name="cnd-sequencer" classname="cnd" module="org.modeshape">
                        <path-expression>default:/files(//*.cnd[*])/jcr:content[@jcr:data] => /derived/cnd/$1</path-expression>
                    </sequencer>
                    <sequencer name="msoffice-sequencer" classname="msoffice" module="org.modeshape.sequencer.msoffice">
                        <path-expression>/files(//*.(xls|ppt|doc)[*])/jcr:content[@jcr:data] => /derived/msoffice/$1</path-expression>
                    </sequencer>
                    <sequencer name="teiid-model-sequencer" classname="model" module="org.modeshape.sequencer.teiid">
                        <path-expression>/files(//*.xmi[*])/jcr:content[@jcr:data] => /derived/teiid/models/$1</path-expression>
                    </sequencer>
                    <sequencer name="teiid-vdb-sequencer" classname="vdb" module="org.modeshape.sequencer.teiid">
                        <path-expression>/files(//*.vdb[*])/jcr:content[@jcr:data] => /derived/teiid/vdbs/$1</path-expression>
                    </sequencer>
                    <!--
                     The XSD, XML, WSDL, and ZIP sequencers all generate a node for the input documents, and so we don't want the filename to
                     be included in the output path. Therefore, only the relative path under '/files' and above '*.xsd' (or '*.wsdl'
                     or '*.xml') is captured in the input path. -->
                    <sequencer name="xsd-sequencer" classname="xsd" module="org.modeshape.sequencer.xsd">
                        <path-expression>/files(//*).xsd[*]/jcr:content[@jcr:data] => /derived/xsd/$1</path-expression>
                    </sequencer>
                    <sequencer name="wsdl-sequencer" classname="wsdl" module="org.modeshape.sequencer.wsdl">
                        <path-expression>/files(//)*.wsdl[*]/jcr:content[@jcr:data] => /derived/wsdl/$1</path-expression>
                    </sequencer>
                    <sequencer name="xml-sequencer" classname="xml" module="org.modeshape.sequencer.xml">
                        <path-expression>/files(//)*.xml[*]/jcr:content[@jcr:data] => /derived/xml/$1</path-expression>
                    </sequencer>
                    <sequencer name="zip-sequencer" classname="zip" module="org.modeshape.sequencer.zip">
                        <path-expression>/files(//*.zip[*])/jcr:content[@jcr:data] => /derived/zip/$1</path-expression>
                    </sequencer>
                    <sequencer name="image-sequencer" classname="image" module="org.modeshape.sequencer.image">
                        <path-expression>/files(//*.(png|jpg|gif)[*])/jcr:content[@jcr:data] => /derived/image/$1</path-expression>
                    </sequencer>
                    <sequencer name="mp3-sequencer" classname="mp3" module="org.modeshape.sequencer.mp3">
                        <path-expression>/files(//*.mp3[*])/jcr:content[@jcr:data] => /derived/mp3/$1</path-expression>
                    </sequencer>
                </sequencers>
                <text-extractors>
                    <text-extractor name="tika-extractor" classname="tika" module="org.modeshape.extractor.tika"/>
                </text-extractors>
            </repository>
            <!--These should be deployed after the repositories, because they use servlet context listeners to load all repositories-->
            <webapp name="modeshape-explorer.war"/>
            <webapp name="modeshape-cmis.war"/>
        </subsystem>
        <subsystem xmlns="urn:jboss:domain:jaxrs:1.0"/>
        <subsystem xmlns="urn:jboss:domain:jca:2.0">
            <archive-validation enabled="true" fail-on-error="true" fail-on-warn="false"/>
            <bean-validation enabled="true"/>
            <default-workmanager>
                <short-running-threads>
                    <core-threads count="50"/>
                    <queue-length count="50"/>
                    <max-threads count="50"/>
                    <keepalive-time time="10" unit="seconds"/>
                </short-running-threads>
                <long-running-threads>
                    <core-threads count="50"/>
                    <queue-length count="50"/>
                    <max-threads count="50"/>
                    <keepalive-time time="10" unit="seconds"/>
                </long-running-threads>
            </default-workmanager>
            <cached-connection-manager/>
        </subsystem>
        <subsystem xmlns="urn:jboss:domain:jdr:1.0"/>
        <subsystem xmlns="urn:jboss:domain:jgroups:2.0" default-stack="udp">
            <stack name="udp">
                <transport type="UDP" socket-binding="jgroups-udp"/>
                <protocol type="PING"/>
                <protocol type="MERGE3"/>
                <protocol type="FD_SOCK" socket-binding="jgroups-udp-fd"/>
                <protocol type="FD_ALL"/>
                <protocol type="VERIFY_SUSPECT"/>
                <protocol type="pbcast.NAKACK2"/>
                <protocol type="UNICAST3"/>
                <protocol type="pbcast.STABLE"/>
                <protocol type="pbcast.GMS"/>
                <protocol type="UFC"/>
                <protocol type="MFC"/>
                <protocol type="FRAG2"/>
                <protocol type="RSVP"/>
            </stack>
            <stack name="tcp">
                <transport type="TCP" socket-binding="jgroups-tcp"/>
                <protocol type="MPING" socket-binding="jgroups-mping"/>
                <protocol type="MERGE2"/>
                <protocol type="FD_SOCK" socket-binding="jgroups-tcp-fd"/>
                <protocol type="FD"/>
                <protocol type="VERIFY_SUSPECT"/>
                <protocol type="pbcast.NAKACK2"/>
                <protocol type="UNICAST3"/>
                <protocol type="pbcast.STABLE"/>
                <protocol type="pbcast.GMS"/>
                <protocol type="MFC"/>
                <protocol type="FRAG2"/>
                <protocol type="RSVP"/>
            </stack>
        </subsystem>
        <subsystem xmlns="urn:jboss:domain:jmx:1.3">
            <expose-resolved-model/>
            <expose-expression-model/>
            <remoting-connector/>
        </subsystem>
        <subsystem xmlns="urn:jboss:domain:jpa:1.1">
            <jpa default-datasource="" default-extended-persistence-inheritance="DEEP"/>
        </subsystem>
        <subsystem xmlns="urn:jboss:domain:jsf:1.0"/>
        <subsystem xmlns="urn:jboss:domain:mail:2.0">
            <mail-session name="default" jndi-name="java:jboss/mail/Default">
                <smtp-server outbound-socket-binding-ref="mail-smtp"/>
            </mail-session>
        </subsystem>
        <subsystem xmlns="urn:jboss:domain:modcluster:1.2">
            <mod-cluster-config advertise-socket="modcluster" connector="ajp">
                <dynamic-load-provider>
                    <load-metric type="busyness"/>
                </dynamic-load-provider>
            </mod-cluster-config>
        </subsystem>
        <subsystem xmlns="urn:jboss:domain:naming:2.0">
            <remote-naming/>
        </subsystem>
        <subsystem xmlns="urn:jboss:domain:pojo:1.0"/>
        <subsystem xmlns="urn:jboss:domain:remoting:2.0">
            <http-connector name="http-remoting-connector" connector-ref="default" security-realm="ApplicationRealm"/>
        </subsystem>
        <subsystem xmlns="urn:jboss:domain:resource-adapters:2.0"/>
        <subsystem xmlns="urn:jboss:domain:sar:1.0"/>
        <subsystem xmlns="urn:jboss:domain:security:1.2">
            <security-domains>
                <security-domain name="other" cache-type="default">
                    <authentication>
                        <login-module code="Remoting" flag="optional">
                            <module-option name="password-stacking" value="useFirstPass"/>
                        </login-module>
                        <login-module code="RealmDirect" flag="required">
                            <module-option name="password-stacking" value="useFirstPass"/>
                        </login-module>
                    </authentication>
                </security-domain>
                <security-domain name="jboss-web-policy" cache-type="default">
                    <authorization>
                        <policy-module code="Delegating" flag="required"/>
                    </authorization>
                </security-domain>
                <security-domain name="jboss-ejb-policy" cache-type="default">
                    <authorization>
                        <policy-module code="Delegating" flag="required"/>
                    </authorization>
                </security-domain>
                <security-domain name="modeshape-security" cache-type="default">
                    <authentication>
                        <login-module code="RealmDirect" flag="required">
                            <module-option name="password-stacking" value="useFirstPass"/>
                        </login-module>
                    </authentication>
                </security-domain>
            </security-domains>
        </subsystem>
        <subsystem xmlns="urn:jboss:domain:threads:1.1"/>
        <subsystem xmlns="urn:jboss:domain:transactions:2.0">
            <core-environment>
                <process-id>
                    <uuid/>
                </process-id>
            </core-environment>
            <recovery-environment socket-binding="txn-recovery-environment" status-socket-binding="txn-status-manager"/>
            <coordinator-environment default-timeout="300"/>
        </subsystem>
        <subsystem xmlns="urn:jboss:domain:undertow:1.0">
            <buffer-caches>
                <buffer-cache name="default" buffer-size="1024" buffers-per-region="1024" max-regions="10"/>
            </buffer-caches>
            <server name="default-server">
                <http-listener name="default" socket-binding="http"/>
                <ajp-listener name="ajp" socket-binding="ajp"/>
                <host name="default-host" alias="localhost">
                    <location name="/" handler="welcome-content"/>
                </host>
            </server>
            <servlet-container name="default" default-buffer-cache="default" stack-trace-on-error="local-only">
                <jsp-config/>
                <persistent-sessions/>
            </servlet-container>
            <handlers>
                <file name="welcome-content" path="${jboss.home.dir}/welcome-content" directory-listing="true"/>
            </handlers>
        </subsystem>
        <subsystem xmlns="urn:jboss:domain:webservices:1.2">
            <modify-wsdl-address>true</modify-wsdl-address>
            <wsdl-host>${jboss.bind.address:127.0.0.1}</wsdl-host>
            <endpoint-config name="Standard-Endpoint-Config"/>
            <endpoint-config name="Recording-Endpoint-Config">
                <pre-handler-chain name="recording-handlers" protocol-bindings="##SOAP11_HTTP ##SOAP11_HTTP_MTOM ##SOAP12_HTTP ##SOAP12_HTTP_MTOM">
                    <handler name="RecordingHandler" class="org.jboss.ws.common.invocation.RecordingServerHandler"/>
                </pre-handler-chain>
            </endpoint-config>
            <client-config name="Standard-Client-Config"/>
        </subsystem>
        <subsystem xmlns="urn:jboss:domain:weld:2.0"/>
    </profile>
    <interfaces>
        <interface name="management">
            <inet-address value="${jboss.bind.address.management:127.0.0.1}"/>
        </interface>
        <interface name="public">
            <inet-address value="${jboss.bind.address:127.0.0.1}"/>
        </interface>
        <!-- TODO - only show this if the jacorb subsystem is added  -->
        <interface name="unsecure">
            <!--
              ~  Used for IIOP sockets in the standard configuration.
              ~                  To secure JacORB you need to setup SSL
              -->
            <inet-address value="${jboss.bind.address.unsecure:127.0.0.1}"/>
        </interface>
    </interfaces>
    <socket-binding-group name="standard-sockets" default-interface="public" port-offset="${jboss.socket.binding.port-offset:0}">
        <socket-binding name="management-native" interface="management" port="${jboss.management.native.port:9999}"/>
        <socket-binding name="management-http" interface="management" port="${jboss.management.http.port:9990}"/>
        <socket-binding name="management-https" interface="management" port="${jboss.management.https.port:9993}"/>
        <socket-binding name="ajp" port="${jboss.ajp.port:8009}"/>
        <socket-binding name="http" port="${jboss.http.port:8080}"/>
        <socket-binding name="https" port="${jboss.https.port:8443}"/>
        <socket-binding name="jgroups-mping" port="0" multicast-address="${jboss.default.multicast.address:230.0.0.4}" multicast-port="45700"/>
        <socket-binding name="jgroups-tcp" port="7600"/>
        <socket-binding name="jgroups-tcp-fd" port="57600"/>
        <socket-binding name="jgroups-udp" port="55200" multicast-address="${jboss.default.multicast.address:230.0.0.4}" multicast-port="45688"/>
        <socket-binding name="jgroups-udp-fd" port="54200"/>
        <socket-binding name="modcluster" port="0" multicast-address="224.0.1.105" multicast-port="23364"/>
        <socket-binding name="txn-recovery-environment" port="4712"/>
        <socket-binding name="txn-status-manager" port="4713"/>
        <outbound-socket-binding name="mail-smtp">
            <remote-destination host="localhost" port="25"/>
        </outbound-socket-binding>
    </socket-binding-group>
</server>


text:
package org.apache.aries.util;

import org.apache.aries.util.internal.DefaultWorker;
import org.apache.aries.util.internal.EquinoxWorker;
import org.apache.aries.util.internal.FelixWorker;
import org.apache.aries.util.internal.FrameworkUtilWorker;
import org.apache.aries.util.internal.R43Worker;
import org.osgi.framework.Bundle;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceRegistration;

public final class AriesFrameworkUtil
{
  private static FrameworkUtilWorker worker;

  static {
    try {
      worker = new R43Worker();
    } catch (Throwable e) {
    }
    Bundle b = FrameworkUtil.getBundle(AriesFrameworkUtil.class);
    String bundleClassName = b == null? "": b.getClass().getName();
    if (worker == null && isEquinox(bundleClassName)) {
      worker = new EquinoxWorker();
    } else if (worker == null && bundleClassName.startsWith("org.apache.felix")) {
      worker = new FelixWorker();
    }

    if (worker == null || !!!worker.isValid()) worker = new DefaultWorker();
  }

  /**
   * This method attempts to get the classloader for a bundle. It may return null if
   * their is no such classloader, or if it cannot obtain the classloader for the bundle.
   *
   * @param b the bundle whose classloader is desired.
   * @return  the classloader if found, or null if for example the bundle is in INSTALLED or UNINSTALLED state
   */
  public static ClassLoader getClassLoader(Bundle b)
  {
    if (b != null && b.getState() != Bundle.UNINSTALLED && b.getState() != Bundle.INSTALLED) {
      return worker.getClassLoader(b);
    } else {
      return null;
    }
  }

  /**
   * Returns true if we are in equinox, and we can access the interfaces we need.
   * @param bundleClassName the class name of the bundle implementation.
   * @return true if we are in equinox, false otherwise.
   */
  private static boolean isEquinox(String bundleClassName)
  {
    if (bundleClassName.startsWith("org.eclipse.osgi")) {
      try {
        Class.forName("org.eclipse.osgi.framework.internal.core.BundleHost");
        return true;
      } catch (ClassNotFoundException e) {
      }
    }
    return false;
  }

  /**
   * This method attempts to get the classloader for a bundle. It will force the creation
   * of a classloader, so if no classloader exists. If the bundle is in installed state, but
   * cannot be resolved the null will be returned.
   *
   * @param b the bundle to get a classloader for
   * @return  the classloader.
   */
  public static ClassLoader getClassLoaderForced(Bundle b)
  {
    if (b == null)
      return null;
    try {
      b.loadClass("java.lang.Object");
    } catch (ClassNotFoundException e) {
    }
    return worker.getClassLoader(b);
  }

  /**
   * Safely unregister the supplied ServiceRegistration, for when you don't
   * care about the potential IllegalStateException and don't want
   * it to run wild through your code
   *
   * @param reg The {@link ServiceRegistration}, may be null
   */
  public static void safeUnregisterService(ServiceRegistration reg)
  {
    if(reg != null) {
      try {
        reg.unregister();
      } catch (IllegalStateException e) {
        //This can be safely ignored
      }
    }
  }
}


text:
extern "C" {
#endif

void uart_init();
void uart_putc( uint8_t c );
//void uart_puts( const char *str );
void uart_puts( const char *str );
void uart_print( const char *format, ... );
uint8_t uart_getc();

#ifdef __cplusplus
}
#endif

#endif // MACHINA_UART_HH


text:
#ifndef __LUCENE_INDEX_FIELDS_WRITER__
#define __LUCENE_INDEX_FIELDS_WRITER__

#import  <Foundation/Foundation.h>
#import  "LCFieldInfos.h"

#define LCFieldsWriter_FIELD_IS_TOKENIZED 0x1
#define LCFieldsWriter_FIELD_IS_BINARY 0x2
#define LCFieldsWriter_FIELD_IS_COMPRESSED 0x4

@class LCIndexOutput;

@interface LCFieldsWriter: NSObject
{
	LCFieldInfos *fieldInfos;
	LCIndexOutput *fieldsStream;
	LCIndexOutput *indexStream;
}

- (id) initWithDirectory: (id <LCDirectory>) d
				 segment: (NSString *) segment
			  fieldInfos: (LCFieldInfos *) fn;
- (void) close;
- (void) addDocument: (LCDocument *) doc;
@end

#endif /* __LUCENE_INDEX_FIELDS_WRITER__ */