text:
#region License

#endregion

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace Irony.Parsing.Construction
{
    // Methods constructing LALR automaton.
    // See _about_parser_construction.txt file in this folder for important comments

    internal partial class ParserDataBuilder
    {
        private LanguageData _language;
        private ParserData _data;
        private Grammar _grammar;
        private ParserStateHash _stateHash = new ParserStateHash();

        internal ParserDataBuilder(LanguageData language)
        {
            this._language = language;
            this._grammar = this._language.Grammar;
        }

        public void Build()
        {
            this._stateHash.Clear();
            this._data = this._language.ParserData;
            this.CreateParserStates();
            var itemsNeedLookaheads = this.GetReduceItemsInInadequateState();
            this.ComputeTransitions(itemsNeedLookaheads);
            this.ComputeLookaheads(itemsNeedLookaheads);
            this.ComputeStatesExpectedTerminals();
            this.ComputeConflicts();
            this.ApplyHints();
            this.HandleUnresolvedConflicts();
            this.CreateRemainingReduceActions();
            //Create error action - if it is not created yet by some hint or custom code
            if (this._data.ErrorAction == null)
            {
                this._data.ErrorAction = new ErrorRecoveryParserAction();
            }
        }//method

        #region Creating parser states
        private void CreateParserStates()
        {
            var grammarData = this._language.GrammarData;

            //1. Base automaton: create states for main augmented root for the grammar
            this._data.InitialState = this.CreateInitialState(grammarData.AugmentedRoot);
            this.ExpandParserStateList(0);
            this.CreateAcceptAction(this._data.InitialState, grammarData.AugmentedRoot);

            //2. Expand automaton: add parser states from additional roots
            foreach (var augmRoot in grammarData.AugmentedSnippetRoots)
            {
                var initialState = this.CreateInitialState(augmRoot);
                this.ExpandParserStateList(this._data.States.Count - 1); //start with just added state - it is the last state in the list
                this.CreateAcceptAction(initialState, augmRoot);
            }
        }

        private void CreateAcceptAction(ParserState initialState, NonTerminal augmentedRoot)
        {
            var root = augmentedRoot.Productions[0].RValues[0];
            var shiftAction = initialState.Actions[root] as ShiftParserAction;
            var shiftOverRootState = shiftAction.NewState;
            shiftOverRootState.Actions[this._grammar.Eof] = new AcceptParserAction();
        }

        private ParserState CreateInitialState(NonTerminal augmentedRoot)
        {
            //for an augmented root there is an initial production "Root' -> .Root"; so we need the LR0 item at 0 index
            var iniItemSet = new LR0ItemSet();
            iniItemSet.Add(augmentedRoot.Productions[0].LR0Items[0]);
            var initialState = this.FindOrCreateState(iniItemSet);
            var rootNt = augmentedRoot.Productions[0].RValues[0] as NonTerminal;
            this._data.InitialStates[rootNt] = initialState;
            return initialState;
        }

        private void ExpandParserStateList(int initialIndex)
        {
            // Iterate through states (while new ones are created) and create shift transitions and new states
            for (int index = initialIndex; index < this._data.States.Count; index++)
            {
                var state = this._data.States[index];
                //Get all possible shifts
                foreach (var term in state.BuilderData.ShiftTerms)
                {
                    var shiftItems = state.BuilderData.ShiftItems.SelectByCurrent(term);
                    //Get set of shifted cores and find/create target state
                    var shiftedCoreItems = shiftItems.GetShiftedCores();
                    var newState = this.FindOrCreateState(shiftedCoreItems);
                    //Create shift action
                    var newAction = new ShiftParserAction(term, newState);
                    state.Actions[term] = newAction;
                    //Link items in old/new states
                    foreach (var shiftItem in shiftItems)
                    {
                        shiftItem.ShiftedItem = newState.BuilderData.AllItems.FindByCore(shiftItem.Core.ShiftedItem);
                    }//foreach shiftItem
                }//foreach term
            } //for index
        }//method

        private ParserState FindOrCreateState(LR0ItemSet coreItems)
        {
            string key = ComputeLR0ItemSetKey(coreItems);
            ParserState state;
            if (this._stateHash.TryGetValue(key, out state))
            {
                return state;
            }
            //create new state
            state = new ParserState("S" + this._data.States.Count);
            state.BuilderData = new ParserStateData(state, coreItems);
            this._data.States.Add(state);
            this._stateHash[key] = state;
            return state;
        }

        #endregion

        #region Compute transitions, lookbacks, lookaheads
        //We compute only transitions that are really needed to compute lookaheads in inadequate states.
        // We start with reduce items in inadequate state and find their lookbacks - this is initial list of transitions.
        // Then for each transition in the list we check if it has items with nullable tails; for those items we compute
        // lookbacks - these are new or already existing transitons - and so on, we repeat the operation until no new transitions
        // are created.
        private void ComputeTransitions(LRItemSet forItems)
        {
            var newItemsNeedLookbacks = forItems;
            while (newItemsNeedLookbacks.Count > 0)
            {
                var newTransitions = this.CreateLookbackTransitions(newItemsNeedLookbacks);
                newItemsNeedLookbacks = this.SelectNewItemsThatNeedLookback(newTransitions);
            }
        }

        private LRItemSet SelectNewItemsThatNeedLookback(TransitionList transitions)
        {
            //Select items with nullable tails that don't have lookbacks yet
            var items = new LRItemSet();
            foreach (var trans in transitions)
            {
                foreach (var item in trans.Items)
                {
                    if (item.Core.TailIsNullable && item.Lookbacks.Count == 0)
                    {
                        //only if it does not have lookbacks yet
                        items.Add(item);
                    }
                }
            }

            return items;
        }

        private LRItemSet GetReduceItemsInInadequateState()
        {
            var result = new LRItemSet();
            foreach (var state in this._data.States)
            {
                if (state.BuilderData.IsInadequate)
                {
                    result.UnionWith(state.BuilderData.ReduceItems);
                }
            }
            return result;
        }

        private TransitionList CreateLookbackTransitions(LRItemSet sourceItems)
        {
            var newTransitions = new TransitionList();
            //Build set of initial cores - this is optimization for performance
            //We need to find all initial items in all states that shift into one of sourceItems
            // Each such initial item would have the core from the "initial" cores set that we build from source items.
            var iniCores = new LR0ItemSet();
            foreach (var sourceItem in sourceItems)
            {
                iniCores.Add(sourceItem.Core.Production.LR0Items[0]);
            }
            //find
            foreach (var state in this._data.States)
            {
                foreach (var iniItem in state.BuilderData.InitialItems)
                {
                    if (!iniCores.Contains(iniItem.Core))
                    {
                        continue;
                    }

                    var iniItemNt = iniItem.Core.Production.LValue; // iniItem's non-terminal (left side of production)
                    Transition lookback = null; // local var for lookback - transition over iniItemNt
                    var currItem = iniItem; // iniItem is initial item for all currItem's in the shift chain.
                    while (currItem != null)
                    {
                        if (sourceItems.Contains(currItem))
                        {
                            // We create transitions lazily, only when we actually need them. Check if we have iniItem's transition
                            // in local variable; if not, get it from state's transitions table; if not found, create it.
                            if (lookback == null && !state.BuilderData.Transitions.TryGetValue(iniItemNt, out lookback))
                            {
                                lookback = new Transition(state, iniItemNt);
                                newTransitions.Add(lookback);
                            }
                            //Now for currItem, either add trans to Lookbacks, or "include" it into currItem.Transition
                            // We need lookbacks ONLY for final items; for non-Final items we need proper Include lists on transitions
                            if (currItem.Core.IsFinal)
                            {
                                currItem.Lookbacks.Add(lookback);
                            }
                            else
                            {
                                // if (currItem.Transition != null)
                                // Note: looks like checking for currItem.Transition is redundant - currItem is either:
                                //    - Final - always the case for the first run of this method;
                                //    - it has a transition after the first run, due to the way we select sourceItems list
                                //       in SelectNewItemsThatNeedLookback (by transitions)
                                currItem.Transition.Include(lookback);
                            }
                        }//if
                         //move to next item
                        currItem = currItem.ShiftedItem;
                    }//while
                }//foreach iniItem
            }//foreach state
            return newTransitions;
        }

        private void ComputeLookaheads(LRItemSet forItems)
        {
            foreach (var reduceItem in forItems)
            {
                // Find all source states - those that contribute lookaheads
                var sourceStates = new ParserStateSet();
                foreach (var lookbackTrans in reduceItem.Lookbacks)
                {
                    sourceStates.Add(lookbackTrans.ToState);
                    sourceStates.UnionWith(lookbackTrans.ToState.BuilderData.ReadStateSet);
                    foreach (var includeTrans in lookbackTrans.Includes)
                    {
                        sourceStates.Add(includeTrans.ToState);
                        sourceStates.UnionWith(includeTrans.ToState.BuilderData.ReadStateSet);
                    }//foreach includeTrans
                }//foreach lookbackTrans
                 //Now merge all shift terminals from all source states
                foreach (var state in sourceStates)
                {
                    reduceItem.Lookaheads.UnionWith(state.BuilderData.ShiftTerminals);
                }
                //Remove SyntaxError - it is pseudo terminal
                if (reduceItem.Lookaheads.Contains(this._grammar.SyntaxError))
                {
                    reduceItem.Lookaheads.Remove(this._grammar.SyntaxError);
                }
                //Sanity check
                if (reduceItem.Lookaheads.Count == 0)
                {
                    this._language.Errors.Add(GrammarErrorLevel.InternalError, reduceItem.State, "Reduce item '{0}' in state {1} has no lookaheads.", reduceItem.Core, reduceItem.State);
                }
            }//foreach reduceItem
        }//method

        #endregion

        #region Analyzing and resolving conflicts
        private void ComputeConflicts()
        {
            foreach (var state in this._data.States)
            {
                if (!state.BuilderData.IsInadequate)
                {
                    continue;
                }
                //first detect conflicts
                var stateData = state.BuilderData;
                stateData.Conflicts.Clear();
                var allLkhds = new BnfTermSet();
                //reduce/reduce --------------------------------------------------------------------------------------
                foreach (var item in stateData.ReduceItems)
                {
                    foreach (var lkh in item.Lookaheads)
                    {
                        if (allLkhds.Contains(lkh))
                        {
                            state.BuilderData.Conflicts.Add(lkh);
                        }

                        allLkhds.Add(lkh);
                    }//foreach lkh
                }//foreach item

                //shift/reduce ---------------------------------------------------------------------------------------
                foreach (var term in stateData.ShiftTerminals)
                {
                    if (allLkhds.Contains(term))
                    {
                        stateData.Conflicts.Add(term);
                    }
                }
            }
        }//method

        private void ApplyHints()
        {
            foreach (var state in this._data.States)
            {
                var stateData = state.BuilderData;
                //Add automatic precedence hints
                if (stateData.Conflicts.Count > 0)
                {
                    foreach (var conflict in stateData.Conflicts.ToList())
                    {
                        if (conflict.Flags.IsSet(TermFlags.IsOperator))
                        {
                            //Find any reduce item with this lookahead and add PrecedenceHint
                            var reduceItem = stateData.ReduceItems.SelectByLookahead(conflict).First();
                            var precHint = new PrecedenceHint();
                            reduceItem.Core.Hints.Add(precHint);
                        }
                    }
                }
                // Apply (activate) hints - these should resolve conflicts as well
                foreach (var item in state.BuilderData.AllItems)
                {
                    foreach (var hint in item.Core.Hints)
                    {
                        hint.Apply(this._language, item);
                    }
                }
            }//foreach
        }//method

        //Resolve to default actions
        private void HandleUnresolvedConflicts()
        {
            foreach (var state in this._data.States)
            {
                if (state.BuilderData.Conflicts.Count == 0)
                {
                    continue;
                }

                var shiftReduceConflicts = state.BuilderData.GetShiftReduceConflicts();
                var reduceReduceConflicts = state.BuilderData.GetReduceReduceConflicts();
                var stateData = state.BuilderData;
                if (shiftReduceConflicts.Count > 0)
                {
                    this._language.Errors.Add(GrammarErrorLevel.Conflict, state, Resources.ErrSRConflict, state, shiftReduceConflicts.ToString());
                }

                if (reduceReduceConflicts.Count > 0)
                {
                    this._language.Errors.Add(GrammarErrorLevel.Conflict, state, Resources.ErrRRConflict, state, reduceReduceConflicts.ToString());
                }
                //Create default actions for these conflicts. For shift-reduce, default action is shift, and shift action already
                // exist for all shifts from the state, so we don't need to do anything, only report it
                //For reduce-reduce create reduce actions for the first reduce item (whatever comes first in the set).
                foreach (var conflict in reduceReduceConflicts)
                {
                    var reduceItems = stateData.ReduceItems.SelectByLookahead(conflict);
                    var firstProd = reduceItems.First().Core.Production;
                    var action = new ReduceParserAction(firstProd);
                    state.Actions[conflict] = action;
                }
                //stateData.Conflicts.Clear(); -- do not clear them, let the set keep the auto-resolved conflicts, may find more use for this later
            }
        }

        #endregion

        #region final actions: creating remaining reduce actions, computing expected terminals, cleaning up state data
        //Create reduce actions for states with a single reduce item (and no shifts)
        private void CreateRemainingReduceActions()
        {
            foreach (var state in this._data.States)
            {
                if (state.DefaultAction != null)
                {
                    continue;
                }

                var stateData = state.BuilderData;
                if (stateData.ShiftItems.Count == 0 && stateData.ReduceItems.Count == 1)
                {
                    state.DefaultAction = ReduceParserAction.Create(stateData.ReduceItems.First().Core.Production);
                    continue; //next state; if we have default reduce action, we don't need to fill actions dictionary for lookaheads
                }
                //create actions
                foreach (var item in state.BuilderData.ReduceItems)
                {
                    var action = ReduceParserAction.Create(item.Core.Production);
                    foreach (var lkh in item.Lookaheads)
                    {
                        if (state.Actions.ContainsKey(lkh))
                        {
                            continue;
                        }

                        state.Actions[lkh] = action;
                    }
                }//foreach item
            }//foreach state
        }

        //Note that for states with a single reduce item the result is empty
        private void ComputeStatesExpectedTerminals()
        {
            foreach (var state in this._data.States)
            {
                state.ExpectedTerminals.UnionWith(state.BuilderData.ShiftTerminals);
                //Add lookaheads from reduce items
                foreach (var reduceItem in state.BuilderData.ReduceItems)
                {
                    state.ExpectedTerminals.UnionWith(reduceItem.Lookaheads);
                }

                this.RemoveTerminals(state.ExpectedTerminals, this._grammar.SyntaxError, this._grammar.Eof);
            }//foreach state
        }

        private void RemoveTerminals(TerminalSet terms, params Terminal[] termsToRemove)
        {
            foreach (var termToRemove in termsToRemove)
            {
                if (terms.Contains(termToRemove))
                {
                    terms.Remove(termToRemove);
                }
            }
        }

        public void CleanupStateData()
        {
            foreach (var state in this._data.States)
            {
                state.ClearData();
            }
        }
        #endregion

        #region Utilities: ComputeLR0ItemSetKey
        //Parser states are distinguished by the subset of kernel LR0 items.
        // So when we derive new LR0-item list by shift operation,
        // we need to find out if we have already a state with the same LR0Item list.
        // We do it by looking up in a state hash by a key - [LR0 item list key].
        // Each list's key is a concatenation of items' IDs separated by ','.
        // Before producing the key for a list, the list must be sorted;
        //   thus we garantee one-to-one correspondence between LR0Item sets and keys.
        // And of course, we count only kernel items (with dot NOT in the first position).
        public static string ComputeLR0ItemSetKey(LR0ItemSet items)
        {
            if (items.Count == 0)
            {
                return string.Empty;
            }
            //Copy non-initial items to separate list, and then sort it
            LR0ItemList itemList = new LR0ItemList();
            foreach (var item in items)
            {
                itemList.Add(item);
            }
            //quick shortcut
            if (itemList.Count == 1)
            {
                return itemList[0].ID.ToString();
            }

            itemList.Sort(CompareLR0Items); //Sort by ID
                                            //now build the key
            StringBuilder sb = new StringBuilder(100);
            foreach (LR0Item item in itemList)
            {
                sb.Append(item.ID);
                sb.Append(",");
            }//foreach
            return sb.ToString();
        }

        private static int CompareLR0Items(LR0Item x, LR0Item y)
        {
            if (x.ID < y.ID)
            {
                return -1;
            }

            if (x.ID == y.ID)
            {
                return 0;
            }

            return 1;
        }
        #endregion

        #region comments
        // Computes set of expected terms in a parser state. While there may be extended list of symbols expected at some point,
        // we want to reorganize and reduce it. For example, if the current state expects all arithmetic operators as an input,
        // it would be better to not list all operators (+, -, *, /, etc) but simply put "operator" covering them all.
        // To achieve this grammar writer can group operators (or any other terminals) into named groups using Grammar's methods
        // AddTermReportGroup, AddNoReportGroup etc. Then instead of reporting each operator separately, Irony would include
        // a single "group name" to represent them all.
        // The "expected report set" is not computed during parser construction (it would bite considerable time), but on demand during parsing,
        // when error is detected and the expected set is actually needed for error message.
        // Multi-threading concerns. When used in multi-threaded environment (web server), the LanguageData would be shared in
        // application-wide cache to avoid rebuilding the parser data on every request. The LanguageData is immutable, except
        // this one case - the expected sets are constructed late by CoreParser on the when-needed basis.
        // We don't do any locking here, just compute the set and on return from this function the state field is assigned.
        // We assume that this field assignment is an atomic, concurrency-safe operation. The worst thing that might happen
        // is "double-effort" when two threads start computing the same set around the same time, and the last one to finish would
        // leave its result in the state field.
        #endregion
        internal static StringSet ComputeGroupedExpectedSetForState(Grammar grammar, ParserState state)
        {
            var terms = new TerminalSet();
            terms.UnionWith(state.ExpectedTerminals);
            var result = new StringSet();
            //Eliminate no-report terminals
            foreach (var group in grammar.TermReportGroups)
            {
                if (group.GroupType == TermReportGroupType.DoNotReport)
                {
                    terms.ExceptWith(group.Terminals);
                }
            }
            //Add normal and operator groups
            foreach (var group in grammar.TermReportGroups)
            {
                if ((group.GroupType == TermReportGroupType.Normal || group.GroupType == TermReportGroupType.Operator) &&
                     terms.Overlaps(group.Terminals))
                {
                    result.Add(group.Alias);
                    terms.ExceptWith(group.Terminals);
                }
            }
            //Add remaining terminals "as is"
            foreach (var terminal in terms)
            {
                result.Add(terminal.ErrorAlias);
            }

            return result;
        }
    }//class
}//namespace


text:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { fetchWeather } from '../actions/index';

class SearchBar extends Component {

    constructor(props) {
        super(props);

        this.state = { term: ''};
        this.onInputChange = this.onInputChange.bind(this);
        this.onFormSubmit = this.onFormSubmit.bind(this);
    }

    onInputChange(e) {
        this.setState({ term: e.target.value});
    }

    onFormSubmit(e) {
        e.preventDefault();

        // fetch weather data
        this.props.fetchWeather(this.state.term);
        // set search term to empty string
        this.setState({ term: '' });
    }

    render() {
        return (
            <form onSubmit={this.onFormSubmit} className="input-group">
                <input
                    placeholder="Enter city name"
                    className="form-control"
                    value={this.state.term}
                    onChange={this.onInputChange} />
                <span className="input-group-btn">
                    <button type="submit" className="btn btn-secondary">Submit</button>
                </span>
            </form>
        );
    }
}

function mapDispatchToProps(dispatch) {
    return bindActionCreators({ fetchWeather }, dispatch);
}

export default connect(null, mapDispatchToProps)(SearchBar);

redpajama_set_name: RedPajamaGithub


text:
namespace mediaslayer
{

DebugGuiFrontend::DebugGuiFrontend()
    : IFrontend(0),
      _w(new MainWindow())
{
    connect(_w.data(), SIGNAL(getMediaContent(MediaQuery)), this, SIGNAL(getMediaContent(MediaQuery)));
    connect(_w.data(), SIGNAL(getMediaObject(quint32)), this, SIGNAL(getMediaObject(quint32)));
    connect(_w.data(), SIGNAL(getPlaylist()), this, SIGNAL(getPlaylist()));
    connect(_w.data(), SIGNAL(getPlaylistIndex()), this, SIGNAL(getPlaylistIndex()));
    connect(_w.data(), SIGNAL(next()), this, SIGNAL(next()));
    connect(_w.data(), SIGNAL(pause()), this, SIGNAL(pause()));
    connect(_w.data(), SIGNAL(play()), this, SIGNAL(play()));
    connect(_w.data(), SIGNAL(previous()), this, SIGNAL(previous()));
    connect(_w.data(), SIGNAL(seek(int)), this, SIGNAL(seek(int)));
    connect(_w.data(), SIGNAL(startImport(QDir)), this, SIGNAL(startImport(QDir)));
    connect(_w.data(), SIGNAL(stop()), this, SIGNAL(stop()));
}

void DebugGuiFrontend::updateMediaContent(MediaQuery resultQuery)
{
    this->_w->updateMediaContent(resultQuery);
}

void DebugGuiFrontend::initialize()
{
    this->_w->initialize();
    this->_w->show();
}

void DebugGuiFrontend::showImportDialog(QMap<QString, MediaObject> newMediaObjects)
{
    this->_w->showImportDialog(newMediaObjects);
}

void DebugGuiFrontend::updatePlaylistIndex(quint32 index)
{
    this->_w->updatePlaylistIndex(index);
}

void DebugGuiFrontend::updatePlaylist(QList<MediaObject> playlist)
{
    this->_w->updatePlaylist(playlist);
}

void DebugGuiFrontend::positionChanged(qint64 progress)
{
    this->_w->positionChanged(progress);
}

void DebugGuiFrontend::durationChanged(qint64 duration)
{
    this->_w->durationChanged(duration);
}

}


text:
var logger = require('../util/logger');
module.exports = function() {
  return function(err, req, res, next) {
    if(err) {
      logger.log(err.message, 'ERROR MESSAGE');
      res.status(500).send(err);
    }
    next();
  }
}


text:
A web based music player that accesses files on the server's local file system,
programmed in Python and Javascript.

This is still a work in progress.

## Dependencies

At Development time:
* Python 3.5 (see `requirements.txt`)
* NodeJS (see `package.json`)
* Taglib (Debian/Ubuntu: `apt-get install libtag1-dev`)
* The Sass compiler (Debian/Ubuntu `apt-get install ruby-sass`)

Python and Node dependencies can by installed by simply executing `make deps`.

At runtime, only Python 3.5 and the libraries listed in `requirements.txt` are needed.

## Compiling

Use `make` to build the production variant of the application. `make debug` produces
the development version which includes, for example, unoptimized Javascript.

After the successful termination of `make`, the application can be found inside the
`build/dist` directory.

