text:
package org.apache.jackrabbit.oak.plugins.document;

import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;

import com.google.common.collect.Lists;

import org.apache.jackrabbit.oak.plugins.document.DocumentStoreException.Type;

import static java.util.Collections.singletonList;
import static java.util.Collections.singletonMap;

/**
 * Wraps a document store and can be instructed to fail operations.
 */
class FailingDocumentStore extends DocumentStoreWrapper {

    private final Random random;

    private volatile double p;

    private AtomicLong failAfter = new AtomicLong(Long.MAX_VALUE);

    private AtomicLong numFailures = new AtomicLong(0);

    private Type exceptionType = Type.GENERIC;

    class Fail {

        private Fail() {
            never();
        }

        Fail after(int numOps) {
            p = -1;
            failAfter.set(numOps);
            return this;
        }

        Fail withType(Type type) {
            exceptionType = type;
            return this;
        }

        void never() {
            p = -1;
            numFailures.set(0);
            failAfter.set(Long.MAX_VALUE);
            exceptionType = Type.GENERIC;
        }

        void once() {
            numFailures.set(1);
        }

        void eternally() {
            numFailures.set(Long.MAX_VALUE);
        }

        Fail randomly(double probability) {
            p = probability;
            return this;
        }
    }

    FailingDocumentStore(DocumentStore store, long seed) {
        this(store, new Random(seed));
    }

    FailingDocumentStore(DocumentStore store) {
        this(store, new Random());
    }

    private FailingDocumentStore(DocumentStore store, Random r) {
        super(store);
        this.random = r;
    }

    Fail fail() {
        return new Fail();
    }

    @Override
    public <T extends Document> void remove(Collection<T> collection,
                                            String key) {
        maybeFail();
        super.remove(collection, key);
    }

    @Override
    public <T extends Document> void remove(Collection<T> collection,
                                            List<String> keys) {
        // redirect to single document remove method
        for (String k : keys) {
            remove(collection, k);
        }
    }

    @Override
    public <T extends Document> int remove(Collection<T> collection,
                                           Map<String, Long> toRemove) {
        int num = 0;
        // remove individually
        for (Map.Entry<String, Long> rm : toRemove.entrySet()) {
            maybeFail();
            num += super.remove(collection, singletonMap(rm.getKey(), rm.getValue()));
        }
        return num;
    }

    @Override
    public <T extends Document> int remove(Collection<T> collection,
                                           String indexedProperty,
                                           long startValue,
                                           long endValue)
            throws DocumentStoreException {
        maybeFail();
        return super.remove(collection, indexedProperty, startValue, endValue);
    }

    @Override
    public <T extends Document> boolean create(Collection<T> collection,
                                               List<UpdateOp> updateOps) {
        // create individually
        for (UpdateOp op : updateOps) {
            maybeFail();
            if (!super.create(collection, singletonList(op))) {
                return false;
            }
        }
        return true;
    }

    @Override
    public <T extends Document> T createOrUpdate(Collection<T> collection,
                                                 UpdateOp update) {
        maybeFail();
        return super.createOrUpdate(collection, update);
    }

    @Override
    public <T extends Document> List<T> createOrUpdate(Collection<T> collection,
                                                       List<UpdateOp> updateOps) {
        List<T> result = Lists.newArrayList();
        // redirect to single document createOrUpdate
        for (UpdateOp op : updateOps) {
            result.add(createOrUpdate(collection, op));
        }
        return result;
    }

    @Override
    public <T extends Document> T findAndUpdate(Collection<T> collection,
                                                UpdateOp update) {
        maybeFail();
        return super.findAndUpdate(collection, update);
    }

    private void maybeFail() {
        if (random.nextFloat() < p || failAfter.getAndDecrement() <= 0) {
            if (numFailures.getAndDecrement() > 0) {
                throw new DocumentStoreException("write operation failed", null, exceptionType);
            }
        }
    }
}


text:
function(ament_index_has_resource var resource_type resource_name)
  if(resource_type STREQUAL "")
    message(FATAL_ERROR
      "ament_index_has_resource() called without a 'resource_type'")
  endif()
  if(resource_name STREQUAL "")
    message(FATAL_ERROR
      "ament_index_has_resource() called without a 'resource_name'")
  endif()

  cmake_parse_arguments(ARG "" "PREFIX_PATH" "" ${ARGN})
  if(ARG_UNPARSED_ARGUMENTS)
    message(FATAL_ERROR "ament_index_has_resource() called with unused "
      "arguments: ${ARG_UNPARSED_ARGUMENTS}")
  endif()

  if(ARG_PREFIX_PATH)
    set(prefix_path "${ARG_PREFIX_PATH}")
  else()
    ament_index_get_prefix_path(prefix_path)
  endif()

  set(retval FALSE)
  foreach(path IN LISTS prefix_path)
    if(EXISTS
        "${path}/share/ament_index/resource_index/${resource_type}/${resource_name}")
      set(retval TRUE)
      break()
    endif()
  endforeach()
  set(${var} "${retval}" PARENT_SCOPE)
endfunction()

redpajama_set_name: RedPajamaGithub


text:
/**
 * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
 * @version v12.0.0
 * @link http://www.ag-grid.com/
 * @license MIT
 */
"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
var component_1 = require("../../widgets/component");
var svgFactory_1 = require("../../svgFactory");
var utils_1 = require("../../utils");
var columnController_1 = require("../../columnController/columnController");
var gridOptionsWrapper_1 = require("../../gridOptionsWrapper");
var context_1 = require("../../context/context");
var touchListener_1 = require("../../widgets/touchListener");
var componentAnnotations_1 = require("../../widgets/componentAnnotations");
var originalColumnGroup_1 = require("../../entities/originalColumnGroup");
var svgFactory = svgFactory_1.SvgFactory.getInstance();
var HeaderGroupComp = (function (_super) {
    __extends(HeaderGroupComp, _super);
    function HeaderGroupComp() {
        return _super.call(this, HeaderGroupComp.TEMPLATE) || this;
    }
    HeaderGroupComp.prototype.init = function (params) {
        this.params = params;
        this.setupLabel();
        this.addGroupExpandIcon();
        if (this.params.columnGroup.isExpandable()) {
            this.setupExpandIcons();
        }
        else {
            this.removeExpandIcons();
        }
    };
    HeaderGroupComp.prototype.setupExpandIcons = function () {
        this.addInIcon('columnGroupOpened', 'agOpened', svgFactory.createGroupExpandedIcon);
        this.addInIcon('columnGroupClosed', 'agClosed', svgFactory.createGroupContractedIcon);
        this.addTouchAndClickListeners(this.eCloseIcon);
        this.addTouchAndClickListeners(this.eOpenIcon);
        this.updateIconVisibilty();
        this.addDestroyableEventListener(this.params.columnGroup.getOriginalColumnGroup(), originalColumnGroup_1.OriginalColumnGroup.EVENT_EXPANDED_CHANGED, this.updateIconVisibilty.bind(this));
    };
    HeaderGroupComp.prototype.addTouchAndClickListeners = function (eElement) {
        var _this = this;
        var expandAction = function () {
            var newExpandedValue = !_this.params.columnGroup.isExpanded();
            _this.columnController.setColumnGroupOpened(_this.params.columnGroup, newExpandedValue);
        };
        var touchListener = new touchListener_1.TouchListener(this.eCloseIcon);
        this.addDestroyableEventListener(touchListener, touchListener_1.TouchListener.EVENT_TAP, expandAction);
        this.addDestroyFunc(function () { return touchListener.destroy(); });
        this.addDestroyableEventListener(eElement, 'click', expandAction);
    };
    HeaderGroupComp.prototype.updateIconVisibilty = function () {
        var expanded = this.params.columnGroup.isExpanded();
        utils_1.Utils.setVisible(this.eOpenIcon, !expanded);
        utils_1.Utils.setVisible(this.eCloseIcon, expanded);
    };
    HeaderGroupComp.prototype.removeExpandIcons = function () {
        utils_1.Utils.setVisible(this.eOpenIcon, false);
        utils_1.Utils.setVisible(this.eCloseIcon, false);
    };
    HeaderGroupComp.prototype.addInIcon = function (iconName, refName, defaultIconFactory) {
        var eIcon = utils_1.Utils.createIconNoSpan(iconName, this.gridOptionsWrapper, null, defaultIconFactory);
        this.getRefElement(refName).appendChild(eIcon);
    };
    HeaderGroupComp.prototype.addGroupExpandIcon = function () {
        if (!this.params.columnGroup.isExpandable()) {
            utils_1.Utils.setVisible(this.eOpenIcon, false);
            utils_1.Utils.setVisible(this.eCloseIcon, false);
            return;
        }
    };
    HeaderGroupComp.prototype.setupLabel = function () {
        // no renderer, default text render
        if (this.params.displayName && this.params.displayName !== '') {
            if (utils_1.Utils.isBrowserSafari()) {
                this.getGui().style.display = 'table-cell';
            }
            var eInnerText = this.getRefElement('agLabel');
            eInnerText.innerHTML = this.params.displayName;
        }
    };
    HeaderGroupComp.TEMPLATE = "
" +
        "" +
        "" +
        "" +
        "
";
    __decorate([
        context_1.Autowired('columnController'),
        __metadata("design:type", columnController_1.ColumnController)
    ], HeaderGroupComp.prototype, "columnController", void 0);
    __decorate([
        context_1.Autowired('gridOptionsWrapper'),
        __metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper)
    ], HeaderGroupComp.prototype, "gridOptionsWrapper", void 0);
    __decorate([
        componentAnnotations_1.RefSelector('agOpened'),
        __metadata("design:type", HTMLElement)
    ], HeaderGroupComp.prototype, "eOpenIcon", void 0);
    __decorate([
        componentAnnotations_1.RefSelector('agClosed'),
        __metadata("design:type", HTMLElement)
    ], HeaderGroupComp.prototype, "eCloseIcon", void 0);
    return HeaderGroupComp;
}(component_1.Component));
exports.HeaderGroupComp = HeaderGroupComp;


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.LanguageServer;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Roslyn.Utilities;
using StreamJsonRpc;

