text:
import { t, ChartMetadata, ChartPlugin } from '@superset-ui/core';
import transformProps from '../transformProps';
import example1 from './images/LineChart.jpg';
import example2 from './images/LineChart2.jpg';
import battery from './images/battery.jpg';
import thumbnail from './images/thumbnail.png';
import { ANNOTATION_TYPES } from '../vendor/superset/AnnotationTypes';
import controlPanel from './controlPanel';

const metadata = new ChartMetadata({
  canBeAnnotationTypes: [ANNOTATION_TYPES.TIME_SERIES],
  category: t('Evolution'),
  credits: ['http://nvd3.org'],
  description: t('Classic chart that visualizes how metrics change over time.'),
  exampleGallery: [
    { url: example1 },
    { url: example2 },
    { url: battery, caption: t('Battery level over time') },
  ],
  name: t('Line Chart'),
  supportedAnnotationTypes: [
    ANNOTATION_TYPES.TIME_SERIES,
    ANNOTATION_TYPES.INTERVAL,
    ANNOTATION_TYPES.EVENT,
    ANNOTATION_TYPES.FORMULA,
  ],
  tags: [t('Aesthetic'), t('Legacy'), t('nvd3'), t('Deprecated')],
  thumbnail,
  useLegacyApi: true,
});

export default class LineChartPlugin extends ChartPlugin {
  constructor() {
    super({
      loadChart: () => import('../ReactNVD3'),
      metadata,
      transformProps,
      controlPanel,
    });
  }
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2015 Zhu.Jin Liang

#ifndef CAFFE_UTIL_UTIL_COORDS_H_
#define CAFFE_UTIL_UTIL_COORDS_H_

#include <map>

#include "caffe/net.hpp"
#include "caffe/util/coords.hpp"

namespace caffe {

template <typename Dtype> class Net;

/*
 * @brief bottom的大小至少为0,找出在net中,
 * 				从bottom[0]映射到bottom[1]的映射关系
 */
template <typename Dtype>
DiagonalAffineMap<Dtype> GetMapBetweenFeatureMap(const vector<Blob<Dtype>*>& bottom,
		const Net<Dtype>* const net);

}  // namespace caffe

#endif  // CAFFE_UTIL_UTIL_COORDS_H_


text:
package lejos.hardware;

import lejos.hardware.device.NewIRLink;
import lejos.hardware.lcd.LCD;
import lejos.hardware.port.SensorPort;
import lejos.utility.Delay;

/**
 * Description: LeJOS NXJ new IRLink driver.
 * Run PF Extended Mode Tests.
 * // RM: It works!
 */

public class IRLinkPF_EM {

    /* Sensors */
    private NewIRLink pfIRLink;

    /* Constructor */
    public IRLinkPF_EM() {
        pfIRLink = new NewIRLink(SensorPort.S2);
    }

    public static void main(String[] args) {
        IRLinkPF_EM obj = new IRLinkPF_EM();
        obj.testPFExtendedMode(); // Run PF Extended Mode Tests.
    }

    // PF Extended Mode Tests.
    public void testPFExtendedMode() {

        LCD.drawString("PF EM:", 0, 0);
        //for (int i=0; i<4; i++) {
        //	pfIRLink.sendPFExtended(i, IRLink.PF_EM_COMMAND_SYNCTOGGLEBIT);
        //}

        while (!(Button.ESCAPE.isDown())) {

            if (Button.ENTER.isDown()) {
                // Stop all motors on output A and toggle output B.
                LCD.drawString("Float A, Tog B", 0, 1);
                for (int i = 0; i < 4; i++) {
                    pfIRLink.sendPFExtended(i, NewIRLink.PF_EM_COMMAND_BRAKEFLOAT_OUTPUT_A);
                    pfIRLink.sendPFExtended(i, NewIRLink.PF_EM_COMMAND_TOGGLEFORWARDFLOAT_OUTPUT_B);
                }
            }

            if (Button.RIGHT.isDown()) {
                // PWM: Increase speed on all motors on output A.
                LCD.drawString("Incr A        ", 0, 1);
                for (int i = 0; i < 4; i++) {
                    pfIRLink.sendPFExtended(i, NewIRLink.PF_EM_COMMAND_INCREMENTSPEED_OUTPUT_A);

                    // Wait some time between each channel.
                    Delay.msDelay(100);
                }
            }

            if (Button.LEFT.isDown()) {
                // PWM: Decrease speed on all motors on output A and toggle output B.
                LCD.drawString("Decr A, Tog B ", 0, 1);
                for (int i = 0; i < 4; i++) {
                    pfIRLink.sendPFExtended(i, NewIRLink.PF_EM_COMMAND_DECREMENTSPEED_OUTPUT_A);
                    pfIRLink.sendPFExtended(i, NewIRLink.PF_EM_COMMAND_TOGGLEFORWARDFLOAT_OUTPUT_B);

                    // Wait some time between each channel.
                    Delay.msDelay(100);
                }
            }
        }
    }
}


text:
using Content.Shared.Actions;
using Robust.Shared.GameStates;
using Robust.Shared.Serialization;
using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype;

namespace Content.Shared.VendingMachines
{
    [NetworkedComponent()]
    public abstract class SharedVendingMachineComponent : Component
    {
        /// <summary>
        /// PrototypeID for the vending machine's inventory, see <see cref="VendingMachineInventoryPrototype"/>
        /// </summary>
        [DataField("pack", customTypeSerializer: typeof(PrototypeIdSerializer<VendingMachineInventoryPrototype>))]
        public string PackPrototypeId = string.Empty;

        /// <summary>
        /// Used by the server to determine how long the vending machine stays in the "Deny" state.
        /// Used by the client to determine how long the deny animation should be played.
        /// </summary>
        [DataField("denyDelay")]
        public float DenyDelay = 2.0f;

        /// <summary>
        /// Used by the server to determine how long the vending machine stays in the "Eject" state.
        /// The selected item is dispensed afer this delay.
        /// Used by the client to determine how long the deny animation should be played.
        /// </summary>
        [DataField("ejectDelay")]
        public float EjectDelay = 1.2f;

        [ViewVariables]
        public Dictionary<string, VendingMachineInventoryEntry> Inventory = new();

        [ViewVariables]
        public Dictionary<string, VendingMachineInventoryEntry> EmaggedInventory = new();

        [ViewVariables]
        public Dictionary<string, VendingMachineInventoryEntry> ContrabandInventory = new();

        public bool Emagged;
        public bool Contraband;
    }

    [Serializable, NetSerializable]
    public sealed class VendingMachineInventoryEntry
    {
        [ViewVariables(VVAccess.ReadWrite)]
        public InventoryType Type;
        [ViewVariables(VVAccess.ReadWrite)]
        public string ID;
        [ViewVariables(VVAccess.ReadWrite)]
        public uint Amount;
        public VendingMachineInventoryEntry(InventoryType type, string id, uint amount)
        {
            Type = type;
            ID = id;
            Amount = amount;
        }
    }

    [Serializable, NetSerializable]
    public enum InventoryType : byte
    {
        Regular,
        Emagged,
        Contraband
    }

    [Serializable, NetSerializable]
    public enum VendingMachineVisuals
    {
        VisualState
    }

    [Serializable, NetSerializable]
    public enum VendingMachineVisualState
    {
        Normal,
        Off,
        Broken,
        Eject,
        Deny,
    }

    [Serializable, NetSerializable]
    public enum ContrabandWireKey : byte
    {
        StatusKey,
        TimeoutKey
    }

    [Serializable, NetSerializable]
    public enum EjectWireKey : byte
    {
        StatusKey,
    }

    public sealed class VendingMachineSelfDispenseEvent : InstantActionEvent { };
}


text:
extern const struct luaL_Reg CvNArrayIterator_m[];
#endif


text:
import datetime
import logging
from re import match as re_match

from sqlalchemy import text

from rdr_service.dao.bigquery_sync_dao import BigQuerySyncDao, BigQueryGenerator
from rdr_service.model.bq_base import BQRecord, BQFieldTypeEnum
from rdr_service.model.bq_questionnaires import PDR_CODE_TO_MODULE_LIST
from rdr_service.code_constants import PPI_SYSTEM, PMI_SKIP_CODE
from rdr_service.participant_enums import QuestionnaireResponseStatus, TEST_HPO_NAME

class BQPDRQuestionnaireResponseGenerator(BigQueryGenerator):
    """
    Generate a questionnaire module response BQRecord
    """
    ro_dao = None

    def make_bqrecord(self, p_id, module_id, latest=False, convert_to_enum=False):
        """
        Generate a list of questionnaire module BQRecords for the given participant id.
        :param p_id: participant id
        :param module_id: A questionnaire module id, IE: 'TheBasics'.  Note that the code table can have multiple
                          entries that match this value, so we automatically filter on the system (PPI_SYSTEM) as well
        :param latest: only process the most recent response if True
        :param convert_to_enum: If schema field description includes Enum class info, convert value to Enum.
        :return: BQTable object, List of BQRecord objects
        """

        # Query to get all the question codes across all questionnaire versions of the module.
        _question_code_sql = """
            select c.value
            from code c
            inner join (
                select distinct qq.code_id
                from questionnaire_question qq where qq.questionnaire_id in (
                    select qc.questionnaire_id from questionnaire_concept qc
                            where qc.code_id = (
                                select code_id from code c2 where c2.value = :module_id and c2.system = :system
                            )
                )
            ) qq2 on qq2.code_id = c.code_id
            order by c.code_id;
        """

        # Query to get a list of questionnaire_response_id values for this participant and module
        # The list will be from most recently received/replayed response to earliest.  This mirrors how the
        # deprecated stored procedure sp_get_questionnaire_answers used to order its results
        #
        # PDR-254:  Updating the module response data to include a test_participant flag as a common field
        # Intended to make filtering module response data by test_participant status more efficient in BigQuery
        _participant_module_responses_sql = """
            select qr.questionnaire_id, qr.questionnaire_response_id, qr.created, qr.authored, qr.language,
                   qr.participant_id, qh2.external_id, qr.status,
                   CASE
                       WHEN p.is_test_participant = 1  or p.is_ghost_id = 1 or h.name = :test_hpo THEN 1
                       ELSE 0
                   END as test_participant
            from questionnaire_response qr
            inner join questionnaire_history qh2 on qh2.questionnaire_id = qr.questionnaire_id
                       and qh2.version = qr.questionnaire_version
            inner join participant p on p.participant_id = qr.participant_id
            left join hpo h on p.hpo_id = h.hpo_id
            -- Screen out classification DUPLICATE (1) responses from the PDR data [PDR-640]
            where qr.participant_id = :p_id and qr.classification_type != 1 and qr.questionnaire_id IN (
                select q.questionnaire_id from questionnaire q
                inner join questionnaire_history qh on q.version = qh.version
                       and qh.questionnaire_id = q.questionnaire_id
                inner join questionnaire_concept qc on qc.questionnaire_id = q.questionnaire_id
                      and qc.questionnaire_version = qh.version
                inner join code c on c.code_id = qc.code_id
                where c.value = :module_id and c.system = :system
                order by qr.created DESC
            );
        """

        # Query to get questionnaire answers for a specific questionnaire_response_id (no ordering needed)
        _response_answers_sql = """
            SELECT qr.questionnaire_id,
               qq.code_id,
               (select c.value from code c where c.code_id = qq.code_id and c.system = :system) as code_name,
               COALESCE((SELECT c.value from code c where c.code_id = qra.value_code_id),
                        qra.value_integer, qra.value_decimal,
                        qra.value_boolean, qra.value_string, qra.value_system,
                        qra.value_uri, qra.value_date, qra.value_datetime) as answer
            FROM questionnaire_response qr
                     INNER JOIN questionnaire_response_answer qra
                                ON qra.questionnaire_response_id = qr.questionnaire_response_id
                     INNER JOIN questionnaire_question qq
                                ON qra.question_id = qq.questionnaire_question_id
            WHERE qr.questionnaire_response_id = :qr_id
                  and (qra.ignore is null or qra.ignore = 0)
        """

        if not self.ro_dao:
            self.ro_dao = BigQuerySyncDao(backup=True)

        table = PDR_CODE_TO_MODULE_LIST.get(module_id, None)
        if table is None:
            logging.info('Generator: ignoring questionnaire module id [{0}].'.format(module_id))
            return None, list()

