text:
using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEditor;
using UnityEngine;

namespace SuperSystems.UnityBuild
{

[CustomPropertyDrawer(typeof(BuildPlatformList))]
public class BuildPlatformListDrawer : PropertyDrawer
{
    private int index = 0;
    private SerializedProperty list = null;
    private BuildPlatformList platformList = null;

    private List<string> availablePlatformNameList = new List<string>();
    private List<Type> availablePlatformTypeList = new List<Type>();

    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        EditorGUI.BeginProperty(position, label, property);

        EditorGUILayout.BeginHorizontal();
        property.serializedObject.Update();

        bool show = property.isExpanded;
        UnityBuildGUIUtility.DropdownHeader("Build Platforms", ref show, false, GUILayout.ExpandWidth(true));
        property.isExpanded = show;

        UnityBuildGUIUtility.HelpButton("Parameter-Details#build-platforms");
        EditorGUILayout.EndHorizontal();

        //if (list == null)
        //{
            platformList = fieldInfo.GetValue(property.serializedObject.targetObject) as BuildPlatformList;
            PopulateList();
            list = property.FindPropertyRelative("platforms");
            list.serializedObject.Update();
        //}

        if (show)
        {
            EditorGUILayout.BeginVertical(UnityBuildGUIUtility.dropdownContentStyle);

            // Draw all created/enabled platforms.
            int enabledCount = 0;
            for (int i = 0; i < list.arraySize; i++)
            {
                SerializedProperty platformProperty = list.GetArrayElementAtIndex(i);
                SerializedProperty platformEnabled = platformProperty.FindPropertyRelative("enabled");

                if (platformEnabled.boolValue)
                {
                    ++enabledCount;
                    EditorGUILayout.PropertyField(platformProperty, GUILayout.MaxHeight(0));
                }
            }

            if (enabledCount > 0)
                GUILayout.Space(20);

            // Draw all available platforms.
            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            index = EditorGUILayout.Popup(index, availablePlatformNameList.ToArray(), UnityBuildGUIUtility.popupStyle, GUILayout.ExpandWidth(false), GUILayout.MaxWidth(250));
            if (GUILayout.Button("Add Platform", GUILayout.ExpandWidth(false), GUILayout.MaxWidth(150)))
            {
                platformList.platforms.Add((BuildPlatform)Activator.CreateInstance(availablePlatformTypeList[index]));
                platformList.platforms[platformList.platforms.Count - 1].enabled = true;

                for (int i = platformList.platforms.Count - 1; i >= 0; i--)
                {
                    if (!platformList.platforms[i].enabled)
                        platformList.platforms.RemoveAt(i);
                }
            }
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();

            EditorGUILayout.EndVertical();
        }

        EditorGUI.EndProperty();
    }

    private void PopulateList()
    {
        Type ti = typeof(BuildPlatform);

        availablePlatformNameList.Clear();
        availablePlatformTypeList.Clear();
        foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
        {
            foreach (Type t in asm.GetTypes())
            {
                if (ti.IsAssignableFrom(t) && ti != t)
                {
                    BuildPlatform instance = (BuildPlatform)Activator.CreateInstance(t);
                    availablePlatformNameList.Add(instance.platformName);
                    availablePlatformTypeList.Add(t);
                }
            }
        }
    }
}

}


text:
Interacting with the API
=========================

.. warning::

    This API documentation is still in an early state. It contains errors, omissions, etc., and could change drastically at any time.

Overview
----------

``chancecoind`` features a full-fledged JSON RPC 2.0-based API, which allows
third-party applications to perform functions on the Chancecoin network
without having to deal with the low‐level details of the protocol such as
transaction encoding and state management.

Connecting to the API
----------------------

By default, ``chancecoind`` will listen on port ``4000`` (if on mainnet) or port ``14000`` (on testnet) for API
requests. API requests are made via a HTTP POST request to ``/jsonrpc/``, with JSON-encoded
data passed as the POST body. For more information on JSON RPC, please see the `JSON RPC 2.0 specification <http://www.jsonrpc.org/specification>`__.

.. _examples:

Python Example
^^^^^^^^^^^^^^^

.. code-block:: python

    import json
    import requests
    from requests.auth import HTTPBasicAuth

    url = "http://localhost:4000/jsonrpc/"
    headers = {'content-type': 'application/json'}
    auth = HTTPBasicAuth('rpcuser', 'rpcpassword')

    #Fetch all balances for a specific address, using keyword-based arguments
    payload = {
      "method": "get_balances",
      "params": {"filters": {'field': 'address', 'op': '==', 'value': "14qqz8xpzzEtj6zLs3M1iASP7T4mj687yq"}},
      "jsonrpc": "2.0",
      "id": 0,
    }
    response = requests.post(
      url, data=json.dumps(payload), headers=headers, auth=auth).json()
    print("GET_BALANCES RESULT: ", response)

redpajama_set_name: RedPajamaGithub


text:
@protocol LMARequest <NSObject, LMAProviderDelegate>

/// Provider instance
/// Set by controller
@property (strong, nonatomic) id<LMAProvider> provider;

/// Authorization results
/// Set by request from provider delegate methods
@property (strong, nonatomic, readonly) NSDictionary *credential;
@property (strong, nonatomic, readonly) NSError *error;

/// Called when authorization process is finished
/// Called by request
@property (copy, nonatomic) void (^completionBlock)(void);

/// Start authorization request
/// Called by user
- (void)start;
/// Cancel authorization request
/// Called by user
- (void)cancel;

/// Called for all requests, until it returns YES from at least one of them
/// Called by controller
- (BOOL)handleOpenURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation;
/// Called for all requests
/// Called by controller
- (void)handleDidBecomeActive;

@end


text:
package org.backuity.puppet

import org.backuity.ansi.AnsiFormatter.FormattedHelper

case class Module(description: Module.Description, dependencies: Module.Graph) {
  def name = description.name
  def version = description.version
  def tag = description.tag
  def uri = description.uri
}

object Module {
  type Graph = Set[Module]

  def apply(name: String, tag: Option[String], uri: String, dependencies: Set[Module] = Set.empty) : Module = {
    Module(Module.Description(name,tag,uri),dependencies)
  }

  case class Description(name: String, tag: Option[String], uri: String) {
    lazy val version = Version(tag)
  }

  def showGraph(graph: Graph, withUri: Boolean = true) : String = {
    val root = Module("Puppetfile", None, "", graph)
    def showModule(m: Module) = {
      if( m.name == "Puppetfile" ) {
        "Puppetfile"
      } else {
        val uri = if( withUri ) ansi"%blue{ @ ${m.uri}}" else ""
        ansi"${m.name}(%bold{${m.version}})$uri"
      }
    }
    Graph.toAscii[Module](root, _.dependencies.toList.sortBy(_.name), showModule)
  }
}


text: test maven build file


text:
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// 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
//
// THIS CODE IS PROVIDED ON AN  *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.PythonTools.Analysis;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Intellisense;
using Microsoft.PythonTools.Parsing;
using Microsoft.PythonTools.Projects;
using Microsoft.PythonTools.Repl;
using Microsoft.VisualStudio.InteractiveWindow;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Differencing;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Utilities;
using Microsoft.VisualStudioTools;

namespace Microsoft.PythonTools.Editor {
    sealed class PythonTextBufferInfo {
        private static readonly object PythonTextBufferInfoKey = new { Id = "PythonTextBufferInfo" };

        public static PythonTextBufferInfo ForBuffer(PythonEditorServices services, ITextBuffer buffer) {
            var bi = (buffer ?? throw new ArgumentNullException(nameof(buffer))).Properties.GetOrCreateSingletonProperty(
                PythonTextBufferInfoKey,
                () => new PythonTextBufferInfo(services, buffer)
            );
            if (bi._replace) {
                bi = bi.ReplaceBufferInfo();
            }
            return bi;
        }

        public static PythonTextBufferInfo TryGetForBuffer(ITextBuffer buffer) {
            PythonTextBufferInfo bi;
            if (buffer == null) {
                return null;
            }
            if (!buffer.Properties.TryGetProperty(PythonTextBufferInfoKey, out bi) || bi == null) {
                return null;
            }
            if (bi._replace) {
                bi = bi.ReplaceBufferInfo();
            }
            return bi;
        }

        /// <summary>
        /// Calling this function marks the buffer to be replaced next
        /// time it is retrieved.
        /// </summary>
        public static void MarkForReplacement(ITextBuffer buffer) {
            var bi = TryGetForBuffer(buffer);
            if (bi != null) {
                bi._replace = true;
                bi.TraceWithStack("MarkForReplacement");
            }
        }

        public static IEnumerable<PythonTextBufferInfo> GetAllFromView(ITextView view) {
            return view.BufferGraph.GetTextBuffers(_ => true)
                .Select(b => TryGetForBuffer(b))
                .Where(b => b != null);
        }

        private readonly object _lock = new object();

        private AnalysisEntry _analysisEntry;
        private TaskCompletionSource<AnalysisEntry> _waitingForEntry;

        private readonly ConcurrentDictionary<object, IPythonTextBufferInfoEventSink> _eventSinks;

        private readonly Lazy<string> _filename;
        private readonly Lazy<Uri> _documentUri;
        private readonly TokenCache _tokenCache;
        private readonly LocationTracker _locationTracker;

        private readonly bool _hasChangedOnBackground;
        private bool _replace;

        internal PythonLanguageVersion _defaultLanguageVersion;

        private readonly AnalysisLogWriter _traceLog;

        private PythonTextBufferInfo(PythonEditorServices services, ITextBuffer buffer) {
            Services = services;
            Buffer = buffer;
            _eventSinks = new ConcurrentDictionary<object, IPythonTextBufferInfoEventSink>();
            _filename = new Lazy<string>(GetOrCreateFilename);
            _documentUri = new Lazy<Uri>(GetOrCreateDocumentUri);
            _tokenCache = new TokenCache();
            _defaultLanguageVersion = PythonLanguageVersion.None;

            ITextDocument doc;
            if (Buffer.Properties.TryGetProperty(typeof(ITextDocument), out doc)) {
                Document = doc;
                Document.EncodingChanged += Document_EncodingChanged;
            }
            Buffer.ContentTypeChanged += Buffer_ContentTypeChanged;
            Buffer.Changed += Buffer_TextContentChanged;
            Buffer.ChangedLowPriority += Buffer_TextContentChangedLowPriority;

            if (Buffer is ITextBuffer2 buffer2) {
                _hasChangedOnBackground = true;
                buffer2.ChangedOnBackground += Buffer_TextContentChangedOnBackground;
            }

            _locationTracker = new LocationTracker(Buffer.CurrentSnapshot);

            _traceLog = OpenTraceLog();
        }