## Running

Inside the `dist` directory, execute `main.py`. See `--help` for supported options.

## LICENSE

MIT. See `LICENSE` file.


text:
import Component from '../Component'
import Mapper from './Mapper'
import SortedDemuxer from './SortedDemuxer'

const Memorizer = () => {
  let memory

  return Component({
    inputs: ['memory', 'value'],
    components: {
      memory: Component(v => { memory = v }),
      mapper: Mapper(value => ({value, memory})),
      demuxer: SortedDemuxer('memory', 'value')
    },
    connections: [
      ['in.memory', 'memory'],
      ['in.value', 'mapper'],
      ['mapper', 'out'],
      ['in', 'demuxer'],
      ['demuxer.memory', 'memory'],
      ['demuxer.value', 'mapper']
    ]
  })
}

export default Memorizer


text:
namespace blink {

#ifndef NDEBUG

static WTF::String paintPhaseAsDebugString(int paintPhase)
{
    // Must be kept in sync with PaintPhase.
    switch (paintPhase) {
    case 0: return "PaintPhaseBlockBackground";
    case 1: return "PaintPhaseChildBlockBackground";
    case 2: return "PaintPhaseChildBlockBackgrounds";
    case 3: return "PaintPhaseFloat";
    case 4: return "PaintPhaseForeground";
    case 5: return "PaintPhaseOutline";
    case 6: return "PaintPhaseChildOutlines";
    case 7: return "PaintPhaseSelfOutline";
    case 8: return "PaintPhaseSelection";
    case 9: return "PaintPhaseCollapsedTableBorders";
    case 10: return "PaintPhaseTextClip";
    case 11: return "PaintPhaseMask";
    case DisplayItem::PaintPhaseMax: return "PaintPhaseClippingMask";
    default:
        ASSERT_NOT_REACHED();
        return "Unknown";
    }
}

#define PAINT_PHASE_BASED_DEBUG_STRINGS(Category) \
    if (type >= DisplayItem::Category##PaintPhaseFirst && type <= DisplayItem::Category##PaintPhaseLast) \
        return #Category + paintPhaseAsDebugString(type - DisplayItem::Category##PaintPhaseFirst);

#define DEBUG_STRING_CASE(DisplayItemName) \
    case DisplayItem::DisplayItemName: return #DisplayItemName

#define DEFAULT_CASE default: ASSERT_NOT_REACHED(); return "Unknown"

static WTF::String specialDrawingTypeAsDebugString(DisplayItem::Type type)
{
    switch (type) {
        DEBUG_STRING_CASE(BoxDecorationBackground);
        DEBUG_STRING_CASE(Caret);
        DEBUG_STRING_CASE(ColumnRules);
        DEBUG_STRING_CASE(DebugRedFill);
        DEBUG_STRING_CASE(DragImage);
        DEBUG_STRING_CASE(SVGImage);
        DEBUG_STRING_CASE(LinkHighlight);
        DEBUG_STRING_CASE(PageOverlay);
        DEBUG_STRING_CASE(PageWidgetDelegateBackgroundFallback);
        DEBUG_STRING_CASE(PopupContainerBorder);
        DEBUG_STRING_CASE(PopupListBoxBackground);
        DEBUG_STRING_CASE(PopupListBoxRow);
        DEBUG_STRING_CASE(Resizer);
        DEBUG_STRING_CASE(SVGClip);
        DEBUG_STRING_CASE(SVGFilter);
        DEBUG_STRING_CASE(SVGMask);
        DEBUG_STRING_CASE(ScrollbarBackButtonEnd);
        DEBUG_STRING_CASE(ScrollbarBackButtonStart);
        DEBUG_STRING_CASE(ScrollbarBackground);
        DEBUG_STRING_CASE(ScrollbarBackTrack);
        DEBUG_STRING_CASE(ScrollbarCorner);
        DEBUG_STRING_CASE(ScrollbarForwardButtonEnd);
        DEBUG_STRING_CASE(ScrollbarForwardButtonStart);
        DEBUG_STRING_CASE(ScrollbarForwardTrack);
        DEBUG_STRING_CASE(ScrollbarHorizontal);
        DEBUG_STRING_CASE(ScrollbarThumb);
        DEBUG_STRING_CASE(ScrollbarTickmarks);
        DEBUG_STRING_CASE(ScrollbarTrackBackground);
        DEBUG_STRING_CASE(ScrollbarVertical);
        DEBUG_STRING_CASE(SelectionGap);
        DEBUG_STRING_CASE(SelectionTint);
        DEBUG_STRING_CASE(TableCellBackgroundFromSelfPaintingRow);
        DEBUG_STRING_CASE(VideoBitmap);
        DEBUG_STRING_CASE(WebPlugin);
        DEFAULT_CASE;
    }
}

static WTF::String drawingTypeAsDebugString(DisplayItem::Type type)
{
    PAINT_PHASE_BASED_DEBUG_STRINGS(Drawing);
    return "Drawing" + specialDrawingTypeAsDebugString(type);
}

static WTF::String clipTypeAsDebugString(DisplayItem::Type type)
{
    PAINT_PHASE_BASED_DEBUG_STRINGS(ClipBox);
    PAINT_PHASE_BASED_DEBUG_STRINGS(ClipColumnBounds);
    PAINT_PHASE_BASED_DEBUG_STRINGS(ClipLayerFragment);

    switch (type) {
        DEBUG_STRING_CASE(ClipFileUploadControlRect);
        DEBUG_STRING_CASE(ClipFrameToVisibleContentRect);
        DEBUG_STRING_CASE(ClipFrameScrollbars);
        DEBUG_STRING_CASE(ClipLayerBackground);
        DEBUG_STRING_CASE(ClipLayerColumnBounds);
        DEBUG_STRING_CASE(ClipLayerFilter);
        DEBUG_STRING_CASE(ClipLayerForeground);
        DEBUG_STRING_CASE(ClipLayerParent);
        DEBUG_STRING_CASE(ClipLayerOverflowControls);
        DEBUG_STRING_CASE(ClipNodeImage);
        DEBUG_STRING_CASE(ClipPopupListBoxFrame);
        DEBUG_STRING_CASE(ClipSelectionImage);
        DEBUG_STRING_CASE(PageWidgetDelegateClip);
        DEBUG_STRING_CASE(TransparencyClip);
        DEFAULT_CASE;
    }
}

static String transform3DTypeAsDebugString(DisplayItem::Type type)
{
    switch (type) {
        DEBUG_STRING_CASE(Transform3DElementTransform);
        DEFAULT_CASE;
    }
}

WTF::String DisplayItem::typeAsDebugString(Type type)
{
    if (isDrawingType(type))
        return drawingTypeAsDebugString(type);
    if (isCachedType(type))
        return "Cached" + drawingTypeAsDebugString(cachedTypeToDrawingType(type));
    if (isClipType(type))
        return clipTypeAsDebugString(type);
    if (isEndClipType(type))
        return "End" + clipTypeAsDebugString(endClipTypeToClipType(type));

    PAINT_PHASE_BASED_DEBUG_STRINGS(FloatClip);
    if (isEndFloatClipType(type))
        return "End" + typeAsDebugString(endFloatClipTypeToFloatClipType(type));

    PAINT_PHASE_BASED_DEBUG_STRINGS(Scroll);
    if (isEndScrollType(type))
        return "End" + typeAsDebugString(endScrollTypeToScrollType(type));

    if (isTransform3DType(type))
        return transform3DTypeAsDebugString(type);
    if (isEndTransform3DType(type))
        return "End" + transform3DTypeAsDebugString(endTransform3DTypeToTransform3DType(type));

    PAINT_PHASE_BASED_DEBUG_STRINGS(SubtreeCached);
    PAINT_PHASE_BASED_DEBUG_STRINGS(BeginSubtree);
    PAINT_PHASE_BASED_DEBUG_STRINGS(EndSubtree);

    switch (type) {
        DEBUG_STRING_CASE(BeginFilter);
        DEBUG_STRING_CASE(EndFilter);
        DEBUG_STRING_CASE(BeginCompositing);
        DEBUG_STRING_CASE(EndCompositing);
        DEBUG_STRING_CASE(BeginTransform);
        DEBUG_STRING_CASE(EndTransform);
        DEBUG_STRING_CASE(BeginClipPath);
        DEBUG_STRING_CASE(EndClipPath);
        DEBUG_STRING_CASE(BeginFixedPosition);
        DEBUG_STRING_CASE(EndFixedPosition);
        DEBUG_STRING_CASE(BeginFixedPositionContainer);
        DEBUG_STRING_CASE(EndFixedPositionContainer);
        DEFAULT_CASE;
    }
}

WTF::String DisplayItem::asDebugString() const
{
    WTF::StringBuilder stringBuilder;
    stringBuilder.append('{');
    dumpPropertiesAsDebugString(stringBuilder);
    stringBuilder.append('}');
    return stringBuilder.toString();
}

void DisplayItem::dumpPropertiesAsDebugString(WTF::StringBuilder& stringBuilder) const
{
    stringBuilder.append(String::format("client: \"%p", client()));
    if (!clientDebugString().isEmpty()) {
        stringBuilder.append(' ');
        stringBuilder.append(clientDebugString());
    }
    stringBuilder.append("\", type: \"");
    stringBuilder.append(typeAsDebugString(type()));
    stringBuilder.append('"');
    if (m_id.scopeContainer)
        stringBuilder.append(String::format(", scope: \"%p,%d\"", m_id.scopeContainer, m_id.scopeId));
}

#endif

} // namespace blink


text:
package waitmap

import (
	"sync"
)

// TODO use sync/atomic wherever possible

// An entry in a WaitMap.
type entry struct {
	mutx *sync.Mutex
	cond *sync.Cond
	data interface{}
	ok   bool
}

type WaitMap struct {
	lock *sync.Mutex
	ents map[interface{}]*entry
}

func New() *WaitMap {
	return &WaitMap{
		lock: new(sync.Mutex),
		ents: make(map[interface{}]*entry),
	}
}

func NewCap(c int) *WaitMap {
	return &WaitMap{
		lock: new(sync.Mutex),
		ents: make(map[interface{}]*entry, c),
	}
}

// Retrieves the value mapped to by k. If no such value is yet available, waits
// until one is, and then returns that. Otherwise, it returns the value
// available at the time Get is called.
func (m *WaitMap) Get(k interface{}) interface{} {
	m.lock.Lock()
	e, ok := m.ents[k]
	if !ok {
		mutx := new(sync.Mutex)
		e = &entry{
			mutx: mutx,
			cond: sync.NewCond(mutx),
			data: nil,
			ok:   false,
		}
		m.ents[k] = e
	}
	m.lock.Unlock()

	// If e.ok is true, e.data exists and can never cease to exist. We need
	// this check to avoid using a nil e.mutx. We could also actually check
	// e.mutx to see if it's nil, but this accomplishes the same thing and
	// will be slightly faster on average (since we will often avoid
	// unnecessarily messing with the mutex).
	if e.ok {
		return e.data
	}
	e.mutx.Lock()
	e.cond.Wait()
	e.mutx.Unlock()
	return e.data
}

// Maps the given key and value, waking any waiting calls to Get. Returns false
// (and changes nothing) if the key is already in the map.
func (m *WaitMap) Set(k interface{}, v interface{}) bool {
	m.lock.Lock()
	e, ok := m.ents[k]
	if !ok {
		mutx := new(sync.Mutex)
		e := &entry{
			mutx: mutx,
			cond: sync.NewCond(mutx),
			data: v,
			ok:   true,
		}
		m.ents[k] = e
		m.lock.Unlock()
		return true
	}
	if e.ok {
		m.lock.Unlock()
		return false
	}
	e.mutx.Lock()
	m.lock.Unlock()
	e.data = v
	e.ok = true
	e.cond.Broadcast()
	e.mutx.Unlock()
	return true
}

// Returns true if k is a key in the map.
func (m *WaitMap) Check(k interface{}) bool {
	m.lock.Lock()
	e, ok := m.ents[k]
	m.lock.Unlock()
	if !ok {
		return false
	}
	return e.ok
}


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

import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable;
import com.google.devtools.build.lib.concurrent.ThreadSafety.ThreadSafe;
import com.google.devtools.build.lib.packages.NoSuchTargetException;
import com.google.devtools.build.skyframe.SkyValue;
import javax.annotation.Nullable;

/**
 * A <i>transitive</i> target reference that, when built in skyframe, loads the entire
 * transitive closure of a target.
 */
@Immutable
@ThreadSafe
public class TransitiveTargetValue implements SkyValue {
  private final NestedSet<Label> transitiveTargets;
  private final boolean encounteredLoadingError;
  @Nullable private final NoSuchTargetException errorLoadingTarget;