        # This section refactors how the module answer data is built, replacing  the sp_get_questionnaire_answers
        # stored procedure.  That procedure's logic was no longer consistent with how codebook structures are defined
        # in the new REDCap-managed DRC process.  TODO: tech debt for PDR PostgreSQL to consider changes to the
        #  code table so we can more robustly handle the codebook definitions we get from REDCap
        with self.ro_dao.session() as session:
            question_codes = session.execute(_question_code_sql, {'module_id': module_id, 'system': PPI_SYSTEM})

            # Retrieve all the responses for this participant/module ID (most recent first)
            qnans = []
            responses = session.execute(_participant_module_responses_sql, {'module_id': module_id, 'p_id': p_id,
                                                                            'test_hpo': TEST_HPO_NAME,
                                                                            'system': PPI_SYSTEM})
            for qr in responses:
                # Populate the response metadata (created, authored, etc.) into a data dict
                data = self.ro_dao.to_dict(qr, result_proxy=responses)
                # PDR-235:  Adding response FHIR status enum values (IN_PROGRESS, COMPLETED, ...)  to the metadata
                # dict.  Providing both string and integer key/value pairs, per the PDR BigQuery schema conventions
                if isinstance(data['status'], int):
                    data['status_id'] = int(QuestionnaireResponseStatus(data['status']))
                    data['status'] = str(QuestionnaireResponseStatus(data['status']))

                answers = session.execute(_response_answers_sql, {'qr_id': qr.questionnaire_response_id,
                                                                  'system': PPI_SYSTEM})
                ans_dict = {qc.value: None for qc in question_codes}
                for ans in answers:
                    # Note: BigQuery will ignore unrecognized fields, but log potentially new content for debugging
                    # purposes
                    if ans.code_name not in ans_dict.keys():
                        logging.debug("""questionnaireResponseID {0} contains previously unrecognized answer code {1}
                                for module {2}
                            """.format(qr.questionnaire_response_id, ans.code_name, module_id))

                    # Handle multi-select question codes (such as ethnicity or gender identity response options) where
                    # user provided more than one answer and concatenate into comma-separated list.  This mirrors
                    # GROUP_CONCAT SQL logic from the deprecated sp_get_questionnaire_answers proc
                    if ans.code_name in ans_dict.keys() and ans_dict[ans.code_name]:
                        # If answer value coalesced to null, skip those (found during testing in lower environments)
                        if ans.answer:
                            prev_answer = ans_dict[ans.code_name]
                            ans_dict[ans.code_name] = ",".join([prev_answer, ans.answer])
                    else:
                        ans_dict[ans.code_name] = ans.answer

                # Merge all the answers from this response payload with the response metadata and save
                data.update(ans_dict)
                qnans.append(data)

            if len(qnans) == 0:
                return None, list()

            bqrs = list()
            for qnan in qnans:
                bqr = BQRecord(schema=table().get_schema(), data=qnan, convert_to_enum=convert_to_enum)
                bqr.participant_id = p_id  # reset participant_id.

                fields = bqr.get_fields()
                for field in fields:
                    fld_name = field['name']
                    if fld_name in (
                        'id',
                        'created',
                        'modified',
                        'authored',
                        'language',
                        'participant_id',
                        'questionnaire_response_id',
                        'questionnaire_id',
                        'external_id',
                        'status',
                        'status_id'
                    ):
                        continue

                    fld_value = getattr(bqr, fld_name, None)
                    # Check to see if the field has been forced to boolean and set the default.
                    if field['type'] == BQFieldTypeEnum.INTEGER.name:
                        setattr(bqr, fld_name, 0)
                    if fld_value is None:
                        continue
                    # question responses values need to be coerced to a String type.
                    if isinstance(fld_value, (datetime.date, datetime.datetime)):
                        setattr(bqr, fld_name, fld_value.isoformat())
                    # Check to see if the field has been forced to boolean, set to 1 because we have a value.
                    elif field['type'] == BQFieldTypeEnum.INTEGER.name:
                        if fld_value != PMI_SKIP_CODE:
                            setattr(bqr, fld_name, 1)
                    # Truncate zip code fields to 3 chars (PDR fields are strings), provided the field
                    # has a digit as its first non-whitespace char.  This does NOT try to discover all possible
                    # invalid zipcode string conditions before truncating, but ensures coded values like PMI_Skip
                    # don't get truncated
                    elif fld_name in ('StreetAddress_PIIZIP', 'EmploymentWorkAddress_ZipCode') and \
                           len(fld_value.lstrip()) > 2 and re_match(r'^\s*\d+', fld_value):
                        setattr(bqr, fld_name, fld_value.lstrip()[:3])
                    else:
                        setattr(bqr, fld_name, str(fld_value))

                bqrs.append(bqr)
                if latest:
                    break

        return table, bqrs

def bq_questionnaire_update_task(p_id, qr_id):
    """
    Cloud Task: Generate a BQ questionnaire response record from the given p_id and questionnaire response id.
    :param p_id: participant id
    :param qr_id: A questionnaire response id.
    """
    # determine what the module id is for the given questionnaire response id.
    sql = text("""
    select c.value from
        questionnaire_response qr inner join questionnaire_concept qc on qr.questionnaire_id = qc.questionnaire_id
        inner join code c on qc.code_id = c.code_id and c.system = :system
    where qr.questionnaire_response_id = :qr_id
  """)

    ro_dao = BigQuerySyncDao(backup=True)
    w_dao = BigQuerySyncDao()
    qr_gen = BQPDRQuestionnaireResponseGenerator()
    module_id = None

    with ro_dao.session() as ro_session:

        results = ro_session.execute(sql, {'qr_id': qr_id, 'system': PPI_SYSTEM})
        if results:
            for row in results:
                module_id = row.value
                break

            if not module_id:
                logging.warning(f'No questionnaire module id found for questionnaire response id {qr_id}')
                return

            table, bqrs = qr_gen.make_bqrecord(p_id, module_id, latest=True)
            with w_dao.session() as w_session:
                for bqr in bqrs:
                    qr_gen.save_bqrecord(qr_id, bqr, bqtable=table, w_dao=w_dao, w_session=w_session)


text:
PostallyAddressable lets you add postal addresses to your models. The postal addresses are all saved in one place using polymorphism, so you don't have to create additional columns when tracking a new model's address. You can also save the latitude, longitude, and time zone to the postal address if your application requires that information.

## Todo

 * Documentation
 * Tests (for 'has_postal_address models')

## Compatibility

Works with `ActiveRecord` 3+.

## Installation

### Rails 3 & 4

1. Add PostallyAddressable to your `Gemfile`.

    `gem 'postally_addressable', :git => 'git://github.com/mariusz360/postally_addressable.git'`

2. Generate a migration which will add a `postal_addresses` table to your database.

    `bundle exec rails generate postally_addressable:install`

3. Run the migration.

    `bundle exec rake db:migrate`

4. Add `has_postal_address` to your models.

## Usage

```ruby
class User < ActiveRecord::Base
  has_postal_address
end
```

```ruby
>> user = User.new         # initializes user, then initializes postal address
>> user.postal_address     # #<PostalAddress id: nil, ...>

>> # Set the user's address
>> user.address_line_1 = "123 Mission St"

>> # Set the user's apt/suite/building
>> user.address_line_2 = "Apt 2"

>> # Set the user's locality
>> user.locality = "San Francisco"

>> # you can use 'city' instead of 'locality'
>> user.city               # "San Francisco"

>> # 'state' and 'province' mean the same thing
>> user.state = "California"
>> user.province           # "California"

>> # set the postal code
>> user.postal_code = "94105"

>> # check that an attribute isn't empty
>> user.country?           # false
>> user.country = "USA"
>> user.country?           # true

>> # saving the time zone is sometimes very useful
>> user.time_zone_name = "Pacific Time (US & Canada)"

>> # save user
>> user.save               # autosaves postal address
>> user.postal_address.id  # 1

>> # get the user's complete mailing address
>> user.mailing_address    # "123 Mission St Apt 2, San Francisco California 94105, USA"

>> # if you need the geocoordinates, you can save them to the postal address as well
>> geocoded_result = Geocoder.search(user.mailing_address).first
>> user.update(latitude: geocoded_result.latitude, longitude: geocoded_result.latitude)
```

### Caveats

 * The postal address attributes available in the postally addressable object behave as methods. Therefore, `obj.as_json(only: :address_line_1)` would return an empty hash. Instead, do `obj.as_json(methods: :address_line_1)`.
 * `has_postal_address` adds a default scope to the postally addressable model to eager load the postal addresses. This can be turned off by passing `eager_load: false` to `has_postal_address`.


text:
package com.vmware.vim25;

/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/

public enum HostGraphicsInfoGraphicsType {
  basic ("basic"),
  shared ("shared"),
  direct ("direct");

  @SuppressWarnings("unused")
  private final String val;
  private HostGraphicsInfoGraphicsType(String val)
  {
    this.val = val;
  }
}


text:
from __future__ import print_function

import json
import os
import urllib
import boto3
import hashlib

s3 = boto3.client('s3')

BUF_SIZE=4096

def hash_stream(stream, hfunc):
    while True:
        data = stream.read(BUF_SIZE)
        if not data:
            break
        hfunc.update(data)
    return hfunc.hexdigest()

def hashFile(event, context):
    bucket = event['Records'][0]['s3']['bucket']['name']
    key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key'].encode('utf8'))
    print("File: %s:%s" % (bucket, key))
    if key.endswith(".sha1"):
        print("Nothing to do")
        return

