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

namespace Aras.ViewModel
{
    [Attributes.ClientControl("Aras.View.ListValue")]
    public class ListValue : Control
    {
        private System.String _value;
        [Attributes.Property("Value", Attributes.PropertyTypes.String, true)]
        public System.String Value
        {
            get
            {
                return this._value;
            }
            set
            {
                if (System.String.Compare(this._value, value) != 0)
                {
                    this._value = value;
                    this.OnPropertyChanged("Value");
                }
            }
        }

        private System.String _label;
        [Attributes.Property("Label", Attributes.PropertyTypes.String, true)]
        public System.String Label
        {
            get
            {
                return this._label;
            }
            set
            {
                if (System.String.Compare(this._label, value) != 0)
                {
                    this._label = value;
                    this.OnPropertyChanged("Label");
                }
            }
        }

        protected override void CheckBinding(object Binding)
        {
            base.CheckBinding(Binding);

            if (Binding != null)
            {
                if (!(Binding is Model.Relationships.Value))
                {
                    throw new Model.Exceptions.ArgumentException("Binding must be of type Aras.Model.ListValue");
                }
            }
        }

        protected override void AfterBindingChanged()
        {
            base.AfterBindingChanged();

            if (this.Binding != null)
            {
                this.Value = (System.String)((Model.Relationships.Value)this.Binding).Property("value").Value;
                this.Label = (System.String)((Model.Relationships.Value)this.Binding).Property("label").Value;
            }
            else
            {
                this.Value = null;
                this.Label = null;
            }
        }

        protected override void BeforeBindingChanged()
        {
            base.BeforeBindingChanged();

            if (this.Binding != null)
            {
                this.Value = null;
                this.Label = null;
            }
        }

        public override string ToString()
        {
            return this.Value;
        }

        public ListValue(Manager.Session Session)
            :base(Session)
        {

        }
    }
}


text:
Ext.Loader.setConfig({enabled: true});

Ext.Loader.setPath('Ext.ux', '../ux/');
Ext.require([
    'Ext.grid.*',
    'Ext.data.*',
    'Ext.util.*',
    'Ext.grid.plugin.BufferedRenderer'
]);

Ext.define('Employee', {
    extend: 'Ext.data.Model',
    fields: [
       {name: 'rating', type: 'int'},
       {name: 'salary', type: 'float'},
       {name: 'name'},
       'rowHeight'
    ]
});

Ext.onReady(function(){
    /**
     * Returns an array of fake data
     * @param {Number} count The number of fake rows to create data for
     * @return {Array} The fake record data, suitable for usage with an ArrayReader
     */
    function createFakeData(count) {
        var firstNames   = ['Ed', 'Tommy', 'Aaron', 'Abe', 'Jamie', 'Adam', 'Dave', 'David', 'Jay', 'Nicolas', 'Nige'],
            lastNames    = ['Spencer', 'Maintz', 'Conran', 'Elias', 'Avins', 'Mishcon', 'Kaneda', 'Davis', 'Robinson', 'Ferrero', 'White'],
            ratings      = [1, 2, 3, 4, 5],
            salaries     = [100, 400, 900, 1500, 1000000];

        var data = [];
        for (var i = 0; i < (count || 25); i++) {
            var ratingId    = Math.floor(Math.random() * ratings.length),
                salaryId    = Math.floor(Math.random() * salaries.length),
                firstNameId = Math.floor(Math.random() * firstNames.length),
                lastNameId  = Math.floor(Math.random() * lastNames.length),

                rating      = ratings[ratingId],
                salary      = salaries[salaryId],
                name        = Ext.String.format("{0} {1}", firstNames[firstNameId], lastNames[lastNameId]);

            data.push({
                id: 'rec-' + i,
                rating: rating,
                salary: salary,
                name: name,
                rowHeight: (i == count - 1) ? 150 : Ext.Number.randomInt(21, 50)
            });
        }
        return data;
    }
    // create the Data Store
    var store = Ext.create('Ext.data.Store', {
        id: 'store',
        pageSize: 50000,
        // allow the grid to interact with the paging scroller by buffering
        buffered: true,
        // never purge any data, we prefetch all up front
        purgePageCount: 0,
        model: 'Employee',
        proxy: {
            type: 'memory'
        }
    });

    var grid = Ext.create('Ext.grid.Panel', {
        width: 700,
        height: 500,
        title: 'Bufffered Grid of 49,679 random records',
        store: store,
        verticalScroller: {
            variableRowHeight: true
        },
        loadMask: true,
        selModel: {
            pruneRemoved: false,
            selectionMode: 'MULTI'
        },
        viewConfig: {
            trackOver: false
        },
        // grid columns
        columns:[{
            xtype: 'rownumberer',
            width: 40,
            sortable: false,
            xhooks: {
                renderer: function(v, meta, record) {
                    meta.tdAttr = 'style="vertical-align:center;height:' + record.data.rowHeight + 'px"';
                    return this.callParent(arguments);
                }
            }
        },{
            text: 'Name',
            flex:1 ,
            sortable: true,
            dataIndex: 'name'
        },{
            text: 'Rating',
            width: 125,
            sortable: true,
            dataIndex: 'rating'
        },{
            text: 'Salary',
            width: 125,
            sortable: true,
            dataIndex: 'salary',
            align: 'right',
            renderer: Ext.util.Format.usMoney
        }],
        renderTo: Ext.getBody()
    });

    var data = createFakeData(49679),
        ln = data.length,
        records = [],
        i = 0;
    for (; i < ln; i++) {
        records.push(Ext.create('Employee', data[i]));
    }

    // Load data as a single, 50000 record page, only render 50 rows.
    store.cachePage(records, 1);
    store.guaranteeRange(0, 49);
});

redpajama_set_name: RedPajamaGithub


text:
package Inheritence.personal_retire;

import java.io.*;
class retire extends personal
{
    double years,pfa,grta;

    retire(double a,double d,double e,String x,String y)
    {
        super(x,y,d,e);

        years=a;
        pfa=0;
        grta=0;

    }

    void prot()throws IOException
    {
        pfa=(2*super.pay*years)/100;
    }

    void grot()throws IOException
    {
        if(years>=10.0)
        {
            grta=12*super.pay;
        }
        else
        grta=0;
    }

    void display()throws IOException
    {
        super.show();
        System.out.println("Years of service="+years);
        System.out.println("Profited fund amount="+pfa);
        System.out.println("Grot="+grta);
    }

    public static void main()throws IOException
    {
        BufferedReader dr=new BufferedReader(new InputStreamReader(System.in));

        System.out.println("Enter the name");
        String a=dr.readLine();

        System.out.println("Enter the pan number");
        String b=dr.readLine();

        System.out.println("Enter the basic pay");
        double c=Double.parseDouble(dr.readLine());

        System.out.println("Enter the Account number");
        double d=Double.parseDouble(dr.readLine());

        System.out.println("Enter the years of service");
        double e=Double.parseDouble(dr.readLine());

        retire r=new retire(e,c,d,a,b);

        r.prot();
        r.grot();
        r.display();
    }
}


