text:
var $ = require('jquery');
var t = require('../../utils/translate');

require('jquery-ui/ui/core');
require('jquery-ui/ui/widget');
require('jquery-ui/ui/mouse');
require('jquery-ui/ui/draggable');
require('jquery-ui/ui/resizable');
require('jquery-ui/ui/button');
require('jquery-ui/ui/dialog');

var SideBarBookmarks = function($sidebar) {
    this.$sidebar = $sidebar;
};

SideBarBookmarks.prototype = {
    addBookmark: function($form, $container) {
        $.ajax({
            url: $form.attr('action'),
            method: $form.attr('method'),
            dataType: 'json',
            data: $form.serialize(),
            success: function (result) {
                if (result.error) {
                    return;
                }

                var $item = $container
                    .find('.bookmark-item.clone')
                    .clone()
                    .removeClass('clone');

                $item
                    .attr('href', result.url)
                    .find('.sidebar-link-label')
                    .append(result.title);
                $item
                    .find('.bookmarks-remove')
                    .data('bookmark-id', result.id);

                $container.append($item);
            }
        });
    },
    deleteBookmark: function($form, $item) {
        $.ajax({
            url: $form.attr('action'),
            method: $form.attr('method'),
            dataType: 'json',
            data: $form.serialize(),
            success: function (result) {
                if (result.error) {
                    return;
                }

                $item.remove();
            }
        });
    },
    initBookmarksAdding: function($sidebar) {
        var self = this;
        var $form = $sidebar.find('#bookmarks-add-form');
        var $titleInput = $form.find('input[name="title"]');
        var $urlInput = $form.find('input[name="url"]');
        var $dialog = $sidebar.find('#bookmarks-add-dialog');
        var $container = $sidebar.find('.bookmarks-list');

        $sidebar.find('.bookmarks-add').on('click', function(e) {
            e.preventDefault();

            var $link = $(this);
            var defaultTitle = $link.data('title') ? $link.data('title') : document.title;
            var url = window.location.href;

            $titleInput.val(defaultTitle);
            $urlInput.val(url);

            var buttons = {};

            buttons[t('Add')] = function() {
                self.addBookmark($form, $container);
                $(this).dialog('close');
            };

            buttons[t('Cancel')] = function() {
                $(this).dialog('close');
            };

            $dialog.dialog({
                resizable: false,
                modal: true,
                buttons: buttons
            });
        });
    },
    initBookmarksRemoving: function($sidebar) {
        var self = this;
        var $form = $sidebar.find('#bookmarks-remove-form');
        var $idInput = $form.find('input[name="id"]');
        var $dialog = $sidebar.find('#bookmarks-remove-dialog');

        $sidebar.on('click', '.bookmarks-remove', function(e) {
            e.preventDefault();

            var $remove = $(this);
            var $item = $remove.closest('.bookmark-item');
            var bookmarkId = $remove.data('bookmark-id');

            $idInput.val(bookmarkId);

            var buttons = {};

            buttons[t('Delete')] = function() {
                self.deleteBookmark($form, $item);
                $(this).dialog('close');
            };

            buttons[t('Cancel')] = function() {
                $(this).dialog('close');
            };

            $dialog.dialog({
                resizable: false,
                modal: true,
                buttons: buttons
            });
        });
    },
    initBookmarks: function($sidebar) {
        this.initBookmarksAdding($sidebar);
        this.initBookmarksRemoving($sidebar);
    },
    run: function() {
        try {
            this.initBookmarksAdding(this.$sidebar);
            this.initBookmarksRemoving(this.$sidebar);
        } catch (e) {
            console.error(e, e.stack);
        }
    }
};

module.exports = SideBarBookmarks;


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

    <meta http-equiv="Content-Language" content="en-ca" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" type="text/css" href="../style.css" />
    <title>int::parse Function</title>

            NAnt

          Help

          Function Reference
           int::parse

                        v0.86-beta1

int::parse

[This is preliminary documentation and subject to change.]

 Converts the specified string representation of a number to its 32-bit signed integer equivalent.

Usage

    int int::parse(s)

Parameters

          Name
          Type
          Description

          s
          string
          A string containing a number to convert.

Return Value
 A 32-bit signed integer equivalent to the number contained in s.
Exceptions

            The function will fail in any of the following circumstances:

s is not of the correct format.

s represents a number less than MinValue or greater than MaxValue.

Remarks
 The NumberFormatInfo for the invariant culture is used to supply formatting information about s.
Requirements

Assembly: NAnt.Core (0.86.2898.0)

redpajama_set_name: RedPajamaGithub


text:
module.exports = function(httpRequest, httpResponse, next){
    'use strict';
    httpResponse.setHeader('Access-Control-Allow-Origin', '*');
    httpResponse.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    httpResponse.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
    next();
};


text:
require File.dirname(__FILE__) + "/helper"

class ForNodeTest < NodeTestCase
  def test_failure
    initializer = AssignExprNode.new(NumberNode.new(10))
    decl = VarDeclNode.new('foo', initializer)
    stmt = VarStatementNode.new([decl])

    compare = LessNode.new(ResolveNode.new('foo'), NumberNode.new(10))
    exec = PostfixNode.new(ResolveNode.new('foo'), '++')

    block = BlockNode.new(SourceElementsNode.new([stmt]))

    node = ForNode.new(nil, nil, nil, block)
    assert_sexp([:for, nil, nil, nil, [:block, [[:var, [[:var_decl, :foo, [:assign, [:lit, 10]]]]]]]], node)

    node = ForNode.new(stmt, compare, exec, block)
    assert_sexp([:for,
                [:var, [[:var_decl, :foo, [:assign, [:lit, 10]]]]],
                [:less, [:resolve, 'foo'], [:lit, 10]],
                [:postfix, [:resolve, 'foo'], '++'],
                [:block, [[:var, [[:var_decl, :foo, [:assign, [:lit, 10]]]]]]]], node)
  end
end


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