        private PythonTextBufferInfo ReplaceBufferInfo() {
            TraceWithStack("ReplaceBufferInfo");

            var newInfo = new PythonTextBufferInfo(Services, Buffer);
            foreach (var sink in _eventSinks) {
                newInfo._eventSinks[sink.Key] = sink.Value;
            }

            Buffer.Properties[PythonTextBufferInfoKey] = newInfo;

            Buffer.ContentTypeChanged -= Buffer_ContentTypeChanged;
            Buffer.Changed -= Buffer_TextContentChanged;
            Buffer.ChangedLowPriority -= Buffer_TextContentChangedLowPriority;

            if (Buffer is ITextBuffer2 buffer2) {
                buffer2.ChangedOnBackground -= Buffer_TextContentChangedOnBackground;
            }

            Interlocked.Exchange(ref _waitingForEntry, null)?.TrySetResult(null);

            InvokeSinks(new PythonNewTextBufferInfoEventArgs(PythonTextBufferInfoEvents.NewTextBufferInfo, newInfo));

            _traceLog?.Dispose();

            return newInfo;
        }

        private string GetOrCreateFilename() {
            string path;
            if (Buffer.Properties.TryGetProperty(VsProjectAnalyzer._testFilename, out path)) {
                return path;
            }

            var replEval = Buffer.GetInteractiveWindow()?.Evaluator as IPythonInteractiveIntellisense;
            var docUri = replEval?.DocumentUri;
            if (docUri != null && docUri.IsFile) {
                return docUri.LocalPath;
            }

            if (Buffer.GetInteractiveWindow() != null) {
                return null;
            }

            if (Buffer.Properties.TryGetProperty(typeof(ITextDocument), out ITextDocument doc) &&
                !string.IsNullOrEmpty(path = doc.FilePath)) {
                return PathUtils.NormalizePath(path);
            }

            return null;
        }

        private Uri GetOrCreateDocumentUri() {
            if (Buffer.Properties.TryGetProperty(VsProjectAnalyzer._testDocumentUri, out Uri uri)) {
                return uri;
            }

            var path = Filename;
            if (!string.IsNullOrEmpty(path)) {
                try {
                    if (Path.IsPathRooted(path)) {
                        return new Uri(path);
                    }
                    // Make an opaque identifier for this file
                    var ub = new UriBuilder("python://", Guid.NewGuid().ToString("N")) { Path = path };
                    return ub.Uri;
                } catch (ArgumentException ex) {
                    Debug.Fail("{0} is not a valid path.{1}{2}".FormatInvariant(path, Environment.NewLine, ex.ToUnhandledExceptionMessage(GetType())));
                } catch (UriFormatException ex) {
                    Debug.Fail("{0} is not a valid URI.{1}{2}".FormatInvariant(path, Environment.NewLine, ex.ToUnhandledExceptionMessage(GetType())));
                }
                return null;
            }

            var replEval = Buffer.GetInteractiveWindow()?.Evaluator as IPythonInteractiveIntellisense;
            return replEval?.NextDocumentUri();
        }

        public ITextBuffer Buffer { get; }
        public ITextDocument Document { get; }
        public ITextSnapshot CurrentSnapshot => Buffer.CurrentSnapshot;
        public IContentType ContentType => Buffer.ContentType;
        public string Filename => _filename.Value;
        public Uri DocumentUri => _documentUri.Value;

        public PythonEditorServices Services { get; }

        public PythonLanguageVersion LanguageVersion => AnalysisEntry?.Analyzer.LanguageVersion ?? _defaultLanguageVersion;

        #region Events

        private void OnNewAnalysisEntry(AnalysisEntry entry) {
            Trace("OnNewAnalysisEntry", entry?.Analyzer);
            ClearTokenCache();
            InvokeSinks(new PythonTextBufferInfoEventArgs(PythonTextBufferInfoEvents.NewAnalysisEntry, entry));
        }

        private void AnalysisEntry_ParseComplete(object sender, EventArgs e) {
            Trace("ParseComplete");
            InvokeSinks(new PythonTextBufferInfoEventArgs(PythonTextBufferInfoEvents.NewParseTree, (AnalysisEntry)sender));
        }

        private void AnalysisEntry_AnalysisComplete(object sender, EventArgs e) {
            Trace("AnalysisComplete");
            InvokeSinks(new PythonTextBufferInfoEventArgs(PythonTextBufferInfoEvents.NewAnalysis, (AnalysisEntry)sender));
        }

        private void Buffer_TextContentChanged(object sender, TextContentChangedEventArgs e) {
            Trace("TextContentChanged");
            if (!_hasChangedOnBackground) {
                UpdateTokenCache(e);
            }
            InvokeSinks(new PythonTextBufferInfoNestedEventArgs(PythonTextBufferInfoEvents.TextContentChanged, e));
            if (!_hasChangedOnBackground) {
                InvokeSinks(new PythonTextBufferInfoNestedEventArgs(PythonTextBufferInfoEvents.TextContentChangedOnBackgroundThread, e));
            }
        }

        private void Buffer_TextContentChangedLowPriority(object sender, TextContentChangedEventArgs e) {
            Trace("TextContentChangedLowPriority");
            InvokeSinks(new PythonTextBufferInfoNestedEventArgs(PythonTextBufferInfoEvents.TextContentChangedLowPriority, e));
        }

        private void Buffer_ContentTypeChanged(object sender, ContentTypeChangedEventArgs e) {
            Trace("ContentTypeChanged", e.BeforeContentType, e.AfterContentType);
            ClearTokenCache();
            InvokeSinks(new PythonTextBufferInfoNestedEventArgs(PythonTextBufferInfoEvents.ContentTypeChanged, e));
        }

        private void Buffer_TextContentChangedOnBackground(object sender, TextContentChangedEventArgs e) {
            if (!_hasChangedOnBackground) {
                Debug.Fail("Received TextContentChangedOnBackground unexpectedly");
                return;
            }
            UpdateTokenCache(e);
            InvokeSinks(new PythonTextBufferInfoNestedEventArgs(PythonTextBufferInfoEvents.TextContentChangedOnBackgroundThread, e));
        }

        private void Document_EncodingChanged(object sender, EncodingChangedEventArgs e) {
            Trace("EncodingChanged", e.OldEncoding, e.NewEncoding);
            InvokeSinks(new PythonTextBufferInfoNestedEventArgs(PythonTextBufferInfoEvents.DocumentEncodingChanged, e));
        }

        #endregion

        #region Sink management

        public void AddSink(object key, IPythonTextBufferInfoEventSink sink) {
            if (!_eventSinks.TryAdd(key, sink)) {
                if (_eventSinks[key] != sink) {
                    throw new InvalidOperationException("cannot replace existing sink");
                }
            }
            TraceWithStack("AddSink", key, sink.GetType().FullName);
        }

        public T GetOrCreateSink<T>(object key, Func<PythonTextBufferInfo, T> creator) where T : class, IPythonTextBufferInfoEventSink {
            IPythonTextBufferInfoEventSink sink;
            if (_eventSinks.TryGetValue(key, out sink)) {
                Trace("GetOrCreateSink", typeof(T).FullName, "get", sink.GetType().FullName);
                return sink as T;
            }
            sink = creator(this);
            TraceWithStack("GetOrCreateSink", typeof(T).FullName, "create", sink.GetType().FullName);
            if (!_eventSinks.TryAdd(key, sink)) {
                sink = _eventSinks[key];
                Trace("GetOrCreateSink", typeof(T).FullName, "lost create race", sink.GetType().FullName);
            }
            return sink as T;
        }

        public IPythonTextBufferInfoEventSink TryGetSink(object key) {
            IPythonTextBufferInfoEventSink sink;
            return _eventSinks.TryGetValue(key, out sink) ? sink : null;
        }

        public bool RemoveSink(object key) {
            Trace("RemoveSink", key, _eventSinks.ContainsKey(key));

            return _eventSinks.TryRemove(key, out _);
        }

        private void InvokeSinks(PythonTextBufferInfoEventArgs e) {
            foreach (var sink in _eventSinks.Values) {
                sink.PythonTextBufferEventAsync(this, e)
                    .HandleAllExceptions(Services.Site, GetType())
                    .DoNotWait();
            }
        }

        #endregion

        #region Analysis Info

        public AnalysisEntry AnalysisEntry {
            get {
                var entry = Volatile.Read(ref _analysisEntry);
                if (entry != null && (entry.Analyzer == null || !entry.Analyzer.IsActive)) {
                    // Analyzer has closed, so clear it out from our info.
                    TraceWithStack("AnalyzerExpired", entry.Analyzer);
                    var previous = TrySetAnalysisEntry(null, entry);
                    if (previous != entry) {
                        // The entry has already been updated, so return the new one
                        return previous;
                    }
                    InvokeSinks(new PythonTextBufferInfoEventArgs(PythonTextBufferInfoEvents.AnalyzerExpired));
                    return null;
                }
                return entry;
            }
        }

        /// <summary>
        /// Returns the current analysis entry if it is not null. Otherwise
        /// waits for a non-null entry to be set and returns it. If cancelled,
        /// return null.
        /// </summary>
        public Task<AnalysisEntry> GetAnalysisEntryAsync(CancellationToken cancellationToken) {
            var entry = AnalysisEntry;
            if (entry != null) {
                Trace("GetAnalysisEntryAsync", "completed synchronously");
                return Task.FromResult(entry);
            }
            TraceWithStack("GetAnalysisEntryAsync", "waiting");
            var tcs = Volatile.Read(ref _waitingForEntry);
            if (tcs != null) {
                return tcs.Task;
            }
            tcs = new TaskCompletionSource<AnalysisEntry>();
            tcs = Interlocked.CompareExchange(ref _waitingForEntry, tcs, null) ?? tcs;
            entry = AnalysisEntry;
            if (entry != null) {
                tcs.TrySetResult(entry);
            } else if (cancellationToken.CanBeCanceled) {
                cancellationToken.Register(() => tcs.TrySetResult(null));
            }
            return tcs.Task;
        }

        /// <summary>
        /// Changes the analysis entry to <paramref name="entry"/> if the current
        /// entry matches <paramref name="ifCurrent"/>. Returns the current analysis
        /// entry, regardless of whether it changed or not.
        /// </summary>
        public AnalysisEntry TrySetAnalysisEntry(AnalysisEntry entry, AnalysisEntry ifCurrent) {
            var previous = Interlocked.CompareExchange(ref _analysisEntry, entry, ifCurrent);

            if (previous != ifCurrent) {
                TraceWithStack("FailedToSetAnalysisEntry", previous?.Analyzer, entry?.Analyzer, ifCurrent?.Analyzer);
                return previous;
            }

            if (previous != null) {
                previous.AnalysisComplete -= AnalysisEntry_AnalysisComplete;
                previous.ParseComplete -= AnalysisEntry_ParseComplete;
                previous.Analyzer.BufferDetached(previous, Buffer);
            }
            if (entry != null) {
                entry.AnalysisComplete += AnalysisEntry_AnalysisComplete;
                entry.ParseComplete += AnalysisEntry_ParseComplete;

                Interlocked.Exchange(ref _waitingForEntry, null)?.TrySetResult(entry);
            }

            TraceWithStack("TrySetAnalysisEntry", entry?.Analyzer, ifCurrent?.Analyzer);
            OnNewAnalysisEntry(entry);

            return entry;
        }

