text:
"""
EasyBuild support for Quantum ESPRESSO, implemented as an easyblock

@author: Kenneth Hoste (Ghent University)
"""
import fileinput
import os
import re
import shutil
import sys
from distutils.version import LooseVersion

import easybuild.tools.environment as env
import easybuild.tools.toolchain as toolchain
from easybuild.easyblocks.generic.configuremake import ConfigureMake
from easybuild.framework.easyconfig import CUSTOM
from easybuild.tools.build_log import EasyBuildError
from easybuild.tools.modules import get_software_root

class EB_QuantumESPRESSO(ConfigureMake):
    """Support for building and installing Quantum ESPRESSO."""

    @staticmethod
    def extra_options():
        """Custom easyconfig parameters for Quantum ESPRESSO."""
        extra_vars = {
            'hybrid': [False, "Enable hybrid build (with OpenMP)", CUSTOM],
            'with_scalapack': [True, "Enable ScaLAPACK support", CUSTOM],
        }
        return ConfigureMake.extra_options(extra_vars)

    def __init__(self, *args, **kwargs):
        """Add extra config options specific to Quantum ESPRESSO."""
        super(EB_QuantumESPRESSO, self).__init__(*args, **kwargs)

        self.build_in_installdir = True

        self.install_subdir = "espresso-%s" % self.version

    def patch_step(self):
        """Patch files from build dir (not start dir)."""
        super(EB_QuantumESPRESSO, self).patch_step(beginpath=self.builddir)

    def configure_step(self):
        """Custom configuration procedure for Quantum ESPRESSO."""

        if self.cfg['hybrid']:
            self.cfg.update('configopts', '--enable-openmp')

        if not self.toolchain.options.get('usempi', None):
            self.cfg.update('configopts', '--disable-parallel')

        if not self.cfg['with_scalapack']:
            self.cfg.update('configopts', '--without-scalapack')

        repls = []

        if self.toolchain.comp_family() in [toolchain.INTELCOMP]:
            # set preprocessor command (-E to stop after preprocessing, -C to preserve comments)
            cpp = "%s -E -C" % os.getenv('CC')
            repls.append(('CPP', cpp, False))
            env.setvar('CPP', cpp)

        super(EB_QuantumESPRESSO, self).configure_step()

        # compose list of DFLAGS (flag, value, keep_stuff)
        # for guidelines, see include/defs.h.README in sources
        dflags = []

        comp_fam_dflags = {
            toolchain.INTELCOMP: '-D__INTEL',
            toolchain.GCC: '-D__GFORTRAN -D__STD_F95',
        }
        dflags.append(comp_fam_dflags[self.toolchain.comp_family()])

        libfft = os.getenv('LIBFFT')
        if libfft:
            if "fftw3" in libfft:
                dflags.append('-D__FFTW3')
            else:
                dflags.append('-D__FFTW')
            env.setvar('FFTW_LIBS', libfft)

        if get_software_root('ACML'):
            dflags.append('-D__ACML')

        if self.toolchain.options.get('usempi', None):
            dflags.append('-D__MPI -D__PARA')

        if self.cfg['hybrid']:
            dflags.append(" -D__OPENMP")

        if self.cfg['with_scalapack']:
            dflags.append(" -D__SCALAPACK")

        # always include -w to supress warnings
        dflags.append('-w')

        repls.append(('DFLAGS', ' '.join(dflags), False))

        # complete C/Fortran compiler and LD flags
        if self.cfg['hybrid']:
            repls.append(('LDFLAGS', self.toolchain.get_flag('openmp'), True))
            repls.append(('(?:C|F90|F)FLAGS', self.toolchain.get_flag('openmp'), True))

        # obtain library settings
        libs = []
        for lib in ['BLAS', 'LAPACK', 'FFT', 'SCALAPACK']:
            val = os.getenv('LIB%s' % lib)
            repls.append(('%s_LIBS' % lib, val, False))
            libs.append(val)
        libs = ' '.join(libs)

        repls.append(('BLAS_LIBS_SWITCH', 'external', False))
        repls.append(('LAPACK_LIBS_SWITCH', 'external', False))
        repls.append(('LD_LIBS', os.getenv('LIBS'), False))

        self.log.debug("List of replacements to perform: %s" % repls)

        # patch make.sys file
        fn = os.path.join(self.cfg['start_dir'], 'make.sys')
        try:
            for line in fileinput.input(fn, inplace=1, backup='.orig.eb'):
                for (k, v, keep) in repls:
                    # need to use [ \t]* instead of \s*, because vars may be undefined as empty,
                    # and we don't want to include newlines
                    if keep:
                        line = re.sub(r"^(%s\s*=[ \t]*)(.*)$" % k, r"\1\2 %s" % v, line)
                    else:
                        line = re.sub(r"^(%s\s*=[ \t]*).*$" % k, r"\1%s" % v, line)

                    # fix preprocessing directives for .f90 files in make.sys if required
                if self.toolchain.comp_family() in [toolchain.GCC]:
                    line = re.sub("\$\(MPIF90\) \$\(F90FLAGS\) -c \$<",
                                  "$(CPP) -C $(CPPFLAGS) $< -o $*.F90\n" +
                                  "\t$(MPIF90) $(F90FLAGS) -c $*.F90 -o $*.o",
                                  line)

                sys.stdout.write(line)
        except IOError, err:
            raise EasyBuildError("Failed to patch %s: %s", fn, err)

        self.log.debug("Contents of patched %s: %s" % (fn, open(fn, "r").read()))

        # patch default make.sys for wannier
        if LooseVersion(self.version) >= LooseVersion("5"):
            fn = os.path.join(self.cfg['start_dir'], 'install', 'make_wannier90.sys')
        else:
            fn = os.path.join(self.cfg['start_dir'], 'plugins', 'install', 'make_wannier90.sys')
        try:
            for line in fileinput.input(fn, inplace=1, backup='.orig.eb'):
                line = re.sub(r"^(LIBS\s*=\s*).*", r"\1%s" % libs, line)

                sys.stdout.write(line)

        except IOError, err:
            raise EasyBuildError("Failed to patch %s: %s", fn, err)

        self.log.debug("Contents of patched %s: %s" % (fn, open(fn, "r").read()))

        # patch Makefile of want plugin
        wantprefix = 'want-'
        wantdirs = [d for d in os.listdir(self.builddir) if d.startswith(wantprefix)]

        if len(wantdirs) > 1:
            raise EasyBuildError("Found more than one directory with %s prefix, help!", wantprefix)

        if len(wantdirs) != 0:
            fn = os.path.join(self.builddir, wantdirs[0], 'conf', 'make.sys.in')
            try:
                for line in fileinput.input(fn, inplace=1, backup='.orig.eb'):
                    # fix preprocessing directives for .f90 files in make.sys if required
                    if self.toolchain.comp_family() in [toolchain.GCC]:
                        line = re.sub("@f90rule@",
                                      "$(CPP) -C $(CPPFLAGS) $< -o $*.F90\n" +
                                      "\t$(MPIF90) $(F90FLAGS) -c $*.F90 -o $*.o",
                                      line)

                    sys.stdout.write(line)
            except IOError, err:
                raise EasyBuildError("Failed to patch %s: %s", fn, err)

        # move non-espresso directories to where they're expected and create symlinks
        try:
            dirnames = [d for d in os.listdir(self.builddir) if not d.startswith('espresso')]
            targetdir = os.path.join(self.builddir, "espresso-%s" % self.version)
            for dirname in dirnames:
                shutil.move(os.path.join(self.builddir, dirname), os.path.join(targetdir, dirname))
                self.log.info("Moved %s into %s" % (dirname, targetdir))

                dirname_head = dirname.split('-')[0]
                linkname = None
                if dirname_head == 'sax':
                    linkname = 'SaX'
                if dirname_head == 'wannier90':
                    linkname = 'W90'
                elif dirname_head in ['gipaw', 'plumed', 'want', 'yambo']:
                    linkname = dirname_head.upper()
                if linkname:
                    os.symlink(os.path.join(targetdir, dirname), os.path.join(targetdir, linkname))

        except OSError, err:
            raise EasyBuildError("Failed to move non-espresso directories: %s", err)

    def install_step(self):
        """Skip install step, since we're building in the install directory."""
        pass

    def sanity_check_step(self):
        """Custom sanity check for Quantum ESPRESSO."""

        # build list of expected binaries based on make targets
        bins = ["iotk", "iotk.x", "iotk_print_kinds.x"]

        if 'cp' in self.cfg['buildopts'] or 'all' in self.cfg['buildopts']:
            bins.extend(["cp.x", "cppp.x", "wfdd.x"])

        if 'gww' in self.cfg['buildopts']:  # only for v4.x, not in v5.0 anymore
            bins.extend(["gww_fit.x", "gww.x", "head.x", "pw4gww.x"])

        if 'ld1' in self.cfg['buildopts'] or 'all' in self.cfg['buildopts']:
            bins.extend(["ld1.x"])

        if 'gipaw' in self.cfg['buildopts']:
            bins.extend(["gipaw.x"])

        if 'neb' in self.cfg['buildopts'] or 'pwall' in self.cfg['buildopts'] or \
           'all' in self.cfg['buildopts']:
            if LooseVersion(self.version) > LooseVersion("5"):
                bins.extend(["neb.x", "path_interpolation.x"])

        if 'ph' in self.cfg['buildopts'] or 'all' in self.cfg['buildopts']:
            bins.extend(["d3.x", "dynmat.x", "lambda.x", "matdyn.x", "ph.x", "phcg.x", "q2r.x"])
            if LooseVersion(self.version) > LooseVersion("5"):
                bins.extend(["fqha.x", "q2qstar.x"])

        if 'pp' in self.cfg['buildopts'] or 'pwall' in self.cfg['buildopts'] or \
           'all' in self.cfg['buildopts']:
            bins.extend(["average.x", "bands.x", "dos.x", "epsilon.x", "initial_state.x",
                         "plan_avg.x", "plotband.x", "plotproj.x", "plotrho.x", "pmw.x", "pp.x",
                         "projwfc.x", "sumpdos.x", "pw2wannier90.x", "pw_export.x", "pw2gw.x",
                         "wannier_ham.x", "wannier_plot.x"])
            if LooseVersion(self.version) > LooseVersion("5"):
                bins.extend(["pw2bgw.x", "bgw2pw.x"])
            else:
                bins.extend(["pw2casino.x"])

        if 'pw' in self.cfg['buildopts'] or 'all' in self.cfg['buildopts']:
            bins.extend(["band_plot.x", "dist.x", "ev.x", "kpoints.x", "pw.x", "pwi2xsf.x",
                         "bands_FS.x", "kvecs_FS.x"])
            if LooseVersion(self.version) > LooseVersion("5"):
                bins.extend(["generate_vdW_kernel_table.x"])
            else:
                bins.extend(["path_int.x"])

        if 'pwcond' in self.cfg['buildopts'] or 'pwall' in self.cfg['buildopts'] or \
           'all' in self.cfg['buildopts']:
            bins.extend(["pwcond.x"])

        if 'tddfpt' in self.cfg['buildopts'] or 'all' in self.cfg['buildopts']:
            if LooseVersion(self.version) > LooseVersion("5"):
                bins.extend(["turbo_lanczos.x", "turbo_spectrum.x"])

        upftools = []
        if 'upf' in self.cfg['buildopts'] or 'all' in self.cfg['buildopts']:
            upftools = ["casino2upf.x", "cpmd2upf.x", "fhi2upf.x", "fpmd2upf.x", "ncpp2upf.x",
                        "oldcp2upf.x", "read_upf_tofile.x", "rrkj2upf.x", "uspp2upf.x", "vdb2upf.x",
                        "virtual.x"]
            if LooseVersion(self.version) > LooseVersion("5"):
                upftools.extend(["interpolate.x", "upf2casino.x"])

        if 'vdw' in self.cfg['buildopts']:  # only for v4.x, not in v5.0 anymore
            bins.extend(["vdw.x"])

        if 'w90' in self.cfg['buildopts']:
            bins.extend(["wannier90.x"])

        want_bins = []
        if 'want' in self.cfg['buildopts']:
            want_bins = ["bands.x", "blc2wan.x", "conductor.x", "current.x", "disentangle.x",
                         "dos.x", "gcube2plt.x", "kgrid.x", "midpoint.x", "plot.x", "sumpdos",
                         "wannier.x", "wfk2etsf.x"]
            if LooseVersion(self.version) > LooseVersion("5"):
                want_bins.extend(["cmplx_bands.x", "decay.x", "sax2qexml.x", "sum_sgm.x"])

        if 'xspectra' in self.cfg['buildopts']:
            bins.extend(["xspectra.x"])

        yambo_bins = []
        if 'yambo' in self.cfg['buildopts']:
            yambo_bins = ["a2y", "p2y", "yambo", "ypp"]

        pref = self.install_subdir

        custom_paths = {
                        'files': [os.path.join(pref, 'bin', x) for x in bins] +
                                 [os.path.join(pref, 'upftools', x) for x in upftools] +
                                 [os.path.join(pref, 'WANT', 'bin', x) for x in want_bins] +
                                 [os.path.join(pref, 'YAMBO', 'bin', x) for x in yambo_bins],
                        'dirs': [os.path.join(pref, 'include')]
                       }

        super(EB_QuantumESPRESSO, self).sanity_check_step(custom_paths=custom_paths)

    def make_module_req_guess(self):
        """Custom path suggestions for Quantum ESPRESSO."""

        guesses = super(EB_QuantumESPRESSO, self).make_module_req_guess()

        guesses.update({
                        'PATH': [os.path.join(self.install_subdir, x) for x in ['bin', 'upftools',
                                                                                'WANT/bin',
                                                                                'YAMBO/bin']],
                        'CPATH': [os.path.join(self.install_subdir, 'include')],
                       })

        return guesses