using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;

namespace Microsoft.CodeAnalysis.Editor.Implementation.LanguageClient
{
    /// <summary>
    /// Implementation of <see cref="LanguageServerTarget"/> that also supports
    /// VS LSP extension methods.
    /// </summary>
    internal class VisualStudioInProcLanguageServer : LanguageServerTarget
    {
        private readonly ImmutableArray<string> _supportedLanguages;

        internal VisualStudioInProcLanguageServer(
            AbstractRequestDispatcherFactory requestDispatcherFactory,
            JsonRpc jsonRpc,
            ICapabilitiesProvider capabilitiesProvider,
            LspWorkspaceRegistrationService workspaceRegistrationService,
            IGlobalOptionService globalOptions,
            IAsynchronousOperationListenerProvider listenerProvider,
            ILspLogger logger,
            ImmutableArray<string> supportedLanguages,
            string? clientName,
            WellKnownLspServerKinds serverKind)
            : base(requestDispatcherFactory, jsonRpc, capabilitiesProvider, workspaceRegistrationService, lspMiscellaneousFilesWorkspace: null, globalOptions, listenerProvider, logger, supportedLanguages, clientName, serverKind)
        {
            _supportedLanguages = supportedLanguages;
        }

        public override Task InitializedAsync()
        {
            return Task.CompletedTask;
        }

        [JsonRpcMethod(VSInternalMethods.DocumentPullDiagnosticName, UseSingleObjectParameterDeserialization = true)]
        public Task<VSInternalDiagnosticReport[]?> GetDocumentPullDiagnosticsAsync(VSInternalDocumentDiagnosticsParams diagnosticsParams, CancellationToken cancellationToken)
        {
            Contract.ThrowIfNull(_clientCapabilities, $"{nameof(InitializeAsync)} has not been called.");

            return RequestDispatcher.ExecuteRequestAsync<VSInternalDocumentDiagnosticsParams, VSInternalDiagnosticReport[]?>(
                Queue, VSInternalMethods.DocumentPullDiagnosticName,
                diagnosticsParams, _clientCapabilities, ClientName, cancellationToken);
        }

        [JsonRpcMethod(VSInternalMethods.WorkspacePullDiagnosticName, UseSingleObjectParameterDeserialization = true)]
        public Task<VSInternalWorkspaceDiagnosticReport[]?> GetWorkspacePullDiagnosticsAsync(VSInternalWorkspaceDiagnosticsParams diagnosticsParams, CancellationToken cancellationToken)
        {
            Contract.ThrowIfNull(_clientCapabilities, $"{nameof(InitializeAsync)} has not been called.");

            return RequestDispatcher.ExecuteRequestAsync<VSInternalWorkspaceDiagnosticsParams, VSInternalWorkspaceDiagnosticReport[]?>(
                Queue, VSInternalMethods.WorkspacePullDiagnosticName,
                diagnosticsParams, _clientCapabilities, ClientName, cancellationToken);
        }

        [JsonRpcMethod(VSMethods.GetProjectContextsName, UseSingleObjectParameterDeserialization = true)]
        public Task<VSProjectContextList?> GetProjectContextsAsync(VSGetProjectContextsParams textDocumentWithContextParams, CancellationToken cancellationToken)
        {
            Contract.ThrowIfNull(_clientCapabilities, $"{nameof(InitializeAsync)} has not been called.");

            return RequestDispatcher.ExecuteRequestAsync<VSGetProjectContextsParams, VSProjectContextList?>(Queue, VSMethods.GetProjectContextsName,
                textDocumentWithContextParams, _clientCapabilities, ClientName, cancellationToken);
        }

        [JsonRpcMethod(VSInternalMethods.OnAutoInsertName, UseSingleObjectParameterDeserialization = true)]
        public Task<VSInternalDocumentOnAutoInsertResponseItem?> GetDocumentOnAutoInsertAsync(VSInternalDocumentOnAutoInsertParams autoInsertParams, CancellationToken cancellationToken)
        {
            Contract.ThrowIfNull(_clientCapabilities, $"{nameof(InitializeAsync)} has not been called.");

            return RequestDispatcher.ExecuteRequestAsync<VSInternalDocumentOnAutoInsertParams, VSInternalDocumentOnAutoInsertResponseItem?>(Queue, VSInternalMethods.OnAutoInsertName,
                autoInsertParams, _clientCapabilities, ClientName, cancellationToken);
        }

        [JsonRpcMethod(Methods.TextDocumentLinkedEditingRangeName, UseSingleObjectParameterDeserialization = true)]
        public Task<LinkedEditingRanges?> GetLinkedEditingRangesAsync(LinkedEditingRangeParams renameParams, CancellationToken cancellationToken)
        {
            Contract.ThrowIfNull(_clientCapabilities, $"{nameof(InitializeAsync)} has not been called.");

            return RequestDispatcher.ExecuteRequestAsync<LinkedEditingRangeParams, LinkedEditingRanges?>(Queue, Methods.TextDocumentLinkedEditingRangeName,
                renameParams, _clientCapabilities, ClientName, cancellationToken);
        }