        public void ClearAnalysisEntry() {
            var previous = Interlocked.Exchange(ref _analysisEntry, null);
            TraceWithStack("ClearAnalysisEntry", previous?.Analyzer);

            if (previous != null) {
                previous.AnalysisComplete -= AnalysisEntry_AnalysisComplete;
                previous.ParseComplete -= AnalysisEntry_ParseComplete;
                previous.Analyzer.BufferDetached(previous, Buffer);

                OnNewAnalysisEntry(null);
            }
        }

        private readonly SortedDictionary<int, ITextSnapshot> _expectParse = new SortedDictionary<int, ITextSnapshot>();
        private readonly SortedDictionary<int, ITextSnapshot> _expectAnalysis = new SortedDictionary<int, ITextSnapshot>();
        private ITextSnapshot _lastSentSnapshot;

        public ITextSnapshot LastAnalysisSnapshot { get; private set; }

        public ITextSnapshot LastSentSnapshot {
            get {
                lock (_lock) {
                    return _lastSentSnapshot;
                }
            }
        }

        public void ClearSentSnapshot() {
            lock (_lock) {
                _lastSentSnapshot = null;
                _expectAnalysis.Clear();
                _expectParse.Clear();
            }
        }

        public ITextSnapshot AddSentSnapshot(ITextSnapshot sent) {
            lock (_lock) {
                var prevSent = _lastSentSnapshot;
                Trace("AddSentSnapshot", prevSent?.Version?.VersionNumber, sent?.Version?.VersionNumber);
                if (prevSent != null && prevSent.Version.VersionNumber > sent.Version.VersionNumber) {
                    return prevSent;
                }
                _lastSentSnapshot = sent;
                _expectAnalysis[sent.Version.VersionNumber] = sent;
                _expectParse[sent.Version.VersionNumber] = sent;
                return prevSent;
            }
        }

        public bool UpdateLastReceivedParse(int version) {
            lock (_lock) {
                Trace("UpdateLastReceivedParse", version, _expectParse.ContainsKey(version) ? "expected" : "unexpected");
                var toRemove = _expectParse.Keys.TakeWhile(k => k < version).ToArray();
                foreach (var i in toRemove) {
                    Debug.WriteLine($"Skipped parse for version {i}");
                    Trace("SkipParse", i);
                    _expectParse.Remove(i);
                }
                return _expectParse.Remove(version);
            }
        }

        public bool UpdateLastReceivedAnalysis(int version) {
            lock (_lock) {
                Trace("UpdateLastReceivedAnalysis", version, _expectAnalysis.ContainsKey(version) ? "expected" : "unexpected");

                var toRemove = _expectAnalysis.Keys.TakeWhile(k => k < version).ToArray();
                foreach (var i in toRemove) {
                    Debug.WriteLine($"Skipped analysis for version {i}");
                    Trace("SkipAnalysis", i);
                    _expectAnalysis.Remove(i);
                }
                if (_expectAnalysis.TryGetValue(version, out var snapshot)) {
                    _expectAnalysis.Remove(version);
                    if (snapshot.Version.VersionNumber > (LastAnalysisSnapshot?.Version.VersionNumber ?? -1)) {
                        LastAnalysisSnapshot = snapshot;
                        _locationTracker.UpdateBaseSnapshot(snapshot);
                        return true;
                    }
                }
                return false;
            }
        }

        public LocationTracker LocationTracker => _locationTracker;

        /// <summary>
        /// Returns the first token containing or adjacent to the specified point.
        /// </summary>
        public TrackingTokenInfo? GetTokenAtPoint(SnapshotPoint point) {
            return GetTrackingTokens(new SnapshotSpan(point, 0))
                .Cast<TrackingTokenInfo?>()
                .FirstOrDefault();
        }

        /// <summary>
        /// Returns tokens for the specified line.
        /// </summary>
        public IEnumerable<TrackingTokenInfo> GetTokens(ITextSnapshotLine line) {
            using (var cacheSnapshot = _tokenCache.GetSnapshot()) {
                var lineTokenization = cacheSnapshot.GetLineTokenization(line, GetTokenizerLazy());
                var lineNumber = line.LineNumber;
                var lineSpan = line.Snapshot.CreateTrackingSpan(line.ExtentIncludingLineBreak, SpanTrackingMode.EdgeNegative);
                return lineTokenization.Tokens.Select(t => new TrackingTokenInfo(t, lineNumber, lineSpan));
            }
        }

        public IEnumerable<TrackingTokenInfo> GetTokens(SnapshotSpan span) {
            return GetTrackingTokens(span);
        }

        /// <summary>
        /// Iterates forwards through tokens starting from the token at or
        /// adjacent to the specified point.
        /// </summary>
        public IEnumerable<TrackingTokenInfo> GetTokensForwardFromPoint(SnapshotPoint point) {
            var line = point.GetContainingLine();

            foreach (var token in GetTrackingTokens(new SnapshotSpan(point, line.End))) {
                yield return token;
            }

            while (line.LineNumber < line.Snapshot.LineCount - 1) {
                line = line.Snapshot.GetLineFromLineNumber(line.LineNumber + 1);
                // Use line.Extent because GetLineTokens endpoints are inclusive - we
                // will get the line break token because it is adjacent, but no
                // other repetitions.
                foreach (var token in GetTrackingTokens(line.Extent)) {
                    yield return token;
                }
            }
        }

        /// <summary>
        /// Iterates backwards through tokens starting from the token at or
        /// adjacent to the specified point.
        /// </summary>
        public IEnumerable<TrackingTokenInfo> GetTokensInReverseFromPoint(SnapshotPoint point) {
            var line = point.GetContainingLine();

            foreach (var token in GetTrackingTokens(new SnapshotSpan(line.Start, point)).Reverse()) {
                yield return token;
            }

            while (line.LineNumber > 0) {
                line = line.Snapshot.GetLineFromLineNumber(line.LineNumber - 1);
                // Use line.Extent because GetLineTokens endpoints are inclusive - we
                // will get the line break token because it is adjacent, but no
                // other repetitions.
                foreach (var token in GetTrackingTokens(line.Extent).Reverse()) {
                    yield return token;
                }
            }
        }

        internal IEnumerable<TrackingTokenInfo> GetTrackingTokens(SnapshotSpan span) {
            int firstLine = span.Start.GetContainingLine().LineNumber;
            int lastLine = span.End.GetContainingLine().LineNumber;

            int startCol = span.Start - span.Start.GetContainingLine().Start;
            int endCol = span.End - span.End.GetContainingLine().Start;

            // We need current state of the cache since it can change from a background thread
            using (var cacheSnapshot = _tokenCache.GetSnapshot()) {
                var tokenizerLazy = GetTokenizerLazy();
                for (int line = firstLine; line <= lastLine; ++line) {
                    var lineTokenization = cacheSnapshot.GetLineTokenization(span.Snapshot.GetLineFromLineNumber(line), tokenizerLazy);

                    foreach (var token in lineTokenization.Tokens.MaybeEnumerate()) {
                        if (line == firstLine && token.Column + token.Length < startCol) {
                            continue;
                        }
                        if (line == lastLine && token.Column > endCol) {
                            continue;
                        }
                        yield return new TrackingTokenInfo(token, line, lineTokenization.Line);
                    }
                }
            }
        }

        public bool DoNotParse {
            get => Buffer.Properties.ContainsProperty(BufferParser.DoNotParse);
            set {
                if (value) {
                    Buffer.Properties[BufferParser.DoNotParse] = BufferParser.DoNotParse;
                } else {
                    Buffer.Properties.RemoveProperty(BufferParser.DoNotParse);
                }
            }
        }

        public bool ParseImmediately {
            get => Buffer.Properties.ContainsProperty(BufferParser.ParseImmediately);
            set {
                if (value) {
                    Buffer.Properties[BufferParser.ParseImmediately] = BufferParser.ParseImmediately;
                } else {
                    Buffer.Properties.RemoveProperty(BufferParser.ParseImmediately);
                }
            }
        }

        #endregion

        #region Token Cache Management
        private Lazy<Tokenizer> GetTokenizerLazy()
            => new Lazy<Tokenizer>(() => new Tokenizer(LanguageVersion, options: TokenizerOptions.Verbatim | TokenizerOptions.VerbatimCommentsAndLineJoins));

        private void ClearTokenCache() => _tokenCache.Clear();

        private void UpdateTokenCache(TextContentChangedEventArgs e) {
            // NOTE: Runs on background thread

            var snapshot = e.After;
            if (snapshot.TextBuffer != Buffer) {
                Debug.Fail("Mismatched buffer");
                return;
            }

            if (snapshot.IsReplBufferWithCommand()) {
                return;
            }

            // Prevent later updates overwriting our tokenization
            _tokenCache.Update(e, GetTokenizerLazy());
        }
        #endregion

        #region Diagnostic Tracing

        private static readonly Lazy<bool> _shouldUseTraceLog = new Lazy<bool>(GetShouldUseTraceLog);
        private static bool GetShouldUseTraceLog() {
            using (var root = Win32.Registry.CurrentUser.OpenSubKey(PythonCoreConstants.LoggingRegistrySubkey, false)) {
                var value = root?.GetValue("BufferInfo", null);
                int? asInt = value as int?;
                if (asInt.HasValue) {
                    if (asInt.GetValueOrDefault() == 0) {
                        // REG_DWORD but 0 means no logging
                        return false;
                    }
                } else if (string.IsNullOrEmpty(value as string)) {
                    // Empty string or no value means no logging
                    return false;
                }
            }
            return true;
        }

        private AnalysisLogWriter OpenTraceLog() {
            if (!_shouldUseTraceLog.Value) {
                return null;
            }
            return new AnalysisLogWriter(
                PathUtils.GetAvailableFilename(Path.GetTempPath(), "PythonTools_Buffer_{0}_{1:yyyyMMddHHmmss}".FormatInvariant(PathUtils.GetFileOrDirectoryName(_filename.Value), DateTime.Now), ".log"),
                false,
                false,
                cacheSize: 1
            );
        }

        internal void Trace(string eventName, params object[] args) {
            _traceLog?.Log(eventName, args);
        }

        private void TraceWithStack(string eventName, params object[] args) {
            if (_traceLog != null) {
                var stack = new StackTrace(1, true).ToString().Replace("\r\n", "").Replace("\n", "");
                _traceLog.Log(eventName, args.Concat(Enumerable.Repeat(stack, 1)).ToArray());
                _traceLog.Flush();
            }
        }

        #endregion
    }