text:
$Pref::WorldEditor::FileSpec = "Torque Mission Files (*.mis)|*.mis|All Files (*.*)|*.*|";

//////////////////////////////////////////////////////////////////////////
// File Menu Handlers
//////////////////////////////////////////////////////////////////////////

function EditorFileMenu::onMenuSelect(%this) {
	// don't do this since it won't exist if this is a "demo"
	if(!isWebDemo())
		%this.enableItem(2, EditorIsDirty());
}

//////////////////////////////////////////////////////////////////////////

// Package that gets temporarily activated to toggle editor after mission loading.
// Deactivates itself.
package BootEditor {

	function GameConnection::initialControlSet( %this ) {
		Parent::initialControlSet( %this );
		toggleEditor( true );
		deactivatePackage( "BootEditor" );
	}

};

//////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////
// View Menu Handlers
//////////////////////////////////////////////////////////////////////////

function EditorViewMenu::onMenuSelect( %this ) {
	%this.checkItem( 1, EWorldEditor.renderOrthoGrid );
}

//////////////////////////////////////////////////////////////////////////
// Edit Menu Handlers
//////////////////////////////////////////////////////////////////////////

function EditorEditMenu::onMenuSelect( %this ) {
	// UndoManager is in charge of enabling or disabling the undo/redo items.
	Editor.getUndoManager().updateUndoMenu(  );

	// SICKHEAD: It a perfect world we would abstract
	// cut/copy/paste with a generic selection object
	// which would know how to process itself.

	// Give the active editor a chance at fixing up
	// the state of the edit menu.
	// Do we really need this check here?
	if ( isObject( Lab.currentEditor ) )
		Lab.currentEditor.onEditMenuSelect( %this );
}

//////////////////////////////////////////////////////////////////////////

function EditorMenuEditDelete() {
	if ( isObject( Lab.currentEditor ) )
		Lab.currentEditor.handleDelete();
}

function EditorMenuEditDeselect() {
	if ( isObject( Lab.currentEditor ) )
		Lab.currentEditor.handleDeselect();
}

function EditorMenuEditCut() {
	if ( isObject( Lab.currentEditor ) )
		Lab.currentEditor.handleCut();
}

function EditorMenuEditCopy() {
	if ( isObject( Lab.currentEditor ) )
		Lab.currentEditor.handleCopy();
}

function EditorMenuEditPaste() {
	if ( isObject( Lab.currentEditor ) )
		Lab.currentEditor.handlePaste();
}

//////////////////////////////////////////////////////////////////////////
// Window Menu Handler
//////////////////////////////////////////////////////////////////////////

function EditorToolsMenu::onSelectItem(%this, %id) {
	%toolName = getField( %this.item[%id], 2 );
	EditorGui.setEditor(%toolName, %paletteName  );
	%this.checkRadioItem(0, %this.getItemCount(), %id);
	return true;
}

function EditorToolsMenu::setupDefaultState(%this) {
	Parent::setupDefaultState(%this);
}

//////////////////////////////////////////////////////////////////////////
// Camera Menu Handler
//////////////////////////////////////////////////////////////////////////

function EditorCameraMenu::onSelectItem(%this, %id, %text) {
	if(%id == 0 || %id == 1) {
		// Handle the Free Camera/Orbit Camera toggle
		%this.checkRadioItem(0, 1, %id);
	}

	return Parent::onSelectItem(%this, %id, %text);
}

function EditorCameraMenu::setupDefaultState(%this) {
	// Set the Free Camera/Orbit Camera check marks
	%this.checkRadioItem(0, 1, 0);
	Parent::setupDefaultState(%this);
}

function EditorFreeCameraTypeMenu::onSelectItem(%this, %id, %text) {
	// Handle the camera type radio
	%this.checkRadioItem(0, 2, %id);
	return Parent::onSelectItem(%this, %id, %text);
}

function EditorFreeCameraTypeMenu::setupDefaultState(%this) {
	// Set the camera type check marks
	%this.checkRadioItem(0, 2, 0);
	Parent::setupDefaultState(%this);
}

function EditorCameraSpeedMenu::onSelectItem(%this, %id, %text) {
	// Grab and set speed
	%speed = getField( %this.item[%id], 2 );
	$Camera::movementSpeed = %speed;
	// Update Editor
	%this.checkRadioItem(0, 6, %id);
	// Update Toolbar TextEdit
	EWorldEditorCameraSpeed.setText( $Camera::movementSpeed );
	// Update Toolbar Slider
	CameraSpeedDropdownCtrlContainer-->Slider.setValue( $Camera::movementSpeed );
	return true;
}
function EditorCameraSpeedMenu::setupDefaultState(%this) {
	// Setup camera speed gui's. Both menu and editorgui
	%this.setupGuiControls();
	//Grab and set speed
	%defaultSpeed =  Lab.levelsDirectory @ Lab.levelName @ "/cameraSpeed";

	if( %defaultSpeed $= "" ) {
		// Update Editor with default speed
		%defaultSpeed = 25;
	}

	$Camera::movementSpeed = %defaultSpeed;
	// Update Toolbar TextEdit
	EWorldEditorCameraSpeed.setText( %defaultSpeed );
	// Update Toolbar Slider
	CameraSpeedDropdownCtrlContainer-->Slider.setValue( %defaultSpeed );
	Parent::setupDefaultState(%this);
}