  private TransitiveTargetValue(
      NestedSet<Label> transitiveTargets,
      boolean encounteredLoadingError,
      @Nullable NoSuchTargetException errorLoadingTarget) {
    this.transitiveTargets = transitiveTargets;
    this.encounteredLoadingError = encounteredLoadingError;
    this.errorLoadingTarget = errorLoadingTarget;
  }

  static TransitiveTargetValue unsuccessfulTransitiveLoading(
      NestedSet<Label> transitiveTargets, @Nullable NoSuchTargetException errorLoadingTarget) {
    return new TransitiveTargetValue(
        transitiveTargets, /*encounteredLoadingError=*/ true, errorLoadingTarget);
  }

  static TransitiveTargetValue successfulTransitiveLoading(NestedSet<Label> transitiveTargets) {
    return new TransitiveTargetValue(transitiveTargets, /*encounteredLoadingError=*/ false, null);
  }

  /** Returns the error, if any, from loading the target. */
  @Nullable
  public NoSuchTargetException getErrorLoadingTarget() {
    return errorLoadingTarget;
  }

  /** Returns the targets that were transitively loaded. */
  public NestedSet<Label> getTransitiveTargets() {
    return transitiveTargets;
  }

  public boolean encounteredLoadingError() {
    return encounteredLoadingError;
  }
}


text:
"""Tests for the devolo Home Control integration."""
from collections.abc import Awaitable, Callable
from unittest.mock import patch

from aiohttp import ClientWebSocketResponse
from devolo_home_control_api.exceptions.gateway import GatewayOfflineError
import pytest

from homeassistant.components.binary_sensor import DOMAIN as BINARY_SENSOR_DOMAIN
from homeassistant.components.devolo_home_control import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
from homeassistant.setup import async_setup_component

from . import configure_integration
from .mocks import HomeControlMock, HomeControlMockBinarySensor

async def test_setup_entry(hass: HomeAssistant, mock_zeroconf):
    """Test setup entry."""
    entry = configure_integration(hass)
    with patch("homeassistant.components.devolo_home_control.HomeControl"):
        await hass.config_entries.async_setup(entry.entry_id)
        assert entry.state is ConfigEntryState.LOADED

@pytest.mark.credentials_invalid
async def test_setup_entry_credentials_invalid(hass: HomeAssistant):
    """Test setup entry fails if credentials are invalid."""
    entry = configure_integration(hass)
    await hass.config_entries.async_setup(entry.entry_id)
    assert entry.state is ConfigEntryState.SETUP_ERROR

@pytest.mark.maintenance
async def test_setup_entry_maintenance(hass: HomeAssistant):
    """Test setup entry fails if mydevolo is in maintenance mode."""
    entry = configure_integration(hass)
    await hass.config_entries.async_setup(entry.entry_id)
    assert entry.state is ConfigEntryState.SETUP_RETRY

async def test_setup_gateway_offline(hass: HomeAssistant, mock_zeroconf):
    """Test setup entry fails on gateway offline."""
    entry = configure_integration(hass)
    with patch(
        "homeassistant.components.devolo_home_control.HomeControl",
        side_effect=GatewayOfflineError,
    ):
        await hass.config_entries.async_setup(entry.entry_id)
        assert entry.state is ConfigEntryState.SETUP_RETRY

async def test_unload_entry(hass: HomeAssistant):
    """Test unload entry."""
    entry = configure_integration(hass)
    with patch("homeassistant.components.devolo_home_control.HomeControl"):
        await hass.config_entries.async_setup(entry.entry_id)
        await hass.async_block_till_done()
        await hass.config_entries.async_unload(entry.entry_id)
        assert entry.state is ConfigEntryState.NOT_LOADED

async def test_remove_device(
    hass: HomeAssistant,
    hass_ws_client: Callable[[HomeAssistant], Awaitable[ClientWebSocketResponse]],
):
    """Test removing a device."""
    assert await async_setup_component(hass, "config", {})
    entry = configure_integration(hass)
    test_gateway = HomeControlMockBinarySensor()
    with patch(
        "homeassistant.components.devolo_home_control.HomeControl",
        side_effect=[test_gateway, HomeControlMock()],
    ):
        await hass.config_entries.async_setup(entry.entry_id)
        await hass.async_block_till_done()

        device_registry = dr.async_get(hass)
        device_entry = device_registry.async_get_device(identifiers={(DOMAIN, "Test")})
        assert device_entry

        client = await hass_ws_client(hass)
        await client.send_json(
            {
                "id": 1,
                "type": "config/device_registry/remove_config_entry",
                "config_entry_id": entry.entry_id,
                "device_id": device_entry.id,
            }
        )
        response = await client.receive_json()
        assert response["success"]
        assert device_registry.async_get_device(identifiers={(DOMAIN, "Test")}) is None
        assert hass.states.get(f"{BINARY_SENSOR_DOMAIN}.test") is None


text:
package cc.engeld;

public class Bubble implements SortElements {

    @Override
    public void sortItems(Integer[] elementos) {
        Integer aux;
        for (Integer i = 0; i < elementos.length - 1; i++) {
            for (Integer j = 0; j < elementos.length - 1; j++) {
                if (elementos[j].compareTo(elementos[j + 1]) == MAIOR) {
                    aux = elementos[j];
                    elementos[j] = elementos[j + 1];
                    elementos[j + 1] = aux;
                }
            }
        }
    }
}


text:
package org.springframework.richclient.list;

import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import java.util.Map;

import javax.swing.ComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.UIManager;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
import javax.swing.text.PlainDocument;

import org.springframework.util.Assert;

/**
 * Provides AutoCompletion to a combobox. Works with the editor of the JComboBox
 * to make the conversion between strings and the objects of the JComboBox
 * model.

 * Based on code contributed to the public domain by Thomas Bierhance
 * (http://www.orbital-computer.de/JComboBox/)
 *
 * @author Peter De Bruycker
 * @author Thomas Bierhance
 */
public class ComboBoxAutoCompletion extends PlainDocument {

    private final ChangeHandler changeHandler = new ChangeHandler();

    private final JComboBox comboBox;

    private final JTextComponent editor;

    boolean hitBackspace;

    boolean hitBackspaceOnSelection;

    private Map item2string = new HashMap();

    private ComboBoxModel model;

    private boolean selectingValue;

    /**
     * Adds autocompletion support to the given JComboBox.
     *
     * @param comboBox
     *            the combobox
     */
    public ComboBoxAutoCompletion(final JComboBox comboBox) {
        Assert.notNull(comboBox, "The ComboBox cannot be null.");
        Assert.isTrue(!comboBox.isEditable(), "The ComboBox must not be editable.");
        Assert.isTrue(comboBox.getEditor().getEditorComponent() instanceof JTextComponent,
                "Only ComboBoxes with JTextComponent as editor are supported.");

        this.comboBox = comboBox;
        comboBox.setEditable(true);

        model = comboBox.getModel();
        model.addListDataListener(changeHandler);

        editor = (JTextComponent)comboBox.getEditor().getEditorComponent();
        editor.setDocument(this);
        editor.addFocusListener(changeHandler);
        editor.addKeyListener(changeHandler);

        fillItem2StringMap();

        // Handle initially selected object
        Object selected = comboBox.getSelectedItem();
        comboBox.getEditor().setItem(selected);
    }

    private void fillItem2StringMap() {
        editor.setDocument(new PlainDocument());

        item2string.clear();

        JTextComponent editor = (JTextComponent)comboBox.getEditor().getEditorComponent();

        // get current item of editor
        Object currentItem = comboBox.getEditor().getItem();
        for (int i = 0; i < comboBox.getItemCount(); i++) {
            Object item = comboBox.getItemAt(i);
            comboBox.getEditor().setItem(item);
            item2string.put(item, editor.getText());
        }
        // reset item in editor
        comboBox.getEditor().setItem(currentItem);

        editor.setDocument(this);
    }

    private String getStringFor(Object item) {
        return (String)item2string.get(item);
    }

    private void highlightCompletedText(int start) {
        editor.setCaretPosition(getLength());
        editor.moveCaretPosition(start);
    }

    /**
     * @see javax.swing.text.Document#insertString(int, java.lang.String,
     *      javax.swing.text.AttributeSet)
     */
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
        // ignore empty insert
        if (str == null || str.length() == 0)
            return;
        if(selectingValue)
            return;
        // check offset position
        if (offs < 0 || offs > getLength())
            throw new BadLocationException("Invalid offset - must be >= 0 and <= " + getLength(), offs);

        // construct the resulting string
        String currentText = getText(0, getLength());
        String beforeOffset = currentText.substring(0, offs);
        String afterOffset = currentText.substring(offs, currentText.length());
        String futureText = beforeOffset + str + afterOffset;

        // lookup and select a matching item
        Object item = lookupItem(futureText);
        if (item != null) {
            selectingValue = true;
            try {
                comboBox.setSelectedItem(item);
            } finally {
                selectingValue = false;
            }
        }
        else {
            // keep old item selected if there is no match
            item = comboBox.getSelectedItem();
            // imitate no insert (later on offs will be incremented by
            // str.length(): selection won't move forward)
            offs = offs - str.length();
            // provide feedback to the user that his input has been received but
            // can not be accepted
            // comboBox.getToolkit().beep();
            // when available use:
            UIManager.getLookAndFeel().provideErrorFeedback(comboBox);
        }

        // display the completed string
        String itemString = item == null ? "" : getStringFor(item);
        setText(itemString);

        // if the user selects an item via mouse the the whole string will be
        // inserted.
        // highlight the entire text if this happens.
        if (itemString != null) {
            if (itemString.equals(str) && offs == 0) {
                highlightCompletedText(0);
            }
            else {
                highlightCompletedText(offs + str.length());
                // show popup when the user types
                if (comboBox.isShowing()) {
                    comboBox.setPopupVisible(true);
                }
            }
        }
    }

    private Object lookupItem(String pattern) {
        Object selectedItem = model.getSelectedItem();
        // only search for a different item if the currently selected does not
        // match
        if (selectedItem != null && startsWithIgnoreCase(getStringFor(selectedItem), pattern)) {
            return selectedItem;
        }

        // iterate over all items
        for (int i = 0, n = model.getSize(); i < n; i++) {
            Object currentItem = model.getElementAt(i);
            // current item starts with the pattern?
            if (startsWithIgnoreCase(getStringFor(currentItem), pattern)) {
                return currentItem;
            }
        }

        // no item starts with the pattern => return null
        return null;
    }