text:
* Proposal: [SDL-0106](0106-remote-control-onRcStatus-notification.md)
* Author: [Zhimin Yang](https://github.com/yang1070)
* Status: **Accepted**
* Impacted Platforms: [Core / iOS / Android / RPC ]

## Introduction
One simple resource allocation rule is that at any given time only one application controls a RC module. For example, if SDL allocates a climate control module to application ONE, SDL rejects other applications to change the settings of the same climate control module. The module is freed when application ONE exits, disconnects, goes to HMI level NONE or no longer has the right to control the module due to various reasons (for example, a policy update revokes the access right to the module from the app, or SDL re-allocates the module to another app). In the last case, the mobile application is not aware of the change.

A new notification originated from SDL is nice to have. If SDL allocates a module to an application or it de-allocates a module from an application, SDL shall send OnRCStatus notifications to both the mobile application and the HMI. The notification shall contain an array of the RC modules allocated to the application, so that the mobile application can know it gains or loses control of a module before a failure request, and the HMI can update the status on which application controls which modules.

## Motivation

Mobile applications need to know which remote control modules it can control. HMI needs to show which application controls which module or modules.

SDL core manages the remote control modules. It allocates a module to an application upon a successful `OnButtonPress` or `SetInteriorVehicleData` request to access a `free` module. The application knows whether it can control the module from the result code of the response message. If the result is `SUCCESS`, the application stays in control of the module and can send more control requests. If the result is anything other than `SUCCESS`, the application cannot control the requested module. It shall stop sending more requests to the same module unless it goes to HMI level `FULL`.

SDL can free the allocated resource for various reasons. In most of the cases, the application knows it no longer has the control of the module. However, in some cases, the application does not know it loses the control of the module. For example, a policy update can revoke the application's access to a module. In another example, when a foreground application tries to access an allocated resource, SDL can de-allocate the module from a background application and re-allocate the module to the foreground application. It happens either automatically (the `RCAccessMode` of RC settings is configured as `AUTO_ALLOW`) or manually with the driver's allowing the control right transfer via a popup (the `RCAccessMode` of RC settings is configured as `ASK_DRIVER`). However, in both examples, the application that previously controls the module is not aware of the change until it receives a failure response on next control request. The HMI is also not aware of the change.

## Proposed solution

Add an `OnRCStatus` notification RPC to `Mobile_API.xml` and `HMI_API.xml`

SDL shall send OnRCStatus notifications to all registered mobile applications and the HMI whenever (1) SDL allocates a module to an application or (2) it de-allocates a module from an application, or (3) an application registers with SDL.

#### Existing data related to the change
```
<enum name="ModuleType">
  <element name="CLIMATE"/>
  <element name="RADIO"/>
  <element name="AUDIO"/>
  <element name="LIGHT">
  <element name="HMI_SETTINGS">
  <element name="SEAT">
</enum>

<struct name="ModuleData">
    <description>The moduleType indicates which type of data should be changed and identifies which data object exists in this struct. For example, if the moduleType is CLIMATE then a "climateControlData" should exist</description>
    <param name="moduleType" type="ModuleType" mandatory="true">
    </param>
    <param name="radioControlData" type="RadioControlData" mandatory="false">
    </param>
    <param name="climateControlData" type="ClimateControlData" mandatory="false">
    </param>
    ...
</struct>
```

#### Additions to Mobile_API

```xml
<element name="OnRCStatusID" value="32784" hexvalue="801A" />

<function name="OnRCStatus" messagetype="notification">
  <description>Issued by SDL to notify the application about remote control status change on SDL</description>
  <param name="allocatedModules" type="ModuleData" minsize="0" maxsize="100" array="true" mandatory="true">
    <description>Contains a list (zero or more) of module types that are allocated to the application.</description>
  </param>
  <param name="freeModules" type="ModuleData" minsize="0" maxsize="100" array="true" mandatory="true">
    <description>Contains a list (zero or more) of module types that are free to access for the application.</description>
  </param>
</function>
```
In theory, ```allocatedModules``` and ```freeModules``` shall be two module ID arrays. Since there is not currently agreement on the ID/ZONE scheme of the resources, we use `ModuleData` here. All the optional control data inside of `ModuleData` shall not be included in the notifications. In the future, when we define an ID for a module, we can extend `ModuleData` to include the module ID, without a breaking change.

#### Additions to HMI_API
```xml
<function name="OnRCStatus" messagetype="notification">
  <description>Issued by SDL to notify HMI about remote control status change on SDL</description>
  <param name="appID" type="Integer" mandatory="true">
    <description>ID of selected application.</description>
  </param>
  <param name="allocatedModules" type="ModuleData" minsize="0" maxsize="100" array="true" mandatory="true">
    <description>Contains a list (zero or more) of module types that are allocated to the application.</description>
  </param>
  <param name="freeModules" type="ModuleData" minsize="0" maxsize="100" array="true" mandatory="true">
    <description>Contains a list (zero or more) of module types that are free to access for the application.</description>
  </param>
</function>
```

## Potential downsides
None.

## Impact on existing code
RPC and Mobile iOS/Android SDK changes:
- New mobile API parameters support

SDL core changes:
- Send notifications when a module is allocated/de-allocated to an application.

## Alternatives considered
We can remove the array of free modules in the notification. The difference is that without free module list SDL shall send notifications to the affected application instead of to all applications.

```xml
<function name="OnRCStatus" messagetype="notification">
  <description>Issued by SDL to notify the application about remote control status change on SDL</description>
  <param name="allocatedModules" type="ModuleData" minsize="0" maxsize="100" array="true" mandatory="true">
    <description>Contains a list (zero or more) of module types that are allocated to the application.</description>
  </param>
</function>
```

Another approach is to extend `OnHMIStatus` notification to include new remote control status info. However, that is only for SDL -> Application. We still need a notification from SDL to HMI.


text:
{% import 'appbuilder/general/lib.html' as lib %}

{% if value_columns %}

    {% for item in value_columns %}
        {% set pk=pks[loop.index-1] %}
        {% for value in include_columns %}
            {% set path = url_for(modelview_name + '.list',pk=pk,next=request.path) %}
            {% set path = path | set_link_filters(filters) %}

            {{ item[value] }}
        {% endfor %}
    {% endfor %}

{% else %}
     {{_("No records found")}}
{% endif %}


text:
package org.apache.dubbo.metadata.annotation.processing.builder;

import org.apache.dubbo.metadata.annotation.processing.util.TypeUtils;
import org.apache.dubbo.metadata.definition.model.TypeDefinition;

import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.type.DeclaredType;

import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isSimpleType;

/**
 * {@link TypeDefinitionBuilder} for {@link TypeUtils#SIMPLE_TYPES Java Simple Type}
 *
 * @since 2.7.6
 */
public class SimpleTypeDefinitionBuilder implements DeclaredTypeDefinitionBuilder {

    @Override
    public boolean accept(ProcessingEnvironment processingEnv, DeclaredType type) {
        return isSimpleType(type);
    }

    @Override
    public void build(ProcessingEnvironment processingEnv, DeclaredType type, TypeDefinition typeDefinition) {
        //  DO NOTHING
    }

    @Override
    public int getPriority() {
        return MIN_PRIORITY - 1;
    }
}


text:
package net.xenqtt.message;

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

import java.util.HashSet;
import java.util.Set;

import net.xenqtt.message.MessageStatsImpl;
import net.xenqtt.message.MqttChannel;

import org.junit.Before;
import org.junit.Test;

public class MessageStatsImplTest {

	Set<MqttChannel> openChannels;
	MessageStatsImpl stats;

	@Before
	public void setup() {
		openChannels = new HashSet<MqttChannel>();
		for (int i = 1; i <= 100; i++) {
			MqttChannel channel = mock(MqttChannel.class);
			when(channel.sendQueueDepth()).thenReturn(i);
			when(channel.inFlightMessageCount()).thenReturn(1);
			openChannels.add(channel);
		}
		stats = new MessageStatsImpl(openChannels);
	}

	@Test
	public void testGetMessagesQueuedToSend() {
		assertEquals(0, stats.getMessagesQueuedToSend());
		assertEquals(5050, stats.clone().getMessagesQueuedToSend());
	}

	@Test
	public void testGetMessagesInFlight() {
		assertEquals(0, stats.getMessagesInFlight());
		assertEquals(100, stats.clone().getMessagesInFlight());
	}

	@Test
	public void testGetMessagesSent() {
		stats.messageSent(false);
		stats.messageSent(false);
		stats.messageSent(true);
		stats.messageSent(true);
		stats.messageSent(false);
		stats.messageSent(false);
		stats.messageSent(false);

		assertEquals(7, stats.getMessagesSent());
		assertEquals(7, stats.clone().getMessagesSent());
	}

	@Test
	public void testGetMessagesResent() {
		stats.messageSent(false);
		stats.messageSent(false);
		stats.messageSent(true);
		stats.messageSent(true);
		stats.messageSent(false);
		stats.messageSent(false);
		stats.messageSent(false);

		assertEquals(2, stats.getMessagesResent());
		assertEquals(2, stats.clone().getMessagesResent());
	}

	@Test
	public void testGetMessagesReceived() {
		stats.messageReceived(true);
		stats.messageReceived(false);
		stats.messageReceived(true);
		stats.messageReceived(false);
		stats.messageReceived(false);
		stats.messageReceived(false);
		stats.messageReceived(true);

		assertEquals(7, stats.getMessagesReceived());
		assertEquals(7, stats.clone().getMessagesReceived());
	}

	@Test
	public void testGetDuplicateMessagesReceived() {
		stats.messageReceived(true);
		stats.messageReceived(false);
		stats.messageReceived(true);
		stats.messageReceived(false);
		stats.messageReceived(false);
		stats.messageReceived(false);
		stats.messageReceived(true);

		assertEquals(3, stats.getDuplicateMessagesReceived());
		assertEquals(3, stats.clone().getDuplicateMessagesReceived());
	}

	@Test
	public void testGetMinAckLatencyMillis() {
		stats.messageAcked(10);
		stats.messageAcked(100);
		stats.messageAcked(1000);
		stats.messageAcked(10000);
		stats.messageAcked(100000);
		stats.messageAcked(1000000);
		stats.messageAcked(10000000);

		assertEquals(10, stats.getMinAckLatencyMillis());
		assertEquals(10, stats.clone().getMinAckLatencyMillis());
	}

	@Test
	public void testGetMaxAckLatencyMillis() {
		stats.messageAcked(10);
		stats.messageAcked(100);
		stats.messageAcked(1000);
		stats.messageAcked(10000);
		stats.messageAcked(100000);
		stats.messageAcked(1000000);
		stats.messageAcked(10000000);

		assertEquals(10000000, stats.getMaxAckLatencyMillis());
		assertEquals(10000000, stats.clone().getMaxAckLatencyMillis());
	}

	@Test
	public void testGetAverageAckLatencyMillis() {
		stats.messageAcked(10);
		stats.messageAcked(100);
		stats.messageAcked(1000);
		stats.messageAcked(10000);
		stats.messageAcked(100000);
		stats.messageAcked(1000000);
		stats.messageAcked(10000000);

		double expected = (10 + 100 + 1000 + 10000 + 100000 + 1000000 + 10000000) / 7.0;
		assertEquals(expected, stats.getAverageAckLatencyMillis(), 0.0);
		assertEquals(expected, stats.clone().getAverageAckLatencyMillis(), 0.0);
	}

	@Test
	public void testReset() {
		stats.messageAcked(10);
		stats.messageAcked(100);
		stats.messageAcked(1000);
		stats.messageReceived(false);
		stats.messageReceived(true);
		stats.messageReceived(false);
		stats.messageSent(true);
		stats.messageSent(true);
		stats.messageSent(false);

		assertEquals(5050, stats.clone().getMessagesQueuedToSend());
		assertEquals(100, stats.clone().getMessagesInFlight());
		assertEquals(3, stats.getMessagesSent());
		assertEquals(2, stats.getMessagesResent());
		assertEquals(3, stats.getMessagesReceived());
		assertEquals(1, stats.getDuplicateMessagesReceived());
		assertEquals(10, stats.getMinAckLatencyMillis());
		assertEquals(1000, stats.getMaxAckLatencyMillis());
		assertEquals(370.0, stats.getAverageAckLatencyMillis(), 0.0);

		stats.reset();
		assertEquals(5050, stats.clone().getMessagesQueuedToSend());
		assertEquals(100, stats.clone().getMessagesInFlight());
		assertEquals(0, stats.getMessagesSent());
		assertEquals(0, stats.getMessagesResent());
		assertEquals(0, stats.getMessagesReceived());
		assertEquals(0, stats.getDuplicateMessagesReceived());
		assertEquals(0, stats.getMinAckLatencyMillis());
		assertEquals(0, stats.getMaxAckLatencyMillis());
		assertEquals(0.0, stats.getAverageAckLatencyMillis(), 0.0);
	}

	@Test
	public void testClone() {
		stats.messageAcked(10);
		stats.messageAcked(100);
		stats.messageAcked(1000);
		stats.messageReceived(false);
		stats.messageReceived(true);
		stats.messageReceived(false);
		stats.messageSent(true);
		stats.messageSent(true);
		stats.messageSent(false);

		assertEquals(0, stats.getMessagesQueuedToSend());
		assertEquals(5050, stats.clone().getMessagesQueuedToSend());
		assertEquals(0, stats.getMessagesInFlight());
		assertEquals(100, stats.clone().getMessagesInFlight());
		assertEquals(3, stats.getMessagesSent());
		assertEquals(2, stats.getMessagesResent());
		assertEquals(3, stats.getMessagesReceived());
		assertEquals(1, stats.getDuplicateMessagesReceived());
		assertEquals(10, stats.getMinAckLatencyMillis());
		assertEquals(1000, stats.getMaxAckLatencyMillis());
		assertEquals(370.0, stats.getAverageAckLatencyMillis(), 0.0);

		MessageStatsImpl clone = stats.clone();
		stats.reset();
		assertEquals(5050, clone.getMessagesQueuedToSend());
		assertEquals(100, clone.getMessagesInFlight());
		assertEquals(3, clone.getMessagesSent());
		assertEquals(2, clone.getMessagesResent());
		assertEquals(3, clone.getMessagesReceived());
		assertEquals(1, clone.getDuplicateMessagesReceived());
		assertEquals(10, clone.getMinAckLatencyMillis());
		assertEquals(1000, clone.getMaxAckLatencyMillis());
		assertEquals(370.0, clone.getAverageAckLatencyMillis(), 0.0);
	}

}


text:
"""An entity to create and contain samples, persisted to Verta."""

from __future__ import print_function

import json

from verta._internal_utils import time_utils
from verta._protos.public.monitoring import Summary_pb2 as SummaryService
from verta._protos.public.monitoring.Summary_pb2 import (
    CreateSummarySample,
    DeleteSummarySampleRequest,
    Empty as EmptyProto,
    FindSummarySampleRequest,
    SummarySample as SummarySampleProto,
)
from verta.tracking.entities import _entity
from verta import data_types
from verta.monitoring.alert.entities import Alerts
from .queries import SummarySampleQuery
from .summary_sample import SummarySample

class Summary(_entity._ModelDBEntity):
    """A summary object to validate and aggregate summary samples.

    Users should obtain summaries through one of the query or create methods of
    the ``summaries`` attribute on the monitoring
    sub-:class:`~verta.monitoring.client.Client` instead of
    initializing Summary objects.

    Parameters
    ----------
    conn
        A connection object to the backend service.
    conf
        A configuration object used by conn methods.
    msg
        A protobuf message ai.verta.monitoring.Summary

    Attributes
    ----------
    name: str
        The name of this summary.
    """

    def __init__(self, conn, conf, msg):
        super(Summary, self).__init__(conn, conf, SummaryService, "summary", msg)
        self._conn = conn
        self._conf = conf
        self._monitored_entity_id = msg.monitored_entity_id  # TODO: hide me
        self.name = msg.name
        self.type = msg.type_name  # TODO: hide me

    def __repr__(self):
        return "Summary name:{}, type:{}, monitored_entity_id:{}".format(
            self.name, self.type, self.monitored_entity_id
        )

    @property
    def alerts(self):
        return Alerts(self._conn, self._conf, self.monitored_entity_id, summary=self)

    @property
    def monitored_entity_id(self):
        return self._monitored_entity_id

    def log_sample(
        self, data, labels, time_window_start, time_window_end, created_at=None
    ):
        """Log a summary sample for this summary.

        Parameters
        ----------
        data
            A :mod:`VertaDataType <verta.data_types>` consistent with the type of this summary.
        labels : dict of str to str, optional
            A mapping between label keys and values.
        time_window_start : datetime.datetime or int
            Either a timezone aware datetime object or unix epoch milliseconds.
        time_window_end : datetime.datetime or int
            Either a timezone aware datetime object or unix epoch milliseconds.
        created_after : datetime.datetime or int, optional
            Either a timezone aware datetime object or unix epoch milliseconds.
            Defaults to now, but offered as a parameter to permit backfilling of
            summary samples.

        Returns
        -------
        :class:`~verta.monitoring.summaries.summary_sample.SummarySample`
            A persisted summary sample.
        """
        if not isinstance(data, data_types._VertaDataType):
            raise TypeError(
                "expected a supported VertaDataType, found {}".format(type(data))
            )
        if data._type_string() != self.type:
            raise TypeError(
                "expected a {}, found {}".format(self.type, data._type_string())
            )

        if not created_at:
            created_at = time_utils.now()

        content = json.dumps(data._as_dict())

        created_at_millis = time_utils.epoch_millis(created_at)
        window_start_millis = time_utils.epoch_millis(time_window_start)
        window_end_millis = time_utils.epoch_millis(time_window_end)

        msg = CreateSummarySample(
            summary_id=self.id,
            summary_type_name=data._type_string(),
            content=content,
            labels=labels,
            created_at_millis=created_at_millis,
            time_window_start_at_millis=window_start_millis,
            time_window_end_at_millis=window_end_millis,
        )

        endpoint = "/api/v1/summaries/createSample"
        response = self._conn.make_proto_request("POST", endpoint, body=msg)
        result_msg = self._conn.must_proto_response(response, SummarySampleProto)
        return SummarySample(self._conn, self._conf, result_msg)

    def find_samples(self, query=None):
        """Find summary samples belonging to this summary.

        Parameters
        ----------
        query : :class:`~verta.monitoring.summaries.queries.SummarySampleQuery`, optional
            A query object which filters the set of summary samples.

        Returns
        -------
        list of :class:`~verta.monitoring.summaries.summary_sample.SummarySample`
            A list of summary samples belonging to this summary and matching the
            query.
        """
        if query is None:
            query = SummarySampleQuery()
        msg = query._to_proto_request()
        if self.id not in msg.filter.find_summaries.ids:
            msg.filter.find_summaries.ids.append(self.id)

        endpoint = "/api/v1/summaries/findSample"
        response = self._conn.make_proto_request("POST", endpoint, body=msg)
        success = self._conn.must_proto_response(
            response, FindSummarySampleRequest.Response
        )
        samples = [
            SummarySample(self._conn, self._conf, record) for record in success.samples
        ]
        return samples

    def has_type(self, data_type_cls):  # TODO: hideme
        return self.type == data_type_cls._type_string()

    def delete_samples(self, summary_samples):
        """Delete summary samples from this summary.

        Parameters
        ----------
        summary_samples : list of :class:`~verta.monitoring.summaries.summary_sample.SummarySample`
            The summary samples which should be deleted from this summary.

        Returns
        -------
        bool
            True if the delete was successful.
        """
        try:
            ids = [sample.id for sample in summary_samples]
        except:
            ids = summary_samples
        endpoint = "/api/v1/summaries/deleteSample"
        msg = DeleteSummarySampleRequest(ids=ids)
        response = self._conn.make_proto_request("DELETE", endpoint, body=msg)
        self._conn.must_proto_response(response, EmptyProto)
        return True

    def delete(self):
        """
        Delete this summary.

        Returns
        -------
        bool
            ``True`` if the delete was successful.

        Raises
        ------
        :class:`requests.HTTPError`
            If the delete failed.

        """
        msg = SummaryService.DeleteSummaryRequest(ids=[self.id])
        endpoint = "/api/v1/summaries/deleteSummary"
        response = self._conn.make_proto_request("DELETE", endpoint, body=msg)
        self._conn.must_response(response)
        return True


text:
/**
 * Autogenerated by Thrift Compiler (0.9.3)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
#ifndef workflow_data_model_TYPES_H
#define workflow_data_model_TYPES_H

#include <iosfwd>

#include <thrift/Thrift.h>
#include <thrift/TApplicationException.h>
#include <thrift/protocol/TProtocol.h>
#include <thrift/transport/TTransport.h>

#include <thrift/cxxfunctional.h>
#include "application_io_models_types.h"
#include "airavata_commons_types.h"

struct WorkflowState {
  enum type {
    CREATED = 0,
    STARTED = 1,
    EXECUTING = 2,
    COMPLETED = 3,
    FAILED = 4,
    CANCELLING = 5,
    CANCELED = 6
  };
};

extern const std::map<int, const char*> _WorkflowState_VALUES_TO_NAMES;

struct ComponentState {
  enum type {
    CREATED = 0,
    WAITING = 1,
    READY = 2,
    RUNNING = 3,
    COMPLETED = 4,
    FAILED = 5,
    CANCELED = 6
  };
};

extern const std::map<int, const char*> _ComponentState_VALUES_TO_NAMES;

class WorkflowModel;

class ComponentStatus;

class WorkflowStatus;

class EdgeModel;

class PortModel;

class NodeModel;

typedef struct _WorkflowModel__isset {
  _WorkflowModel__isset() : image(false), workflowInputs(false), workflowOutputs(false), creationTime(false) {}
  bool image :1;
  bool workflowInputs :1;
  bool workflowOutputs :1;
  bool creationTime :1;
} _WorkflowModel__isset;

class WorkflowModel {
 public:

  WorkflowModel(const WorkflowModel&);
  WorkflowModel& operator=(const WorkflowModel&);
  WorkflowModel() : templateId("DO_NOT_SET_AT_CLIENTS"), name(), graph(), gatewayId(), createdUser(), image(), creationTime(0) {
  }

  virtual ~WorkflowModel() throw();
  std::string templateId;
  std::string name;
  std::string graph;
  std::string gatewayId;
  std::string createdUser;
  std::string image;
  std::vector< ::apache::airavata::model::application::io::InputDataObjectType>  workflowInputs;
  std::vector< ::apache::airavata::model::application::io::OutputDataObjectType>  workflowOutputs;
  int64_t creationTime;

  _WorkflowModel__isset __isset;

  void __set_templateId(const std::string& val);

  void __set_name(const std::string& val);

  void __set_graph(const std::string& val);

  void __set_gatewayId(const std::string& val);

  void __set_createdUser(const std::string& val);

  void __set_image(const std::string& val);

  void __set_workflowInputs(const std::vector< ::apache::airavata::model::application::io::InputDataObjectType> & val);

  void __set_workflowOutputs(const std::vector< ::apache::airavata::model::application::io::OutputDataObjectType> & val);

  void __set_creationTime(const int64_t val);

  bool operator == (const WorkflowModel & rhs) const
  {
    if (!(templateId == rhs.templateId))
      return false;
    if (!(name == rhs.name))
      return false;
    if (!(graph == rhs.graph))
      return false;
    if (!(gatewayId == rhs.gatewayId))
      return false;
    if (!(createdUser == rhs.createdUser))
      return false;
    if (__isset.image != rhs.__isset.image)
      return false;
    else if (__isset.image && !(image == rhs.image))
      return false;
    if (__isset.workflowInputs != rhs.__isset.workflowInputs)
      return false;
    else if (__isset.workflowInputs && !(workflowInputs == rhs.workflowInputs))
      return false;
    if (__isset.workflowOutputs != rhs.__isset.workflowOutputs)
      return false;
    else if (__isset.workflowOutputs && !(workflowOutputs == rhs.workflowOutputs))
      return false;
    if (__isset.creationTime != rhs.__isset.creationTime)
      return false;
    else if (__isset.creationTime && !(creationTime == rhs.creationTime))
      return false;
    return true;
  }
  bool operator != (const WorkflowModel &rhs) const {
    return !(*this == rhs);
  }

  bool operator < (const WorkflowModel & ) const;

  uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
  uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;

  virtual void printTo(std::ostream& out) const;
};

void swap(WorkflowModel &a, WorkflowModel &b);

inline std::ostream& operator<<(std::ostream& out, const WorkflowModel& obj)
{
  obj.printTo(out);
  return out;
}

typedef struct _ComponentStatus__isset {
  _ComponentStatus__isset() : reason(false), timeofStateChange(false) {}
  bool reason :1;
  bool timeofStateChange :1;
} _ComponentStatus__isset;

class ComponentStatus {
 public:

  ComponentStatus(const ComponentStatus&);
  ComponentStatus& operator=(const ComponentStatus&);
  ComponentStatus() : state((ComponentState::type)0), reason(), timeofStateChange(0) {
    state = (ComponentState::type)0;

  }

  virtual ~ComponentStatus() throw();
  ComponentState::type state;
  std::string reason;
  int64_t timeofStateChange;

  _ComponentStatus__isset __isset;

  void __set_state(const ComponentState::type val);

  void __set_reason(const std::string& val);

  void __set_timeofStateChange(const int64_t val);

  bool operator == (const ComponentStatus & rhs) const
  {
    if (!(state == rhs.state))
      return false;
    if (__isset.reason != rhs.__isset.reason)
      return false;
    else if (__isset.reason && !(reason == rhs.reason))
      return false;
    if (__isset.timeofStateChange != rhs.__isset.timeofStateChange)
      return false;
    else if (__isset.timeofStateChange && !(timeofStateChange == rhs.timeofStateChange))
      return false;
    return true;
  }
  bool operator != (const ComponentStatus &rhs) const {
    return !(*this == rhs);
  }

  bool operator < (const ComponentStatus & ) const;

  uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
  uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;

  virtual void printTo(std::ostream& out) const;
};

void swap(ComponentStatus &a, ComponentStatus &b);

inline std::ostream& operator<<(std::ostream& out, const ComponentStatus& obj)
{
  obj.printTo(out);
  return out;
}

typedef struct _WorkflowStatus__isset {
  _WorkflowStatus__isset() : timeOfStateChange(false), reason(false) {}
  bool timeOfStateChange :1;
  bool reason :1;
} _WorkflowStatus__isset;

class WorkflowStatus {
 public:

  WorkflowStatus(const WorkflowStatus&);
  WorkflowStatus& operator=(const WorkflowStatus&);
  WorkflowStatus() : state((WorkflowState::type)0), timeOfStateChange(0), reason() {
  }

  virtual ~WorkflowStatus() throw();
  WorkflowState::type state;
  int64_t timeOfStateChange;
  std::string reason;

  _WorkflowStatus__isset __isset;

  void __set_state(const WorkflowState::type val);

  void __set_timeOfStateChange(const int64_t val);

  void __set_reason(const std::string& val);

  bool operator == (const WorkflowStatus & rhs) const
  {
    if (!(state == rhs.state))
      return false;
    if (__isset.timeOfStateChange != rhs.__isset.timeOfStateChange)
      return false;
    else if (__isset.timeOfStateChange && !(timeOfStateChange == rhs.timeOfStateChange))
      return false;
    if (__isset.reason != rhs.__isset.reason)
      return false;
    else if (__isset.reason && !(reason == rhs.reason))
      return false;
    return true;
  }
  bool operator != (const WorkflowStatus &rhs) const {
    return !(*this == rhs);
  }

  bool operator < (const WorkflowStatus & ) const;

  uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
  uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;

  virtual void printTo(std::ostream& out) const;
};

void swap(WorkflowStatus &a, WorkflowStatus &b);

inline std::ostream& operator<<(std::ostream& out, const WorkflowStatus& obj)
{
  obj.printTo(out);
  return out;
}

typedef struct _EdgeModel__isset {
  _EdgeModel__isset() : name(false), status(false), description(false) {}
  bool name :1;
  bool status :1;
  bool description :1;
} _EdgeModel__isset;

class EdgeModel {
 public:

  EdgeModel(const EdgeModel&);
  EdgeModel& operator=(const EdgeModel&);
  EdgeModel() : edgeId("DO_NOT_SET_AT_CLIENTS"), name(), description() {
  }

  virtual ~EdgeModel() throw();
  std::string edgeId;
  std::string name;
  ComponentStatus status;
  std::string description;

  _EdgeModel__isset __isset;

  void __set_edgeId(const std::string& val);

  void __set_name(const std::string& val);

  void __set_status(const ComponentStatus& val);

  void __set_description(const std::string& val);

  bool operator == (const EdgeModel & rhs) const
  {
    if (!(edgeId == rhs.edgeId))
      return false;
    if (__isset.name != rhs.__isset.name)
      return false;
    else if (__isset.name && !(name == rhs.name))
      return false;
    if (__isset.status != rhs.__isset.status)
      return false;
    else if (__isset.status && !(status == rhs.status))
      return false;
    if (__isset.description != rhs.__isset.description)
      return false;
    else if (__isset.description && !(description == rhs.description))
      return false;
    return true;
  }
  bool operator != (const EdgeModel &rhs) const {
    return !(*this == rhs);
  }

  bool operator < (const EdgeModel & ) const;

  uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
  uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;

  virtual void printTo(std::ostream& out) const;
};

void swap(EdgeModel &a, EdgeModel &b);

inline std::ostream& operator<<(std::ostream& out, const EdgeModel& obj)
{
  obj.printTo(out);
  return out;
}

typedef struct _PortModel__isset {
  _PortModel__isset() : name(false), status(false), value(false), description(false) {}
  bool name :1;
  bool status :1;
  bool value :1;
  bool description :1;
} _PortModel__isset;

class PortModel {
 public:

  PortModel(const PortModel&);
  PortModel& operator=(const PortModel&);
  PortModel() : portId("DO_NOT_SET_AT_CLIENTS"), name(), value(), description() {
  }

  virtual ~PortModel() throw();
  std::string portId;
  std::string name;
  ComponentStatus status;
  std::string value;
  std::string description;

  _PortModel__isset __isset;

  void __set_portId(const std::string& val);

  void __set_name(const std::string& val);

  void __set_status(const ComponentStatus& val);

  void __set_value(const std::string& val);

  void __set_description(const std::string& val);

  bool operator == (const PortModel & rhs) const
  {
    if (!(portId == rhs.portId))
      return false;
    if (__isset.name != rhs.__isset.name)
      return false;
    else if (__isset.name && !(name == rhs.name))
      return false;
    if (__isset.status != rhs.__isset.status)
      return false;
    else if (__isset.status && !(status == rhs.status))
      return false;
    if (__isset.value != rhs.__isset.value)
      return false;
    else if (__isset.value && !(value == rhs.value))
      return false;
    if (__isset.description != rhs.__isset.description)
      return false;
    else if (__isset.description && !(description == rhs.description))
      return false;
    return true;
  }
  bool operator != (const PortModel &rhs) const {
    return !(*this == rhs);
  }

  bool operator < (const PortModel & ) const;

  uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
  uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;

  virtual void printTo(std::ostream& out) const;
};

void swap(PortModel &a, PortModel &b);

inline std::ostream& operator<<(std::ostream& out, const PortModel& obj)
{
  obj.printTo(out);
  return out;
}

typedef struct _NodeModel__isset {
  _NodeModel__isset() : name(false), applicationId(false), applicationName(false), status(false), description(false) {}
  bool name :1;
  bool applicationId :1;
  bool applicationName :1;
  bool status :1;
  bool description :1;
} _NodeModel__isset;

class NodeModel {
 public:

  NodeModel(const NodeModel&);
  NodeModel& operator=(const NodeModel&);
  NodeModel() : nodeId("DO_NOT_SET_AT_CLIENTS"), name(), applicationId(), applicationName(), description() {
  }

  virtual ~NodeModel() throw();
  std::string nodeId;
  std::string name;
  std::string applicationId;
  std::string applicationName;
  ComponentStatus status;
  std::string description;

  _NodeModel__isset __isset;

  void __set_nodeId(const std::string& val);

  void __set_name(const std::string& val);

  void __set_applicationId(const std::string& val);

  void __set_applicationName(const std::string& val);

  void __set_status(const ComponentStatus& val);

  void __set_description(const std::string& val);

  bool operator == (const NodeModel & rhs) const
  {
    if (!(nodeId == rhs.nodeId))
      return false;
    if (__isset.name != rhs.__isset.name)
      return false;
    else if (__isset.name && !(name == rhs.name))
      return false;
    if (__isset.applicationId != rhs.__isset.applicationId)
      return false;
    else if (__isset.applicationId && !(applicationId == rhs.applicationId))
      return false;
    if (__isset.applicationName != rhs.__isset.applicationName)
      return false;
    else if (__isset.applicationName && !(applicationName == rhs.applicationName))
      return false;
    if (__isset.status != rhs.__isset.status)
      return false;
    else if (__isset.status && !(status == rhs.status))
      return false;
    if (__isset.description != rhs.__isset.description)
      return false;
    else if (__isset.description && !(description == rhs.description))
      return false;
    return true;
  }
  bool operator != (const NodeModel &rhs) const {
    return !(*this == rhs);
  }

  bool operator < (const NodeModel & ) const;

  uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
  uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;

  virtual void printTo(std::ostream& out) const;
};

void swap(NodeModel &a, NodeModel &b);

inline std::ostream& operator<<(std::ostream& out, const NodeModel& obj)
{
  obj.printTo(out);
  return out;
}

#endif


text:
package org.springframework.context;

import java.util.Map;

/**
 * A stub {@link ApplicationListener}.
 *
 * @author Thomas Risberg
 * @author Juergen Hoeller
 */
public class BeanThatListens implements ApplicationListener<ApplicationEvent> {

	private BeanThatBroadcasts beanThatBroadcasts;

	private int eventCount;

	public BeanThatListens() {
	}

	public BeanThatListens(BeanThatBroadcasts beanThatBroadcasts) {
		this.beanThatBroadcasts = beanThatBroadcasts;
		Map<?, BeanThatListens> beans = beanThatBroadcasts.applicationContext.getBeansOfType(BeanThatListens.class);
		if (!beans.isEmpty()) {
			throw new IllegalStateException("Shouldn't have found any BeanThatListens instances");
		}
	}

	@Override
	public void onApplicationEvent(ApplicationEvent event) {
		eventCount++;
		if (beanThatBroadcasts != null) {
			beanThatBroadcasts.receivedCount++;
		}
	}

	public int getEventCount() {
		return eventCount;
	}

	public void zero() {
		eventCount = 0;
	}

}


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

import com.facebook.presto.operator.aggregation.state.NullableBigintState;
import com.facebook.presto.spi.type.StandardTypes;
import com.facebook.presto.type.SqlType;

@AggregationFunction("sum")
public final class LongSumAggregation
{
    public static final InternalAggregationFunction LONG_SUM = new AggregationCompiler().generateAggregationFunction(LongSumAggregation.class);

    private LongSumAggregation() {}

    @InputFunction
    @IntermediateInputFunction
    public static void sum(NullableBigintState state, @SqlType(StandardTypes.BIGINT) long value)
    {
        state.setNull(false);
        state.setLong(state.getLong() + value);
    }
}


text:
package org.apache.sling.event.impl.jobs.config;

/**
 * Constants for the queue configuration.
 */
public abstract class ConfigurationConstants {

    public static final int NUMBER_OF_PROCESSORS = Runtime.getRuntime().availableProcessors();

    public static final String DEFAULT_PRIORITY = "NORM";
    public static final int DEFAULT_RETRIES = 10;
    public static final long DEFAULT_RETRY_DELAY = 2000;
    public static final int DEFAULT_MAX_PARALLEL = 15;

    public static final String PROP_NAME = "queue.name";
    public static final String PROP_TYPE = "queue.type";
    public static final String PROP_TOPICS = "queue.topics";
    public static final String PROP_MAX_PARALLEL = "queue.maxparallel";
    public static final String PROP_RETRIES = "queue.retries";
    public static final String PROP_RETRY_DELAY = "queue.retrydelay";
    public static final String PROP_PRIORITY = "queue.priority";
    public static final String PROP_KEEP_JOBS = "queue.keepJobs";
    public static final String PROP_THREAD_POOL_SIZE = "queue.threadPoolSize";
    public static final String PROP_PREFER_RUN_ON_CREATION_INSTANCE = "queue.preferRunOnCreationInstance";

}


text:
#pragma once
#include <rj_msgs/msg/detection_frame.hpp>
#include <rj_vision_filter/ball/camera_ball.hpp>
#include <rj_vision_filter/robot/camera_robot.hpp>
#include <utility>
#include <vector>

namespace vision_filter {
using DetectionFrameMsg = rj_msgs::msg::DetectionFrame;

/**
 * Simple non-protobuf object representing a camera frame
 */
class CameraFrame {
public:
    /**
     * Creates a camera frame directly from the protobuf packets
     *
     * @param t_capture Time the frame was captured
     * @param camera_id ID of the camera this frame corresponds to
     * @param camera_balls Unsorted list of ball detections
     * @param camera_robots_yellow Unsorted list of yellow team robot detections
     * @param camera_robots_blue Unsorted list of blue team robot detections
     */
    CameraFrame(RJ::Time t_capture, int camera_id,
                std::vector<CameraBall> camera_balls,
                std::vector<CameraRobot> camera_robots_yellow,
                std::vector<CameraRobot> camera_robots_blue)
        : t_capture(t_capture),
          camera_id(camera_id),
          camera_balls(std::move(camera_balls)),
          camera_robots_yellow(std::move(camera_robots_yellow)),
          camera_robots_blue(std::move(camera_robots_blue)) {}

    /**
     * @brief Constructor from DetectionFrameMsg.
     * @param msg
     */
    CameraFrame(const DetectionFrameMsg& msg,
                const rj_geometry::TransformMatrix& world_to_team,
                double team_angle)
        : t_capture{rj_convert::convert_from_ros(msg.t_capture)},
          camera_id{static_cast<int>(msg.camera_id)},
          camera_balls{},
          camera_robots_yellow{},
          camera_robots_blue{} {
        for (const DetectionBallMsg& ball_msg : msg.balls) {
            camera_balls.emplace_back(t_capture, ball_msg, world_to_team);
        }

        for (const DetectionRobotMsg& robot_msg : msg.robots_blue) {
            camera_robots_blue.emplace_back(t_capture, robot_msg, world_to_team,
                                          team_angle);
        }
        for (const DetectionRobotMsg& robot_msg : msg.robots_yellow) {
            camera_robots_yellow.emplace_back(t_capture, robot_msg, world_to_team,
                                            team_angle);
        }
    }

    RJ::Time t_capture;
    int camera_id;
    std::vector<CameraBall> camera_balls;
    std::vector<CameraRobot> camera_robots_yellow;
    std::vector<CameraRobot> camera_robots_blue;
};
}  // namespace vision_filter


text:
var emitter = require('./index')()

emitter.on('*', function () {
  console.log('all events emitted', this.event)
})

emitter.on('example', function () {
  console.log('example event emitted')
})

emitter.emit('example')

emitter.on('demo', function () {
  console.log('multiple events with `demo` namespace emitted', this.event)
})

emitter.emit('demo:cool')
emitter.emit('demo:awesome')
emitter.emit('demo:great')


text:
package com.cwainner.chris.recipecentral.ui;

import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.ToggleButton;

import com.cwainner.chris.recipecentral.Constants;
import com.cwainner.chris.recipecentral.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import butterknife.Bind;
import butterknife.ButterKnife;

public class LoginActivity extends AppCompatActivity {

    @Bind(R.id.createAccountButton) ToggleButton createAccountButton;

    private DatabaseReference searchedReference;
    private FirebaseAuth.AuthStateListener authStateListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        searchedReference = FirebaseDatabase.getInstance().getReference().child(Constants.FIREBASE_CHILD_SEARCHED);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        final FragmentManager fm = getSupportFragmentManager();
        LoginFragment initialLoginFragment = new LoginFragment();
        FragmentTransaction fragmentTransaction = fm.beginTransaction();
        fragmentTransaction.replace(R.id.loginFrameLayout, initialLoginFragment);
        fragmentTransaction.commit();

        createAccountButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    // Load create account fragment
                    CreateAccountFragment createAccountFragment = new CreateAccountFragment();

                    FragmentTransaction fragmentTransaction = fm.beginTransaction();
                    fragmentTransaction.replace(R.id.loginFrameLayout, createAccountFragment);
                    fragmentTransaction.commit();
                } else {
                    // Load login fragment
                    LoginFragment loginFragment = new LoginFragment();
                    FragmentTransaction fragmentTransaction = fm.beginTransaction();
                    fragmentTransaction.replace(R.id.loginFrameLayout, loginFragment);
                    fragmentTransaction.commit();
                }
            }
        });
    }
}