function EditorCameraSpeedMenu::setupGuiControls(%this) {
	// Default levelInfo params
	%minSpeed = 5;
	%maxSpeed = 200;
	%speedA =  Lab.levelsDirectory @ Lab.levelName @ "/cameraSpeedMin";
	%speedB =  Lab.levelsDirectory @ Lab.levelName @ "/cameraSpeedMax";

	if( %speedA < %speedB ) {
		if( %speedA == 0 ) {
			if( %speedB > 1 )
				%minSpeed = 1;
			else
				%minSpeed = 0.1;
		} else {
			%minSpeed = %speedA;
		}

		%maxSpeed = %speedB;
	}

	// Set up the camera speed items
	%inc = ( (%maxSpeed - %minSpeed) / (%this.getItemCount() - 1) );

	for( %i = 0; %i < %this.getItemCount(); %i++)
		%this.item[%i] = setField( %this.item[%i], 2, (%minSpeed + (%inc * %i)));

	// Set up min/max camera slider range
	eval("CameraSpeedDropdownCtrlContainer-->Slider.range = \"" @ %minSpeed @ " " @ %maxSpeed @ "\";");
}
//////////////////////////////////////////////////////////////////////////
// World Menu Handler Object Menu
//////////////////////////////////////////////////////////////////////////

function EditorWorldMenu::onMenuSelect(%this) {
	%selSize = EWorldEditor.getSelectionSize();
	%lockCount = EWorldEditor.getSelectionLockCount();
	%hideCount = EWorldEditor.getSelectionHiddenCount();
	%this.enableItem(0, %lockCount < %selSize);  // Lock Selection
	%this.enableItem(1, %lockCount > 0);  // Unlock Selection
	%this.enableItem(3, %hideCount < %selSize);  // Hide Selection
	%this.enableItem(4, %hideCount > 0);  // Show Selection
	%this.enableItem(6, %selSize > 1 && %lockCount == 0);  // Align bounds
	%this.enableItem(7, %selSize > 1 && %lockCount == 0);  // Align center
	%this.enableItem(9, %selSize > 0 && %lockCount == 0);  // Reset Transforms
	%this.enableItem(10, %selSize > 0 && %lockCount == 0);  // Reset Selected Rotation
	%this.enableItem(11, %selSize > 0 && %lockCount == 0);  // Reset Selected Scale
	%this.enableItem(12, %selSize > 0 && %lockCount == 0);  // Transform Selection
	%this.enableItem(14, %selSize > 0 && %lockCount == 0);  // Drop Selection
	%this.enableItem(17, %selSize > 0); // Make Prefab
	%this.enableItem(18, %selSize > 0); // Explode Prefab
	%this.enableItem(20, %selSize > 1); // Mount
	%this.enableItem(21, %selSize > 0); // Unmount
}

//////////////////////////////////////////////////////////////////////////

function EditorDropTypeMenu::onSelectItem(%this, %id, %text) {
	// This sets up which drop script function to use when
	// a drop type is selected in the menu.
	EWorldEditor.dropType = getField(%this.item[%id], 2);
	%this.checkRadioItem(0, (%this.getItemCount() - 1), %id);
	return true;
}

function EditorDropTypeMenu::setupDefaultState(%this) {
	// Check the radio item for the currently set drop type.
	%numItems = %this.getItemCount();
	%dropTypeIndex = 0;

	for( ; %dropTypeIndex < %numItems; %dropTypeIndex ++ )
		if( getField( %this.item[ %dropTypeIndex ], 2 ) $= EWorldEditor.dropType )
			break;

	// Default to screenCenter if we didn't match anything.
	if( %dropTypeIndex > (%numItems - 1) )
		%dropTypeIndex = 4;

	%this.checkRadioItem( 0, (%numItems - 1), %dropTypeIndex );
	Parent::setupDefaultState(%this);
}

//////////////////////////////////////////////////////////////////////////

function EditorAlignBoundsMenu::onSelectItem(%this, %id, %text) {
	// Have the editor align all selected objects by the selected bounds.
	EWorldEditor.alignByBounds(getField(%this.item[%id], 2));
	return true;
}

function EditorAlignBoundsMenu::setupDefaultState(%this) {
	// Allow the parent to set the menu's default state
	Parent::setupDefaultState(%this);
}

//////////////////////////////////////////////////////////////////////////

function EditorAlignCenterMenu::onSelectItem(%this, %id, %text) {
	// Have the editor align all selected objects by the selected axis.
	EWorldEditor.alignByAxis(getField(%this.item[%id], 2));
	return true;
}

function EditorAlignCenterMenu::setupDefaultState(%this) {
	// Allow the parent to set the menu's default state
	Parent::setupDefaultState(%this);
}

redpajama_set_name: RedPajamaGithub


text:
    <title>Lokar test</title>

The test template for Lokar

Home

      You can link somewhere by typing #{a(location)}.
      link to somewhere

      % - the arguments you have passed to this action are:

          Argument 0
          Argument 1
          Argument 2
          Argument 3
          Argument 4


text:
package org.eclipse.rdf4j.query.resultio.sparqlstarjson;

import java.io.OutputStream;

/**
 * @deprecated since 3.4.0 - moved to {@link org.eclipse.rdf4j.query.resultio.sparqljson.SPARQLStarResultsJSONWriter}
 */
@Deprecated
public class SPARQLStarResultsJSONWriter
		extends org.eclipse.rdf4j.query.resultio.sparqljson.SPARQLStarResultsJSONWriter {

	public SPARQLStarResultsJSONWriter(OutputStream out) {
		super(out);
	}

}


text:
namespace blink {

class ModuleScriptFetcher;
class ScriptState;

// WorkerModulatorImpl is the Modulator implementation used in worker contexts
// (that means, not main documents). Module operations depending on the Worker
// context should be implemented in this class, not in ModulatorImplBase.
class WorkerModulatorImpl final : public ModulatorImplBase {
 public:
  explicit WorkerModulatorImpl(ScriptState*);

  // Implements ModulatorImplBase.
  ModuleScriptFetcher* CreateModuleScriptFetcher(
      ModuleScriptCustomFetchType,
      base::PassKey<ModuleScriptLoader> pass_key) override;

 private:
  // Implements ModulatorImplBase.
  bool IsDynamicImportForbidden(String* reason) override;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_SCRIPT_WORKER_MODULATOR_IMPL_H_


text:
const GelatoComponent = require('gelato/component');

/**
 * @class DashboardStatusComponent
 * @extends {GelatoComponent}
 */
const DashboardStatusComponent = GelatoComponent.extend({

  /**
   * @property template
   * @type {Function}
   */
  template: require('./DashboardStatus'),

  /**
   * @method initialize
   * @constructor
   */
  initialize: function () {
    this.errorFetchingDueCount = false;
    this.dueCount = null;
    this.vocablists = app.user.vocablists;
    this.listenTo(this.vocablists, 'state', this.render);
    this.updateDueCount();
  },

  /**
   * @method render
   * @returns {DashboardStatusComponent}
   */
  render: function () {
    this.renderTemplate();
    return this;
  },

  /**
   * @method updateDueCount
   */
  updateDueCount: function () {
    let url = app.getApiUrl() + 'items/due';

    if (app.config.useV2Gets.itemsdue) {
      url = app.getApiUrl(2) + 'gae/items/due';
    }

    if (app.user.offline.isReady()) {
      app.user.offline.loadDueCount({list: this.listIds}).then((result) => {
        this.dueCount = result || 0;
        this.render();
        this.trigger('component:loaded', 'goal');
      });

      return;
    }

    $.ajax({
      url: url,
      type: 'GET',
      headers: app.user.session.getHeaders(),
      context: this,
      data: {
        lang: app.getLanguage(),
        languageCode: app.getLanguage(),
        parts: app.user.getFilteredParts().join(','),
        styles: app.user.getFilteredStyles().join(','),
      },
      error: function (error) {
        this.dueCount = '-';
        this.errorFetchingDueCount = true;
        this.render();
        this.trigger('fetch-data:failed', 'goal');
      },
      success: function (result) {
        let count = 0;
        for (const part in result.due) {
          if (result.due.hasOwnProperty(part)) {
            for (const style in result.due[part]) {
              if (result.due[part].hasOwnProperty(style)) {
                count += result.due[part][style];
              }
            }
          }
        }
        this.dueCount = count;
        this.render();
        this.trigger('component:loaded', 'goal');
      },
    });
  },

});

module.exports = DashboardStatusComponent;


text:
package mesosphere.marathon
package api.akkahttp
import akka.http.scaladsl.model.Uri.Path
import akka.http.scaladsl.server.PathMatcher.{ Matched, Unmatched }
import akka.http.scaladsl.model.{ DateTime, HttpHeader, HttpMethods, HttpProtocols }
import akka.http.scaladsl.server.{ PathMatcher1, Directive0, Directives => AkkaDirectives }
import akka.http.scaladsl.model.headers._
import scala.concurrent.duration._

/**
  * All Marathon Directives and Akka Directives
  *
  * These should be imported by the respective controllers
  */
object Directives extends AuthDirectives with LeaderDirectives with AkkaDirectives {

  /**
    * Path matcher, that matches a segment only, if it is defined in the given set.
    * @param set the allowed path segments.
    */
  class PathIsAvailableInSet(set: Set[String]) extends PathMatcher1[String] {
    def apply(path: Path) = path match {
      case Path.Segment(segment, tail) if set(segment) ⇒ Matched(tail, Tuple1(segment))
      case _ ⇒ Unmatched
    }
  }

  /**
    * Use this directive to enable Cross Origin Resource Sharing for a given set of origins.
    *
    * @param origins the origins to allow.
    */
  def corsResponse(origins: Seq[String]): Directive0 = {
    import HttpMethods._
    extractRequest.flatMap { request =>
      val headers = Seq.newBuilder[HttpHeader]

      // add all pre-defined origins
      origins.foreach(headers += `Access-Control-Allow-Origin`(_))

      // allow all header that are defined as request headers
      request.header[`Access-Control-Request-Headers`].foreach(request =>
        headers += `Access-Control-Allow-Headers`(request.headers)
      )

      // define allowed methods
      headers += `Access-Control-Allow-Methods`(GET, HEAD, OPTIONS)

      // do not ask again for one day
      headers += `Access-Control-Max-Age`(1.day.toSeconds)

      respondWithHeaders (headers.result())
    }
  }