        [JsonRpcMethod(VSInternalMethods.TextDocumentInlineCompletionName, UseSingleObjectParameterDeserialization = true)]
        public Task<VSInternalInlineCompletionList?> GetInlineCompletionsAsync(VSInternalInlineCompletionRequest request, CancellationToken cancellationToken)
        {
            Contract.ThrowIfNull(_clientCapabilities, $"{nameof(InitializeAsync)} has not been called.");

            return RequestDispatcher.ExecuteRequestAsync<VSInternalInlineCompletionRequest, VSInternalInlineCompletionList?>(Queue, VSInternalMethods.TextDocumentInlineCompletionName,
                request, _clientCapabilities, ClientName, cancellationToken);
        }
    }
}


text:
#ifndef _NAMESPACE_H_
#define _NAMESPACE_H_

/*
 * Adjust names so that headers declare "hidden" names.
 *
 * README: When modifying this file don't forget to make the appropriate
 *         changes in un-namespace.h!!!
 */

/*
 * ISO C (C90) section.  Most names in libc aren't in ISO C, so they
 * should be here.  Most aren't here...
 */
#define		err				_err
#define		warn				_warn

/*
 * Prototypes for syscalls/functions that need to be overridden
 * in libc_r/libpthread.
 */
#define		accept				_accept
#define		__acl_aclcheck_fd		___acl_aclcheck_fd
#define		__acl_delete_fd			___acl_delete_fd
#define		__acl_get_fd			___acl_get_fd
#define		__acl_set_fd			___acl_set_fd
#define		bind				_bind
#define		__cap_get_fd			___cap_get_fd
#define		__cap_set_fd			___cap_set_fd
#define		close				_close
#define		connect				_connect
#define		dup				_dup
#define		dup2				_dup2
#define		execve				_execve
#define		fcntl				_fcntl
/*#define		flock				_flock */
#define		flockfile			_flockfile
#define		fstat				_fstat
#define		fstatfs				_fstatfs
#define		fsync				_fsync
#define		funlockfile			_funlockfile
#define		getdirentries			_getdirentries
#define		getlogin			_getlogin
#define		getpeername			_getpeername
#define		getprogname			_getprogname
#define		getsockname			_getsockname
#define		getsockopt			_getsockopt
#define		ioctl				_ioctl
/* #define		kevent				_kevent */
#define		listen				_listen
#define		nanosleep			_nanosleep
#define		open				_open
#define		poll				_poll
#define		pthread_cond_broadcast		_pthread_cond_broadcast
#define		pthread_cond_destroy		_pthread_cond_destroy
#define		pthread_cond_init		_pthread_cond_init
#define		pthread_cond_signal		_pthread_cond_signal
#define		pthread_cond_timedwait		_pthread_cond_timedwait
#define		pthread_cond_wait		_pthread_cond_wait
#define		pthread_exit			_pthread_exit
#define		pthread_getspecific		_pthread_getspecific
#define		pthread_key_create		_pthread_key_create
#define		pthread_key_delete		_pthread_key_delete
#define		pthread_main_np			_pthread_main_np
#define		pthread_mutex_destroy		_pthread_mutex_destroy
#define		pthread_mutex_init		_pthread_mutex_init
#define		pthread_mutex_lock		_pthread_mutex_lock
#define		pthread_mutex_trylock		_pthread_mutex_trylock
#define		pthread_mutex_unlock		_pthread_mutex_unlock
#define		pthread_mutexattr_destroy	_pthread_mutexattr_destroy
#define		pthread_mutexattr_init		_pthread_mutexattr_init
#define		pthread_mutexattr_settype	_pthread_mutexattr_settype
#define		pthread_once			_pthread_once
#define		pthread_rwlock_destroy		_pthread_rwlock_destroy
#define		pthread_rwlock_init		_pthread_rwlock_init
#define		pthread_rwlock_rdlock		_pthread_rwlock_rdlock
#define		pthread_rwlock_wrlock		_pthread_rwlock_wrlock
#define		pthread_rwlock_tryrdlock	_pthread_rwlock_tryrdlock
#define		pthread_rwlock_trywrlock	_pthread_rwlock_trywrlock
#define		pthread_rwlock_unlock		_pthread_rwlock_unlock
#define		pthread_self			_pthread_self
#define		pthread_setspecific		_pthread_setspecific
#define		pthread_sigmask			_pthread_sigmask
#define		read				_read
#define		readv				_readv
#define		recvfrom			_recvfrom
#define		recvmsg				_recvmsg
#define		select				_select
#define		sendmsg				_sendmsg
#define		sendto				_sendto
#define		setsockopt			_setsockopt
/*#define		sigaction			_sigaction*/
#define		sigprocmask			_sigprocmask
#define		sigsuspend			_sigsuspend
#define		socket				_socket
#define		socketpair			_socketpair
#define		wait4				_wait4
#define		waitpid				_waitpid
#define		write				_write
#define		writev				_writev

/*
 * Other hidden syscalls/functions that libc_r needs to override
 * but are not used internally by libc.
 *
 * XXX - When modifying libc to use one of the following, remove
 * the prototype from below and place it in the list above.
 */
#if 0
#define		creat				_creat
#define		fchflags			_fchflags
#define		fchmod				_fchmod
#define		fpathconf			_fpathconf
#define		ftrylockfile			_ftrylockfile
#define		msync				_msync
#define		nfssvc				_nfssvc
#define		pause				_pause
#define		pthread_rwlockattr_init		_pthread_rwlockattr_init
#define		pthread_rwlockattr_destroy	_pthread_rwlockattr_destroy
#define		sched_yield			_sched_yield
#define		sendfile			_sendfile
#define		shutdown			_shutdown
#define		sigaltstack			_sigaltstack
#define		sigpending			_sigpending
#define		sigreturn			_sigreturn
#define		sigsetmask			_sigsetmask
#define		sleep				_sleep
#define		system				_system
#define		tcdrain				_tcdrain
#define		wait				_wait
#endif

#endif /* _NAMESPACE_H_ */


text:
using namespace BridgeRT;

LampParameters::LampParameters(LSF* pLightingService)
    : m_pLightingService (pLightingService)
    , m_lampParametersInterface (nullptr)
{
}

LampParameters::~LampParameters()
{
    if (m_pLightingService != nullptr)
    {
        delete m_pLightingService;
        m_pLightingService = nullptr;
    }
}

QStatus
LampParameters::Initialize()
{
    QStatus status = ER_OK;

    // Create LampParameters interface
    CHK_AJSTATUS(alljoyn_busattachment_createinterface(m_pLightingService->GetBus(), LAMP_PARAMETERS_INTERFACE_NAME, &m_lampParametersInterface));

    // Add "Version" Property to LampParameters Interface
    CHK_AJSTATUS(alljoyn_interfacedescription_addproperty(
        m_lampParametersInterface,
        PROPERTY_VERSION_STR,
        ARG_UINT32_STR,
        ALLJOYN_PROP_ACCESS_READ
        ));

    // Add "Energy_Usage_Milliwatts" Property to LampParameters Interface
    CHK_AJSTATUS(alljoyn_interfacedescription_addproperty(
        m_lampParametersInterface,
        PROPERTY_ENERGY_USAGE_MILLIWATTS_STR,
        ARG_UINT32_STR,
        ALLJOYN_PROP_ACCESS_READ
        ));

    // Add "Brightness_Lumens" Property to LampParameters Interface
    CHK_AJSTATUS(alljoyn_interfacedescription_addproperty(
        m_lampParametersInterface,
        PROPERTY_BRIGHTNESS_LUMENS_STR,
        ARG_UINT32_STR,
        ALLJOYN_PROP_ACCESS_READ
        ));

    // Activate the LampParameters Interface
    alljoyn_interfacedescription_activate(m_lampParametersInterface);

    // add LampParameters interface to bus object
    status = alljoyn_busobject_addinterface_announced(m_pLightingService->GetBusObject(), m_lampParametersInterface);
    if (ER_BUS_IFACE_ALREADY_EXISTS == status)
    {
        // this is OK
        status = ER_OK;
    }
    CHK_AJSTATUS(status);

leave:

    return status;
}