text:
/*
 * Javascript tests for Analytics
 */

import { cb, platformUrl } from "./utils";

var analytics: Analytics;
beforeAll(function() {
  analytics = cb.Analytics();
});

describe("ClearBlade Analytics", function() {
  it("gets storage data", function() {
    var callNum = ClearBlade.request.mock.calls.length;
    var expectedData = {
      URI: platformUrl,
      endpoint: "api/v/2/analytics/storage",
      method: "GET",
      qs: "query={}",
      user: { authToken: "testUserToken", email: "test@fake.com" }
    };
    analytics.getStorage({}, function(err, data) {
      expect(err).toBeNull();
      expect(ClearBlade.request.mock.calls[callNum][0]).toEqual(expectedData);
    });
  });

  it("gets count", function() {
    var callNum = ClearBlade.request.mock.calls.length;
    var expectedData = {
      URI: platformUrl,
      endpoint: "api/v/2/analytics/count",
      method: "GET",
      qs: "query={}",
      user: { authToken: "testUserToken", email: "test@fake.com" }
    };
    analytics.getCount({}, function(err, data) {
      expect(err).toBeNull();
      expect(ClearBlade.request.mock.calls[callNum][0]).toEqual(expectedData);
    });
  });

  it("gets event list", function() {
    var callNum = ClearBlade.request.mock.calls.length;
    var expectedData = {
      URI: platformUrl,
      endpoint: "api/v/2/analytics/eventlist",
      method: "GET",
      qs: "query={}",
      user: { authToken: "testUserToken", email: "test@fake.com" }
    };
    analytics.getEventList({}, function(err, data) {
      expect(err).toBeNull();
      expect(ClearBlade.request.mock.calls[callNum][0]).toEqual(expectedData);
    });
  });

  it("gets event totals", function() {
    var callNum = ClearBlade.request.mock.calls.length;
    var expectedData = {
      URI: platformUrl,
      endpoint: "api/v/2/analytics/eventtotals",
      method: "GET",
      qs: "query={}",
      user: { authToken: "testUserToken", email: "test@fake.com" }
    };
    analytics.getEventTotals({}, function(err, data) {
      expect(err).toBeNull();
      expect(ClearBlade.request.mock.calls[callNum][0]).toEqual(expectedData);
    });
  });

  it("gets user events", function() {
    var callNum = ClearBlade.request.mock.calls.length;
    var expectedData = {
      URI: platformUrl,
      endpoint: "api/v/2/analytics/userevents",
      method: "GET",
      qs: "query={}",
      user: { authToken: "testUserToken", email: "test@fake.com" }
    };
    analytics.getUserEvents({}, function(err, data) {
      expect(err).toBeNull();
      expect(ClearBlade.request.mock.calls[callNum][0]).toEqual(expectedData);
    });
  });
});