    /**
     * @see javax.swing.text.Document#remove(int, int)
     */
    public void remove(int offs, int length) throws BadLocationException {
        // ignore no deletion
        if (length == 0)
            return;
        // check positions
        if (offs < 0 || offs > getLength() || length < 0 || (offs + length) > getLength())
            throw new BadLocationException("Invalid parameters.", offs);

        if (hitBackspace) {
            // user hit backspace => move the selection backwards
            // old item keeps being selected
            if (offs > 0) {
                if (hitBackspaceOnSelection)
                    offs--;
            }
            else {
                // User hit backspace with the cursor positioned on the start =>
                // beep
                comboBox.getToolkit().beep();
                // when available use:
                // UIManager.getLookAndFeel().provideErrorFeedback(comboBox);
            }
            highlightCompletedText(offs);
            // show popup when the user types
            if (comboBox.isShowing())
                comboBox.setPopupVisible(true);
        }
        else {
            super.remove(offs, length);
        }
    }

    private void setText(String text) throws BadLocationException {
        // remove all text and insert the new text
        super.remove(0, getLength());
        super.insertString(0, text, null);
    }

    // checks if str1 starts with str2 - ignores case
    private boolean startsWithIgnoreCase(String str1, String str2) {
        return str1 != null && str2 != null && str1.toUpperCase().startsWith(str2.toUpperCase());
    }

    private final class ChangeHandler extends KeyAdapter implements FocusListener, ListDataListener {

        // Highlight whole text when user hits enter
        // Register when user hits backspace
        public void keyPressed(KeyEvent e) {
            hitBackspace = false;
            switch (e.getKeyCode()) {
            case KeyEvent.VK_ENTER:
                highlightCompletedText(0);
                break;
            // determine if the pressed key is backspace (needed by the remove
            // method)
            case KeyEvent.VK_BACK_SPACE:
                hitBackspace = true;
                hitBackspaceOnSelection = editor.getSelectionStart() != editor.getSelectionEnd();
                break;
            // ignore delete key
            case KeyEvent.VK_DELETE:
                e.consume();
                ComboBoxAutoCompletion.this.comboBox.getToolkit().beep();
                break;
            }
        }

        // Bug 5100422 on Java 1.5: Editable JComboBox won't hide popup when
        // tabbing out
        private boolean hidePopupOnFocusLoss = System.getProperty("java.version").startsWith("1.5");

        public void focusGained(FocusEvent e) {
            // Highlight whole text when gaining focus
            highlightCompletedText(0);
        }

        public void focusLost(FocusEvent e) {
            // Workaround for Bug 5100422 - Hide Popup on focus loss
            if (hidePopupOnFocusLoss)
                ComboBoxAutoCompletion.this.comboBox.setPopupVisible(false);
        }

        public void contentsChanged(ListDataEvent e) {
            if(!selectingValue)
                fillItem2StringMap();
        }

        public void intervalAdded(ListDataEvent e) {
            fillItem2StringMap();
        }

        public void intervalRemoved(ListDataEvent e) {
            fillItem2StringMap();
        }
    }
}


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

namespace Meru.Common.Providers
{
    public interface IBotProvider : IRunnable
    {
        event Func<IMessage, Task> OnMessageDelete;
        event Func<IMessage, Task> OnMessageEdit;
        event Func<IMessage, Task> OnMessageReceive;

		event Func<IGuild, Task> OnGuildCreate;
		event Func<IGuild, Task> OnGuildUpdate;

		event Func<IUser, Task> OnGuildMemberAdd;
		event Func<IUser, Task> OnGuildMemberRemove;
		event Func<IUser, Task> OnGuildMemberUpdate;

		event Func<IUser, Task> OnUserUpdate;
	}
}


text:
package proxy

import (
	"github.com/realglobe-Inc/go-lib/rglog"
)

const logRoot = "github.com/realglobe-Inc"

var log = rglog.Logger(logRoot + "/edo-access-proxy/api/proxy")


text:
/*
* LOCAL includes
*/
#include "camera.hpp"

namespace alros
{
namespace recorder
{

CameraRecorder::CameraRecorder( const std::string& topic_, float buffer_frequency ):
  buffer_frequency_(buffer_frequency),
  buffer_duration_( helpers::bufferDefaultDuration ),
  counter_(1)
{
  topic_info_ = topic_ + "/camera_info";
  topic_img_ = topic_ + "/image_raw";
}

void CameraRecorder::write(const sensor_msgs::ImagePtr& img, const sensor_msgs::CameraInfo& camera_info)
{
  if (!img->header.stamp.isZero()) {
    gr_->write(topic_img_, *img, img->header.stamp);
  }
  else {
    gr_->write(topic_img_, *img);
  }
  if (!camera_info.header.stamp.isZero()) {
    gr_->write(topic_info_, camera_info, camera_info.header.stamp);
  }
  else {
    gr_->write(topic_info_, camera_info);
  }
}

void CameraRecorder::writeDump(const ros::Time& time)
{
  boost::mutex::scoped_lock lock_write_buffer( mutex_ );
  boost::circular_buffer< std::pair<sensor_msgs::ImagePtr, sensor_msgs::CameraInfo> >::iterator it;
  for (it = buffer_.begin(); it != buffer_.end(); it++)
  {
    if (it->first != NULL)
    {
      write(it->first, it->second);
    }
  }
}

void CameraRecorder::reset(boost::shared_ptr<GlobalRecorder> gr, float conv_frequency)
{
  gr_ = gr;
  conv_frequency_ = conv_frequency;
  max_counter_ = static_cast<int>(conv_frequency/buffer_frequency_);
  buffer_size_ = static_cast<size_t>(buffer_duration_*(conv_frequency/max_counter_));
  buffer_.resize(buffer_size_);
  is_initialized_ = true;
}

void CameraRecorder::bufferize( const sensor_msgs::ImagePtr& img, const sensor_msgs::CameraInfo& camera_info )
{
  boost::mutex::scoped_lock lock_bufferize( mutex_ );
  if (counter_ < max_counter_)
  {
    counter_++;
  }
  else
  {
    counter_ = 1;
    buffer_.push_back(std::make_pair(img, camera_info));
  }
}

void CameraRecorder::setBufferDuration(float duration)
{
  boost::mutex::scoped_lock lock_bufferize( mutex_ );
  buffer_size_ = static_cast<size_t>(duration*(conv_frequency_/max_counter_));
  buffer_duration_ = duration;
  buffer_.set_capacity(buffer_size_);
}

} //publisher
} // alros


text:
package stereosystem.soundsystemwithjavaconfig;

/**
 * Created by luosf on 2017/5/11.
 */
public interface MediaPlayer {

    void play();
}


text:
package io.crate.analyze;

import io.crate.metadata.ReferenceInfos;
import io.crate.metadata.TableIdent;
import io.crate.metadata.table.TableInfo;

public class AddColumnAnalyzedStatement extends AbstractDDLAnalyzedStatement {

    private final ReferenceInfos referenceInfos;
    private TableInfo tableInfo;
    private AnalyzedTableElements analyzedTableElements;
    private boolean newPrimaryKeys = false;

    protected AddColumnAnalyzedStatement(ReferenceInfos referenceInfos) {
        this.referenceInfos = referenceInfos;
    }

    public void table(TableIdent tableIdent) {
        tableInfo = referenceInfos.getWritableTable(tableIdent);
    }

    public TableInfo table() {
        return this.tableInfo;
    }

    @Override
    public <C, R> R accept(AnalyzedStatementVisitor<C, R> visitor, C context) {
        return visitor.visitAddColumnStatement(this, context);
    }

    public void analyzedTableElements(AnalyzedTableElements analyzedTableElements) {
        this.analyzedTableElements = analyzedTableElements;
    }

    public AnalyzedTableElements analyzedTableElements() {
        return this.analyzedTableElements;
    }

    public void newPrimaryKeys(boolean newPrimaryKeys) {
        this.newPrimaryKeys = newPrimaryKeys;
    }

    public boolean newPrimaryKeys() {
        return this.newPrimaryKeys;
    }
}


text:
import type {RNTesterModuleExample} from '../../types/RNTesterTypes';
import * as React from 'react';
import RNTesterButton from '../../components/RNTesterButton';
import ToggleNativeDriver from './utils/ToggleNativeDriver';
import {Text, StyleSheet, View, Animated} from 'react-native';
import RNTConfigurationBlock from '../../components/RNTConfigurationBlock';

const styles = StyleSheet.create({
  content: {
    backgroundColor: 'deepskyblue',
    borderWidth: 1,
    borderColor: 'dodgerblue',
    padding: 20,
    margin: 20,
    borderRadius: 10,
    alignItems: 'center',
  },
});

function FadeInView({
  useNativeDriver,
  children,
}: {
  useNativeDriver: boolean,
  children: React.Node,
}) {
  //opacity 0
  const [fadeAnim] = React.useState(() => new Animated.Value(0));
  React.useEffect(() => {
    Animated.timing(
      // Uses easing functions
      fadeAnim, // The value to drive
      {
        // Target
        toValue: 1,

        // Configuration
        duration: 2000,

        useNativeDriver,
      },
    ).start(); // Don't forget start!
  }, [fadeAnim, useNativeDriver]);

  return (
    <Animated.View // Special animatable View
      style={{
        opacity: fadeAnim, // Binds
      }}>
      {children}
    </Animated.View>
  );
}

function FadeInExample(): React.Node {
  const [show, setShow] = React.useState(true);
  const [useNativeDriver, setUseNativeDriver] = React.useState(false);
  return (
    <View>
      <RNTConfigurationBlock>
        <ToggleNativeDriver
          value={useNativeDriver}
          onValueChange={setUseNativeDriver}
        />
      </RNTConfigurationBlock>
      <RNTesterButton testID="toggle-button" onPress={() => setShow(!show)}>
        Press to {show ? 'Hide' : 'Show'}
      </RNTesterButton>
      {show && (
        <FadeInView useNativeDriver={useNativeDriver}>
          <View testID="fade-in-view" style={styles.content}>
            <Text>FadeInView</Text>
          </View>
        </FadeInView>
      )}
    </View>
  );
}

export default ({
  title: 'FadeInView',
  name: 'fadeInView',
  description: ('Uses a simple timing animation to ' +
    'bring opacity from 0 to 1 when the component ' +
    'mounts.': string),
  expect:
    'FadeInView box should animate from opacity 0 to 1. \nExpect no animation when hiding.\nHiding the view mid-animation should not affect next animation.',
  render: (): React.Node => <FadeInExample />,
}: RNTesterModuleExample);


text:
Uber chameleon

https://eng.uber.com/chameleon/


text:
const { readFile, writeFile, rename } = require('fs').promises;
const debug = require('debug')('liftie:cache');

module.exports = cache;

function cache(file) {
  const fileNew = file + '.new';
  let data;
  let promiseData;
  let loaded = 0;
  let timeout;

  function get(key) {
    if (!loaded) {
      return;
    }
    return data[key];
  }

  function set(key, value) {
    if (!loaded) {
      return;
    }
    data[key] = value;
    if (!timeout) {
      timeout = setTimeout(dump, 60000); // 1 minute
    }
  }

  async function load() {
    async function readData() {
      try {
        debug('Reading from %s', file);
        const str = await readFile(file, { encoding: 'utf8' });
        return JSON.parse(str);
      } catch(e) {
        console.error('Cannot read cache data', e);
        return {};
      }
    }

    if (!promiseData) {
      promiseData = readData();
    }
    data = await promiseData;
    debug('Data is: %j', data);
    return ++loaded;
  }

  async function dump() {
    timeout = undefined;
    if (loaded < 1) {
      return;
    }
    try {
      const str = JSON.stringify(data);
      debug('Writing to %s %s...', fileNew, str.slice(0, 100));
      await writeFile(fileNew, str, { encoding: 'utf8' });
      await rename(fileNew, file);
    }
    catch (e) {
      console.error('Cannot write cache data', e);
    }
  }

  return {
    get,
    set,
    load
  };
}