QStatus
LampParameters::Get(_In_z_ const char* propName, _Out_ alljoyn_msgarg val)
{
    QStatus status = ER_OK;

    if (strcmp(PROPERTY_VERSION_STR, propName) == 0)
    {
        uint32 version = m_pLightingService->GetLSFHandler()->LampParameters_Version;
        status = alljoyn_msgarg_set(val, "u", version);
    }
    else if (strcmp(PROPERTY_ENERGY_USAGE_MILLIWATTS_STR, propName) == 0)
    {
        uint32 energyUsageMilliwatts = m_pLightingService->GetLSFHandler()->LampParameters_EnergyUsageMilliwatts;
        status = alljoyn_msgarg_set(val, "u", energyUsageMilliwatts);
    }
    else if (strcmp(PROPERTY_BRIGHTNESS_LUMENS_STR, propName) == 0)
    {
        uint32 brightnessLumens = m_pLightingService->GetLSFHandler()->LampParameters_BrightnessLumens;
        status = alljoyn_msgarg_set(val, "u", brightnessLumens);
    }

    return status;
}


text:
import os
from setuptools import setup

def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

setup(
    name='mkpasswd',
    version='1.1',
    author='Thom Dixon',
    author_email='thom@thomdixon.org',
    description=('A CLI tool and module for generating random passwords'),
    long_description=read('README.md'),
    entry_points={
        'console_scripts': ['mkpasswd-py=mkpasswd:main']
    },
    packages=['mkpasswd'],
    zip_safe=False
)


text:
using Cirrious.MvvmCross.Binding.BindingContext;
using Cirrious.MvvmCross.Touch.Views;
using MonoTouch.ObjCRuntime;
using MonoTouch.UIKit;
using MonoTouch.Foundation;

namespace MonkeysList.Touch.Views
{
    [Register("FirstView")]
    public class FirstView : MvxViewController
    {
        private SingleRowGridView _gridView;

        public override void ViewDidLoad()
        {

            base.ViewDidLoad();

            //Initialize new SingleRowGridView
            _gridView = new SingleRowGridView(View.Bounds);

			// ios7 layout
            if (RespondsToSelector(new Selector("edgesForExtendedLayout")))
               EdgesForExtendedLayout = UIRectEdge.None;

            //Bind GridView
            var set = this.CreateBindingSet<FirstView, Core.ViewModels.FirstViewModel>();
            set.Bind(_gridView).For("SingleRowData").To(vm => vm.Monkeys);
            set.Apply();

            Add(_gridView);
        }
    }
}


text:
<!DOCTYPE html>

    <title>Telegram Driver - Rapid SCADA Documentation</title>
    <meta charset="utf-8" />
    <link href="../../../../css/scadadoc.min.css" rel="stylesheet" type="text/css" />

Telegram Driver

Overview

Telegram Driver is designed to send notifications using the popular Telegram messenger. The advantages of using Telegram is quickness of receiving notifications, no fee for the service and easy notification group management.

Installation

Telegram Driver is installed in accordance with the general sequence of installing Communicator drivers. The driver library file is KpTelegram.dll.

Configuring

Creating Telegram Bot

First you need to create a Telegram bot. To do this:

Install the application and register Telegram.

Add the bot named BotFather to the contact list.

In the dialog with BotFather, run the command /newbot and follow the instructions from BotFather.

Click the menu icon and create a new group to receive notifications.

Add the bot you created to the new group.

Add contacts to the new group. These contacts will receive notifications.

Driver Settings

Configure notifications in the following sequence:

Using the Administrator application, open the Device types table and check that the device type "224 Telegram" exists. If the specified record is missing, enter it manually.

Using Administrator, create a separate communication line and a single device of the Telegram type that belongs to this communication line.

Import the created communication line and the device to Communicator. Enable sending commands for the communication line.

Using Communicator, open the device properties, enter the bot token obtained when creating the bot, and generate a bot password that is needed to manage subscriptions.

Go to the Registration page and register the driver using the hyperlinks on the form.

Save the driver configuration.

Restart the Communicator service by clicking .

Manage Subscriptions

If the settings are correct, your bot will respond to commands, for example, the /help command.

To add or remove subscriptions to the group, use the /start and /stop commands with the previously generated password. However, by default, subscription changes are blocked. To unlock it, send a standard command number 2 with a value of 1 by Communicator. Now you can add or remove subscriptions.

Sending Messages

To send a message from Rapid SCADA to a Telegram group, you need send a binary command number 1 containing the group name (or identifier) and the message text. For example: RapidScadaBotTestGroup; Test message.

Automatic sending of notifications in case of specific conditions and events are performed by Automatic Control Module.


text:
package com.parse.starter.fragment;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;

import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.parse.starter.R;
import com.parse.starter.adapter.RecyclerViewAdapter;
import com.parse.starter.object.Item;

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

public class ContentMyListingsSell extends Fragment {
    RecyclerView recyclerView;
    RecyclerViewAdapter recyclerViewAdapter;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_content_my_listings_buy, container, false);
        recyclerView = (RecyclerView) view.findViewById(R.id.buying_list);
        recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));

        recyclerViewAdapter = new RecyclerViewAdapter(this.getActivity(), 2);
        recyclerView.setAdapter(recyclerViewAdapter);
        getSellData();
        return view;
    }

    // retrieve and display data of items bought by the current user, from parse
    private void getSellData() {
        ParseUser currentUser = ParseUser.getCurrentUser();
        List<String> sellProducts = (List<String>)currentUser.get("sellProduct");

        if (sellProducts == null) return;

        ParseQuery<ParseObject> query = ParseQuery.getQuery("Item").whereContainedIn("objectId", sellProducts);

        query.addDescendingOrder("createdAt");

        query.findInBackground(new FindCallback<ParseObject>() {
            @Override
            public void done(List<ParseObject> objects, ParseException e) {
                if (e == null) {
                    List<Item> items = new ArrayList<>();
                    for (ParseObject parseObject : objects) {
                        Item item = new Item();
                        item.objectId = parseObject.getObjectId();
                        item.title = parseObject.getString("title");
                        item.description = parseObject.getString("description");
                        item.createdAt = parseObject.getCreatedAt();
                        item.updatedAt = parseObject.getUpdatedAt();
                        items.add(item);
                    }
                    recyclerViewAdapter.setItems(items);
                } else {

                }
            }
        });

    }
}


text:
import React, { PropTypes } from 'react';
import KeyBinding from 'react-keybinding';
import { connect } from 'react-redux';

import ModalsActionCreators from '../../stores/modals_action_creators';
import ModalsSelectors from '../../stores/modals_selectors';

const mapStateToProps = (state) => ({
  showSuccessModal: ModalsSelectors.getShowSuccessModal(state),
  successMessage: ModalsSelectors.getSuccessMessage(state),
});

const mapDispatchToProps = {
  closeSuccessModal: ModalsActionCreators.closeSuccessModal,
};

let SuccessModal = React.createClass({
  propTypes: {
    showSuccessModal: PropTypes.bool.isRequired,
    successMessage: PropTypes.string,
    closeSuccessModal: PropTypes.func.isRequired,
  },

  mixins: [KeyBinding],

  keybindings: {
    'esc': function(e) {
      this.props.closeSuccessModal();
    },
  },

  render() {
    const { showSuccessModal, successMessage, closeSuccessModal } = this.props;

    const isActive = showSuccessModal ? 'active' : '';
    const modalClass = `animate modal modal-content ${isActive}`;

    return (

          <button className='unround pad1 icon fr close button quiet' onClick={closeSuccessModal} />

Success

            {successMessage}

    );
  }
});