<title>org.apache.poi.xssf.streaming (POI API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

org.apache.poi.xssf.streaming

Classes

GZIPSheetDataWriter

SheetDataWriter

SXSSFCell

SXSSFCreationHelper

SXSSFDrawing

SXSSFEvaluationWorkbook

SXSSFFormulaEvaluator

SXSSFPicture

SXSSFRow

SXSSFSheet

SXSSFWorkbook

Exceptions

SXSSFFormulaEvaluator.RowFlushedException

SXSSFFormulaEvaluator.SheetsFlushedException


text:
const /* Imports */
	_ = require('underscore'),
	_modulesList = require('./../../modules/modules'),
	_pluginsList = require('./../../../plugins/plugins');

var _modules, _plugins;

module.exports = {

	loadModules : function() {

		_modules = [];
		_.each(_modulesList.modules, function(m){

			_modules.push(require('./../../modules/' + m));
		});
	},

	getModules : function(){

		return _modules;
	},

	importPlugins : function() {
		_plugins = [];
		_.each(_pluginsList.modules, function(p){

			_plugins.push(require('./../../../plugins' + p));
		});
	},

	getPlugins : function(){

		return _plugins;
	}
};


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
in Sérusiaux, Berger, Brand & Boom, Lichenologist 39(1): 28 (2007)

#### Original name
Porina ocoteae Brand & Sérus.

### Remarks
null


text:
package com.ait.toolkit.sencha.touch.charts.client.events;

import com.google.gwt.event.shared.EventHandler;

public interface ItemMouseMoveHandler extends EventHandler {
	public void onItemMouseMove(ItemMouseMoveEvent event);
}


text:
namespace gpopt
{
using namespace gpos;

//---------------------------------------------------------------------------
//	@class:
//		CXformImplementConstTableGet
//
//	@doc:
//		Implement const table get
//
//---------------------------------------------------------------------------
class CXformImplementConstTableGet : public CXformImplementation
{
private:
	// private copy ctor
	CXformImplementConstTableGet(const CXformImplementConstTableGet &);

public:
	// ctor
	explicit CXformImplementConstTableGet(CMemoryPool *);

	// dtor
	virtual ~CXformImplementConstTableGet()
	{
	}

	// ident accessors
	virtual EXformId
	Exfid() const
	{
		return ExfImplementConstTableGet;
	}

	// return a string for xform name
	virtual const CHAR *
	SzId() const
	{
		return "CXformImplementConstTableGet";
	}

	// compute xform promise for a given expression handle
	virtual EXformPromise
	Exfp(CExpressionHandle &  // exprhdl
	) const
	{
		return CXform::ExfpHigh;
	}

	// actual transform
	void Transform(CXformContext *pxfctxt, CXformResult *pxfres,
				   CExpression *pexpr) const;

};	// class CXformImplementConstTableGet

}  // namespace gpopt

#endif	// !GPOPT_CXformImplementConstTableGet_H

// EOF


text:
package org.springframework.boot.cli.command.install;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.codehaus.groovy.control.CompilationFailedException;

import org.springframework.boot.cli.compiler.GroovyCompiler;
import org.springframework.boot.cli.compiler.GroovyCompilerConfiguration;

/**
 * A {@code DependencyResolver} implemented using Groovy's {@code @Grab}.
 *
 * @author Dave Syer
 * @author Andy Wilkinson
 */
class GroovyGrabDependencyResolver implements DependencyResolver {

	private final GroovyCompilerConfiguration configuration;

	GroovyGrabDependencyResolver(GroovyCompilerConfiguration configuration) {
		this.configuration = configuration;
	}

	@Override
	public List<File> resolve(List<String> artifactIdentifiers)
			throws CompilationFailedException, IOException {
		GroovyCompiler groovyCompiler = new GroovyCompiler(this.configuration);
		List<File> artifactFiles = new ArrayList<>();
		if (!artifactIdentifiers.isEmpty()) {
			List<URL> initialUrls = getClassPathUrls(groovyCompiler);
			groovyCompiler.compile(createSources(artifactIdentifiers));
			List<URL> artifactUrls = getClassPathUrls(groovyCompiler);
			artifactUrls.removeAll(initialUrls);
			for (URL artifactUrl : artifactUrls) {
				artifactFiles.add(toFile(artifactUrl));
			}
		}
		return artifactFiles;
	}

	private List<URL> getClassPathUrls(GroovyCompiler compiler) {
		return new ArrayList<>(Arrays.asList(compiler.getLoader().getURLs()));
	}

	private String createSources(List<String> artifactIdentifiers) throws IOException {
		File file = File.createTempFile("SpringCLIDependency", ".groovy");
		file.deleteOnExit();
		try (OutputStreamWriter stream = new OutputStreamWriter(
				new FileOutputStream(file), StandardCharsets.UTF_8)) {
			for (String artifactIdentifier : artifactIdentifiers) {
				stream.write("@Grab('" + artifactIdentifier + "')");
			}
			// Dummy class to force compiler to do grab
			stream.write("class Installer {}");
		}
		// Windows paths get tricky unless you work with URI
		return file.getAbsoluteFile().toURI().toString();
	}

	private File toFile(URL url) {
		try {
			return new File(url.toURI());
		}
		catch (URISyntaxException ex) {
			return new File(url.getPath());
		}
	}

}


text:
using namespace psy;
using namespace C;

const std::string Lexer::DiagnosticsReporter::ID_of_IncompatibleLanguageDialect = "Lexer-001";
const std::string Lexer::DiagnosticsReporter::ID_of_IncompatibleLanguageExtension = "Lexer-002";

void Lexer::DiagnosticsReporter::IncompatibleLanguageDialect(
        const std::string& feature,
        LanguageDialect::Std expectedStd)
{
    DiagnosticDescriptor descriptor(ID_of_IncompatibleLanguageDialect,
                                    "Incompatible language dialect",
                                    feature + " is available in " + to_string(expectedStd),
                                    DiagnosticSeverity::Warning,
                                    DiagnosticCategory::Syntax);

    lexer_->tree_->newDiagnostic(descriptor, lexer_->tree_->freeTokenSlot());
}

void Lexer::DiagnosticsReporter::IncompatibleLanguageExtension(
        const std::string& feature,
        LanguageExtensions::Ext expectedExt)
{
    DiagnosticDescriptor descriptor(ID_of_IncompatibleLanguageExtension,
                                    "Incompatible language extension",
                                    feature + " is available in " + to_string(expectedExt),
                                    DiagnosticSeverity::Warning,
                                    DiagnosticCategory::Syntax);

    lexer_->tree_->newDiagnostic(descriptor, lexer_->tree_->freeTokenSlot());
}


text:
import { Component } from "react";

import PropTypes from "prop-types";

import { section, formRow } from "uiTheme/radium/forms";

import { FieldWithError, TextField } from "components/Fields";
import AccelerationSection from "components/Forms/AccelerationSection";

import { applyValidators, isRequired } from "utils/validation";

import GeneralMixin from "dyn-load/components/Forms/GeneralMixin";

@GeneralMixin
export default class General extends Component {
  static propTypes = {
    fields: PropTypes.object,
    editing: PropTypes.bool,
    children: PropTypes.node,
    showAccelerationSection: PropTypes.bool,
    entityType: PropTypes.string,
  };

  static defaultProps = {
    showAccelerationSection: true,
  };

  static validate(values) {
    return {
      ...AccelerationSection.validate(values),
      ...applyValidators(values, [isRequired("name")]),
    };
  }

  render() {
    const {
      fields: { name },
      editing,
    } = this.props;

    // TextFields have a set width, so we override them using flexes here to use all the available space
    const fieldWithErrorStyle = {
      display: "flex",
      flex: 1,
      flexDirection: "column",
    };
    const fieldWithErrorDivStyle = { display: "flex", flex: 1 };
    const textStyle = { flex: 1, width: "100%" };

    return (

            <FieldWithError
              errorPlacement="bottom"
              label={la("Name")}
              {...name}
              style={fieldWithErrorStyle}
            >

                <TextField
                  initialFocus
                  {...name}
                  disabled={editing}
                  style={textStyle}
                />

            </FieldWithError>

        {this.props.children}
        {this.props.showAccelerationSection && (
          <AccelerationSection fields={this.props.fields} />
        )}
        {this.renderFooter(this.props.entityType)}

    );
  }
}


text:
/* ###
 * IP: GHIDRA
 *
 * 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.
 */
package agent.frida.model.impl;

import java.util.concurrent.CompletableFuture;

import agent.frida.model.iface2.FridaModelTargetProcess;
import ghidra.dbg.target.schema.*;
import ghidra.dbg.target.schema.TargetObjectSchema.ResyncMode;

@TargetObjectSchemaInfo(
	name = "Memory",
	elementResync = ResyncMode.ALWAYS,
	elements = {
		@TargetElementType(type = FridaModelTargetMemoryRegionImpl.class)
	},
	attributes = {
		@TargetAttributeType(type = Void.class)
	},
	canonicalContainer = true)
public class FridaModelTargetHeapMemoryContainerImpl extends FridaModelTargetMemoryContainerImpl {

	public FridaModelTargetHeapMemoryContainerImpl(FridaModelTargetProcess process) {
		super(process, "Memory (Heap)");
	}

	@Override
	public CompletableFuture<Void> requestElements(boolean refresh) {
		return getManager().listHeapMemory(process.getProcess());
	}

}


text:
@implementation BRModel

@end


text:
// (C) Copyright 2015 Martin Dougiamas
//
// 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.

angular.module('mm.addons.messages')

/**
 * Messages index controller.
 *
 * @module mm.addons.messages
 * @ngdoc controller
 * @name mmaMessagesIndexCtrl
 */
.controller('mmaMessagesIndexCtrl', function($scope, $mmEvents, $ionicPlatform, $ionicTabsDelegate,
            mmaMessagesDiscussionLoadedEvent, mmaMessagesDiscussionLeftEvent) {
    // Listen for discussion loaded event to show user profile link in tablet view.
    var obsLoaded = $mmEvents.on(mmaMessagesDiscussionLoadedEvent, function(userId) {
        $scope.profileLink = $ionicPlatform.isTablet() && $ionicTabsDelegate.selectedIndex() == 0;
        $scope.userId = userId;
    });

    // Listen for discussion loaded event to show user profile link in tablet view.
    var obsLeft = $mmEvents.on(mmaMessagesDiscussionLeftEvent, function() {
        $scope.profileLink = false;
    });

    $scope.$on('$destroy', function() {
        if (obsLoaded && obsLoaded.off) {
            obsLoaded.off();
        }
        if (obsLeft && obsLeft.off) {
            obsLeft.off();
        }
    });
});


text:
package giraudsa.marshall.deserialisation.binary.actions;

import java.io.IOException;
import java.lang.reflect.Array;

import giraudsa.marshall.deserialisation.ActionAbstrait;
import giraudsa.marshall.deserialisation.Unmarshaller;
import giraudsa.marshall.deserialisation.binary.ActionBinary;
import giraudsa.marshall.deserialisation.binary.BinaryUnmarshaller;
import giraudsa.marshall.exception.EntityManagerImplementationException;
import giraudsa.marshall.exception.InstanciationException;
import giraudsa.marshall.exception.NotImplementedSerializeException;
import giraudsa.marshall.exception.SetValueException;
import giraudsa.marshall.exception.UnmarshallExeption;
import utils.champ.FakeChamp;

@SuppressWarnings("rawtypes")
public class ActionBinaryArray<T> extends ActionBinary<T> {
	public static ActionAbstrait<Object> getInstance() { // NOSONAR
		return new ActionBinaryArray<>(Object.class, null);
	}

	private boolean deserialisationFini = false;
	private FakeChamp fakeChamp;
	private int index = 0;

	private int tailleCollection;

	private ActionBinaryArray(final Class<T> type, final BinaryUnmarshaller<?> b) {
		super(type, b);
	}

	@Override
	public void deserialisePariellement()
			throws ClassNotFoundException, NotImplementedSerializeException, IOException, UnmarshallExeption,
			InstanciationException, IllegalAccessException, EntityManagerImplementationException, SetValueException {
		if (!deserialisationFini)
			litObject(fakeChamp);
		else
			exporteObject();
	}

	@Override
	public <U extends T> ActionAbstrait<U> getNewInstance(final Class<U> type, final Unmarshaller unmarshaller) {
		return new ActionBinaryArray<>(type, (BinaryUnmarshaller<?>) unmarshaller);
	}

	@Override
	protected void initialise() throws IOException {

		final Class<?> componentType = fieldInformations.getValueType().getComponentType();
		fakeChamp = new FakeChamp(null, componentType, fieldInformations.getRelation(),
				fieldInformations.getAnnotations());
		if (isDejaVu() && !isDejaTotalementDeSerialise() && strategieDeSerialiseTout()) {
			obj = getObjet();
			tailleCollection = Array.getLength(obj);
			setDejaTotalementDeSerialise();
			deserialisationFini = index >= tailleCollection;
		} else if (isDejaVu()) { // il est soit déjà totalement désérialisé, soit il n'est pas à désérialiser
			deserialisationFini = true;
			obj = getObjet();
		} else { // !dejavu
			tailleCollection = readInt();
			obj = Array.newInstance(componentType, tailleCollection);
			stockeObjetId();
			if (strategieDeSerialiseTout())
				setDejaTotalementDeSerialise();
			deserialisationFini = index >= tailleCollection;
		}
	}

	@Override
	protected void integreObjet(final String nom, final Object objet) throws IllegalAccessException,
			EntityManagerImplementationException, InstanciationException, SetValueException {
		Array.set(obj, index++, objet);
		deserialisationFini = index >= tailleCollection;
		if (deserialisationFini)
			exporteObject();
	}
}


text:
import os

from pifpaf import drivers

class QdrouterdDriver(drivers.Driver):
    DEFAULT_PORT = 5672
    DEFAULT_ARTEMIS_PORT = 5673
    DEFAULT_USERNAME = "pifpaf"
    DEFAULT_PASSWORD = "secrete"
    DEFAULT_DOMAIN = "localhost"

    def __init__(self, port=DEFAULT_PORT,
                 artemis_port=DEFAULT_ARTEMIS_PORT,
                 username=DEFAULT_USERNAME,
                 password=DEFAULT_PASSWORD,
                 domain=DEFAULT_DOMAIN,
                 mesh=False,
                 direct_notify=False,
                 **kwargs):
        """Create a new Qdrouterd instance."""
        super(QdrouterdDriver, self).__init__(templatedir="qdrouterd",
                                              **kwargs)
        self.port = port
        self.artemis_port = artemis_port
        self.username = username
        self.password = password
        self.domain = domain
        self.mesh = mesh
        self.direct_notify = direct_notify

    @classmethod
    def get_options(cls):
        return [
            {"param_decls": ["--port"],
             "type": int,
             "default": cls.DEFAULT_PORT,
             "help": "port to use for Qdrouterd"},
            {"param_decls": ["--artemis_port"],
             "type": int,
             "default": cls.DEFAULT_ARTEMIS_PORT,
             "help": "port to use for broker link"},
            {"param_decls": ["--mesh"],
             "is_flag": True,
             "help": "TODO: Create a 3 HA node mesh"},
            {"param_decls": ["--direct_notify"],
             "is_flag": True,
             "help": "direct message notify and do not attach to broker"},
            {"param_decls": ["--username"],
             "default": cls.DEFAULT_USERNAME,
             "help": "sasl username"},
            {"param_decls": ["--password"],
             "default": cls.DEFAULT_PASSWORD,
             "help": "sasl password"},
            {"param_decls": ["--domain"],
             "default": cls.DEFAULT_DOMAIN,
             "help": "sasl domain"},
        ]

    def saslpasswd2(self, username, password, sasl_db):
        self._exec(["saslpasswd2", "-c", "-p", "-f",
                    sasl_db, username], stdin=password.encode())

    def _setUp(self):
        super(QdrouterdDriver, self)._setUp()

        # setup log, etc used by qdrouterd
        logdir = os.path.join(self.tempdir, "log")
        os.makedirs(logdir)
        etcdir = os.path.join(self.tempdir, "etc")
        os.makedirs(etcdir)
        sasldir = os.path.join(etcdir, "sasl2")
        os.makedirs(sasldir)
        logfile = os.path.join(logdir, "qdrouterd.log")

        template_env = {
            "TMP_DIR": self.tempdir,
            "PORT": self.port,
            "ARTEMIS_PORT": self.artemis_port,
            "SASL_DIR": sasldir,
            "LOG_FILE": logfile,
            "DIRECT_NOTIFY": self.direct_notify,
        }

        qdr_cfg = os.path.join(etcdir, "qdrouterd.conf")
        self.template("qdrouterd.conf",
                      template_env,
                      qdr_cfg)

        sasl_cfg = os.path.join(sasldir, "sasl_qdrouterd.conf")
        self.template("sasl_qdrouterd.conf",
                      template_env,
                      sasl_cfg)

        sasl_db = os.path.join(sasldir, "qdrouterd.sasldb")
        self.saslpasswd2(self.username, self.password, sasl_db)

        c, _ = self._exec(["qdrouterd", "-c", qdr_cfg],
                          wait_for_port=self.port)

        self.putenv("QDROUTERD_PORT", str(self.port))
        self.putenv("QDROUTERD_URL", "amqp://localhost:%s" % self.port)
        self.putenv("URL", "amqp://%s:%s@localhost:%s" % (
            self.username, self.password, self.port))


text:
<?php
return array(
    'router' => array(
        'routes' => array(
            'auth.rest.registration' => array(
                'type' => 'Segment',
                'options' => array(
                    'route' => '/auth/registration[/:registration_id]',
                    'defaults' => array(
                        'controller' => 'Auth\\V1\\Rest\\Registration\\Controller',
                    ),
                ),
            ),
        ),
    ),
    'zf-versioning' => array(
        'uri' => array(
            0 => 'auth.rest.registration',
        ),
    ),
    'zf-rest' => array(
        'Auth\\V1\\Rest\\Registration\\Controller' => array(
            'listener' => 'Auth\\V1\\Rest\\Registration\\RegistrationResource',
            'route_name' => 'auth.rest.registration',
            'route_identifier_name' => 'registration_id',
            'collection_name' => 'registration',
            'entity_http_methods' => array(),
            'collection_http_methods' => array(
                0 => 'POST',
            ),
            'collection_query_whitelist' => array(),
            'page_size' => 25,
            'page_size_param' => null,
            'entity_class' => 'Auth\\V1\\Rest\\Registration\\RegistrationEntity',
            'collection_class' => 'Auth\\V1\\Rest\\Registration\\RegistrationCollection',
            'service_name' => 'Registration',
        ),
    ),
    'zf-content-negotiation' => array(
        'controllers' => array(
            'Auth\\V1\\Rest\\Registration\\Controller' => 'HalJson',
        ),
        'accept_whitelist' => array(
            'Auth\\V1\\Rest\\Registration\\Controller' => array(
                0 => 'application/vnd.auth.v1+json',
                1 => 'application/hal+json',
                2 => 'application/json',
            ),
        ),
        'content_type_whitelist' => array(
            'Auth\\V1\\Rest\\Registration\\Controller' => array(
                0 => 'application/vnd.auth.v1+json',
                1 => 'application/json',
            ),
        ),
    ),
    'zf-hal' => array(
        'metadata_map' => array(
            'Auth\\V1\\Rest\\Registration\\RegistrationEntity' => array(
                'entity_identifier_name' => 'id',
                'route_name' => 'auth.rest.registration',
                'route_identifier_name' => 'registration_id',
                'hydrator' => 'Zend\\Stdlib\\Hydrator\\ArraySerializable',
            ),
            'Auth\\V1\\Rest\\Registration\\RegistrationCollection' => array(
                'entity_identifier_name' => 'id',
                'route_name' => 'auth.rest.registration',
                'route_identifier_name' => 'registration_id',
                'is_collection' => true,
            ),
        ),
    ),
    'zf-content-validation' => array(
        'Auth\\V1\\Rest\\Registration\\Controller' => array(
            'input_filter_specs' => 'Auth\\V1\\Rest\\Registration\\Validator',
        ),
    ),
    'input_filter_specs' => array(
        'Auth\\V1\\Rest\\Registration\\Validator' => array(
            0 => array(
                'name' => 'username',
                'required' => true,
                'filters' => array(),
                'validators' => array(
                    0 => array(
                        'name' => 'Zend\\Validator\\EmailAddress',
                        'options' => array(),
                    ),
                ),
            ),
            1 => array(
                'name' => 'password',
                'required' => true,
                'filters' => array(),
                'validators' => array(
                    0 => array(
                        'name' => 'Zend\\Validator\\StringLength',
                        'options' => array(
                            'min' => '6',
                        ),
                    ),
                ),
            ),
            2 => array(
                'name' => 'firstname',
                'required' => true,
                'filters' => array(),
                'validators' => array(
                    0 => array(
                        'name' => 'Zend\\I18n\\Validator\\Alpha',
                        'options' => array(),
                    ),
                ),
            ),
            3 => array(
                'name' => 'lastname',
                'required' => true,
                'filters' => array(),
                'validators' => array(
                    0 => array(
                        'name' => 'Zend\\I18n\\Validator\\Alpha',
                        'options' => array(),
                    ),
                ),
            ),
        ),
    ),
);


text:
package promplot

import (
	"context"
	"fmt"
	"io"
	"io/ioutil"
	"os"

	"github.com/slack-go/slack"
)

// Slack posts a file to a Slack channel.
func Slack(token, channel, title string, plot io.WriterTo) error {
	api := slack.New(token)

	if _, _, err := api.PostMessageContext(context.Background(), channel, slack.MsgOptionPostMessageParameters(
		slack.PostMessageParameters{
			Username:  "Promplot",
			IconEmoji: ":chart_with_upwards_trend:",
		},
	)); err != nil {
		return fmt.Errorf("failed to post message: %v", err)
	}

	f, err := ioutil.TempFile("", "promplot-")
	if err != nil {
		return fmt.Errorf("failed to create tmp file: %v", err)
	}

	defer func() {
		if err = f.Close(); err != nil {
			panic(fmt.Errorf("failed to close tmp file: %v", err))
		}
		if err = os.Remove(f.Name()); err != nil {
			panic(fmt.Errorf("failed to delete tmp file: %v", err))
		}
	}()

	if _, err = plot.WriteTo(f); err != nil {
		return fmt.Errorf("failed to write plot to file: %v", err)
	}

	if _, err = api.UploadFile(slack.FileUploadParameters{
		Title:    title,
		File:     f.Name(),
		Channels: []string{channel},
	}); err != nil {
		return fmt.Errorf("failed to upload file: %v", err)
	}

	return nil
}


text:
(function() {
  var C, Config;

  module.exports = C = function(repo, callback) {
    return repo.git("config", {
      list: true
    }, function(err, stdout, stderr) {
      var config;
      config = new Config(repo);
      config.parse(stdout);
      return callback(err, config);
    });
  };

  C.Config = Config = (function() {
    function Config(repo1) {
      this.repo = repo1;
    }

    Config.prototype.parse = function(text) {
      var i, key, len, line, ref, ref1, results, value;
      this.items = {};
      ref = text.split("\n");
      results = [];
      for (i = 0, len = ref.length; i < len; i++) {
        line = ref[i];
        if (line.length === 0) {
          continue;
        }
        ref1 = line.split('='), key = ref1[0], value = ref1[1];
        results.push(this.items[key] = value);
      }
      return results;
    };

    return Config;

  })();

}).call(this);


text:
// Copyright (C) 2020 The Android Open Source Project
//
// 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.

package com.google.gerrit.plugins.codeowners.backend;

/** Defines who owns paths for which no code owners are defined. */
public enum FallbackCodeOwners {
  /**
   * Paths for which no code owners are defined are owned by no one. This means changes that touch
   * these files can only be submitted with a code owner override.
   */
  NONE,

  /**
   * Paths for which no code owners are defined are owned by all users. This means changes to these
   * paths can be approved by anyone. If implicit approvals are enabled, these files are always
   * automatically approved.
   *
   * <p>The {@code ALL_USERS} option should only be used with care as it means that any path that is
   * not covered by the code owner config files is automatically opened up to everyone and mistakes
   * with configuring code owners can easily happen. This is why this option is intended to be only
   * used if requiring code owner approvals should not be enforced.
   */
  ALL_USERS;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ResGet.Models
{
    class ResourceFile
    {
        public string Filename { get; set; }
        public byte[] Content { get; set; }
    }
}


text:
#include "GLShaderBase.h"
#include "../HardwareBuffer/GLConstantBuffer.h"

#include "../GLExtensions.h"
#include "../GLParamMapper.h"
#include "../GLCore.h"

namespace Fork
{

namespace Video
{

GLShaderBase::GLShaderBase(const Shader::Types type)
{
    shaderID_ = glCreateShader(GLParamMapper::Map(type));
    ENSURE_GL_SHARED_CONTEXT_FOR_BUFFER("glCreateShader", shaderID_);
}
GLShaderBase::~GLShaderBase()
{
    ENSURE_GL_SHARED_CONTEXT_FOR_BUFFER("glDeleteShader", shaderID_);
    glDeleteShader(shaderID_);
}

bool GLShaderBase::Compile(const std::vector<std::string>& shaderSource, std::string& infoLog)
{
    SetupShaderSource(shaderSource);
    Compile();
    return QueryInfoLog(infoLog);
}

/*
 * ======= Private: =======
 */

void GLShaderBase::SetupShaderSource(const std::vector<std::string>& shaderSource)
{
    /* Get shader source raw pointers */
    const size_t numLines = shaderSource.size();

    std::vector<const GLchar*> sources(numLines);

    for (size_t i = 0, n = numLines; i < n; ++i)
        sources[i] = shaderSource[i].c_str();

    /* Setup sources to shader object */
    glShaderSource(shaderID_, numLines, sources.data(), nullptr);
}

void GLShaderBase::Compile()
{
    FLUSH_GL_ERROR;

    /* Compile shader */
    glCompileShader(shaderID_);

    SHOW_GL_ERROR("glCompileShader");
}

bool GLShaderBase::QueryInfoLog(std::string& infoLog)
{
    /* Query compilation status */
    GLint compileStatus = 0;
    glGetShaderiv(shaderID_, GL_COMPILE_STATUS, &compileStatus);

    /* Query info log length */
    GLint infoLogLength = 0;
    glGetShaderiv(shaderID_, GL_INFO_LOG_LENGTH, &infoLogLength);

    if (infoLogLength > 0)
    {
        /* Query info log output */
        GLsizei charsWritten = 0;
        infoLog.resize(infoLogLength);

        glGetShaderInfoLog(shaderID_, infoLogLength, &charsWritten, &infoLog[0]);

        GLAdjustString(infoLog);
    }
    else
        infoLog.clear();

    return compileStatus == GL_TRUE;
}

} // /namespace Video

} // /namespace Fork

// ========================


text:
MailHog [ ![Download](https://img.shields.io/github/release/mailhog/MailHog.svg) ](https://github.com/mailhog/MailHog/releases/tag/v1.0.0) [![GoDoc](https://godoc.org/github.com/mailhog/MailHog?status.svg)](https://godoc.org/github.com/mailhog/MailHog) [![Build Status](https://travis-ci.org/mailhog/MailHog.svg?branch=master)](https://travis-ci.org/mailhog/MailHog)
=========

Inspired by [MailCatcher](https://mailcatcher.me/), easier to install.

* Download and run MailHog
* Configure your outgoing SMTP server
* View your outgoing email in a web UI
* Release it to a real mail server

Built with Go - MailHog runs without installation on multiple platforms.

### Overview

MailHog is an email testing tool for developers:

* Configure your application to use MailHog for SMTP delivery
* View messages in the web UI, or retrieve them with the JSON API
* Optionally release messages to real SMTP servers for delivery

### Installation

#### Manual installation
[Download the latest release for your platform](/docs/RELEASES.md). Then
[read the deployment guide](/docs/DEPLOY.md) for deployment options.

#### MacOS
```bash
brew update && brew install mailhog
```

Then, start MailHog by running `mailhog` in the command line.

#### Debian / Ubuntu Go < v1.18
```bash
sudo apt-get -y install golang-go
go get github.com/mailhog/MailHog
```

#### Go >= v1.17 (Debian Bookworm)
```bash
sudo apt-get -y install golang-go
go install github.com/mailhog/MailHog@latest
```

Then, start MailHog by running `/path/to/MailHog` in the command line.

E.g. the path to Go's bin files on Ubuntu is `~/go/bin/`, so to start the MailHog run:

```bash
~/go/bin/MailHog
```

#### FreeBSD
```bash
pkg install mailhog
sysrc mailhog_enable="YES"
service mailhog start
```

#### Docker
[Run it from Docker Hub](https://registry.hub.docker.com/r/mailhog/mailhog/) or using the provided [Dockerfile](Dockerfile)

### Configuration

Check out how to [configure MailHog](/docs/CONFIG.md), or use the default settings:
  * the SMTP server starts on port 1025
  * the HTTP server starts on port 8025
  * in-memory message storage

### Features

See [MailHog libraries](docs/LIBRARIES.md) for a list of MailHog client libraries.

* ESMTP server implementing RFC5321
* Support for SMTP AUTH (RFC4954) and PIPELINING (RFC2920)
* Web interface to view messages (plain text, HTML or source)
  * Supports RFC2047 encoded headers
* Real-time updates using EventSource
* Release messages to real SMTP servers
* Chaos Monkey for failure testing
  * See [Introduction to Jim](/docs/JIM.md) for more information
* HTTP API to list, retrieve and delete messages
  * See [APIv1](/docs/APIv1.md) and [APIv2](/docs/APIv2.md) documentation for more information
* [HTTP basic authentication](docs/Auth.md) for MailHog UI and API
* Multipart MIME support
* Download individual MIME parts
* In-memory message storage
* MongoDB and file based storage for message persistence
* Lightweight and portable
* No installation required

#### sendmail

[mhsendmail](https://github.com/mailhog/mhsendmail) is a sendmail replacement for MailHog.

It redirects mail to MailHog using SMTP.

You can also use `MailHog sendmail ...` instead of the separate mhsendmail binary.

Alternatively, you can use your native `sendmail` command by providing `-S`, for example:

```bash
/usr/sbin/sendmail -S mail:1025
```

For example, in PHP you could add either of these lines to `php.ini`:

```
sendmail_path = /usr/local/bin/mhsendmail
sendmail_path = /usr/sbin/sendmail -S mail:1025
```

#### Web UI

![Screenshot of MailHog web interface](/docs/MailHog.png "MailHog web interface")

### Contributing

MailHog is a rewritten version of [MailHog](https://github.com/ian-kent/MailHog), which was born out of [M3MTA](https://github.com/ian-kent/M3MTA).

Clone this repository to ```$GOPATH/src/github.com/mailhog/MailHog``` and type ```make deps```.

See the [Building MailHog](/docs/BUILD.md) guide.

Requires Go 1.4+ to build.

Run tests using ```make test``` or ```goconvey```.

If you make any changes, run ```go fmt ./...``` before submitting a pull request.

### Licence

Copyright © 2014 - 2017, Ian Kent (http://iankent.uk)

Released under MIT license, see [LICENSE](LICENSE.md) for details.


text:
<?php

/**
 * Shipment view form
 *
 * @category   Mage
 * @package    Mage_Adminhtml
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Adminhtml_Block_Sales_Order_Shipment_View_Form extends Mage_Adminhtml_Block_Sales_Order_Abstract
{
    /**
     * Retrieve shipment model instance
     *
     * @return Mage_Sales_Model_Order_Shipment
     */
    public function getShipment()
    {
        return Mage::registry('current_shipment');
    }

    /**
     * Retrieve invoice order
     *
     * @return Mage_Sales_Model_Order
     */
    public function getOrder()
    {
        return $this->getShipment()->getOrder();
    }

    /**
     * Retrieve source
     *
     * @return Mage_Sales_Model_Order_Shipment
     */
    public function getSource()
    {
        return $this->getShipment();
    }

    /**
     * Get create label button html
     *
     * @return string
     */
    public function getCreateLabelButton()
    {
        $data['shipment_id'] = $this->getShipment()->getId();
        $url = $this->getUrl('*/sales_order_shipment/createLabel', $data);
        return $this->getLayout()
            ->createBlock('adminhtml/widget_button')
            ->setData(array(
                'label'   => Mage::helper('sales')->__('Create Shipping Label...'),
                'onclick' => 'packaging.showWindow();',
            ))
            ->toHtml();
    }

    /**
     * Get print label button html
     *
     * @return string
     */
    public function getPrintLabelButton()
    {
        $data['shipment_id'] = $this->getShipment()->getId();
        $url = $this->getUrl('*/sales_order_shipment/printLabel', $data);
        return $this->getLayout()
            ->createBlock('adminhtml/widget_button')
            ->setData(array(
                'label'   => Mage::helper('sales')->__('Print Shipping Label'),
                'onclick' => 'setLocation(\'' . $url . '\')'
            ))
            ->toHtml();
    }

    /**
     * Show packages button html
     *
     * @return string
     */
    public function getShowPackagesButton()
    {
        return $this->getLayout()
            ->createBlock('adminhtml/widget_button')
            ->setData(array(
                'label'   => Mage::helper('sales')->__('Show Packages'),
                'onclick' => 'showPackedWindow();'
            ))
            ->toHtml();
    }

    /**
     * Check is carrier has functionality of creation shipping labels
     *
     * @return bool
     */
    public function canCreateShippingLabel()
    {
        $shippingCarrier = $this->getOrder()->getShippingCarrier();
        return $shippingCarrier && $shippingCarrier->isShippingLabelsAvailable();
    }
}


text:
import badgerlib
import ctypes
import time

class PopupHandler(badgerlib.Handler):
    MB_ICONEXCLAMATION = 0x30
    MB_SYSTEMMODAL = 0x1000
    MB_SERVICE_NOTIFICATION = 0x200000L
    MB_SETFOREGROUND = 0x00010000L
    MB_TOPMOST = 0x00040000L

    def __init__(self, config=None):
        badgerlib.Handler.__init__(self, config)
        self.enable = False
        self.delay = 0.5
        self.message = "Smartcard Still Inserted"
        if self.config:
            self.enable = self.config.get("enable", True)
            self.delay = self.config.get("delay", self.delay)
            self.message = self.config.get("message", self.message)

    def on_lock(self, state):
        if not state.get_inserted() or not self.enable:
            return
        self.alert_threaded()

    #overrides badgerlib.Handler.alert()
    def alert(self, **keywords):
        #TODO: This is technically not thread safe if we ever allow modifying params at runtime
        #Should use the keyword args
        time.sleep(self.delay)
        ctypes.windll.User32.MessageBoxA(None, self.message, "Badger",
            self.MB_SERVICE_NOTIFICATION | self.MB_ICONEXCLAMATION | self.MB_SYSTEMMODAL)


text:
require 'tfc/leagues/active_admin/base'

ActiveAdmin.register Tfc::Leagues::Club do
  Tfc::Leagues::ActiveAdmin::Base.configure(self)

  form do |f|
    f.inputs do
      f.input :name
    end

    f.inputs do
      f.input :description
      f.input :markup_language, :as => :select, :collection => Tfc::Leagues::Configuration.markup_languages.map(&:to_s)
    end

    f.actions
  end # form
end if defined?(ActiveAdmin)


text:
package main

import (
	"bytes"
	"encoding/json"
	"encoding/xml"
	"fmt"
	"github.com/animezb/newsroverd/extract"
	"github.com/animezb/newsroverd/sinks/elasticsink"
	"github.com/codegangsta/martini"
	"io"
	"io/ioutil"
	"net/http"
	"strings"
)

const (
	NZB_XMLNS = "http://www.newzbin.com/DTD/2003/nzb"
)

type nzb struct {
	name  xml.Name  `xml:"nzb"`
	Xmlns string    `xml:"xmlns,attr"`
	Head  []NzbMeta `xml:"head>meta"`
	Files []NzbFile `xml:"file"`
}

type NzbMeta struct {
	Type  string `xml:"type,attr"`
	Value string `xml:",innerxml"`
}

type NzbFile struct {
	Id       string       `xml:"-"`
	Name     string       `xml:"-"`
	Parts    int          `xml:"-"`
	Length   int          `xml:"-"`
	Bytes    int64        `xml:"-"`
	Poster   string       `xml:"poster,attr"`
	Date     int64        `xml:"date,attr"`
	Subject  string       `xml:"subject,attr"`
	Groups   []string     `xml:"groups>group"`
	Segments []NzbSegment `xml:"segments>segment"`
}

type NzbSegment struct {
	Bytes     uint32 `xml:"bytes,attr"`
	Number    uint32 `xml:"number,attr"`
	MessageId string `xml:",innerxml"`
}

type esFileResp struct {
	Hits struct {
		Hits []struct {
			Id     string           `json:"_id"`
			Source elasticsink.File `json:"_source"`
		} `json:"hits"`
	} `json:"hits"`
}

type esSegmentResp struct {
	Hits struct {
		Hits []struct {
			Id     string              `json:"_id"`
			Source elasticsink.Segment `json:"_source"`
		} `json:"hits"`
	} `json:"hits"`
}

func gennzb(ctx *context, params martini.Params, res http.ResponseWriter, req *http.Request) {
	var uploads []string
	if req.Method == "GET" {
		uploads = []string{params["nzbid"]}
	} else if req.Method == "POST" {
		req.ParseForm()
		uploads = req.PostForm["nzb"]
	}
	nzbdl := nzb{
		Xmlns: NZB_XMLNS,
		Files: make([]NzbFile, 0, 16),
	}
	nzbName := params["nzbname"]
	if nzbName == "" && len(uploads) > 0 {
		nzbName = getName(ctx, uploads[0])
	}
	res.Header().Set("Content-Type", "text/html")
	for _, upload := range uploads {
		uploadFiles := getFiles(ctx, upload)
		for _, f := range uploadFiles {
			if nzbName == "" {
				nzbName = f.Name
			}
			f.Segments = getSegments(ctx, f.Id)
			nzbdl.Files = append(nzbdl.Files, f)
		}
	}
	if !strings.HasSuffix(nzbName, ".nzb") {
		nzbName += ".nzb"
	}
	if output, err := xml.Marshal(nzbdl); err == nil {
		res.Header().Set("Content-Type", "application/x-nzb")
		res.Header().Set("Content-Disposition", "attachment; filename=\""+nzbName+"\"")
		res.WriteHeader(200)
		res.Write([]byte(xml.Header))
		res.Write([]byte(`<!DOCTYPE nzb PUBLIC "-//newzBin//DTD NZB 1.0//EN" "http://www.newzbin.com/DTD/nzb/nzb-1.0.dtd">` + "\n"))
		res.Write(output)
	} else {
		panic(err)
	}
}

func getName(ctx *context, upload string) string {
	newReq, err := http.NewRequest("GET", fmt.Sprintf("http://%s:%d/nzb/upload/%s?_source_include=fileprefix", ctx.EsHost, ctx.EsPort, upload), nil)
	resp, err := http.DefaultClient.Do(newReq)
	if err != nil {
		panic(err)
	}
	defer io.Copy(ioutil.Discard, resp.Body)
	defer resp.Body.Close()
	decoder := json.NewDecoder(resp.Body)
	var esResp struct {
		Source struct {
			Name string `json:"fileprefix"`
		} `json:"_source"`
		Found bool `json:"found"`
	}
	err = decoder.Decode(&esResp)
	if err != nil {
		panic(err)
	}
	return strings.TrimSuffix(esResp.Source.Name, ".")
}

func getFiles(ctx *context, upload string) []NzbFile {
	query := map[string]interface{}{
		"filter": map[string]interface{}{
			"term": map[string]interface{}{
				"_routing": upload,
			},
		},
		"size": 16384,
	}
	b, err := json.Marshal(query)
	if err != nil {
		panic(err)
	}

	reader := bytes.NewReader(b)
	newReq, err := http.NewRequest("POST", fmt.Sprintf("http://%s:%d/nzb/file/_search?_source_exclude=segments", ctx.EsHost, ctx.EsPort), reader)
	newReq.Header.Set("Content-Type", "application/json")
	resp, err := http.DefaultClient.Do(newReq)
	if err != nil {
		panic(err)
	}
	defer io.Copy(ioutil.Discard, resp.Body)
	defer resp.Body.Close()

	decoder := json.NewDecoder(resp.Body)
	var esResp esFileResp
	err = decoder.Decode(&esResp)
	if err != nil {
		panic(err)
	}
	results := make([]NzbFile, len(esResp.Hits.Hits))
	for idx, hit := range esResp.Hits.Hits {
		nzbf := NzbFile{
			Id:      hit.Id,
			Name:    hit.Source.Filename,
			Poster:  hit.Source.Poster,
			Date:    hit.Source.Date.Unix(),
			Subject: ensureFirstPart(hit.Source.Subject),
			Groups:  hit.Source.Group,
			Parts:   hit.Source.Complete,
			Length:  hit.Source.Length,
			Bytes:   hit.Source.Size,
		}
		results[idx] = nzbf
	}
	return results
}

func ensureFirstPart(subject string) string {
	/* SabNzbd won't properly extract without this */
	part := extract.ExtractYencPart(subject)
	if part != 1 {
		length := extract.ExtractYencLength(subject)
		nsubject := strings.Replace(subject, fmt.Sprintf("(%d/%d)", part, length), fmt.Sprintf("(1/%d)", length), 1)
		if nsubject == subject {
			nsubject = strings.Replace(subject, fmt.Sprintf("(%02d/%d)", part, length), fmt.Sprintf("(01/%d)", length), 1)
		}
		if nsubject == subject {
			nsubject = strings.Replace(subject, fmt.Sprintf("(%03d/%d)", part, length), fmt.Sprintf("(001/%d)", length), 1)
		}
		if nsubject == subject {
			nsubject = strings.Replace(subject, fmt.Sprintf("(%04d/%d)", part, length), fmt.Sprintf("(001/%d)", length), 1)
		}
		subject = nsubject
	}
	return subject
}

func getSegments(ctx *context, fileId string) []NzbSegment {
	query := map[string]interface{}{
		"filter": map[string]interface{}{
			"term": map[string]interface{}{
				"_routing": fileId,
			},
		},
		"size": 65536,
	}
	b, err := json.Marshal(query)
	if err != nil {
		panic(err)
	}

	reader := bytes.NewReader(b)
	newReq, err := http.NewRequest("POST", fmt.Sprintf("http://%s:%d/nzb/segment/_search", ctx.EsHost, ctx.EsPort), reader)
	newReq.Header.Set("Content-Type", "application/json")
	resp, err := http.DefaultClient.Do(newReq)
	if err != nil {
		panic(err)
	}

	defer io.Copy(ioutil.Discard, resp.Body)
	defer resp.Body.Close()

	decoder := json.NewDecoder(resp.Body)
	var esResp esSegmentResp
	err = decoder.Decode(&esResp)
	if err != nil {
		panic(err)
	}
	results := make([]NzbSegment, len(esResp.Hits.Hits))
	for idx, hit := range esResp.Hits.Hits {
		nzbsg := NzbSegment{
			Bytes:     uint32(hit.Source.Bytes),
			Number:    uint32(hit.Source.Part),
			MessageId: strings.TrimSuffix(strings.TrimPrefix(hit.Source.MessageId, "<"), ">"),
		}
		results[idx] = nzbsg
	}
	return results
}


text:
(function () {
    'use strict';
    angular.module('gestionBayres.main', [['bower_components/ac-angular-cajas/ac-encomiendas.js',
            'bower_components/ac-angular-cajas/ac-encomiendas-administracion.js']])
        .controller('MainController', MainController);

    MainController.$inject = ['CajasService', 'UserService', 'StockService', 'EncomiendasService', 'PedidoVars', 'PedidoService', '$location'];
    function MainController(CajasService, UserService, StockService, EncomiendasService, PedidoVars, PedidoService, $location) {

        var vm = this;

        vm.saldoFinal = 0;
        vm.saldoInicial = 0;
        vm.ahorro = 0;
        vm.reponer = [];
        vm.encomiendas = [];
        vm.pedidos = [];
        vm.showCaja = true;
        vm.showProducto = true;
        vm.showEncomienda = true;
        vm.showPedido = true;
        vm.cliente;
        vm.pedido;
        vm.producto;

        //FUNCIONES
        vm.goToPagina = goToPagina;
        vm.removeProducto = removeProducto;
        vm.removeEncomienda = removeEncomienda;
        vm.removePedido = removePedido;
        vm.detalleProducto = detalleProducto;
        vm.detalleEncomienda = detalleEncomienda;

        function goToPagina(pagina) {
            $location.path(pagina);
        }

        function removeProducto(producto) {
            console.log(producto);

            if (confirm("¿Esta seguro que desea borrar el producto " + producto.nombre + "?") == true) {
                console.log('borrar producto');
            } else {
                console.log('No se borra el producto');
            }
        }

        function removeEncomienda(cliente) {
            console.log(cliente);

            if (confirm("¿Esta seguro que desea borrar la encomienda del cliente " + cliente.cliente + "?") == true) {
                console.log('borrar encomienda');
            } else {
                console.log('No se borra la encomienda');
            }
        }

        function removePedido(pedido) {
            console.log(pedido);

            if (confirm("¿Esta seguro que desea borrar el pedido " + pedido + "?") == true) {
                console.log('borrar pedido');
            } else {
                console.log('No se borra el pedido');
            }
        }

        function detalleProducto(producto) {
            console.log(producto);
        }

        function detalleEncomienda(encomenda) {
            console.log(encomenda);
        }

        PedidoVars.all = false;
        PedidoService.get(
            function (data) {
                vm.pedidos = data;
                //console.log(vm.pedidos);
            }
        );

        EncomiendasService.get(false).then(function (data) {
            for (var i = 0; i < data.length; i++) {
                data[i].fecha_entrega = (new Date(data[i].fecha_entrega)).getDate() + '/' + ((new Date(data[i].fecha_entrega)).getMonth() + 1) + '/'+ (new Date(data[i].fecha_entrega)).getFullYear();
            }

            vm.encomiendas = data;
        });

        StockService.getAReponer(UserService.getFromToken().data.sucursal_id).then(function (data) {
            data.sort(function (a, b) {
                return a.nombre - b.nombre;
            });

            vm.reponer = data;
        });

        CajasService.getSaldoInicial(UserService.getFromToken().data.sucursal_id, UserService.getFromToken().data.caja_id, function (data) {

            vm.saldoInicial = parseFloat(data.replace('"', ''));
            vm.saldoFinal = vm.saldoInicial;
            CajasService.getCajaDiaria(UserService.getFromToken().data.sucursal_id, UserService.getFromToken().data.caja_id, function (data) {
                var asientos = [];
                var detalles = [];
                var asiento = {};

                for (var i = 0; i < data.length; i++) {
                    for (var x = 0; x < data[i].movimientos.length; x++) {

                        //agrego el movimiento de caja - Estos son los totales que aparecen al final del movimiento

                        if (data[i].movimientos[x].cuenta_id.indexOf('1.1.1.0') > -1 || // Caja chica
                            data[i].movimientos[x].cuenta_id.indexOf('1.1.2.0') > -1 || // Deudores
                            data[i].movimientos[x].cuenta_id.indexOf('1.1.4.0') > -1 || // Tarjeta
                            data[i].movimientos[x].cuenta_id.indexOf('2.1.1.0') > -1 || // Proveedores a deuda
                            data[i].movimientos[x].cuenta_id.indexOf('1.1.1.2') > -1    // CC CA MP ML
                        ) {

                            if (data[i].movimientos[x].cuenta_id.indexOf('1.1.1.0') > -1) {
                                vm.saldoFinal += parseFloat(data[i].movimientos[x].importe);
                            }
                        }

                    }
                }

            });
        });

        func();
        function func() {
            CajasService.getTotalByCuenta('1.1.1.3' + UserService.getFromToken().data.sucursal_id, UserService.getFromToken().data.sucursal_id, function (data) {
                console.log(data);
                if (data[0] == undefined) {

                    vm.ahorro = 0;
                } else {

                    vm.ahorro = data[0].importe;
                    CajasService.getResultado('1.1.1.3' + UserService.getFromToken().data.sucursal_id, function (data) {
                        console.log(data);
                        vm.ahorro = parseFloat(vm.ahorro) + parseFloat(data[0].total);
                    });
                }
            });
        }

    }
})();


text:
from google.cloud import storage

def list_buckets():
    """Lists all buckets."""

    storage_client = storage.Client()
    buckets = storage_client.list_buckets()

    for bucket in buckets:
        print(bucket.name)

# [END storage_list_buckets]

if __name__ == "__main__":
    list_buckets()


text:
<?php

namespace app\modules\job\controllers\backend;

use Yii;
use yii\data\ActiveDataProvider;
use app\components\BackendController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

use app\modules\job\models\User;
use app\modules\job\models\UserJob;
use app\modules\job\models\UserJobSeekerResume;

/**
 * AccountController implements the CRUD actions for UserJob model.
 */
class AccountController extends BackendController
{

    public function behaviors() {
        $data = [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
        return array_merge(parent::behaviors(), $data);
    }

    /**
     * Lists all UserJob models.
     * @return mixed
     */
    public function actionIndex()
    {
        $queryParams = Yii::$app->request->getQueryParams();

        $searchModel = new UserJob;
        $searchModel->scenario = 'search';
        $dataProvider = $searchModel->search($queryParams);

        Yii::$app->view->title = Yii::t($this->module->id, 'Manage Members');
        Yii::$app->view->params['breadcrumbs'][] = ['label' => Yii::t($this->module->id, 'Manage Members'), 'url' => ['index']];

        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel
        ]);
    }

    /**
     * Displays a single UserJob model.
     * @param integer $_id
     * @return mixed
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);

        Yii::$app->view->title = $model->user->email;
        Yii::$app->view->params['breadcrumbs'][] = ['label' => Yii::t($this->module->id, 'Manage Members'), 'url' => ['index']];

        return $this->render('view', [
            'model' => $model
        ]);
    }

    /**
     * Updates an existing UserJob model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $_id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $modelUser = User::findOne($id);
        $modelUserJob = UserJob::findOne($id);

        if (!isset($modelUser, $modelUserJob)) {
            throw new NotFoundHttpException("The user was not found.");
        }

        if ($modelUser->load(Yii::$app->request->post()) && $modelUserJob->load(Yii::$app->request->post())) {
            $modelUserValidate = $modelUser->validate();
            $modelUserJobValidate = $modelUserJob->validate();

            if ($modelUserValidate && $modelUserJobValidate) {
                $modelUserJob->email = $modelUser->email;

                if ($modelUser->save(false) && $modelUserJob->save(false)) {
                    if ($modelUserJob->role == 'seeker') {
                        UserJobSeekerResume::updateAll(['nationality' => $modelUserJob->seeker_nationality, 'salary' => $modelUserJob->seeker_salary], ['_id' => $modelUserJob->_id]);
                    }

                    if (Yii::$app->request->post('save_type') !== 'apply') {
                        return $this->redirect(['view', 'id' => (string) $modelUser->_id]);
                    }
                }
            }
        }

        Yii::$app->view->title = Yii::t('yii', 'Update');
        Yii::$app->view->params['breadcrumbs'][] = ['label' => Yii::t($this->module->id, 'Manage Members'), 'url' => ['index']];
        Yii::$app->view->params['breadcrumbs'][] = Yii::$app->view->title;

        return $this->render('form', [
            'modelUser' => $modelUser,
            'modelUserJob' => $modelUserJob,
        ]);
    }

    /**
     * Deletes an existing UserJob model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $_id
     * @return mixed
     */
    public function actionDelete($id)
    {
        if (!Yii::$app->user->can(UserJob::moduleName() . ':delete'))
            return $this->render('//message', ['messages' => ['danger' => Yii::t('yii', 'You are not allowed to perform this action.')]]);

        $this->findModel($id)->delete();
        return $this->redirect(['index']);
    }

    /**
     * Finds the UserJob model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $_id
     * @return UserJob the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = UserJob::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
module.exports = {
	register: register
};

function register(server, options, next) {
	if (!options.enabled) {
		next();
		return;
	}

	var basePath = options.base || '';
	var providerSettings = Object.create(options.provider);

	server.auth.strategy('google-oauth', 'bell', options.provider);

	server.route([
		{
			method: ['POST', 'GET'],
			path: options.basePath.concat('/google'),
			handler: function(req, reply) {
				if (req.auth.isAuthenticated) {
					req.session.set('credentials', req.auth.credentials);
					reply.redirect(options.basePath.concat('/google/callback'));
				}
				else {
					return reply(Boom.create(401, 'Failed auth'));
				}
			},
			config: {
				auth: {
					strategy: 'google-oauth'
				}
			}
		}
	]);

	next();
}

register.attributes = {
	name: 'perse-web-google-provider',
	version: '0.5.0'
};


text:
package vStrikerTestEngine.swift;

import java.util.concurrent.Callable;

import org.apache.commons.io.FilenameUtils;

import vStrikerEntities.Api;
import vStrikerEntities.ExecutionReportData;

import com.emc.vipr.swift.swiftapi;

//@author Sanjeev Chauhan

public class SwiftDeleteWorker implements Callable<ExecutionReportData> {

	private String objectLocation;
	private Api api;
	ExecutionReportData reportData = new ExecutionReportData();

	/*
	 * Default Constructor
	 */
	public SwiftDeleteWorker(){
	}

	/*
	 * Constructor
	 */
	public SwiftDeleteWorker(String objectLocation, Api api) {
		this.api = api;
		this.objectLocation = objectLocation;
	}

	public ExecutionReportData call() throws Exception {
		reportData.setDataKey("Swift");
		reportData.setCrudValue("Delete");
		try{
			long startTime = System.nanoTime();

		swiftapi.DeleteObject(api.getSubtenant(), api.getSecretKey(),
						api.getUrl(), api.getBucket(), FilenameUtils.getName(objectLocation));
		long endTime = System.nanoTime();
		reportData.setThreadValue(Thread.currentThread().getName());
		reportData.setDataValue(Long.toString((endTime-startTime)/1000000));
	} catch (Exception e) {
		reportData.setDataValue(e.getMessage());
	}
		return reportData;
	}
}


text:
from ..requests import Request

__all__ = ("ExpirationPolicy",)

class ExpirationPolicy:
    async def is_expired(self, request: Request) -> bool:
        raise NotImplementedError()

    def __repr__(self) -> str:
        return f"{self.__class__.__qualname__}()"


text:
require 'serf/command'

require 'moogle/error'
require 'moogle/events/target_updated'
require 'moogle/requests/update_target'
require 'moogle/models'

module Moogle
module Commands

  class UpdateTarget
    include Serf::Command

    self.request_factory = Moogle::Requests::UpdateTarget

    def call
      target_model = opts :target_model, Moogle::Target
      event_class = opts :event_class, Moogle::Events::TargetUpdated
      representer = opts :representer, Moogle::TargetRepresenter

      target = target_model.get request.target_id
      raise '404 Not found' unless target

      result = target.update update_params
      raise target.errors.full_messages.join('; ') unless target.saved?

      target_rep = target.dup.extend representer

      return event_class.new request.create_child_uuids.merge(target: target)
    rescue => e
      e.extend Moogle::Error
      raise e
    end

    protected

    def update_params
      { options: request.options }
    end

  end

end
end


text:
using System.IO;
using System.Runtime.InteropServices;

namespace System.Drawing.Text
{

    public sealed class PrivateFontCollection : FontCollection
    {

        // constructors

        public PrivateFontCollection()
        {
            Status status = SafeNativeMethods.Gdip.GdipNewPrivateFontCollection(out _nativeFontCollection);
            SafeNativeMethods.Gdip.CheckStatus(status);
        }

        // methods
        public void AddFontFile(string filename)
        {
            if (filename == null)
                throw new ArgumentNullException("filename");

            // this ensure the filename is valid (or throw the correct exception)
            string fname = Path.GetFullPath(filename);

            if (!File.Exists(fname))
                throw new FileNotFoundException();

            // note: MS throw the same exception FileNotFoundException if the file exists but isn't a valid font file
            Status status = SafeNativeMethods.Gdip.GdipPrivateAddFontFile(_nativeFontCollection, fname);
            SafeNativeMethods.Gdip.CheckStatus(status);
        }

        public void AddMemoryFont(IntPtr memory, int length)
        {
            // note: MS throw FileNotFoundException if something is bad with the data (except for a null pointer)
            Status status = SafeNativeMethods.Gdip.GdipPrivateAddMemoryFont(_nativeFontCollection, memory, length);
            SafeNativeMethods.Gdip.CheckStatus(status);
        }

        // methods
        protected override void Dispose(bool disposing)
        {
            if (_nativeFontCollection != IntPtr.Zero)
            {
                SafeNativeMethods.Gdip.GdipDeletePrivateFontCollection(ref _nativeFontCollection);

                // This must be zeroed out, otherwise our base will also call
                // the GDI+ delete method on unix platforms. We're keeping the
                // base.Dispose() call in case other cleanup ever gets added there
                _nativeFontCollection = IntPtr.Zero;
            }

            base.Dispose(disposing);
        }
    }
}


text:
package authentication

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"encoding/base64"
	"errors"
	"io"
)

func Encrypt(key, text []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	b := base64.StdEncoding.EncodeToString(text)
	ciphertext := make([]byte, aes.BlockSize+len(b))
	iv := ciphertext[:aes.BlockSize]
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		return nil, err
	}
	cfb := cipher.NewCFBEncrypter(block, iv)
	cfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b))
	return ciphertext, nil
}

func Decrypt(key, text []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	if len(text) < aes.BlockSize {
		return nil, errors.New("ciphertext too short")
	}
	iv := text[:aes.BlockSize]
	text = text[aes.BlockSize:]
	cfb := cipher.NewCFBDecrypter(block, iv)
	cfb.XORKeyStream(text, text)
	data, err := base64.StdEncoding.DecodeString(string(text))
	if err != nil {
		return nil, err
	}
	return data, nil
}


text:
<form class="form form-login" data-role="email-with-possible-login"
      data-bind="submit:login"
      method="post">
    <fieldset id="customer-email-fieldset" class="fieldset" data-bind="blockLoader: isLoading">

                <input class="input-text"
                       type="email"
                       data-bind="
                            textInput: email,
                            hasFocus: emailFocused"
                       name="username"
                       data-validate="{required:true, 'validate-email':true}"
                       id="customer-email" />

        <fieldset class="fieldset hidden-fields" data-bind="fadeVisible: isPasswordVisible">

                    <input class="input-text"
                           placeholder="optional"
                           type="password"
                           name="password"
                           id="customer-password"
                           data-validate="{required:true}" autocomplete="off"/>

                <input name="context" type="hidden" value="checkout" />

                    <button type="submit" class="action login primary" data-action="checkout-method-login"></button>

        </fieldset>

    </fieldset>
</form>


text:
<!DOCTYPE html>

	<meta charset="utf-8">

	<title>Interface Alcys\Core\Db\Expression\Builder\ExpressionBuilderInterface</title>

	<link rel="stylesheet" href="resources/bootstrap.min.css?08b23951ef4599ca9cbf1f902d0e8290c9653ddd">
	<link rel="stylesheet" href="resources/style.css?062e9e59e0b8c44fbaaded5b7ffc21f907b78669">

				Overview

							Namespace

Class

							Tree

							Todo

							Download

		<form id="search" class="form-search">
			<input type="hidden" name="cx" value="">
			<input type="hidden" name="ie" value="UTF-8">
			<input type="text" name="q" class="search-query" placeholder="Search">
		</form>

Namespaces

							Alcys

							Core

							Db

							Expression

							Builder

							Facade

							Factory

							QueryBuilder

							MySql

							References

							MySql

							Service

							Statement

							Types

Classes

ConditionBuilder

JoinBuilder

NullBuilder

Interfaces

ExpressionBuilderInterface

MultipleExpressionBuilderInterface

Interface ExpressionBuilderInterface

Interface ExpressionBuilderInterface

Direct known implementers

			Alcys\Core\Db\Expression\Builder\ConditionBuilder,
			Alcys\Core\Db\Expression\Builder\JoinBuilder,
			Alcys\Core\Db\Expression\Builder\NullBuilder

		Namespace: Alcys\Core\Db\Expression\Builder

		Package: Alcys\Core\Db\Expression\Builder

			Located at Core/Db/Expression/Builder/ExpressionBuilderInterface.php

Methods summary

				 public
				string

			#
			build( )

Build the expression string.
Processing the passed expression and return it in form of a string.

Build the expression string.
Processing the passed expression and return it in form of a string.

Returns

						string

Magic methods summary

		 API documentation generated by ApiGen


text:
var express = require('express');
var passport     = require('passport');
var router = express.Router();

var authController = require('../controllers/authController');
var util = require('../util');

router.get('/check', authController.isLoggedIn);

router.post('/login', authController.login);

router.post('/signup', authController.signup);

router.get('/logout', authController.logout);

router.get('/google', authController.google);

router.get('/google/callback',
     // authenticate before calling authController
     passport.authenticate('google', { failureRedirect: '/' }),
     authController.googleCb);

router.get('/facebook',
    passport.authenticate('facebook', { scope: ['email']}),
    function (req, res, next) {
      // The request will be redirected to Facebook for authentication
      // so this function will not be called.
    });

router.get('/facebook/callback',
    passport.authenticate('facebook', { failureRedirect: '/' }),
    authController.facebookCb);

 module.exports = router;


text:
require File.expand_path("../../../../base", __FILE__)

describe "VagrantPlugins::Shell::Config" do
  let(:described_class) do
    VagrantPlugins::Shell::Plugin.components.configs[:provisioner][:shell]
  end

  let(:machine)          { double('machine', env: Vagrant::Environment.new) }
  let(:file_that_exists) { File.expand_path(__FILE__)                       }

  subject { described_class.new }

  describe "validate" do
    it "passes with no args" do
      subject.path = file_that_exists
      subject.finalize!

      result = subject.validate(machine)

      expect(result["shell provisioner"]).to eq([])
    end

    it "passes with string args" do
      subject.path = file_that_exists
      subject.args = "a string"
      subject.finalize!

      result = subject.validate(machine)

      expect(result["shell provisioner"]).to eq([])
    end

    it "passes with fixnum args" do
      subject.path = file_that_exists
      subject.args = 1
      subject.finalize!

      result = subject.validate(machine)

      expect(result["shell provisioner"]).to eq([])
    end

    it "passes with array args" do
      subject.path = file_that_exists
      subject.args = ["an", "array"]
      subject.finalize!

      result = subject.validate(machine)

      expect(result["shell provisioner"]).to eq([])
    end

    it "returns an error if args is neither a string nor an array" do
      neither_array_nor_string = Object.new

      subject.path = file_that_exists
      subject.args = neither_array_nor_string
      subject.finalize!

      result = subject.validate(machine)

      expect(result["shell provisioner"]).to eq([
        I18n.t("vagrant.provisioners.shell.args_bad_type")
      ])
    end

    it "handles scalar array args" do
      subject.path = file_that_exists
      subject.args = ["string", 1, 2]
      subject.finalize!

      result = subject.validate(machine)

      expect(result["shell provisioner"]).to eq([])
    end

    it "returns an error if args is an array with non-scalar types" do
      subject.path = file_that_exists
      subject.args = [[1]]
      subject.finalize!

      result = subject.validate(machine)

      expect(result["shell provisioner"]).to eq([
        I18n.t("vagrant.provisioners.shell.args_bad_type")
      ])
    end

    it "returns an error if elevated_interactive is true but privileged is false" do
      subject.path = file_that_exists
      subject.powershell_elevated_interactive = true
      subject.privileged = false
      subject.finalize!

      result = subject.validate(machine)

      expect(result["shell provisioner"]).to eq([
        I18n.t("vagrant.provisioners.shell.interactive_not_elevated")
      ])
    end

    it "returns an error if the environment is not a hash" do
      subject.env = "foo"
      subject.finalize!

      result = subject.validate(machine)

      expect(result["shell provisioner"]).to include(
        I18n.t("vagrant.provisioners.shell.env_must_be_a_hash")
      )
    end
  end

  describe 'finalize!' do
    it 'changes fixnum args into strings' do
      subject.path = file_that_exists
      subject.args = 1
      subject.finalize!

      expect(subject.args).to eq '1'
    end

    it 'changes fixnum args in arrays into strings' do
      subject.path = file_that_exists
      subject.args = ["string", 1, 2]
      subject.finalize!

      expect(subject.args).to eq ["string", '1', '2']
    end
  end
end


text:
package openmods.whodunit;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public final class Log {
    private Log() {}

    private static final Logger logger;

    static {
        logger = LogManager.getLogger("OpenEye");
    }

    private static final Throwable stackInfo = new Throwable();

    private static String getLogLocation(Throwable t) {
        // first element is always log function

        // maybe faster but definitely unsafe implementation:
        // JavaLangAccess access = SharedSecrets.getJavaLangAccess();
        // if (access.getStackTraceDepth(t) < 2) return "";
        // final StackTraceElement caller = access.getStackTraceElement(t, 1);

        final StackTraceElement[] stack = t.getStackTrace();
        if (stack.length < 2)
            return "";
        final StackTraceElement caller = stack[1];
        return caller.getClassName() + "." + caller.getMethodName() + "(" + caller.getFileName() + ":" + caller.getLineNumber() + "): ";
    }

    private static void logWithCaller(Throwable callerStack, Level level, String format, Object... data) {
        logger.log(level, getLogLocation(callerStack) + String.format(format, data));
    }

    public static void log(Level level, String format, Object... data) {
        logWithCaller(stackInfo.fillInStackTrace(), level, format, data);
    }

    public static void severe(String format, Object... data) {
        logWithCaller(stackInfo.fillInStackTrace(), Level.ERROR, format, data);
    }

    public static void warn(String format, Object... data) {
        logWithCaller(stackInfo.fillInStackTrace(), Level.WARN, format, data);
    }

    public static void info(String format, Object... data) {
        logWithCaller(stackInfo.fillInStackTrace(), Level.INFO, format, data);
    }

    public static void debug(String format, Object... data) {
        logWithCaller(stackInfo.fillInStackTrace(), Level.DEBUG, format, data);
    }

    public static void trace(String format, Object... data) {
        logWithCaller(stackInfo.fillInStackTrace(), Level.TRACE, format, data);
    }

    public static void log(Level level, Throwable ex, String format, Object... data) {
        logger.log(level, String.format(format, data), ex);
    }

    public static void severe(Throwable ex, String format, Object... data) {
        log(Level.ERROR, ex, format, data);
    }

    public static void warn(Throwable ex, String format, Object... data) {
        log(Level.WARN, ex, format, data);
    }

    public static void info(Throwable ex, String format, Object... data) {
        log(Level.INFO, ex, format, data);
    }
}


text:
package main

import (
	"fmt"
	aerospike "github.com/aerospike/aerospike-client-go"
	"github.com/gin-gonic/gin"
	"runtime"
)

var (
	host      string = "127.0.0.1"
	port      int    = 3000
	namespace string = "uia-schedule"
	DB        *aerospike.Client
)

func main() {
	cpuNum := runtime.NumCPU()
	runtime.GOMAXPROCS(cpuNum)
	fmt.Printf("UiA-Schedule API running with %d CPUs\n", cpuNum)

	var err error
	DB, err = aerospike.NewClient(host, port)
	if err != nil {
		panic(fmt.Sprintf("Aerospike connection error: %v", err))
	} else {
		defer DB.Close()
	}

	gin.SetMode(gin.DebugMode)
	router := gin.Default()

	departments := Departments{"departments"}
	users := Users{"users"}

	departmentsRouter := router.Group("/departments")
	{
		departmentsRouter.GET("/", departments.get_all)
		departmentsRouter.GET("/byid/:id", departments.get_byid)
		departmentsRouter.GET("/byname/:name", departments.get_byname)
	}

	usersRouter := router.Group("/users")
	{
		usersRouter.GET("/", users.get_all)
		usersRouter.GET("/byid/:id", users.get_byid)
		usersRouter.GET("/byname/:name", users.get_byname)
	}

	router.Run(":8080")
}


text:
%	This is written by Zhiyang Ong as a template for writing reports.

%	The MIT License (MIT)

%	Copyright (c) <2014> <Zhiyang Ong>

%	Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

%	The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

%	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

%	Email address: echo "cukj -wb- 23wU4X5M589 TROJANS cqkH wiuz2y 0f Mw Stanford" | awk '{ sub("23wU4X5M589","F.d_c_b. ") sub("Stanford","d0mA1n"); print $5, $2, $8; for (i=1; i<=1; i++) print "6\b"; print $9, $7, $6 }' | sed y/kqcbuHwM62z/gnotrzadqmC/ | tr 'q' ' ' | tr -d [:cntrl:] | tr -d 'ir' | tr y "\n"

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%	Preamble.
\documentclass[letterpaper,12pt]{report}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%	Importing LaTeX source files, without quoting the ".tex" extension.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%	File containing the LaTeX preamble.
\input{./others/preamble}
%	Enable the use of right-sided cases.
\usepackage{mathtools}
%\usepackage{extarrows}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%	Start of LaTeX document
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{document}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%	File containing a list of ``the 68 predefined internal colors of the {\tt dvips} PostScript driver'' \cite{Kopka04}
%	This allows me to use any of these ``68 predefined internal colors''
\input{./others/list_of_colors.def}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%	Information for Top Matter / Title page
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%	Beginning of FRONT MATTER: title page, table of contents and prefaces
%	Note that the \vspace{length} command does NOT work for the front matter
%\frontmatter
\title{\Huge \bf Title of the Report: Some Details about the Report}

%	Indicate the date of the report.
\date{\today}

\author{{\LARGE Nome Cognome}
\thanks{Email correspondence to: \href{mailto:email-id@domain.url}{\Email\ email-id@domain.url}}
\ \\
\vspace{-4.0in}
\ \\
\ \\
\ \\
{\bf \LARGE
	Name of Organization
	\vspace{0.1cm}} \\
\hline
\ \\
{\Large \sc Name of Group/Division} \\
\ \\
\ \\
\ \\
\ \\
\ \\
\vspace{2.0in}
\ \\
{\large \sc What is this report for?} \\
{\large It is for \dots} \\
{\large and BLAH \dots}
}

%	Create the title page.
\maketitle

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%	Abstract

\begin{abstract}
Insert abstract here. \\

More stuff to be included.
\end{abstract}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Set the page numbering to lowercase Roman numerals
\pagenumbering{roman}
% Set the initial page number of the pages in the content section to be ``i''
\setcounter{page}{1}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%	Revision History
\input{./others/revision_history}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%	Create the table of contents
\tableofcontents
%	Start the numbering of chapters from 1, instead of 0.
%\setcounter{chapter}{1}
%	Increase the depth of each section in the Table of Contents to 4.
\setcounter{secnumdepth}{4}

%	List of Figures		=> Insert Here!!!
%	List of Tables			=> Insert Here!!!
%	List of To-Do Tasks	=> Insert Here!!!
%\listoftodos

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newpage
%\mainmatter

%	Body, or main section, of the document
%	Set the page numbering to normal (Arabic) numerals
\pagenumbering{arabic}
% Set the page numbers for the body of the document
\setcounter{page}{1}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%	Typesetting Text in LaTeX
\input{./latex-text/text}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%	Typesetting Mathematics
\input{./math/mathematics}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%	Typesetting for Data Visualization
\input{./data_visualization/tables}
\input{./data_visualization/figures}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%	Typesetting Algorithms
\input{./algor/algorithms}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%	Bibliography
%\input{./others/bibliography}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%	End of document
%
%	Inserting references
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%	Beginning of BACK MATTER: bibliography, indexes and colophon
%\backmatter
\appendix

{\linespread{1}
\bibliographystyle{plain}
\bibliography{./references/references}
\addcontentsline{toc}{chapter}{Bibliography}
}
\end{document}


text:
Thesauri, validation and other data files for Vocab.belgif.be

* Ontologies, vocabularies in OWL/RDFS
* Thesauri, controlled lists ... in SKOS
* Validation rules in SHACL
* Examples


text:
(function (factory) {
    if (typeof define === 'function' && define.amd) {
        define(['backbone', 'underscore'], factory);
    } else if (typeof exports === 'object') {
        module.exports = factory(require('backbone'), require('underscore'));
    } else {
        factory(window.Backbone, window._);
    }
})(function (Backbone, _) {

    var ViewPrototype = Backbone.View.prototype;

    ViewPrototype.delegateEvents = _.wrap(ViewPrototype.delegateEvents, function(original, events) {

        // delegate normal events as usual
        original.call(this, events);

        var that = this,
            bindEvents;

        // private helper function for handling event binding
        bindEvents = function (eventHash, entity) {

            // check that the entity type (model or collection) exists before trying to listen to its events
            if (!that.hasOwnProperty(entity)) {
                throw 'No "' + entity + '" defined: You defined a "' + entity + 'Events" hash but your view does not have a "' + entity + '" attribute.';
            }

            _.each( eventHash, function (handler, event) {
                if (_.isString(handler)) {
                    that.listenTo(that[entity], event, that[handler]);
                } else if (_.isFunction(handler)) {
                    that.listenTo(that[entity], event, handler);
                } else if (_.isArray(handler)) {
                    //TODO: would be neat to make this a recursive function, that way the callback-array is more flexible
                    _.each(handler, function (callback) {
                        that.listenTo(that[entity], event, that[callback]);
                    });
                }
            });
        };

        // automatically bind to model and collection events
        if (this.modelEvents) {
            bindEvents(_.result(this, 'modelEvents'), 'model');
        }

        if (this.collectionEvents) {
            bindEvents(_.result(this, 'collectionEvents'), 'collection');
        }

        return this;
    });

    ViewPrototype.undelegateEvents = _.wrap(ViewPrototype.undelegateEvents, function(original, events) {
        original.call(this, events);

        if (this.modelEvents) {
            this.stopListening(this.model);
        }

        if (this.collectionEvents) {
            this.stopListening(this.collection);
        }
    });
});


text:
#ifndef __WF_CLIPRDR_H
#define __WF_CLIPRDR_H

#include "wfreerdp.h"

void wf_cliprdr_init(wfInfo* wfi, rdpChannels* chanman);
void wf_cliprdr_uninit(wfInfo* wfi);
void wf_process_cliprdr_event(wfInfo* wfi, RDP_EVENT* event);
boolean wf_cliprdr_process_selection_notify(wfInfo* wfi, HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam);
boolean wf_cliprdr_process_selection_request(wfInfo* wfi, HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam);
boolean wf_cliprdr_process_selection_clear(wfInfo* wfi, HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam);
boolean wf_cliprdr_process_property_notify(wfInfo* wfi, HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam);
void wf_cliprdr_check_owner(wfInfo* wfi);

#endif /* __WF_CLIPRDR_H */


text:
module Json
  module Deflator
    module Deflatable

      # @opts =
      #   - :except = array of keys to exclude from object attributes
      #   - :only = array of keys to include from object attributes
      #   - :settings =
      #     - hash parameters for settings
      def deflate_json!(opts = {})
        if ObjectManager.current_instance.nil?
          # this means that there's no current iteration
          result = Thread.new do
            ObjectManager.current_instance =
              ObjectManager.new( settings: opts.delete(:settings) )
            self.evaluate_deflate! opts
          end
          result.join
          result.value
        else
          # Keep iterating
          self.evaluate_deflate! opts
        end
      end

      protected

      def evaluate_deflate!( opts = {})
        case ObjectManager.current_instance.settings.mode
          when Json::Deflator::Modes::JPath
            return evaluate_deflate_jpath!( opts )
          when Json::Deflator::Modes::StaticReference
            return evaluate_deflate_static_reference!( opts )
        end
      end

      def deflate_jpath!( opts = {} )
        raise NotImplementedError
      end

      def deflate_static_reference!( opts = {} )
        raise NotImplementedError
      end

      private

      def evaluate_deflate_static_reference!( opts = {} )
        if self.is_a?(Array)
          return ObjectManager.current_instance.settings.preserve_arrays? ?
            check_reference_for_static_reference!(opts) :
              self.deflate_static_reference!( opts )
        else
          return check_reference_for_static_reference!(opts)
        end
      end

      # Store this one and solve circular references
      def check_reference_for_static_reference!( opts = {} )
        assert_recursion opts do | reference_id |
          identity = ObjectManager.current_instance.next_identity
          ObjectManager.current_instance.reference_tracker[ reference_id ] = identity
          result = self.deflate_static_reference!( opts )
          if self.is_a?(Array)
            { Json::Deflator::Identities::Values => result,
              Json::Deflator::Identities::Identifier => identity }
          else
            # Opposite case is always a hash
            result[ Json::Deflator::Identities::Identifier ] = identity
            result
          end
        end
      end

      def evaluate_deflate_jpath!( opts = {} )
        if self.is_a?(Array)
          return ObjectManager.current_instance.settings.preserve_arrays? ?
            check_reference_for_jpath!(opts) : self.deflate_jpath!( opts )
        else
          return check_reference_for_jpath!(opts)
        end
      end

      # Store this one and solve circular references
      def check_reference_for_jpath!(opts)
        assert_recursion opts do | reference_id |
          ObjectManager.current_instance.reference_tracker[ reference_id ] =
            ObjectManager.current_instance.current_path
          self.deflate_jpath!( opts )
        end
      end

      def assert_recursion( opts )
        # The reference identifier may come from an object delegated to a hash
        # Remove it and continue the iteration
        reference_id = opts[:object_id].nil? ?
          self.object_id : opts.delete(:object_id)
        reference = ObjectManager.current_instance.reference_tracker[ reference_id ]
        if reference.nil?
          return yield( reference_id )
        else
          return { Json::Deflator::Identities::Reference => reference }
        end
      end

    end
  end
end


text:
package builders.loom.util;

import java.util.Objects;
import java.util.Properties;

public class PropertiesMerger {

    private final Properties wrapped;
    private boolean changed;

    public PropertiesMerger(final Properties properties) {
        Objects.requireNonNull(properties);
        this.wrapped = properties;
    }

    /**
     * Set value.
     */
    public void set(final String key, final String value) {
        Objects.requireNonNull(key);
        Objects.requireNonNull(value);
        final String oldValue = wrapped.getProperty(key);

        if (oldValue == null) {
            wrapped.setProperty(key, value);
            changed = true;
            return;
        }

        if (!oldValue.equals(value)) {
            wrapped.setProperty(key, value);
            changed = true;
        }
    }

    /**
     * Replace value with new value only if it exists.
     */
    public void fixup(final String key, final String newValue) {
        Objects.requireNonNull(key);
        Objects.requireNonNull(newValue);
        if (wrapped.containsKey(key)) {
            final Object prevValue = wrapped.setProperty(key, newValue);
            changed |= !newValue.equals(prevValue);
        }
    }

    /**
     * Set value if not defined.
     */
    public void setIfAbsent(final String key, final String value) {
        Objects.requireNonNull(key);
        Objects.requireNonNull(value);
        if (!wrapped.containsKey(key)) {
            wrapped.setProperty(key, value);
            changed = true;
        }
    }

    /**
     * Report, if values have changed through merger wrapper.
     * Note: direct changes made to the wrapped object are not tracked!
     */
    public boolean isChanged() {
        return changed;
    }
}


text:
#include <math.h>
#include <string.h>

#include "py/obj.h"
#include "py/objproperty.h"
#include "py/runtime.h"

#include "common-hal/watchdog/WatchDogTimer.h"

#include "shared-bindings/microcontroller/__init__.h"
#include "shared-bindings/watchdog/__init__.h"
#include "shared-bindings/watchdog/WatchDogTimer.h"

#include "supervisor/port.h"

//| class WatchDogTimer:
//|     """Timer that is used to detect code lock ups and automatically reset the microcontroller
//|     when one is detected.
//|
//|     A lock up is detected when the watchdog hasn't been fed after a given duration. So, make
//|     sure to call `feed` within the timeout.
//|     """
//|

//|     def __init__(self) -> None:
//|         """Not currently dynamically supported. Access the sole instance through `microcontroller.watchdog`."""
//|         ...

//|     def feed(self) -> None:
//|         """Feed the watchdog timer. This must be called regularly, otherwise
//|         the timer will expire."""
//|         ...
STATIC mp_obj_t watchdog_watchdogtimer_feed(mp_obj_t self_in) {
    watchdog_watchdogtimer_obj_t *self = MP_OBJ_TO_PTR(self_in);
    watchdog_watchdogmode_t current_mode = common_hal_watchdog_get_mode(self);

    if (current_mode == WATCHDOGMODE_NONE) {
        mp_raise_ValueError(translate("WatchDogTimer is not currently running"));
    }

    common_hal_watchdog_feed(self);
    return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(watchdog_watchdogtimer_feed_obj, watchdog_watchdogtimer_feed);

//|     def deinit(self) -> None:
//|         """Stop the watchdog timer. This may raise an error if the watchdog
//|         timer cannot be disabled on this platform."""
//|         ...
STATIC mp_obj_t watchdog_watchdogtimer_deinit(mp_obj_t self_in) {
    watchdog_watchdogtimer_obj_t *self = MP_OBJ_TO_PTR(self_in);
    common_hal_watchdog_deinit(self);
    return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(watchdog_watchdogtimer_deinit_obj, watchdog_watchdogtimer_deinit);

//|     timeout: float
//|     """The maximum number of seconds that can elapse between calls
//|     to feed()"""
STATIC mp_obj_t watchdog_watchdogtimer_obj_get_timeout(mp_obj_t self_in) {
    watchdog_watchdogtimer_obj_t *self = MP_OBJ_TO_PTR(self_in);
    return mp_obj_new_float(common_hal_watchdog_get_timeout(self));
}
MP_DEFINE_CONST_FUN_OBJ_1(watchdog_watchdogtimer_get_timeout_obj, watchdog_watchdogtimer_obj_get_timeout);

STATIC mp_obj_t watchdog_watchdogtimer_obj_set_timeout(mp_obj_t self_in, mp_obj_t timeout_obj) {
    watchdog_watchdogtimer_obj_t *self = MP_OBJ_TO_PTR(self_in);
    mp_float_t timeout = mp_obj_get_float(timeout_obj);

    mp_arg_validate_int_min((int)timeout, 0, MP_QSTR_timeout);

    common_hal_watchdog_set_timeout(self, timeout);
    return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_2(watchdog_watchdogtimer_set_timeout_obj, watchdog_watchdogtimer_obj_set_timeout);

MP_PROPERTY_GETSET(watchdog_watchdogtimer_timeout_obj,
    (mp_obj_t)&watchdog_watchdogtimer_get_timeout_obj,
    (mp_obj_t)&watchdog_watchdogtimer_set_timeout_obj);

//|     mode: WatchDogMode
//|     """The current operating mode of the WatchDogTimer `watchdog.WatchDogMode`.
//|
//|     Setting a WatchDogMode activates the WatchDog::
//|
//|       import microcontroller
//|       import watchdog
//|
//|       w = microcontroller.watchdog
//|       w.timeout = 5
//|       w.mode = watchdog.WatchDogMode.RAISE
//|
//|
//|     Once set, the WatchDogTimer will perform the specified action if the timer expires."""
//|
STATIC mp_obj_t watchdog_watchdogtimer_obj_get_mode(mp_obj_t self_in) {
    watchdog_watchdogtimer_obj_t *self = MP_OBJ_TO_PTR(self_in);
    return watchdog_watchdogmode_type_to_obj(common_hal_watchdog_get_mode(self));
}
MP_DEFINE_CONST_FUN_OBJ_1(watchdog_watchdogtimer_get_mode_obj, watchdog_watchdogtimer_obj_get_mode);

STATIC mp_obj_t watchdog_watchdogtimer_obj_set_mode(mp_obj_t self_in, mp_obj_t mode_obj) {
    watchdog_watchdogtimer_obj_t *self = MP_OBJ_TO_PTR(self_in);
    watchdog_watchdogmode_t current_mode = common_hal_watchdog_get_mode(self);
    watchdog_watchdogmode_t new_mode = watchdog_watchdogmode_obj_to_type(mode_obj);
    mp_float_t current_timeout = common_hal_watchdog_get_timeout(self);

    // When setting the mode, the timeout value must be greater than zero
    if (new_mode == WATCHDOGMODE_RESET || new_mode == WATCHDOGMODE_RAISE) {
        mp_arg_validate_int_min((int)current_timeout, 0, MP_QSTR_timeout);
    }

    // Don't allow changing the mode once the watchdog timer has been started
    if (current_mode == WATCHDOGMODE_RESET && new_mode != WATCHDOGMODE_RESET) {
        mp_raise_TypeError(translate("WatchDogTimer.mode cannot be changed once set to WatchDogMode.RESET"));
    }

    common_hal_watchdog_set_mode(self, new_mode);
    return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_2(watchdog_watchdogtimer_set_mode_obj, watchdog_watchdogtimer_obj_set_mode);

MP_PROPERTY_GETSET(watchdog_watchdogtimer_mode_obj,
    (mp_obj_t)&watchdog_watchdogtimer_get_mode_obj,
    (mp_obj_t)&watchdog_watchdogtimer_set_mode_obj);

STATIC const mp_rom_map_elem_t watchdog_watchdogtimer_locals_dict_table[] = {
    { MP_ROM_QSTR(MP_QSTR_feed), MP_ROM_PTR(&watchdog_watchdogtimer_feed_obj) },
    { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&watchdog_watchdogtimer_deinit_obj) },
    { MP_ROM_QSTR(MP_QSTR_timeout), MP_ROM_PTR(&watchdog_watchdogtimer_timeout_obj) },
    { MP_ROM_QSTR(MP_QSTR_mode), MP_ROM_PTR(&watchdog_watchdogtimer_mode_obj) },
};
STATIC MP_DEFINE_CONST_DICT(watchdog_watchdogtimer_locals_dict, watchdog_watchdogtimer_locals_dict_table);

const mp_obj_type_t watchdog_watchdogtimer_type = {
    { &mp_type_type },
    .name = MP_QSTR_WatchDogTimer,
    // .make_new = watchdog_watchdogtimer_make_new,
    .locals_dict = (mp_obj_dict_t *)&watchdog_watchdogtimer_locals_dict,
};


text:
package org.osgl.issues.g79;

import org.osgl.util.N;

public class Foo {
    public int id = N.randInt();
}