text:
#import "NSObject.h"

@class NSMutableDictionary;

// Not exported
@interface OADColorMap : NSObject
{
    NSMutableDictionary *mMappings;
}

- (void)addDefaultMappings:(_Bool)arg1;
- (_Bool)isEqual:(id)arg1;
- (void)addMapping:(int)arg1 index:(int)arg2;
- (int)mappingForIndex:(int)arg1;
- (void)dealloc;
- (id)init;

@end


text:
namespace Vriska
{
  WindowsThread::WindowsThread() : _threadId(0)
  {
  }

  WindowsThread::~WindowsThread()
  {
  }

  bool			WindowsThread::operator==(INativeThread const & other) const
  {
    WindowsThread const &	nt = reinterpret_cast<WindowsThread const &>(other);

    return (_threadId == nt._threadId);
  }

  bool			WindowsThread::operator!=(INativeThread const & other) const
  {
    return (!(*this == other));
  }

  bool			WindowsThread::launch(IRunnable& run)
  {
    return ((_handle = CreateThread(NULL, 0, reinterpret_cast<LPTHREAD_START_ROUTINE>(&start_thread), &run, 0, _threadId)) != NULL);
  }

  bool			WindowsThread::join()
  {
    return (WaitForSingleObject(_handle, INFINITE) != WAIT_FAILED);
  }

