text:
import demistomock as demisto
from CommonServerPython import *  # noqa: E402 lgtm [py/polluting-import]
from CommonServerUserPython import *  # noqa: E402 lgtm [py/polluting-import]

# IMPORTS
import json
import copy
import requests
from datetime import datetime

import dateparser

# Disable insecure warnings
requests.packages.urllib3.disable_warnings()

# CONSTANTS
DATE_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
MAX_INCIDENTS = 100

class Client(BaseClient):
    """ Client to communicate with the Bastille service API """

    @staticmethod
    def _build_event_query_params(site, concentrator, map, protocol=None, since=None,
                                  until=None, tags=None, event_id=None,
                                  limit=MAX_INCIDENTS):
        """ Build dictionary of common event query parameters """

        if isinstance(since, datetime):
            since = str(since.timestamp())
        if isinstance(until, datetime):
            until = str(until.timestamp())

        params = {
            'site': site,
            'concentrator': concentrator,
            'map': map,
            'limit': limit
        }

        if protocol is not None:
            params['protocol'] = protocol
        if since is not None:
            params['since'] = since
        if until is not None:
            params['until'] = until
        if tags is not None:
            params['tags'] = tags
        if event_id is not None:
            params['event_id'] = event_id

        return params

    def get_zone_events(self, site, concentrator, map, zone=None, protocol=None,
                        since=None, until=None, tags=None, event_id=None,
                        limit=MAX_INCIDENTS):
        """ Get detections that occurred in one given or all zones """

        url_suffix = '/detection/zones'

        params = self._build_event_query_params(site, concentrator, map, protocol, since,
                                                until, tags, event_id, limit)
        if zone is not None:
            params['zone'] = zone

        return self._http_request(method='GET', url_suffix=url_suffix, params=params)

    def get_device_events(self, site, concentrator, map, transmitter_id=None,
                          protocol=None, since=None, until=None, tags=None, event_id=None,
                          limit=MAX_INCIDENTS):
        """ Get device detection events for one given transmitter """

        url_suffix = '/detection/devices'

        params = self._build_event_query_params(site, concentrator, map, protocol, since,
                                                until, tags, event_id, limit)
        params['transmitter_id'] = transmitter_id

        return self._http_request(method='GET', url_suffix=url_suffix, params=params)

    @staticmethod
    def _build_tag_action_body(site, concentrator, map, transmitter_id, tag):
        """ Build dictionary of common device tagging action query body entries """

        data = {
            'site': site,
            'concentrator': concentrator,
            'map': map,
            'transmitter_id': transmitter_id,
            'tag': tag
        }

        return data

    def add_device_tag(self, site, concentrator, map, transmitter_id, tag):
        """ Add tag to a device """

        url_suffix = 'admin/devices/action.addTag'

        data = self._build_tag_action_body(site, concentrator, map, transmitter_id, tag)

        return self._http_request(method='POST', url_suffix=url_suffix, json_data=data)

    def remove_device_tag(self, site, concentrator, map, transmitter_id, tag):
        """ Remove tag from an existing device """

        url_suffix = 'admin/devices/action.removeTag'

        data = self._build_tag_action_body(site, concentrator, map, transmitter_id, tag)

        return self._http_request(method='POST', url_suffix=url_suffix, json_data=data)

def test_module(client):
    """ Check connection to the Bastille API service """

    try:
        site, concentrator, map = get_site_params()
        client.get_zone_events(limit=0, site=site, concentrator=concentrator, map=map)
    except DemistoException as exc:
        exc_msg = str(exc)
        if '[404]' in exc_msg or 'ConnectionError' in exc_msg:
            result = 'Server not found: check server URL'
        elif '[401]' in exc_msg or '[403]' in exc_msg:
            result = 'Authorization error: check API key'
        elif '[500]' in exc_msg:
            result = 'Internal server error'
        else:
            result = f'Unknown error {exc_msg}'
    else:
        result = 'ok'

    return result

def get_site_params():
    """ Helper to get the area related integration parameters """

    params = demisto.params()
    site = params.get('site')
    concentrator = params.get('concentrator')
    map = params.get('map')

    return site, concentrator, map

def get_event_args(args):
    """ Helper to get the common event related command arguments """

    protocol = args.get('protocol')
    since = args.get('since')
    until = args.get('until')
    limit = args.get('limit')
    tags = args.get('tags')
    event_id = args.get('event_id')

    if isinstance(since, str):
        since_date = dateparser.parse(since, settings={'TIMEZONE': 'UTC'})
        assert since_date is not None, f'failed parsing {since}'
        since = since_date.timestamp()
    if isinstance(until, str):
        until_date = dateparser.parse(until, settings={'TIMEZONE': 'UTC'})
        assert until_date is not None, f'failed parsing {until}'
        until = until_date.timestamp()

    return protocol, since, until, limit, tags, event_id

def format_timestamp(timestamp):
    """ Convert unix epoch to ISO formatted timestamp """

    return datetime.utcfromtimestamp(timestamp).astimezone().isoformat()

def parse_events(events, readable_fields):
    """ Helper to parse common event command response """

    for event in events:
        event['first_seen'] = {
            'time': format_timestamp(event['first_seen']['time_s']),
            'position': [round(p, 2) for p in event['first_seen']['position']]
        }
        if 'last_seen' in event:
            event['last_seen'] = {
                'time': format_timestamp(event['last_seen']['time_s']),
                'position': [round(p, 2) for p in event['last_seen']['position']]
            }
    readable_events = [{f: e[f] for f in readable_fields} for e in events]

    return events, readable_events

def get_zone_events_command(client, args):
    """ Command to fetch zone events """

    site, concentrator, map = get_site_params()
    protocol, since, until, limit, tags, event_id = get_event_args(args)
    zone = args.get('zone')

    events = client.get_zone_events(site=site, concentrator=concentrator, map=map,
                                    zone=zone, protocol=protocol, since=since,
                                    until=until, limit=limit, tags=tags,
                                    event_id=event_id)

    readable_fields = ['event_id', 'area', 'zone_name', 'tags', 'device_info',
                       'emitter', 'first_seen', 'last_seen']

    raw_response = copy.deepcopy(events)
    context_events, readable_events = parse_events(events, readable_fields)

    readable_output = tableToMarkdown('Zone Events', readable_events, readable_fields)
    context_output = {'Bastille.ZoneEvent(val.event_id == obj.event_id)': context_events}

    return readable_output, context_output, raw_response

def get_device_events_command(client, args):
    """ Command to fetch device detection events """

    site, concentrator, map = get_site_params()
    protocol, since, until, limit, tags, event_id = get_event_args(args)
    transmitter_id = args.get('transmitter_id')

    events = client.get_device_events(site=site, concentrator=concentrator, map=map,
                                      protocol=protocol, since=since, until=until,
                                      limit=limit, tags=tags, event_id=event_id,
                                      transmitter_id=transmitter_id)

    readable_fields = ['event_id', 'area', 'tags', 'device_info', 'emitter',
                       'first_seen', 'last_seen']

    raw_response = copy.deepcopy(events)
    context_events, readable_events = parse_events(events, readable_fields)

    readable_output = tableToMarkdown('Device Events', readable_events, readable_fields)
    context_output = {
        'Bastille.DeviceEvent(val.event_id == obj.event_id)': context_events}

    return readable_output, context_output, raw_response

def add_device_tag_command(client, args):
    """ Command to add tag to an existing admin devices entry """

    site, concentrator, map = get_site_params()

    transmitter_id = args.get('transmitter_id')
    tag = args.get('tag')

    result = client.add_device_tag(site=site, concentrator=concentrator, map=map,
                                   transmitter_id=transmitter_id, tag=tag)

    if 'status' not in result:
        return_error('Failed to add device tag')

    return result['status'], {}, result

def remove_device_tag_command(client, args):
    """ Command to remove tag from an existing admin devices entry """

    site, concentrator, map = get_site_params()

    transmitter_id = args.get('transmitter_id')
    tag = args.get('tag')

    result = client.remove_device_tag(site=site, concentrator=concentrator, map=map,
                                      transmitter_id=transmitter_id, tag=tag)

    if 'status' not in result:
        return_error('Failed to remove device tag')

    return result['status'], {}, result

def fetch_incidents(client, last_run, first_fetch_time):
    """ Callback to fetch incidents periodically """

    last_fetch_time = last_run.get('last_fetch', first_fetch_time)

    site, concentrator, map = get_site_params()

    params = demisto.params()
    tags = params.get('tags') or None
    event_types = params.get('event_types')

    zone_events = []
    if 'all' in event_types or 'zone_event' in event_types:
        zone_events = client.get_zone_events(concentrator=concentrator, map=map,
                                             site=site, tags=tags, since=last_fetch_time)

    device_events = []
    if 'all' in event_types or 'device_event' in event_types:
        device_events = client.get_device_events(concentrator=concentrator, map=map,
                                                 site=site, tags=tags,
                                                 since=last_fetch_time)

    events = zone_events + device_events
    current_fetch_time = last_fetch_time

    incidents = []
    for event in events:
        event_time = int(event['time_s'])
        incident = {
            'name': event['event_type'],
            'occurred': datetime.utcfromtimestamp(event_time).strftime(
                DATE_FORMAT),
            'rawJSON': json.dumps(event),
        }

        if event_time > current_fetch_time:
            incidents.append(incident)

        if event_time > last_fetch_time:
            last_fetch_time = event_time

    next_run = {'last_fetch': last_fetch_time}

    return next_run, incidents

def main():
    """ Parse and validate integration parameters """

    params = demisto.params()
    api_url = urljoin(params['api_url'])
    api_key = params.get('api_key')
    proxy = params.get('proxy', False)
    verify_certificate = not params.get('insecure', False)

    headers = {
        'Content-Type': 'application/json',
        'x-api-key': api_key,
    }

    first_fetch_date = dateparser.parse(params.get('first_fetch', '5 minutes'), settings={'TIMEZONE': 'UTC'})
    assert first_fetch_date is not None
    first_fetch = first_fetch_date.timestamp()

    try:
        handle_proxy()
        client = Client(api_url, headers=headers, verify=verify_certificate, proxy=proxy)

        if demisto.command() == 'test-module':
            result = test_module(client)
            demisto.results(result)

        elif demisto.command() == 'fetch-incidents':
            next_run, incidents = fetch_incidents(
                client=client,
                last_run=demisto.getLastRun(),
                first_fetch_time=first_fetch,
            )
            demisto.setLastRun(next_run)
            demisto.incidents(incidents)

        elif demisto.command() == 'bastille-get-zone-events':
            results = get_zone_events_command(client, demisto.args())
            return_outputs(*results)

        elif demisto.command() == 'bastille-get-device-events':
            results = get_device_events_command(client, demisto.args())
            return_outputs(*results)

        elif demisto.command() == 'bastille-add-device-tag':
            results = add_device_tag_command(client, demisto.args())
            return_outputs(*results)

        elif demisto.command() == 'bastille-remove-device-tag':
            results = remove_device_tag_command(client, demisto.args())
            return_outputs(*results)

    except Exception as e:
        return_error(
            f'Failed to execute {demisto.command()} command. Error: {str(e)}')

if __name__ in ('__main__', '__builtin__', 'builtins'):
    main()


text:
package org.apache.geronimo.connector.deployment;

import javax.enterprise.deploy.model.DeployableObject;
import javax.enterprise.deploy.shared.ModuleType;
import javax.enterprise.deploy.spi.DeploymentConfiguration;

import org.apache.geronimo.connector.deployment.dconfigbean.ResourceAdapterDConfigRoot;
import org.apache.geronimo.connector.deployment.dconfigbean.ResourceAdapter_1_0DConfigRoot;
import org.apache.geronimo.connector.deployment.jsr88.Connector15DCBRoot;
import org.apache.geronimo.deployment.ModuleConfigurer;
import org.apache.geronimo.gbean.GBeanInfo;
import org.apache.geronimo.gbean.GBeanInfoBuilder;
import org.apache.geronimo.j2ee.j2eeobjectnames.NameFactory;