  /**
    * The noCache directive will set proper no-cache headers based on the HTTP protocol
    */
  val noCache: Directive0 = {
    import CacheDirectives._
    import HttpProtocols._
    extractRequest.flatMap {
      _.protocol match {
        case `HTTP/1.0` =>
          respondWithHeaders (
            RawHeader("Pragma", "no-cache")
          )
        case `HTTP/1.1` =>
          respondWithHeaders (
            `Cache-Control`(`no-cache`, `no-store`, `must-revalidate`),
            `Expires`(DateTime.now)
          )
      }
    }
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
RmsEntry (2013 FRC Java API)
</TITLE>

<META NAME="date" CONTENT="2014-01-01">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

"
2013 FRC Java API
"

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.sun.squawk.rms

Class RmsEntry

java.lang.Object
  com.sun.squawk.rms.RmsEntry

All Implemented Interfaces:
IRmsEntry

Direct Known Subclasses:
ApplicationDescriptorEntry, RecordEntry, RecordStoreEntry, RecordStoreSequenceEntry, UnknownEntry

public abstract class RmsEntry
extends Object
implements IRmsEntry

Field Summary

protected  Address
address

protected  int
size

Constructor Summary

RmsEntry()

Method Summary

 Address
getAddress()

 void
readFrom(IMemoryHeapBlock memoryBlock)

 void
setAddress(Address address)

 int
size()

 void
writeTo(DataOutputStream dataOut)

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Methods inherited from interface com.sun.squawk.rms.IRmsEntry

getType, visit

Field Detail

address

protected Address address

size

protected int size

Constructor Detail

RmsEntry

public RmsEntry()

Method Detail

getAddress

public Address getAddress()

Specified by:
getAddress in interface IRmsEntry

readFrom

public void readFrom(IMemoryHeapBlock memoryBlock)
              throws IOException

Specified by:
readFrom in interface IRmsEntry

Throws:

IOException

setAddress

public void setAddress(Address address)

Specified by:
setAddress in interface IRmsEntry

size

public int size()

Specified by:
size in interface IRmsEntry

writeTo

public void writeTo(DataOutputStream dataOut)
             throws IOException

Specified by:
writeTo in interface IRmsEntry

Throws:

IOException

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

"
2013 FRC Java API
"

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

"For updated information see the Java FRC site"


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Deprecated List (Solr 6.0.0 API)</title>
<meta name="date" content="2016-04-01">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Help

Prev

Next

Frames

No Frames

All Classes

Deprecated API

Contents

Deprecated Methods

Deprecated Constructors

Deprecated Methods

Method and Description

org.apache.solr.common.cloud.ClusterState.getZkClusterStateVersion()

true cluster state spans many ZK nodes, stop depending on the version number of the shared node!

org.apache.solr.common.util.ExecutorUtil.shutdownAndAwaitTerminationWithInterrupt(ExecutorService)

org.apache.solr.common.util.ExecutorUtil.shutdownWithInterruptAndAwaitTermination(ExecutorService)

Deprecated Constructors

Constructor and Description

org.apache.solr.common.util.NamedList(List<Object>)

Use NamedList.NamedList(java.util.Map.Entry[]) for the NamedList instantiation

org.apache.solr.common.util.SimpleOrderedMap(List<Object>)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Help

Prev

Next

Frames

No Frames

All Classes

          Copyright © 2000-2016 Apache Software Foundation.  All Rights Reserved.


text:
package me.pauzen.scheduler.task;

public abstract class AsyncTask extends Task {

    private Thread thread;

    public AsyncTask(Thread thread) {
        this.thread = thread;
    }

    /**
     * Does not use ticks.
     */
    @Override
    public void tick() {
    }

    @Override
    public void stop() {
        thread.stop();
    }

    @Override
    public void start() {
        thread = new Thread(this);
        thread.start();
    }

    @Override
    public void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public Thread getThread() {
        return thread;
    }
}


text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>The source code</title>
  <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />

/**
 * @ignore
 * use and attach mod for kissy simple loader
 * @author yiminghe@gmail.com, lifesinger@gmail.com
 */
(function (S, undefined) {

    var Loader, data, utils, UA,
        remoteLoads = {},
        LOADING, LOADED, ERROR, ATTACHED;

    Loader = S.Loader;
    data = Loader.Status;
    utils = Loader.Utils;
    UA = S.UA;
    LOADING = data.LOADING;
    LOADED = data.LOADED;
    ERROR = data.ERROR;
    ATTACHED = data.ATTACHED;

    function LoadChecker(fn) {
        S.mix(this, {
            fn: fn,
            waitMods: {},
            requireLoadedMods: {}
        });
    }

    LoadChecker.prototype = {

        constructor: LoadChecker,

        check: function () {
            var self = this,
                fn = self.fn;
            if (fn && S.isEmptyObject(self.waitMods)) {
                fn();
                self.fn = null;
            }
        },

        addWaitMod: function (modName) {
            this.waitMods[modName] = 1;
        },

        removeWaitMod: function (modName) {
            delete this.waitMods[modName];
        },

        isModWait: function (modName) {
            return this.waitMods[modName];
        },

        // only load mod requires once
        // prevent looping dependency sub tree more than once for one use()
        loadModRequires: function (loader, mod) {
            // 根据每次 use 缓存子树
            var self = this,
                requireLoadedMods = self.requireLoadedMods,
                modName = mod.name,
                requires;
            if (!requireLoadedMods[modName]) {
                requireLoadedMods[modName] = 1;
                requires = mod.getNormalizedRequires();
                loadModules(loader, requires, self);
            }
        }

    };

    S.augment(Loader, {
        /**
         * Start load specific mods, and fire callback when these mods and requires are attached.
         * @member KISSY.Loader
         *
         * for example:
         *      @example
         *      S.use('mod-name', callback);
         *      S.use('mod1,mod2', callback);
         *
         * @param {String|String[]} modNames names of mods to be loaded,if string then separated by space
         * @param {Function} callback callback when modNames are all loaded,
         * with KISSY as first argument and mod 's value as the following arguments
         * @param _forceSync internal use, do not set
         * @chainable
         */
        use: function (modNames, callback, /* for internal */_forceSync) {
            var self = this,
                normalizedModNames,
                loadChecker = new LoadChecker(loadReady),
                runtime = self.runtime;

            modNames = utils.getModNamesAsArray(modNames);
            modNames = utils.normalizeModNamesWithAlias(runtime, modNames);

            normalizedModNames = utils.unalias(runtime, modNames);

            function loadReady() {
                utils.attachModsRecursively(normalizedModNames, runtime);
                callback && callback.apply(runtime, utils.getModules(runtime, modNames));
            }

            loadModules(self, normalizedModNames, loadChecker);

            // in case modules is loaded statically
            // synchronous check
            // but always async for loader
            if (_forceSync) {
                loadChecker.check();
            } else {
                setTimeout(function () {
                    loadChecker.check();
                }, 0);
            }
            return self;
        }
    });

    function loadModules(self, modNames, loadChecker) {
        var i,
            l = modNames.length;
        for (i = 0; i < l; i++) {
            loadModule(self, modNames[i], loadChecker);
        }
    }

    function loadModule(self, modName, loadChecker) {
        var runtime = self.runtime,
            status,
            isWait,
            mods = runtime.Env.mods,
            mod = mods[modName];

        if (!mod) {
            utils.createModuleInfo(runtime, modName);
            mod = mods[modName];
        }

        status = mod.status;

        if (status == ATTACHED) {
            return;
        }

        // 已经静态存在在页面上
        // 或者该模块不是根据自身模块名动态加载来的(io.js包含 io/base,io/form)
        if (status === LOADED) {
            loadChecker.loadModRequires(self, mod);
        } else {
            isWait = loadChecker.isModWait(modName);
            // prevent duplicate listen for this use
            //  use('a,a') or
            //  user('a,c') a require b, c require b
            // listen b only once
            // already waiting, will notify loadReady in the future
            if (isWait) {
                return;
            }
            // error or init or loading
            loadChecker.addWaitMod(modName);
            // in case parallel use (more than one use)
            if (status <= LOADING) {
                // load and attach this module
                fetchModule(self, mod, loadChecker);
            }

        }
    }

    // Load a single module.
    function fetchModule(self, mod, loadChecker) {

        var runtime = self.runtime,
            modName = mod.getName(),
            charset = mod.getCharset(),
            url = mod.getFullPath(),
            currentModule = 0,
            ie = UA.ie,
            isCss = mod.getType() == 'css';

        mod.status = LOADING;

        if (ie && !isCss) {
            self.__startLoadModName = modName;
            self.__startLoadTime = Number(+new Date());
        }

        S.getScript(url, {
            attrs: ie ? {
                'data-mod-name': modName
            } : undefined,
            // syntaxError in all browser will trigger this
            // same as #111 : https://github.com/kissyteam/kissy/issues/111
            success: function () {
                // parallel use
                // 只设置第一个 use 处
                if (mod.status == LOADING) {
                    if (isCss) {
                        // css does not set LOADED because no add for css! must be set manually
                        utils.registerModule(runtime, modName, S.noop);
                    } else {
                        // does not need this step for css
                        // standard browser(except ie9) fire load after KISSY.add immediately
                        if (currentModule = self.__currentMod) {
                            // S.log('standard browser get mod name after load : ' + modName);
                            utils.registerModule(runtime,
                                modName, currentModule.fn,
                                currentModule.config);
                            self.__currentMod = null;
                        }
                    }
                }

                // nodejs is synchronous,
                // use('x,y')
                // need x,y filled into waitingMods first
                // x,y waiting -> x -> load -> y -> load -> check

                S.later(checkHandler);
            },
            error: checkHandler,
            // source:mod.name + '-init',
            charset: charset
        });

        function checkHandler() {
            if (mod.fn) {
                if (!remoteLoads[modName]) {
                    S.log('load remote module: "' + modName + '" from: "' + url + '"', 'info');
                    remoteLoads[modName] = 1;
                }
                // 只在 LOADED 后加载依赖项一次
                // 防止 config('modules') requires 和模块中 requires 不一致
                loadChecker.loadModRequires(self, mod);
                loadChecker.removeWaitMod(modName);
                // a mod is loaded, need to check globally
                loadChecker.check();
            } else {
                // ie will call success even when getScript error(404)
                _modError();
            }
        }

        function _modError() {
            S.log(modName + ' is not loaded! can not find module in path : ' + url, 'error');
            mod.status = ERROR;
        }

    }
})(KISSY);

/*
 2012-10-08 yiminghe@gmail.com refactor
 - use 调用先统一 load 再统一 attach

 2012-09-20 yiminghe@gmail.com refactor
 - 参考 async 重构,去除递归回调
 */


text:
package galaxyspace.systems.SolarSystem.moons.io.world.gen.dungeon;

import java.util.Random;

import asmodeuscore.core.astronomy.dimension.world.gen.dungeons.standart.DungeonConfiguration;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.gen.structure.StructureBoundingBox;
import net.minecraft.world.gen.structure.StructureComponent;
import net.minecraft.world.gen.structure.template.TemplateManager;

public abstract class PieceIo extends StructureComponent
{
    protected DungeonConfiguration configuration;

    public PieceIo()
    {
    }

    public PieceIo(DungeonConfiguration configuration)
    {
        this.configuration = configuration;
    }

    @Override
    protected void writeStructureToNBT(NBTTagCompound tagCompound)
    {
        this.configuration.writeToNBT(tagCompound);
    }

    @Override
    protected void readStructureFromNBT(NBTTagCompound tagCompound, TemplateManager manager)
    {
        if (this.configuration == null)
        {
            this.configuration = new DungeonConfiguration();
            this.configuration.readFromNBT(tagCompound);
        }
    }

    protected StructureBoundingBox getExtension(EnumFacing direction, int length, int width)
    {
        int blockX, blockZ, sizeX, sizeZ;
        switch (direction)
        {
        case NORTH:
            sizeX = width;
            sizeZ = length;
            blockX = this.boundingBox.minX + (this.boundingBox.maxX - this.boundingBox.minX) / 2 - sizeX / 2;
            blockZ = this.boundingBox.minZ - sizeZ;
            break;
        case EAST:
            sizeX = length;
            sizeZ = width;
            blockX = this.boundingBox.maxX;
            blockZ = this.boundingBox.minZ + (this.boundingBox.maxZ - this.boundingBox.minZ) / 2 - sizeZ / 2;
            break;
        case SOUTH:
            sizeX = width;
            sizeZ = length;
            blockX = this.boundingBox.minX + (this.boundingBox.maxX - this.boundingBox.minX) / 2 - sizeX / 2;
            blockZ = this.boundingBox.maxZ;
            break;
        case WEST:
        default:
            sizeX = length;
            sizeZ = width;
            blockX = this.boundingBox.minX - sizeX;
            blockZ = this.boundingBox.minZ + (this.boundingBox.maxZ - this.boundingBox.minZ) / 2 - sizeZ / 2;
            break;
        }
        return new StructureBoundingBox(blockX, blockZ, blockX + sizeX, blockZ + sizeZ);
    }

    public PieceIo getNextPiece(DungeonStartIo startPiece, Random rand)
    {
        return null;
    }
}


text:
Initial alpha release, still tied to a rails application config. There are no test, and some tight coupling deep in the code. This is an internal tool in the early stages
of open source
Hopefully this should be improved in later releases.

## Installation

Add the gem to your Gemfile

    gem 'winston_mongodb_rails'

Add `config/initializers/mongo_logger.rb`

    app_config = Rails.application.config
    Mog = WinstonMongodbRails::MongoLogger.create_logger(app_config, ((app_config.paths.log.to_a rescue nil) || app_config.paths['log']).first)

For mongo configuration, you need to add the configuration of the mongodb database to `config/mongo_logger.yml`, `config/mongoid.yml` or `config/database.yml`

    production:
      username: username
      password: password
      database: logs
      replicaset: ['10.10.10.2:27017', '10.10.10.1:27017']
      replicaset_name: 'replicaset_name'

    development:
      username: username
      password: password
      database: logs
      host: localhost

## Usage

    Mog.error "This is an error", object_to_inspect
    Mog.debug "Debug message"
    Mog.info "Info message"


text:
package org.semanticweb.elk.owl.filters;

import org.semanticweb.elk.owl.interfaces.ElkSubObjectPropertyOfAxiom;
import org.semanticweb.elk.owl.visitors.ElkSubObjectPropertyOfAxiomVisitor;

/**
 * A filter producing objects in {@link ElkSubObjectPropertyOfAxiom} from
 * objects of this type.
 *
 * @author "Yevgeny Kazakov"
 *
 */
public interface ElkSubObjectPropertyOfAxiomFilter extends
		ElkSubObjectPropertyOfAxiomVisitor<ElkSubObjectPropertyOfAxiom> {

	// nothing else

}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.monitor.fluent;

import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.http.rest.PagedFlux;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.util.Context;
import com.azure.resourcemanager.monitor.fluent.models.MetricNamespaceInner;

/** An instance of this class provides access to all the operations defined in MetricNamespacesClient. */
public interface MetricNamespacesClient {
    /**
     * Lists the metric namespaces for the resource.
     *
     * @param resourceUri The identifier of the resource.
     * @param startTime The ISO 8601 conform Date start time from which to query for metric namespaces.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return represents collection of metric namespaces.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    PagedFlux<MetricNamespaceInner> listAsync(String resourceUri, String startTime);

    /**
     * Lists the metric namespaces for the resource.
     *
     * @param resourceUri The identifier of the resource.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return represents collection of metric namespaces.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    PagedFlux<MetricNamespaceInner> listAsync(String resourceUri);

    /**
     * Lists the metric namespaces for the resource.
     *
     * @param resourceUri The identifier of the resource.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return represents collection of metric namespaces.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    PagedIterable<MetricNamespaceInner> list(String resourceUri);

    /**
     * Lists the metric namespaces for the resource.
     *
     * @param resourceUri The identifier of the resource.
     * @param startTime The ISO 8601 conform Date start time from which to query for metric namespaces.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return represents collection of metric namespaces.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    PagedIterable<MetricNamespaceInner> list(String resourceUri, String startTime, Context context);
}


text:
"""A CLI to import whisper data into Cassandra."""

from __future__ import print_function

from multiprocessing import dummy as multiprocessing_dummy
import argparse
import datetime
import logging
import multiprocessing
import os
import progressbar
import re
import scandir
import struct
import sys
import time

import whisper

from biggraphite import accessor as bg_accessor
from biggraphite import utils as bg_utils
from biggraphite.cli import command

_DEV_NULL = open(os.devnull, "w")

_POINT_STRUCT = struct.Struct(whisper.pointFormat)
_WORKER = None

log = logging.getLogger(__name__)

def metric_name_from_wsp(root_dir, prefix, wsp_path):
    """Return the name of a metric given a wsp file path and a root directory.

    The path do not have to exist.

    Args:
      root_dir: A directory that is parent to all metrics.
      prefix: Prefix to preprend to metric names.
      wsp_path: The name of a file ending with wsp file in root_dir.

    Returns:
      The metric name.
    """
    relpath = os.path.relpath(wsp_path, root_dir)
    assert ".." not in relpath, "%s not a child of %" % (root_dir, wsp_path)
    relpath_noext = os.path.splitext(relpath)[0]
    return prefix + relpath_noext.replace(os.path.sep, ".")

class _Worker(object):

    def __init__(self, opts):
        settings = bg_utils.settings_from_args(opts)
        bg_utils.set_log_level(settings)
        self._accessor = bg_utils.accessor_from_settings(settings)
        self._opts = opts
        self.time_start = time.mktime(self._opts.time_start.timetuple())
        self.time_end = time.mktime(self._opts.time_end.timetuple())

    @staticmethod
    def _read_metadata(metric_name, path):
        info = whisper.info(path)
        if not info:
            return None

        retentions = bg_accessor.Retention([
            bg_accessor.Stage(precision=a["secondsPerPoint"], points=a["points"])
            for a in info["archives"]
        ])
        aggregator = bg_accessor.Aggregator.from_carbon_name(
            info["aggregationMethod"])
        return bg_accessor.MetricMetadata(
            aggregator=aggregator,
            retention=retentions,
            carbon_xfilesfactor=info["xFilesFactor"],
        )

    def _read_points(self, path):
        """Return a list of (timestamp, value)."""
        info = whisper.info(path)
        res = []
        if not info:
            return []

        archives = info["archives"]
        with open(path) as f:
            buf = f.read()

        stage0 = True
        for archive in archives:
            offset = archive["offset"]
            stage = bg_accessor.Stage(
                precision=archive["secondsPerPoint"],
                points=archive["points"],
                stage0=stage0)
            stage0 = False
            if stage in self._opts.ignored_stages:
                continue

            for _ in range(archive["points"]):
                timestamp, value = _POINT_STRUCT.unpack_from(buf, offset)
                offset += whisper.pointSize

                if timestamp == 0:
                    continue
                elif timestamp >= self.time_start and timestamp <= self.time_end:
                    res.append((timestamp, value, 1, stage))

        return res

    def import_whisper(self, path):
        if not self._accessor.is_connected:
            self._accessor.connect()

        name = metric_name_from_wsp(
            self._opts.root_directory,
            self._opts.prefix, path)
        metadata = self._read_metadata(name, path)
        log.debug("%s: %s" % (name, metadata.as_string_dict()))

        if not metadata:
            return 0

        metric = self._accessor.make_metric(name, metadata)
        if not self._opts.no_metadata:
            self._accessor.create_metric(metric)

        ret = 0
        if not self._opts.no_data:
            points = self._read_points(path)
            self._accessor.insert_downsampled_points(metric, points)
            ret = len(points)

        return ret

def _setup_process(opts):
    global _WORKER
    _WORKER = _Worker(opts)

def _import_whisper(*args, **kwargs):
    assert _WORKER is not None, "_setup_process was never called"
    try:
        return _WORKER.import_whisper(*args, **kwargs)
    except Exception as e:
        log.exception(e)
        return 0

def _parse_opts(args):
    parser = argparse.ArgumentParser(
        description="Import whisper files into BigGraphite.")
    parser.add_argument("root_directory", metavar="WHISPER_DIR",
                        help="directory in which to find whisper files")
    parser.add_argument("--filter", type=str, default=".*\.wsp",
                        help="Only import metrics matching this filter")
    parser.add_argument("--prefix", metavar="WHISPER_PREFIX", default="",
                        help="prefix to prepend to metric names")
    parser.add_argument("--quiet", action="store_const", default=False, const=True,
                        help="Show no output unless there are problems.")
    parser.add_argument("--process", metavar="N", type=int,
                        help="number of concurrent process",
                        default=multiprocessing.cpu_count())
    parser.add_argument("--no-data", action="store_true",
                        help="Do not import data, only metadata.")
    parser.add_argument("--no-metadata", action="store_true",
                        help="Do not import metadata, only data.")
    parser.add_argument("--ignored_stages", nargs="*",
                        help="Do not import data for these stages.",
                        default=[])
    parser.add_argument(
        "--time-start",
        action=command.ParseDateTimeArg,
        help="Read points written later than this time.",
        default=datetime.datetime.fromtimestamp(0),
        required=False,
    )
    parser.add_argument(
        "--time-end",
        action=command.ParseDateTimeArg,
        help="Read points written earlier than this time.",
        default=datetime.datetime.now(),
        required=False,
    )
    bg_utils.add_argparse_arguments(parser)
    opts = parser.parse_args(args)
    opts.ignored_stages = [
        bg_accessor.Stage.from_string(s)
        for s in opts.ignored_stages
    ]
    return opts

# TODO: put that in a thread.
class _Walker():
    def __init__(self, root_directory, regexp):
        self.count = 0
        self.root_directory = root_directory
        self.regexp = re.compile(regexp)

    def paths(self, root=None):
        root = root or self.root_directory
        for entry in scandir.scandir(root):
            if entry.is_dir():
                for filename in self.paths(entry.path):
                    yield filename
            elif self.regexp.match(os.path.join(root, entry.name)):
                self.count += 1
                yield os.path.join(root, entry.name)

def main(args=None):
    """Entry point for the module."""
    if not args:
        args = sys.argv[1:]

    opts = _parse_opts(args)

    pool_factory = multiprocessing.Pool
    if opts.process == 1:
        pool_factory = multiprocessing_dummy.Pool
    pool = pool_factory(opts.process, initializer=_setup_process, initargs=(opts,))

    out_fd = sys.stderr
    if opts.quiet:
        out_fd = _DEV_NULL
    if "__pypy__" not in sys.builtin_module_names:
        print("Running without PyPy, this is about 20 times slower", file=out_fd)
        out_fd.flush()

    walker = _Walker(opts.root_directory, opts.filter)
    paths = walker.paths()
    total_points = 0
    max_value = progressbar.UnknownLength
    with progressbar.ProgressBar(max_value=max_value, fd=out_fd, redirect_stderr=True) as pbar:
        try:
            res = pool.imap_unordered(_import_whisper, paths)
            for n_path, n_points in enumerate(res):
                total_points += n_points
                pbar.update(n_path)
        except KeyboardInterrupt:
            pool.terminate()

    pool.close()
    pool.join()

    print("Uploaded", walker.count, "metrics containing", total_points, "points", file=out_fd)

if __name__ == "__main__":
    main()


text:
@class GYMExercise;

@interface GYMExerciseListTableViewCellModel : NSObject
@property (nonatomic, strong) GYMExercise *exercise;
@property (nonatomic, copy, readonly) NSString *exerciseName;
@property (nonatomic, copy, readonly) NSString *numberOfSets;
@property (nonatomic, copy, readonly) NSString *numberOfRepetitions;
@property (nonatomic, copy, readonly) NSString *weight;
@end


text:
var dbPath = process.env.MONGOHQ_URL || 'mongodb://vinit:wordpass@oceanic.mongohq.com:10038/bender001';

var onlineSellersList = "sellers_list.txt";
var productCategoryList = "product_category_list.txt";
var serviceCategoryList = "service_category_list.txt";

// Import the data layer
var mongoose = require('mongoose');
var fs = require('fs');
var config = {
  mail: require('../config/mail')
};

console.log("Zorsay DB Worker Started.");

console.log('Trying to connect to mongo at: '+dbPath);

mongoose.connect(dbPath, function onMongooseError(err) {
  console.log('inside mongoose connect callback');
  if (err)  {
    console.log('err found in connecting to mongo');
    console.log(err);
    throw err;
  }
  console.log('all good while connecting to mongo');

  // Import the models
  models = {};

  models.PublicCounter = require('../models/PublicCounter')(config, mongoose);

  // models.Account = require('./models/Account')(config, mongoose, nodemailer),
  // models.Shopex = require('../models/Shopex')(config, mongoose, PublicCounter),
  // models.Question = require('../models/Shopex')(config, mongoose, PublicCounter),
  // models.Answer = require('../models/Shopex')(config, mongoose, PublicCounter),

  models.Seller = require('../models/Seller_new')(config, mongoose, models),
  models.ProductCat = require('../models/ProductCat_new')(config, mongoose, models),
  models.ServiceCat = require('../models/ServiceCat_new')(config, mongoose, models),

  fs.readFile(onlineSellersList, "utf-8", function(err, data){
    if (err)
      throw err;
    // console.log(data);
    sellers = data.split("\n");
    console.log(sellers.length);

    for(var i = 0; i < sellers.length; ++i) {
      seller_name = sellers[i].trim();
      if (seller_name) {
        seller_domain = seller_name.toLowerCase();
        seller_url_name = seller_domain;

        models.Seller.createNode({
          site_domain: seller_domain,
          name: seller_name,
          url_name: seller_url_name,
        }, function(err, saved_seller){
          console.log("createNode callback for sellers");
          if (err)
            console.log(err);
          // console.log(JSON.stringify(saved_seller));
        });
      }
    }
  }) // sellers list inserted

  fs.readFile(productCategoryList, "utf-8", function(err, data){
    if (err)
      throw err;
    // console.log(data);
    pro_cats = data.split("\n");
    console.log(pro_cats.length);

    for(var i = 0; i < pro_cats.length; ++i) {
      pro_cat_name = pro_cats[i].trim();
      if (pro_cat_name) {
        pro_cat_url_name = pro_cat_name.replace(/\s+/g, "-").replace(/[^-a-zA-Z0-9]+/g,"");

        models.ProductCat.createNode({
          name: pro_cat_name,
          url_name: pro_cat_url_name,
        }, function(err, saved_pro_cat){
          console.log("createNode callback for pro_cats");
          if (err)
            console.log(err.message);
          // console.log(JSON.stringify(saved_pro_cat));
        });
      }
    }
  }) // Product Category list inserted

  fs.readFile(serviceCategoryList, "utf-8", function(err, data){
    if (err)
      throw err;
    // console.log(data);
    ser_cats = data.split("\n");
    console.log(ser_cats.length);

    for(var i = 0; i < ser_cats.length; ++i) {
      ser_cat_name = ser_cats[i].trim();
      if (ser_cat_name) {
        ser_cat_url_name = ser_cat_name.replace(/\s+/g, "-").replace(/[^-a-zA-Z0-9]+/g,"");

        models.ServiceCat.createNode({
          name: ser_cat_name,
          url_name: ser_cat_url_name,
        }, function(err, saved_ser_cat){
          console.log("createNode callback for ser_cats");
          if (err)
            console.log(err.message);
          // console.log(JSON.stringify(saved_ser_cat));
        });
      }
    }
  }) // Service Category list inserted

});


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2018 Srikavin Ramkumar
  ~
  ~ 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.
  -->

<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>infuzion</groupId>
    <artifactId>client</artifactId>
    <version>2.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.0</version>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>infuzion</groupId>
            <artifactId>common</artifactId>
            <version>2.0-SNAPSHOT</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-validator/commons-validator -->
        <dependency>
            <groupId>commons-validator</groupId>
            <artifactId>commons-validator</artifactId>
            <version>1.4.0</version>
        </dependency>
    </dependencies>

</project>


text:
#pragma warning disable 1717
namespace Javax.Security.Auth
{
		///
		///  <para>Legacy security code; do not use. </para>
		///
		/// <java-name>
		/// javax/security/auth/AuthPermission
		/// </java-name>
		[Dot42.DexImport("javax/security/auth/AuthPermission", AccessFlags = 49)]
		public sealed partial class AuthPermission : global::Java.Security.BasicPermission
 /* scope: __dot42__ */
		{
				[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
				public AuthPermission(string name) /* MethodBuilder.Create */
				{
				}

				[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1)]
				public AuthPermission(string name, string actions) /* MethodBuilder.Create */
				{
				}

				[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
				protected internal AuthPermission() /* TypeBuilder.AddDefaultConstructor */
				{
				}

		}

		///
		///  <para>Signals that the Destroyable#destroy() method failed. </para>
		///
		/// <java-name>
		/// javax/security/auth/DestroyFailedException
		/// </java-name>
		[Dot42.DexImport("javax/security/auth/DestroyFailedException", AccessFlags = 33)]
		public partial class DestroyFailedException : global::System.Exception
 /* scope: __dot42__ */
		{
				///
				///  <para>Creates an exception of type <c>DestroyFailedException </c> . </para>
				///
				[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
				public DestroyFailedException() /* MethodBuilder.Create */
				{
				}

				///
				///  <para>Creates an exception of type <c>DestroyFailedException </c> .</para> <para></para>
				///
				[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
				public DestroyFailedException(string message) /* MethodBuilder.Create */
				{
				}

		}

		///
		///  <para>Allows for special treatment of sensitive information, when it comes to destroying or clearing of the data. </para>
		///
		/// <java-name>
		/// javax/security/auth/Destroyable
		/// </java-name>
		[Dot42.DexImport("javax/security/auth/Destroyable", AccessFlags = 1537)]
		public partial interface IDestroyable
 /* scope: __dot42__ */
		{
				///
				///  <para>Erases the sensitive information. Once an object is destroyed any calls to its methods will throw an <c>IllegalStateException </c> . If it does not succeed a DestroyFailedException is thrown.</para> <para></para>
				///
				/// <java-name>
				/// destroy
				/// </java-name>
				[Dot42.DexImport("destroy", "()V", AccessFlags = 1025)]
				void Destroy() /* MethodBuilder.Create */ ;

				///
				///  <para>Returns <c>true </c> once an object has been safely destroyed.</para> <para></para>
				///
				/// <returns>
				///  <para>whether the object has been safely destroyed. </para>
				/// </returns>
				/// <java-name>
				/// isDestroyed
				/// </java-name>
				bool IsDestroyed
				{
						[Dot42.DexImport("isDestroyed", "()Z", AccessFlags = 1025)]
						get;
				}

		}

		///
		///  <para>Legacy security code; do not use. </para>
		///
		/// <java-name>
		/// javax/security/auth/PrivateCredentialPermission
		/// </java-name>
		[Dot42.DexImport("javax/security/auth/PrivateCredentialPermission", AccessFlags = 49)]
		public sealed partial class PrivateCredentialPermission : global::Java.Security.Permission
 /* scope: __dot42__ */
		{
				[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1)]
				public PrivateCredentialPermission(string name, string action) /* MethodBuilder.Create */
				{
				}

				/// <java-name>
				/// hashCode
				/// </java-name>
				[Dot42.DexImport("hashCode", "()I", AccessFlags = 1)]
				public override int GetHashCode() /* MethodBuilder.Create */
				{
						return default(int);
				}

				/// <java-name>
				/// equals
				/// </java-name>
				[Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 1)]
				public override bool Equals(object @object) /* MethodBuilder.Create */
				{
						return default(bool);
				}

				/// <java-name>
				/// implies
				/// </java-name>
				[Dot42.DexImport("implies", "(Ljava/security/Permission;)Z", AccessFlags = 1)]
				public override bool Implies(global::Java.Security.Permission permission) /* MethodBuilder.Create */
				{
						return default(bool);
				}

				/// <java-name>
				/// newPermissionCollection
				/// </java-name>
				[Dot42.DexImport("newPermissionCollection", "()Ljava/security/PermissionCollection;", AccessFlags = 1)]
				public override global::Java.Security.PermissionCollection NewPermissionCollection() /* MethodBuilder.Create */
				{
						return default(global::Java.Security.PermissionCollection);
				}

				[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
				protected internal PrivateCredentialPermission() /* TypeBuilder.AddDefaultConstructor */
				{
				}

				/// <java-name>
				/// getPrincipals
				/// </java-name>
				public string[][] Principals
				{
						[Dot42.DexImport("getPrincipals", "()[[Ljava/lang/String;", AccessFlags = 1)]
						get{ return default(string[][]); }
				}

				/// <java-name>
				/// getActions
				/// </java-name>
				public override string Actions
				{
						[Dot42.DexImport("getActions", "()Ljava/lang/String;", AccessFlags = 1)]
						get{ return default(string); }
				}

				/// <java-name>
				/// getCredentialClass
				/// </java-name>
				public string CredentialClass
				{
						[Dot42.DexImport("getCredentialClass", "()Ljava/lang/String;", AccessFlags = 1)]
						get{ return default(string); }
				}

		}

		///
		///  <para>The central class of the <c>javax.security.auth </c> package representing an authenticated user or entity (both referred to as "subject"). IT defines also the static methods that allow code to be run, and do modifications according to the subject's permissions. </para> <para>A subject has the following features:

 <para>A set of <c>Principal </c> objects specifying the identities bound to a  <c>Subject </c> that distinguish it. </para>

 <para>Credentials (public and private) such as certificates, keys, or authentication proofs such as tickets </para>

</para>
		///
		/// <java-name>
		/// javax/security/auth/Subject
		/// </java-name>
		[Dot42.DexImport("javax/security/auth/Subject", AccessFlags = 49)]
		public sealed partial class Subject : global::Java.IO.ISerializable
 /* scope: __dot42__ */
		{
				///
				///  <para>The default constructor initializing the sets of public and private credentials and principals with the empty set. </para>
				///
				[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
				public Subject() /* MethodBuilder.Create */
				{
				}

				///
				///  <para>The constructor for the subject, setting its public and private credentials and principals according to the arguments.</para> <para></para>
				///
				[Dot42.DexImport("<init>", "(ZLjava/util/Set;Ljava/util/Set;Ljava/util/Set;)V", AccessFlags = 1, Signature = "(ZLjava/util/Set<+Ljava/security/Principal;>;Ljava/util/Set<*>;Ljava/util/Set<*>;" +
    ")V")]
				public Subject(bool readOnly, global::Java.Util.ISet<global::Java.Security.IPrincipal> subjPrincipals, global::Java.Util.ISet<object> pubCredentials, global::Java.Util.ISet<object> privCredentials) /* MethodBuilder.Create */
				{
				}

				///
				///  <para>Runs the code defined by <c>action </c> using the permissions granted to the <c>Subject </c> itself and to the code as well.</para> <para></para>
				///
				/// <returns>
				///  <para>the <c>Object </c> returned when running the <c>action </c> . </para>
				/// </returns>
				/// <java-name>
				/// doAs
				/// </java-name>
				[Dot42.DexImport("doAs", "(Ljavax/security/auth/Subject;Ljava/security/PrivilegedAction;)Ljava/lang/Object;" +
    "", AccessFlags = 9, Signature = "<T:Ljava/lang/Object;>(Ljavax/security/auth/Subject;Ljava/security/PrivilegedActi" +
    "on<TT;>;)TT;")]
				public static T DoAs<T>(global::Javax.Security.Auth.Subject subject, global::Java.Security.IPrivilegedAction<T> action) /* MethodBuilder.Create */
				{
						return default(T);
				}

				///
				///  <para>Run the code defined by <c>action </c> using the permissions granted to the <c>Subject </c> and to the code itself, additionally providing a more specific context.</para> <para></para>
				///
				/// <returns>
				///  <para>the <c>Object </c> returned when running the <c>action </c> . </para>
				/// </returns>
				/// <java-name>
				/// doAsPrivileged
				/// </java-name>
				[Dot42.DexImport("doAsPrivileged", "(Ljavax/security/auth/Subject;Ljava/security/PrivilegedAction;Ljava/security/Acce" +
    "ssControlContext;)Ljava/lang/Object;", AccessFlags = 9, Signature = "<T:Ljava/lang/Object;>(Ljavax/security/auth/Subject;Ljava/security/PrivilegedActi" +
    "on<TT;>;Ljava/security/AccessControlContext;)TT;")]
				public static T DoAsPrivileged<T>(global::Javax.Security.Auth.Subject subject, global::Java.Security.IPrivilegedAction<T> action, global::Java.Security.AccessControlContext context) /* MethodBuilder.Create */
				{
						return default(T);
				}

				///
				///  <para>Runs the code defined by <c>action </c> using the permissions granted to the <c>Subject </c> itself and to the code as well.</para> <para></para>
				///
				/// <returns>
				///  <para>the <c>Object </c> returned when running the <c>action </c> . </para>
				/// </returns>
				/// <java-name>
				/// doAs
				/// </java-name>
				[Dot42.DexImport("doAs", "(Ljavax/security/auth/Subject;Ljava/security/PrivilegedExceptionAction;)Ljava/lan" +
    "g/Object;", AccessFlags = 9, Signature = "<T:Ljava/lang/Object;>(Ljavax/security/auth/Subject;Ljava/security/PrivilegedExce" +
    "ptionAction<TT;>;)TT;")]
				public static T DoAs<T>(global::Javax.Security.Auth.Subject subject, global::Java.Security.IPrivilegedExceptionAction<T> action) /* MethodBuilder.Create */
				{
						return default(T);
				}

				///
				///  <para>Run the code defined by <c>action </c> using the permissions granted to the <c>Subject </c> and to the code itself, additionally providing a more specific context.</para> <para></para>
				///
				/// <returns>
				///  <para>the <c>Object </c> returned when running the <c>action </c> . </para>
				/// </returns>
				/// <java-name>
				/// doAsPrivileged
				/// </java-name>
				[Dot42.DexImport("doAsPrivileged", "(Ljavax/security/auth/Subject;Ljava/security/PrivilegedExceptionAction;Ljava/secu" +
    "rity/AccessControlContext;)Ljava/lang/Object;", AccessFlags = 9, Signature = "<T:Ljava/lang/Object;>(Ljavax/security/auth/Subject;Ljava/security/PrivilegedExce" +
    "ptionAction<TT;>;Ljava/security/AccessControlContext;)TT;")]
				public static T DoAsPrivileged<T>(global::Javax.Security.Auth.Subject subject, global::Java.Security.IPrivilegedExceptionAction<T> action, global::Java.Security.AccessControlContext context) /* MethodBuilder.Create */
				{
						return default(T);
				}

				///
				///  <para>Checks two Subjects for equality. More specifically if the principals, public and private credentials are equal, equality for two <c>Subjects </c> is implied.</para> <para></para>
				///
				/// <returns>
				///  <para> <c>true </c> if the specified <c>Subject </c> is equal to this one. </para>
				/// </returns>
				/// <java-name>
				/// equals
				/// </java-name>
				[Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 1)]
				public override bool Equals(object obj) /* MethodBuilder.Create */
				{
						return default(bool);
				}

				///
				///  <para>Returns this <c>Subject </c> 's Principal which is a subclass of the <c>Class </c> provided.</para> <para></para>
				///
				/// <returns>
				///  <para>this <c>Subject </c> 's Principal. Modifications to the returned set of <c>Principal </c> s do not affect this <c>Subject </c> 's set. </para>
				/// </returns>
				/// <java-name>
				/// getPrincipals
				/// </java-name>
				[Dot42.DexImport("getPrincipals", "(Ljava/lang/Class;)Ljava/util/Set;", AccessFlags = 1, Signature = "<T::Ljava/security/Principal;>(Ljava/lang/Class<TT;>;)Ljava/util/Set<TT;>;")]
				public global::Java.Util.ISet<T> GetPrincipals<T>(global::System.Type c) /* MethodBuilder.Create */
				{
						return default(global::Java.Util.ISet<T>);
				}

				///
				///  <para>Returns this <c>Subject </c> 's private credentials which are a subclass of the <c>Class </c> provided.</para> <para></para>
				///
				/// <returns>
				///  <para>this <c>Subject </c> 's private credentials. Modifications to the returned set of credentials do not affect this <c>Subject </c> 's credentials. </para>
				/// </returns>
				/// <java-name>
				/// getPrivateCredentials
				/// </java-name>
				[Dot42.DexImport("getPrivateCredentials", "(Ljava/lang/Class;)Ljava/util/Set;", AccessFlags = 1, Signature = "<T:Ljava/lang/Object;>(Ljava/lang/Class<TT;>;)Ljava/util/Set<TT;>;")]
				public global::Java.Util.ISet<T> GetPrivateCredentials<T>(global::System.Type c) /* MethodBuilder.Create */
				{
						return default(global::Java.Util.ISet<T>);
				}

				///
				///  <para>Returns this <c>Subject </c> 's public credentials which are a subclass of the <c>Class </c> provided.</para> <para></para>
				///
				/// <returns>
				///  <para>this <c>Subject </c> 's public credentials. Modifications to the returned set of credentials do not affect this <c>Subject </c> 's credentials. </para>
				/// </returns>
				/// <java-name>
				/// getPublicCredentials
				/// </java-name>
				[Dot42.DexImport("getPublicCredentials", "(Ljava/lang/Class;)Ljava/util/Set;", AccessFlags = 1, Signature = "<T:Ljava/lang/Object;>(Ljava/lang/Class<TT;>;)Ljava/util/Set<TT;>;")]
				public global::Java.Util.ISet<T> GetPublicCredentials<T>(global::System.Type c) /* MethodBuilder.Create */
				{
						return default(global::Java.Util.ISet<T>);
				}

				///
				///  <para>Returns a hash code of this <c>Subject </c> .</para> <para></para>
				///
				/// <returns>
				///  <para>a hash code of this <c>Subject </c> . </para>
				/// </returns>
				/// <java-name>
				/// hashCode
				/// </java-name>
				[Dot42.DexImport("hashCode", "()I", AccessFlags = 1)]
				public override int GetHashCode() /* MethodBuilder.Create */
				{
						return default(int);
				}

				///
				///  <para>Prevents from modifications being done to the credentials and Principal sets. After setting it to read-only this <c>Subject </c> can not be made writable again. The destroy method on the credentials still works though. </para>
				///
				/// <java-name>
				/// setReadOnly
				/// </java-name>
				[Dot42.DexImport("setReadOnly", "()V", AccessFlags = 1)]
				public void SetReadOnly() /* MethodBuilder.Create */
				{
				}

				///
				///  <para>Returns a <c>String </c> representation of this <c>Subject </c> .</para> <para></para>
				///
				/// <returns>
				///  <para>a <c>String </c> representation of this <c>Subject </c> . </para>
				/// </returns>
				/// <java-name>
				/// toString
				/// </java-name>
				[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)]
				public override string ToString() /* MethodBuilder.Create */
				{
						return default(string);
				}

				///
				///  <para>Returns the <c>Subject </c> that was last associated with the <c>context </c> provided as argument.</para> <para></para>
				///
				/// <returns>
				///  <para>the <c>Subject </c> that was last associated with the <c>context </c> provided as argument. </para>
				/// </returns>
				/// <java-name>
				/// getSubject
				/// </java-name>
				[Dot42.DexImport("getSubject", "(Ljava/security/AccessControlContext;)Ljavax/security/auth/Subject;", AccessFlags = 9)]
				public static global::Javax.Security.Auth.Subject GetSubject(global::Java.Security.AccessControlContext context) /* MethodBuilder.Create */
				{
						return default(global::Javax.Security.Auth.Subject);
				}

				///
				///  <para>Returns this <c>Subject </c> 's Principal.</para> <para></para>
				///
				/// <returns>
				///  <para>this <c>Subject </c> 's Principal. </para>
				/// </returns>
				/// <java-name>
				/// getPrincipals
				/// </java-name>
				public global::Java.Util.ISet<global::Java.Security.IPrincipal> Principals
				{
						[Dot42.DexImport("getPrincipals", "()Ljava/util/Set;", AccessFlags = 1, Signature = "()Ljava/util/Set<Ljava/security/Principal;>;")]
						get{ return default(global::Java.Util.ISet<global::Java.Security.IPrincipal>); }
				}

				///
				///  <para>Returns the private credentials associated with this <c>Subject </c> .</para> <para></para>
				///
				/// <returns>
				///  <para>the private credentials associated with this <c>Subject </c> . </para>
				/// </returns>
				/// <java-name>
				/// getPrivateCredentials
				/// </java-name>
				public global::Java.Util.ISet<object> PrivateCredentials
				{
						[Dot42.DexImport("getPrivateCredentials", "()Ljava/util/Set;", AccessFlags = 1, Signature = "()Ljava/util/Set<Ljava/lang/Object;>;")]
						get{ return default(global::Java.Util.ISet<object>); }
				}

				///
				///  <para>Returns the public credentials associated with this <c>Subject </c> .</para> <para></para>
				///
				/// <returns>
				///  <para>the public credentials associated with this <c>Subject </c> . </para>
				/// </returns>
				/// <java-name>
				/// getPublicCredentials
				/// </java-name>
				public global::Java.Util.ISet<object> PublicCredentials
				{
						[Dot42.DexImport("getPublicCredentials", "()Ljava/util/Set;", AccessFlags = 1, Signature = "()Ljava/util/Set<Ljava/lang/Object;>;")]
						get{ return default(global::Java.Util.ISet<object>); }
				}

				///
				///  <para>Returns whether this <c>Subject </c> is read-only or not.</para> <para></para>
				///
				/// <returns>
				///  <para>whether this <c>Subject </c> is read-only or not. </para>
				/// </returns>
				/// <java-name>
				/// isReadOnly
				/// </java-name>
				public bool IsReadOnly
				{
						[Dot42.DexImport("isReadOnly", "()Z", AccessFlags = 1)]
						get{ return default(bool); }
				}

		}

		///
		///  <para>Legacy security code; do not use. </para>
		///
		/// <java-name>
		/// javax/security/auth/SubjectDomainCombiner
		/// </java-name>
		[Dot42.DexImport("javax/security/auth/SubjectDomainCombiner", AccessFlags = 33)]
		public partial class SubjectDomainCombiner : global::Java.Security.IDomainCombiner
 /* scope: __dot42__ */
		{
				[Dot42.DexImport("<init>", "(Ljavax/security/auth/Subject;)V", AccessFlags = 1)]
				public SubjectDomainCombiner(global::Javax.Security.Auth.Subject subject) /* MethodBuilder.Create */
				{
				}

				///
				///  <para>Returns a combination of the two provided <c>ProtectionDomain </c> arrays. Implementers can simply merge the two arrays into one, remove duplicates and perform other optimizations.</para> <para></para>
				///
				/// <returns>
				///  <para>a single <c>ProtectionDomain </c> array computed from the two provided arrays. </para>
				/// </returns>
				/// <java-name>
				/// combine
				/// </java-name>
				[Dot42.DexImport("combine", "([Ljava/security/ProtectionDomain;[Ljava/security/ProtectionDomain;)[Ljava/securi" +
    "ty/ProtectionDomain;", AccessFlags = 1)]
				public virtual global::Java.Security.ProtectionDomain[] Combine(global::Java.Security.ProtectionDomain[] current, global::Java.Security.ProtectionDomain[] assigned) /* MethodBuilder.Create */
				{
						return default(global::Java.Security.ProtectionDomain[]);
				}

				[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
				protected internal SubjectDomainCombiner() /* TypeBuilder.AddDefaultConstructor */
				{
				}

				/// <java-name>
				/// getSubject
				/// </java-name>
				public virtual global::Javax.Security.Auth.Subject Subject
				{
						[Dot42.DexImport("getSubject", "()Ljavax/security/auth/Subject;", AccessFlags = 1)]
						get{ return default(global::Javax.Security.Auth.Subject); }
				}

		}

}


text:
'use strict';

const debug = require('debug')('swagger-service-skeleton:error-handler');

module.exports = () =>
  (error, req, res, next) => {
    debug('ERROR Occured: %s', error);
    res.json({
      message: error.toString(),
      stack: error.stack,
    }, 500);
    next();
  };