  bool			WindowsThread::terminate()
  {
    return (TerminateThread(_handle, 0) != 0);
  }

  DWORD		WindowsThread::start_thread(LPVOID arg)
  {
    IRunnable	*run = reinterpret_cast<IRunnable *>(arg);

    run->run();
    return (0);
  }
}


text: java -cp build;%JBOSSCLIENT_PATH% Subscriber receive %1 %2 %3


text:
<LINK REL="stylesheet" HREF="../static/styles.css">

<TITLE>Channel::setReverbProperties</TITLE>

Firelight Technologies FMOD Studio API

Channel::setReverbProperties

Sets the wet level (or send level) of a particular reverb instance for the Channel/Channelgroup.

C++ Syntax

FMOD_RESULT Channel::setReverbProperties(
  int instance,
  float wet
);

C Syntax

FMOD_RESULT FMOD_Channel_SetReverbProperties(
  FMOD_CHANNEL *channel,
  int instance,
  float wet
);

C# Syntax

RESULT Channel.setReverbProperties(
  int instance,
  float wet
);

Parameters

instance

Index of the particular reverb instance to target, from 0 to 3.

wet

Send level for the signal to the reverb, from 0 (none) to 1.0 (full), default = 1.0 for Channels, 0.0 for ChannelGroups. See remarks.

Return Values

If the function succeeds then the return value is FMOD_OK.

If the function fails then the return value will be one of the values defined in the FMOD_RESULT enumeration.

Remarks

A Channel is automatically connected to a reverb instance 0 if it exists.  A ChannelGroup though is a dynamic object and will not send to a reverb by default.

To make a ChannelGroup send to a reverb, setReverbProperties must be called.

A ChannelGroup reverb is optimal for the case where you want to send 1 mixed signal to the reverb, rather than a lot of indivual channel reverb sends.

It is advisable to do this to reduce CPU if you have many channels inside a channelgroup.

With A ChannelGroup that has reverb activated on it, and if the ChannelGroup also has Channels that have sends to the same reverb, the behaviour will be that the reverb signal will be sent twice for the channel.

It is better to disable the reverb for channels if you are sending reverb from the parent ChannelGroup.

See Also

ChannelControl::getReverbProperties

Version 1.08.02 Built on Apr 14, 2016


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using EnvDTE;
using EnvDTE80;

using IBR.StringResourceBuilder2011.Modules;

namespace IBR.StringResourceBuilder2011
{
  /// <summary>
  /// Interaction logic for SRBControl.xaml
  /// </summary>
  public partial class SRBControl : UserControl
  {
    #region Constructor

    public SRBControl()
    {
      Trace.WriteLine("Entering SRBControl()");

      InitializeComponent();

      this.progressBar1.Visibility = Visibility.Hidden;

      m_Dte2 = Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(DTE)) as DTE2;

      m_StringResourceBuilder = new StringResourceBuilder(m_Dte2);

      m_StringResourceBuilder.InitProgress        = InitProgress;
      m_StringResourceBuilder.HideProgress        = HideProgress;
      m_StringResourceBuilder.SetProgress         = SetProgress;
      m_StringResourceBuilder.ClearGrid           = ClearGrid;
      m_StringResourceBuilder.SetGridItemsSource  = SetGridItemsSource;
      m_StringResourceBuilder.RefreshGrid         = RefreshGrid;
      m_StringResourceBuilder.SelectCell          = SelectCell;
      m_StringResourceBuilder.GetSelectedItem     = GetSelectedItem;
      m_StringResourceBuilder.GetSelectedColIndex = GetSelectedColIndex;
      m_StringResourceBuilder.GetSelectedRowIndex = GetSelectedRowIndex;
    }

    #endregion //Constructor -----------------------------------------------------------------------

    #region Types
    #endregion //Types -----------------------------------------------------------------------------

    #region Fields

    private DTE2 m_Dte2;

    private bool m_IsVisible;
    //private bool m_IsVisibleChanged;

    private StringResourceBuilder m_StringResourceBuilder;

    private TextEditorEvents m_TextEditorEvents;
    //private EnvDTE80.TextDocumentKeyPressEvents m_TextDocumentKeyPressEvents;
    private int m_FocusedTextDocumentWindowHash;

    private bool m_IsSelectedCellChangedProgrammatically;
    private bool m_IsMakeInProgress;

    private double m_Progress;
    private double m_ProgressStep;

    private int m_LastCurrentColumn = 1;

    #endregion //Fields ----------------------------------------------------------------------------

    #region Properties

    private Microsoft.VisualStudio.Shell.OleMenuCommand m_RescanButton;
    public Microsoft.VisualStudio.Shell.OleMenuCommand RescanButton
    {
      get { return (m_RescanButton); }
      set { m_RescanButton = value; }
    }