SuccessModal = connect(
  mapStateToProps,
  mapDispatchToProps
)(SuccessModal);

export default SuccessModal;


text:
package nlgo

import (
	"fmt"
	"github.com/pkg/errors"
	"strings"
	"sync"
	"syscall"
	"time"
	"unsafe"
)

func align(size, tick int) int {
	return (size + tick - 1) &^ (tick - 1)
}

func NLMSG_ALIGN(size int) int {
	return align(size, syscall.NLMSG_ALIGNTO)
}

func NLA_ALIGN(size int) int {
	return align(size, syscall.NLA_ALIGNTO)
}

const NLA_TYPE_MASK = ^uint16(syscall.NLA_F_NESTED | syscall.NLA_F_NET_BYTEORDER)

type NlaValue interface {
	// returns the entire nlattr byte sequence including header and trailing alignment padding
	Build(syscall.NlAttr) []byte
}

// Attr represents single netlink attribute package.
// Developer memo: syscall.ParseNetlinkRouteAttr does not parse nested attributes.
// I wanted to make deep parser.
type Attr struct {
	Header syscall.NlAttr
	Value  NlaValue
}

func (self Attr) Field() uint16 {
	return self.Header.Type & NLA_TYPE_MASK
}

func (self Attr) Bytes() []byte {
	return self.Value.Build(self.Header)
}

func (self Attr) Build(hdr syscall.NlAttr) []byte {
	return Binary(self.Bytes()).Build(hdr)
}

func (self Attr) Array() []Attr {
	return []Attr{self}
}

type AttrList interface {
	Slice() []Attr
	Bytes() []byte
}

type AttrSlice []Attr

func (self AttrSlice) Bytes() []byte {
	var ret []byte
	for _, attr := range []Attr(self) {
		ret = append(ret, attr.Value.Build(attr.Header)...)
	}
	return ret
}

func (self AttrSlice) Build(hdr syscall.NlAttr) []byte {
	return Binary(self.Bytes()).Build(hdr)
}

func (self AttrSlice) String() string {
	var comps []string
	for _, attr := range []Attr(self) {
		comps = append(comps, fmt.Sprintf("%d: %v", attr.Field(), attr.Value))
	}
	return fmt.Sprintf("[%s]", strings.Join(comps, ", "))
}

func (self AttrSlice) Slice() []Attr {
	return []Attr(self)
}

type Policy interface {
	Parse([]byte) (NlaValue, error)
}

type SinglePolicy int

const (
	U8Policy SinglePolicy = iota
	U16Policy
	U32Policy
	U64Policy
	StringPolicy
	FlagPolicy
	NulStringPolicy
	BinaryPolicy
	S8Policy
	S16Policy
	S32Policy
	S64Policy
)

func (self SinglePolicy) Parse(nla []byte) (NlaValue, error) {
	if len(nla) < syscall.SizeofNlAttr {
		return nil, errors.Wrapf(NLE_RANGE, "len(nla)=%d < syscall.SizeofNlAttr", len(nla))
	}
	hdr := (*syscall.NlAttr)(unsafe.Pointer(&nla[0]))
	if int(hdr.Len) < NLA_HDRLEN || int(hdr.Len) > len(nla) {
		return nil, errors.Wrapf(NLE_RANGE, "hdr.Len=%d len(nla)=%d", hdr.Len, len(nla))
	}
	attr := Attr{
		Header: *hdr,
		Value:  Binary(nla[NLA_HDRLEN:hdr.Len]),
	}
	var err error
	switch self {
	case U8Policy:
		err = setU8(&attr)
	case U16Policy:
		err = setU16(&attr)
	case U32Policy:
		err = setU32(&attr)
	case U64Policy:
		err = setU64(&attr)
	case BinaryPolicy:
		// do nothing
	case StringPolicy:
		err = setString(&attr)
	case NulStringPolicy:
		err = setNulString(&attr)
	case FlagPolicy:
		err = setFlag(&attr)
	case S8Policy:
		err = setS8(&attr)
	case S16Policy:
		err = setS16(&attr)
	case S32Policy:
		err = setS32(&attr)
	case S64Policy:
		err = setS64(&attr)
	default:
		err = fmt.Errorf("unknown single policy")
	}
	return attr, err
}

func parseElement(p Policy, attr *Attr) error {
	if p != nil {
		switch policy := p.(type) {
		case SinglePolicy:
			if value, err := policy.Parse(attr.Bytes()); err != nil {
				return err
			} else {
				*attr = value.(Attr)
			}
		default:
			if value, err := policy.Parse([]byte(attr.Value.(Binary))); err != nil {
				return err
			} else {
				attr.Value = value
			}
		}
	} else if attr.Header.Type&syscall.NLA_F_NESTED != 0 {
		if list, err := SimpleListPolicy.Parse([]byte(attr.Value.(Binary))); err != nil {
			return err
		} else {
			attr.Value = list
		}
	}
	return nil
}

type ListPolicy struct {
	Nested Policy
}

var SimpleListPolicy ListPolicy

func (self ListPolicy) Parse(nla []byte) (NlaValue, error) {
	var attrs []Attr
	for len(nla) >= NLA_HDRLEN {
		var attr Attr
		if sattr, err := BinaryPolicy.Parse(nla); err != nil {
			return nil, err
		} else {
			attr = sattr.(Attr)
		}
		if err := parseElement(self.Nested, &attr); err != nil {
			return nil, err
		}
		attrs = append(attrs, attr)
		nla = nla[NLA_ALIGN(int(attr.Header.Len)):]
	}
	return AttrSlice(attrs), nil
}

type AttrMap struct {
	AttrSlice
	Policy MapPolicy
}

func (self AttrMap) Get(field uint16) NlaValue {
	for _, attr := range self.Slice() {
		if attr.Field() == field {
			return attr.Value
		}
	}
	return nil
}

func (self AttrMap) String() string {
	var comps []string
	for _, attr := range self.AttrSlice {
		field := attr.Field()
		name := "?"
		if n, ok := self.Policy.Names[field]; ok {
			name = n
		}
		comps = append(comps, fmt.Sprintf("%s: %v", name, attr.Value))
	}
	return fmt.Sprintf("%s(%s)", self.Policy.Prefix, strings.Join(comps, ", "))
}

type MapPolicy struct {
	Prefix string
	Names  map[uint16]string
	Rule   map[uint16]Policy
}

func (self MapPolicy) Parse(nla []byte) (NlaValue, error) {
	var attrs []Attr
	for len(nla) >= NLA_HDRLEN {
		var attr Attr
		if sattr, err := BinaryPolicy.Parse(nla); err != nil {
			return nil, err
		} else {
			attr = sattr.(Attr)
		}
		if err := parseElement(self.Rule[attr.Field()], &attr); err != nil {
			return nil, err
		}
		attrs = append(attrs, attr)
		nla = nla[NLA_ALIGN(int(attr.Header.Len)):]
	}
	return AttrMap{
		AttrSlice: attrs,
		Policy:    self,
	}, nil
}

// error.h

type NlError int

const (
	NLE_SUCCESS NlError = iota
	NLE_FAILURE
	NLE_INTR
	NLE_BAD_SOCK
	NLE_AGAIN
	NLE_NOMEM
	NLE_EXIST
	NLE_INVAL
	NLE_RANGE
	NLE_MSGSIZE
	NLE_OPNOTSUPP
	NLE_AF_NOSUPPORT
	NLE_OBJ_NOTFOUND
	NLE_NOATTR
	NLE_MISSING_ATTR
	NLE_AF_MISMATCH
	NLE_SEQ_MISMATCH
	NLE_MSG_OVERFLOW
	NLE_MSG_TRUNC
	NLE_NOADDR
	NLE_SRCRT_NOSUPPORT
	NLE_MSG_TOOSHORT
	NLE_MSGTYPE_NOSUPPORT
	NLE_OBJ_MISMATCH
	NLE_NOCACHE
	NLE_BUSY
	NLE_PROTO_MISMATCH
	NLE_NOACCESS
	NLE_PERM
	NLE_PKTLOC_FILE
	NLE_PARSE_ERR
	NLE_NODEV
	NLE_IMMUTABLE
	NLE_DUMP_INTR
)