/**
 *
 *
 * @version $Rev$ $Date$
 */
public class RARConfigurer implements ModuleConfigurer {

    public DeploymentConfiguration createConfiguration(DeployableObject deployable) {
        if (ModuleType.RAR.equals(deployable.getType())) {
            if (deployable.getDDBeanRoot().getDDBeanRootVersion().equals("1.5")) {
                return new RARConfiguration(deployable, new Connector15DCBRoot(deployable.getDDBeanRoot()));
            }
            String[] specVersion = deployable.getDDBeanRoot().getText("connector/spec-version");
            if (specVersion.length > 0 && "1.0".equals(specVersion[0])) {
                return new RARConfiguration(deployable, new ResourceAdapter_1_0DConfigRoot(deployable.getDDBeanRoot()));
            }
            throw new IllegalArgumentException("Unknown resource adapter version: " + deployable.getDDBeanRoot().getDDBeanRootVersion());
        } else {
            return null;
        }
    }

    public static final GBeanInfo GBEAN_INFO;

    static {
        GBeanInfoBuilder infoFactory = GBeanInfoBuilder.createStatic(RARConfigurer.class, NameFactory.DEPLOYMENT_CONFIGURER);
        infoFactory.addInterface(ModuleConfigurer.class);
        GBEAN_INFO = infoFactory.getBeanInfo();
    }