    private Microsoft.VisualStudio.Shell.OleMenuCommand m_FirstButton;
    public Microsoft.VisualStudio.Shell.OleMenuCommand FirstButton
    {
      get { return (m_FirstButton); }
      set { m_FirstButton = value; }
    }

    private Microsoft.VisualStudio.Shell.OleMenuCommand m_PreviousButton;
    public Microsoft.VisualStudio.Shell.OleMenuCommand PreviousButton
    {
      get { return (m_PreviousButton); }
      set { m_PreviousButton = value; }
    }

    private Microsoft.VisualStudio.Shell.OleMenuCommand m_NextButton;
    public Microsoft.VisualStudio.Shell.OleMenuCommand NextButton
    {
      get { return (m_NextButton); }
      set { m_NextButton = value; }
    }

    private Microsoft.VisualStudio.Shell.OleMenuCommand m_LastButton;
    public Microsoft.VisualStudio.Shell.OleMenuCommand LastButton
    {
      get { return (m_LastButton); }
      set { m_LastButton = value; }
    }

    private Microsoft.VisualStudio.Shell.OleMenuCommand m_MakeButton;
    public Microsoft.VisualStudio.Shell.OleMenuCommand MakeButton
    {
      get { return (m_MakeButton); }
      set { m_MakeButton = value; }
    }

    private Microsoft.VisualStudio.Shell.OleMenuCommand m_SettingsButton;
    public Microsoft.VisualStudio.Shell.OleMenuCommand SettingsButton
    {
      get { return (m_SettingsButton); }
      set { m_SettingsButton = value; }
    }

    #endregion //Properties ------------------------------------------------------------------------

    #region Events

    private void StringResBuilderWindow_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
      m_IsVisible = (bool)e.NewValue;
      //m_IsVisibleChanged = true;

      if (!m_IsVisible)
      {
        //remove event handlers
        m_Dte2.Events.WindowEvents.WindowActivated -= WindowEvents_WindowActivated;
        m_Dte2.Events.WindowEvents.WindowClosing   -= WindowEvents_WindowClosing;

        Cleanup();
      }
      else
      {
        //assign event handlers (remove first to prevent from doubling them)
        m_Dte2.Events.WindowEvents.WindowActivated -= WindowEvents_WindowActivated;
        m_Dte2.Events.WindowEvents.WindowActivated += WindowEvents_WindowActivated;
        m_Dte2.Events.WindowEvents.WindowClosing   -= WindowEvents_WindowClosing;
        m_Dte2.Events.WindowEvents.WindowClosing   += WindowEvents_WindowClosing;
      } //else
    }

    private void dataGrid1_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
    {
      if (m_IsSelectedCellChangedProgrammatically)
        return;

      ResetCurrentCellToSelection();

      SetEnabled();
    }

    private void dataGrid1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
      DataGrid grid = (sender as DataGrid);
      DataGridColumn col = grid.CurrentColumn;
      if (col == null)
        return;

      if (!col.IsReadOnly)
        return;

      if (e != null)
        e.Handled = true;

      m_StringResourceBuilder.SelectStringInTextDocument();
    }

    private void dataGrid1_GotFocus(object sender, RoutedEventArgs e)
    {
      if (this.dataGrid1.IsMouseOver)
        return;

      //sadly, the DataGrid sets the focus to the first cell when focus returns so we restore it here
      ResetCurrentCellToSelection();
    }

    #region EnvDTE

    private void WindowEvents_WindowActivated(EnvDTE.Window gotFocus, EnvDTE.Window lostFocus)
    {
      //Trace.WriteLine(string.Format("\n>>>> WindowEvents_WindowActivated() - '{0}' <- '{1}' ({2})\n", gotFocus.Caption, lostFocus.Caption, (m_Dte2.ActiveDocument == null) ? "null" : m_Dte2.ActiveDocument.Name));
      Debug.Print("\n>>>> WindowEvents_WindowActivated() - '{0}' <- '{1}' ({2})\n", (gotFocus == null) ? "null" : gotFocus.Caption, (lostFocus == null) ? "null" : lostFocus.Caption, (m_Dte2.ActiveDocument == null) ? "null" : m_Dte2.ActiveDocument.Name);

      if (m_StringResourceBuilder.IsBrowsing)
        return;

      if (!m_IsVisible)
        return;

      if (m_Dte2.ActiveDocument == null)
      {
        if (m_StringResourceBuilder.Window != null)
          WindowEvents_WindowClosing(m_StringResourceBuilder.Window);

        return;
      } //if

      Trace.WriteLine("WindowEvents_WindowActivated()");

      if (m_TextEditorEvents != null)
      {
        m_TextEditorEvents.LineChanged -= m_TextEditorEvents_LineChanged;
        m_TextEditorEvents = null;
      } //if

      //if (m_TextDocumentKeyPressEvents != null)
      //{
      //  m_TextDocumentKeyPressEvents.AfterKeyPress -= m_TextDocumentKeyPressEvents_AfterKeyPress;
      //  m_TextDocumentKeyPressEvents.AfterKeyPress += m_TextDocumentKeyPressEvents_AfterKeyPress;
      //  m_TextDocumentKeyPressEvents = null;
      //} //if

      EnvDTE.Window window = m_Dte2.ActiveDocument.ActiveWindow;

      bool isGotDocument    = (gotFocus != null) && (gotFocus.Document != null),
           isLostDocument   = (lostFocus != null) && (lostFocus.Document != null),
           isGotCode        = isGotDocument && (gotFocus.Caption.EndsWith(".cs") || gotFocus.Caption.EndsWith(".vb")),
           isLostCode       = isLostDocument && (lostFocus.Caption.EndsWith(".cs") || lostFocus.Caption.EndsWith(".vb"));

      if (!isGotDocument /*&& !isLostDocument*/ && (m_StringResourceBuilder.Window != null))
        window = m_StringResourceBuilder.Window;
      if (isGotCode)
        window = gotFocus;
      else if (!isGotDocument && isLostCode)
        window = lostFocus;

      if ((window != null) && (window.Document != null) && (window.Caption.EndsWith(".cs") || window.Caption.EndsWith(".vb")))
      {
        TextDocument txtDoc = window.Document.Object("TextDocument") as TextDocument;
        if (txtDoc != null)
        {
          EnvDTE80.Events2 events = (EnvDTE80.Events2)m_Dte2.Events;

          m_TextEditorEvents = events.TextEditorEvents[txtDoc];
          m_TextEditorEvents.LineChanged -= m_TextEditorEvents_LineChanged;
          m_TextEditorEvents.LineChanged += m_TextEditorEvents_LineChanged;

          //m_TextDocumentKeyPressEvents = events.TextDocumentKeyPressEvents[txtDoc];
          //m_TextDocumentKeyPressEvents.AfterKeyPress -= m_TextDocumentKeyPressEvents_AfterKeyPress;
          //m_TextDocumentKeyPressEvents.AfterKeyPress += m_TextDocumentKeyPressEvents_AfterKeyPress;

          if (m_FocusedTextDocumentWindowHash != window.GetHashCode())
          {
            m_FocusedTextDocumentWindowHash                   = window.GetHashCode();
            m_StringResourceBuilder.FocusedTextDocumentWindow = window;
            this.Dispatcher.BeginInvoke(new Action(m_StringResourceBuilder.DoBrowse));
          } //if
        } //if
      }
      //else if (m_StringResourceBuilder.Window != null)
      //  WindowEvents_WindowClosing(m_StringResourceBuilder.Window);
    }

    private void WindowEvents_WindowClosing(EnvDTE.Window Window)
    {
      if (Window != m_StringResourceBuilder.Window)
        return;

      Trace.WriteLine("WindowEvents_WindowClosing()");

      Cleanup();
    }

    private void m_TextEditorEvents_LineChanged(TextPoint startPoint, TextPoint endPoint, int hint)
    {
      if (m_IsMakeInProgress)
        return;

      vsTextChanged textChangedHint = (vsTextChanged)hint;

      System.Diagnostics.Trace.WriteLine(string.Format("#### m_TextEditorEvents_LineChanged {0};{1} {2};{3} ({4})",
                                                       startPoint.Line, startPoint.LineCharOffset,
                                                       endPoint.Line, endPoint.LineCharOffset,
                                                       textChangedHint.ToString()));

      //if (((textChangedHint & vsTextChanged.vsTextChangedNewline) == 0) &&
      //    ((textChangedHint & vsTextChanged.vsTextChangedMultiLine) == 0) &&
      //    (textChangedHint != 0))
      //  return;

      if (m_IsVisible)
        this.Dispatcher./*Begin*/Invoke(new Action<TextPoint, TextPoint>(m_StringResourceBuilder.DoBrowse), startPoint, endPoint); //[12-07-21 DR]: synchronously due to multiple events for one edit
      else
        m_FocusedTextDocumentWindowHash = 0;
    }

    //private void m_TextDocumentKeyPressEvents_AfterKeyPress(string keyPress, EnvDTE.TextSelection selection, bool inStatementCompletion)
    //{
    //  System.Diagnostics.Trace.WriteLine(string.Format("#### m_TextDocumentKeyPressEvents_AfterKeyPress '{0}' {1} ({2})", keyPress, selection.AnchorPoint.Line, inStatementCompletion));
    //}

    #endregion

    #endregion //Events ----------------------------------------------------------------------------

    #region Private members

    private void SetEnabled()
    {
      int count         = this.dataGrid1.Items.Count,
          selectedIndex = GetSelectedRowIndex();
      bool isEmpty      = (count == 0),
           //isMulti      = (count > 1),
           isFirst      = (selectedIndex == 0),
           isLast       = (selectedIndex == count - 1);

      if (m_FirstButton    != null) m_FirstButton.Enabled    = !isFirst;
      if (m_LastButton     != null) m_LastButton.Enabled     = !isLast;
      if (m_PreviousButton != null) m_PreviousButton.Enabled = !isFirst;
      if (m_NextButton     != null) m_NextButton.Enabled     = !isLast;
      if (m_MakeButton     != null) m_MakeButton.Enabled     = !isEmpty;
    }

    private void Cleanup()
    {
      m_StringResourceBuilder.Window                    = null;
      m_StringResourceBuilder.FocusedTextDocumentWindow = null;
      m_FocusedTextDocumentWindowHash                   = 0;

      if (m_TextEditorEvents != null)
      {
        m_TextEditorEvents.LineChanged -= m_TextEditorEvents_LineChanged;
        m_TextEditorEvents = null;
      } //if

      ClearGrid();

      m_StringResourceBuilder.ClearStringResources();
    }

    #region ProgressBar
    private void InitProgress(double maximum)
    {
      this.progressBar1.Value = 0D;
      this.progressBar1.Maximum = maximum;
      this.progressBar1.Visibility = Visibility.Visible;
      this.progressBar1.Refresh();

      m_Progress = 0D;
      m_ProgressStep = this.progressBar1.Maximum / 10D;
    }

    private void HideProgress()
    {
      this.progressBar1.Visibility = Visibility.Hidden;
      this.progressBar1.Refresh();
    }

    private void SetProgress(double value)
    {
      try
      {
        //System.Diagnostics.Debug.Print("{0}/{1}", value, this.progressBar1.Maximum);
        this.progressBar1.Value = value;

        if (m_Progress + m_ProgressStep <= value)
        {
          m_Progress += m_ProgressStep;
          this.progressBar1.Refresh();
        } //if
      }
      catch
      {
        System.Diagnostics.Debug.Print("###err");
      }
    }

    private void SetProgress(int value)
    {
#if USE_THREAD
      try
      {
        //System.Diagnostics.Debug.Print("{0}/{1}", value, this.progressBar1.Maximum);
        this.progressBar1.Value = (double)value;

        if (m_Progress + m_ProgressStep <= (double)value)
        {
          m_Progress += m_ProgressStep;
          //this.progressBar1.Refresh();
        } //if
      }
      catch
      {
        System.Diagnostics.Debug.Print("###err");
      }
#else
      SetProgress((double)value);
#endif
    }
    #endregion

    #region Grid
    private void ClearGrid()
    {
      if (this.dataGrid1.ItemsSource != null)
      {
        if (this.dataGrid1.CurrentColumn != null)
          m_LastCurrentColumn = this.dataGrid1.CurrentColumn.DisplayIndex;
        else if ((this.dataGrid1.SelectedCells.Count > 0) && (this.dataGrid1.SelectedCells[0].Column != null))
          m_LastCurrentColumn = this.dataGrid1.SelectedCells[0].Column.DisplayIndex;
        else
          m_LastCurrentColumn = 1;
      } //if

      this.dataGrid1.UnselectAllCells();
      this.dataGrid1.ItemsSource = null;
    }

    private void SetGridItemsSource(System.Collections.IEnumerable source)
    {
      this.dataGrid1.ItemsSource = source;
    }

    private void RefreshGrid()
    {
      this.dataGrid1.Items.Refresh();
    }

    private void SelectCell(int rowNo,
                            int colNo)
    {
      if (this.dataGrid1.Items.Count <= rowNo)
        rowNo = this.dataGrid1.Items.Count - 1;

      if (this.dataGrid1.Columns.Count <= colNo)
        colNo = this.dataGrid1.Columns.Count - 1;

      if (rowNo < 0)
        return;

      if (colNo < 0)
        return;

      m_IsSelectedCellChangedProgrammatically = true;

      this.dataGrid1.UnselectAllCells();

      DataGridCellInfo cellInfo = new DataGridCellInfo(this.dataGrid1.Items[rowNo], this.dataGrid1.Columns[colNo]);
      this.dataGrid1.CurrentCell = cellInfo;
      this.dataGrid1.ScrollIntoView(this.dataGrid1.Items[rowNo]);

      this.dataGrid1.SelectedCells.Add(cellInfo);

      m_StringResourceBuilder.SelectedGridRowIndex = rowNo;

      SetEnabled();

      m_IsSelectedCellChangedProgrammatically = false;
    }

    private StringResource GetSelectedItem()
    {
      //Debug.Print(">>> {0}", (this.dataGrid1.SelectedCells.Count == 0) ? "null" : (this.dataGrid1.SelectedCells[0].Item as StringResource).Name);

      if (this.dataGrid1.SelectedCells.Count > 0)
        return (this.dataGrid1.SelectedCells[0].Item as StringResource);
      else
        return (null);
    }

    private int GetSelectedRowIndex()
    {
      object currentItem = GetSelectedItem();

      if (currentItem == null)
        return (0);

      return (this.dataGrid1.Items.IndexOf(currentItem));
    }

    private int GetSelectedColIndex()
    {
      if (this.dataGrid1.CurrentColumn == null)
        return (m_LastCurrentColumn);

      return (this.dataGrid1.CurrentColumn.DisplayIndex);
    }

    private void ResetCurrentCellToSelection()
    {
      bool isCellChangeProgrammatically = m_IsSelectedCellChangedProgrammatically;

      m_IsSelectedCellChangedProgrammatically = true;

      if ((this.dataGrid1.SelectedCells.Count > 0) && (this.dataGrid1.CurrentCell != this.dataGrid1.SelectedCells[0]))
        this.dataGrid1.CurrentCell = this.dataGrid1.SelectedCells[0];

      m_IsSelectedCellChangedProgrammatically = isCellChangeProgrammatically;
    }

    private void GetGridSelectionStates(out bool isEmpty,
                                        out bool isFirst,
                                        out bool isLast)
    {
      int count         = this.dataGrid1.Items.Count,
          selectedIndex = GetSelectedRowIndex();

      isEmpty = (count == 0);
      isFirst = (selectedIndex == 0);
      isLast  = (selectedIndex == count - 1);
    }
    #endregion

    #endregion //Private members -------------------------------------------------------------------

    #region Public members

    //Rescan

    internal bool GetRescanEnabled()
    {
      return (true);
    }

    internal void DoRescan()
    {
      m_StringResourceBuilder.DoBrowse();
    }

    //First

    internal bool GetFirstEnabled()
    {
      bool isEmpty,
           isFirst,
           isLast;

      GetGridSelectionStates(out isEmpty, out isFirst, out isLast);

      return (!isFirst && !isEmpty);
    }

    internal void DoGotoFirst()
    {
      SelectCell(0, GetSelectedColIndex());
      m_StringResourceBuilder.SelectStringInTextDocument();
    }

    //Previous

    internal bool GetPreviousEnabled()
    {
      bool isEmpty,
           isFirst,
           isLast;

      GetGridSelectionStates(out isEmpty, out isFirst, out isLast);

      return (!isFirst && !isEmpty);
    }

    internal void DoGotoPrevious()
    {
      SelectCell(GetSelectedRowIndex() - 1, GetSelectedColIndex());
      m_StringResourceBuilder.SelectStringInTextDocument();
    }

    //Next

    internal bool GetNextEnabled()
    {
      bool isEmpty,
           isFirst,
           isLast;

      GetGridSelectionStates(out isEmpty, out isFirst, out isLast);

      return (!isLast && !isEmpty);
    }

    internal void DoGotoNext()
    {
      SelectCell(GetSelectedRowIndex() + 1, GetSelectedColIndex());
      m_StringResourceBuilder.SelectStringInTextDocument();
    }

    //Last

    internal bool GetLastEnabled()
    {
      bool isEmpty,
           isFirst,
           isLast;

      GetGridSelectionStates(out isEmpty, out isFirst, out isLast);

      return (!isLast && !isEmpty);
    }

    internal void DoGotoLast()
    {
      SelectCell(this.dataGrid1.Items.Count - 1, GetSelectedColIndex());
      m_StringResourceBuilder.SelectStringInTextDocument();
    }

    //Make

    internal bool GetMakeEnabled()
    {
      bool isEmpty,
           isFirst,
           isLast;

      GetGridSelectionStates(out isEmpty, out isFirst, out isLast);

      return (!isEmpty);
    }

    internal void DoMake()
    {
      try
      {
        m_IsMakeInProgress = true;
        m_StringResourceBuilder.BuildAndUseResource();
      }
      finally
      {
        m_IsMakeInProgress = false;
      }
    }

    //Settings

    internal bool GetSettingsEnabled()
    {
      return (true);
    }

    internal void DoSettings()
    {
      GUI.SettingsWindow window = new GUI.SettingsWindow(m_StringResourceBuilder.Settings);

      if (window.ShowDialog() ?? false)
      {
        m_StringResourceBuilder.SaveSettings();
        DoRescan();
      } //if

#if xDEBUG
      OutlineCode();
#endif
    }

    #endregion //Public members -----------------------------------------------------------------------
  } //class
} //namespace