    try:
        response = s3.get_object(Bucket=bucket, Key=key)
        sha1 = hash_stream(response['Body'],hashlib.sha1())
        print("SHA1: " + sha1)
        newkey = key+".sha1"
        print(newkey)
        response = s3.put_object(Bucket=bucket,Key=newkey, Body=sha1)
        return sha1
    except Exception as e:
        print(e)
        print('Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket))
        raise e


text:
"""
Volume driver for Zadara Virtual Private Storage Array (VPSA).

This driver requires VPSA with API ver.12.06 or higher.
"""

import httplib

from cinder import exception
from cinder import flags
from cinder.openstack.common import log as logging
from cinder.openstack.common import cfg
from cinder import utils
from cinder.volume import driver
from cinder.volume import iscsi

from lxml import etree

LOG = logging.getLogger("cinder.volume.driver")

zadara_opts = [
    cfg.StrOpt('zadara_vpsa_ip',
               default=None,
               help='Management IP of Zadara VPSA'),
    cfg.StrOpt('zadara_vpsa_port',
               default=None,
               help='Zadara VPSA port number'),
    cfg.BoolOpt('zadara_vpsa_use_ssl',
               default=False,
               help='Use SSL connection'),
    cfg.StrOpt('zadara_user',
               default=None,
               help='User name for the VPSA'),
    cfg.StrOpt('zadara_password',
               default=None,
               help='Password for the VPSA'),

    cfg.StrOpt('zadara_vpsa_poolname',
               default=None,
               help='Name of VPSA storage pool for volumes'),

    cfg.StrOpt('zadara_default_cache_policy',
               default='write-through',
               help='Default cache policy for volumes'),
    cfg.StrOpt('zadara_default_encryption',
               default='NO',
               help='Default encryption policy for volumes'),
    cfg.StrOpt('zadara_default_striping_mode',
               default='simple',
               help='Default striping mode for volumes'),
    cfg.StrOpt('zadara_default_stripesize',
               default='64',
               help='Default stripe size for volumes'),
    cfg.StrOpt('zadara_vol_name_template',
               default='OS_%s',
               help='Default template for VPSA volume names'),
    cfg.BoolOpt('zadara_vpsa_auto_detach_on_delete',
               default=True,
               help="Automatically detach from servers on volume delete"),
    cfg.BoolOpt('zadara_vpsa_allow_nonexistent_delete',
               default=True,
               help="Don't halt on deletion of non-existing volumes"),
    ]

FLAGS = flags.FLAGS
FLAGS.register_opts(zadara_opts)

class ZadaraVPSAConnection(object):
    """Executes volume driver commands on VPSA."""

    def __init__(self, host, port, ssl, user, password):
        self.host = host
        self.port = port
        self.use_ssl = ssl
        self.user = user
        self.password = password
        self.access_key = None

        self.ensure_connection()

    def _generate_vpsa_cmd(self, cmd, **kwargs):
        """Generate command to be sent to VPSA."""

        def _joined_params(params):
            param_str = []
            for k, v in params.items():
                param_str.append("%s=%s" % (k, v))
            return '&'.join(param_str)

        # Dictionary of applicable VPSA commands in the following format:
        # 'command': (method, API_URL, {optional parameters})
        vpsa_commands = {
            'login': ('POST',
                      '/api/users/login.xml',
                      {'user': self.user,
                       'password': self.password}),

            # Volume operations
            'create_volume': ('POST',
                              '/api/volumes.xml',
                              {'display_name': kwargs.get('name'),
                               'virtual_capacity': kwargs.get('size'),
                               'raid_group_name[]': FLAGS.zadara_vpsa_poolname,
                               'quantity': 1,
                               'cache': FLAGS.zadara_default_cache_policy,
                               'crypt': FLAGS.zadara_default_encryption,
                               'mode': FLAGS.zadara_default_striping_mode,
                               'stripesize': FLAGS.zadara_default_stripesize,
                               'force': 'NO'}),
            'delete_volume': ('DELETE',
                              '/api/volumes/%s.xml' % kwargs.get('vpsa_vol'),
                              {}),

            # Server operations
            'create_server': ('POST',
                              '/api/servers.xml',
                              {'display_name': kwargs.get('initiator'),
                               'iqn': kwargs.get('initiator')}),

            # Attach/Detach operations
            'attach_volume': ('POST',
                              '/api/servers/%s/volumes.xml'
                                    % kwargs.get('vpsa_srv'),
                              {'volume_name[]': kwargs.get('vpsa_vol'),
                               'force': 'NO'}),
            'detach_volume': ('POST',
                              '/api/volumes/%s/detach.xml'
                                    % kwargs.get('vpsa_vol'),
                              {'server_name[]': kwargs.get('vpsa_srv'),
                               'force': 'NO'}),

            # Get operations
            'list_volumes': ('GET',
                             '/api/volumes.xml',
                             {}),
            'list_controllers': ('GET',
                                 '/api/vcontrollers.xml',
                                 {}),
            'list_servers': ('GET',
                             '/api/servers.xml',
                             {}),
            'list_vol_attachments': ('GET',
                                     '/api/volumes/%s/servers.xml'
                                            % kwargs.get('vpsa_vol'),
                                     {}),
            }

        if cmd not in vpsa_commands.keys():
            raise exception.UnknownCmd(cmd=cmd)
        else:
            (method, url, params) = vpsa_commands[cmd]

        if method == 'GET':
            # For GET commands add parameters to the URL
            params.update(dict(access_key=self.access_key,
                               page=1, start=0, limit=0))
            url += '?' + _joined_params(params)
            body = ''

        elif method == 'DELETE':
            # For DELETE commands add parameters to the URL
            params.update(dict(access_key=self.access_key))
            url += '?' + _joined_params(params)
            body = ''

        elif method == 'POST':
            if self.access_key:
                params.update(dict(access_key=self.access_key))
            body = _joined_params(params)

        else:
            raise exception.UnknownCmd(cmd=method)

        return (method, url, body)

    def ensure_connection(self, cmd=None):
        """Retrieve access key for VPSA connection."""

        if self.access_key or cmd == 'login':
            return

        cmd = 'login'
        xml_tree = self.send_cmd(cmd)
        user = xml_tree.find('user')
        if user is None:
            raise exception.MalformedResponse(cmd=cmd,
                                        reason='no "user" field')

        access_key = user.findtext('access-key')
        if access_key is None:
            raise exception.MalformedResponse(cmd=cmd,
                                        reason='no "access-key" field')

        self.access_key = access_key

    def send_cmd(self, cmd, **kwargs):
        """Send command to VPSA Controller."""

        self.ensure_connection(cmd)

        (method, url, body) = self._generate_vpsa_cmd(cmd, **kwargs)
        LOG.debug(_('Sending %(method)s to %(url)s. Body "%(body)s"')
                        % locals())

        if self.use_ssl:
            connection = httplib.HTTPSConnection(self.host, self.port)
        else:
            connection = httplib.HTTPConnection(self.host, self.port)
        connection.request(method, url, body)
        response = connection.getresponse()

        if response.status != 200:
            connection.close()
            raise exception.BadHTTPResponseStatus(status=response.status)
        data = response.read()
        connection.close()

        xml_tree = etree.fromstring(data)
        status = xml_tree.findtext('status')
        if status != '0':
            raise exception.FailedCmdWithDump(status=status, data=data)

        if method in ['POST', 'DELETE']:
            LOG.debug(_('Operation completed. %(data)s') % locals())
        return xml_tree

class ZadaraVPSAISCSIDriver(driver.ISCSIDriver):
    """Zadara VPSA iSCSI volume driver."""

    def __init__(self, *args, **kwargs):
        super(ZadaraVPSAISCSIDriver, self).__init__(*args, **kwargs)

    def do_setup(self, context):
        """
        Any initialization the volume driver does while starting.
        Establishes initial connection with VPSA and retrieves access_key.
        """
        self.vpsa = ZadaraVPSAConnection(FLAGS.zadara_vpsa_ip,
                                         FLAGS.zadara_vpsa_port,
                                         FLAGS.zadara_vpsa_use_ssl,
                                         FLAGS.zadara_user,
                                         FLAGS.zadara_password)

    def check_for_setup_error(self):
        """Returns an error (exception) if prerequisites aren't met."""
        self.vpsa.ensure_connection()

    def local_path(self, volume):
        """Return local path to existing local volume."""
        LOG.error(_("Call to local_path should not happen."
                    " Verify that use_local_volumes flag is turned off."))
        raise NotImplementedError()

    def _xml_parse_helper(self, xml_tree, first_level, search_tuple,
                          first=True):
        """
        Helper for parsing VPSA's XML output.

        Returns single item if first==True or list for multiple selection.
        If second argument in search_tuple is None - returns all items with
        appropriate key.
        """

        objects = xml_tree.find(first_level)
        if objects is None:
            return None

        result_list = []
        (key, value) = search_tuple
        for object in objects.getchildren():
            found_value = object.findtext(key)
            if found_value and (found_value == value or value is None):
                if first:
                    return object
                else:
                    result_list.append(object)
        return result_list if result_list else None

    def _get_vpsa_volume_name(self, name):
        """Return VPSA's name for the volume."""
        xml_tree = self.vpsa.send_cmd('list_volumes')
        volume = self._xml_parse_helper(xml_tree, 'volumes',
                                        ('display-name', name))
        if volume is not None:
            return volume.findtext('name')

        return None

    def _get_active_controller_details(self):
        """Return details of VPSA's active controller."""
        xml_tree = self.vpsa.send_cmd('list_controllers')
        ctrl = self._xml_parse_helper(xml_tree, 'vcontrollers',
                                        ('state', 'active'))
        if ctrl is not None:
            return dict(target=ctrl.findtext('target'),
                        ip=ctrl.findtext('iscsi-ip'),
                        chap_user=ctrl.findtext('chap-username'),
                        chap_passwd=ctrl.findtext('chap-target-secret'))
        return None

    def _get_server_name(self, initiator):
        """Return VPSA's name for server object with given IQN."""
        xml_tree = self.vpsa.send_cmd('list_servers')
        server = self._xml_parse_helper(xml_tree, 'servers',
                                        ('iqn', initiator))
        if server is not None:
            return server.findtext('name')
        return None

    def _create_vpsa_server(self, initiator):
        """Create server object within VPSA (if doesn't exist)."""
        vpsa_srv = self._get_server_name(initiator)
        if not vpsa_srv:
            xml_tree = self.vpsa.send_cmd('create_server', initiator=initiator)
            vpsa_srv = xml_tree.findtext('server-name')
        return vpsa_srv

    def create_volume(self, volume):
        """Create volume."""
        self.vpsa.send_cmd('create_volume',
                    name=FLAGS.zadara_vol_name_template % volume['name'],
                    size=volume['size'])

    def delete_volume(self, volume):
        """
        Delete volume.

        Return ok if doesn't exist. Auto detach from all servers.
        """
        # Get volume name
        name = FLAGS.zadara_vol_name_template % volume['name']
        vpsa_vol = self._get_vpsa_volume_name(name)
        if not vpsa_vol:
            msg = _('Volume %(name)s could not be found. '
                'It might be already deleted') % locals()
            LOG.warning(msg)
            if FLAGS.zadara_vpsa_allow_nonexistent_delete:
                return
            else:
                raise exception.VolumeNotFound(volume_id=name)

        # Check attachment info and detach from all
        xml_tree = self.vpsa.send_cmd('list_vol_attachments',
                                      vpsa_vol=vpsa_vol)
        servers = self._xml_parse_helper(xml_tree, 'servers',
                                ('iqn', None), first=False)
        if servers:
            if not FLAGS.zadara_vpsa_auto_detach_on_delete:
                raise exception.VolumeAttached(volume_id=name)

            for server in servers:
                vpsa_srv = server.findtext('name')
                if vpsa_srv:
                    self.vpsa.send_cmd('detach_volume',
                                vpsa_srv=vpsa_srv, vpsa_vol=vpsa_vol)

        # Delete volume
        self.vpsa.send_cmd('delete_volume', vpsa_vol=vpsa_vol)

    def create_export(self, context, volume):
        """Irrelevant for VPSA volumes. Export created during attachment."""
        pass

    def ensure_export(self, context, volume):
        """Irrelevant for VPSA volumes. Export created during attachment."""
        pass

    def remove_export(self, context, volume):
        """Irrelevant for VPSA volumes. Export removed during detach."""
        pass

    def initialize_connection(self, volume, connector):
        """
        Attach volume to initiator/host.

        During this call VPSA exposes volume to particular Initiator. It also
        creates a 'server' entity for Initiator (if it was not created before)

        All necessary connection information is returned, including auth data.
        Connection data (target, LUN) is not stored in the DB.
        """

        # Get/Create server name for IQN
        initiator_name = connector['initiator']
        vpsa_srv = self._create_vpsa_server(initiator_name)
        if not vpsa_srv:
            raise exception.ZadaraServerCreateFailure(name=initiator_name)

        # Get volume name
        name = FLAGS.zadara_vol_name_template % volume['name']
        vpsa_vol = self._get_vpsa_volume_name(name)
        if not vpsa_vol:
            raise exception.VolumeNotFound(volume_id=name)

        # Get Active controller details
        ctrl = self._get_active_controller_details()
        if not ctrl:
            raise exception.ZadaraVPSANoActiveController()

        # Attach volume to server
        self.vpsa.send_cmd('attach_volume',
                            vpsa_srv=vpsa_srv, vpsa_vol=vpsa_vol)

        # Get connection info
        xml_tree = self.vpsa.send_cmd('list_vol_attachments',
                                      vpsa_vol=vpsa_vol)
        server = self._xml_parse_helper(xml_tree, 'servers',
                                        ('iqn', initiator_name))
        if server is None:
            raise exception.ZadaraAttachmentsNotFound(name=name)
        target = server.findtext('target')
        lun = server.findtext('lun')
        if target is None or lun is None:
            raise exception.ZadaraInvalidAttachmentInfo(name=name,
                            reason='target=%s, lun=%s' % (target, lun))

        properties = {}
        properties['target_discovered'] = False
        properties['target_portal'] = '%s:%s' % (ctrl['ip'], '3260')
        properties['target_iqn'] = target
        properties['target_lun'] = lun
        properties['volume_id'] = volume['id']

        properties['auth_method'] = 'CHAP'
        properties['auth_username'] = ctrl['chap_user']
        properties['auth_password'] = ctrl['chap_passwd']

        LOG.debug(_('Attach properties: %(properties)s') % locals())
        return {'driver_volume_type': 'iscsi',
                'data': properties}

    def terminate_connection(self, volume, connector):
        """
        Detach volume from the initiator.
        """
        # Get server name for IQN
        initiator_name = connector['initiator']
        vpsa_srv = self._get_server_name(initiator_name)
        if not vpsa_srv:
            raise exception.ZadaraServerNotFound(name=initiator_name)

        # Get volume name
        name = FLAGS.zadara_vol_name_template % volume['name']
        vpsa_vol = self._get_vpsa_volume_name(name)
        if not vpsa_vol:
            raise exception.VolumeNotFound(volume_id=name)

        # Detach volume from server
        self.vpsa.send_cmd('detach_volume',
                            vpsa_srv=vpsa_srv, vpsa_vol=vpsa_vol)

    def create_volume_from_snapshot(self, volume, snapshot):
        raise NotImplementedError()

    def create_snapshot(self, snapshot):
        raise NotImplementedError()

    def delete_snapshot(self, snapshot):
        raise NotImplementedError()


text:
<?php

require_once(__DIR__ . "/../model/config.php");

$query = $_SESSION["connection"]->query("CREATE TABLE posts ("
        . "id int (11) NOT NULL AUTO_INCREMENT,"
        . "title varchar(255) NOT NULL,"
        . "post text NOT NULL,"
        . "PRIMARY KEY (id))");

if ($query) {
    echo "
Succesfully created table: posts
";
} else {
    echo "
" . $_SESSION["connection"]->error . "
";
}

$query = $_SESSION["connection"]->query("CREATE TABLE users("
        . "id int(11) NOT NULL AUTO_INCREMENT,"
        . "username varchar(30) NOT NULL,"
        . "email varchar(50) NOT NULL,"
        . "password char(128) NOT NULL,"
        . "salt char(128) NOT NULL,"
        . "PRIMARY KEY (id))");

if ($query) {
    echo "
Succesfully created table: users
";
} else {
    echo "
" . $_SESSION["connection"]->error . "
";
}


text:
set -e

diffs=`git diff --cached --name-only --diff-filter=ACMTUXB editor.user.js editor.meta.js version spelling-corrections.txt content-free-words.txt example-domain-words.txt file-extensions.txt top-level-domains.txt`
if [ "z$diffs" != "z" ]
then
	echo "Local changes detected, commit changes before bumping version"
	exit 0
fi

diffs=`git diff --cached --name-only --diff-filter=ACMTUXB origin editor.user.js spelling-corrections.txt content-free-words.txt example-domain-words.txt file-extensions.txt top-level-domains.txt`
if [ "z$diffs" == "z" ]
then
	echo "No changes compared to origin, version does not need to be bumped"
	exit 0
fi

version=`cat version`
newversion=`semver -i "$1" $version`
echo "Old version: $version"
echo "New version: $newversion"
echo $newversion > version
sed -E -i "s|^// \@version .*|// @version $newversion|g" editor.user.js
awk '/^\/\/ ==UserScript==$/,/^\/\/ ==\/UserScript==$/' editor.user.js > editor.meta.js
git commit -m "bump version" editor.user.js editor.meta.js version


text:
var allImg = document.getElementsByTagName("img"), i = 0, img;

var images = ["http://www.dogbreedinfo.com/images12/BorderCollie6yearsKaya.JPG",
    "http://www.dogbreedslist.info/uploads/allimg/dog-pictures/Border-Collie-3.jpg",
    "http://nextranks.com/data_images/dogs/border-collie/border-collie-05.jpg",
    "http://www.lockeyebc.com/images/spice_pup_pics/7wks/dollyrainbowwave1.jpg",
    "http://animalsbreeds.com/wp-content/uploads/2015/01/border-collie-10.jpg"];

while (img = allImg[i++]) {
    img.src = images[getRandomInt(0, images.length)];
}

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
}


text:
using System.Runtime.CompilerServices;

namespace System.Threading.WebWorkers {
	[Imported, NamedValues]
	public enum WorkerGlobalScopeEvents {
		Close,
		Error,
		Offline,
		Online
	}
}


text:
layout: documentation
title: Custom Rules
---

# Custom rules
Skylark is the name of the extension mechanism in Bazel. It lets you write
[custom build rules](rules.md) as well as compose existing ones into
[macros](macros.md).

## Getting started

Read the [concepts](concepts.md) behind Skylark and try the
[cookbook examples](cookbook.md). To go further, read about the
[standard library](lib/globals.html).


text:
layout: detail
key: giftlist
header:
    title: Gift List
---

We will be having two gift lists.

## Honeymoon

We are using Patchwork to accept contributions to our honeymoon. Check it out [**here**](http://patchworkit.com/hollyandandrew).

## John Lewis

The John Lewis gift list is now closed.


text:
package com.navercorp.pinpoint.collector.receiver.grpc.service;

import com.navercorp.pinpoint.collector.receiver.DispatchHandler;
import com.navercorp.pinpoint.grpc.MessageFormatUtils;
import com.navercorp.pinpoint.grpc.StatusError;
import com.navercorp.pinpoint.grpc.StatusErrors;
import com.navercorp.pinpoint.grpc.server.ServerContext;
import com.navercorp.pinpoint.grpc.trace.PSpan;
import com.navercorp.pinpoint.grpc.trace.PSpanChunk;
import com.navercorp.pinpoint.grpc.trace.PSpanMessage;
import com.navercorp.pinpoint.grpc.trace.SpanGrpc;
import com.navercorp.pinpoint.io.header.Header;
import com.navercorp.pinpoint.io.header.HeaderEntity;
import com.navercorp.pinpoint.io.header.v2.HeaderV2;
import com.navercorp.pinpoint.io.request.DefaultMessage;
import com.navercorp.pinpoint.io.request.Message;
import com.navercorp.pinpoint.io.request.ServerRequest;
import com.navercorp.pinpoint.thrift.io.DefaultTBaseLocator;

import com.google.protobuf.Empty;
import com.google.protobuf.GeneratedMessageV3;
import io.grpc.Status;
import io.grpc.StatusException;
import io.grpc.StatusRuntimeException;
import io.grpc.stub.StreamObserver;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;

import java.util.HashMap;
import java.util.Objects;

/**
 * @author jaehong.kim
 */
public class SpanService extends SpanGrpc.SpanImplBase {
    private final Logger logger = LogManager.getLogger(this.getClass());
    private final boolean isDebug = logger.isDebugEnabled();
    private final DispatchHandler<GeneratedMessageV3, GeneratedMessageV3> dispatchHandler;
    private final ServerRequestFactory serverRequestFactory;

    public SpanService(DispatchHandler<GeneratedMessageV3, GeneratedMessageV3> dispatchHandler, ServerRequestFactory serverRequestFactory) {
        this.dispatchHandler = Objects.requireNonNull(dispatchHandler, "dispatchHandler");
        this.serverRequestFactory = Objects.requireNonNull(serverRequestFactory, "serverRequestFactory");
    }

    @Override
    public StreamObserver<PSpanMessage> sendSpan(final StreamObserver<Empty> responseObserver) {
        StreamObserver<PSpanMessage> observer = new StreamObserver<PSpanMessage>() {
            @Override
            public void onNext(PSpanMessage spanMessage) {
                if (isDebug) {
                    logger.debug("Send PSpan={}", MessageFormatUtils.debugLog(spanMessage));
                }

                if (spanMessage.hasSpan()) {
                    final Message<PSpan> message = newMessage(spanMessage.getSpan(), DefaultTBaseLocator.SPAN);
                    send(message, responseObserver);
                } else if (spanMessage.hasSpanChunk()) {
                    final Message<PSpanChunk> message = newMessage(spanMessage.getSpanChunk(), DefaultTBaseLocator.SPANCHUNK);
                    send(message, responseObserver);
                } else {
                    if (isDebug) {
                        logger.debug("Found empty span message {}", MessageFormatUtils.debugLog(spanMessage));
                    }
                }
            }

            @Override
            public void onError(Throwable throwable) {
                com.navercorp.pinpoint.grpc.Header header = ServerContext.getAgentInfo();

                final StatusError statusError = StatusErrors.throwable(throwable);
                if (statusError.isSimpleError()) {
                    logger.info("Failed to span stream, {} cause={}", header, statusError.getMessage(), statusError.getThrowable());
                } else {
                    logger.warn("Failed to span stream, {} cause={}", header, statusError.getMessage(), statusError.getThrowable());
                }
            }

            @Override
            public void onCompleted() {
                com.navercorp.pinpoint.grpc.Header header = ServerContext.getAgentInfo();
                logger.info("onCompleted {}", header);

                Empty empty = Empty.newBuilder().build();
                responseObserver.onNext(empty);
                responseObserver.onCompleted();
            }
        };
        return observer;
    }

    private <T> Message<T> newMessage(T requestData, short serviceType) {
        final Header header = new HeaderV2(Header.SIGNATURE, HeaderV2.VERSION, serviceType);
        final HeaderEntity headerEntity = new HeaderEntity(new HashMap<>());
        return new DefaultMessage<>(header, headerEntity, requestData);
    }

    private void send(final Message<? extends GeneratedMessageV3> message, StreamObserver<Empty> responseObserver) {
        try {
            ServerRequest<GeneratedMessageV3> request = (ServerRequest<GeneratedMessageV3>) serverRequestFactory.newServerRequest(message);
            this.dispatchHandler.dispatchSendMessage(request);
        } catch (Exception e) {
            logger.warn("Failed to request. message={}", message, e);
            if (e instanceof StatusException || e instanceof StatusRuntimeException) {
                responseObserver.onError(e);
            } else {
                // Avoid detailed exception
                responseObserver.onError(Status.INTERNAL.withDescription("Bad Request").asException());
            }
        }
    }

}


text:
package net.technowizardry.xmpp;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

public class MemoryStream {
	private PipedInputStream toServerStream;
	private OutputStream outputStream;

	public MemoryStream() throws IOException {
		toServerStream = new PipedInputStream();
		outputStream = new PipedOutputStream(toServerStream);
	}

	public OutputStream getStream() {
		return outputStream;
	}

	public String readAll() throws IOException {
		int avail = toServerStream.available();
		byte[] buffer = new byte[avail];
		toServerStream.read(buffer);
		return new String(buffer);
	}
}


text:
from collections import Iterable
import collections
import sys

if sys.version_info.major > 2:
    basestring = str

def to_str(item):
    return bytearray.decode(item) if isinstance(item, bytearray) else str(item)

def listify(item, default=None, itemlen=0):
    """
    Convert C{item} to a list if it isn't one already

    @param item: thing to be converted to a list if it isn't already
    @type item: any

    @param default: default value if not supplied
    @type default: any

    @param itemlen: minimum number of elements to return.
    @type itemlen: int
    """
    if item is None:
        item = default
    if not isinstance(item, Iterable) or isinstance(item, basestring):
        item = [item]
    return list(item) + ([default] * max(itemlen - len(item), 0))

def isList(possible_list):
    return isinstance(possible_list, collections.Iterable) and not isinstance(possible_list, basestring)

def flatten(possible_list):
    """ Flatten a list by one level.

    >>> flatten(None)

    >>> flatten([])
    []

    >>> flatten([None])
    [None]

    >>> flatten("abc")
    'abc'

    >>> flatten([1,2,3])
    [1, 2, 3]

    >>> flatten([[1,2],[3,4,[5]]])
    [1, 2, 3, 4, [5]]

    @param possible_list: the list to be flattened.
    @return: flattening
    """
    def flatten_(pl):
        if isList(pl):
            for e in pl:
                if isList(e):
                    for e1 in e:
                        yield e1
                else:
                    yield e
        else:
            yield pl

    return list(flatten_(possible_list)) if isList(possible_list) else possible_list


text:
(function () {
    var app = angular.module("settings", [ "ngResource" ]);

    app.controller("settingsController", ["$scope", "settingsService", function ($scope, settingsService) {
        var vm = this;

        vm.newSettings = {};

        vm.items = [];

        settingsService.query(function (data) {
            vm.items = data.items;
        });

        vm.Save = function () {
            settingsService.save(vm.newSettings, function (data) {
                vm.items = data.items;
            });
        };

        vm.Delete = function (item) {
            settingsService.del({ name: item.name },
                function (data) {
                    vm.items = data.items;
                });
        };
    }]);

    app.factory("settingsService", ["$resource",
      function ($resource) {
          return $resource("/api/settings", {}, {
              query: { method: "GET", isArray: false, cache: false },
              del: { method: "DELETE" },
              save: { method: "POST" }
          });
      }]);

})();


text:
About Canvas
            General information and credits.

Canvas was born out of a desire for an elegant, well-architectured personal publishing platform built on Laravel that would be
           attractive to developers and non-developers alike. If you like using this application and feel like it has helped you in any way, share it, tweet about it, fork it and give it a star on GitHub.

                Star
                Fork
                Follow @austintoddj

Code released under the MIT License

Coded by Todd Austin and an awesome group of contributors

UI/UX based on Google Material Design · Powered by the Laravel Framework

                Releases ·
                Changelog ·
                GitHub ·
                Packagist ·
                Issues


text:
/* Right to Left */
@keyframes placeHolderShimmer {
  0% {
    background-position: -868px 0;
  }
  100% {
    background-position: 868px 0;
  }
}
.ellipsis:before {
  float: right;
}
.ellipsis > *:first-child {
  float: left;
  margin-left: auto;
  margin-right: -5px;
}
.ellipsis:after {
  float: left;
  left: auto;
  right: 100%;
  padding-left: 5px;
  padding-right: 0;
  margin-left: 0;
  margin-right: -3em;
  text-align: left;
  background: -webkit-gradient(linear, right top, left top, from(rgba(255, 255, 255, 0)), to(white), color-stop(50%, white));
  background: -moz-linear-gradient(to left, rgba(255, 255, 255, 0), white 50%, white);
  background: -o-linear-gradient(to left, rgba(255, 255, 255, 0), white 50%, white);
  background: -ms-linear-gradient(to left, rgba(255, 255, 255, 0), white 50%, white);
  background: linear-gradient(to left, rgba(255, 255, 255, 0), white 50%, white);
}
.dataobject-page .dataobject-tabs .nav {
  float: left;
  font-size: 0;
}
.dataobject-page .dataobject-tabs .nav li {
  font-size: 17px;
  margin: 0 3px;
  /*float: right;*/
}
.dataobject-page .dataobject-tabs .nav li:first-child {
  margin-left: 3px;
  margin-right: 15px;
}
.dataobject-page .dataobject-tabs .nav li:last-child {
  margin-left: 15px;
  margin-right: 3px;
}
.dataobject-page .dataobject-tabs .tab-content {
  float: right;
}
.dataobject-page .dataobject-item .card .caption {
  left: auto;
  right: 0;
}
.dataobject-page .dataobject-related.dataobject-item > div .content {
  padding-left: 0;
  padding-right: 6px;
}
.dataobject-page .dataobject-header .dataobject-card .dataobject-brief {
  text-align: right;
  /*margin-left: auto;*/
  /*margin-right: (@dataobject-picture-size + 8px);*/
  padding-left: 0;
  padding-right: 168px;
}
.dataobject-page .dataobject-header .dataobject-card.card-form {
  text-align: right;
}
.dataobject-page .dataobject-header .dataobject-card.card-form .ss-uploadfield .ss-uploadfield-item .ss-uploadfield-item-preview {
  float: right;
}
.dataobject-page .dataobject-header .dataobject-card.card-form .ss-uploadfield .ss-uploadfield-item .ss-uploadfield-item-info {
  margin-left: auto;
  margin-right: 180px;
  text-align: right;
}
.dataobject-page .dataobject-header .dataobject-card.card-form .ss-uploadfield .ss-uploadfield-item .ss-uploadfield-item-info .ss-uploadfield-item-name {
  text-align: right;
}
.dataobject-page .dataobject-header .dataobject-card.card-form .ss-uploadfield .ss-uploadfield-item .ss-uploadfield-item-info .ss-uploadfield-item-name * {
  float: right;
}
.dataobject-page .dataobject-header .dataobject-card.card-form .ss-uploadfield .ss-uploadfield-item .ss-uploadfield-item-info .ss-uploadfield-item-name .size {
  padding: 0 5px 0 0;
}
.dataobject-page .dataobject-header .dataobject-card.card-form .ss-uploadfield .ss-uploadfield-item .ss-uploadfield-item-info .ss-uploadfield-item-actions button {
  float: right;
}
.dataobject-page .dataobject-header .dataobject-card.card-form .ss-uploadfield .ss-ui-button {
  margin: 0 0 6px 10px;
}
.dataobject-page .dataobject-header .dataobject-card.card-form .Actions .form-group {
  float: right;
  margin: 0 0 0 5px;
}
.modal {
  text-align: right;
}
.modal a.close-modal {
  left: 8px;
  right: auto;
}
/* Small (Landscape phone to portrait tablet) */
@media (max-width: 767px) {
  .dataobject-page .dataobject-item > div .content {
    padding-left: 0;
    padding-right: 6px;
  }
  .dataobject-page .dataobject-header .dataobject-card .dataobject-brief {
    display: block;
    /*margin: 12px auto;*/
    padding: 12px 0;
    text-align: center;
  }
  .dataobject-page .dataobject-header .dataobject-card .dataobject-brief .dataobject-info {
    text-align: right;
  }
  .dataobject-page .object-label.object-label-top-left {
    left: auto;
    right: -4px;
  }
  .dataobject-page .object-label.object-label-top-right {
    left: -4px;
    right: auto;
  }
  .dataobject-page .object-label.object-label-bottom-left {
    left: auto;
    right: -4px;
  }
  .dataobject-page .object-label.object-label-bottom-right {
    left: -4px;
    right: auto;
  }
}
/* X-Small (Landscape phones and down) */
@media (max-width: 480px) {
  .dataobject-page .dataobject-item > div .content {
    padding-left: 0;
    padding-right: 6px;
  }
  .dataobject-page .object-label.object-label-top-left {
    left: auto;
    right: -6px;
  }
  .dataobject-page .object-label.object-label-top-right {
    left: -6px;
    right: auto;
  }
  .dataobject-page .object-label.object-label-bottom-left {
    left: auto;
    right: -6px;
  }
  .dataobject-page .object-label.object-label-bottom-right {
    left: -6px;
    right: auto;
  }
  .blocker .modal .card-header {
    padding: 8px 8px 8px 20px;
  }
}
/*# sourceMappingURL=dataobject-rtl.css.map */


text:
class RemoveReceiverFromMessages < ActiveRecord::Migration
  def change
    remove_column :messages, :receiver_id, :integer
  end
end


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/**
 * @name: S11.8.2_A3.1_T1.2;
 * @section: 11.8.2;
 * @assertion: If Type(Primitive(x)) is not String or Type(Primitive(y)) is not String, then operator x > y returns ToNumber(x) > ToNumber(y);
 * @description: Type(Primitive(x)) and Type(Primitive(y)) vary between primitive number and Number object;
*/

//CHECK#1
if (1 > 1 !== false) {
  $ERROR('#1: 1 > 1 === false');
}

//CHECK#2
if (new Number(1) > 1 !== false) {
  $ERROR('#2: new Number(1) > 1 === false');
}

//CHECK#3
if (1 > new Number(1) !== false) {
  $ERROR('#3: 1 > new Number(1) === false');
}

//CHECK#4
if (new Number(1) > new Number(1) !== false) {
  $ERROR('#4: new Number(1) > new Number(1) === false');
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<title>Overview</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="EDoc">

Modules

tfloats


text:
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>

#include "xbps_api_impl.h"

static xbps_array_t
merge_filelist(xbps_dictionary_t d)
{
	xbps_array_t a, result;
	xbps_dictionary_t filed;
	unsigned int i;

	result = xbps_array_create();
	assert(result);

	if ((a = xbps_dictionary_get(d, "files"))) {
		for (i = 0; i < xbps_array_count(a); i++) {
			filed = xbps_array_get(a, i);
			xbps_array_add(result, filed);
		}
	}
	if ((a = xbps_dictionary_get(d, "links"))) {
		for (i = 0; i < xbps_array_count(a); i++) {
			filed = xbps_array_get(a, i);
			xbps_array_add(result, filed);
		}
	}
	if ((a = xbps_dictionary_get(d, "conf_files"))) {
		for (i = 0; i < xbps_array_count(a); i++) {
			filed = xbps_array_get(a, i);
			xbps_array_add(result, filed);
		}
	}
	if ((a = xbps_dictionary_get(d, "dirs"))) {
		for (i = 0; i < xbps_array_count(a); i++) {
			filed = xbps_array_get(a, i);
			xbps_array_add(result, filed);
		}
	}

	return result;
}

xbps_array_t
xbps_find_pkg_obsoletes(struct xbps_handle *xhp,
			xbps_dictionary_t instd,
			xbps_dictionary_t newd)
{
	xbps_array_t instfiles, newfiles, obsoletes;
	/* These are symlinks in Void and must not be removed */
	const char *basesymlinks[] = {
		"./bin",
		"./sbin",
		"./usr/sbin",
		"./lib",
		"./lib32",
		"./lib64",
		"./usr/lib32",
		"./usr/lib64",
		"./var/run",
	};
	int rv = 0;

	assert(xbps_object_type(instd) == XBPS_TYPE_DICTIONARY);
	assert(xbps_object_type(newd) == XBPS_TYPE_DICTIONARY);

	obsoletes = xbps_array_create();
	assert(obsoletes);

	instfiles = merge_filelist(instd);
	if (xbps_array_count(instfiles) == 0) {
		/* nothing to check if current pkg does not own any file */
		xbps_object_release(instfiles);
		return obsoletes;
	}
	newfiles = merge_filelist(newd);

	/*
	 * Iterate over files list from installed package.
	 */
	for (unsigned int i = 0; i < xbps_array_count(instfiles); i++) {
		xbps_object_t obj, obj2;
		xbps_string_t oldstr, newstr;
		struct stat st;
		uint64_t mtime = 0;
		const char *oldhash;
		char file[PATH_MAX];
		bool found = false;

		obj = xbps_array_get(instfiles, i);
		if (xbps_object_type(obj) != XBPS_TYPE_DICTIONARY) {
			/* ignore unexistent files */
			continue;
		}
		oldstr = xbps_dictionary_get(obj, "file");
		if (oldstr == NULL)
			continue;

		snprintf(file, sizeof(file), ".%s", xbps_string_cstring_nocopy(oldstr));

		if (xbps_dictionary_get_cstring_nocopy(obj, "sha256", &oldhash)) {
			rv = xbps_file_hash_check(file, oldhash);
			if (rv == ENOENT || rv == ERANGE) {
				/*
				  Skip unexistent and files that do not
				 * match the hash.
				 */
				continue;
			}
		}
		/*
		 * Check if current file is available in new pkg filelist.
		 */
		for (unsigned int x = 0; x < xbps_array_count(newfiles); x++) {
			obj2 = xbps_array_get(newfiles, x);
			newstr = xbps_dictionary_get(obj2, "file");
			assert(newstr);
			/*
			 * Skip files with same path.
			 */
			if (xbps_string_equals(oldstr, newstr)) {
				found = true;
				break;
			}
		}
		if (found) {
			continue;
		}
		/*
		 * Make sure to not remove any symlink of root directory.
		 */
		for (uint8_t x = 0; x < __arraycount(basesymlinks); x++) {
			if (strcmp(file, basesymlinks[x]) == 0) {
				found = true;
				xbps_dbg_printf(xhp, "[obsoletes] ignoring "
				    "%s removal\n", file);
				break;
			}
		}
		if (found) {
			continue;
		}
		/*
		 * Finally check if file mtime on disk matched what
		 * the installed pkg has stored.
		 */
		if (xbps_dictionary_get_uint64(obj, "mtime", &mtime)) {
			if (lstat(file, &st) == -1) {
				xbps_dbg_printf(xhp, "[obsoletes] lstat failed "
				    "for %s: %s\n", file, strerror(errno));
				continue;
			}
			if (mtime != (uint64_t)st.st_mtime)
				continue;

			xbps_dbg_printf(xhp,
			    "[obsoletes] %s: matched mtime, adding obsolete.\n", file);
		}
		/*
		 * Obsolete found, add onto the array.
		 */
		xbps_dbg_printf(xhp, "found obsolete: %s\n", file);
		xbps_array_add_cstring(obsoletes, file);
	}
	xbps_object_release(instfiles);
	xbps_object_release(newfiles);

	return obsoletes;
}


text:
#include "ecma-builtin-typedarray-helpers.h"

#if JERRY_BUILTIN_TYPEDARRAY

#include "ecma-builtins.h"
#include "ecma-function-object.h"
#include "ecma-gc.h"
#include "ecma-objects.h"
#include "ecma-typedarray-object.h"

#include "jcontext.h"

#define ECMA_BUILTINS_INTERNAL
#include "ecma-builtins-internal.h"

/**
 * Common implementation of the [[Construct]] call of TypedArrays.
 *
 * @return ecma value of the new TypedArray object
 *         Returned value must be freed with ecma_free_value
 */
ecma_value_t
ecma_typedarray_helper_dispatch_construct (const ecma_value_t *arguments_list_p, /**< arguments list */
                                           uint32_t arguments_list_len, /**< number of arguments */
                                           ecma_typedarray_type_t typedarray_id) /**< id of the typedarray */
{
  JERRY_ASSERT (arguments_list_len == 0 || arguments_list_p != NULL);
  ecma_builtin_id_t proto_id = ecma_typedarray_helper_get_prototype_id (typedarray_id);
  ecma_object_t *prototype_obj_p = NULL;
  ecma_object_t *current_new_target_p = JERRY_CONTEXT (current_new_target_p);

  if (current_new_target_p != NULL)
  {
    prototype_obj_p = ecma_op_get_prototype_from_constructor (current_new_target_p, proto_id);
    if (prototype_obj_p == NULL)
    {
      return ECMA_VALUE_ERROR;
    }
  }
  else
  {
    prototype_obj_p = ecma_builtin_get (proto_id);
  }

  ecma_value_t val = ecma_op_create_typedarray (arguments_list_p,
                                                arguments_list_len,
                                                prototype_obj_p,
                                                ecma_typedarray_helper_get_shift_size (typedarray_id),
                                                typedarray_id);

  if (current_new_target_p != NULL)
  {
    ecma_deref_object (prototype_obj_p);
  }

  return val;
} /* ecma_typedarray_helper_dispatch_construct */

#endif /* JERRY_BUILTIN_TYPEDARRAY */


text:
mtt::dht::Responder::Responder(DataListener& l) : listener(l)
{
	tokenSecret[0] = tokenSecret[1] = Random::Number();
}

bool mtt::dht::Responder::handlePacket(const udp::endpoint& endpoint, DataBuffer& data)
{
	if (data.empty())
		return false;

	BencodeParser parser;
	if (!parser.parse(data.data(), data.size()) || !parser.getRoot()->isMap())
		return false;

	auto root = parser.getRoot();
	auto msgType = root->getTxtItem("y");
	if (!msgType || !(msgType->size == 1 && *msgType->data == 'q'))
		return false;

	auto transactionId = root->getTxtItem("t");
	auto requestType = root->getTxtItem("q");
	auto requestData = root->getDictItem("a");

	if (!transactionId || !requestType || !requestData)
		return false;

	auto sourceId = requestData->getTxtItem("id");

	if (!sourceId || sourceId->size != 20)
		return false;

	PacketBuilder response(requestType->size == 9 ? 256 : 64);
	response.add("d1:t", 4);
	response << std::to_string(transactionId->size);
	response.add(':');
	response.add(transactionId->data, transactionId->size);
	response.add("1:y1:r", 6);
	response.add("1:rd2:id20:", 11);
	response.add(mtt::config::getInternal().hashId, 20);

	DHT_LOG("Request: " << std::string(requestType->data, requestType->data + requestType->size) << " from " << endpoint.address().to_string());// hexToString((const uint8_t*)sourceId->data, sourceId->size));

	if (requestType->equals("find_node", 9))
	{
		auto target = requestData->getTxtItem("target");
		if (!target || target->size != 20)
			return false;

		writeNodes(target->data, endpoint, requestData, response);
	}
	else if (requestType->equals("get_peers", 9))
	{
		auto info = requestData->getTxtItem("info_hash");
		if (!info || info->size != 20)
			return false;

		writeNodes(info->data, endpoint, requestData, response);
		writeValues(info->data, endpoint, response);

		response.add("5:token4:", 9);
		auto token = getAnnounceToken(endpoint);
		response.add((char*)&token, 4);
	}
	else if (requestType->equals("announce_peer", 13))
	{
		auto infoHash = requestData->getTxtItem("info_hash");
		auto token = requestData->getTxtItem("token");

		if (!infoHash || infoHash->size != 20 || !token || token->size != 4 || !isValidToken(*(uint32_t*)token->data, endpoint))
			return false;

		int port = requestData->getInt("port");
		bool impliedPort = requestData->getInt("implied_port") == 1;

		announcedPeer(infoHash->data, Addr(endpoint.address(), impliedPort ? endpoint.port() : (uint16_t)port));
	}

	response.add("ee", 2);

	listener.sendMessage(endpoint, response.getBuffer());

	table->nodeResponded(NodeInfo{ sourceId->data, Addr(endpoint.address(), endpoint.port()) });

	return true;
}

bool mtt::dht::Responder::writeNodes(const char* hash, const udp::endpoint& endpoint, const mtt::BencodeParser::Object* requestData, PacketBuilder& out)
{
	bool wantV4 = endpoint.address().is_v4();
	bool wantV6 = endpoint.address().is_v6();

	if (auto want = requestData->getListItem("want"))
	{
		auto wantWhat = want->getFirstItem();
		while (wantWhat && wantWhat->isText())
		{
			if (wantWhat->info.equals("n4", 2))
				wantV4 = true;
			else if (wantWhat->info.equals("n6", 2))
				wantV6 = true;

			wantWhat = wantWhat->getNextSibling();
		}
	}

	auto found = table->getClosestNodes((const uint8_t*)hash);

	if (found.empty())
		return false;

	PacketBuilder nodes;
	PacketBuilder nodesV6;

	for (auto& n : found)
	{
		if (n.addr.ipv6 && wantV6)
		{
			nodesV6.add(n.id.data, 20);
			nodesV6.add(n.addr.addrBytes, 16);
			nodesV6.add16(n.addr.port);
		}
		else if (!n.addr.ipv6 && wantV4)
		{
			nodes.add(n.id.data, 20);
			nodes.add(n.addr.addrBytes, 4);
			nodes.add16(n.addr.port);
		}
	}

	out.add("5:nodes", 7);
	out << std::to_string(nodes.out.size() + nodesV6.out.size());
	out.add(':');

	if (!nodes.out.empty())
		out.add(nodes.out.data(), nodes.out.size());
	if (!nodesV6.out.empty())
		out.add(nodesV6.out.data(), nodesV6.out.size());

	return false;
}

bool mtt::dht::Responder::writeValues(const char* infoHash, const udp::endpoint& endpoint, PacketBuilder& out)
{
	auto it = values.find(*(NodeId*)infoHash);
	if (it == values.end())
		return false;

	bool wantv6 = endpoint.address().is_v6();

	uint32_t maxcount = mtt::config::getInternal().dht.maxPeerValuesResponse;
	if (wantv6)
		maxcount = uint32_t(maxcount / 3.0f);
	uint32_t count = 0;

	auto addrPrefix = wantv6 ? "18:" : "6:";
	uint32_t addrPrefixSize = wantv6 ? 3 : 2;

	out.add("6:valuesl", 9);

	for (auto& v : it->second)
	{
		if (count < maxcount && v.addr.ipv6 == wantv6)
		{
			out.add(addrPrefix, addrPrefixSize);
			out.add(v.addr.addrBytes, wantv6 ? 16 : 4);
			out.add16(v.addr.port);
			count++;
		}
	}

	if(count > 0)
		out.add('e');
	else
		out.out.resize(out.out.size() - 9);

	return count > 0;
}

void mtt::dht::Responder::announcedPeer(const char* infoHash, const Addr& peer)
{
	DHT_LOG("announcedPeer " << peer.toString() << " infoHash " << hexToString((const uint8_t*)infoHash, 20));

	NodeId id;
	id.copy(infoHash);

	StoredValue v;
	v.timestamp = (uint32_t)::time(0);
	v.addr = peer;

	std::lock_guard<std::mutex> guard(valuesMutex);

	auto& vals = values[id];

	auto it = vals.begin();
	for (; it != vals.end(); it++)
		if (it->addr == peer)
			break;

	if (it != vals.end())
		*it = v;
	else if (vals.size() < mtt::config::getInternal().dht.maxStoredAnnouncedPeers)
		vals.push_back(v);
}

void mtt::dht::Responder::refreshStoredValues()
{
	std::lock_guard<std::mutex> guard(valuesMutex);

	auto oldestTime = (uint32_t)::time(0) - 30*60;
	for (auto it = values.begin(); it != values.end();)
	{
		auto& vals = it->second;
		for (auto it2 = vals.begin(); it2 != vals.end();)
		{
			if (it2->timestamp < oldestTime)
				it2 = vals.erase(it2);
			else
				it2++;
		}

		if (it->second.empty())
			it = values.erase(it);
		else
			it++;
	}
}

bool mtt::dht::Responder::isValidToken(uint32_t token, const udp::endpoint& e)
{
	std::lock_guard<std::mutex> guard(tokenMutex);

	auto addr = e.address().to_string();

	if (getAnnounceToken(addr, tokenSecret[0]) == token)
		return true;
	if (getAnnounceToken(addr, tokenSecret[1]) == token)
		return true;

	return false;
}

uint32_t mtt::dht::Responder::getAnnounceToken(const udp::endpoint& e)
{
	std::lock_guard<std::mutex> guard(tokenMutex);

	return getAnnounceToken(e.address().to_string(), tokenSecret[0]);
}

uint32_t mtt::dht::Responder::getAnnounceToken(const std::string& addr, uint32_t secret)
{
	uint32_t out = secret;

	for (auto& c : addr)
	{
		out += c;
	}

	return out;
}

void mtt::dht::Responder::refresh()
{
	refreshStoredValues();

	{
		std::lock_guard<std::mutex> guard(tokenMutex);

		tokenSecret[1] = tokenSecret[0];
		tokenSecret[0] = Random::Number();
	}
}


text:
import DS from 'ember-data';

export default DS.Model.extend({
    displayName: DS.attr('string'),
});


text:
This is the public Twilio REST API.

## Overview
This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project from the OpenAPI specs located at [twilio/twilio-oai](https://github.com/twilio/twilio-oai/tree/main/spec).  By using the [OpenAPI-spec](https://www.openapis.org/) from a remote server, you can easily generate an API client.

- API version: 1.37.3
- Package version: 1.0.0
- Build package: com.twilio.oai.TwilioGoGenerator
For more information, please visit [https://support.twilio.com](https://support.twilio.com)

## Installation

Install the following dependencies:

```shell
go get github.com/stretchr/testify/assert
go get golang.org/x/net/context
```

Put the package under your project folder and add the following in import:

```golang
import "./openapi"
```

## Documentation for API Endpoints

All URIs are relative to *https://chat.twilio.com*

Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
*CredentialsApi* | [**CreateCredential**](docs/CredentialsApi.md#createcredential) | **Post** /v2/Credentials |
*CredentialsApi* | [**DeleteCredential**](docs/CredentialsApi.md#deletecredential) | **Delete** /v2/Credentials/{Sid} |
*CredentialsApi* | [**FetchCredential**](docs/CredentialsApi.md#fetchcredential) | **Get** /v2/Credentials/{Sid} |
*CredentialsApi* | [**ListCredential**](docs/CredentialsApi.md#listcredential) | **Get** /v2/Credentials |
*CredentialsApi* | [**UpdateCredential**](docs/CredentialsApi.md#updatecredential) | **Post** /v2/Credentials/{Sid} |
*ServicesApi* | [**CreateService**](docs/ServicesApi.md#createservice) | **Post** /v2/Services |
*ServicesApi* | [**DeleteService**](docs/ServicesApi.md#deleteservice) | **Delete** /v2/Services/{Sid} |
*ServicesApi* | [**FetchService**](docs/ServicesApi.md#fetchservice) | **Get** /v2/Services/{Sid} |
*ServicesApi* | [**ListService**](docs/ServicesApi.md#listservice) | **Get** /v2/Services |
*ServicesApi* | [**UpdateService**](docs/ServicesApi.md#updateservice) | **Post** /v2/Services/{Sid} |
*ServicesBindingsApi* | [**DeleteBinding**](docs/ServicesBindingsApi.md#deletebinding) | **Delete** /v2/Services/{ServiceSid}/Bindings/{Sid} |
*ServicesBindingsApi* | [**FetchBinding**](docs/ServicesBindingsApi.md#fetchbinding) | **Get** /v2/Services/{ServiceSid}/Bindings/{Sid} |
*ServicesBindingsApi* | [**ListBinding**](docs/ServicesBindingsApi.md#listbinding) | **Get** /v2/Services/{ServiceSid}/Bindings |
*ServicesChannelsApi* | [**CreateChannel**](docs/ServicesChannelsApi.md#createchannel) | **Post** /v2/Services/{ServiceSid}/Channels |
*ServicesChannelsApi* | [**DeleteChannel**](docs/ServicesChannelsApi.md#deletechannel) | **Delete** /v2/Services/{ServiceSid}/Channels/{Sid} |
*ServicesChannelsApi* | [**FetchChannel**](docs/ServicesChannelsApi.md#fetchchannel) | **Get** /v2/Services/{ServiceSid}/Channels/{Sid} |
*ServicesChannelsApi* | [**ListChannel**](docs/ServicesChannelsApi.md#listchannel) | **Get** /v2/Services/{ServiceSid}/Channels |
*ServicesChannelsApi* | [**UpdateChannel**](docs/ServicesChannelsApi.md#updatechannel) | **Post** /v2/Services/{ServiceSid}/Channels/{Sid} |
*ServicesChannelsInvitesApi* | [**CreateInvite**](docs/ServicesChannelsInvitesApi.md#createinvite) | **Post** /v2/Services/{ServiceSid}/Channels/{ChannelSid}/Invites |
*ServicesChannelsInvitesApi* | [**DeleteInvite**](docs/ServicesChannelsInvitesApi.md#deleteinvite) | **Delete** /v2/Services/{ServiceSid}/Channels/{ChannelSid}/Invites/{Sid} |
*ServicesChannelsInvitesApi* | [**FetchInvite**](docs/ServicesChannelsInvitesApi.md#fetchinvite) | **Get** /v2/Services/{ServiceSid}/Channels/{ChannelSid}/Invites/{Sid} |
*ServicesChannelsInvitesApi* | [**ListInvite**](docs/ServicesChannelsInvitesApi.md#listinvite) | **Get** /v2/Services/{ServiceSid}/Channels/{ChannelSid}/Invites |
*ServicesChannelsMembersApi* | [**CreateMember**](docs/ServicesChannelsMembersApi.md#createmember) | **Post** /v2/Services/{ServiceSid}/Channels/{ChannelSid}/Members |
*ServicesChannelsMembersApi* | [**DeleteMember**](docs/ServicesChannelsMembersApi.md#deletemember) | **Delete** /v2/Services/{ServiceSid}/Channels/{ChannelSid}/Members/{Sid} |
*ServicesChannelsMembersApi* | [**FetchMember**](docs/ServicesChannelsMembersApi.md#fetchmember) | **Get** /v2/Services/{ServiceSid}/Channels/{ChannelSid}/Members/{Sid} |
*ServicesChannelsMembersApi* | [**ListMember**](docs/ServicesChannelsMembersApi.md#listmember) | **Get** /v2/Services/{ServiceSid}/Channels/{ChannelSid}/Members |
*ServicesChannelsMembersApi* | [**UpdateMember**](docs/ServicesChannelsMembersApi.md#updatemember) | **Post** /v2/Services/{ServiceSid}/Channels/{ChannelSid}/Members/{Sid} |
*ServicesChannelsMessagesApi* | [**CreateMessage**](docs/ServicesChannelsMessagesApi.md#createmessage) | **Post** /v2/Services/{ServiceSid}/Channels/{ChannelSid}/Messages |
*ServicesChannelsMessagesApi* | [**DeleteMessage**](docs/ServicesChannelsMessagesApi.md#deletemessage) | **Delete** /v2/Services/{ServiceSid}/Channels/{ChannelSid}/Messages/{Sid} |
*ServicesChannelsMessagesApi* | [**FetchMessage**](docs/ServicesChannelsMessagesApi.md#fetchmessage) | **Get** /v2/Services/{ServiceSid}/Channels/{ChannelSid}/Messages/{Sid} |
*ServicesChannelsMessagesApi* | [**ListMessage**](docs/ServicesChannelsMessagesApi.md#listmessage) | **Get** /v2/Services/{ServiceSid}/Channels/{ChannelSid}/Messages |
*ServicesChannelsMessagesApi* | [**UpdateMessage**](docs/ServicesChannelsMessagesApi.md#updatemessage) | **Post** /v2/Services/{ServiceSid}/Channels/{ChannelSid}/Messages/{Sid} |
*ServicesChannelsWebhooksApi* | [**CreateChannelWebhook**](docs/ServicesChannelsWebhooksApi.md#createchannelwebhook) | **Post** /v2/Services/{ServiceSid}/Channels/{ChannelSid}/Webhooks |
*ServicesChannelsWebhooksApi* | [**DeleteChannelWebhook**](docs/ServicesChannelsWebhooksApi.md#deletechannelwebhook) | **Delete** /v2/Services/{ServiceSid}/Channels/{ChannelSid}/Webhooks/{Sid} |
*ServicesChannelsWebhooksApi* | [**FetchChannelWebhook**](docs/ServicesChannelsWebhooksApi.md#fetchchannelwebhook) | **Get** /v2/Services/{ServiceSid}/Channels/{ChannelSid}/Webhooks/{Sid} |
*ServicesChannelsWebhooksApi* | [**ListChannelWebhook**](docs/ServicesChannelsWebhooksApi.md#listchannelwebhook) | **Get** /v2/Services/{ServiceSid}/Channels/{ChannelSid}/Webhooks |
*ServicesChannelsWebhooksApi* | [**UpdateChannelWebhook**](docs/ServicesChannelsWebhooksApi.md#updatechannelwebhook) | **Post** /v2/Services/{ServiceSid}/Channels/{ChannelSid}/Webhooks/{Sid} |
*ServicesRolesApi* | [**CreateRole**](docs/ServicesRolesApi.md#createrole) | **Post** /v2/Services/{ServiceSid}/Roles |
*ServicesRolesApi* | [**DeleteRole**](docs/ServicesRolesApi.md#deleterole) | **Delete** /v2/Services/{ServiceSid}/Roles/{Sid} |
*ServicesRolesApi* | [**FetchRole**](docs/ServicesRolesApi.md#fetchrole) | **Get** /v2/Services/{ServiceSid}/Roles/{Sid} |
*ServicesRolesApi* | [**ListRole**](docs/ServicesRolesApi.md#listrole) | **Get** /v2/Services/{ServiceSid}/Roles |
*ServicesRolesApi* | [**UpdateRole**](docs/ServicesRolesApi.md#updaterole) | **Post** /v2/Services/{ServiceSid}/Roles/{Sid} |
*ServicesUsersApi* | [**CreateUser**](docs/ServicesUsersApi.md#createuser) | **Post** /v2/Services/{ServiceSid}/Users |
*ServicesUsersApi* | [**DeleteUser**](docs/ServicesUsersApi.md#deleteuser) | **Delete** /v2/Services/{ServiceSid}/Users/{Sid} |
*ServicesUsersApi* | [**FetchUser**](docs/ServicesUsersApi.md#fetchuser) | **Get** /v2/Services/{ServiceSid}/Users/{Sid} |
*ServicesUsersApi* | [**ListUser**](docs/ServicesUsersApi.md#listuser) | **Get** /v2/Services/{ServiceSid}/Users |
*ServicesUsersApi* | [**UpdateUser**](docs/ServicesUsersApi.md#updateuser) | **Post** /v2/Services/{ServiceSid}/Users/{Sid} |
*ServicesUsersBindingsApi* | [**DeleteUserBinding**](docs/ServicesUsersBindingsApi.md#deleteuserbinding) | **Delete** /v2/Services/{ServiceSid}/Users/{UserSid}/Bindings/{Sid} |
*ServicesUsersBindingsApi* | [**FetchUserBinding**](docs/ServicesUsersBindingsApi.md#fetchuserbinding) | **Get** /v2/Services/{ServiceSid}/Users/{UserSid}/Bindings/{Sid} |
*ServicesUsersBindingsApi* | [**ListUserBinding**](docs/ServicesUsersBindingsApi.md#listuserbinding) | **Get** /v2/Services/{ServiceSid}/Users/{UserSid}/Bindings |
*ServicesUsersChannelsApi* | [**DeleteUserChannel**](docs/ServicesUsersChannelsApi.md#deleteuserchannel) | **Delete** /v2/Services/{ServiceSid}/Users/{UserSid}/Channels/{ChannelSid} |
*ServicesUsersChannelsApi* | [**FetchUserChannel**](docs/ServicesUsersChannelsApi.md#fetchuserchannel) | **Get** /v2/Services/{ServiceSid}/Users/{UserSid}/Channels/{ChannelSid} |
*ServicesUsersChannelsApi* | [**ListUserChannel**](docs/ServicesUsersChannelsApi.md#listuserchannel) | **Get** /v2/Services/{ServiceSid}/Users/{UserSid}/Channels |
*ServicesUsersChannelsApi* | [**UpdateUserChannel**](docs/ServicesUsersChannelsApi.md#updateuserchannel) | **Post** /v2/Services/{ServiceSid}/Users/{UserSid}/Channels/{ChannelSid} |

## Documentation For Models

 - [ListUserResponse](docs/ListUserResponse.md)
 - [ListChannelResponse](docs/ListChannelResponse.md)
 - [ChatV2User](docs/ChatV2User.md)
 - [ListInviteResponse](docs/ListInviteResponse.md)
 - [ListBindingResponse](docs/ListBindingResponse.md)
 - [ListMessageResponse](docs/ListMessageResponse.md)
 - [ListServiceResponse](docs/ListServiceResponse.md)
 - [ListChannelWebhookResponse](docs/ListChannelWebhookResponse.md)
 - [ListMemberResponse](docs/ListMemberResponse.md)
 - [ChatV2Message](docs/ChatV2Message.md)
 - [ChatV2Credential](docs/ChatV2Credential.md)
 - [ListUserChannelResponse](docs/ListUserChannelResponse.md)
 - [ListCredentialResponse](docs/ListCredentialResponse.md)
 - [ChatV2UserChannel](docs/ChatV2UserChannel.md)
 - [ChatV2UserBinding](docs/ChatV2UserBinding.md)
 - [ListUserBindingResponse](docs/ListUserBindingResponse.md)
 - [ListRoleResponse](docs/ListRoleResponse.md)
 - [ChatV2Member](docs/ChatV2Member.md)
 - [ChatV2Invite](docs/ChatV2Invite.md)
 - [ChatV2Channel](docs/ChatV2Channel.md)
 - [ListBindingResponseMeta](docs/ListBindingResponseMeta.md)
 - [ChatV2Role](docs/ChatV2Role.md)
 - [ChatV2Service](docs/ChatV2Service.md)
 - [ChatV2ChannelWebhook](docs/ChatV2ChannelWebhook.md)
 - [ChatV2Binding](docs/ChatV2Binding.md)

## Documentation For Authorization

## accountSid_authToken

- **Type**: HTTP basic authentication

Example

```golang
auth := context.WithValue(context.Background(), sw.ContextBasicAuth, sw.BasicAuth{
    UserName: "username",
    Password: "password",
})
r, err := client.Service.Operation(auth, args)
```


text:
import { createSelector } from 'reselect';

export const requestTrackingsSelector = state => state.app.requestTrackings;

export const requestTrackingSelector = type => (
  createSelector(
    requestTrackingsSelector,
    trackings => trackings[type],
  )
);

export const isActiveRequestSelector = type => (
  createSelector(
    requestTrackingSelector(type),
    tracking => !!tracking,
  )
);

export const isActiveRefreshRequestSelector = type => (
  createSelector(
    requestTrackingSelector(type),
    tracking => !!(tracking && tracking.isRefresh),
  )
);

export const fetchedDataSelector = key => (
  state => state.fetches[key]
);

export const isActiveBackgroundRequestWithNoFetchedDataSelector = (requestType, fetchKey) => (
  createSelector(
    requestTrackingSelector(requestType),
    fetchedDataSelector(fetchKey),
    (tracking, data) => (
      (tracking && !data) ? !tracking.isRefresh : false
    ),
  )
);


text:
using System;
using System.Linq;
using Infrastructure.Settings;
using HtmlAgilityPack;

namespace Domain.Strategies
{
    public abstract class TagParserStrategy
    {
        protected string TagName;
        protected string TypeAttributeName => "type";
        protected string NameAttributeValue => "name";

        protected TagParserStrategy(IConfigReader configReader)
        {
            if (configReader == null)
                throw new ArgumentNullException(nameof(configReader));

            var izichizitTagName = configReader.GetStringSetting("Izichizit.TagName", "izichizit");
            TagName = izichizitTagName;
        }

        public abstract string Parse(string template);

        protected HtmlNode LoadDocument(string template)
        {
            var html = new HtmlDocument();
            html.LoadHtml(template);

            return html.DocumentNode;
        }
    }
}


text:
"""Test calling functions in static methods with a stripped binary."""

from __future__ import print_function

import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil

class TestObjCStaticMethodStripped(TestBase):

    mydir = TestBase.compute_mydir(__file__)

    def setUp(self):
        # Call super's setUp().
        TestBase.setUp(self)
        # Find the line numbers to break inside main().
        self.main_source = "static.m"
        self.break_line = line_number(
            self.main_source, '// Set breakpoint here.')

    @skipUnlessDarwin
    @add_test_categories(['pyapi'])
    @skipIf(
        debug_info=no_match("dsym"),
        bugnumber="This test requires a stripped binary and a dSYM")
    #<rdar://problem/12042992>
    def test_with_python_api(self):
        """Test calling functions in static methods with a stripped binary."""
        if self.getArchitecture() == 'i386':
            self.skipTest("requires modern objc runtime")
        self.build()
        exe = self.getBuildArtifact("a.out")

        target = self.dbg.CreateTarget(exe)
        self.assertTrue(target, VALID_TARGET)

        bpt = target.BreakpointCreateByLocation(
            self.main_source, self.break_line)
        self.assertTrue(bpt, VALID_BREAKPOINT)

        # Now launch the process, and do not stop at entry point.
        process = target.LaunchSimple(
            None, None, self.get_process_working_directory())

        self.assertTrue(process, PROCESS_IS_VALID)

        # The stop reason of the thread should be breakpoint.
        thread_list = lldbutil.get_threads_stopped_at_breakpoint(process, bpt)

        # Make sure we stopped at the first breakpoint.
        self.assertTrue(
            len(thread_list) != 0,
            "No thread stopped at our breakpoint.")
        self.assertTrue(len(thread_list) == 1,
                        "More than one thread stopped at our breakpoint.")

        # Now make sure we can call a function in the static method we've
        # stopped in.
        frame = thread_list[0].GetFrameAtIndex(0)
        self.assertTrue(frame, "Got a valid frame 0 frame.")

        cmd_value = frame.EvaluateExpression("(char *) sel_getName (_cmd)")
        self.assertTrue(cmd_value.IsValid())
        sel_name = cmd_value.GetSummary()
        self.assertTrue(
            sel_name == "\"doSomethingWithString:\"",
            "Got the right value for the selector as string.")

        cmd_value = frame.EvaluateExpression(
            "[Foo doSomethingElseWithString:string]")
        self.assertTrue(cmd_value.IsValid())
        string_length = cmd_value.GetValueAsUnsigned()
        self.assertTrue(
            string_length == 27,
            "Got the right value from another class method on the same class.")


text:
function EmitterBlueTrail(container){
	var texture	= THREE.ImageUtils.loadTexture('vendor/threex.particles/examples/images/blue_particle.jpg')
	var maxAge	= 1;
	var tweenOpacity= createTweenMidi(maxAge, 0.33*maxAge, 0.33*maxAge);
	var tweenScale	= (function(){
		var tweenMidi	= createTweenMidi(maxAge, 0.2*maxAge, 0.2*maxAge);
		return function(age){
			return (1 + 1 * tweenMidi(age)) * 0.3
		}
	})();
	var updateFcts	= []
	var prevPosition= null;
	this.emit	= function(position){
		// init sprite material
		var material	= new THREE.SpriteMaterial({
			map			: texture,
			useScreenCoordinates	: false,
			color			: 0xAA4488,
			transparent		: true,
			blending		: THREE.AdditiveBlending
		})
		// init sprite
		var sprite	= new THREE.Sprite(material)
		//sprite.rotation	= Math.random() * Math.PI*2
		sprite.position.copy( position )
		container.add( sprite )

		// compute velocity
		prevPosition	= prevPosition || position.clone();
		var velocity	= position.clone().sub(prevPosition).normalize();
		prevPosition.copy( position )

		// start a little bit behind the container
		sprite.position.add( velocity.clone().multiplyScalar(-0.1) )

		// init pattern
		sprite.scale.set(1,1,1).multiplyScalar( tweenScale(0) )
		material.opacity= tweenOpacity(0)

		var birthDate	= Date.now()/1000;
		updateFcts.push(function callback(delta, now){
			var age	= Date.now()/1000 - birthDate;
			if( age >= maxAge ){
				sprite.parent.remove(sprite)
				updateFcts.splice(updateFcts.indexOf(callback),1)
				return;
			}
			sprite.scale.set(1,1,1).multiplyScalar( tweenScale(age) )
			material.opacity= tweenOpacity(age)
		})
	}
	var lastEmit	= 0;
	this.emitThrottle= function(position, rate){
		// rate limiter emition
		var now	= Date.now()/1000
		if( rate === 0 || now - lastEmit < 1/rate )	return;
		lastEmit	= now;
		// emit now
		this.emit(position)
	}
	this.update	= function(delta, now){
		updateFcts.forEach(function(updateFct){
			updateFct(delta, now)
		})
	}
	function createTweenMidi(maxAge, attackTime, releaseTime){
		return function(age){
			if( age < attackTime ){
				return age / attackTime
			}else if( age < maxAge - releaseTime ){
				return 1;
			}else{
				return (maxAge - age) / releaseTime
			}
		}
	}
}


text:
'use strict'

const config = require('../../config').backend
const { sequelize } = require('../common/db')
const jwt = require('jsonwebtoken')
const User = sequelize.import('../model/user.model.js')
const _ = require('lodash')

/**
 * Attaches the user object to the request if authenticated
 * Otherwise returns 401
 */
async function isAuthenticated(ctx, next) {
  try {
    if (ctx.headers.authorization) {
      ctx.headers.authorization = ctx.headers.authorization.replace(/Bearer /g, '')
    }
    const decoded = jwt.verify(ctx.headers.authorization || ctx.query.access_token || '', config.secrets.session)
    const user = await User.findById(decoded._id)
    if (_.isEmpty(user)) {
      ctx.status = 401
      return
    }
    ctx.state.user = decoded
    return next()
  } catch (err) {
    ctx.status = 401
    ctx.body = {
      error: err.message || 'JsonWebTokenError'
    }
    return
  }
}

/**
 * Checks if the user role meets the minimum requirements of the route
 */
async function hasRole(ctx, next, roleRequired) {
  if (!roleRequired) {
    return ctx.throw('Required role needs to be set')
  }
  if (config.userRoles.indexOf(ctx.state.user.role) <= config.userRoles.indexOf(roleRequired)) {
    return next()
  } else {
    ctx.status = 403
    return
  }
}

/**
 * Returns a jwt token signed by the app secret
 */
function signToken(user) {
  return jwt.sign({ id: user.id, name: user.name }, config.secrets.session, { expiresIn: '7d' })
}

/**
 * Set token cookie directly for oAuth strategies
 */
function setTokenCookie(ctx) {
  if (!ctx.state.user) {
    ctx.status = 404
    ctx.body({ message: 'Something went wrong, please try again.' })
    return
  }
  const token = signToken(ctx.state.user)
  ctx.cookies.set('token', JSON.stringify(token))
  ctx.redirect('/')
}

exports.isAuthenticated = isAuthenticated
exports.hasRole = hasRole
exports.signToken = signToken
exports.setTokenCookie = setTokenCookie


text:
package com.example.lifx_sdk_samples;

import java.util.ArrayList;

import lifx.java.android.client.LFXClient;
import lifx.java.android.entities.LFXHSBKColor;
import lifx.java.android.entities.LFXTypes.LFXFuzzyPowerState;
import lifx.java.android.entities.LFXTypes.LFXPowerState;
import lifx.java.android.light.LFXLight;
import lifx.java.android.light.LFXLight.LFXLightListener;
import lifx.java.android.light.LFXLightCollection;
import lifx.java.android.light.LFXLightCollection.LFXLightCollectionListener;
import lifx.java.android.light.LFXTaggedLightCollection;
import lifx.java.android.network_context.LFXNetworkContext;
import lifx.java.android.network_context.LFXNetworkContext.LFXNetworkContextListener;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class LFXSDKLightEditLabelActivity extends Activity implements LFXLightListener, LFXLightCollectionListener, LFXNetworkContextListener
{
	private LFXNetworkContext networkContext;
	private LFXSDKLightListAdapter lightListAdapter;
	private LFXSDKTaggedLightCollectionListAdapter groupListAdapter;

	@Override
	protected void onCreate( Bundle savedInstanceState)
	{
		super.onCreate( savedInstanceState);
		setContentView( R.layout.lifx_list_sample_layout);

		networkContext = LFXClient.getSharedInstance( getApplicationContext()).getLocalNetworkContext();
		networkContext.addNetworkContextListener( this);
		networkContext.getAllLightsCollection().addLightCollectionListener( this);

		ListView lightListView = (ListView) findViewById( R.id.light_list_view);
		lightListAdapter = new LFXSDKLightListAdapter( this);
		lightListView.setAdapter( lightListAdapter);

		ListView groupListView = (ListView) findViewById( R.id.group_list_view);
		groupListAdapter = new LFXSDKTaggedLightCollectionListAdapter( this);
		groupListView.setAdapter( groupListAdapter);

		updateStateFromLIFX();

		lightListView.setOnItemClickListener( new OnItemClickListener()
		{
			@Override
			public void onItemClick( AdapterView<?> arg0, View arg1, int position, long arg3)
			{
				LFXLight light = (LFXLight) lightListAdapter.getItem( position);
				showLabelDialogForLight( light);
			}
		});

		groupListView.setOnItemClickListener( new OnItemClickListener()
		{
			@Override
			public void onItemClick( AdapterView<?> arg0, View arg1, int position, long arg3)
			{
				LFXTaggedLightCollection lightCollection = (LFXTaggedLightCollection) groupListAdapter.getItem( position);
				showLabelDialogForLightCollection( lightCollection);
			}
		});
	}

	public void showLabelDialogForLight( LFXLight light)
	{
		final LFXLight finalLight = light;

		AlertDialog.Builder alert = new AlertDialog.Builder( this);
		alert.setTitle("Rename Light Too:");

		 // Set an EditText view to get user input
		 final EditText input = new EditText( this);
		 alert.setView(input);

		    alert.setPositiveButton( "Ok", new DialogInterface.OnClickListener()
		    {
			    public void onClick( DialogInterface dialog, int whichButton)
			    {
			        String value = input.getText().toString();
			        finalLight.setLabel( value);
			        return;
			    }
		    });

		    alert.setNegativeButton( "Cancel", new DialogInterface.OnClickListener()
		    {
		        public void onClick(DialogInterface dialog, int which)
		        {
		            return;
		        }
		    });

		   alert.show();
	}

	public void showLabelDialogForLightCollection( LFXTaggedLightCollection lightCollection)
	{
		final LFXTaggedLightCollection finalLightCollection = lightCollection;

		AlertDialog.Builder alert = new AlertDialog.Builder( this);
		alert.setTitle("Rename Group Too:");

		 // Set an EditText view to get user input
		 final EditText input = new EditText( this);
		 alert.setView(input);

		    alert.setPositiveButton( "Ok", new DialogInterface.OnClickListener()
		    {
			    public void onClick( DialogInterface dialog, int whichButton)
			    {
			        String value = input.getText().toString();
			        finalLightCollection.setLabel( value);
			        return;
			    }
		    });

		    alert.setNegativeButton( "Cancel", new DialogInterface.OnClickListener()
		    {
		        public void onClick(DialogInterface dialog, int which)
		        {
		            return;
		        }
		    });

		   alert.show();
	}

	@Override
	public boolean onCreateOptionsMenu( Menu menu)
	{
		getMenuInflater().inflate( R.menu.sample, menu);
		return true;
	}

	@Override
	protected void onPause()
	{
		networkContext.removeNetworkContextListener( this);
		super.onPause();
	}

	private void updateStateFromLIFX()
	{
		ArrayList<LFXLight> allLights = networkContext.getAllLightsCollection().getLights();
		lightListAdapter.updateWithLights( allLights);

		ArrayList<LFXTaggedLightCollection> lightCollections = networkContext.getTaggedLightCollections();
		groupListAdapter.updateWithLightCollections( lightCollections);
	}

	@Override
	public void networkContextDidConnect( LFXNetworkContext networkContext)
	{
		Toast toast = Toast.makeText( this, "CONNECTED", Toast.LENGTH_SHORT);
		toast.show();
	}

	@Override
	public void networkContextDidDisconnect( LFXNetworkContext networkContext)
	{
		Toast toast = Toast.makeText( this, "DISCONNECTED", Toast.LENGTH_SHORT);
		toast.show();
	}

	@Override
	public void networkContextDidAddTaggedLightCollection( LFXNetworkContext networkContext, LFXTaggedLightCollection collection)
	{
		updateStateFromLIFX();
	}

	@Override
	public void networkContextDidRemoveTaggedLightCollection( LFXNetworkContext networkContext, LFXTaggedLightCollection collection)
	{
		updateStateFromLIFX();
	}

	@Override
	public void lightCollectionDidAddLight( LFXLightCollection lightCollection, LFXLight light)
	{
		updateStateFromLIFX();
		light.addLightListener( this);
	}

	@Override
	public void lightCollectionDidRemoveLight( LFXLightCollection lightCollection, LFXLight light)
	{
		updateStateFromLIFX();
		light.removeLightListener( this);
	}

	@Override
	public void lightCollectionDidChangeLabel( LFXLightCollection lightCollection, String label) {}

	@Override
	public void lightCollectionDidChangeColor( LFXLightCollection lightCollection, LFXHSBKColor color) {}

	@Override
	public void lightCollectionDidChangeFuzzyPowerState( LFXLightCollection lightCollection, LFXFuzzyPowerState fuzzyPowerState) {}

	@Override
	public void lightDidChangeLabel( LFXLight light, String label)
	{
		updateStateFromLIFX();
	}

	@Override
	public void lightDidChangeColor( LFXLight light, LFXHSBKColor color)
	{
		updateStateFromLIFX();
	}

	@Override
	public void lightDidChangePowerState( LFXLight light, LFXPowerState powerState)
	{
		updateStateFromLIFX();
	}
}