func (self NlError) Error() string {
	switch self {
	default:
		return "Unspecific failure"
	case NLE_SUCCESS:
		return "Success"
	case NLE_FAILURE:
		return "Unspecific failure"
	case NLE_INTR:
		return "Interrupted system call"
	case NLE_BAD_SOCK:
		return "Bad socket"
	case NLE_AGAIN:
		return "Try again"
	case NLE_NOMEM:
		return "Out of memory"
	case NLE_EXIST:
		return "Object exists"
	case NLE_INVAL:
		return "Invalid input data or parameter"
	case NLE_RANGE:
		return "Input data out of range"
	case NLE_MSGSIZE:
		return "Message size not sufficient"
	case NLE_OPNOTSUPP:
		return "Operation not supported"
	case NLE_AF_NOSUPPORT:
		return "Address family not supported"
	case NLE_OBJ_NOTFOUND:
		return "Object not found"
	case NLE_NOATTR:
		return "Attribute not available"
	case NLE_MISSING_ATTR:
		return "Missing attribute"
	case NLE_AF_MISMATCH:
		return "Address family mismatch"
	case NLE_SEQ_MISMATCH:
		return "Message sequence number mismatch"
	case NLE_MSG_OVERFLOW:
		return "Kernel reported message overflow"
	case NLE_MSG_TRUNC:
		return "Kernel reported truncated message"
	case NLE_NOADDR:
		return "Invalid address for specified address family"
	case NLE_SRCRT_NOSUPPORT:
		return "Source based routing not supported"
	case NLE_MSG_TOOSHORT:
		return "Netlink message is too short"
	case NLE_MSGTYPE_NOSUPPORT:
		return "Netlink message type is not supported"
	case NLE_OBJ_MISMATCH:
		return "Object type does not match cache"
	case NLE_NOCACHE:
		return "Unknown or invalid cache type"
	case NLE_BUSY:
		return "Object busy"
	case NLE_PROTO_MISMATCH:
		return "Protocol mismatch"
	case NLE_NOACCESS:
		return "No Access"
	case NLE_PERM:
		return "Operation not permitted"
	case NLE_PKTLOC_FILE:
		return "Unable to open packet location file"
	case NLE_PARSE_ERR:
		return "Unable to parse object"
	case NLE_NODEV:
		return "No such device"
	case NLE_IMMUTABLE:
		return "Immutable attribute"
	case NLE_DUMP_INTR:
		return "Dump inconsistency detected, interrupted"
	}
}

// socket.c

var pidLock = &sync.Mutex{}
var pidUsed = make(map[int]bool)

const (
	NL_SOCK_BUFSIZE_SET = 1 << iota
	NL_SOCK_PASSCRED
	NL_OWN_PORT
	NL_MSG_PEEK
	NL_NO_AUTO_ACK
)

type NlSock struct {
	Local     syscall.SockaddrNetlink
	Peer      syscall.SockaddrNetlink
	Fd        int
	SeqNext   uint32
	SeqExpect uint32
	Flags     int // NL_NO_AUTO_ACK etc.,
}

func NlSocketAlloc() *NlSock {
	tick := uint32(time.Now().Unix())
	return &NlSock{
		Fd: -1,
		Local: syscall.SockaddrNetlink{
			Family: syscall.AF_NETLINK,
		},
		Peer: syscall.SockaddrNetlink{
			Family: syscall.AF_NETLINK,
		},
		SeqNext:   tick,
		SeqExpect: tick,
		Flags:     NL_OWN_PORT,
	}
}

func NlSocketFree(sk *NlSock) {
	if sk == nil {
		return
	}
	if sk.Fd >= 0 {
		syscall.Close(sk.Fd)
	}
	pidLock.Lock()
	defer func() {
		pidLock.Unlock()
	}()
	high := sk.Local.Pid >> 22
	delete(pidUsed, int(high))
}

func NlSocketSetBufferSize(sk *NlSock, rxbuf, txbuf int) error {
	if rxbuf <= 0 {
		rxbuf = 32768
	}
	if txbuf <= 0 {
		txbuf = 32768
	}
	if sk == nil || sk.Fd == -1 {
		return NLE_BAD_SOCK
	}
	if err := syscall.SetsockoptInt(sk.Fd, syscall.SOL_SOCKET, syscall.SO_SNDBUF, txbuf); err != nil {
		return err
	}
	if err := syscall.SetsockoptInt(sk.Fd, syscall.SOL_SOCKET, syscall.SO_RCVBUF, rxbuf); err != nil {
		return err
	}
	sk.Flags |= NL_SOCK_BUFSIZE_SET
	return nil
}

// NlConnect is same with libnl nl_connect. nl_close is required for releaseing internal fd.
func NlConnect(sk *NlSock, protocol int) error {
	if sk == nil || sk.Fd != -1 {
		return NLE_BAD_SOCK
	}
	if fd, err := syscall.Socket(syscall.AF_NETLINK, syscall.SOCK_RAW|syscall.SOCK_CLOEXEC, protocol); err != nil {
		return err
	} else {
		sk.Fd = fd
	}
	if sk.Flags&NL_SOCK_BUFSIZE_SET != 0 {
		if err := NlSocketSetBufferSize(sk, 0, 0); err != nil {
			return err
		}
	}
	if sk.Local.Pid == 0 { // _nl_socket_is_local_port_unspecified
		// kernel will assign Pid
		local := &syscall.SockaddrNetlink{
			Family: syscall.AF_NETLINK,
		}
		if err := syscall.Bind(sk.Fd, local); err != nil {
			return err
		} else if sa, err := syscall.Getsockname(sk.Fd); err != nil {
			return err
		} else {
			local = sa.(*syscall.SockaddrNetlink)
		}
		if local == nil {
			return NLE_EXIST
		}
		sk.Local = *local
		sk.Flags &^= NL_OWN_PORT
	} else {
		if err := syscall.Bind(sk.Fd, &(sk.Local)); err != nil {
			return err
		}
	}
	return nil
}

// NlSocketAddMembership is same with libnl nl_socket_add_membership.
func NlSocketAddMembership(sk *NlSock, group int) error {
	if sk == nil {
		return NLE_BAD_SOCK
	}
	return syscall.SetsockoptInt(sk.Fd, SOL_NETLINK, syscall.NETLINK_ADD_MEMBERSHIP, group)
}

// NlSocketAddMembership is same with libnl nl_socket_drop_membership.
func NlSocketDropMembership(sk *NlSock, group int) error {
	if sk == nil {
		return NLE_BAD_SOCK
	}
	return syscall.SetsockoptInt(sk.Fd, SOL_NETLINK, syscall.NETLINK_DROP_MEMBERSHIP, group)
}

// msg.c

const NL_AUTO_PORT = 0
const NL_AUTO_SEQ = 0

// NlSendSimple is same with libnl nl_send_simple.
func NlSendSimple(sk *NlSock, family uint16, flags uint16, buf []byte) error {
	return sk.Request(syscall.NetlinkMessage{
		Header: syscall.NlMsghdr{
			Len:   syscall.NLMSG_HDRLEN + uint32(len(buf)),
			Type:  family,
			Flags: flags,
		},
		Data: buf,
	})
}

// nl.c