    public static GBeanInfo getGBeanInfo() {
        return GBEAN_INFO;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.wso2.carbon.event.processor.core.internal.storm;

import org.apache.log4j.Logger;
import org.wso2.carbon.databridge.commons.Credentials;
import org.wso2.carbon.databridge.commons.Event;
import org.wso2.carbon.databridge.commons.StreamDefinition;
import org.wso2.carbon.databridge.commons.thrift.utils.HostAddressFinder;
import org.wso2.carbon.databridge.core.AgentCallback;
import org.wso2.carbon.databridge.core.DataBridge;
import org.wso2.carbon.databridge.core.Utils.AgentSession;
import org.wso2.carbon.databridge.core.definitionstore.InMemoryStreamDefinitionStore;
import org.wso2.carbon.databridge.core.exception.DataBridgeException;
import org.wso2.carbon.databridge.core.internal.authentication.AuthenticationHandler;
import org.wso2.carbon.databridge.receiver.thrift.ThriftDataReceiver;
import org.wso2.carbon.databridge.receiver.thrift.ThriftDataReceiverFactory;
import org.wso2.carbon.event.processor.core.ExecutionPlanConfiguration;
import org.wso2.carbon.event.processor.core.internal.listener.SiddhiOutputStreamListener;
import org.wso2.carbon.event.processor.storm.common.client.ManagerServiceClient;
import org.wso2.carbon.event.processor.storm.common.helper.StormDeploymentConfigurations;
import org.wso2.carbon.event.processor.storm.common.util.StormUtils;
import org.wso2.carbon.user.api.UserStoreException;

import java.net.SocketException;
import java.util.HashMap;
import java.util.List;

/**
 * Receives events from the Event publisher bolt running on storm. There will be one SindhiStormOutputEventListener instance
 * per execution plan per tenant (all exported streams of execution plan are handled form a single instance). When events are
 * received from storm, the event  will be directed to the relevant output stream listener depending on the stream to forward
 * the event to the relevant output adaptor for the stream.
 */
public class SindhiStormOutputEventListener implements AgentCallback {
    private static Logger log = Logger.getLogger(SindhiStormOutputEventListener.class);
    private ExecutionPlanConfiguration executionPlanConfiguration;
    private ThriftDataReceiver thriftDataReceiver;
    private int listeningPort;
    private int tenantId;
    private String thisHostIp;
    private int cepMangerPort = StormDeploymentConfigurations.getCepManagerPort();
    private String cepMangerHost = StormDeploymentConfigurations.getCepManagerHost();
    private HashMap<String, SiddhiOutputStreamListener> streamNameToOutputStreamListener = new HashMap<String, SiddhiOutputStreamListener>();
    private static final String DEFAULT_STREAM_VERSION = "1.0.0";
    private int minListeningPort = StormDeploymentConfigurations.getMinListingPort();
    private int maxListeningPort = StormDeploymentConfigurations.getMaxListeningPort();

    public SindhiStormOutputEventListener(ExecutionPlanConfiguration executionPlanConfiguration, int tenantId){
        this.executionPlanConfiguration = executionPlanConfiguration;
        this.tenantId = tenantId;
        init();
    }

    public void registerOutputStreamListener(String siddhiStreamName, SiddhiOutputStreamListener outputStreamListener){
        log.info("Registering Output stream listener for Siddhi stream " + siddhiStreamName);
        streamNameToOutputStreamListener.put(siddhiStreamName + ":" + DEFAULT_STREAM_VERSION, outputStreamListener);
    }

    @Override
    public void definedStream(StreamDefinition streamDefinition, int tenantId) {
        log.info(streamDefinition.getStreamId() + " Internal data bridge stream defined for tenant " + tenantId + " to communicate with storm.");
    }

    @Override
    public void removeStream(StreamDefinition streamDefinition, int tenantId) {
        // This will never happen since storm bolt does not remove streams once defined.
        log.warn(streamDefinition.getStreamId() + " data bridge stream removed for tenant " + tenantId);
    }

    @Override
    public void receive(List<Event> events, Credentials credentials) {
        for (Event event: events){
            SiddhiOutputStreamListener outputStreamListener = streamNameToOutputStreamListener.get(event.getStreamId());

            if (outputStreamListener != null){
                outputStreamListener.sendEventData(event.getPayloadData());
            }else{
                log.error("Cannot find output event listener for stream " + event.getStreamId() + " in execution plan " + executionPlanConfiguration.getName()
                        + " of tenant " + tenantId);
            }
        }
    }

    private void registerWithCepMangerService(){
        log.info("Registering CEP Publisher for " + executionPlanConfiguration.getName() + ":" + tenantId + " at " + thisHostIp + ":" + listeningPort);
        ManagerServiceClient client = new ManagerServiceClient(cepMangerHost, cepMangerPort, null);
        client.registerCepPublisher(executionPlanConfiguration.getName(), tenantId, thisHostIp, listeningPort, StormDeploymentConfigurations.getReconnectInterval());
    }

    private void init(){
        log.info("[CEP Publisher]Initializing Storm output event listener for execution plan '" + executionPlanConfiguration.getName() + "'"
                 + "(TenantID=" + tenantId + ")");

        DataBridge databridge = new DataBridge(new AuthenticationHandler() {
            @Override
            public boolean authenticate(String userName, String password) { return true;}
            @Override
            public String getTenantDomain(String userName) { return "admin";}
            @Override
            public int getTenantId(String s) throws UserStoreException { return -1234;}
            @Override
            public void initContext(AgentSession agentSession) {}
            @Override
            public void destroyContext(AgentSession agentSession) {}
        }, new InMemoryStreamDefinitionStore());

        databridge.subscribe(this);
        try {
            selectPort();
            thriftDataReceiver = new ThriftDataReceiverFactory().createAgentServer(listeningPort, databridge);
            thisHostIp = HostAddressFinder.findAddress("localhost");
            thriftDataReceiver.start(thisHostIp);
            registerWithCepMangerService();
        } catch (SocketException e) {
            log.error("Failed to start Thrift listener for execution plan :" + executionPlanConfiguration.getName(), e);
        } catch (DataBridgeException e) {
            log.error("Failed to start Thrift listener for execution plan :" + executionPlanConfiguration.getName(), e);
        }
    }

    private void selectPort(){
        for (int i = minListeningPort; i <= maxListeningPort; i++){
            if (!StormUtils.isPortUsed(i)){
                listeningPort = i;
                break;
            }
        }
    }

}


text:
# angular-froala
angular-froala provides AngularJS bindings to the froala WYSIWYG editor.

###Looking for Version 2? Check out the `editorV.2` branch

## Installation

1. Clone this repo or download the zip.
2. Run `bower install` or Download the editor from [http://froala.com/wysiwyg-editor/](http://froala.com/wysiwyg-editor/) and jQuery
3. Load Froala WYSIWYG editor, jQuery and the angular-froala files into your project
	- src/angular-froala.js
	- src/froala-sanitize.js

## Usage

1. Add the `froala` dependency to your Angular project. example:
	* `angular.module('myApp', ['froala'])`
2. Create a textarea with the froala directive in your view and give it a model, where `myHtml` is a variable on `$scope`.
	* `<textarea froala ng-model="myHtml"></textarea> `

###Options

**Setting Defaults**: to set defaults for the editor pass a config object to angular.value with the key `froalaConfig` like this:
```javascript
angular.module('myApp', ['froala']).
	value('froalaConfig', {
		inlineMode: false,
		placeholder: 'Enter Text Here'
	});
```

**From the Controller**: to set options from the controller, create an options object on scope and simply pass it to the froala directive. example:

_app.js_

```javascript
function myCtrl($scope){
	$scope.myHtml = "<h1>Hello World</h1>"
	$scope.froalaOptions = {
		buttons : ["bold", "italic", "underline", "sep", "align", "insertOrderedList", "insertUnorderedList"]
	}
}
```
_view.html_

```html
<textarea froala="froalaOptions" ngModel="myHtml"></textarea>
```
View a list of all the options available in the [docs](http://froala.com/wysiwyg-editor/docs/options)

###Methods

To use the methods available, access the editor instance from your froalaOptions object `$scope.options.froala(method)` and use it as described in the [method docs](http://froala.com/wysiwyg-editor/docs/methods). example:

```javascript
function myCtrl($scope){
	$scope.myHtml = "";
	$scope.froalaOptions = {
		buttons : ["bold", "italic", "underline", "sep", "align", "insertOrderedList", "insertUnorderedList"]
	}

//Use the methods like this
$scope.froalaOptions.froala("getSelection");
```
###Events
 Events can be used one of two ways as an attribute on the directive, or passed in with the options.
####Attribute
_app.js_

```js
$scope.editorOnFocus = function(e, editor){
	//Do Something
}
```
_view.html_

```html
<textarea froala="froalaOptions" ngModel="myHtml" froala-event-focus="editorOnFocus"></textarea>
```
###options
_app.js_

```js
$scope.froalaOptions = {
	inlineMode: false,
	placeholder: "Edit Me",
	events : {
		focus : function(e, editor) {/* ... */}
	}
```

###Displaying Html

Using `ng-bind-html` will render your html on the page but the default angular-sanitize.js will strip out all style tags. Remedy this by including `froala-sanitize.js` instead. example: `<div ng-bind-html="myHtml"></div>`

Congrats all is done!

## License

The `angular-froala` project is under MIT license.

Froala Editor has [3 different licenses](http://froala.com/wysiwyg-editor/pricing) for commercial use.
For details please see [License Agreement](http://froala.com/wysiwyg-editor/terms).


text:
<?xml version="1.0" encoding="utf-8"?>

Editing Item Comments

How to edit comments on the Repository module. Note: The COMMENTS link displays the total number of comments for this item.

Search for the required item.

Click the COMMENTS (1) link. Existing comments for this item are now displayed in the User Comments panel.

Click the Edit   button beside the comment to be edited.

In the Comment text box, edit the comment as required.

               Click the Update button.The edited comment now displays a Comment edited message.

A Repository module displaying an edited Comment


text:
var MongoClient = require('mongodb').MongoClient,
    startup = require('./startup.js'),
    settings = require('./config.js'),
    Guid = require('Guid');
var bcrypt = require("bcrypt-nodejs");

var fullMongoUrl = settings.mongoConfig.serverUrl + settings.mongoConfig.database;
var exports = module.exports = {};
startup();
MongoClient.connect(fullMongoUrl)
    .then(function(db) {
        var myCollection = db.collection("party");

        // setup your body
	exports.getPartyById = function(partyId){
return myCollection.find({partyId: partyId}).toArray();
};

exports.getPartyBy_Id = function(_id){
	return myCollection.find({_id: _id}).toArray();
	};

	exports.createParty = function(partyId, partyName, createdBy, playList, config){
	return myCollection.insertOne({_id: Guid.create().toString(), partyId: partyId, partyName: partyName, createdBy: createdBy, playList: playList, config: config}).then(function(newParty){
        // todo tianchi
        return newParty.insertedId;

    }).then(function(partynew){
    	return exports.getPartyBy_Id(partynew);
    });

}

    });


text:
```sh
sudo npm install -g gulp # gulpが無ければ
npm install
gulp
```

index.htmlを開けば起動する


text:
package org.ojalgo.algebra;

/**
 * @author apete
 */
public interface ScalarOperation {

    public interface Addition<T, N extends Number> extends ScalarOperation {

        /**
         * @return this + scalarAddend.
         */
        T add(double scalarAddend);

        /**
         * @return this + scalarAddend.
         */
        T add(N scalarAddend);

    }

    public interface Division<T, N extends Number> extends ScalarOperation {

        /**
         * @return this / scalarDivisor.
         */
        T divide(double scalarDivisor);

        /**
         * @return this / scalarDivisor.
         */
        T divide(N scalarDivisor);

    }

    public interface Multiplication<T, N extends Number> extends ScalarOperation {

        /**
         * @return this * scalarMultiplicand.
         */
        T multiply(double scalarMultiplicand);

        /**
         * @return this * multiplicand.
         */
        T multiply(N scalarMultiplicand);

    }

    public interface Subtraction<T, N extends Number> extends ScalarOperation {

        /**
         * @return this - scalarSubtrahend.
         */
        T subtract(double scalarSubtrahend);

        /**
         * @return this - scalarSubtrahend.
         */
        T subtract(N scalarSubtrahend);

    }

}


text:
package br.com.trisoft.eventos.dao.hibernate;

import java.io.Serializable;
import java.util.List;

import br.com.trisoft.eventos.dao.ParticipanteEventoDAO;
import br.com.trisoft.eventos.model.Evento;
import br.com.trisoft.eventos.model.key.ParticipanteEventoId;
import br.com.trisoft.eventos.model.relationship.ParticipanteEvento;

public class HibernateParticipanteEventoDAO extends HibernateGenericDAO<ParticipanteEvento, Long>
		implements ParticipanteEventoDAO, Serializable {

	private static final long serialVersionUID = 1L;

	@Override
	public ParticipanteEvento buscarInscricao(ParticipanteEventoId id) {
		return getEntityManager().find(ParticipanteEvento.class, id);
	}

	@Override
	public void removerParticipanteInscrito(ParticipanteEvento participanteEvento) {
		getEntityManager()
				.remove(getEntityManager().getReference(ParticipanteEvento.class, participanteEvento.getId()));
	}

	@Override
	public List<ParticipanteEvento> buscarInscricaoComPaginacao(int first, int pageSize, Evento evento) {
		List<ParticipanteEvento> lista = getEntityManager()
				.createNamedQuery("ParticipanteEvento.buscarTodos", ParticipanteEvento.class)
				.setParameter("Evento", evento).setFirstResult(first).setMaxResults(pageSize).getResultList();
		return lista;
	}

	@Override
	public Long encontrarInscricaoQuantidade(Evento evento) {
		Long count = getEntityManager().createNamedQuery("ParticipanteEvento.contar", Long.class)
				.setParameter("Evento", evento).getSingleResult();
		return count;
	}

}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Config_model extends Base_model
{

	/*
	 * Content of the config file to alter
	 *
	 */
	static protected $content = NULL;

	/*
	 * Complete path to the config folder
	 *
	 */
	static protected $path = NULL;

	/*
	 * Name of the config file
	 *
	 */
	static protected $config_file = NULL;

	// --------------------------------------------------------------------

	/**
	 * Constructor
	 *
	 * @param	string  Path to the config file folder
	 *
	 */
	public function __construct()
	{
		// Ionize Core config file
		if (is_dir(realpath(APPPATH.'config')))
		{
			self::$path = realpath(APPPATH.'config').'/';
		}
		parent::__construct();
	}

	// --------------------------------------------------------------------

	/**
	 * Opens one config file
	 *
	 * @param	string			config file name
	 * @param 	null|string		Module name
	 */
	public function open_file($config_file, $module = NULL)
	{
		// Module config file ?
		if ( !is_null($module) && is_dir(realpath(MODPATH.$module.'/config')))
		{
			self::$path = realpath(MODPATH.$module.'/config').'/';
		}

		// Gets the content of the asked file
		if (is_file(realpath(self::$path.$config_file)))
		{
			self::$content = @file_get_contents(self::$path.$config_file);

			self::$config_file = $config_file;
		}
	}

	// --------------------------------------------------------------------

	/**
	 * Sets a config value
	 *
	 * @param $key
	 * @param $val
	 *
	 * @return bool
	 */
	public function set_config($key, $val)
	{
		if ( ! is_null(self::$content))
		{
			$pattern = '%(?sx)
				(
					\$'."config
					\[(['\"])
					(".$key.")
					\\2\]
					\s*=\s*
				)
				(.+?);
			%";

			$type = gettype($val);

			if ($type == 'string')
			{
				if (strtolower($val) == 'true')
					$val = var_export(TRUE, TRUE);

				else if (strtolower($val) == 'false')
					$val = var_export(FALSE, TRUE);

				else $val = "'".$val."'";
			}
			if ($type == 'boolean') $val = ($val ? var_export(TRUE, TRUE) : var_export(FALSE, TRUE) );

			if ($type == 'array')
			{
				$val = preg_replace("/[0-9]+ \=\>/i", '', var_export($val, TRUE));
				$val = str_replace("\n", "\r\n", $val);
			}

			self::$content = preg_replace($pattern, "\\1$val;", self::$content);

			return TRUE;
		}

		return FALSE;
	}

	// --------------------------------------------------------------------

	/**
	 * Change a config value
	 *
	 * @param	String	The config file name
	 * @param	String	key to change
	 * @param	Mixed	value to set to the key
	 * @param	String	Module name, in case of a module config file
	 *
	 * @return bool|int
	 */
	public function change($config_file, $key, $val, $module = NULL)
	{
		self::open_file($config_file, $module);

		self::set_config($key, $val);

		return self::save();
	}

	// --------------------------------------------------------------------

	/**
	 * Saves the config file
	 *
	 * @return bool
	 *
	 */
	public function save()
	{
		if ( ! is_null(self::$content))
		{
			$ret = @file_put_contents(self::$path.self::$config_file, self::$content);

			if ( ! $ret)
			{
				return FALSE;
			}
			return TRUE;
		}
		return FALSE;
	}
}

/* End of file config_model.php */
/* Location: ./application/models/config_model.php */


text:
/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <nuttx/config.h>

#include <errno.h>
#include <debug.h>

#include <nuttx/nx/nx.h>
#include "nxfe.h"

/****************************************************************************
 * Pre-Processor Definitions
 ****************************************************************************/

/****************************************************************************
 * Private Types
 ****************************************************************************/

/****************************************************************************
 * Private Data
 ****************************************************************************/

/****************************************************************************
 * Public Data
 ****************************************************************************/

/****************************************************************************
 * Private Functions
 ****************************************************************************/

/****************************************************************************
 * Public Functions
 ****************************************************************************/

/****************************************************************************
 * Name: nx_setbgcolor
 *
 * Description:
 *  Set the color of the background
 *
 * Input Parameters:
 *   handle  - The connection handle
 *   color - The color to use in the background
 *
 * Return:
 *   OK on success; ERROR on failure with errno set appropriately
 *
 ****************************************************************************/

int nx_setbgcolor(NXHANDLE handle,
                  nxgl_mxpixel_t color[CONFIG_NX_NPLANES])
{
  FAR struct nxfe_conn_s *conn = (FAR struct nxfe_conn_s *)handle;
  struct nxsvrmsg_setbgcolor_s outmsg;

#ifdef CONFIG_DEBUG
  if (!conn)
    {
      errno = EINVAL;
      return ERROR;
    }
#endif

  /* Format the fill command */

  outmsg.msgid = NX_SVRMSG_SETBGCOLOR;
  nxgl_colorcopy(outmsg.color, color);

  /* Forward the fill command to the server */

  return nxmu_sendserver(conn, &outmsg, sizeof(struct nxsvrmsg_setbgcolor_s));
}


text:
import React from "react"
import { theme } from "@looker/components"
import { DataDictionary } from "./DataDictionary"
import { ThemeProvider } from "styled-components"

export const Extension: React.FC = () => (
  <ThemeProvider theme={theme}>
    <DataDictionary />
  </ThemeProvider>
)


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

namespace FlowSimulation.Enviroment
{
    public sealed class Generator
    {
        private ulong _id;

        public Generator(ulong initValue = 0UL)
        {
            _id = initValue;
        }

        public void Reset(ulong initValue = 0UL)
        {
            _id = initValue;
        }

        public ulong GetID()
        {
            return ++_id;
        }
    }
}


text:
package Transactions;

require Exporter;
@ISA =  qw(Exporter);
@EXPORT = qw(handleTransactions );
@EXPORT_OK = qw(handleTransactions );

use strict;
use CGI qw(param unescape escape);

use lib '.';
use Reg_common;
use Defs;
use Utils;
use FormHelpers;
use HTMLForm;
use AuditLog;

use InvoicePay;
require Payments;
require TransLog;

# GET INFORMATION RELATING TO THIS MEMBERS TYPE (IE. COACH, PLAYER ETC)

sub handleTransactions	{
	my($action, $Data, $intTableID, $entityID)=@_;

	## TABLEID is PersonID or TeamID etc

	my $ID=param("tID") || 0;

  	my $resultHTML='';
	my $heading='';

  if ($action =~ /_TXN_LIST/) {
        $entityID = getLastEntityID($Data->{'clientValues'});
		($resultHTML,$heading) = TransLog::handleTransLogs('list', $Data, $entityID, $intTableID);
  }
  elsif ($action =~ /_TXN_EDIT/) {
		($resultHTML,$heading) = displayTransaction($Data, $intTableID, $ID, 1);
  }
  elsif ($action =~ /_TXN_ADD/) {
		($resultHTML,$heading) = displayTransaction($Data, $intTableID, 0, 1);
  }
  elsif ($action =~ /_TXN_DEL/) {
		($resultHTML,$heading) = deleteTransaction($Data, $intTableID, $ID);
  }
  if ($action =~ /_TXN_FAILURE/) {
	my $intLogID=param("ci") || '';
		Payments::processTransLogFailure($Data->{'db'}, $intLogID);
		($resultHTML,$heading) = ("There was an error processing the payment.  Please try again.", "Error with Payment");
  }

	if (! $heading)	{
		$heading = ($Data->{'SystemConfig'}{'txns_link_name'}) ? $Data->{'SystemConfig'}{'txns_link_name'} :  'Transactions';
	}
	#$heading ||= $Data->{'SystemConfig'}{'txns_link_name'} || 'Transactions';

	#$heading ||= 'Transactions';
  return ($resultHTML,$heading);

}

sub deleteTransaction	{
	my ($Data, $intPersonID, $id) = @_;
	my $db=$Data->{'db'} || undef;
	my $st = qq[
		DELETE FROM tblTransactions
		WHERE intID = $intPersonID
			AND intTransactionID = $id
			AND intTableType = $Data->{'clientValues'}{'currentLevel'}
	];
	my $query = $db->prepare($st);
	$query->execute;
  auditLog($id, $Data, 'Delete', 'Transaction');
  return ("Transaction has been deleted", "Transaction deleted");
}

sub displayTransaction	{

  my($Data, $TableID, $id, $edit) = @_;

    my $lang = $Data->{'lang'};
	my $db=$Data->{'db'} || undef;
    my $client=setClient($Data->{'clientValues'}) || '';
	my $target=$Data->{'target'} || '';
	my $option=$edit ? ($id ? 'edit' : 'add')  :'display' ;
	my $type2=param("ty2") || '';
#($Data->{'Realm'},$Data->{'RealmSubType'})=getRealm($Data);

	my $action = 'P_TXN_EDIT';
	$action = 'C_TXN_EDIT' if $Data->{'clientValues'}{'currentLevel'} == $Defs::LEVEL_CLUB;
    my $resultHTML = '';
	my $toplist='';

	my $entityID= getLastEntityID($Data->{'clientValues'}) || 0;
    $entityID=0 if ($entityID== $Defs::INVALID_ID);
	my %DataVals=();
	my $statement=qq[
		SELECT
      P.strName,
      T.* ,
      DATE_FORMAT(T.dtTransaction ,"%d/%m/%Y") AS dtTransaction,
      DATE_FORMAT(T.dtStart ,"%d/%m/%Y") AS dtStart,
      DATE_FORMAT(T.dtEnd ,"%d/%m/%Y") AS dtEnd,
      DATE_FORMAT(T.dtPaid ,"%d/%m/%Y") AS dtPaid,
			PParent.strName as ParentProductName,
			COUNT(tChildren.intTransactionID) as NumChildren,
			SUM(tChildren.curAmount) as AmountAlreadyPaid
		FROM tblTransactions as T INNER JOIN tblProducts as P ON (P.intProductID = T.intProductID)
		LEFT JOIN tblTransactions as tParent ON (tParent.intTransactionID= T.intParentTXNID)
		LEFT JOIN tblProducts as PParent ON (PParent.intProductID = tParent.intProductID)
		LEFT JOIN tblTransactions as tChildren ON (tChildren.intParentTXNID = T.intTransactionID and tChildren.intStatus=1 and tChildren.intProductID=T.intProductID)
		WHERE T.intID =$TableID
			AND T.intTableType=$Data->{'clientValues'}{'currentLevel'}
			AND T.intTransactionID = $id
		GROUP BY T.intTransactionID
	];

	my $query = $db->prepare($statement);
	my $RecordData={};
	$query->execute;
	my $dref=$query->fetchrow_hashref();
	$dref->{'NumChildren'} ||= 0;
	my $txnupdate=qq[
		UPDATE tblTransactions
			SET --VAL--
		WHERE intTransactionID=$id
	];
	my $txnadd=qq[
		INSERT INTO tblTransactions (intTXNEntityID, intID, intTableType, intRealmID, intRealmSubTypeID, dtTransaction, --FIELDS--)
			VALUES ($entityID, $TableID, $Data->{'clientValues'}{'currentLevel'}, $Data->{'Realm'}, $Data->{'RealmSubType'}, SYSDATE(), --VAL--)
	];

	 my $authLevel = $Data->{'clientValues'}{'authLevel'}||=$Defs::INVALID_ID;

        my $WHEREClub = '';
        if ($entityID) { # and $authLevel == $Defs::LEVEL_CLUB)        {
                $WHEREClub = qq[
                        AND ((intCreatedLevel=0 or intCreatedLevel > 3) or (intCreatedLevel = $Defs::LEVEL_CLUB and intCreatedID = $entityID))
                ];
        }

  my $prodSellLevel = qq[ AND (intMinSellLevel <= $Data->{'clientValues'}{'authLevel'} or intMinSellLevel=0)];
  my $st_prods=qq[ SELECT intProductID, strName FROM tblProducts WHERE intProductType NOT IN ($Defs::PROD_TYPE_MINFEE) AND intRealmID = $Data->{'Realm'} and  intInactive = 0 $WHEREClub AND intProductSubRealmID IN (0, $Data->{'RealmSubType'}) $prodSellLevel];

  my $st_paymenttypes=qq[ SELECT intPaymentTypeID, strPaymentType FROM tblPaymentTypes WHERE intRealmID = $Data->{'Realm'}];
  my ($prods_vals,$prods_order)=getDBdrop_down_Ref($Data->{'db'},$st_prods,'');
  my ($paytypes_vals,$paytypes_order)=getDBdrop_down_Ref($Data->{'db'},$st_paymenttypes,'');

	my $readonly = ($dref->{intStatus} == $Defs::TXN_UNPAID) ? 1 : 0;
	#my $amount_readonly = $Data->{'clientValues'}{'authLevel'} >= $Defs::LEVEL_ASSOC ? 0: 1;
	my $amount_readonly = ! $dref->{intStatus} ? 0: 1;
	$amount_readonly = 1 if ! $id;
	my $prod_readonly= $id ? 1: 0;
	my %FieldDefs = (
		TXN => {
			fields => {
				intStatus=> {
			        	label => $lang->txt("Paid ?"),
		                	value => $dref->{'intStatus'},
                			type  => 'lookup',
                			options=> {$Defs::TXN_PAID => $Defs::TransactionStatus{$Defs::TXN_PAID}, $Defs::TXN_CANCELLED=> $Defs::TransactionStatus{$Defs::TXN_CANCELLED}},
					readonly=>$readonly,
            			},
				intDelivered=> {
			        	label => $lang->txt("Delivered ?"),
		                	value => $dref->{'intDelivered'},
                			type  => 'checkbox',
                			displaylookup => {0=>'Undelivered', 1=>'Delivered'},
            			},
				dtPaid=> {
					label => $lang->txt('Date Paid'),
					type => 'text',
					readonly=>1,
					size => 30,
					value => $dref->{'dtPaid'},
				},
				PartPayment=> {
					label => $dref->{'intParentTXNID'} ? $lang->txt('Part Payment for') : '',
					type => 'text',
					readonly=>1,
					size => 30,
					value => Payments::TXNtoInvoiceNum($dref->{intParentTXNID}) . qq[ - $dref->{'ParentProductName'}],
				},
				intQty=> {
					label => $lang->txt('Quantity'),
					type => 'text',
					size => 8,
					value => $dref->{'intQty'} || 1,
				},
				curAmount=> {
					label => $lang->txt('Amount Due'),
					type => 'text',
					size => 8,
					value => $dref->{'curAmount'},
					readonly=>$amount_readonly,
				},
				AmountAlreadyPaid=> {
					label => $dref->{'AmountAlreadyPaid'} ? $lang->txt('Amount Already Paid via Part Payments') : '',
					type => 'text',
					size => 8,
					value => $dref->{'AmountAlreadyPaid'},
					readonly=>1,
				},

        ## TC
        dtStart => {
          label => $Data->{'SystemConfig'}{'AllowTxnStartDateEdit'} ? $lang->txt('Start Date') : '',
          type => 'date',
          value => $dref->{'dtStart'},
					noadd => 1,
        },
       dtEnd => {
          label => $Data->{'SystemConfig'}{'AllowTxnEndDateEdit'} ? $lang->txt('End Date') : '',
          type => 'date',
          value => $dref->{'dtEnd'},
					noadd => 1,
        },
        ## TC
				strNotes=> {
					label => $lang->txt('Notes'),
					type => 'textarea',
					value => $dref->{'strNotes'},
					rows => 5,
		                	cols=> 45,
				},
				intProductID => {
          				label => $lang->txt('Product'),
          				type => 'lookup',
          				compulsory => 1,
		          		value => $dref->{'intProductID'},
          				options =>  $prods_vals,
		          		firstoption => ['',$lang->txt('Select Product')],
					readonly=>$prod_readonly,
        			},
		},
		order => [qw(intProductID curAmount AmountAlreadyPaid dtPaid intQty intStatus intDelivered strNotes dtStart dtEnd PartPayment)],
			options => {
				labelsuffix => ':',
				hideblank => 1,
				target => $Data->{'target'},
				formname => 'txn_form',
				submitlabel => 'Update Transaction',
				introtext => 'auto',
				buttonloc => 'bottom',
				updateSQL => $txnupdate,
				addSQL => $txnadd,
				afteraddFunction => \&checkTXNPricing,
				afteraddParams => [$Data,$Data->{'db'}, $TableID],
				beforeaddFunction => \&preTXNAddUpdate,
				beforeupdateFunction => \&preTXNAddUpdate,
				beforeaddParams => [$option,$Data,$Data->{'db'}, $client, $TableID, 0],
				beforeupdateParams => [$option,$Data,$Data->{'db'}, $client, $TableID, $id],

        auditFunction=> \&auditLog,
        auditAddParams => [
          $Data,
          'Add',
          'Transactions'
        ],
        auditEditParams => [
          $id,
          $Data,
          'Update',
          'Transactions'
        ],

				stopAfterAction => 1,
				updateOKtext => qq[

Record updated successfully

					{'target'}?client=$client&a=M_TXN_LIST">].$lang->txt('Return to Transaction').qq[
				],
				addOKtext => qq[

Record updated successfully

					{'target'}?client=$client&a=P_TXN_LIST">].$lang->txt('Return to Transaction').qq[
				],
			},
			sections => [ ['main',$lang->txt('Details')], ],
			carryfields =>  {
				client => $client,
				a=> $action,
				tID => $id,
			},
		},
	);
	($resultHTML, undef )=handleHTMLForm($FieldDefs{'TXN'}, undef, $option, '',$db);
	my $url = getPartPayURL($Data, $id) if ($dref->{'NumChildren'});
	if ($url)	{
		$resultHTML.= qq[].$lang->txt('Click to View Part Payment form').qq[

];
	}
	$resultHTML .= showTransactionChildren($Data, $id) if ($dref->{'NumChildren'});

	if($option eq 'display')	{
		$resultHTML .=allowedAction($Data, 'txn_e') ?qq[ {'intTransactionID'}&client=$client">].$lang->txt('Edit Details').qq[ ] : '';
	}

		$resultHTML=qq[

].$lang->txt('No Transaction were found.').qq[

		] if !ref $dref;

		$resultHTML=qq[

$toplist

					$resultHTML

		];
		my $heading = $Data->{'SystemConfig'}{'txns_link_name'}  || $lang->txt('Transactions');
		return ($resultHTML,$heading);
}

sub showTransactionChildren	{

	my ($Data, $id) = @_;

	my $st = qq[
		SELECT
      T.* ,
      DATE_FORMAT(T.dtTransaction ,"%d/%m/%Y") AS dtTransaction,
      DATE_FORMAT(T.dtStart ,"%d/%m/%Y") AS dtStart,
      DATE_FORMAT(T.dtEnd ,"%d/%m/%Y") AS dtEnd,
      DATE_FORMAT(T.dtPaid ,"%d/%m/%Y") AS dtPaid
		FROM
			tblTransactions as T
			INNER JOIN tblProducts as P ON (
				P.intProductID = T.intProductID
			)
		WHERE
			T.intParentTXNID = ?
			AND T.intTXNEntityID= ?
			AND T.intParentTXNID > 0
			AND T.intStatus=1
			AND P.intProductType<>2
	];

	my $qry = $Data->{'db'}->prepare($st);
    my $entityID = getLastEntityID($Data->{'clientValues'}) || 0;
	$qry->execute($id, $entityID);
	my $count=0;
	my $body = qq[

Part Payment records

Below is a list of the successful Part Payments for the selected Transaction.

				Invoice Number
				Payee
				Amount
				Payment Ref ID
				Paid Date
				Payee Notes

	];
	while (my $dref=$qry->fetchrow_hashref())	{
		$count++;
		$body .= qq[

				]. Payments::TXNtoInvoiceNum($dref->{'intTransactionID'}) . qq[
				$dref->{'strPayeeName'}
				\$$dref->{'curAmount'}
				$dref->{'intTransLogID'}
				$dref->{'dtPaid'}
				$dref->{'strPayeeNotes'}

		];
	};

	$body .= qq[
];

	$body = '' if ! $count;

	return $body;
}

sub checkTXNPricing	{
	my($id,$params, $Data,$db, $personID)=@_;
        $personID||=0;

    my $entityID = getLastEntityID($Data->{'clientValues'}) || 0;
	my $statement = qq[
        SELECT PP.curAmount, P.curDefaultAmount, T.intQty
	FROM tblTransactions as T
	        LEFT JOIN tblProducts as P ON (P.intProductID = T.intProductID)
			LEFT JOIN tblProductPricing as PP ON (PP.intProductID = P.intProductID AND PP.intRealmID = $Data->{'Realm'} AND ((PP.intID = T.intTXNEntityID AND intLevel >= $Defs::LEVEL_CLUB)
];
    $statement .= qq[ OR (PP.intID = $entityID AND intLevel>=$Defs::LEVEL_CLUB)] if ($entityID and $entityID != $Defs::INVALID_ID);
    $statement .= qq[))
	WHERE T.intTransactionID = $id
    ];
    my $query = $db->prepare($statement) or query_error($statement);
    $query->execute or query_error($statement);

	my ($PPamount, $defaultAmount, $qty)= $query->fetchrow_array();
	$PPamount ||= 0;
        $defaultAmount ||=0;

	 my $amount = $PPamount || $defaultAmount || 0;
	my $totalamount = $amount * $qty;

	$statement = qq[
		UPDATE tblTransactions
		SET curAmount = $totalamount, curPerItem=$amount
		WHERE intTransactionID = $id
	];

    $query = $db->prepare($statement) or query_error($statement);
    $query->execute or query_error($statement);

}

sub preTXNAddUpdate	{

	my($params, $action, $Data,$db, $client, $personID, $transID)=@_;

	$personID ||= 0;
	$transID ||=0;
	my $prodID = $params->{'d_intProductID'} || 0;

	my $st = qq[
		SELECT T.intTransactionID
		FROM tblTransactions as T INNER JOIN tblProducts as P ON (T.intProductID = P.intProductID)
		WHERE T.intID = $personID
			AND T.intTableType=$Defs::LEVEL_PERSON
			AND T.intProductID = $prodID
			AND P.intAssocUnique = 1
	];
	$st .= qq[ AND T.intTransactionID <> $transID] if $transID;
	$st .= qq[
		LIMIT 1
	];
    	my $query = $db->prepare($st) or query_error($st);
    	$query->execute or query_error($st);
    	my ($intExistingTransactionID) = $query->fetchrow_array();
	$intExistingTransactionID ||= 0;

	my $error_text = qq[

You are only allowed to have one instance of the selected product

		{'target'}?client=$client&a=P_TXN_LIST">Return to Transaction
	];
	return (0,$error_text) if $intExistingTransactionID;
	return (1,'');

}

1;


text:
@interface LikesNode ()
@property (nonatomic, strong) ASImageNode *iconNode;
@property (nonatomic, strong) ASTextNode *countNode;
@property (nonatomic, assign) NSInteger likesCount;
@property (nonatomic, assign) BOOL liked;
@end

@implementation LikesNode

- (instancetype)initWithLikesCount:(NSInteger)likesCount
{
    self = [super init];
    if (self) {
        _likesCount = likesCount;
        _liked = (_likesCount > 0) ? [LikesNode getYesOrNo] : NO;

        _iconNode = [[ASImageNode alloc] init];
        _iconNode.image = (_liked) ? [UIImage imageNamed:@"icon_liked.png"] : [UIImage imageNamed:@"icon_like.png"];
        [self addSubnode:_iconNode];

        _countNode = [[ASTextNode alloc] init];
        if (_likesCount > 0) {

            NSDictionary *attributes = _liked ? [TextStyles cellControlColoredStyle] : [TextStyles cellControlStyle];
            _countNode.attributedText = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%ld", (long)_likesCount] attributes:attributes];

        }
        [self addSubnode:_countNode];

        // make it tappable easily
        self.hitTestSlop = UIEdgeInsetsMake(-10, -10, -10, -10);
    }

    return self;

}

+ (BOOL)getYesOrNo
{
    int tmp = (arc4random() % 30)+1;
    if (tmp % 5 == 0) {
        return YES;
    }
    return NO;
}

- (ASLayoutSpec *)layoutSpecThatFits:(ASSizeRange)constrainedSize
{
    ASStackLayoutSpec *mainStack =
    [ASStackLayoutSpec
     stackLayoutSpecWithDirection:ASStackLayoutDirectionHorizontal
     spacing:6.0
     justifyContent:ASStackLayoutJustifyContentStart
     alignItems:ASStackLayoutAlignItemsCenter
     children:@[_iconNode, _countNode]];

    mainStack.style.minWidth = ASDimensionMakeWithPoints(60.0);
    mainStack.style.maxHeight = ASDimensionMakeWithPoints(40.0);

    return mainStack;
}

@end


text:
const { LF, h2 } = require('md-writer');

module.exports = class ReadmeSections extends Array {
    getPositionIndex(position) {
        const after = /after:(.+)/.exec(position);

        if (after) {
            const [, title] = after;

            return (this.getSectionIndex(title) + 1);
        }

        const before = /before:(.+)/.exec(position);

        if (before) {
            const [, title] = before;

            return this.getSectionIndex(title);
        }

        const radix = 10;

        return parseInt(position, radix);
    }

    getSectionIndex(title = '') {
        return this.reduce((accumulator, sectionPair, index) => {
            const [header] = sectionPair;

            return (header == h2(title)) ? index : accumulator; // eslint-disable-line eqeqeq
        }, NaN);
    }

    toString() {
        return this.map(headerBodyPair => headerBodyPair.join(LF))
            .join(`${LF}${LF}`);
    }
};


text:
package android.support.v8.renderscript;

import android.util.Log;

/**
 * Intrinsic for applying a per-channel lookup table. Each
 * channel of the input has an independant lookup table. The
 * tables are 256 entries in size and can cover the full value
 * range of {@link Element#U8_4}.
 **/
public class ScriptIntrinsicLUT extends ScriptIntrinsic {
    private final Matrix4f mMatrix = new Matrix4f();
    private Allocation mTables;
    private final byte mCache[] = new byte[1024];
    private boolean mDirty = true;

    protected ScriptIntrinsicLUT(int id, RenderScript rs) {
        super(id, rs);
    }

    /**
     * Supported elements types are {@link Element#U8_4}
     *
     * The defaults tables are identity.
     *
     * @param rs The RenderScript context
     * @param e Element type for intputs and outputs
     *
     * @return ScriptIntrinsicLUT
     */
    public static ScriptIntrinsicLUT create(RenderScript rs, Element e) {
        if (rs.isNative) {
            RenderScriptThunker rst = (RenderScriptThunker) rs;
            return ScriptIntrinsicLUTThunker.create(rs, e);
        }

        int id = rs.nScriptIntrinsicCreate(3, e.getID(rs));

        ScriptIntrinsicLUT si = new ScriptIntrinsicLUT(id, rs);
        si.mTables = Allocation.createSized(rs, Element.U8(rs), 1024);
        for (int ct=0; ct < 256; ct++) {
            si.mCache[ct] = (byte)ct;
            si.mCache[ct + 256] = (byte)ct;
            si.mCache[ct + 512] = (byte)ct;
            si.mCache[ct + 768] = (byte)ct;
        }
        si.setVar(0, si.mTables);
        return si;
    }

    private void validate(int index, int value) {
        if (index < 0 || index > 255) {
            throw new RSIllegalArgumentException("Index out of range (0-255).");
        }
        if (value < 0 || value > 255) {
            throw new RSIllegalArgumentException("Value out of range (0-255).");
        }
    }

    /**
     * Set an entry in the red channel lookup table
     *
     * @param index Must be 0-255
     * @param value Must be 0-255
     */
    public void setRed(int index, int value) {
        validate(index, value);
        mCache[index] = (byte)value;
        mDirty = true;
    }

    /**
     * Set an entry in the green channel lookup table
     *
     * @param index Must be 0-255
     * @param value Must be 0-255
     */
    public void setGreen(int index, int value) {
        validate(index, value);
        mCache[index+256] = (byte)value;
        mDirty = true;
    }

    /**
     * Set an entry in the blue channel lookup table
     *
     * @param index Must be 0-255
     * @param value Must be 0-255
     */
    public void setBlue(int index, int value) {
        validate(index, value);
        mCache[index+512] = (byte)value;
        mDirty = true;
    }

    /**
     * Set an entry in the alpha channel lookup table
     *
     * @param index Must be 0-255
     * @param value Must be 0-255
     */
    public void setAlpha(int index, int value) {
        validate(index, value);
        mCache[index+768] = (byte)value;
        mDirty = true;
    }

    /**
     * Invoke the kernel and apply the lookup to each cell of ain
     * and copy to aout.
     *
     * @param ain Input allocation
     * @param aout Output allocation
     */
    public void forEach(Allocation ain, Allocation aout) {
        if (mDirty) {
            mDirty = false;
            mTables.copyFromUnchecked(mCache);
        }
        forEach(0, ain, aout, null);
    }

    /**
     * Get a KernelID for this intrinsic kernel.
     *
     * @return Script.KernelID The KernelID object.
     */
    public Script.KernelID getKernelID() {
        return createKernelID(0, 3, null, null);
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

<TITLE>CLHS: Issue CONSTANT-MODIFICATION:DISALLOW Summary</TITLE>
<META HTTP-EQUIV="Author" CONTENT="Kent M. Pitman">
<META HTTP-EQUIV="Organization" CONTENT="The Harlequin Group Limited">
<LINK REL=TOP HREF="../FrontMatter/index.html">
<LINK REL=COPYRIGHT HREF="../FrontMatter/About-HyperSpec.html#Legal">
<LINK REL=DISCLAIMER HREF="../FrontMatter/About-HyperSpec.html#Disclaimer">
<LINK REL=PREV HREF="../Issues/iss082.html">
<LINK REL=UP HREF="../Issues/Issues-Alphabetical.html">
<LINK REL=NEXT HREF="../Issues/iss084.html">

Issue CONSTANT-MODIFICATION:DISALLOW Summary

These passages are relevant to issue <TT>CONSTANT-MODIFICATION:DISALLOW</TT>:

Accessor AREF

Accessor BIT, SBIT

Accessor CHAR, SCHAR

Accessor ELT

Accessor SVREF

Function INTERSECTION, NINTERSECTION

Function MERGE

Function REMOVE, REMOVE-IF, REMOVE-IF-NOT, DELETE, DELETE-IF, DELETE-IF-NOT

Function REMOVE-DUPLICATES, DELETE-DUPLICATES

Function SET-DIFFERENCE, NSET-DIFFERENCE

Function SET-EXCLUSIVE-OR, NSET-EXCLUSIVE-OR

Function SORT, STABLE-SORT

Function SUBLIS, NSUBLIS

Function SUBST, SUBST-IF, SUBST-IF-NOT, NSUBST, NSUBST-IF, NSUBST-IF-NOT

Function SUBSTITUTE, SUBSTITUTE-IF, SUBSTITUTE-IF-NOT, NSUBSTITUTE, NSUBSTITUTE-IF, NSUBSTITUTE-IF-NOT

Function UNION, NUNION

Special Operator QUOTE

Copyright 1996, The Harlequin Group Limited.  All Rights Reserved.


text:
#ifndef PH_MAP_PROVIDER_H
#define PH_MAP_PROVIDER_H

/* Includes {{{1 */

#include <gtk/gtk.h>

/* Data structure {{{1 */

/*
 * Information that is necessary to download and display map tiles.
 */
typedef struct _PHMapProvider {
    gchar *name;                /* user-supplied name */
    gboolean predefined;        /* is this one of the default providers? */
    gchar *url;                 /* URL with placeholders */
    guint tile_size;            /* tile size in pixels */
    guint zoom_min;             /* minimum and */
    guint zoom_max;             /* maximum zoom level */
    guint zoom_detail;          /* lowest zoom level considered detailed */
} PHMapProvider;

/*
 * Equivalent columns for the map provider list store used by the configuration
 * framework.
 */
enum {
    PH_MAP_PROVIDER_COLUMN_NAME,
    PH_MAP_PROVIDER_COLUMN_PREDEFINED,
    PH_MAP_PROVIDER_COLUMN_URL,
    PH_MAP_PROVIDER_COLUMN_TILE_SIZE,
    PH_MAP_PROVIDER_COLUMN_ZOOM_MIN,
    PH_MAP_PROVIDER_COLUMN_ZOOM_MAX,
    PH_MAP_PROVIDER_COLUMN_ZOOM_DETAIL,
    PH_MAP_PROVIDER_COLUMN_COUNT
};

#define PH_TYPE_MAP_PROVIDER (ph_map_provider_get_type())

GType ph_map_provider_get_type();

/* Public interface {{{1 */

PHMapProvider *ph_map_provider_new_from_list(GtkListStore *store,
                                             GtkTreeIter *iter);
void ph_map_provider_to_list(const PHMapProvider *provider,
                             GtkListStore *store,
                             GtkTreeIter *iter);
void ph_map_provider_to_list_single(const PHMapProvider *provider,
                                    GtkListStore *store,
                                    GtkTreeIter *iter,
                                    gint column);

PHMapProvider *ph_map_provider_copy(const PHMapProvider *provider);
void ph_map_provider_free(PHMapProvider *provider);

gchar *ph_map_provider_get_tile_url(const PHMapProvider *provider,
                                    guint zoom,
                                    glong x,
                                    glong y);
gchar *ph_map_provider_get_cache_dir(const PHMapProvider *provider);

/* }}} */

#endif

/* vim: set sw=4 sts=4 et cino=(0,Ws tw=80 fdm=marker: */


text:
class ChangeSendTimeToDateTime < ActiveRecord::Migration[4.2]
  def change
    remove_column :users, :send_time
    add_column :users, :send_time, :time, :null=>false, :default=>"08:00:00"
  end
end


text:
PHPDocker.io generated environment
==================================

# Add to your project #

Simply, unzip the file into your project, this will create `docker-compose.yml` on the root of your project and a folder named `phpdocker` containing nginx and php-fpm config for it.

Ensure the webserver config on `docker\nginx.conf` is correct for your project. PHPDocker.io will have customised this file according to the application type you chose on the generator, for instance `web/app|app_dev.php` on a Symfony project, or `public/index.php` on generic apps.

Note: you may place the files elsewhere in your project. Make sure you modify the locations for the php-fpm dockerfile, the php.ini overrides and nginx config on `docker-compose.yml` if you do so.

# How to run #

Dependencies:

  * Docker engine v1.13 or higher. Your OS provided package might be a little old, if you encounter problems, do upgrade. See [https://docs.docker.com/engine/installation](https://docs.docker.com/engine/installation)
  * Docker compose v1.12 or higher. See [docs.docker.com/compose/install](https://docs.docker.com/compose/install/)

Once you're done, simply `cd` to your project and run `docker-compose up -d`. This will initialise and start all the containers, then leave them running in the background.

## Services exposed outside your environment ##

You can access your application via **`localhost`**, if you're running the containers directly, or through **``** when run on a vm. nginx and mailhog both respond to any hostname, in case you want to add your own hostname on your `/etc/hosts`

Service|Address outside containers
------|---------|-----------
Webserver|[localhost:8081](http://localhost:8081)
MySQL|**host:** `localhost`; **port:** `8083`

## Hosts within your environment ##

You'll need to configure your application to use any services you enabled:

Service|Hostname|Port number
------|---------|-----------
php-fpm|php-fpm|9000
MySQL|mysql|3306 (default)

# Docker compose cheatsheet #

**Note:** you need to cd first to where your docker-compose.yml file lives.

  * Start containers in the background: `docker-compose up -d`
  * Start containers on the foreground: `docker-compose up`. You will see a stream of logs for every container running.
  * Stop containers: `docker-compose stop`
  * Kill containers: `docker-compose kill`
  * View container logs: `docker-compose logs`
  * Execute command inside of container: `docker-compose exec SERVICE_NAME COMMAND` where `COMMAND` is whatever you want to run. Examples:
        * Shell into the PHP container, `docker-compose exec php-fpm bash`
        * Run symfony console, `docker-compose exec php-fpm bin/console`
        * Open a mysql shell, `docker-compose exec mysql mysql -uroot -pCHOSEN_ROOT_PASSWORD`

# Recommendations #

It's hard to avoid file permission issues when fiddling about with containers due to the fact that, from your OS point of view, any files created within the container are owned by the process that runs the docker engine (this is usually root). Different OS will also have different problems, for instance you can run stuff in containers using `docker exec -it -u $(id -u):$(id -g) CONTAINER_NAME COMMAND` to force your current user ID into the process, but this will only work if your host OS is Linux, not mac. Follow a couple of simple rules and save yourself a world of hurt.

  * Run composer outside of the php container, as doing so would install all your dependencies owned by `root` within your vendor folder.
  * Run commands (ie Symfony's console, or Laravel's artisan) straight inside of your container. You can easily open a shell as described above and do your thing from there.


text:
DomainReliabilityInternalsUI::DomainReliabilityInternalsUI(
    content::WebUI* web_ui)
    : content::WebUIController(web_ui) {
  content::WebUIDataSource* html_source = content::WebUIDataSource::Create(
      chrome::kChromeUIDomainReliabilityInternalsHost);
  html_source->OverrideContentSecurityPolicy(
      network::mojom::CSPDirectiveName::ScriptSrc,
      "script-src chrome://resources 'self' 'unsafe-eval';");
  html_source->OverrideContentSecurityPolicy(
      network::mojom::CSPDirectiveName::TrustedTypes,
      "trusted-types jstemplate;");
  html_source->AddResourcePath("domain_reliability_internals.css",
      IDR_DOMAIN_RELIABILITY_INTERNALS_CSS);
  html_source->AddResourcePath("domain_reliability_internals.js",
      IDR_DOMAIN_RELIABILITY_INTERNALS_JS);
  html_source->SetDefaultResource(IDR_DOMAIN_RELIABILITY_INTERNALS_HTML);
  Profile* profile = Profile::FromWebUI(web_ui);
  content::WebUIDataSource::Add(profile, html_source);

  web_ui->AddMessageHandler(
      std::make_unique<DomainReliabilityInternalsHandler>());
}

DomainReliabilityInternalsUI::~DomainReliabilityInternalsUI() = default;

DomainReliabilityInternalsHandler::DomainReliabilityInternalsHandler() =
    default;
DomainReliabilityInternalsHandler::~DomainReliabilityInternalsHandler() =
    default;

void DomainReliabilityInternalsHandler::RegisterMessages() {
  web_ui()->RegisterDeprecatedMessageCallback(
      "updateData",
      base::BindRepeating(&DomainReliabilityInternalsHandler::HandleUpdateData,
                          base::Unretained(this)));
}

void DomainReliabilityInternalsHandler::HandleUpdateData(
    const base::ListValue* args) {
  DCHECK_EQ(1u, args->GetListDeprecated().size());
  AllowJavascript();
  callback_id_ = args->GetListDeprecated()[0].GetString();

  Profile* profile = Profile::FromWebUI(web_ui());
  network::mojom::NetworkContext* network_context =
      profile->GetDefaultStoragePartition()->GetNetworkContext();
  network_context->GetDomainReliabilityJSON(
      base::BindOnce(&DomainReliabilityInternalsHandler::OnDataUpdated,
                     weak_factory_.GetWeakPtr()));
}

void DomainReliabilityInternalsHandler::OnDataUpdated(base::Value data) {
  ResolveJavascriptCallback(base::Value(std::move(callback_id_)), data);
  callback_id_.clear();
}


text:
package cloud.orbit.actors.extensions.dynamodb;

@DynamoDBStateConfiguration(collection = "helloIdAndCollection", idDecorationOverride = "3W2rQqmuuYPKznDYNNn3GB")
public class HelloStateWithIdOverrideAndCollection extends HelloState
{
}


text:
module Sprinkle
  module Installers
    class InstallPackage < Installer #:nodoc:
      cattr_accessor :installer
      attr_accessor :packages #:nodoc:

      def initialize(parent, packages, &block) #:nodoc:
        super parent, &block
        if packages.is_a?(Array) && packages.first.is_a?(Array)
          packages = packages.first
        else
          packages = [packages] unless packages.is_a? Array
        end

        @packages = packages
      end

      protected

      def install_commands #:nodoc:
        case installer
          when :smart
            "smart install #{@packages.join(' ')} -y 2>&1 | tee -a /var/log/smart-sprinkle"
          when :yum
            "yum install #{@packages.join(' ')} -y 2>&1 | tee -a /var/log/yum-sprinkle"
          else
            raise "Unknown InstallPackage.installer"
        end
      end
    end

    class UninstallPackage < Installer
      attr_accessor :packages #:nodoc:

      def initialize(parent, packages, &block) #:nodoc:
        super parent, &block
        if packages.is_a?(Array) && packages.first.is_a?(Array)
          packages = packages.first
        else
          packages = [packages] unless packages.is_a? Array
        end

        @packages = packages
      end

      protected

      def install_commands #:nodoc:
        case Sprinkle::Installers::InstallPackage.installer
          when :smart
            "smart remove #{@packages.join(' ')} -y 2>&1 | tee -a /var/log/smart-sprinkle"
          when :yum
            "yum erase #{@packages.join(' ')} -y 2>&1 | tee -a /var/log/yum-sprinkle"
          else
            raise "Unknown InstallPackage.installer"
        end
      end
    end
  end
end

module Sprinkle
  module Package
    class Package
      def install_package(*names, &block) #:nodoc:
        ActiveSupport::Deprecation.warn("install_package will be removed from sprinkle 0.8, please use yum or smart installers instead.")
        @installers << Sprinkle::Installers::InstallPackage.new(self, names, &block)
      end

      def uninstall_package(*names, &block) #:nodoc:
        ActiveSupport::Deprecation.warn("uninstall_package will be removed from sprinkle 0.8, please use yum or smart installers instead.")
        @installers << Sprinkle::Installers::UninstallPackage.new(self, names, &block)
      end

      alias_method :install_packages, :install_package #:nodoc:
      alias_method :uninstall_packages, :uninstall_package #:nodoc:
    end
  end
end


text:
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using Duality.Editor.Plugins.Base.Forms;
using Duality.Editor.Plugins.Base.Properties;
using Duality.Resources;

namespace Duality.Editor.Plugins.Base.EditorActions
{
	/// <summary>
	/// Opens a window for slicing a pixmap into atlas regions.
	/// </summary>
	public class SlicePixmap : EditorAction<Pixmap>
	{
		public override string Name
		{
			get { return EditorBaseRes.ActionName_SlicePixmap; }
		}
		public override Image Icon
		{
			get { return EditorBaseRes.IconPixmapSlicer; }
		}
		public override int Priority
		{
			get { return base.Priority - 1; }
		}

		public override void Perform(IEnumerable<Pixmap> pixmaps)
		{
			PixmapSlicerForm slicingForm = DualityEditorApp.GetPlugin<EditorBasePlugin>().RequestPixmapSlicerForm();
			slicingForm.TargetPixmap = pixmaps.First();
			slicingForm.Show();
		}

		public override bool CanPerformOn(IEnumerable<Pixmap> pixmaps)
		{
			return pixmaps.Count() == 1;
		}
	}
}


text:
<!doctype html>

Test for  [CSSRegions] Crash reflowing content in variable width regions.

On success, you should see past below and test does not crash or assert.

Floating content

PASS


text:
<single-article article-image="{{user.avatarUrl || mainCtrl.defaultAvatar}}">

{{user.username || user.email || user.lastName}} registered on {{user.registeredOn | date}}

      Username: {{user.username}}

      First Name: {{user.firstName}}

       Last Name: {{user.lastName}}

      Email:{{user.email}}

</single-article>


text:
@define-mixin v-center {
	position: absolute;
	top: 50%;

	transform: translateY(-50%);
}

@define-mixin center {
	position: absolute;
	top: 50%;
	left: 50%;

	transform: translate(-50%, -50%);
}

@define-mixin clearfix {

	&::after {
		content: '';

		display: block;

		clear: both;
	}
}

@define-mixin ratio $width, $height {
	display: block;
	height: 0;
	padding: 0 0 resolve(strip($height) / strip($width) * 100)% 0;

	position: relative;

	overflow: hidden;
}

@define-mixin baseline $font-size, $cap-height, $below: 0, $decal: 0 {

	/*  */
	$lines: resolve(2 * round(resolve(ceil(resolve($font-size / (var(--default-font-size) * var(--default-line-height)) * var(--default-line-height)))) / 2));
	$rhythm: ($lines * var(--default-font-size) - $cap-height * $font-size) / 2;

	padding-top: rem(calc($rhythm - $decal), var(--default-font-size));
	margin-bottom: rem(calc(-1 * $rhythm + $below * var(--default-line-height) * var(--default-font-size)), var(--default-font-size));

	font-size: rem($font-size, var(--default-font-size));
	line-height: $(lines)rem;
}


text:
static const unsigned int ABREVIATION_SIZE = 4;

int char_to_int(char c) {
  if(c == 'I') {
    return 1;
  } else if(c == 'V') {
    return 5;
  } else if(c == 'X') {
    return 10;
  } else if(c == 'L') {
    return 50;
  } else if(c == 'C') {
    return 100;
  } else if(c == 'D') {
    return 500;
  } else if(c == 'M') {
    return 1000;
  }

  return 0;
}

char* int_to_char(int number) {
  char* result = malloc(sizeof(char) * 15);
  int base_values[] = { 1000, 500, 100, 50, 10, 5, 1 };
  char glyphs[] = "MDCLXVI";
  int num_glyphs = strlen(glyphs);
  assert(sizeof(base_values)/sizeof(int) == num_glyphs);

  int glyph_location = 0;
  int i;
  for(i = 0; i < num_glyphs; i++) {
    while(base_values[i] <= number) {
      number -= base_values[i];
      result[glyph_location] = glyphs[i];
      glyph_location += 1;
    }
  }
  result[glyph_location] = '\0';

  return result;
}

void insert_expansion(
  char* destination,
  char c,
  unsigned int times,
  unsigned int* starting_index)
{
  unsigned int i;
  for(i = 0; i < times; i++) {
    destination[*starting_index + i] = c;
  }
  *starting_index += times;
}

int is_substitutable_sequence(char* original, unsigned int* at, char* sequence) {
  unsigned int length = strlen(sequence);
  unsigned int original_length = strlen(original);
  unsigned int i;
  for(i = 0; i < strlen(sequence); i++) {
    if(*at+i >= original_length || original[*at+i] != sequence[i]) { return 0; }
  }
  *at += length - 1;
  return 1;
}

char* expand_abbreviations(char original[]) {
  unsigned int original_length = strlen(original);
  unsigned int expanded_length = original_length * 3 + 1;
  char* expanded = calloc(expanded_length, sizeof(char));
  unsigned int j = 0;

  unsigned int i;
  for(i = 0; i < original_length; i++) {
    if(is_substitutable_sequence(original, &i, "IV")) {
      insert_expansion(expanded, 'I', ABREVIATION_SIZE, &j);
    } else if(is_substitutable_sequence(original, &i, "IX")) {
      insert_expansion(expanded, 'V', 1, &j);
      insert_expansion(expanded, 'I', ABREVIATION_SIZE, &j);
    } else if(is_substitutable_sequence(original, &i, "XL")) {
      insert_expansion(expanded, 'X', ABREVIATION_SIZE, &j);
    } else if(is_substitutable_sequence(original, &i, "XC")) {
      insert_expansion(expanded, 'L', 1, &j);
      insert_expansion(expanded, 'X', ABREVIATION_SIZE, &j);
    } else if(is_substitutable_sequence(original, &i, "CD")) {
      insert_expansion(expanded, 'C', ABREVIATION_SIZE, &j);
    } else if(is_substitutable_sequence(original, &i, "CM")) {
      insert_expansion(expanded, 'D', 1, &j);
      insert_expansion(expanded, 'C', ABREVIATION_SIZE, &j);
    } else {
      expanded[j] = original[i];
      j += 1;
    }
  }

  return expanded;
}

void insert_abbreviation(
  char* destination,
  char* abbreviation,
  unsigned int* starting_index)
{
  unsigned int abbreviation_length = strlen(abbreviation);
  unsigned int i;
  for(i = 0; i < abbreviation_length; i++) {
    destination[*starting_index + i] = abbreviation[i];
  }
  *starting_index += abbreviation_length;
}

char* abbreviate(char original[]) {
  unsigned int original_length = strlen(original);
  char* abbreviated = calloc(original_length + 1, sizeof(char));
  unsigned int j = 0;

  unsigned int i;
  for(i = 0; i < original_length; i++) {
    if(is_substitutable_sequence(original, &i, "DCCCC")) {
      insert_abbreviation(abbreviated, "CM", &j);
    } else if(is_substitutable_sequence(original, &i, "CCCC")) {
      insert_abbreviation(abbreviated, "CD", &j);
    } else if(is_substitutable_sequence(original, &i, "LXXXX")) {
      insert_abbreviation(abbreviated, "XC", &j);
    } else if(is_substitutable_sequence(original, &i, "XXXX")) {
      insert_abbreviation(abbreviated, "XL", &j);
    } else if(is_substitutable_sequence(original, &i, "VIIII")) {
      insert_abbreviation(abbreviated, "IX", &j);
    } else if(is_substitutable_sequence(original, &i, "IIII")) {
      insert_abbreviation(abbreviated, "IV", &j);
    } else {
      abbreviated[j] = original[i];
      j += 1;
    }
  }

  return abbreviated;
}

int tally(char* expanded) {
  int result = 0;

  unsigned int i;
  for(i = 0; i < strlen(expanded); i++) {
    result += char_to_int(expanded[i]);
  }

  return result;
}

// public

int roman_to_int(char roman[]) {
  char* expanded = expand_abbreviations(roman);
  int result = tally(expanded);
  free(expanded);

  return result;
}

char* int_to_roman(int arabic) {
  char* prefix = arabic < 0 ? "-" : "";
  char* expanded = int_to_char(abs(arabic));
  char* postfix = abbreviate(expanded);
  char* result = malloc(sizeof(prefix) + sizeof(postfix));
  strcpy(result, prefix);
  strcat(result, postfix);
  free(expanded);
  free(postfix);

  return result;
}


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

    <groupId>com.boxfuse.samples</groupId>
    <artifactId>tomee</artifactId>
    <version>1.0</version>
    <packaging>war</packaging>
    <name>${project.artifactId}</name>

    <pluginRepositories>
        <pluginRepository>
            <id>boxfuse-repo</id>
            <url>https://files.boxfuse.com</url>
        </pluginRepository>
        <pluginRepository>
            <id>central</id>
            <url>https://repo1.maven.org/maven2/</url>
        </pluginRepository>
    </pluginRepositories>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.apache.openejb</groupId>
            <artifactId>javaee-api</artifactId>
            <version>6.0-6</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>org.hsqldb</groupId>
            <artifactId>hsqldb</artifactId>
            <version>2.3.2</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>net.sourceforge.htmlunit</groupId>
            <artifactId>htmlunit</artifactId>
            <version>2.17</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>com.boxfuse.client</groupId>
                <artifactId>boxfuse-maven-plugin</artifactId>
                <version>1.11.0.713</version>
                <executions>
                    <execution>
                        <id>boxfuse-run</id>
                        <phase>pre-integration-test</phase>
                        <goals>
                            <goal>fuse</goal>
                            <goal>run</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>boxfuse-kill</id>
                        <phase>post-integration-test</phase>
                        <goals>
                            <goal>kill</goal>
                            <goal>rm</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.17</version>
                <configuration>
                    <encoding>UTF-8</encoding>
                    <excludes>
                        <exclude>**/*LargeTest.java</exclude>
                    </excludes>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>2.17</version>
                <configuration>
                    <encoding>UTF-8</encoding>
                </configuration>
                <executions>
                    <execution>
                        <id>run-integration-tests</id>
                        <goals>
                            <goal>integration-test</goal>
                        </goals>
                        <phase>integration-test</phase>
                        <configuration>
                            <includes>
                                <include>**/*LargeTest.java</include>
                            </includes>
                            <excludes>
                                <exclude>**/*SmallTest.java</exclude>
                                <exclude>**/*MediumTest.java</exclude>
                            </excludes>
                            <parallel>none</parallel>
                            <threadCount>1</threadCount>
                            <perCoreThreadCount>true</perCoreThreadCount>
                            <redirectTestOutputToFile>true</redirectTestOutputToFile>
                            <systemPropertyVariables>
                                <boxfuse.instance.url>${boxfuse.instances.0.url}</boxfuse.instance.url>
                            </systemPropertyVariables>
                        </configuration>
                    </execution>
                    <execution>
                        <id>verify-integration-tests</id>
                        <goals>
                            <goal>verify</goal>
                        </goals>
                        <phase>post-integration-test</phase>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


text:
## Azure Cache for Redis: Azure AD with Redisson client library

### Table of contents

- [Prerequisites](#prerequisites)
- [Authenticate with Azure AD - Hello World](#authenticate-with-azure-ad-hello-world)
- [Authenticate with Azure AD - Handle Reauthentication](#authenticate-with-azure-ad-handle-reauthentication)
- [Authenticate with Azure AD - Using Token Cache](#authenticate-with-azure-ad-using-token-cache)
- [Troubleshooting](#troubleshooting)

#### Prerequisites
- Configuration of Role and Role Assignments is required before using the sample code in this document.
- Familiarity with the [Redisson](https://github.com/redisson/redisson) and [Azure Identity for Java](https://docs.microsoft.com/azure/developer/java/sdk/identity) client libraries is required.
- **Dependency Requirements:**
   ```xml
    <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-identity</artifactId>
        <version>1.5.0</version>
    </dependency>

    <dependency>
        <groupId>org.redisson</groupId>
        <artifactId>redisson</artifactId>
        <version>3.17.0</version>
    </dependency>
   ```

#### Samples Guidance
* [Authenticate with Azure AD - Hello World](#authenticate-with-azure-ad-hello-world):
   This sample is recommended for users getting started to use Azure AD authentication with Azure Cache for Redis.

* [Authenticate with Azure AD - Handle Reauthentication](#authenticate-with-azure-ad-handle-reauthentication):
   This sample is recommended to users looking to build long-running applications and would like to handle reauthenticating with Azure AD upon token expiry.

* [Authenticate with Azure AD - Using Token Cache](#authenticate-with-azure-ad-using-token-cache):
  This sample is recommended to users looking to build long-running applications that would like to handle reauthenticating with a token cache. The token cache stores and proactively refreshes the Azure AD access token 2 minutes before expiry and ensures a non-expired token is available for use when the cache is accessed.

#### Authenticate with Azure AD: Hello World
This sample is intended to assist in authenticating with Azure AD via the Redisson client library. It focuses on displaying the logic required to fetch an Azure AD access token and to use it as password when setting up the Redisson client instance. It Further shows how to recreate and authenticate the Redisson Client instance when its connection is broken in error/exception scenarios.

##### Migration Guidance
When migrating your existing application code, replace the password input with the Azure AD token.
Integrate the logic in your application code to fetch an Azure AD access token via the Azure Identity library as shown below and replace it with the password configuring/retrieving logic in your application code.

```java
//Construct a Token Credential from Identity library, e.g. DefaultAzureCredential / ClientSecretCredential / Client CertificateCredential / ManagedIdentityCredential etc.
DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().build();

// Fetch an Azure AD token to be used for authentication.
// Note: The Scopes parameter will change as the Azure AD Authentication support hits public preview and eventually GA's.
String token = defaultAzureCredential
    .getToken(new TokenRequestContext()
        .addScopes("https://*.cacheinfra.windows.net:10225/appid/.default")).block().getToken();

// Create Client Configuration
Config config = new Config();
config.useSingleServer()
    .setAddress("redis://<HOST_NAME>:6380") // TODO: Replace Host Name with Azure Cache for Redis Host Name.
    .setKeepAlive(true) // Keep the connection alive.
    .setUsername("<USERNAME>") // Username is Required
    .setPassword(token) // Azure AD Access Token as password is required.
    .setClientName("Reddison-Client");

RedissonClient redisson = Redisson.create(config);

// perform operations
RBuckets rBuckets =  redisson.getBuckets();
RBucket<String> bucket = redisson.getBucket("Az:key");
bucket.set("This is object value");

String objectValue = bucket.get();
System.out.println("stored object value: " + objectValue);

redisson.shutdown();
```

##### Supported Token Credentials for Azure AD Authentication
**Note:** The samples in this doc use the Azure Identity library's `DefaultAzureCredential` to fetch an Azure AD access token. The other supported `TokenCredential` implementations that can be used from [Azure Identity for Java](https://docs.microsoft.com/azure/developer/java/sdk/identity) are as follows:
* [Client Certificate Credential](https://docs.microsoft.com/azure/developer/java/sdk/identity-service-principal-auth#client-certificate-credential)
* [Client Secret Credential](https://docs.microsoft.com/azure/developer/java/sdk/identity-service-principal-auth#client-secret-credential)
* [Managed Identity Credential](https://docs.microsoft.com/azure/developer/java/sdk/identity-azure-hosted-auth#managed-identity-credential)
* [Username Password Credential](https://docs.microsoft.com/azure/developer/java/sdk/identity-user-auth#username-password-credential)
* [Azure CLI Credential](https://docs.microsoft.com/azure/developer/java/sdk/identity-dev-env-auth#azure-cli-credential)
* [Interactive Browser Credential](https://docs.microsoft.com/azure/developer/java/sdk/identity-user-auth#interactive-browser-credential)
* [Device Code Credential](https://docs.microsoft.com/azure/developer/java/sdk/identity-user-auth#device-code-credential)

#### Authenticate with Azure AD: Handle Reauthentication
This sample is intended to assist in authenticating with Azure AD via Redisson client library. It focuses on displaying the logic required to fetch an Azure AD access token and to use it as password when setting up the Redisson client instance. It also shows how to recreate and authenticate the Redisson client instance when its connection is broken in error/exception scenarios.

##### Migration Guidance
When migrating your existing application code, replace the password input with the Azure AD token.
Integrate the logic in your application code to fetch an Azure AD access token via the Azure Identity library as shown below and replace it with the password configuring/retrieving logic in your application code.

```java

//Construct a Token Credential from Identity library, e.g. DefaultAzureCredential / ClientSecretCredential / Client CertificateCredential / ManagedIdentityCredential etc.
DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().build();

// Fetch an Azure AD token to be used for authentication. This token will be used as the password.
// Note: The Scopes parameter will change as the Azure AD Authentication support hits public preview and eventually GA's.
TokenRequestContext trc = new TokenRequestContext().addScopes("https://*.cacheinfra.windows.net:10225/appid/.default");
AccessToken accessToken = getAccessToken(defaultAzureCredential, trc);

// Create Redisson Client
// Host Name, Port, Username and Azure AD Token are required here.
// TODO: Replace <HOST_NAME> with Azure Cache for Redis Host name.
RedissonClient redisson = createRedissonClient("redis://<HOST_NAME>:6380", "<USERNAME>", accessToken);

int maxTries = 3;
int i = 0;

while (i < maxTries) {
    try {
        // perform operations
        RBuckets rBuckets = redisson.getBuckets();
        RBucket<String> bucket = redisson.getBucket("Az:key");
        bucket.set("This is object value");

        String objectValue = bucket.get();
        System.out.println("stored object value: " + objectValue);
        break;
    } catch (RedisException exception) {
        // TODO: Handle Exception as Required.
        exception.printStackTrace();

        // For Exceptions containing Invalid Username Password / Permissions not granted error messages, look at troubleshooting section at the end of document.

        if (redisson.isShutdown()) {
            // Recreate the client with a fresh token non-expired token as password for authentication.
            redisson = createRedissonClient("redis://<HOST_NAME>:6380", "<USERNAME>", getAccessToken(defaultAzureCredential, trc));
        }
    } catch (Exception e) {
        // Handle Exception as required
        e.printStackTrace();
    }
    i++;
}
redisson.shutdown();

// Helper Code
private static RedissonClient createRedissonClient(String address, String username, AccessToken accessToken) {

    Config config = new Config();
    config.useSingleServer()
        .setAddress(address)
        .setKeepAlive(true)
        .setUsername(username)
        .setPassword(accessToken.getToken())
        .setClientName("Reddison-Client");

    return Redisson.create(config);
}

private static AccessToken getAccessToken(TokenCredential tokenCredential, TokenRequestContext trc) {
    return tokenCredential.getToken(trc).block();
}
```

#### Authenticate with Azure AD: Using Token Cache
This sample is intended to assist in authenticating with Azure AD via the Redisson client library. It focuses on displaying the logic required to fetch an Azure AD access token using a token cache and to use it as password when setting up the Redisson client instance. It also shows how to recreate and authenticate the Redisson client instance using the cached access token when its connection is broken in error/exception scenarios. The token cache stores and proactively refreshes the Azure AD access token 2 minutes before expiry and ensures a non-expired token is available for use when the cache is accessed.

##### Migration Guidance
When migrating your existing application code, replace the password input with the Azure AD token.
Integrate the logic in your application code to fetch an Azure AD access token via the Azure Identity library. Store the token in a token cache, as shown below. Replace the token with the password configuring/retrieving logic in your application code.

```java
//Construct a Token Credential from Identity library, e.g. DefaultAzureCredential / ClientSecretCredential / Client CertificateCredential / ManagedIdentityCredential etc.
DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().build();

// Fetch an Azure AD token to be used for authentication. This token will be used as the password.
// Note: The Scopes parameter will change as the Azure AD Authentication support hits public preview and eventually GA's.
TokenRequestContext trc = new TokenRequestContext().addScopes("https://*.cacheinfra.windows.net:10225/appid/.default");

// Instantiate the Token Refresh Cache, this cache will proactively refresh the access token 2 minutes before expiry.
TokenRefreshCache tokenRefreshCache = new TokenRefreshCache(defaultAzureCredential, trc, Duration.ofMinutes(2));;
AccessToken accessToken = tokenRefreshCache.getAccessToken();

// Create Redisson Client
// Host Name, Port, Username and Azure AD Token are required here.
// TODO: Replace <HOST_NAME> with Azure Cache for Redis Host name.
RedissonClient redisson = createRedissonClient("redis://<HOST_NAME>:6380", "<USERNAME>", accessToken);

int maxTries = 3;
int i = 0;

while (i < maxTries) {
    try {
        // perform operations
        RBuckets rBuckets = redisson.getBuckets();
        RBucket<String> bucket = redisson.getBucket("Az:key");
        bucket.set("This is object value");

        String objectValue = bucket.get().toString();
        System.out.println("stored object value: " + objectValue);
        break;
    } catch (RedisException exception) {
        // TODO: Handle Exception as Required.
        exception.printStackTrace();

        // For Exceptions containing Invalid Username Password / Permissions not granted error messages, look at troubleshooting section at the end of document.

        if (redisson.isShutdown()) {
            // Recreate the client with a fresh token non-expired token as password for authentication.
            redisson = createRedissonClient("redis://<HOST_NAME>:6380", "<USERNAME>", tokenRefreshCache.getAccessToken());
        }
    } catch (Exception e) {
        // Handle Exception as required
        e.printStackTrace();
    }
    i++;
}
redisson.shutdown();

// Helper Code
private static RedissonClient createRedissonClient(String address, String username, AccessToken accessToken) {

    Config config = new Config();
    config.useSingleServer()
        .setAddress(address)
        .setKeepAlive(true)
        .setUsername(username)
        .setPassword(accessToken.getToken())
        .setClientName("Reddison-Client");

    return Redisson.create(config);
}

/**
 * The token cache to store and proactively refresh the access token.
 */
public static class TokenRefreshCache {
    private final TokenCredential tokenCredential;
    private final TokenRequestContext tokenRequestContext;
    private final Timer timer;
    private volatile AccessToken accessToken;
    private final Duration refreshOffset;

    /**
     * Creates an instance of TokenRefreshCache
     * @param tokenCredential the token credential to be used for authentication.
     * @param tokenRequestContext the token request context to be used for authentication.
     * @param refreshOffset the refresh offset to use to proactively fetch a new access token before expiry time.
     */
    public TokenRefreshCache(TokenCredential tokenCredential, TokenRequestContext tokenRequestContext, Duration refreshOffset) {
        this.tokenCredential = tokenCredential;
        this.tokenRequestContext = tokenRequestContext;
        this.timer = new Timer();
        this.refreshOffset = refreshOffset;
    }

    /**
     * Gets the cached access token.
     * @return the AccessToken
     */
    public AccessToken getAccessToken() {
        if (accessToken != null) {
            return  accessToken;
        } else {
            TokenRefreshTask tokenRefreshTask = new TokenRefreshTask();
            accessToken = tokenCredential.getToken(tokenRequestContext).block();
            timer.schedule(tokenRefreshTask, getTokenRefreshDelay());
            return accessToken;
        }
    }

    private class TokenRefreshTask extends TimerTask {
        // Add your task here
        public void run() {
            accessToken = tokenCredential.getToken(tokenRequestContext).block();
            System.out.println("Refreshed Token with Expiry: " + accessToken.getExpiresAt().toEpochSecond());
            timer.schedule(new TokenRefreshTask(), getTokenRefreshDelay());
        }
    }

    private long getTokenRefreshDelay() {
        return ((accessToken.getExpiresAt()
            .minusSeconds(refreshOffset.getSeconds()))
            .toEpochSecond() - OffsetDateTime.now().toEpochSecond()) * 1000;
    }
}
```

#### Troubleshooting

##### Invalid Username Password Pair Error
In this error scenario, the username provided and the access token used as password are not compatible.
To mitigate this error, navigate to your Azure Cache for Redis resource in the Azure portal. Confirm that:
* In **RBAC Rules**, you've assigned the required role to your user/service principal identity.
* In **Advanced settings**, the **AAD access authorization** box is selected. If not, select it and select the **Save** button.

##### Permissions not granted / NOPERM Error
In this error scenario, the authentication was successful, but your registered user/service principal is not granted the RBAC permission to perform the action.
To mitigate this error, navigate to your Azure Cache for Redis resource in the Azure portal. Confirm that:
* In **RBAC Rules**, you've assigned the appropriate role (Owner, Contributor, Reader) to your user/service principal identity.
* In the event you're using a custom role, ensure the permissions granted under your custom role include the one required for your target action.