text:
from string import Template
from datetime import date

shillingDir = "./";

inFile     = shillingDir+"/share/qt/Info.plist"
outFile    = "Shilling-Qt.app/Contents/Info.plist"
version    = "unknown";

fileForGrabbingVersion = shillingDir+"shilling-qt.pro"
for line in open(fileForGrabbingVersion):
	lineArr = line.replace(" ", "").split("=");
	if lineArr[0].startswith("VERSION"):
		version = lineArr[1].replace("\n", "");

fIn = open(inFile, "r")
fileContent = fIn.read()
s = Template(fileContent)
newFileContent = s.substitute(VERSION=version,YEAR=date.today().year)

fOut = open(outFile, "w");
fOut.write(newFileContent);

print "Info.plist fresh created"


text:
template<typename T>
static T* npc(T* t)
{
    if(!t) throw new ::java::lang::NullPointerException();
    return t;
}

poi::hssf::record::pivottable::DataItemRecord::DataItemRecord(const ::default_init_tag&)
    : super(*static_cast< ::default_init_tag* >(0))
{
    clinit();
}

poi::hssf::record::pivottable::DataItemRecord::DataItemRecord(::poi::hssf::record::RecordInputStream* in)
    : DataItemRecord(*static_cast< ::default_init_tag* >(0))
{
    ctor(in);
}

constexpr int16_t poi::hssf::record::pivottable::DataItemRecord::sid;

void poi::hssf::record::pivottable::DataItemRecord::ctor(::poi::hssf::record::RecordInputStream* in)
{
    super::ctor();
    isxvdData = npc(in)->readUShort();
    iiftab = npc(in)->readUShort();
    df = npc(in)->readUShort();
    isxvd = npc(in)->readUShort();
    isxvi = npc(in)->readUShort();
    ifmt = npc(in)->readUShort();
    name = npc(in)->readString();
}

void poi::hssf::record::pivottable::DataItemRecord::serialize(::poi::util::LittleEndianOutput* out)
{
    npc(out)->writeShort(isxvdData);
    npc(out)->writeShort(iiftab);
    npc(out)->writeShort(df);
    npc(out)->writeShort(isxvd);
    npc(out)->writeShort(isxvi);
    npc(out)->writeShort(ifmt);
    ::poi::util::StringUtil::writeUnicodeString(out, name);
}

int32_t poi::hssf::record::pivottable::DataItemRecord::getDataSize()
{
    return int32_t(2) + int32_t(2) + int32_t(2)+ int32_t(2)+ int32_t(2)+ int32_t(2)+ ::poi::util::StringUtil::getEncodedSize(name);
}

int16_t poi::hssf::record::pivottable::DataItemRecord::getSid()
{
    return sid;
}

java::lang::String* poi::hssf::record::pivottable::DataItemRecord::toString()
{
    auto buffer = new ::java::lang::StringBuffer();
    npc(buffer)->append(u"[SXDI]\n"_j);
    npc(npc(npc(buffer)->append(u"  .isxvdData = "_j))->append(::poi::util::HexDump::shortToHex(isxvdData)))->append(u"\n"_j);
    npc(npc(npc(buffer)->append(u"  .iiftab = "_j))->append(::poi::util::HexDump::shortToHex(iiftab)))->append(u"\n"_j);
    npc(npc(npc(buffer)->append(u"  .df = "_j))->append(::poi::util::HexDump::shortToHex(df)))->append(u"\n"_j);
    npc(npc(npc(buffer)->append(u"  .isxvd = "_j))->append(::poi::util::HexDump::shortToHex(isxvd)))->append(u"\n"_j);
    npc(npc(npc(buffer)->append(u"  .isxvi = "_j))->append(::poi::util::HexDump::shortToHex(isxvi)))->append(u"\n"_j);
    npc(npc(npc(buffer)->append(u"  .ifmt = "_j))->append(::poi::util::HexDump::shortToHex(ifmt)))->append(u"\n"_j);
    npc(buffer)->append(u"[/SXDI]\n"_j);
    return npc(buffer)->toString();
}

extern java::lang::Class *class_(const char16_t *c, int n);

java::lang::Class* poi::hssf::record::pivottable::DataItemRecord::class_()
{
    static ::java::lang::Class* c = ::class_(u"org.apache.poi.hssf.record.pivottable.DataItemRecord", 52);
    return c;
}

int32_t poi::hssf::record::pivottable::DataItemRecord::serialize(int32_t offset, ::int8_tArray* data)
{
    return super::serialize(offset, data);
}

int8_tArray* poi::hssf::record::pivottable::DataItemRecord::serialize()
{
    return super::serialize();
}

java::lang::Class* poi::hssf::record::pivottable::DataItemRecord::getClass0()
{
    return class_();
}


text:
<?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?>
<publishers>
	<publisher name="InjectionPublisher">
		<class>com.pushtechnology.benchmarks.publishers.BroadcastPublisher
		</class>
		<enabled>true</enabled>
		<start>true</start>
        <property name="intervalPauseSeconds">@pauseSeconds@</property>
        <property name="conflationMode">@conflationMode@</property>
		<property name="messageSize">@messageSize@</property>
		<property name="initialMessages">@initialMessages@</property>
		<property name="messageIncrementIntervalInPauses">@messageIncrementIntervalInPauses@</property>
		<property name="messageIncrement">@messageIncrement@</property>
		<property name="initialTopicNum">@initialTopicNum@</property>
		<property name="topicIncrementIntervalInPauses">@topicIncrementIntervalInPauses@</property>
		<property name="topicIncrement">@topicIncrement@</property>
	</publisher>
</publishers>


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>turtledemo.planet_and_moon — ArcherBashPYDocs 1.0.0. documentation</title>

  <link href='https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic|Roboto+Slab:400,700|Inconsolata:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>

    <link rel="stylesheet" href="../../_static/css/theme.css" type="text/css" />

    <link rel="top" title="ArcherBashPYDocs 1.0.0. documentation" href="../../index.html"/>
        <link rel="up" title="Module code" href="../index.html"/>

           ArcherBashPYDocs

  <form id="rtd-search-form" class="wy-form" action="../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

        ArcherBashPYDocs

Docs »

Module code »

turtledemo.planet_and_moon

Source code for turtledemo.planet_and_moon

#!/usr/bin/env python3
"""       turtle-example-suite:

        tdemo_planets_and_moon.py

Gravitational system simulation using the
approximation method from Feynman-lectures,
p.9-8, using turtlegraphics.

Example: heavy central body, light planet,
very light moon!
Planet has a circular orbit, moon a stable
orbit around the planet.

You can hold the movement temporarily by
pressing the left mouse button with the
mouse over the scrollbar of the canvas.

"""
from turtle import Shape, Turtle, mainloop, Vec2D as Vec
from time import sleep

G = 8

[docs]class GravSys(object):
    def __init__(self):
        self.planets = []
        self.t = 0
        self.dt = 0.01

[docs]    def init(self):
        for p in self.planets:
            p.init()

[docs]    def start(self):
        for i in range(10000):
            self.t += self.dt
            for p in self.planets:
                p.step()

[docs]class Star(Turtle):
    def __init__(self, m, x, v, gravSys, shape):
        Turtle.__init__(self, shape=shape)
        self.penup()
        self.m = m
        self.setpos(x)
        self.v = v
        gravSys.planets.append(self)
        self.gravSys = gravSys
        self.resizemode("user")
        self.pendown()

[docs]    def init(self):
        dt = self.gravSys.dt
        self.a = self.acc()
        self.v = self.v + 0.5*dt*self.a

[docs]    def acc(self):
        a = Vec(0,0)
        for planet in self.gravSys.planets:
            if planet != self:
                v = planet.pos()-self.pos()
                a += (G*planet.m/abs(v)**3)*v
        return a

[docs]    def step(self):
        dt = self.gravSys.dt
        self.setpos(self.pos() + dt*self.v)
        if self.gravSys.planets.index(self) != 0:
            self.setheading(self.towards(self.gravSys.planets[0]))
        self.a = self.acc()
        self.v = self.v + dt*self.a

## create compound yellow/blue turtleshape for planets

[docs]def main():
    s = Turtle()
    s.reset()
    s.getscreen().tracer(0,0)
    s.ht()
    s.pu()
    s.fd(6)
    s.lt(90)
    s.begin_poly()
    s.circle(6, 180)
    s.end_poly()
    m1 = s.get_poly()
    s.begin_poly()
    s.circle(6,180)
    s.end_poly()
    m2 = s.get_poly()

    planetshape = Shape("compound")
    planetshape.addcomponent(m1,"orange")
    planetshape.addcomponent(m2,"blue")
    s.getscreen().register_shape("planet", planetshape)
    s.getscreen().tracer(1,0)

    ## setup gravitational system
    gs = GravSys()
    sun = Star(1000000, Vec(0,0), Vec(0,-2.5), gs, "circle")
    sun.color("yellow")
    sun.shapesize(1.8)
    sun.pu()
    earth = Star(12500, Vec(210,0), Vec(0,195), gs, "planet")
    earth.pencolor("green")
    earth.shapesize(0.8)
    moon = Star(1, Vec(220,0), Vec(0,295), gs, "planet")
    moon.pencolor("blue")
    moon.shapesize(0.5)
    gs.init()
    gs.start()
    return "Done!"

if __name__ == '__main__':
    main()
    mainloop()

        © Copyright 2015, Weldon Henson.

  Built with Sphinx using a theme provided by Read the Docs.


text:
'use strict'

var superagent = require('superagent')
var fs = require('fs')

var twQuery = '[out:csv(::id)][timeout:25][date:"{{date}}"]; area(3600449220)->.searchArea; ( node["amenity"="drinking_water"](area.searchArea); way["amenity"="drinking_water"](area.searchArea); relation["amenity"="drinking_water"](area.searchArea);); out body; >; out skel qt;'

var output = []
var done = false

function formatDate(date) {
  var d = new Date(date)
  return (d.getYear() + 1900) + '-' + (d.getMonth() + 1) + '-' + (d.getDate())
}

function queryCount (date, output, done) {
  setTimeout(function () {
    console.log('getting data for ' + formatDate(date) + '...')
    superagent.post('http://overpass-api.de/api/interpreter')
      .type('form')
      .send({ data: twQuery.replace('{{date}}', formatDate(date)) })
      .end(function (err, res) {
        console.log('got data for ' + formatDate(date) + '...')
        output.push({ DATE: date, COUNT: res.text.split('\n').length - 1 })
        if (new Date(date) > Date.now()) {
          done(output)
        } else {
          queryCount(date + 86400000 * 7, output, done)
        }
      })
  }, 5000)
}

function outputCSV (data) {
  console.log('output to CSV...')
  fs.writeFileSync('count.csv',
    data.map(function (d) {
      return formatDate(d.DATE) + ',' + d.COUNT + '\n'
    })
    .join('')
  )
  done = true
}

queryCount((new Date('2015/1/1')).getTime(), output, outputCSV)

setInterval(function () {
  console.log('in progress...')
  if (done) process.exit(0)
}, 1000)


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="de.j4velin.picturechooser"
          android:versionCode="9"
          android:versionName="1.0.9">

    <uses-sdk android:targetSdkVersion="27"/>

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <application
        android:allowBackup="true"
        android:largeHeap="true">
        <activity
            android:name="de.j4velin.picturechooser.Main"
            android:theme="@style/LibTheme.PictureChooser"/>
    </application>