    static class PythonTextBufferInfoExtensions {
        public static PythonTextBufferInfo TryGetInfo(this ITextBuffer buffer) => PythonTextBufferInfo.TryGetForBuffer(buffer);

        public static AnalysisEntry TryGetAnalysisEntry(this ITextBuffer buffer) => PythonTextBufferInfo.TryGetForBuffer(buffer)?.AnalysisEntry;

        public static Task<AnalysisEntry> GetAnalysisEntryAsync(this ITextBuffer buffer, PythonEditorServices services = null, CancellationToken cancellationToken = default(CancellationToken)) {
            var bi = services == null ? PythonTextBufferInfo.TryGetForBuffer(buffer) : services.GetBufferInfo(buffer);
            if (bi != null) {
                return bi.GetAnalysisEntryAsync(cancellationToken);
            }
            return Task.FromResult<AnalysisEntry>(null);
        }

        public static AnalysisEntry TryGetAnalysisEntry(this ITextView view, IServiceProvider site) {
            var entry = view.TextBuffer.TryGetAnalysisEntry();
            if (entry != null) {
                return entry;
            }

            var diffViewer = site.GetComponentModel().GetService<IWpfDifferenceViewerFactoryService>();
            var viewer = diffViewer?.TryGetViewerForTextView(view);
            if (viewer != null) {
                entry = viewer.DifferenceBuffer.RightBuffer.TryGetAnalysisEntry() ??
                    viewer.DifferenceBuffer.LeftBuffer.TryGetAnalysisEntry();
                if (entry != null) {
                    return entry;
                }
            }

            return null;
        }

        public static async Task<ProjectAnalyzer> FindAnalyzerAsync(this IServiceProvider site, ITextView view) {
            ProjectAnalyzer analyzer;

            var bi = view.TextBuffer.TryGetInfo();
            if (bi != null && (analyzer = await FindAnalyzerAsync(site, bi)) != null) {
                return analyzer;
            }

            site.MustBeCalledFromUIThread();
            var diffViewer = site.GetComponentModel().GetService<IWpfDifferenceViewerFactoryService>();
            var viewer = diffViewer?.TryGetViewerForTextView(view);
            if (viewer != null) {
                bi = viewer.DifferenceBuffer.RightBuffer.TryGetInfo();
                if (bi != null && (analyzer = await FindAnalyzerAsync(site, bi)) != null) {
                    return analyzer;
                }
                bi = viewer.DifferenceBuffer.LeftBuffer.TryGetInfo();
                if (bi != null && (analyzer = await FindAnalyzerAsync(site, bi)) != null) {
                    return analyzer;
                }
            }

            return null;
        }

        public static async Task<ProjectAnalyzer> FindAnalyzerAsync(this IServiceProvider site, PythonTextBufferInfo buffer) {
            ProjectAnalyzer analyzer;

            // If we have an analyzer in Properties, we will use that
            // NOTE: This should only be used for tests.
            if (buffer.Buffer.Properties.TryGetProperty(VsProjectAnalyzer._testAnalyzer, out analyzer)) {
                return analyzer;
            }

            // If we have a REPL evaluator we'll use its analyzer
            if (buffer.Buffer.GetInteractiveWindow()?.Evaluator is IPythonInteractiveIntellisense evaluator) {
                return await evaluator.GetAnalyzerAsync();
            }

            // If the file is associated with a project, use its analyzer
            analyzer = await site.GetUIThread().InvokeTask(() => {
                var p = site.GetProjectFromFile(buffer.Filename);
                if (p != null) {
                    return p.GetAnalyzerAsync();
                }
                return Task.FromResult<VsProjectAnalyzer>(null);
            });
            if (analyzer != null) {
                return analyzer;
            }

            var workspaceAnalysis = site.GetComponentModel().GetService<WorkspaceAnalysis>();
            analyzer = await workspaceAnalysis.GetAnalyzerAsync();
            if (analyzer != null) {
                return analyzer;
            }

            return null;
        }

        public static async Task<ProjectAnalyzer> FindAnalyzerAsync(this IServiceProvider site, string filename) {
            return (await FindAllAnalyzersForFile(site, filename, true)).FirstOrDefault() ??
                (await site.GetPythonToolsService().GetSharedAnalyzerAsync());
        }

        public static Task<IReadOnlyList<ProjectAnalyzer>> FindAllAnalyzersForFile(this IServiceProvider site, string filename) {
            return FindAllAnalyzersForFile(site, filename, false);
        }

        private static async Task<IReadOnlyList<ProjectAnalyzer>> FindAllAnalyzersForFile(this IServiceProvider site, string filename, bool firstOnly) {
            if (string.IsNullOrEmpty(filename)) {
                throw new ArgumentNullException(nameof(filename));
            }

            var found = new HashSet<ProjectAnalyzer>();

            // If we have an open document, return that
            var buffer = site.GetTextBufferFromOpenFile(filename)?.TryGetInfo();
            if (buffer != null) {
                var analyzer = await site.FindAnalyzerAsync(buffer);
                if (analyzer != null) {
                    found.Add(analyzer);
                    if (firstOnly) {
                        return found.ToArray();
                    }
                }
            }

            var workspaceAnalysis = site.GetComponentModel().GetService<WorkspaceAnalysis>();
            var workspaceAnalyzer = workspaceAnalysis.TryGetWorkspaceAnalyzer();
            if (workspaceAnalyzer != null) {
                found.Add(workspaceAnalyzer);
                if (firstOnly) {
                    return found.ToArray();
                }
            }

            // Yield all loaded projects containing the file
            var sln = (IVsSolution)site.GetService(typeof(SVsSolution));
            if (sln != null) {
                if (Path.IsPathRooted(filename)) {
                    foreach (var project in sln.EnumerateLoadedPythonProjects()) {
                        if (project.FindNodeByFullPath(filename) != null) {
                            var analyzer = project.TryGetAnalyzer();
                            if (analyzer != null) {
                                found.Add(analyzer);
                                if (firstOnly) {
                                    return found.ToArray();
                                }
                            }
                        }
                    }
                } else {
                    var withSlash = "\\" + filename;
                    foreach (var project in sln.EnumerateLoadedPythonProjects()) {
                        if (project.AllVisibleDescendants.Any(n => n.Url.Equals(filename, StringComparison.OrdinalIgnoreCase) ||
                            n.Url.EndsWithOrdinal(withSlash, ignoreCase: true))) {
                            var analyzer = project.TryGetAnalyzer();
                            if (analyzer != null) {
                                found.Add(analyzer);
                                if (firstOnly) {
                                    return found.ToArray();
                                }
                            }
                        }
                    }
                }
            }

            return found.ToArray();
        }
    }
}


text:
package org.kurento.test.functional.composite;

import java.awt.Color;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.TimeUnit;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runners.Parameterized.Parameters;
import org.kurento.client.Composite;
import org.kurento.client.GStreamerFilter;
import org.kurento.client.HubPort;
import org.kurento.client.MediaPipeline;
import org.kurento.client.WebRtcEndpoint;
import org.kurento.test.base.FunctionalTest;
import org.kurento.test.browser.Browser;
import org.kurento.test.browser.BrowserType;
import org.kurento.test.browser.WebPageType;
import org.kurento.test.browser.WebRtcChannel;
import org.kurento.test.browser.WebRtcMode;
import org.kurento.test.config.BrowserScope;
import org.kurento.test.config.TestScenario;

/**
 * Four synthetic videos are played by four WebRtcEndpoint and mixed by a Composite. The resulting
 * video is played in an WebRtcEndpoint. At the end, a B&N filter is connected in one of the
 * WebRTC's
 *

 * Media Pipeline(s):
 *

 *
4xWebRtcEndpoint -> Composite -> WebRtcEndpoint

 *
1xWebRtcEndpoint -> GStreamerFilter

 *

 * Browser(s):
 *

 *
5 x Chrome

 *

 * Test logic:
 *

 *
(KMS) Media server implements a grid with the media from 4 WebRtcEndpoints and sends the
 * resulting media to another WebRtcEndpoint. Then the media of one the WebRtcEndpoint is filtered
 * with GStreamerFilter (B&N video)

 *
(Browser) WebRtcPeer in rcv-only receives media

 *

 * Main assertion(s):
 *

 *
Color of the video should be the expected in the right position (grid)

 *

 * Secondary assertion(s):
 *

 *
Playing event should be received in remote video tag

 *

 *
 * @author Boni Garcia (bgarcia@gsyc.es)
 * @since 4.2.3
 */
public class CompositeWebRtcTest extends FunctionalTest {

  private static final String BROWSER1 = "browser1";
  private static final String BROWSER2 = "browser2";
  private static final String BROWSER3 = "browser3";
  private static final String BROWSER4 = "browser4";
  private static final String BROWSER5 = "browser5";

  private static int PLAYTIME = 5;

  @Parameters(name = "{index}: {0}")
  public static Collection<Object[]> data() {
    // Test: 5 local Chrome's
    TestScenario test = new TestScenario();
    test.addBrowser(BROWSER1, new Browser.Builder().browserType(BrowserType.CHROME)
        .webPageType(WebPageType.WEBRTC).scope(BrowserScope.LOCAL).build());
    test.addBrowser(BROWSER2,
        new Browser.Builder().browserType(BrowserType.CHROME).webPageType(WebPageType.WEBRTC)
            .scope(BrowserScope.LOCAL).video(getTestFilesDiskPath() + "/video/10sec/red.y4m")
            .build());
    test.addBrowser(BROWSER3,
        new Browser.Builder().browserType(BrowserType.CHROME).webPageType(WebPageType.WEBRTC)
            .scope(BrowserScope.LOCAL).video(getTestFilesDiskPath() + "/video/10sec/green.y4m")
            .build());
    test.addBrowser(BROWSER4,
        new Browser.Builder().browserType(BrowserType.CHROME).webPageType(WebPageType.WEBRTC)
            .scope(BrowserScope.LOCAL).video(getTestFilesDiskPath() + "/video/10sec/blue.y4m")
            .build());
    test.addBrowser(BROWSER5,
        new Browser.Builder().browserType(BrowserType.CHROME).webPageType(WebPageType.WEBRTC)
            .scope(BrowserScope.LOCAL).video(getTestFilesDiskPath() + "/video/10sec/white.y4m")
            .build());
    return Arrays.asList(new Object[][] { { test } });
  }