text:
//Problem 7. Selection sort
//
//Sorting an array means to arrange its elements in increasing order. Write a program to sort an array.
//Use the Selection sort algorithm: Find the smallest element, move it at the first position,
//find the smallest from the rest, move it at the second position, etc.

using System;
class Sort
{
    static void Main()
    {
        Console.Write("Please enter array lenght: ");
        int arrLenght = int.Parse(Console.ReadLine());
        int[] array = new int[arrLenght];
        int switcher;

        Random rng = new Random(); // Fill array with random numbers
        for (int i = 0; i < arrLenght; i++)
        {
            array[i] = rng.Next(1, 99);
            Console.Write(array[i] + " ");
        }

        for (int i = 0; i < arrLenght; i++)
        {
            for (int a = i + 1; a < arrLenght; a++)
            {
                if (array[i] > array[a])
                {
                    switcher = array[i];
                    array[i] = array[a];
                    array[a] = switcher;
                }
            }
        }

        Console.WriteLine();
        for (int i = 0; i < arrLenght; i++)
        {
            Console.Write(array[i] + " ");
        }
    }
}


text:
package org.c4sg.service.impl;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.c4sg.service.GeocodeService;
import org.c4sg.util.CountryCodeConverterUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;
import net.minidev.json.JSONValue;

@Service
public class GoogleGeocodeService implements GeocodeService {

	@Value("${google_map_api_key}")
	private String googleApiKey;

	@Override
	public Map<String, BigDecimal> getGeoCode(String state, String country) throws Exception {

		Map<String,BigDecimal> geocode = new HashMap<String,BigDecimal>();

		// validate input
		if(country != null && !country.isEmpty()) {
			StringBuilder address = new StringBuilder();
			if (state != null && !state.isEmpty()) {
				address.append(state);
				address.append(",");
			}
			String countryCode = CountryCodeConverterUtil.convertToIso2(country);
			address.append(countryCode);

			try {
				URL url = getRequestUrl(address.toString());
				String response = getResponse(url);
				if(response != null) {
					Object obj = JSONValue.parse(response);

					if(obj instanceof JSONObject) {
						JSONObject jsonObject = (JSONObject) obj;
						JSONArray array = (JSONArray) jsonObject.get("results");
						JSONObject element = (JSONObject) array.get(0);
						JSONObject geometry = (JSONObject) element.get("geometry");
						JSONObject location = (JSONObject) geometry.get("location");
						Double lng = (Double) location.get("lng");
						Double lat = (Double) location.get("lat");
						geocode.put("lng", new BigDecimal(lng));
						geocode.put("lat", new BigDecimal(lat));
					}
					return geocode;
				} else {
					throw new Exception("Fail to convert to geocode");
				}
			}
			catch(Exception ex) {
				throw new Exception(ex.getMessage());

			}

		}

		return geocode;
	}

	private String getResponse(URL url) throws Exception {
		HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.setRequestMethod("GET");

		if (httpConnection.getResponseCode() == 200) {
			BufferedReader in = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
			String inputLine;
			StringBuffer response = new StringBuffer();

			while ((inputLine = in.readLine()) != null) {
				response.append(inputLine);
			}
			in.close();
			return response.toString();
		}
		else {
			throw new Exception("Fail to convert to geocode");
		}
	}

	private URL getRequestUrl(String url) throws MalformedURLException, UnsupportedEncodingException {
		StringBuilder query = new StringBuilder();
		query.append("https://maps.googleapis.com/maps/api/geocode/json?address=");
		query.append(URLEncoder.encode(url, "UTF-8"));
		query.append("&key=" + googleApiKey);

		return new URL(query.toString());
	}

}


text:
package com.hotfixs.thinkinginjava.innerclasses;

/**
 * @author wang
 */