</manifest>


text:
/**
 * Модуль представления меню
 *
 * @module      View.User
 * @category    Client side
 * @main        Prices monitoring service
 * @author      Ismax <admin@ismax.ru>
 */

define([
    'backbone'
], function (Backbone) {

    /**
     * Представление меню
     *
     * @class       Menu
     * @namespace   View
     * @constructor
     * @extends     Backbone.View
     */
    var Menu = Backbone.View.extend({
        events: {
            'click .b-menu__label':         'active',
            'mouseenter':                   'mouseenter',
            'mouseleave':                   'mouseleave'
        },

        initialize: function () {
            this.hideTimer = null;
        },

        render: function () {
            $('.b-nav__item[href="' + document.location.pathname + '"]').addClass('b-nav__item_active');

            this.$el.find('.b-menu__sub__item__link').each(function (index, el) {
                if ($(el).attr('href') === document.location.pathname + document.location.hash) {
                    $(el).addClass('b-menu__sub__item__link_active');
                    $(el).parents('.b-menu__sub').next().addClass('b-menu__label_active');
                }
            });
            return this.$el;
        },

        active: function (e) {
            var menu = $(e.currentTarget).parent();

            menu.siblings('.b-menu').find('.b-menu__sub_active').removeClass('b-menu__sub_active');
            if (menu.find('.b-menu__sub').hasClass('b-menu__sub_active')) {
                menu.find('.b-menu__sub').removeClass('b-menu__sub_active');
            } else {
                menu.find('.b-menu__sub').addClass('b-menu__sub_active');

                $(document).click(function doc(e) {
                    if ($(e.target).closest(menu).length === 0) {
                        menu.find('.b-menu__sub').removeClass('b-menu__sub_active');
                        $(document).unbind('click', doc);
                    }
                });
                return false;
            }
        },

        mouseenter: function (e) {
            clearTimeout(this.hideTimer);
        },

        mouseleave: function (e) {
            var menu = $(e.currentTarget).parent();
            this.hideTimer = setTimeout(function () {
                menu.find('.b-menu__sub').removeClass('b-menu__sub_active');
            }, 1000);
        }
    });

    return Menu;
});