  @Test
  public void testCompositeWebRtc() throws Exception {
    // Media Pipeline
    MediaPipeline mp = kurentoClient.createMediaPipeline();
    WebRtcEndpoint webRtcEpRed = new WebRtcEndpoint.Builder(mp).build();
    WebRtcEndpoint webRtcEpGreen = new WebRtcEndpoint.Builder(mp).build();
    WebRtcEndpoint webRtcEpBlue = new WebRtcEndpoint.Builder(mp).build();

    Composite composite = new Composite.Builder(mp).build();
    HubPort hubPort1 = new HubPort.Builder(composite).build();
    HubPort hubPort2 = new HubPort.Builder(composite).build();
    HubPort hubPort3 = new HubPort.Builder(composite).build();

    webRtcEpRed.connect(hubPort1);
    webRtcEpGreen.connect(hubPort2);
    webRtcEpBlue.connect(hubPort3);

    WebRtcEndpoint webRtcEpWhite = new WebRtcEndpoint.Builder(mp).build();
    HubPort hubPort4 = new HubPort.Builder(composite).build();
    webRtcEpWhite.connect(hubPort4);

    WebRtcEndpoint webRtcEpComposite = new WebRtcEndpoint.Builder(mp).build();
    HubPort hubPort5 = new HubPort.Builder(composite).build();
    hubPort5.connect(webRtcEpComposite);

    // WebRTC browsers
    getPage(BROWSER2).initWebRtc(webRtcEpRed, WebRtcChannel.AUDIO_AND_VIDEO, WebRtcMode.SEND_ONLY);
    getPage(BROWSER3).initWebRtc(webRtcEpGreen, WebRtcChannel.AUDIO_AND_VIDEO,
        WebRtcMode.SEND_ONLY);
    getPage(BROWSER4).initWebRtc(webRtcEpBlue, WebRtcChannel.AUDIO_AND_VIDEO, WebRtcMode.SEND_ONLY);
    getPage(BROWSER5).initWebRtc(webRtcEpWhite, WebRtcChannel.AUDIO_AND_VIDEO,
        WebRtcMode.SEND_ONLY);

    getPage(BROWSER1).subscribeEvents("playing");
    getPage(BROWSER1).initWebRtc(webRtcEpComposite, WebRtcChannel.AUDIO_AND_VIDEO,
        WebRtcMode.RCV_ONLY);

    // Assertions
    Assert.assertTrue("Not received media (timeout waiting playing event)",
        getPage(BROWSER1).waitForEvent("playing"));
    Assert.assertTrue("Upper left part of the video must be red",
        getPage(BROWSER1).similarColorAt(Color.RED, 0, 0));
    Assert.assertTrue("Upper right part of the video must be green",
        getPage(BROWSER1).similarColorAt(Color.GREEN, 450, 0));
    Assert.assertTrue("Lower left part of the video must be blue",
        getPage(BROWSER1).similarColorAt(Color.BLUE, 0, 450));
    Assert.assertTrue("Lower right part of the video must be white",
        getPage(BROWSER1).similarColorAt(Color.WHITE, 450, 450));

    // Finally, a black & white filter is connected to one WebRTC
    GStreamerFilter bwFilter =
        new GStreamerFilter.Builder(mp, "videobalance saturation=0.0").build();
    webRtcEpRed.connect(bwFilter);
    bwFilter.connect(hubPort1);
    Thread.sleep(TimeUnit.SECONDS.toMillis(PLAYTIME));
    Assert.assertTrue("When connecting the filter, the upper left part of the video must be gray",
        getPage(BROWSER1).similarColorAt(new Color(75, 75, 75), 0, 0));

    // Release Media Pipeline
    mp.release();
  }

}


text:
<?php

namespace Microsoft\Dynamics\Model;

use SaintSystems\OData\Entity;

/**
* OpportunityClose class
*
* OpportunityClose entity
*
* @category  Model
* @package   Microsoft.Dynamics
* @license   https://opensource.org/licenses/MIT MIT License
* @link      https://www.microsoft.com/en-us/dynamics365/
*/
class OpportunityClose extends Entity
{
     /**
     * The entity set name associated with the entity.
     * This is needed for API calls since this is the API endpoint for this Entity
     *
     * @var string
     */
    static $entity = 'opportunitycloses';

    /**
     * The name of the attribute that is the primary id for the entity.
     * PrimaryIdAttribute from https://msdn.microsoft.com/en-us/library/mt607760.aspx
     *
     * @var string
     */
    static $primaryKey = 'activityid';
}


text:
<?php

/**
 * This file is part of the Minty templating library.
 * (c) Dániel Buga <daniel@bugadani.hu>
 *
 * For licensing information see the LICENSE file.
 */

namespace Minty\Compiler\Tags;

use Minty\Compiler\Tag;

class ElseTag extends Tag
{
    public function getTag()
    {
        return 'else';
    }
}


text:
//=============================================================================
/**
 *  @file    Reactor_Dispatch_Order_Test.cpp
 *
 *  $Id: Reactor_Dispatch_Order_Test.cpp 93638 2011-03-24 13:16:05Z johnnyw $
 *
 *  This is a simple test that checks the order of dispatching of
 *  ACE Reactors.  Order should be: timeout, output, and then input.
 *
 *
 *  @author Irfan Pyarali <irfan@cs.wustl.edu>
 */
//=============================================================================

#include "test_config.h"
#include "ace/OS_NS_string.h"
#include "ace/Reactor.h"
#include "ace/Select_Reactor.h"
#include "ace/WFMO_Reactor.h"
#include "ace/Dev_Poll_Reactor.h"
#include "ace/Pipe.h"
#include "ace/ACE.h"

static const char *message =
"Hello there! Hope you get this message";

class Handler : public ACE_Event_Handler
{
public:
  Handler (ACE_Reactor &reactor);

  ~Handler();

  int handle_timeout (const ACE_Time_Value &tv,
                      const void *arg);

  int handle_input (ACE_HANDLE fd);

  int handle_output (ACE_HANDLE fd);

  ACE_HANDLE get_handle (void) const;

  // We need to add MSG_OOB data transfer to this test to check the
  // order of when <handle_exception> gets called.  I tried with
  // Windows 2000 but only one byte of the message came across as
  // urgent data.  The rest of the data was treated as normal! There
  // was some explanation of Microsoft's TCP/IP deals with out-of-band
  // data in "Out-of-Band Data and Push Bit in TCP/IP" in the MSDN
  // library.  However, I did not comprehend that well enough.  If
  // someone can make this work, please check the order of
  // <handle_exception> getting called.
  // int handle_exception (ACE_HANDLE fd);

  ACE_Pipe pipe_;

  int dispatch_order_;
  bool ok_;           // Constructed and initialized ok
};

Handler::Handler (ACE_Reactor &reactor)
  : ACE_Event_Handler (&reactor),
    dispatch_order_ (1),
    ok_ (false)
{
  // Create the pipe.
  if (0 != this->pipe_.open ())
    ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("pipe")));
  else
    {
      // Register for all events.
      if (0 != this->reactor ()->register_handler
                 (this->pipe_.read_handle (),
                  this,
                  ACE_Event_Handler::READ_MASK | ACE_Event_Handler::WRITE_MASK))
        ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("register")));
      else
        this->ok_ = true;
    }
}

Handler::~Handler (void)
{
  this->pipe_.close ();
}

ACE_HANDLE
Handler::get_handle (void) const
{
  return this->pipe_.read_handle ();
}

int
Handler::handle_timeout (const ACE_Time_Value &,
                         const void *)
{
  int const me = this->dispatch_order_++;
  if (me != 1)
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("handle_timeout should be #1; it's %d\n"),
                me));
  else
    ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Handler::handle_timeout\n")));

  return 0;
}

int
Handler::handle_output (ACE_HANDLE)
{
  int const me = this->dispatch_order_++;
  if (me != 2)
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("handle_output should be #2; it's %d\n"),
                me));
  else
    ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Handler::handle_output\n")));

#if defined (__OpenBSD__) || defined (ACE_VXWORKS)
  // All that we need written has been written, so don't
  // call handle_output again.
  this->reactor ()->mask_ops (this->pipe_.read_handle (),
                              ACE_Event_Handler::WRITE_MASK,
                              ACE_Reactor::CLR_MASK);
#endif /* __OpenBSD__ || ACE_VXWORKS */

  return 0;
}

int
Handler::handle_input (ACE_HANDLE fd)
{
  int const me = this->dispatch_order_++;
  if (me != 3)
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("handle_input should be #3; it's %d\n"),
                me));

  char buffer[BUFSIZ];
  ssize_t result = ACE::recv (fd, buffer, sizeof buffer);
  if (result != ssize_t (ACE_OS::strlen (message)))
    ACE_ERROR ((LM_ERROR, ACE_TEXT ("Handler recv'd %b bytes; expected %B\n"),
                result, ACE_OS::strlen (message)));
  buffer[result] = '\0';

  ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Handler::handle_input: %C\n"), buffer));

  if (ACE_OS::strcmp (buffer, message) != 0)
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("Handler text mismatch; received \"%C\"; ")
                ACE_TEXT ("expected \"%C\"\n"),
                buffer, message));

  this->reactor ()->end_reactor_event_loop ();

  return 0;
}

static bool
test_reactor_dispatch_order (ACE_Reactor &reactor)
{
  Handler handler (reactor);
  if (!handler.ok_)
    {
      ACE_ERROR ((LM_ERROR, ACE_TEXT ("Error initializing test; abort.\n")));
      return false;
    }

  bool ok_to_go = true;

  // This should trigger a call to <handle_input>.
  ssize_t result =
    ACE::send_n (handler.pipe_.write_handle (),
                 message,
                 ACE_OS::strlen (message));
  if (result != ssize_t (ACE_OS::strlen (message)))
    {
      ACE_ERROR ((LM_ERROR, ACE_TEXT ("Handler sent %b bytes; should be %B\n"),
                  result, ACE_OS::strlen (message)));
      ok_to_go = false;
    }

  // This should trigger a call to <handle_timeout>.
  if (-1 == reactor.schedule_timer (&handler,
                                    0,
                                    ACE_Time_Value (0)))
    {
      ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("schedule_timer")));
      ok_to_go = false;
    }

  // Suspend the handlers - only the timer should be dispatched
  ACE_Time_Value tv (1);
  reactor.suspend_handlers ();
  if (0 != reactor.run_reactor_event_loop (tv))
    {
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("%p\n"),
                  ACE_TEXT ("run_reactor_event_loop")));
      ok_to_go = false;
    }

  // only the timer should have fired
  if (handler.dispatch_order_ != 2)
    {
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("Incorrect number fired %d; expected 2\n"),
                  handler.dispatch_order_));
      ok_to_go = false;
    }

  // Reset the dispatch_order_ count and schedule another timer
  handler.dispatch_order_ = 1;
  if (-1 == reactor.schedule_timer (&handler,
                                    0,
                                    ACE_Time_Value (0)))
    {
      ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("schedule_timer")));
      ok_to_go = false;
    }

  // Resume the handlers - things should work now
  reactor.resume_handlers ();

  if (ok_to_go)
    {
      if (0 != reactor.run_reactor_event_loop (tv))
        {
          ACE_ERROR ((LM_ERROR,
                      ACE_TEXT ("%p\n"),
                      ACE_TEXT ("run_reactor_event_loop 2")));
          ok_to_go = false;
        }
    }

  if (0 != reactor.remove_handler (handler.pipe_.read_handle (),
                                   ACE_Event_Handler::ALL_EVENTS_MASK |
                                   ACE_Event_Handler::DONT_CALL))
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("%p\n"),
                ACE_TEXT ("remover_handler pipe")));

  if (handler.dispatch_order_ != 4)
    {
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("Incorrect number fired %d; expected 4\n"),
                  handler.dispatch_order_));
      ok_to_go = false;
    }

  int nr_cancelled = reactor.cancel_timer (&handler);
  if (nr_cancelled > 0)
    ACE_ERROR ((LM_ERROR,
                ACE_TEXT ("Finishing test with %d timers still scheduled\n"),
                nr_cancelled));
  return ok_to_go;
}