func completeMsg(sk *NlSock, hdr *syscall.NlMsghdr) {
	if hdr.Pid == NL_AUTO_PORT {
		hdr.Pid = sk.Local.Pid
	}
	if hdr.Seq == NL_AUTO_SEQ {
		hdr.Seq = sk.SeqNext
		sk.SeqNext++
	}
	hdr.Flags |= syscall.NLM_F_REQUEST
	if sk.Flags&NL_NO_AUTO_ACK == 0 {
		hdr.Flags |= syscall.NLM_F_ACK
	}
}

// NlCompleteMsg is same with libnl nl_complete_msg.
func NlCompleteMsg(sk *NlSock, msg []byte) {
	hdr := (*syscall.NlMsghdr)(unsafe.Pointer(&msg[0]))
	completeMsg(sk, hdr)
}

func (sk *NlSock) Request(msg syscall.NetlinkMessage) error {
	completeMsg(sk, &msg.Header)
	msg.Header.Len = syscall.NLMSG_HDRLEN + uint32(len(msg.Data))
	buf := make([]byte, syscall.NLMSG_HDRLEN+NLMSG_ALIGN(len(msg.Data)))
	copy(buf, (*[syscall.NLMSG_HDRLEN]byte)(unsafe.Pointer(&msg.Header))[:])
	copy(buf[syscall.NLMSG_HDRLEN:], msg.Data)
	return syscall.Sendto(sk.Fd, buf, 0, &sk.Peer)
}


text:
<title>SWIG:Examples:python:extend</title>

<tt>SWIG/Examples/python/extend/</tt>

Extending a simple C++ class in Python

This example illustrates the extending of a C++ class with cross language polymorphism.


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace Project1.API.ViewModels
{
    public class ApplicationUserViewModel
    {
        [Required]
        public string Name { get; set; }

        [Required]
        public string PhoneNumber { get; set; }

        [Required]
        [StringLength(16)]
        public string Password { get; set; }
    }
}


text:
import { Client, createError } from '../../core';
import { RequestError } from 'request-promise/errors';
import request from 'request-promise';

export default class RequestClient extends Client {

  request(url, method, body, headers = {}, options) { // eslint-disable-line max-params
    return request({
      ...options,
      body,
      headers: {
        ...this.defaultHeaders,
        ...headers
      },
      method,
      resolveWithFullResponse: true,
      strictSSL: false,
      url
    })
      .then(response => this._formatResponse(response))
      .catch(response => Promise.reject(response instanceof RequestError ? response : createError(this._formatResponse(response.response), response)));
  }

  _formatResponse({ body, headers, statusCode }) {
    return {
      body: this._parseBody(body),
      headers,
      status: statusCode
    };
  }

  _parseBody(body) {
    try {
      return JSON.parse(body);
    } catch (e) {
      return body;
    }
  }

}


text:
<?php

class Google_Service_Sheets_FilterCriteria extends Google_Collection
{
  protected $collection_key = 'hiddenValues';
  protected $conditionType = 'Google_Service_Sheets_BooleanCondition';
  protected $conditionDataType = '';
  public $hiddenValues;

  public function setCondition(Google_Service_Sheets_BooleanCondition $condition)
  {
    $this->condition = $condition;
  }
  public function getCondition()
  {
    return $this->condition;
  }
  public function setHiddenValues($hiddenValues)
  {
    $this->hiddenValues = $hiddenValues;
  }
  public function getHiddenValues()
  {
    return $this->hiddenValues;
  }
}


text:
using System;
using Nortal.Utilities.MessenteSms;

namespace ExampleApplication
{
	public partial class Default : System.Web.UI.Page
	{
		protected void BalanceCheckingButton_Click(object sender, EventArgs e)
		{
			var smsAgent = new MessenteAgent();
			var messenteResponse = smsAgent.GetAccountBalance();

			AccountBalance.Text = messenteResponse.IsSuccess
				? messenteResponse.SuccessResult + "EUR"
				: "Request failed: " + messenteResponse.FailureReason;
		}

		protected void MessageSendingButton_Click(object sender, EventArgs e)
		{
			var options = new SmsSendingOptions();
			options.Sender = "+37256662995";
			options.DelayedSendTime = DateTime.UtcNow.AddMinutes(1);
			options.DeliveryReportUri = null;

			var smsAgent = new MessenteAgent();
			var messenteResponse = smsAgent.SendMessage(toPhone.Text, messageContent.Text, options);

			MessageSendingResponse.Text = messenteResponse.IsSuccess
				? "Successfully gave message to messente server, sms id: " + messenteResponse.SuccessResult
				: "Sending failed: " + messenteResponse.FailureReason;
		}
	}
}


text:
module("WebGL Transparency", {});

test("Pick transparency values", 2, function () {
    stop();
    var frameLoaded = Q.fcall(promiseIFrameLoaded, "scenes/transparency.html");

    var test = frameLoaded.then(function (doc) {
        var scene = doc.querySelector("#xml3DElem");
        return scene;
    }).then(promiseSceneRendered).then(function (s) {
        var actual = XML3DUnit.getPixelValue(getContextForXml3DElement(s), 150, 100);
        QUnit.closePixel(actual, [128, 153, 102, 255], 1, "Mixed cyan and yellow");
    });

    test.fin(QUnit.start).done();
});

test("ProgramObject.hastransparency is set correctly", function () {
    stop();
    var frameLoaded = Q.fcall(promiseIFrameLoaded, "scenes/transparency.html");
    var material;

    var test = frameLoaded.then(function (doc) {
        var scene = doc.querySelector("#xml3DElem");
        var h = getHandler(scene);
        var shaderFactory = h.renderer.scene.shaderFactory;
        material = shaderFactory.getTemplateById(getWebGLAdapter(doc.getElementById("opaque"))._materialConfiguration.id).shaderClosures[0];
        ok(material, "Found #opaque material");
        if (material) equal(material.hasTransparency(), false, "Opaque material has no transparency set");

        material = shaderFactory.getTemplateById(getWebGLAdapter(doc.getElementById("non-opaque"))._materialConfiguration.id).shaderClosures[0];
        ok(material, "Found #non-opaque material");
        if (material) equal(material.hasTransparency(), true, "Non-Opaque material has transparency set");

        material = shaderFactory.getTemplateById(getWebGLAdapter(doc.getElementById("matte"))._materialConfiguration.id).shaderClosures[0];
        ok(material, "Found #matte material");
        if (material) equal(material.hasTransparency(), false, "Matte material is always opaque");

        var opacityAttribute = doc.getElementById("change_transparencyAttribute");

        material = shaderFactory.getTemplateById(getWebGLAdapter(doc.getElementById("change"))._materialConfiguration.id).shaderClosures[0];

        ok(material, "Found #change material");
        equal(material.hasTransparency(), false, "Initially opaque");
        opacityAttribute.textContent = "0.5";

        return scene;
    }).then(promiseSceneRendered).then(function (s) {
        equal(material.hasTransparency(), true, "Changed after setting opacity parameter to 0.5");
    });

    test.fin(QUnit.start).done();

});

test("Opacity override of non-transparent material", 3, function () {
    stop();
    var frameLoaded = Q.fcall(promiseIFrameLoaded, "scenes/webgl-rendering02.html");

    var test = frameLoaded.then(function (doc) {
        doc.getElementById("tranparencyGroup").style.display = 'inherit';
        return doc.querySelector("#xml3DElem");
    }).then(promiseSceneRendered).then(function (s) {
        var actual = XML3DUnit.getPixelValue(getContextForXml3DElement(s), 100, 100);
        deepEqual(actual, [255,127,127,255], "Override caused obj to be rendered with transparency");

        var override = s.querySelector("#opacityOverride");
        override.parentElement.removeChild(override);
        return s;
    }).then(promiseSceneRendered).then(function(s) {
        var actual = XML3DUnit.getPixelValue(getContextForXml3DElement(s), 100, 100);
        deepEqual(actual, [255,255,255,255], "Removed override, obj now opaque");
    });
    test.fin(QUnit.start).done();
});