text:
[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/sandeepmistry/node-sensortag?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

Node.js lib for the [TI SensorTag](http://www.ti.com/tool/cc2541dk-sensor) and [TI CC2650 SensorTag](http://www.ti.com/tool/cc2650stk)

## Install

```sh
npm install sensortag
```

## Examples

See [test.js](test.js) or [sensorTag folder in Tom Igoe's BluetoothLE-Examples repo ](https://github.com/tigoe/BluetoothLE-Examples/tree/master/sensorTag)

## Usage

```javascript
var SensorTag = require('sensortag');
```

### Discover

#### One

```javascript
SensorTag.discover(callback(sensorTag));
```

#### All

```javascript
function onDiscover(sensorTag) {
  // ...
}

SensorTag.discoverAll(onDiscover);

SensorTag.stopDiscoverAll(onDiscover);
```

#### By id

```javascript
SensorTag.discoverById(id, callback(sensorTag));
```

#### By address

```javascript
SensorTag.discoverByAddress(address, callback(sensorTag));
```

#### Properties:

```javascript
sensorTag = {
  id: "<peripheral id>",
  type: "cc2540" | "cc2650"
}
```

### Connect and Set Up

```javascript
sensorTag.connectAndSetUp(callback(error));
```

### Disconnect

```javascript
sensorTag.disconnect(callback);
```

### Device Info

```javascript
sensorTag.readDeviceName(callback(error, deviceName));

sensorTag.readSystemId(callback(error, systemId));

sensorTag.readSerialNumber(callback(error, serialNumber));

sensorTag.readFirmwareRevision(callback(error, firmwareRevision));

sensorTag.readHardwareRevision(callback(error, hardwareRevision));

sensorTag.readSoftwareRevision(callback(error, softwareRevision));

sensorTag.readManufacturerName(callback(error, manufacturerName));
```

### IR Temperature Sensor

#### Enable/disable

```javascript
sensorTag.enableIrTemperature(callback(error));

sensorTag.disableIrTemperature(callback(error));

sensorTag.setIrTemperaturePeriod(period, callback(error)); // period min 300ms, default period is 1000 ms
```

#### Read

```javascript
sensorTag.readIrTemperature(callback(error, objectTemperature, ambientTemperature));
```

#### Notify/Unnotify

```javascript
sensorTag.notifyIrTemperature(callback(error));

sensorTag.unnotifyIrTemperature(callback(error));

sensorTag.on('irTemperatureChange', callback(objectTemperature, ambientTemperature));
```

### Accelerometer

#### Enable/disable/configure

```javascript
sensorTag.enableAccelerometer(callback(error));

sensorTag.disableAccelerometer(callback(error));

sensorTag.setAccelerometerPeriod(period, callback(error)); // period 1 - 2550 ms, default period is 2000 ms
```

#### Read

```javascript
sensorTag.readAccelerometer(callback(error, x, y, z));
```

#### Notify/Unnotify

```javascript
sensorTag.notifyAccelerometer(callback(error));

sensorTag.unnotifyAccelerometer(callback(error));

sensorTag.on('accelerometerChange', callback(x, y, z));
```

### Humidity Sensor

#### Enable/disable

```javascript
sensorTag.enableHumidity(callback(error));

sensorTag.disableHumidity(callback(error));

sensorTag.setHumidityPeriod(period, callback(error));
```

#### Read

```javascript
sensorTag.readHumidity(callback(error, temperature, humidity));
```

#### Notify/Unnotify

```javascript
sensorTag.notifyHumidity(callback(error));

sensorTag.unnotifyHumidity(callback(error));

sensorTag.on('humidityChange', callback(temperature, humidity));
```

### Magnetometer

#### Enable/disable

```javascript
sensorTag.enableMagnetometer(callback(error));

sensorTag.disableMagnetometer(callback(error));

sensorTag.setMagnetometerPeriod(period, callback(error)); // period 1 - 2550 ms, default period is 2000 ms
```

#### Read

```javascript
sensorTag.readMagnetometer(callback(error, x, y, z));
```

#### Notify/Unnotify

```javascript
sensorTag.notifyMagnetometer(callback(error));

sensorTag.unnotifyMagnetometer(callback(error));

sensorTag.on('magnetometerChange', callback(x, y, z));
```

### Barometric Pressure Sensor

#### Enable/disable

```javascript
sensorTag.enableBarometricPressure(callback(error));

sensorTag.disableBarometricPressure(callback(error));

sensorTag.setBarometricPressurePeriod(period, callback(error)); // period 100 - 2550 ms
```

#### Read

```javascript
sensorTag.readBarometricPressure(callback(error, pressure));
```

#### Notify/Unnotify

```javascript
sensorTag.notifyBarometricPressure(callback(error));

sensorTag.unnotifyBarometricPressure(callback(error));

sensorTag.on('barometricPressureChange', callback(pressure));
```

### Gyroscope

#### Enable/disable/configure

```javascript
sensorTag.enableGyroscope(callback(error));

sensorTag.disableGyroscope(callback(error));

sensorTag.setGyroscopePeriod(period, callback(error)); // period 100 - 2550 ms, default period is 1000 ms
```

#### Read

```javascript
sensorTag.readGyroscope(callback(error, x, y, z));
```

#### Notify/Unnotify

```javascript
sensorTag.notifyGyroscope(callback(error));

sensorTag.unnotifyGyroscope(callback(error));

sensorTag.on('gyroscopeChange', callback(x, y, z));
```

### IO (CC2650 only)

#### Data read/write

```javascript
sensorTag.readIoData(callback(error, value));
sensorTag.writeIoData(value, callback(error));
```

#### Config read/write

```javascript
sensorTag.readIoConfig(callback(error, value));
sensorTag.writeIoConfig(value, callback(error));
```

### Luxometer (CC2650 only)

#### Enable/disable/configure

```javascript
sensorTag.enableLuxometer(callback(error));

sensorTag.disableLuxometer(callback(error));

sensorTag.setLuxometerPeriod(period, callback(error));
```

#### Read

```javascript
sensorTag.readLuxometer(callback(error, lux));
```

#### Notify/Unnotify

```javascript
sensorTag.notifyLuxometer(callback(error));

sensorTag.unnotifyLuxometer(callback(error));

sensorTag.on('luxometerChange', callback(lux));
```

### Simple Key

#### Notify/Unnotify

```javascript
sensorTag.notifySimpleKey(callback(error));

sensorTag.unnotifySimpleKey(callback(error));
```

CC2540:

```javascript
sensorTag.on('simpleKeyChange', callback(left, right));
```

CC2650:

```javascript
sensorTag.on('simpleKeyChange', callback(left, right, reedRelay));
```

[![Analytics](https://ga-beacon.appspot.com/UA-56089547-1/sandeepmistry/node-sensortag?pixel)](https://github.com/igrigorik/ga-beacon)


text:
Divide plant object into twenty equidistant bins and assign pseudolandmark points based upon their actual (not scaled) position.
Once this data is scaled this approach may provide some information regarding shape independent of size.

**plantcv.x_axis_pseudolandmarks**(*img, obj, mask, label="default"*)

**returns** landmarks_on_top (top), landmarks_on_bottom (bottom), landmarks_at_center_along_the_vertical_axis (center_V)

- **Parameters:**
    - img - A copy of the original image (RGB or grayscale) generated using np.copy
    - obj - A contour of the plant object (this should be output from the object_composition.py fxn)
    - mask - This is a binary image. The object should be white and the background should be black.
    - label - Optional label parameter, modifies the variable name of observations recorded
- **Context:**
    - Used to identify a set of sixty equidistant landmarks on the horizontal axis. Once scaled these can be used for shape analysis.
- **Output data stored:** Data ('top_lmk', 'bottom_lmk', 'center_v_lmk') automatically gets stored to the [`Outputs` class](outputs.md) when this function is ran.
    These data can always get accessed during a workflow (example below). For more detail about data output see [Summary of Output Observations](output_measurements.md#summary-of-output-observations)
**Input object contour and image**

![Screenshot](img/documentation_images/x_axis_pseudolandmarks/xpl_example_image.jpg)

```python
from plantcv import plantcv as pcv

# Set global debug behavior to None (default), "print" (to file),
# or "plot" (Jupyter Notebooks or X11)
pcv.params.debug = "plot"

# Identify a set of land mark points
# Results in set of point values that may indicate tip points
top, bottom, center_v = pcv.x_axis_pseudolandmarks(img=img, obj=obj, mask=mask, label="default")

# Access data stored out from x_axis_pseudolandmarks
bottom_landmarks = pcv.outputs.observations['default']['bottom_lmk']['value']

```

**Image of points selected**

![Screenshot](img/documentation_images/x_axis_pseudolandmarks/xap_output.jpg)

**Source Code:** [Here](https://github.com/danforthcenter/plantcv/blob/master/plantcv/plantcv/x_axis_pseudolandmarks.py)


text:
/*---------------------------------------------------------------
	APPLICATION: mrpt_ros bridge
	FILE: stereo_image.h
	AUTHOR: Raghavender Sahdev <raghavendersahdev@gmail.com>
  ---------------------------------------------------------------*/

#pragma once

#include <mrpt/obs/CObservationStereoImages.h>
#include <sensor_msgs/Image.h>
#include <stereo_msgs/DisparityImage.h>

namespace mrpt::ros1bridge
{
/** \addtogroup mrpt_ros1bridge_grp
 * @{ */

bool toROS(
	const mrpt::obs::CObservationStereoImages& obj,
	const std_msgs::Header& msg_header, sensor_msgs::Image& left,
	sensor_msgs::Image& right, stereo_msgs::DisparityImage& disparity);

/** @} */

}  // namespace mrpt::ros1bridge


text:
module Embarista
  module Filters
    class ManifestUrlFilter < Rake::Pipeline::Filter
      attr_reader :options

      def initialize(options= {}, &block)
        @options = options || {}
        raise 'Must pass :path option' unless @options.key?(:path)
        super(&block)
      end

      attr_writer :urls_manifest
      def urls_manifest
        @urls_manifest ||= begin
          if File.exists?(options[:path])
            JSON.parse(IO.read(options[:path]))
          else
            {}
          end
        end
      end

      def generate_output(inputs, output)
        inputs.each do |input|
          code = input.read
          code.gsub!(%r{\bmanifest_url\(\s*(["'/])([^"']+)\1\)}) do |m|
            quote_char = $1
            path = $2

            # take the anchor/querystring off if there is one
            post_path_start = path.index(/[?#]/)
            if post_path_start
              post_path = path[post_path_start..-1]
              path = path[0..post_path_start-1]
            end

            path = "/#{path}" unless path =~ %r{^/}
            path = "#{options[:prefix]}#{path}"
            resolved_path = urls_manifest[path] || path

            # put the anchor/querystring back on, if there is one
            resolved_path = resolved_path + post_path if post_path

            "(#{options[:prepend]}'#{resolved_path}')"
          end
          output.write(code)
        end
      end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c) 2016 Matsv
  ~
  ~ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  ~
  ~ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  ~
  ~ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>viabackwards-parent</artifactId>
        <groupId>nl.matsv</groupId>
        <version>2.4.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>viabackwards-bukkit</artifactId>

    <repositories>
        <repository>
            <id>spigot-repo</id>
            <url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>org.spigotmc</groupId>
            <artifactId>spigot-api</artifactId>
            <version>1.13-R0.1-SNAPSHOT</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>nl.matsv</groupId>
            <artifactId>viabackwards-core</artifactId>
            <version>${project.parent.version}</version>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <targetPath>.</targetPath>
                <filtering>true</filtering>
                <directory>src/main/resources/</directory>
                <includes>
                    <include>*</include>
                </includes>
            </resource>
        </resources>
    </build>
</project>


text:
<%_.each(data.questions, function(q, i){

%>
<div id='<%=data.id%>-question-<%=i%>'
     class='<%=data.id%>-question card-question input-group'>
    Q
    <textarea rows='2' class='form-control question-text'
           onchange='updateQuestion("<%= data.columnName %>", <%= i %> )'><%=q%></textarea>
    <span class='input-group-addon btn-danger btn-remove-question mr-tooltip'
                data-id='<%=data.id%>' data-index='<%=i%>' data-toggle='tooltip' data-placement="top"
                title='remove this question'
                onclick='removeQuestion("<%= data.columnName %>", <%= i %> )'>

<%})%>


text:
package com.sequenceiq.mock.swagger.model;

import java.util.Objects;
import io.swagger.annotations.ApiModel;
import com.fasterxml.jackson.annotation.JsonValue;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import javax.validation.constraints.*;

import com.fasterxml.jackson.annotation.JsonCreator;

/**
 * Represents the configuration staleness status of an entity.
 */
public enum ApiConfigStalenessStatus {

  FRESH("FRESH"),

  STALE_REFRESHABLE("STALE_REFRESHABLE"),

  STALE("STALE");

  private String value;

  ApiConfigStalenessStatus(String value) {
    this.value = value;
  }

  @Override
  @JsonValue
  public String toString() {
    return String.valueOf(value);
  }

  @JsonCreator
  public static ApiConfigStalenessStatus fromValue(String text) {
    for (ApiConfigStalenessStatus b : ApiConfigStalenessStatus.values()) {
      if (String.valueOf(b.value).equals(text)) {
        return b;
      }
    }
    return null;
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<TITLE>Manpage of TIFFSetField</TITLE>

TIFFSetField

Section: Misc. Reference Manual Pages (3T)
Updated: August 28, 1997
Index

Return to Main Contents

NAME

TIFFSetField - set the value(s) of a tag in a
TIFF
file open for writing

SYNOPSIS

#include <tiffio.h>

int TIFFSetField(TIFF* tif, ttag_t tag, ...)

#include <stdarg.h>

int TIFFVSetField(TIFF* tif, ttag_t tag, va_list ap)

DESCRIPTION

TIFFSetField

sets the value of a field
or pseudo-tag in the current directory associated with
the open
TIFF
file
tif.

(A
pseudo-tag

is a parameter that is used to control the operation of the
TIFF
library but whose value is not read or written to the underlying file.)
To set the value of a field
the file must have been previously opened for writing with
TIFFOpen(3T);

pseudo-tags can be set whether the file was opened for reading
or writing.
The field is identified by
tag,

one of the values defined in the include file
tiff.h

(see also the table below).
The actual value is specified using a variable argument list,
as prescribed by the
stdarg(3)

interface (or, on some machines, the
varargs(3)

interface.)

TIFFVSetField

is functionally equivalent to
TIFFSetField

except that it takes a pointer to a variable
argument list.
TIFFVSetField

is useful for writing routines that are layered
on top of the functionality provided by
TIFFSetField.

The tags understood by
libtiff,

the number of parameter values, and the
expected types for the parameter values are shown below.
The data types are:
char*

is null-terminated string and corresponds to the
ASCII
data type;
uint16

is an unsigned 16-bit value;
uint32

is an unsigned 32-bit value;
uint16*

is an array of unsigned 16-bit values.
void*

is an array of data values of unspecified type.

Consult the
TIFF
specification for information on the meaning of each tag.

Tag Name                        Count  Types              Notes

TIFFTAG_ARTIST                  1      char*
TIFFTAG_BADFAXLINES             1      uint32
TIFFTAG_BITSPERSAMPLE           1      uint16             +
TIFFTAG_CLEANFAXDATA            1      uint16
TIFFTAG_COLORMAP                3      uint16*            1<<BitsPerSample arrays
TIFFTAG_COMPRESSION             1      uint16             +
TIFFTAG_CONSECUTIVEBADFAXLINES  1      uint32
TIFFTAG_DATETIME                1      char*
TIFFTAG_DOCUMENTNAME            1      char*
TIFFTAG_DOTRANGE                2      uint16
TIFFTAG_EXTRASAMPLES            2      uint16,uint16*     + count & types array
TIFFTAG_FAXMODE                 1      int                + G3/G4 compression pseudo-tag
TIFFTAG_FAXFILLFUNC             1      TIFFFaxFillFunc    G3/G4 compression pseudo-tag
TIFFTAG_FILLORDER               1      uint16             +
TIFFTAG_GROUP3OPTIONS           1      uint32             +
TIFFTAG_GROUP4OPTIONS           1      uint32             +
TIFFTAG_HALFTONEHINTS           2      uint16
TIFFTAG_HOSTCOMPUTER            1      char*
TIFFTAG_IMAGEDESCRIPTION        1      char*
TIFFTAG_IMAGEDEPTH              1      uint32             +
TIFFTAG_IMAGELENGTH             1      uint32
TIFFTAG_IMAGEWIDTH              1      uint32             +
TIFFTAG_INKNAMES                1      char*
TIFFTAG_INKSET                  1      uint16             +
TIFFTAG_JPEGTABLES              2      uint32*,void*      + count & tables
TIFFTAG_JPEGQUALITY             1      int                JPEG pseudo-tag
TIFFTAG_JPEGCOLORMODE           1      int                + JPEG pseudo-tag
TIFFTAG_JPEGTABLESMODE          1      int                + JPEG pseudo-tag
TIFFTAG_MAKE                    1      char*
TIFFTAG_MATTEING                1      uint16             +
TIFFTAG_MAXSAMPLEVALUE          1      uint16
TIFFTAG_MINSAMPLEVALUE          1      uint16
TIFFTAG_MODEL                   1      char*
TIFFTAG_ORIENTATION             1      uint16
TIFFTAG_PAGENAME                1      char*
TIFFTAG_PAGENUMBER              2      uint16
TIFFTAG_PHOTOMETRIC             1      uint16
TIFFTAG_PLANARCONFIG            1      uint16             +
TIFFTAG_PREDICTOR               1      uint16             +
TIFFTAG_PRIMARYCHROMATICITIES   1      float*             6-entry array
TIFFTAG_REFERENCEBLACKWHITE     1      float*             + 2*SamplesPerPixel array
TIFFTAG_RESOLUTIONUNIT          1      uint16
TIFFTAG_ROWSPERSTRIP            1      uint32             + must be > 0
TIFFTAG_SAMPLEFORMAT            1      uint16             +
TIFFTAG_SAMPLESPERPIXEL         1      uint16             + value must be <= 4
TIFFTAG_SMAXSAMPLEVALUE         1      double
TIFFTAG_SMINSAMPLEVALUE         1      double
TIFFTAG_SOFTWARE                1      char*
TIFFTAG_STONITS                 1      double             +
TIFFTAG_SUBFILETYPE             1      uint32
TIFFTAG_SUBIFD                  2      uint16,uint32*     count & offsets array
TIFFTAG_TARGETPRINTER           1      char*
TIFFTAG_THRESHHOLDING           1      uint16
TIFFTAG_TILEDEPTH               1      uint32             +
TIFFTAG_TILELENGTH              1      uint32             + must be a multiple of 8
TIFFTAG_TILEWIDTH               1      uint32             + must be a multiple of 8
TIFFTAG_TRANSFERFUNCTION        1 or 3 dd                 uint16*1<<BitsPerSample entry arrays
TIFFTAG_XPOSITION               1      float
TIFFTAG_XRESOLUTION             1      float
TIFFTAG_WHITEPOINT              1      float*             2-entry array
TIFFTAG_YCBCRCOEFFICIENTS       1      float*             + 3-entry array
TIFFTAG_YCBCRPOSITIONING        1      uint16             +
TIFFTAG_YCBCRSAMPLING           2      uint16             +
TIFFTAG_YPOSITION               1      float
TIFFTAG_YRESOLUTION             1      float
TIFFTAG_ICCPROFILE              2      uint32,void*       count, profile data*

+ Tag may not have its values changed once data is written.

dd
If
SamplesPerPixel

is one, then a single array is passed; otherwise three arrays should be
passed.

* The contents of this field are quite complex.  See
The ICC Profile Format Specification,

Annex B.3 "Embedding ICC Profiles in TIFF Files"
(available at http://www.color.org) for an explanation.

RETURN VALUES

1 is returned if the tag is defined in the current
directory; otherwise a 0 is returned.

RETURN VALUES

1 is returned if the operation was successful.
Otherwise, 0 is returned if an error was detected.

DIAGNOSTICS

All error messages are directed to the
TIFFError(3T)

routine.

%s: Cannot modify tag "%s" while writing.
Data has already been written to the file, so the
specified tag's value can not be changed.
This restriction is applied to all tags that affect
the format of written data.

%d: Bad value for "%s".
An invalid value was supplied for the named tag.

SEE ALSO

libtiff(3T),

TIFFOpen(3T),

TIFFGetField(3T),

TIFFSetDirectory(3T),

TIFFWriteDirectory(3T),

TIFFReadDirectory(3T)

Index

NAME

SYNOPSIS

DESCRIPTION

RETURN VALUES

RETURN VALUES

DIAGNOSTICS

SEE ALSO

This document was created by
man2html,
using the manual pages.

Time: 01:31:38 GMT, November 23, 1999