int
run_main (int, ACE_TCHAR *[])
{
  ACE_START_TEST (ACE_TEXT ("Reactor_Dispatch_Order_Test"));

  int result = 0;
  ACE_Select_Reactor select_reactor_impl;
  ACE_Reactor select_reactor (&select_reactor_impl);
  ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Testing ACE_Select_Reactor\n")));
  if (!test_reactor_dispatch_order (select_reactor))
    ++result;

  // Winsock 2 things are needed for WFMO_Reactor.
#if defined (ACE_WIN32) && \
    (defined (ACE_HAS_WINSOCK2) && (ACE_HAS_WINSOCK2 != 0))

  ACE_WFMO_Reactor wfmo_reactor_impl;
  ACE_Reactor wfmo_reactor (&wfmo_reactor_impl);
  ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Testing ACE_WFMO_Reactor\n")));
  if (!test_reactor_dispatch_order (wfmo_reactor))
    ++result;

#endif /* ACE_WIN32 && ACE_HAS_WINSOCK2 */

  ACE_END_TEST;
  return result;
}


text:
from sprokit.pipeline import config
from sprokit.pipeline import pipeline
from sprokit.pipeline import scheduler

class TestPythonScheduler(scheduler.PythonScheduler):
    def __init__(self, conf, pipe):
        scheduler.PythonScheduler.__init__(self, conf, pipe)

def __sprokit_register__():
    from sprokit.pipeline import scheduler_registry

    module_name = 'python:test.pythonpath.test'

    reg = scheduler_registry.SchedulerRegistry.self()

    if reg.is_module_loaded(module_name):
        return

    reg.register_scheduler('pythonpath_test_scheduler', 'A test scheduler.', TestPythonScheduler)

    reg.mark_module_as_loaded(module_name)


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="@dimen/menu_line_height"
  tools:background="#40FF0000">
  <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <ImageView
      android:id="@+id/search"
      style="@style/MwmTheme.Menu.Line.Button"
      android:src="@drawable/ic_menu_search"
      android:tag="@string/tag_menu_collapse"/>

    <Space
      android:layout_width="0dp"
      android:layout_height="match_parent"
      android:layout_weight="1"/>

    <ImageView
      android:id="@+id/p2p"
      style="@style/MwmTheme.Menu.Line.Button"
      android:src="@drawable/ic_menu_point_to_point"
      android:tag="@string/tag_menu_collapse"/>

    <Space
      android:layout_width="0dp"
      android:layout_height="match_parent"
      android:layout_weight="1"/>

    <ImageView
      android:id="@+id/discovery"
      style="@style/MwmTheme.Menu.Line.Button"
      android:src="@drawable/ic_menu_discovery"
      android:tag="@string/tag_menu_collapse"/>

    <Space
      android:layout_width="0dp"
      android:layout_height="match_parent"
      android:layout_weight="1"/>

    <ImageView
      android:id="@+id/bookmarks"
      style="@style/MwmTheme.Menu.Line.Button"
      android:src="@drawable/ic_menu_bookmarks"
      android:tag="@string/tag_menu_collapse"/>

    <Space
      android:layout_width="0dp"
      android:layout_height="match_parent"
      android:layout_weight="1"/>

    <!-- Gap for menu open/close button -->
    <View
      android:id="@+id/menu"
      android:layout_width="@dimen/menu_line_button_width_edge"
      android:layout_height="match_parent"/>
  </LinearLayout>

  <FrameLayout
    android:layout_width="@dimen/menu_line_button_width_edge"
    android:layout_height="match_parent"
    android:layout_gravity="end">
    <include layout="@layout/menu_news_marker"/>
  </FrameLayout>
</FrameLayout>


text:
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

using Amazon.Runtime;
using Amazon.Runtime.Internal;

namespace Amazon.SimpleWorkflow.Model
{
    ///
    /// Container for the parameters to the PollForDecisionTask operation.
    /// <para> Used by deciders to get a DecisionTask from the specified decision <c>taskList</c> .
    /// A decision task may be returned for any open workflow execution that is using the specified task list. The task includes a paginated
    /// view of the history of the workflow execution. The decider should use the workflow type and the history to determine how to properly handle
    /// the task. </para> <para> This action initiates a long poll, where the service holds the HTTP connection open and responds as soon a task
    /// becomes available. If no decision task is available in the specified task list before the timeout of 60 seconds expires, an empty result is
    /// returned. An empty result, in this context, means that a DecisionTask is returned, but that the value of taskToken is an empty string.
    /// </para> <para>IMPORTANT: Deciders should set their client side socket timeout to at least 70 seconds (10 seconds higher than the
    /// timeout). </para> <para>IMPORTANT: Because the number of workflow history events for a single workflow execution might be very large,
    /// the result returned might be split up across a number of pages. To retrieve subsequent pages, make additional calls to PollForDecisionTask
    /// using the nextPageToken returned by the initial call. Note that you do not call GetWorkflowExecutionHistory with this nextPageToken.
    /// Instead, call PollForDecisionTask again. </para> <para> Access Control </para> <para>You can use IAM policies to control this
    /// action's access to Amazon SWF resources as follows:</para>
    ///

    ///
Use a <c>Resource</c> element with the domain name to limit the action to only specified domains.

    ///
Use an <c>Action</c> element to allow or deny permission to call this action.

    ///
Use a Condition element with the <c>swf:taskList.name</c> key to allow the action to access only certain task lists.

    ///
    ///

    /// <para>If the caller does not have sufficient permissions to invoke the action, or the parameter values fall outside the specified
    /// constraints, the action fails by throwing <c>OperationNotPermitted</c> . For details and example IAM policies, see Using IAM to Manage
    /// Access to Amazon SWF Workflows.</para>
    ///
    /// <seealso cref="Amazon.SimpleWorkflow.AmazonSimpleWorkflow.PollForDecisionTask"/>
    public class PollForDecisionTaskRequest : AmazonWebServiceRequest
    {
        private string domain;
        private TaskList taskList;
        private string identity;
        private string nextPageToken;
        private int? maximumPageSize;
        private bool? reverseOrder;

        ///
        /// The name of the domain containing the task lists to poll.
        ///
        /// <para>
        /// Constraints:
        /// <list type="definition">
        ///     <item>
        ///         <term>Length</term>
        ///         <description>1 - 256</description>
        ///     </item>
        /// </list>
        /// </para>
        ///
        public string Domain
        {
            get { return this.domain; }
            set { this.domain = value; }
        }