text:
package com.gemstone.gemfire.cache;

import java.io.*;
import java.util.*;
import com.gemstone.gemfire.distributed.Role;
import com.gemstone.gemfire.distributed.internal.membership.InternalRole;

/**
 * Indicates that an attempt to send a distributed cache event to one or more
 * {@link MembershipAttributes#getRequiredRoles required roles} may have
 * failed.  Failure may be caused by departure of one or more required roles
 * while sending the message to them.  If the region scope is {@linkplain
 * com.gemstone.gemfire.cache.Scope#DISTRIBUTED_NO_ACK DISTRIBUTED_NO_ACK} or
 * {@linkplain com.gemstone.gemfire.cache.Scope#GLOBAL GLOBAL} then failure
 * may be caused by one or more required roles not acknowledging receipt of
 * the message.
 *
 * @author Kirk Lund
 * @since 5.0
 */
public class RegionDistributionException extends RegionRoleException {
private static final long serialVersionUID = -5950359426786805646L;

  /**
   * Set of missing required roles causing access to the region to fail.
   * failedRoles is transient to avoid NotSerializableException. See {@link
   * #writeObject} and {@link #readObject} for custom serialization.
   */
  private transient Set failedRoles = Collections.EMPTY_SET;

  /**
   * Constructs a RegionDistributionException with a message.
   * @param s the String message
   * @param regionFullPath full path of region for which access was attempted
   * @param failedRoles the required roles that caused this exception
   */
  public RegionDistributionException(String s, String regionFullPath, Set failedRoles) {
    super(s, regionFullPath);
    this.failedRoles = failedRoles;
    if (this.failedRoles == null) {
      this.failedRoles = Collections.EMPTY_SET;
    }
  }

  /**
   * Constructs a RegionDistributionException with a message and
   * a cause.
   * @param s the String message
   * @param regionFullPath full path of region for which access was attempted
   * @param failedRoles the required roles that caused this exception
   * @param ex the Throwable cause
   */
  public RegionDistributionException(String s,  String regionFullPath, Set failedRoles, Throwable ex) {
    super(s, regionFullPath, ex);
    this.failedRoles = failedRoles;
    if (this.failedRoles == null) {
      this.failedRoles = Collections.EMPTY_SET;
    }
  }

  /**
   * Returns the required roles that caused this exception. One or more
   * roles failed to receive a cache distribution message or acknowledge
   * receipt of that message.
   * @return the required roles that caused this exception
   */
  public Set getFailedRoles() {
    return this.failedRoles;
  }

  /**
   * Override writeObject which is used in serialization. Customize
   * serialization of this exception to avoid escape of InternalRole
   * which is not Serializable.
   */
  private void writeObject(java.io.ObjectOutputStream out)
  throws IOException {
    out.defaultWriteObject();
    // transform roles to string names which are serializable...
    Set roleNames = new HashSet(this.failedRoles.size());
    for (Iterator iter = this.failedRoles.iterator(); iter.hasNext();) {
      String name = ((Role)iter.next()).getName();
      roleNames.add(name);
    }
    out.writeObject(roleNames);
  }

  /**
   * Override readObject which is used in serialization. Customize
   * serialization of this exception to avoid escape of InternalRole
   * which is not Serializable.
   */
  private void readObject(java.io.ObjectInputStream in)
  throws IOException, ClassNotFoundException {
    in.defaultReadObject();
    // transform string names which are serializable back into roles...
    Set roleNames = (Set)in.readObject();
    Set roles = new HashSet(roleNames.size());
    for (Iterator iter = roleNames.iterator(); iter.hasNext();) {
      String name = (String) iter.next();
      roles.add(InternalRole.getRole(name));
    }
    this.failedRoles = roles;
  }

}


text:
input {
  display: block;
  margin-top: 10px;
  padding-left: 20px;
  width: 200px;
  height: 36px;
  background: transparent;
  border: .5px solid #ededed;
  border-radius: 4px;
  outline: none;
}

input[type='submit'] {
  padding: 0;
  background: #5eb288;
  color: white;
  border: none;
}


text:
namespace ros_http_video_streamer
{

/// A request received from a client.
struct request
{
  std::string method;
  std::string uri;
  int http_version_major;
  int http_version_minor;
  std::vector<header> headers;
};

} // ros_http_video_streamer

#endif // HTTP_SERVER3_REQUEST_HPP


text:
package hello.world;

import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.JavaDelegate;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.runtime.ProcessInstanceQuery;

/**
 * Business Process Task that sends notifications about new incidents to a dedicated exchange.
 */
public class HelloWorldTask implements JavaDelegate {

    private final RuntimeService runtimeService;

    /**
     * Full value constructor.
     *
     * @param runtimeService the camunda runtime service handle
     */
    public HelloWorldTask(final RuntimeService runtimeService) {
        this.runtimeService = runtimeService;
    }

    @Override
    public void execute(DelegateExecution execution) throws Exception {

        String processInstanceId = execution.getProcessInstanceId();

        System.out.println(
                "Entering HelloWorldTask.execute (processInstanceId=" + processInstanceId + ")");

        ProcessInstanceQuery query =
                runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId);
        ProcessInstance pi = query.singleResult();

        if (pi == null) {
            System.out
                    .println("WARN - No process instance with id " + processInstanceId + " found!");
        } else {
            System.out.println("Hello World!");
        }

        System.out.println(
                "Exiting HelloWorldTask.execute (processInstanceId=" + processInstanceId + ")");

    }

}


text:
package gov.nasa.arc.mct.chronology;

import gov.nasa.arc.mct.chronology.event.ChronologicalEvent;
import gov.nasa.arc.mct.chronology.event.ChronologicalInstant;
import gov.nasa.arc.mct.chronology.event.ChronologicalInterval;

import java.util.List;

/**
 * A Chronology describes an ordered set of events.
 *
 * A component that contains or manages a model which has some sequential nature may
 * publish this information by offering a Chronology through getCapability().
 *
 * @author vwoeltje
 *
 * @param <T> the type of object which would describe a point within this Chronology
 */
public interface Chronology<T extends ChronologicalInstant> {

	/**
	 * Get the domain in which the events reside - for instance, the UNIX time domain.
	 * The domain is used to perform operations and comparisons involving events in a
	 * generic way.
	 *
	 * @return the domain in which events of this Chronology exist
	 */
	public ChronologyDomain<T>         getDomain();

	/**
	 * Get all events contained within this chronology.
	 *
	 * @return a list of all events in the chronology
	 */
	public List<ChronologicalEvent<T>> getEvents();

	/**
	 * Get a list of events within a given interval.
	 *
	 * @param interval describes the start and end instants of interest for this request
	 * @return a list of all events within the interval
	 */
	public List<ChronologicalEvent<T>> getEvents(ChronologicalInterval<T> interval);

	/**
	 * Determine whether or not this Chronology may be changed within MCT
	 * (some Chronologies may represent read-only data)
	 * @return true if the Chronology may be changed within MCT
	 */
	public boolean                     isMutable();

	/**
	 * Adds a new event to this Chronology.
	 * Note that a Chronology behaves differently from most containers, in that a reference to the specific
	 * event object added will most likely not be retained; rather
	 * @param event the event to add to this Chronology
	 * @param start the start time (will override the event's own start & end)
	 * @return true if the event was successfully added; otherwise false
	 */
	public boolean add(ChronologicalEvent<T> event, T start);

	/**
	 * Remove an event from this Chronology.
	 * @param event the event to be removed.
	 * @return true if the event was successfully removed; otherwise false
	 */
	public boolean remove(ChronologicalEvent<T> event);
}