public class Parcel8 {
    public Wrapping wrapping(int x) {
        return new Wrapping(x) {
            @Override
            public int value() {
                return super.value() * 47;
            }
        };
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="false" android:drawable="@drawable/white_btn_normal" />
    <item android:state_pressed="true" android:drawable="@drawable/white_btn_press" />
    <item android:state_focused="true" android:drawable="@drawable/white_btn_press" />
    <item android:drawable="@drawable/white_btn_normal" />
</selector>


text:
/********************************/
/********* EXAMPLE FILE *********/
/********************************/

var BaseComponent = require('../base-component');

var LiveChatComponent = BaseComponent.extend({
  initialize: function(test, baseSelector) {
    this.baseSelector = baseSelector;
    this.selectors = {
      liveChat: '.live-chat',
    };

    BaseComponent.initialize.call(this, test);
  },

  clickLiveChat: function() {
    this.test.click(this.getSelector('liveChat'));
    this.waitForAngular();
  },
});

module.exports = LiveChatComponent;


text:
package android.telecom;

import com.android.internal.os.SomeArgs;
import com.android.internal.telecom.IVideoCallback;

import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;

/**
 * A component that provides an RPC servant implementation of {@link IVideoCallback},
 * posting incoming messages on the main thread on a client-supplied delegate object.
 *
 * TODO: Generate this and similar classes using a compiler starting from AIDL interfaces.
 *
 * @hide
 */
final class VideoCallbackServant {
    private static final int MSG_RECEIVE_SESSION_MODIFY_REQUEST = 0;
    private static final int MSG_RECEIVE_SESSION_MODIFY_RESPONSE = 1;
    private static final int MSG_HANDLE_CALL_SESSION_EVENT = 2;
    private static final int MSG_CHANGE_PEER_DIMENSIONS = 3;
    private static final int MSG_CHANGE_CALL_DATA_USAGE = 4;
    private static final int MSG_CHANGE_CAMERA_CAPABILITIES = 5;
    private static final int MSG_CHANGE_VIDEO_QUALITY = 6;

    private final IVideoCallback mDelegate;

    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            try {
                internalHandleMessage(msg);
            } catch (RemoteException e) {
            }
        }

        // Internal method defined to centralize handling of RemoteException
        private void internalHandleMessage(Message msg) throws RemoteException {
            switch (msg.what) {
                case MSG_RECEIVE_SESSION_MODIFY_REQUEST: {
                    mDelegate.receiveSessionModifyRequest((VideoProfile) msg.obj);
                    break;
                }
                case MSG_RECEIVE_SESSION_MODIFY_RESPONSE: {
                    SomeArgs args = (SomeArgs) msg.obj;
                    try {
                        mDelegate.receiveSessionModifyResponse(
                                args.argi1,
                                (VideoProfile) args.arg1,
                                (VideoProfile) args.arg2);
                    } finally {
                        args.recycle();
                    }
                    break;
                }
                case MSG_HANDLE_CALL_SESSION_EVENT: {
                    SomeArgs args = (SomeArgs) msg.obj;
                    try {
                        mDelegate.handleCallSessionEvent(args.argi1);
                    } finally {
                        args.recycle();
                    }
                    break;
                }
                case MSG_CHANGE_PEER_DIMENSIONS: {
                    SomeArgs args = (SomeArgs) msg.obj;
                    try {
                        mDelegate.changePeerDimensions(args.argi1, args.argi2);
                    } finally {
                        args.recycle();
                    }
                    break;
                }
                case MSG_CHANGE_CALL_DATA_USAGE: {
                    SomeArgs args = (SomeArgs) msg.obj;
                    try {
                        mDelegate.changeCallDataUsage((long) args.arg1);
                    } finally {
                        args.recycle();
                    }
                    break;
                }
                case MSG_CHANGE_CAMERA_CAPABILITIES: {
                    mDelegate.changeCameraCapabilities((VideoProfile.CameraCapabilities) msg.obj);
                    break;
                }
                case MSG_CHANGE_VIDEO_QUALITY: {
                    mDelegate.changeVideoQuality(msg.arg1);
                    break;
                }
            }
        }
    };

    private final IVideoCallback mStub = new IVideoCallback.Stub() {
        @Override
        public void receiveSessionModifyRequest(VideoProfile videoProfile) throws RemoteException {
            mHandler.obtainMessage(MSG_RECEIVE_SESSION_MODIFY_REQUEST, videoProfile).sendToTarget();
        }

        @Override
        public void receiveSessionModifyResponse(int status, VideoProfile requestedProfile,
                VideoProfile responseProfile) throws RemoteException {
            SomeArgs args = SomeArgs.obtain();
            args.argi1 = status;
            args.arg1 = requestedProfile;
            args.arg2 = responseProfile;
            mHandler.obtainMessage(MSG_RECEIVE_SESSION_MODIFY_RESPONSE, args).sendToTarget();
        }

        @Override
        public void handleCallSessionEvent(int event) throws RemoteException {
            SomeArgs args = SomeArgs.obtain();
            args.argi1 = event;
            mHandler.obtainMessage(MSG_HANDLE_CALL_SESSION_EVENT, args).sendToTarget();
        }

        @Override
        public void changePeerDimensions(int width, int height) throws RemoteException {
            SomeArgs args = SomeArgs.obtain();
            args.argi1 = width;
            args.argi2 = height;
            mHandler.obtainMessage(MSG_CHANGE_PEER_DIMENSIONS, args).sendToTarget();
        }

        @Override
        public void changeCallDataUsage(long dataUsage) throws RemoteException {
            SomeArgs args = SomeArgs.obtain();
            args.arg1 = dataUsage;
            mHandler.obtainMessage(MSG_CHANGE_CALL_DATA_USAGE, args).sendToTarget();
        }

        @Override
        public void changeCameraCapabilities(
                VideoProfile.CameraCapabilities cameraCapabilities)
                throws RemoteException {
            mHandler.obtainMessage(MSG_CHANGE_CAMERA_CAPABILITIES, cameraCapabilities)
                    .sendToTarget();
        }

        @Override
        public void changeVideoQuality(int videoQuality) throws RemoteException {
            mHandler.obtainMessage(MSG_CHANGE_VIDEO_QUALITY, videoQuality, 0).sendToTarget();
        }
    };

    public VideoCallbackServant(IVideoCallback delegate) {
        mDelegate = delegate;
    }

    public IVideoCallback getStub() {
        return mStub;
    }
}


text:
'''
Utility functions for tests.
'''

import os

def data_path(name):
    '''
    Return the absolute path to a file in the test/data directory.
    The name specified should be relative to test/data.
    '''
    return os.path.join(os.path.dirname(__file__), "data", name)


text:
import json
from datetime import datetime, date
from collections import defaultdict

from six import PY3

from dataset.freeze.format.common import Serializer

class JSONEncoder(json.JSONEncoder):

    def default(self, obj):
        if isinstance(obj, (datetime, date)):
            return obj.isoformat()

class JSONSerializer(Serializer):

    def init(self):
        self.buckets = defaultdict(list)

    def write(self, path, result):
        self.buckets[path].append(result)

    def wrap(self, result):
        if self.mode == 'item':
            result = result[0]
        if self.wrap:
            result = {
                'count': self.query.count,
                'results': result
            }
            meta = self.export.get('meta', {})
            if meta is not None:
                result['meta'] = meta
        return result

    def close(self):
        for path, result in self.buckets.items():
            result = self.wrap(result)

            if self.fileobj is None:
                if PY3:  # pragma: no cover
                    fh = open(path, 'w', encoding='utf8')
                else:
                    fh = open(path, 'wb')
            else:
                fh = self.fileobj

            data = json.dumps(result,
                              cls=JSONEncoder,
                              indent=self.export.get_int('indent'))
            if self.export.get('callback'):
                data = "%s && %s(%s);" % (self.export.get('callback'),
                                          self.export.get('callback'),
                                          data)
            fh.write(data)
            fh.close()


text:
linux-arch-install
==================

Comments on how to install Arch Linux from scratch and other usefull topics encountered when playing around with the system.

UEFI-GRUB2-system contains the installation instructions for arch linux.


text:
var express = require('express');
var redis = require("./redis");

module.exports = (function () {
    'use strict';
    var app = express.Router();

    app.get('/user/:id/rep', getUserRep);

    function getUserRep(req, res, next) {
        var id = req.params.id;
        _getUserRep(id, function (obj) {
            res.json({status: "success", obj: obj});
        });
    }

    function _getUserRep(id, cb) {
        var hash = "user:" + id + ":rep:";
        redis.client.multi([
            ["get", hash + "events"],
            ["get", hash + "hushtags"],
            ["get", hash + "locations"]
        ]).execAsync().then(cb).error(function (err) {
            console.log("error while getting rep for user " + id);
            console.log(err);
        });
    }

    var helper = {};

    helper.repChange = function(incrDecr, id, type, cb) {
        var newType = "";
        if (type == "event" || type == "hushtag" || type == "location") {
            newType = type + "s";
        } else if (type == "hushtagUse") {
            newType = "hushtags";
        } else {
            console.log("ERROR: incorrect type for rep increase:"+type);
            cb(false);
        }
        var hash = "user:" + id + ":rep:" + newType;
        var operation = (incrDecr=="incr"?"incr":"decr") + "Async";
        redis.client[operation](hash).then(function () {
            cb(true)
        }).error(function (err) {
            console.log("ERROR: increasing rep for user " + id + " on " + type);
            console.log(err);
            cb(false);
        });
    };

    return {
        router: app,
        helper: helper
    };
})();


text:
#ifndef LOGGING_COMPILE_TIME_H
#define LOGGING_COMPILE_TIME_H 1

#include <type_traits>
#include <cstdarg>

#include "logging_defs.hh"

namespace NAMESPACE
{
    /* TODO we're doing this twice to make it constexpr
     * Can we do extern constexpr?
     */
#ifndef DEFAULT_LOG_LEVEL
#define DEFAULT_LOG_LEVEL (7)
#endif
    constexpr static int compiletime_log_level_constexpr = DEFAULT_LOG_LEVEL;
#undef DEFAULT_LOG_LEVEL

    /**
     * @brief Logging template for vprintf style calls
     * @tparam L The log level to log
     * @param format The format string
     * @param args The format arguments
     */
    template<enum LogLevel L>
        typename std::enable_if<(compiletime_log_level_constexpr >= L), void>::type
        write_log(const char * format, va_list args)
        {
            logging_impl_function(L, format, args);
        }

    /**
     * @brief Logging template for printf style calls
     * @tparam L The log level to log
     * @param format The format string
     * @param ... The format arguments
     */
    template<enum LogLevel L>
        typename std::enable_if<(compiletime_log_level_constexpr >= L), void>::type
        write_log(const char * format, ...)
        {
            va_list args;
            va_start(args, format);
            write_log<L>(format, args);
            va_end(args);
        }

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"

    template<enum LogLevel L>
        typename std::enable_if<(compiletime_log_level_constexpr < L), void>::type
        write_log(const char * format, va_list args)
        {
            /* Intentionally left black for SFINAE */
        }

    template<enum LogLevel L>
        typename std::enable_if<(compiletime_log_level_constexpr < L), void>::type
        write_log(const char * format, ...)
        {
            /* Intentionally left black for SFINAE */
        }

#pragma GCC diagnostic pop
}

#endif /* guard */


text:
package com.thinkgem.jeesite.test.service;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.test.entity.TestData;
import com.thinkgem.jeesite.test.dao.TestDataDao;

/**
 * 单表生成Service
 * @author ThinkGem
 * @version 2015-04-06
 */@Service
@Transactional(readOnly = true)
public class TestDataService extends CrudService<TestDataDao, TestData> {

	public TestData get(String id) {
		return super.get(id);
	}

	public List<TestData> findList(TestData testData) {
		return super.findList(testData);
	}

	public Page<TestData> findPage(Page<TestData> page, TestData testData) {
		return super.findPage(page, testData);
	}

	@Transactional(readOnly = false)
	public void save(TestData testData) {
		super.save(testData);
	}

	@Transactional(readOnly = false)
	public void delete(TestData testData) {
		super.delete(testData);
	}

}