        ///
        /// Sets the Domain property
        ///
        /// <param name="domain">The value to set for the Domain property </param>
        /// <returns>this instance</returns>
        [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
        public PollForDecisionTaskRequest WithDomain(string domain)
        {
            this.domain = domain;
            return this;
        }

        // Check to see if Domain property is set
        internal bool IsSetDomain()
        {
            return this.domain != null;
        }

        ///
        /// Specifies the task list to poll for decision tasks. The specified string must not start or end with whitespace. It must not contain a
        /// <c>:</c> (colon), <c>/</c> (slash), <c>|</c> (vertical bar), or any control characters (\u0000-\u001f | \u007f - \u009f). Also, it must not
        /// contain the literal string "arn".
        ///
        ///
        public TaskList TaskList
        {
            get { return this.taskList; }
            set { this.taskList = value; }
        }

        ///
        /// Sets the TaskList property
        ///
        /// <param name="taskList">The value to set for the TaskList property </param>
        /// <returns>this instance</returns>
        [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
        public PollForDecisionTaskRequest WithTaskList(TaskList taskList)
        {
            this.taskList = taskList;
            return this;
        }

        // Check to see if TaskList property is set
        internal bool IsSetTaskList()
        {
            return this.taskList != null;
        }

        ///
        /// Identity of the decider making the request, which is recorded in the DecisionTaskStarted event in the workflow history. This enables
        /// diagnostic tracing when problems arise. The form of this identity is user defined.
        ///
        /// <para>
        /// Constraints:
        /// <list type="definition">
        ///     <item>
        ///         <term>Length</term>
        ///         <description>0 - 256</description>
        ///     </item>
        /// </list>
        /// </para>
        ///
        public string Identity
        {
            get { return this.identity; }
            set { this.identity = value; }
        }

        ///
        /// Sets the Identity property
        ///
        /// <param name="identity">The value to set for the Identity property </param>
        /// <returns>this instance</returns>
        [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
        public PollForDecisionTaskRequest WithIdentity(string identity)
        {
            this.identity = identity;
            return this;
        }

        // Check to see if Identity property is set
        internal bool IsSetIdentity()
        {
            return this.identity != null;
        }

        ///
        /// If on a previous call to this method a <c>NextPageToken</c> was returned, the results are being paginated. To get the next page of results,
        /// repeat the call with the returned token and all other arguments unchanged. <note>The <c>nextPageToken</c> returned by this action cannot be
        /// used with GetWorkflowExecutionHistory to get the next page. You must call PollForDecisionTask again (with the
        /// <c>nextPageToken</c>) to retrieve the next page of history records. Calling PollForDecisionTask with a <c>nextPageToken</c> will not
        /// return a new decision task.</note>.
        ///
        /// <para>
        /// Constraints:
        /// <list type="definition">
        ///     <item>
        ///         <term>Length</term>
        ///         <description>0 - 2048</description>
        ///     </item>
        /// </list>
        /// </para>
        ///
        public string NextPageToken
        {
            get { return this.nextPageToken; }
            set { this.nextPageToken = value; }
        }

        ///
        /// Sets the NextPageToken property
        ///
        /// <param name="nextPageToken">The value to set for the NextPageToken property </param>
        /// <returns>this instance</returns>
        [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
        public PollForDecisionTaskRequest WithNextPageToken(string nextPageToken)
        {
            this.nextPageToken = nextPageToken;
            return this;
        }

        // Check to see if NextPageToken property is set
        internal bool IsSetNextPageToken()
        {
            return this.nextPageToken != null;
        }

        ///
        /// The maximum number of history events returned in each page. The default is 100, but the caller can override this value to a page size
        /// smaller than the default. You cannot specify a page size greater than 100. Note that the number of events may be less than the
        /// maxiumum page size, in which case, the returned page will have fewer results than the maximumPageSize specified.
        ///
        /// <para>
        /// Constraints:
        /// <list type="definition">
        ///     <item>
        ///         <term>Range</term>
        ///         <description>0 - 1000</description>
        ///     </item>
        /// </list>
        /// </para>
        ///
        public int MaximumPageSize
        {
            get { return this.maximumPageSize ?? default(int); }
            set { this.maximumPageSize = value; }
        }

        ///
        /// Sets the MaximumPageSize property
        ///
        /// <param name="maximumPageSize">The value to set for the MaximumPageSize property </param>
        /// <returns>this instance</returns>
        [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
        public PollForDecisionTaskRequest WithMaximumPageSize(int maximumPageSize)
        {
            this.maximumPageSize = maximumPageSize;
            return this;
        }

        // Check to see if MaximumPageSize property is set
        internal bool IsSetMaximumPageSize()
        {
            return this.maximumPageSize.HasValue;
        }

        ///
        /// When set to <c>true</c>, returns the events in reverse order. By default the results are returned in ascending order of the
        /// <c>eventTimestamp</c> of the events.
        ///
        ///
        public bool ReverseOrder
        {
            get { return this.reverseOrder ?? default(bool); }
            set { this.reverseOrder = value; }
        }

        ///
        /// Sets the ReverseOrder property
        ///
        /// <param name="reverseOrder">The value to set for the ReverseOrder property </param>
        /// <returns>this instance</returns>
        [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
        public PollForDecisionTaskRequest WithReverseOrder(bool reverseOrder)
        {
            this.reverseOrder = reverseOrder;
            return this;
        }

        // Check to see if ReverseOrder property is set
        internal bool IsSetReverseOrder()
        {
            return this.reverseOrder.HasValue;
        }
    }
}


text:
using SuggestionBox.Data.Entities;
using ToolKit.Data;
using ToolKit.Data.NHibernate;

namespace SuggestionBox.Data.Repositories
{
    /// <summary>
    /// Question Like Repository
    /// </summary>
    public class QuestionLikeRepository : Repository<QuestionLike, int>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="QuestionLikeRepository"/> class.
        /// </summary>
        public QuestionLikeRepository()
        {
            if (!SessionPool.Contains("feedback"))
            {
                SessionPool.Add("feedback", Database.Feedback);
            }

            Context = new NHibernateUnitOfWork(SessionPool.Session("feedback"));
        }
    }
}


text:
package org.apache.hadoop.hdfs.tools;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.PrivilegedExceptionAction;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.hdfs.server.namenode.NameNode;
import org.apache.hadoop.hdfs.server.namenode.NamenodeFsck;
import org.apache.hadoop.hdfs.HdfsConfiguration;
import org.apache.hadoop.security.Krb5AndCertsSslSocketConnector;
import org.apache.hadoop.security.SecurityUtil;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

/**
 * This class provides rudimentary checking of DFS volumes for errors and
 * sub-optimal conditions.
 *
The tool scans all files and directories, starting from an indicated
 *  root path. The following abnormal conditions are detected and handled:

 *

 *
files with blocks that are completely missing from all datanodes.

 * In this case the tool can perform one of the following actions:
 *

 *
none ({@link org.apache.hadoop.hdfs.server.namenode.NamenodeFsck#FIXING_NONE})

 *
move corrupted files to /lost+found directory on DFS
 *      ({@link org.apache.hadoop.hdfs.server.namenode.NamenodeFsck#FIXING_MOVE}). Remaining data blocks are saved as a
 *      block chains, representing longest consecutive series of valid blocks.

 *
delete corrupted files ({@link org.apache.hadoop.hdfs.server.namenode.NamenodeFsck#FIXING_DELETE})

 *

 *

 *
detect files with under-replicated or over-replicated blocks

 *

 *  Additionally, the tool collects a detailed overall DFS statistics, and
 *  optionally can print detailed statistics on block locations and replication
 *  factors of each file.
 *  The tool also provides and option to filter open files during the scan.
 *
 */
@InterfaceAudience.Private
public class DFSck extends Configured implements Tool {
  static{
    HdfsConfiguration.init();
  }

  private final UserGroupInformation ugi;
  private final PrintStream out;

  /**
   * Filesystem checker.
   * @param conf current Configuration
   */
  public DFSck(Configuration conf) throws IOException {
    this(conf, System.out);
  }

  public DFSck(Configuration conf, PrintStream out) throws IOException {
    super(conf);
    this.ugi = UserGroupInformation.getCurrentUser();
    this.out = out;
  }

  /**
   * Print fsck usage information
   */
  static void printUsage() {
    System.err.println("Usage: DFSck <path> [-list-corruptfileblocks | " +
        "[-move | -delete | -openforwrite] " +
        "[-files [-blocks [-locations | -racks]]]]");
    System.err.println("\t<path>\tstart checking from this path");
    System.err.println("\t-move\tmove corrupted files to /lost+found");
    System.err.println("\t-delete\tdelete corrupted files");
    System.err.println("\t-files\tprint out files being checked");
    System.err.println("\t-openforwrite\tprint out files opened for write");
    System.err.println("\t-list-corruptfileblocks\tprint out list of missing "
        + "blocks and files they belong to");
    System.err.println("\t-blocks\tprint out block report");
    System.err.println("\t-locations\tprint out locations for every block");
    System.err.println("\t-racks\tprint out network topology for data-node locations");
    System.err.println("\t\tBy default fsck ignores files opened for write, " +
                       "use -openforwrite to report such files. They are usually " +
                       " tagged CORRUPT or HEALTHY depending on their block " +
                        "allocation status");
    ToolRunner.printGenericCommandUsage(System.err);
  }
  /**
   * @param args
   */
  public int run(final String[] args) throws IOException {
    if (args.length == 0) {
      printUsage();
      return -1;
    }

    try {
      return UserGroupInformation.getCurrentUser().doAs(
          new PrivilegedExceptionAction<Integer>() {
            @Override
            public Integer run() throws Exception {
              return doWork(args);
            }
          });
    } catch (InterruptedException e) {
      throw new IOException(e);
    }
  }

  /*
   * To get the list, we need to call iteratively until the server says
   * there is no more left.
   */
  private Integer listCorruptFileBlocks(String dir, String baseUrl)
      throws IOException {
    int errCode = -1;
    int numCorrupt = 0;
    String lastBlock = null;
    final String noCorruptLine = "has no CORRUPT files";
    final String noMoreCorruptLine = "has no more CORRUPT files";
    boolean allDone = false;
    while (!allDone) {
      final StringBuffer url = new StringBuffer(baseUrl);
      if (lastBlock != null) {
        url.append("&startblockafter=").append(lastBlock);
      }
      URL path = new URL(url.toString());
      SecurityUtil.fetchServiceTicket(path);
      URLConnection connection = path.openConnection();
      InputStream stream = connection.getInputStream();
      BufferedReader input = new BufferedReader(new InputStreamReader(
          stream, "UTF-8"));
      try {
        String line = null;
        while ((line = input.readLine()) != null) {
          if ((line.endsWith(noCorruptLine)) ||
              (line.endsWith(noMoreCorruptLine)) ||
              (line.endsWith(NamenodeFsck.NONEXISTENT_STATUS))) {
            allDone = true;
            break;
          }
          if ((line.isEmpty())
              || (line.startsWith("FSCK started by"))
              || (line.startsWith("The filesystem under path")))
            continue;
          numCorrupt++;
          if (numCorrupt == 1) {
            out.println("The list of corrupt files under path '"
                + dir + "' are:");
          }
          out.println(line);
          try {
            // Get the block # that we need to send in next call
            lastBlock = line.split("\t")[0];
          } catch (Exception e) {
            allDone = true;
            break;
          }
        }
      } finally {
        input.close();
      }
    }
    out.println("The filesystem under path '" + dir + "' has "
        + numCorrupt + " CORRUPT files");
    if (numCorrupt == 0)
      errCode = 0;
    return errCode;
  }

  private int doWork(final String[] args) throws IOException {
    String proto = "http://";
    if (UserGroupInformation.isSecurityEnabled()) {
      System.setProperty("https.cipherSuites",
          Krb5AndCertsSslSocketConnector.KRB5_CIPHER_SUITES.get(0));
      proto = "https://";
    }
    final StringBuilder url = new StringBuilder(proto);
    url.append(NameNode.getInfoServer(getConf()));
    url.append("/fsck?ugi=").append(ugi.getShortUserName()).append("&path=");

    String dir = "/";
    // find top-level dir first
    for (int idx = 0; idx < args.length; idx++) {
      if (!args[idx].startsWith("-")) { dir = args[idx]; break; }
    }
    url.append(URLEncoder.encode(dir, "UTF-8"));
    boolean doListCorruptFileBlocks = false;
    for (int idx = 0; idx < args.length; idx++) {
      if (args[idx].equals("-move")) { url.append("&move=1"); }
      else if (args[idx].equals("-delete")) { url.append("&delete=1"); }
      else if (args[idx].equals("-files")) { url.append("&files=1"); }
      else if (args[idx].equals("-openforwrite")) { url.append("&openforwrite=1"); }
      else if (args[idx].equals("-blocks")) { url.append("&blocks=1"); }
      else if (args[idx].equals("-locations")) { url.append("&locations=1"); }
      else if (args[idx].equals("-racks")) { url.append("&racks=1"); }
      else if (args[idx].equals("-list-corruptfileblocks")) {
        url.append("&listcorruptfileblocks=1");
        doListCorruptFileBlocks = true;
      }
    }
    if (doListCorruptFileBlocks) {
      return listCorruptFileBlocks(dir, url.toString());
    }
    URL path = new URL(url.toString());
    SecurityUtil.fetchServiceTicket(path);
    URLConnection connection = path.openConnection();
    InputStream stream = connection.getInputStream();
    BufferedReader input = new BufferedReader(new InputStreamReader(
                                              stream, "UTF-8"));
    String line = null;
    String lastLine = null;
    int errCode = -1;
    try {
      while ((line = input.readLine()) != null) {
        out.println(line);
        lastLine = line;
      }
    } finally {
      input.close();
    }
    if (lastLine.endsWith(NamenodeFsck.HEALTHY_STATUS)) {
      errCode = 0;
    } else if (lastLine.endsWith(NamenodeFsck.CORRUPT_STATUS)) {
      errCode = 1;
    } else if (lastLine.endsWith(NamenodeFsck.NONEXISTENT_STATUS)) {
      errCode = 0;
    }
    return errCode;
  }

  static{
    HdfsConfiguration.init();
  }

  public static void main(String[] args) throws Exception {
    // -files option is also used by GenericOptionsParser
    // Make sure that is not the first argument for fsck
    int res = -1;
    if ((args.length == 0 ) || ("-files".equals(args[0])))
      printUsage();
    else
      res = ToolRunner.run(new DFSck(new HdfsConfiguration()), args);
    System.exit(res);
  }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">

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

  <title>reduce_point_density — MetPy 0.11</title>

    <link rel="shortcut icon" href="../../_static/metpy_32x32.ico"/>

    <link rel="canonical" href="https://unidata.github.io/MetPy/latest/api/generated/metpy.calc.reduce_point_density.html"/>

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

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

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

        <link rel="index" title="Index"
              href="../../genindex.html"/>
        <link rel="search" title="Search" href="../../search.html"/>
    <link rel="top" title="MetPy 0.11" href="../../index.html"/>
        <link rel="up" title="calc" href="metpy.calc.html"/>
        <link rel="next" title="resample_nn_1d" href="metpy.calc.resample_nn_1d.html"/>
        <link rel="prev" title="parse_angle" href="metpy.calc.parse_angle.html"/>

             MetPy

                    <select class="version-list" id="version-list">
                      <option value=''>0.11</option>

                          <option value="../latest">latest</option>

                          <option value="../dev">dev</option>

                    </select>

  <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>

Installation Guide

Getting Started with MetPy

Unit Support

Reference/API Examples

Topical Examples

Tutorials

Reference Guide

constants

units

io

calc

Dry Thermodynamics

Moist Thermodynamics

Soundings

Dynamic/Kinematic

Boundary Layer/Turbulence

Mathematical Functions

Apparent Temperature

Standard Atmosphere

Other

angle_to_direction

find_bounding_indices

find_intersections

get_layer

get_layer_heights

get_perturbation

isentropic_interpolation

nearest_intersection_idx

parse_angle

reduce_point_density

resample_nn_1d

smooth_gaussian

smooth_n_point

Deprecated

plots

ctables

interpolate

gridding

xarray

MetPy Roadmap

GEMPAK Conversion Guide

Support

Contributors Guide

Infrastructure Guide

Citing MetPy

References

          MetPy

Docs »

Reference Guide »

calc »

reduce_point_density

                 Improve this page

reduce_point_density¶

metpy.calc.reduce_point_density(points, radius, priority=None)[source]¶

Return a mask to reduce the density of points in irregularly-spaced data.

This function is used to down-sample a collection of scattered points (e.g. surface
data), returning a mask that can be used to select the points from one or more arrays
(e.g. arrays of temperature and dew point). The points selected can be controlled by
providing an array of priority values (e.g. rainfall totals to ensure that
stations with higher precipitation remain in the mask). The points and radius can be
specified with units. If none are provided, meters are assumed.

Parameters

points ((N, K) array-like) – N locations of the points in K dimensional space

radius (pint.Quantity or float) – Minimum radius allowed between points. If units are not provided, meters is assumed.

priority ((N, K) array-like, optional) – If given, this should have the same shape as points; these values will
be used to control selection priority for points.

Returns

(N,) array-like of boolean values indicating whether points should be kept. This

can be used directly to index numpy arrays to return only the desired points.

Examples

>>> metpy.calc.reduce_point_density(np.array([1, 2, 3]), 1.)
array([ True, False, True])
>>> metpy.calc.reduce_point_density(np.array([1, 2, 3]), 1.,
... priority=np.array([0.1, 0.9, 0.3]))
array([False, True, False])

Examples using metpy.calc.reduce_point_density¶

Mesonet Station Plot¶

Station Plot¶

        Next

         Previous

        © Copyright 2019, MetPy Developers. Development supported by National Science Foundation grants AGS-1344155, OAC-1740315, and AGS-1901712..
      Last updated on Oct 18, 2019 at 17:16:45.

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

Do you enjoy using MetPy?
  Say Thanks!


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="chronometer1" type="id" />
</resources>


text:
package cn.libery.knots.api.websource;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.IOException;

import cn.libery.knots.model.User;

/**
 * 获取Profile Starred amount
 * Created by Libery on 2016/7/20.
 * Email:libery.szq@qq.com
 */
public class WebApiProvider {
    private String host;
    private String userAgent;

    public WebApiProvider(String host, String userAgent) {
        this.host = host;
        this.userAgent = userAgent;
    }

    public User getUser(String username) throws IOException {
        return fetch(host, username, userAgent);
    }

    private static User fetch(String host, String user, String userAgent) throws IOException {
        User userWebInfo = new User();
        Document doc = Jsoup.connect(host + user).userAgent(userAgent).get();
        Elements navigatorElements = doc.select(".counter");
        String starred = navigatorElements.get(1).text();
        userWebInfo.setStarred(Integer.valueOf(starred));
        return userWebInfo;
    }
}


text:
package com.runetooncraft.warpigeon.engine.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;

import com.esotericsoftware.yamlbeans.YamlException;
import com.esotericsoftware.yamlbeans.YamlReader;
import com.esotericsoftware.yamlbeans.YamlWriter;

@SuppressWarnings("rawtypes")
public class YamlConfig {
	public File file = null;
	public Map config = null;
	public YamlConfig(File file) {
		this.file = file;
		load();
	}

	private void load() {
		try {
			YamlReader reader = new YamlReader(new FileReader(file));
			Object configobj = reader.read();
			config = (Map) configobj;
		} catch (YamlException | FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	public void save() {
		try {
			YamlWriter writer = new YamlWriter(new FileWriter(file));
			writer.write(config);
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public File getFile() {
		return file;
	}

	public Map getMap() {
		return config;
	}

	public void setMap(Map config) {
		this.config = config;
	}

}


text:
<html>
<head>
<script>

</script>
<script src="../js/lib/jquery.js"></script>
<script src="../js/cdc_height_tables.js"></script>
<script src="../js/nih_bp_tables.js"></script>
<script src="derive_height_times.js"></script>

</head>
<body>
  <textarea id='results' style="width: 100%; height: 100%;"></textarea>
<script>
</script>
<script>
var r = compute_times();
r = JSON.stringify(r);
r = r.replace(/},/g, "},\n");
$("#results").val("var HEIGHT_STALENESS_DATA = "+r);
</script>
</body>
</html>


text:
var g = newGlobal('new-compartment');
var dbg = Debugger(g);
var log = '';
dbg.onDebuggerStatement = function (frame) {
    log += frame.environment.getVariable("x") + frame.environment.getVariable("y");
};
g.eval("Object.getPrototypeOf(this).x = 'a';\n" +
       "Object.prototype.y = 'b';\n" +
       "debugger;\n");
assertEq(log, 'ab');


text:
Longest Palindrome

Find the length of the longest substring in the given string s that is the same in reverse.

As an example, if the input was "I like racecars that go fast", the substring (racecar) length would be 7.

If the length of the input string is 0, return value must be 0.

Example:

    "a" -> 1
    "aab" -> 2
    "abcde" -> 1
    "zzbaabcd" -> 4
    "" -> 0
```py
def longest_palindrome (s):

    longest = 0
    length = len(s)

    for outer in range(length+1):
        for inner in range(outer, length+1):
            check = s[outer:inner]
            if check == check[::-1] and len(check) > longest:
                longest = len(check)
    return longest
```


text:
    Base = function() {};
    Base.prototype = {
      super: $super,
      emit: function(inMsg) {
        document.body.appendChild(document.createTextNode(inMsg));
      },
      soundOff: function() {
        this.emit('[Base]');
      }
    };
    //
    Sub = function() {};
    Sub.prototype = extend(Base.prototype, {
      soundOff: function() {
        this.emit('[Sub]');
        this.super();
      }
    });
    //
    SubSub = function() {};
    SubSub.prototype = extend(Sub.prototype, {
      soundOff: function() {
        this.emit('[SubSub]');
        this.super();
      }
    });
    //
    subsub = new SubSub();
    subsub.soundOff();


text:
import * as actionTypes from './qualityCenterActionTypes';
import objectAssign from 'object-assign';
import normalize from 'json-api-normalizer';

const INIT_STATE = {
  //A list of quality center queries visible to the user
  queries: {},
  queryComponents: {},
  isLoaded: false
};

export default function (state = INIT_STATE, action) {
  switch (action.type) {
    case actionTypes.LOAD_QC_QUERIES_REQUEST:
      //TODO: show loading screen?
      return state;

    case actionTypes.LOAD_QC_QUERIES_COMPLETE:
      console.log('qualityCenterReducer LOAD_QC_QUERIES_COMPLETE: payload - ');
      console.log(action.payload);
      console.log('normalized payload: ');
      let normalized = normalize(action.payload);
      console.log(normalized);
      return objectAssign({}, state,
        {
          queries: normalized.qualityCenterQuery,
          queryComponents: normalized.qualityCenterQueryComponent,
          isLoaded: true
        });

    default:
      return state;
  }
}


text:
// 04.Implement previous by using native SQL query and executing it through the DbContext.

namespace _04.PreviousWithSqlQuery
{
    using System;
    using System.Collections.Generic;

    using EntityFramework.Data;

    class PreviousWithSqlQuery
    {
        static void Main(string[] args)
        {
            using (var db = new NorthwindEntities())
            {
                string sqlQuery = "SELECT DISTINCT c.ContactName " +
                                  "FROM Orders o " +
                                  "JOIN Customers c " +
                                  "ON o.CustomerID = c.CustomerID " +
                                  "WHERE (1997 = (DATEPART(yyyy, o.OrderDate))) AND (o.ShipCountry = 'Canada')";

                var orders =  db.Database.SqlQuery<string>(sqlQuery);

                foreach (var order in orders)
                {
                    Console.WriteLine(order);
                }
            }
        }
    }
}


text:
package de.larmic.restvsservlet.rest;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;

@Path("/simpleRestEndpoint")
public class SimpleRestEndpoint {

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String get() {
        System.out.println("simple REST endpoint GET called");
        return "simple REST endpoint GET called";
    }

    @PUT
    @Consumes(MediaType.TEXT_PLAIN)
    @Produces(MediaType.TEXT_PLAIN)
    public String put() {
        System.out.println("simple REST endpoint PUT called");
        return "simple REST endpoint PUT called";
    }
}


text:
/**
 * \file
 *         A very simple Contiki application showing how to use the temperature
 *			sensor.
 * \author
 *         Salvatore Pitrulli <salvopitru@users.sourceforge.net>
 *
 */

#include "contiki.h"

#include "dev/temperature-sensor.h"
#include "board.h"

#include <stdio.h> /* For printf() */
/*---------------------------------------------------------------------------*/
PROCESS(temp_process, "Temperature process");
AUTOSTART_PROCESSES(&temp_process);
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(temp_process, ev, data)
{
  static struct etimer etimer;

  PROCESS_BEGIN();

  boardPrintStringDescription();
  printf("Starting measuring temperature\r\n");

  while(1) {
    etimer_set(&etimer, CLOCK_SECOND);

    PROCESS_WAIT_UNTIL(etimer_expired(&etimer));

    unsigned int temp = temperature_sensor.value(0);
    printf("Temp: %d.%d °C  \r",temp/10,temp-(temp/10)*10);
  }

  PROCESS_END();
}
/*---------------------------------------------------------------------------*/