text:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
using Moq;
using Xunit;
using Microsoft.VisualStudio.ComponentModelHost;

namespace Merq
{
	public class CommandBusComponentSpec
	{
		[Fact]
		public void when_instantiating_with_service_provider_then_uses_component_model_service()
		{
			new CommandBusComponent(Mock.Of<IServiceProvider>(x =>
				x.GetService(typeof(SComponentModel)) == Mock.Of<IComponentModel>()));
		}

		[Fact]
		public void when_executing_command_without_handler_then_throws ()
		{
			var bus = new CommandBusComponent(Mock.Of<IComponentModel>());

			Assert.Throws<NotSupportedException> (() => bus.Execute (new Command ()));
		}

		[Fact]
		public void when_executing_command_with_result_without_handler_then_throws ()
		{
			var bus = new CommandBusComponent(Mock.Of<IComponentModel>());

			Assert.Throws<NotSupportedException> (() => bus.Execute<Result> (new CommandWithResult ()));
		}

		[Fact]
		public async void when_executing_async_command_without_handler_then_throws ()
		{
			var bus = new CommandBusComponent(Mock.Of<IComponentModel>());

			await Assert.ThrowsAsync<NotSupportedException> (() => bus.ExecuteAsync (new AsyncCommand (), CancellationToken.None));
		}

		[Fact]
		public async void when_executing_async_command_with_result_without_handler_then_throws ()
		{
			var bus = new CommandBusComponent(Mock.Of<IComponentModel>());

			await Assert.ThrowsAsync<NotSupportedException> (() => bus.ExecuteAsync<Result> (new AsyncCommandWithResult (), CancellationToken.None));
		}

		[Fact]
		public void when_can_handle_requested_for_non_registered_handler_then_returns_false ()
		{
			var bus = new CommandBusComponent(Mock.Of<IComponentModel>());

			Assert.False (bus.CanHandle<Command> ());
		}

		[Fact]
		public void when_can_handle_requested_for_registered_handler_type_then_returns_true ()
		{
			var bus = new CommandBusComponent(Mock.Of<IComponentModel>(x =>
				x.GetExtensions<ICanExecute<Command>>() == new[] { Mock.Of<ICanExecute<Command>>() }));

			Assert.True (bus.CanHandle<Command> ());
		}

		[Fact]
		public void when_can_handle_requested_for_registered_handler_instance_then_returns_true ()
		{
			var bus = new CommandBusComponent(Mock.Of<IComponentModel>(x =>
				x.GetExtensions<ICanExecute<Command>>() == new[] { Mock.Of<ICanExecute<Command>>() } ));

			Assert.True (bus.CanHandle (new Command ()));
		}

		[Fact]
		public void when_can_handle_requested_for_null_command_then_throws ()
		{
			var bus = new CommandBusComponent(Mock.Of<IComponentModel>());

			Assert.Throws<ArgumentNullException> (() => bus.CanHandle ((Command)null));
		}

		[Fact]
		public void when_can_execute_requested_and_no_handler_registered_then_returns_false ()
		{
			var bus = new CommandBusComponent(Mock.Of<IComponentModel>());

			Assert.False (bus.CanExecute (new Command ()));
		}

		[Fact]
		public void when_can_execute_requested_then_invokes_sync_handler ()
		{
			var command = new Command();
			var bus = new CommandBusComponent(Mock.Of<IComponentModel>(x =>
				x.GetExtensions<ICanExecute<Command>>() == new[] { Mock.Of<ICanExecute<Command>>(c => c.CanExecute(command) == true) }));

			Assert.True (bus.CanExecute (command));
		}

		[Fact]
		public void when_can_execute_requested_then_invokes_async_handler ()
		{
			var command = new AsyncCommand();
			var bus = new CommandBusComponent(Mock.Of<IComponentModel>(x =>
				x.GetExtensions<ICanExecute<AsyncCommand>>() == new[] { Mock.Of<ICanExecute<AsyncCommand>>(c => c.CanExecute(command) == true) }));

			Assert.True (bus.CanExecute (command));
		}

		[Fact]
		public void when_executing_sync_command_then_invokes_sync_handler ()
		{
			var handler = new Mock<ICommandHandler<Command>>();
			var command = new Command();

			var bus = new CommandBusComponent(Mock.Of<IComponentModel>(x =>
				x.GetExtensions<ICommandHandler<Command>>() == new[] { handler.Object }));

			bus.Execute (command);

			handler.Verify (x => x.Execute (command));
		}

		[Fact]
		public void when_executing_sync_command_then_invokes_sync_handler_with_result ()
		{
			var handler = new Mock<ICommandHandler<CommandWithResult, Result>>();
			var command = new CommandWithResult();
			var bus = new CommandBusComponent(Mock.Of<IComponentModel>(x =>
				x.GetExtensions<ICommandHandler<CommandWithResult, Result>>() == new[] { handler.Object }));

			bus.Execute (command);

			handler.Verify (x => x.Execute (command));
		}

		[Fact]
		public void when_executing_sync_command_with_result_then_invokes_sync_handler_with_result ()
		{
			var handler = new Mock<ICommandHandler<CommandWithResult, Result>>();
			var command = new CommandWithResult();
			var expected = new Result();

			handler.Setup (x => x.Execute (command)).Returns (expected);
			var bus = new CommandBusComponent(Mock.Of<IComponentModel>(x =>
				x.GetExtensions<ICommandHandler<CommandWithResult, Result>>() == new[] { handler.Object }));

			var result = bus.Execute (command);

			Assert.Same (expected, result);
		}

		[Fact]
		public async void when_executing_async_command_then_invokes_async_handler ()
		{
			var handler = new Mock<IAsyncCommandHandler<AsyncCommand>>();
			var command = new AsyncCommand();

			handler.Setup (x => x.ExecuteAsync (command, CancellationToken.None)).Returns (Task.FromResult (true));
			var bus = new CommandBusComponent(Mock.Of<IComponentModel>(x =>
				x.GetExtensions<IAsyncCommandHandler<AsyncCommand>>() == new[] { handler.Object }));

			await bus.ExecuteAsync (command, CancellationToken.None);

			handler.Verify (x => x.ExecuteAsync (command, CancellationToken.None));
		}

		[Fact]
		public async void when_executing_async_command_then_invokes_async_handler_with_result ()
		{
			var handler = new Mock<IAsyncCommandHandler<AsyncCommandWithResult, Result>>();
			var command = new AsyncCommandWithResult();
			var result = new Result();

			handler.Setup (x => x.ExecuteAsync (command, CancellationToken.None)).Returns (Task.FromResult (result));
			var bus = new CommandBusComponent(Mock.Of<IComponentModel>(x =>
				x.GetExtensions<IAsyncCommandHandler<AsyncCommandWithResult, Result>>() == new[] { handler.Object }));

			await bus.ExecuteAsync (command, CancellationToken.None);

			handler.Verify (x => x.ExecuteAsync (command, CancellationToken.None));
		}

		[Fact]
		public void when_can_handle_with_null_command_then_throws ()
		{
			Assert.Throws<ArgumentNullException> (() => new CommandBusComponent(Mock.Of<IComponentModel>()).CanHandle (null));
		}

		[Fact]
		public void when_can_execute_with_null_command_then_throws ()
		{
			Assert.Throws<ArgumentNullException> (() => new CommandBusComponent(Mock.Of<IComponentModel>()).CanExecute<Command> (null));
		}

		[Fact]
		public void when_execute_with_null_command_then_throws ()
		{
			Assert.Throws<ArgumentNullException> (() => new CommandBusComponent(Mock.Of<IComponentModel>()).Execute (default (Command)));
		}

		[Fact]
		public void when_execute_result_with_null_command_then_throws ()
		{
			Assert.Throws<ArgumentNullException> (() => new CommandBusComponent(Mock.Of<IComponentModel>()).Execute (default (CommandWithResult)));
		}

		[Fact]
		public async Task when_executeasync_with_null_command_then_throws ()
		{
			await Assert.ThrowsAsync<ArgumentNullException> (() => new CommandBusComponent(Mock.Of<IComponentModel>()).ExecuteAsync (default (AsyncCommand), CancellationToken.None));
		}

		[Fact]
		public async Task when_executeasync_result_with_null_command_then_throws ()
		{
			await Assert.ThrowsAsync<ArgumentNullException> (() => new CommandBusComponent(Mock.Of<IComponentModel>()).ExecuteAsync (default (AsyncCommandWithResult), CancellationToken.None));
		}

		[Fact]
		public void when_executing_non_public_command_handler_then_invokes_handler_with_result ()
		{
			var handler = new NonPublicCommandHandlerWithResults (new Result());
			var bus = new CommandBusComponent(Mock.Of<IComponentModel>(x =>
				x.GetExtensions<ICommandHandler<CommandWithResults, IEnumerable<Result>>>() == new[] { handler }));

			var results = bus.Execute (new CommandWithResults());

			Assert.Equal (1, results.Count ());
		}

		[Fact]
		public void when_executing_command_as_explicit_ICommand_then_invokes_handler ()
		{
			var handler = new Mock<ICommandHandler<Command>>();
			var command = new Command();
			var bus = new CommandBusComponent(Mock.Of<IComponentModel>(x =>
				x.GetExtensions<ICommandHandler<Command>>() == new[] { handler.Object }));

			bus.Execute ((ICommand)command);

			handler.Verify (x => x.Execute (command));
		}

		[Fact]
		public void when_execute_command_throws_then_rethrows_original_exception()
		{
			var command = new Command();
			var bus = new CommandBusComponent(Mock.Of<IComponentModel>(x =>
				x.GetExtensions<ICommandHandler<Command>>() == new[] { new ThrowingCommandHandler() }));

			var ex = Assert.Throws<InvalidOperationException>(() => bus.Execute((ICommand)command));

			Assert.Equal("Invalid", ex.Message);
		}

		public class ThrowingCommandHandler : ICommandHandler<Command>
		{
			public bool CanExecute(Command command) => true;

			public void Execute(Command command)
			{
				throw new InvalidOperationException("Invalid");
			}
		}

		public class AsyncCommand : IAsyncCommand { }

		public class AsyncCommandWithResult : IAsyncCommand<Result> { }

		public class Command : ICommand { }

		public class CommandWithResult : ICommand<Result> { }

		public class CommandWithResults : ICommand<IEnumerable<Result>> { }

		public class Result { }

		class NonPublicCommandHandlerWithResults : ICommandHandler<CommandWithResults, IEnumerable<Result>>
		{
			Result result;

			public NonPublicCommandHandlerWithResults (Result result)
			{
				this.result = result;
			}

			bool ICanExecute<CommandWithResults>.CanExecute (CommandWithResults command)
			{
				return true;
			}

			IEnumerable<Result> ICommandHandler<CommandWithResults, IEnumerable<Result>>.Execute (CommandWithResults command)
			{
				yield return result;
			}
		}
	}
}


text:
import type { IHttpInterceptor, IHttpProvider, IRequestConfig } from 'angular';
import { module } from 'angular';
import { $location, $log } from 'ngimport';

import { JsonUtils } from '../utils';

export class DebugInterceptor implements IHttpInterceptor {
  public request = (config: IRequestConfig): IRequestConfig => {
    try {
      // This is a great opportunity to break Deck, so be careful.
      this.logMutatingRequest(config);
    } catch (e) {
      $log.warn('Debug interceptor bug: ', e.message);
    }
    return config;
  };

  private logMutatingRequest(config: IRequestConfig): void {
    if (
      $location.url() &&
      $location.url().includes('debug=true') &&
      ['POST', 'PUT', 'DELETE'].includes(config.method)
    ) {
      $log.log(`${config.method}: ${config.url} \n`, JsonUtils.makeSortedStringFromObject(config.data));
    }
  }
}

export const DEBUG_INTERCEPTOR = 'spinnaker.core.debug.interceptor';
module(DEBUG_INTERCEPTOR, [])
  .service('debugInterceptor', DebugInterceptor)
  .config(['$httpProvider', ($httpProvider: IHttpProvider) => $httpProvider.interceptors.push('debugInterceptor')]);

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * CLI Config file for the Doctrine2 CLI.
 */

use Doctrine\ORM\Tools\Console\ConsoleRunner;

//Do the bootstrap manually
define('APPPATH', dirname(__FILE__) . '/application/');
define('BASEPATH', APPPATH . '/../system/');
define('ENVIRONMENT', 'development');

chdir(APPPATH);
require APPPATH . '/libraries/Doctrine.php';

// replace with mechanism to retrieve EntityManager in your app
$doctrine = new Doctrine();
$entityManager = $doctrine->em;

return ConsoleRunner::createHelperSet($entityManager);
?>


text:
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.Editor.Shared.Tagging;
using Microsoft.CodeAnalysis.Editor.Shared.Threading;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Tagging;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.Editor.Tagging
{
    internal partial class AbstractAsynchronousTaggerProvider<TTag>
    {
        private sealed partial class TagSource : ForegroundThreadAffinitizedObject
        {
            #region Fields that can be accessed from either thread

            /// <summary>
            /// The async worker we defer to handle foreground/background thread management for this
            /// tagger. Note: some operations we perform on this must be uncancellable.  Specifically,
            /// once we've updated our internal state we need to *ensure* that the UI eventually gets in
            /// sync with it. As such, we allow cancellation of our tasks *until* we update our state.
            /// From that point on, we must proceed and execute the tasks.
            /// </summary>
            private readonly AsynchronousSerialWorkQueue _workQueue;

            private readonly AbstractAsynchronousTaggerProvider<TTag> _dataSource;

            private IEqualityComparer<ITagSpan<TTag>> _tagSpanComparer;

            /// <summary>
            /// async operation notifier
            /// </summary>
            private readonly IAsynchronousOperationListener _asyncListener;

            /// <summary>
            /// foreground notification service
            /// </summary>
            private readonly IForegroundNotificationService _notificationService;

            #endregion

            #region Fields that can only be accessed from the foreground thread

            private readonly ITextView _textViewOpt;
            private readonly ITextBuffer _subjectBuffer;

            /// <summary>
            /// Our tagger event source that lets us know when we should call into the tag producer for
            /// new tags.
            /// </summary>
            private readonly ITaggerEventSource _eventSource;

            /// <summary>
            /// During the time that we are paused from updating the UI, we will use these tags instead.
            /// </summary>
            private ImmutableDictionary<ITextBuffer, TagSpanIntervalTree<TTag>> _previousCachedTagTrees;

            /// <summary>
            /// accumulated text changes since last tag calculation
            /// </summary>
            private TextChangeRange? _accumulatedTextChanges_doNotAccessDirectly;
            private ImmutableDictionary<ITextBuffer, TagSpanIntervalTree<TTag>> _cachedTagTrees_doNotAccessDirectly;
            private object _state_doNotAccessDirecty;
            private bool _upToDate_doNotAccessDirectly = false;

            #endregion

            public event Action<ICollection<KeyValuePair<ITextBuffer, NormalizedSnapshotSpanCollection>>> TagsChangedForBuffer;

            public event EventHandler Paused;
            public event EventHandler Resumed;

            public TagSource(
                ITextView textViewOpt,
                ITextBuffer subjectBuffer,
                AbstractAsynchronousTaggerProvider<TTag> dataSource,
                IAsynchronousOperationListener asyncListener,
                IForegroundNotificationService notificationService)
            {
                if (dataSource.SpanTrackingMode == SpanTrackingMode.Custom)
                {
                    throw new ArgumentException("SpanTrackingMode.Custom not allowed.", "spanTrackingMode");
                }

                _subjectBuffer = subjectBuffer;
                _textViewOpt = textViewOpt;
                _dataSource = dataSource;
                _asyncListener = asyncListener;
                _notificationService = notificationService;
                _tagSpanComparer = new TagSpanComparer(_dataSource.TagComparer);

                DebugRecordInitialStackTrace();

                this._workQueue = new AsynchronousSerialWorkQueue(asyncListener);
                this.CachedTagTrees = ImmutableDictionary.Create<ITextBuffer, TagSpanIntervalTree<TTag>>();

                _eventSource = CreateEventSource();

                Connect();

                // Kick off a task to compute the initial set of tags.
                RecalculateTagsOnChanged(new TaggerEventArgs(TaggerDelay.Short));
            }

            private ITaggerEventSource CreateEventSource()
            {
                var eventSource = _dataSource.CreateEventSource(_textViewOpt, _subjectBuffer);

                // If there are any options specified for this tagger, then also hook up event
                // notifications for when those options change.
                var optionChangedEventSources =
                    _dataSource.Options.Concat<IOption>(_dataSource.PerLanguageOptions)
                        .Select(o => TaggerEventSources.OnOptionChanged(_subjectBuffer, o, TaggerDelay.NearImmediate)).ToList();

                if (optionChangedEventSources.Count == 0)
                {
                    // No options specified for this tagger.  So just keep the event source as is.
                    return eventSource;
                }

                optionChangedEventSources.Add(eventSource);
                return TaggerEventSources.Compose(optionChangedEventSources);
            }

            private TextChangeRange? AccumulatedTextChanges
            {
                get
                {
                    this._workQueue.AssertIsForeground();
                    return _accumulatedTextChanges_doNotAccessDirectly;
                }

                set
                {
                    this._workQueue.AssertIsForeground();
                    _accumulatedTextChanges_doNotAccessDirectly = value;
                }
            }

            private ImmutableDictionary<ITextBuffer, TagSpanIntervalTree<TTag>> CachedTagTrees
            {
                get
                {
                    this._workQueue.AssertIsForeground();
                    return _cachedTagTrees_doNotAccessDirectly;
                }

                set
                {
                    this._workQueue.AssertIsForeground();
                    _cachedTagTrees_doNotAccessDirectly = value;
                }
            }

            private object State
            {
                get
                {
                    this._workQueue.AssertIsForeground();
                    return _state_doNotAccessDirecty;
                }

                set
                {
                    this._workQueue.AssertIsForeground();
                    _state_doNotAccessDirecty = value;
                }
            }

            private bool UpToDate
            {
                get
                {
                    this._workQueue.AssertIsForeground();
                    return _upToDate_doNotAccessDirectly;
                }

                set
                {
                    this._workQueue.AssertIsForeground();
                    _upToDate_doNotAccessDirectly = value;
                }
            }

            public void RegisterNotification(Action action, int delay, CancellationToken cancellationToken)
            {
                _notificationService.RegisterNotification(action, delay, this._asyncListener.BeginAsyncOperation("TagSource"), cancellationToken);
            }

            /// <summary>
            /// Called by derived types to enqueue tags re-calculation request
            /// </summary>
            private void RecalculateTagsOnChanged(TaggerEventArgs e)
            {
                // First, cancel any previous requests (either still queued, or started).  We no longer
                // want to continue it if new changes have come in.
                this._workQueue.CancelCurrentWork();

                RegisterNotification(RecomputeTagsForeground, (int)e.Delay.ComputeTimeDelay(this._subjectBuffer).TotalMilliseconds, this._workQueue.CancellationToken);
            }

            private void Connect()
            {
                this._workQueue.AssertIsForeground();

                _eventSource.Changed += OnChanged;
                _eventSource.UIUpdatesResumed += OnUIUpdatesResumed;
                _eventSource.UIUpdatesPaused += OnUIUpdatesPaused;

                if (_dataSource.TextChangeBehavior.HasFlag(TaggerTextChangeBehavior.TrackTextChanges))
                {
                    this._subjectBuffer.Changed += OnSubjectBufferChanged;
                }

                if (_dataSource.CaretChangeBehavior.HasFlag(TaggerCaretChangeBehavior.RemoveAllTagsOnCaretMoveOutsideOfTag))
                {
                    if (_textViewOpt == null)
                    {
                        throw new ArgumentException(
                            nameof(_dataSource.CaretChangeBehavior) + " can only be specified for an " + nameof(IViewTaggerProvider));
                    }

                    _textViewOpt.Caret.PositionChanged += OnCaretPositionChanged;
                }

                // Tell the interaction object to start issuing events.
                _eventSource.Connect();
            }

            public void Disconnect()
            {
                this._workQueue.AssertIsForeground();
                this._workQueue.CancelCurrentWork();

                // Tell the interaction object to stop issuing events.
                _eventSource.Disconnect();

                if (_dataSource.CaretChangeBehavior.HasFlag(TaggerCaretChangeBehavior.RemoveAllTagsOnCaretMoveOutsideOfTag))
                {
                    this._textViewOpt.Caret.PositionChanged -= OnCaretPositionChanged;
                }

                if (_dataSource.TextChangeBehavior.HasFlag(TaggerTextChangeBehavior.TrackTextChanges))
                {
                    this._subjectBuffer.Changed -= OnSubjectBufferChanged;
                }

                _eventSource.UIUpdatesPaused -= OnUIUpdatesPaused;
                _eventSource.UIUpdatesResumed -= OnUIUpdatesResumed;
                _eventSource.Changed -= OnChanged;
            }

            private void RaiseTagsChanged(ITextBuffer buffer, NormalizedSnapshotSpanCollection difference)
            {
                this.AssertIsForeground();
                if (difference.Count == 0)
                {
                    // nothing changed.
                    return;
                }

                RaiseTagsChanged(SpecializedCollections.SingletonCollection(
                    new KeyValuePair<ITextBuffer, NormalizedSnapshotSpanCollection>(buffer, difference)));
            }

            private void RaiseTagsChanged(ICollection<KeyValuePair<ITextBuffer, NormalizedSnapshotSpanCollection>> collection)
            {
                var tagsChangedForBuffer = TagsChangedForBuffer;
                if (tagsChangedForBuffer != null)
                {
                    tagsChangedForBuffer(collection);
                }
            }

            private void RaisePaused()
            {
                var paused = this.Paused;
                if (paused != null)
                {
                    paused(this, EventArgs.Empty);
                }
            }

            private void RaiseResumed()
            {
                var resumed = this.Resumed;
                if (resumed != null)
                {
                    resumed(this, EventArgs.Empty);
                }
            }

            private static T NextOrDefault<T>(IEnumerator<T> enumerator)
            {
                return enumerator.MoveNext() ? enumerator.Current : default(T);
            }

            /// <summary>
            /// Return all the spans that appear in only one of "latestSpans" or "previousSpans".
            /// </summary>
            private static IEnumerable<SnapshotSpan> Difference<T>(IEnumerable<ITagSpan<T>> latestSpans, IEnumerable<ITagSpan<T>> previousSpans, IEqualityComparer<T> comparer)
                where T : ITag
            {
                var latestEnumerator = latestSpans.GetEnumerator();
                var previousEnumerator = previousSpans.GetEnumerator();
                try
                {
                    var latest = NextOrDefault(latestEnumerator);
                    var previous = NextOrDefault(previousEnumerator);

                    while (latest != null && previous != null)
                    {
                        var latestSpan = latest.Span;
                        var previousSpan = previous.Span;

                        if (latestSpan.Start < previousSpan.Start)
                        {
                            yield return latestSpan;
                            latest = NextOrDefault(latestEnumerator);
                        }
                        else if (previousSpan.Start < latestSpan.Start)
                        {
                            yield return previousSpan;
                            previous = NextOrDefault(previousEnumerator);
                        }
                        else
                        {
                            // If the starts are the same, but the ends are different, report the larger
                            // region to be conservative.
                            if (previousSpan.End > latestSpan.End)
                            {
                                yield return previousSpan;
                                latest = NextOrDefault(latestEnumerator);
                            }
                            else if (latestSpan.End > previousSpan.End)
                            {
                                yield return latestSpan;
                                previous = NextOrDefault(previousEnumerator);
                            }
                            else
                            {
                                if (!comparer.Equals(latest.Tag, previous.Tag))
                                {
                                    yield return latestSpan;
                                }

                                latest = NextOrDefault(latestEnumerator);
                                previous = NextOrDefault(previousEnumerator);
                            }
                        }
                    }

                    while (latest != null)
                    {
                        yield return latest.Span;
                        latest = NextOrDefault(latestEnumerator);
                    }

                    while (previous != null)
                    {
                        yield return previous.Span;
                        previous = NextOrDefault(previousEnumerator);
                    }
                }
                finally
                {
                    latestEnumerator.Dispose();
                    previousEnumerator.Dispose();
                }
            }
        }
    }
}


text:
package net.sourceforge.pmd.perl.tokens;

import net.sourceforge.pmd.perl.Token;
import net.sourceforge.pmd.perl.PerlParserConstants;

public class Semicolon extends Token {

    public Semicolon (Token t) {
        super(";", t);
        kind = PerlParserConstants.SEMICOLON;
    }

}


text:
namespace chromeos {

MockUserManager::MockUserManager() : user_(NULL),
                                     user_flow_(new DefaultUserFlow()) {}

MockUserManager::~MockUserManager() {
  delete user_;
}

const User* MockUserManager::GetLoggedInUser() const {
  return user_;
}

User* MockUserManager::GetLoggedInUser() {
  return user_;
}

const User* MockUserManager::GetActiveUser() const {
  return user_;
}

User* MockUserManager::GetActiveUser() {
  return user_;
}

UserImageManager* MockUserManager::GetUserImageManager() {
  return user_image_manager_.get();
}

// Creates a new User instance.
void MockUserManager::SetActiveUser(const std::string& email) {
  delete user_;
  user_ = User::CreateRegularUser(email);
}

UserFlow* MockUserManager::GetCurrentUserFlow() const {
  return user_flow_.get();
}

UserFlow* MockUserManager::GetUserFlow(const std::string&) const {
  return user_flow_.get();
}

User* MockUserManager::CreatePublicAccountUser(const std::string& email) {
  delete user_;
  user_ = User::CreatePublicAccountUser(email);
  return user_;
}

}  // namespace chromeos


text:
package io.dummymaker.export;

import io.dummymaker.export.impl.CsvExporter;
import io.dummymaker.export.impl.JsonExporter;
import io.dummymaker.export.impl.SqlExporter;
import io.dummymaker.export.impl.XmlExporter;
import io.dummymaker.export.validators.*;
import io.dummymaker.factory.impl.GenFactory;
import io.dummymaker.model.DummyTime;
import io.dummymaker.model.DummyTimeFormatter;
import io.dummymaker.model.DummyUnixTime;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

/**
 * "default comment"
 *
 * @author GoodforGod
 * @since 28.04.2018
 */
@RunWith(Parameterized.class)
public class ValidatorExporterTest extends Assert {

    private final GenFactory factory = new GenFactory();

    private IExporter exporter;
    private IValidator validator;

    public ValidatorExporterTest(IExporter exporter, IValidator validator) {
        this.exporter = exporter;
        this.validator = validator;
    }

    @Parameters(name = "{index}: Exporter - ({0})")
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][] {
                { new CsvExporter(), new CsvValidator() },
                { new JsonExporter(), new JsonValidator() },
                { new XmlExporter(), new XmlValidator() },
                { new SqlExporter(), new SqlValidator() }
        });
    }

    @Test
    public void datesPatternMatchWhenExported() {
        final DummyTime dummy = factory.build(DummyTime.class);
        assertNotNull(dummy);

        final String exported = exporter.convert(dummy);

        final String splitter = (exporter instanceof CsvExporter)
                ? ","
                : "\n";
        final String[] split = exported.split(splitter);
        assertNotNull(split);

        validator.isDummyTimeValid(split);
    }

    @Test
    public void datetimeUnixWhenExported() {
        final DummyUnixTime dummy = factory.build(DummyUnixTime.class);
        assertNotNull(dummy);

        final String exported = exporter.convert(dummy);

        final String splitter = (exporter instanceof CsvExporter)
                ? ","
                : "\n";
        final String[] split = exported.split(splitter);
        assertNotNull(split);

        validator.isDummyUnixTimeValid(split);
    }

    @Test
    public void datetimeFormatterWhenExported() {
        final DummyTimeFormatter dummy = factory.build(DummyTimeFormatter.class);
        assertNotNull(dummy);

        final String exported = exporter.convert(dummy);

        final String splitter = (exporter instanceof CsvExporter)
                ? ","
                : "\n";
        final String[] split = exported.split(splitter);
        assertNotNull(split);

        validator.isDummyTimeFormatterValid(split);
    }
}


text:
//
//  TMainBottomTabBarButton.m
//  Tikeyc
//
//  Created by ways on 2016/11/14.
//  Copyright © 2016年 tikeyc. All rights reserved.
//

#import "TMainBottomTabBarButton.h"

@interface TMainBottomTabBarButton ()

@end

@implementation TMainBottomTabBarButton

- (id)initWithFrame:(CGRect)rect withNormalImageName:(NSString *)normalImageName withHighlightedImageName:(NSString *)highlightedImageName withLabelTitle:(NSString *)title{
    self = [super initWithFrame:rect];
    if (self) {
        self.normalImage = [UIImage imageNamed:normalImageName];
        self.highlightedImage = [UIImage imageNamed:highlightedImageName];
        self.title = title;
        self.backgroundColor = TColor_RGB(91, 91, 91);
        [self initSubViews];
    }
    return self;
}

- (void)initSubViews{
    //
    _iconImage = [[UIImageView alloc] init];
    _iconImage.backgroundColor = [UIColor clearColor];
    _iconImage.frame = CGRectMake((self.width - _normalImage.size.width/*25*/)/2, 4, _normalImage.size.width/*25*/, _normalImage.size.height/*23*/);
    _iconImage.image = _normalImage;
    [self addSubview:_iconImage];
    //
    _label = [[UILabel alloc] initWithFrame:CGRectMake(0, _iconImage.bottom + 3, self.width, 15)];
    _label.backgroundColor = [UIColor clearColor];
    _label.font = [UIFont systemFontOfSize:12.0f];
    _label.textColor = TColor_RGB(255, 255, 255);
    _label.textAlignment = NSTextAlignmentCenter;
    _label.text = self.title;
    [self addSubview:_label];
}

- (void)setSelected:(BOOL)selected{
    [super setSelected:selected];

    _iconImage.image = selected ? _highlightedImage : _normalImage;
}

- (void)setTitle:(NSString *)title{
    if (_title != title) {
        _title = nil;
        _title = title;
    }
    _label.text = _title;
}

@end


text:
package io.cattle.iaas.lb.api.action;

import io.cattle.iaas.lb.api.service.LoadBalancerApiService;
import io.cattle.platform.api.action.ActionHandler;
import io.cattle.platform.core.constants.LoadBalancerConstants;
import io.cattle.platform.core.model.LoadBalancerConfig;
import io.cattle.platform.object.ObjectManager;
import io.cattle.platform.object.util.DataAccessor;
import io.github.ibuildthecloud.gdapi.request.ApiRequest;

import javax.inject.Inject;

public class LoadBalancerConfigAddListenerActionHandler implements ActionHandler {

    @Inject
    ObjectManager objectManager;

    @Inject
    LoadBalancerApiService lbService;

    @Override
    public String getName() {
        return LoadBalancerConstants.PROCESS_LB_CONFIG_ADD_LISTENER;
    }

    @Override
    public Object perform(String name, Object obj, ApiRequest request) {
        if (!(obj instanceof LoadBalancerConfig)) {
            return null;
        }
        LoadBalancerConfig config = (LoadBalancerConfig) obj;
        long listenerId = DataAccessor.fromMap(request.getRequestObject())
                .withKey(LoadBalancerConstants.FIELD_LB_LISTENER_ID).as(Long.class);

        lbService.addListenerToConfig(config, listenerId);

        return objectManager.reload(config);
    }
}


text:
"""Metrics: Methods to store and access system state"""
from fabric.colors import green, magenta,cyan,blue
from articurate.pymotherlode import api

#Use as @metrics.inspect to print return value in terminal
def inspect(f):
	def newfn(*args, **kwargs):
		out = f(*args, **kwargs)
		#print blue("metrics.inspect:")+cyan(f.__module__+"."+f.__name__+":")+green(str(out))
		print blue("metrics.inspect:")+green(str(out))
		return out
	return newfn

#Use as @metrics.track to store return value in the motherlode, do not use any other decorators below this
def track(f):
	def newfn(*args, **kwargs):
		out = f(*args, **kwargs)
		methodName = f.__module__+"."+f.__name__
		api.storeMetric(methodName, out)
		print blue("metrics.track:")+cyan(methodName)
		return out
	return newfn

#Use as @metrics.track_by("key") to store return value of the function in motherlode, indexed by key.
#This allows one to store multiple return values of a function at once.
#Do not use any other decorators below this, just as with @metrics.track
#It is recommended not to use trailing _ in the function name which is encapsulated by this decorator.
#Will still work, but it's easier for me to debug stuff this way. And it's not likely either that
#a trailing _ will be needed.
def track_by(key):
	def track(f):
		def newfn(*args, **kwargs):
			out = f(*args, **kwargs)
			shortmethodName = f.__module__+"."+f.__name__
			methodName = f.__module__+"."+f.__name__+"_"+key
			api.storeMetric(methodName, out)
			print blue("metrics.track:")+cyan(shortmethodName)+"_"+magenta(key)
			return out
		return newfn
	return track


text:
-	[`2`, `2.6`, `2.6.0`, `latest` (*Dockerfile*)](https://github.com/docker/distribution-library-image/blob/4339e1083299550aeb5915e0d5a5238d159872da/Dockerfile)

For more information about this image and its history, please see [the relevant manifest file (`library/registry`)](https://github.com/docker-library/official-images/blob/master/library/registry). This image is updated via [pull requests to the `docker-library/official-images` GitHub repo](https://github.com/docker-library/official-images/pulls?q=label%3Alibrary%2Fregistry).

For detailed information about the virtual/transfer sizes and individual layers of each of the above supported tags, please see [the `repos/registry/tag-details.md` file](https://github.com/docker-library/repo-info/blob/master/repos/registry/tag-details.md) in [the `docker-library/repo-info` GitHub repo](https://github.com/docker-library/repo-info).

# Docker Registry

This image contains an implementation of the Docker Registry HTTP API V2 for use with Docker 1.6+. See [github.com/docker/distribution](https://github.com/docker/distribution) for more details about what it is.

## Run a local registry: Quick Version

```console
$ docker run -d -p 5000:5000 --restart always --name registry registry:2
```

Now, use it from within Docker:

```console
$ docker pull ubuntu
$ docker tag ubuntu localhost:5000/ubuntu
$ docker push localhost:5000/ubuntu
```

## Recommended Reading

The [documentation over at docs.docker.com](https://docs.docker.com/registry/) is a good place to learn more about what the registry is, how it works, and how to use it.

Specifically, [the section regarding deployment](https://docs.docker.com/registry/deploying/) has pointers for more complex use cases than simply running a registry on localhost.

# Support

If you are interested in commercial support, the [Docker Trusted Registry](https://www.docker.com/docker-trusted-registry) provides an image registry, LDAP/Active Directory integration, security certificates, and more in a solution that includes commercial support.

# Supported Docker versions

This image is officially supported on Docker version 1.13.0.

Support for older versions (down to 1.6) is provided on a best-effort basis.

Please see [the Docker installation documentation](https://docs.docker.com/installation/) for details on how to upgrade your Docker daemon.

# User Feedback

## Issues

If you have any problems with or questions about this image, please contact us through a [GitHub issue](https://github.com/docker/distribution-library-image/issues). If the issue is related to a CVE, please check for [a `cve-tracker` issue on the `official-images` repository first](https://github.com/docker-library/official-images/issues?q=label%3Acve-tracker).

You can also reach many of the official image maintainers via the `#docker-library` IRC channel on [Freenode](https://freenode.net).

## Contributing

You are invited to contribute new features, fixes, or updates, large or small; we are always thrilled to receive pull requests, and do our best to process them as fast as we can.

Before you start to code, we recommend discussing your plans through a [GitHub issue](https://github.com/docker/distribution-library-image/issues), especially for more ambitious contributions. This gives other contributors a chance to point you in the right direction, give you feedback on your design, and help you find out if someone else is working on the same thing.

## Documentation

Documentation for this image is stored in the [`registry/` directory](https://github.com/docker-library/docs/tree/master/registry) of the [`docker-library/docs` GitHub repo](https://github.com/docker-library/docs). Be sure to familiarize yourself with the [repository's `README.md` file](https://github.com/docker-library/docs/blob/master/README.md) before attempting a pull request.


text:
package com.google.android.finsky.activities;

import android.content.Context;
import android.content.res.Resources;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import com.android.volley.Response.ErrorListener;
import com.android.volley.VolleyError;
import com.google.android.finsky.FinskyApp;
import com.google.android.finsky.adapters.CardRecyclerViewAdapter;
import com.google.android.finsky.adapters.EmptyRecyclerViewAdapter;
import com.google.android.finsky.adapters.QuickLinkHelper.QuickLinkInfo;
import com.google.android.finsky.analytics.FinskyEventLog;
import com.google.android.finsky.analytics.PlayStore.PlayStoreUiElement;
import com.google.android.finsky.api.DfeApi;
import com.google.android.finsky.api.model.ContainerList;
import com.google.android.finsky.api.model.DfeToc;
import com.google.android.finsky.api.model.Document;
import com.google.android.finsky.api.model.MultiDfeList;
import com.google.android.finsky.api.model.OnDataChangedListener;
import com.google.android.finsky.config.G;
import com.google.android.finsky.experiments.FinskyExperiments;
import com.google.android.finsky.fragments.DfeRecyclerBinder;
import com.google.android.finsky.layout.LayoutSwitcher;
import com.google.android.finsky.layout.LayoutSwitcher.RetryButtonListener;
import com.google.android.finsky.layout.SpacerHeightAwareFrameLayout;
import com.google.android.finsky.layout.actionbar.ActionBarController;
import com.google.android.finsky.layout.play.PlayRecyclerView;
import com.google.android.finsky.layout.play.PlayStoreUiElementNode;
import com.google.android.finsky.layout.play.SelectableUiElementNode;
import com.google.android.finsky.navigationmanager.NavigationManager;
import com.google.android.finsky.protos.Browse.BrowseTab;
import com.google.android.finsky.protos.DocV2;
import com.google.android.finsky.utils.ClientMutationCache;
import com.google.android.finsky.utils.ErrorStrings;
import com.google.android.finsky.utils.ObjectMap;
import com.google.android.finsky.utils.UiUtils;
import com.google.android.play.image.BitmapLoader;
import com.google.android.play.utils.config.GservicesValue;

public final class ListTab
  implements Response.ErrorListener, ViewPagerTab, OnDataChangedListener, LayoutSwitcher.RetryButtonListener, PlayStoreUiElementNode
{
  protected final ActionBarController mActionBarController;
  private DfeRecyclerBinder mBinder;
  private final ClientMutationCache mClientMutationCache;
  private Document mContainerDocument;
  private final DfeApi mDfeApi;
  private boolean mIsCurrentlySelected;
  private final LayoutInflater mLayoutInflater;
  private LayoutSwitcher mLayoutSwitcher;
  private final MultiDfeList mMultiDfeList;
  protected final NavigationManager mNavigationManager;
  private SelectableUiElementNode mParentNode;
  private final boolean mPreventTabPreloading;
  private final QuickLinkHelper.QuickLinkInfo[] mQuickLinks;
  private boolean mRecyclerViewBoundAlready = false;
  private ViewGroup mRecyclerViewTabWrapper;
  private ObjectMap mRestoredInstanceState = ObjectMap.EMPTY;
  boolean mShouldDeferDataDisplay;
  private final SpacerHeightProvider mSpacerHeightProvider;
  private final TabbedAdapter.TabDataListener mTabDataListener;
  private final int mTabMode;
  private final String mTitle;
  protected final DfeToc mToc;
  private PlayStore.PlayStoreUiElement mUiElementProto = FinskyEventLog.obtainPlayStoreUiElement(408);

  public ListTab(Context paramContext, NavigationManager paramNavigationManager, BitmapLoader paramBitmapLoader, DfeApi paramDfeApi, LayoutInflater paramLayoutInflater, TabbedAdapter.TabData paramTabData, DfeToc paramDfeToc, ClientMutationCache paramClientMutationCache, boolean paramBoolean, ActionBarController paramActionBarController, int paramInt, TabbedAdapter.TabDataListener paramTabDataListener, SpacerHeightProvider paramSpacerHeightProvider)
  {
    this.mLayoutInflater = paramLayoutInflater;
    this.mMultiDfeList = paramTabData.multiDfeList;
    this.mQuickLinks = paramTabData.quickLinks;
    int i;
    String str;
    label74:
    ContainerList localContainerList;
    int k;
    label178:
    int m;
    if (paramInt == 2)
    {
      i = 1;
      if (i == 0) {
        break label308;
      }
      str = paramTabData.browseTab.title;
      this.mTitle = str;
      this.mParentNode = paramTabData.elementNode;
      localContainerList = this.mMultiDfeList.mContainerList;
      localContainerList.mWindowDistance = (paramContext.getResources().getInteger(2131623938) * UiUtils.getFeaturedGridColumnCount(paramContext.getResources(), 1.0D));
      localContainerList.addDataChangedListener(this);
      localContainerList.addErrorListener(this);
      this.mShouldDeferDataDisplay = paramBoolean;
      int j = paramNavigationManager.getCurrentPageType();
      if ((!FinskyApp.get().getExperiments().isEnabled(12605163L)) && (!((Boolean)G.preventTabPreloadingOnHomePage.get()).booleanValue())) {
        break label314;
      }
      k = 1;
      if (j != 1) {
        break label320;
      }
      m = 1;
      label187:
      if ((k == 0) || (m == 0)) {
        break label326;
      }
    }
    label308:
    label314:
    label320:
    label326:
    for (boolean bool = true;; bool = false)
    {
      this.mPreventTabPreloading = bool;
      if (!this.mPreventTabPreloading) {
        localContainerList.startLoadItems();
      }
      this.mToc = paramDfeToc;
      this.mNavigationManager = paramNavigationManager;
      this.mDfeApi = paramDfeApi;
      this.mClientMutationCache = paramClientMutationCache;
      this.mActionBarController = paramActionBarController;
      this.mTabMode = paramInt;
      this.mTabDataListener = paramTabDataListener;
      this.mSpacerHeightProvider = paramSpacerHeightProvider;
      this.mBinder = new DfeRecyclerBinder(this.mToc, this.mDfeApi, this.mClientMutationCache);
      this.mBinder.init(paramContext, this.mNavigationManager, paramBitmapLoader);
      return;
      i = 0;
      break;
      str = null;
      break label74;
      k = 0;
      break label178;
      m = 0;
      break label187;
    }
  }

  private void setChildSpacerHeightProvider(int paramInt)
  {
    ((SpacerHeightAwareFrameLayout)this.mRecyclerViewTabWrapper.findViewById(paramInt)).setSpacerHeightProvider(this.mSpacerHeightProvider);
  }

  public final void childImpression(PlayStoreUiElementNode paramPlayStoreUiElementNode)
  {
    FinskyEventLog.childImpression(this, paramPlayStoreUiElementNode);
  }

  public final PlayStoreUiElementNode getParentNode()
  {
    return this.mParentNode;
  }

  public final PlayStore.PlayStoreUiElement getPlayStoreUiElement()
  {
    return this.mUiElementProto;
  }

  public final View getView(int paramInt)
  {
    if (this.mRecyclerViewTabWrapper == null)
    {
      this.mRecyclerViewTabWrapper = ((ViewGroup)this.mLayoutInflater.inflate(2130969059, null));
      setChildSpacerHeightProvider(2131755697);
      setChildSpacerHeightProvider(2131755806);
      this.mLayoutSwitcher = new LayoutSwitcher(this.mRecyclerViewTabWrapper, 2131756027, 2131755806, 2131755697, this, 0);
      PlayRecyclerView localPlayRecyclerView = (PlayRecyclerView)this.mRecyclerViewTabWrapper.findViewById(2131755329);
      localPlayRecyclerView.getContext();
      localPlayRecyclerView.setLayoutManager(new LinearLayoutManager());
      localPlayRecyclerView.setAdapter(new EmptyRecyclerViewAdapter());
      syncViewToState();
    }
    return this.mRecyclerViewTabWrapper;
  }

  public final void onDataChanged()
  {
    syncViewToState();
  }

  public final void onDestroy()
  {
    DfeRecyclerBinder localDfeRecyclerBinder = this.mBinder;
    localDfeRecyclerBinder.detachFromData();
    if (localDfeRecyclerBinder.mAdapter != null)
    {
      localDfeRecyclerBinder.mAdapter.onDestroy();
      localDfeRecyclerBinder.mAdapter = null;
    }
    localDfeRecyclerBinder.mRecyclerView = null;
    ContainerList localContainerList = this.mMultiDfeList.mContainerList;
    localContainerList.removeDataChangedListener(this);
    localContainerList.removeErrorListener(this);
    this.mMultiDfeList.flushData();
    this.mRecyclerViewTabWrapper = null;
    this.mRecyclerViewBoundAlready = false;
  }

  public final ObjectMap onDestroyView()
  {
    if (this.mRecyclerViewTabWrapper != null)
    {
      PlayRecyclerView localPlayRecyclerView = (PlayRecyclerView)this.mRecyclerViewTabWrapper.findViewById(2131755329);
      if (localPlayRecyclerView.getVisibility() == 0)
      {
        ObjectMap localObjectMap = new ObjectMap();
        DfeRecyclerBinder localDfeRecyclerBinder = this.mBinder;
        Bundle localBundle = localObjectMap.mBundle;
        if (localDfeRecyclerBinder.mAdapter != null) {
          localDfeRecyclerBinder.mAdapter.onSaveInstanceState(localPlayRecyclerView, localBundle);
        }
        return localObjectMap;
      }
    }
    return null;
  }

  public final void onErrorResponse(VolleyError paramVolleyError)
  {
    syncViewToState();
  }

  public final void onRestoreInstanceState(ObjectMap paramObjectMap)
  {
    if (this.mRestoredInstanceState != null) {
      this.mRestoredInstanceState = paramObjectMap;
    }
  }

  public final void onRetry()
  {
    ContainerList localContainerList = this.mMultiDfeList.mContainerList;
    localContainerList.resetItems();
    localContainerList.mCurrentRequest = null;
    localContainerList.startLoadItems();
    syncViewToState();
  }

  public final void setTabSelected(boolean paramBoolean)
  {
    if (paramBoolean != this.mIsCurrentlySelected)
    {
      if (!paramBoolean) {
        break label87;
      }
      ContainerList localContainerList = this.mMultiDfeList.mContainerList;
      if ((this.mPreventTabPreloading) && (!localContainerList.isReady()) && (!localContainerList.isInTransit())) {
        localContainerList.startLoadItems();
      }
      FinskyEventLog.startNewImpression(this.mParentNode);
      this.mParentNode.setNodeSelected(true);
      if (this.mParentNode.getPlayStoreUiElement().child.length == 0) {
        FinskyEventLog.requestImpressions(this.mRecyclerViewTabWrapper);
      }
    }
    for (;;)
    {
      this.mIsCurrentlySelected = paramBoolean;
      return;
      label87:
      this.mParentNode.setNodeSelected(false);
    }
  }

  final void syncViewToState()
  {
    if (this.mRecyclerViewTabWrapper == null) {}
    do
    {
      ContainerList localContainerList;
      do
      {
        return;
        localContainerList = this.mMultiDfeList.mContainerList;
        if (!localContainerList.inErrorState()) {
          break;
        }
      } while (this.mRecyclerViewBoundAlready);
      this.mLayoutSwitcher.switchToErrorMode(ErrorStrings.get(FinskyApp.get(), localContainerList.getVolleyError()));
      return;
      if ((this.mShouldDeferDataDisplay) || (!localContainerList.isReady())) {
        break;
      }
      if (this.mContainerDocument == null) {
        this.mContainerDocument = localContainerList.mContainerDocument;
      }
      if (this.mContainerDocument != null) {
        FinskyEventLog.setServerLogCookie(this.mUiElementProto, this.mContainerDocument.mDocument.serverLogsCookie);
      }
      this.mLayoutSwitcher.switchToDataMode();
    } while (this.mRecyclerViewBoundAlready);
    int i;
    DfeRecyclerBinder localDfeRecyclerBinder;
    ViewGroup localViewGroup;
    Document localDocument;
    QuickLinkHelper.QuickLinkInfo[] arrayOfQuickLinkInfo;
    String str;
    int j;
    if (this.mRestoredInstanceState != null)
    {
      i = 1;
      this.mBinder.setData(this.mMultiDfeList);
      localDfeRecyclerBinder = this.mBinder;
      localViewGroup = this.mRecyclerViewTabWrapper;
      localDocument = this.mContainerDocument;
      arrayOfQuickLinkInfo = this.mQuickLinks;
      str = this.mTitle;
      j = this.mTabMode;
      if (i == 0) {
        break label311;
      }
    }
    label311:
    for (Bundle localBundle = this.mRestoredInstanceState.mBundle;; localBundle = null)
    {
      localDfeRecyclerBinder.bind(localViewGroup, localDocument, arrayOfQuickLinkInfo, str, j, localBundle, this.mTabDataListener, this, this.mSpacerHeightProvider);
      if ((i == 0) && (Build.VERSION.SDK_INT >= 16))
      {
        PlayRecyclerView localPlayRecyclerView = (PlayRecyclerView)this.mRecyclerViewTabWrapper.findViewById(2131755329);
        Animation localAnimation = AnimationUtils.loadAnimation(localPlayRecyclerView.getContext(), 2131034138);
        localAnimation.setInterpolator(new FastOutSlowInInterpolator());
        localAnimation.setDuration(300L);
        LayoutAnimationController localLayoutAnimationController = new LayoutAnimationController(localAnimation);
        localLayoutAnimationController.setDelay(0.1F);
        localPlayRecyclerView.setLayoutAnimation(localLayoutAnimationController);
      }
      this.mRestoredInstanceState = null;
      this.mRecyclerViewBoundAlready = true;
      return;
      i = 0;
      break;
    }
    this.mLayoutSwitcher.switchToLoadingMode();
  }
}

/* Location:           F:\apktool\apktool\Google_Play_Store6.0.5\classes-dex2jar.jar

 * Qualified Name:     com.google.android.finsky.activities.ListTab

 * JD-Core Version:    0.7.0.1

 */


text:
SDMBNConfig sdmbn_config;

SDMBNLocals *sdmbn_locals = NULL;

// Global statistics variables
SDMBNStatistics sdmbn_stats;

// Hack for benchmarking
pthread_mutex_t sdmbn_lock_get;

// Thread for sending discovery packets
static pthread_t discovery_thread;

int sdmbn_init(SDMBNLocals *locals)
{
    // Check arguments
    if (NULL == locals)
    { return -1; }

    // Initialize statistics
    bzero(&sdmbn_stats, sizeof(sdmbn_stats));

    // Parse configuration
    sdmbn_parse_config();

    // Store list of MB-specific functions
    sdmbn_locals = locals;

    // Initialize connection lock
    assert(0 == pthread_mutex_init(&sdmbn_lock_conn, NULL));

    // Initialize state
    if (state_init() < 0)
    {
        ERROR_PRINT("Failed to initialize state");
        return -1;
    }

    // Initialize events
    if (events_init() < 0)
    {
        ERROR_PRINT("Failed to initialize events");
        return -1;
    }

    // Create get lock
    assert(0 == pthread_mutex_init(&sdmbn_lock_get, NULL));
    if (sdmbn_config.release_get_pkts > 0
            || sdmbn_config.release_get_flows > 0)
    { pthread_mutex_lock(&sdmbn_lock_get); }

    // Create discovery packet sending thread
    if (sdmbn_locals->device != NULL)
    { pthread_create(&discovery_thread, NULL, discovery_send, NULL); }
    else
    { ERROR_PRINT("No device provided"); }

    INFO_PRINT("Initialized");

    return 1;
}

int sdmbn_cleanup()
{
    // Destroy get lock
    pthread_mutex_destroy(&sdmbn_lock_get);

    // Clean-up state
    if (state_cleanup() < 0)
    { ERROR_PRINT("Failed to cleanup state"); }

    // Clean-up events
    if (events_cleanup() < 0)
    { ERROR_PRINT("Failed to cleanup events"); }

    // Call local cleanup function
    if (sdmbn_locals->cleanup != NULL)
    { sdmbn_locals->cleanup(); }

    // Remove list of MB-specific functions
    sdmbn_locals = NULL;

    INFO_PRINT("Cleaned-up");

    return 1;
}

void sdmbn_notify_packet_received(char *type, struct timeval *recv_time)
{
    sdmbn_stats.pkts_received++;
    //double releaseTime;
    //releaseTime = recv_time->tv_sec + 0.000001 * recv_time->tv_usec;
    //INFO_PRINT("pkts_received=%d, flows_active=%d,received_time=%f"
    //      ,sdmbn_stats.pkts_received, sdmbn_stats.flows_active,releaseTime);
    // Output count statistics
    //if (0 == (sdmbn_stats.pkts_received % 10))
    //{ INFO_PRINT("pkts_received=%d, flows_active=%d",
    //        sdmbn_stats.pkts_received, sdmbn_stats.flows_active); }

    // Unlock get lock
    if (sdmbn_config.release_get_pkts > 0
            || sdmbn_config.release_get_flows > 0)
    {
        if (sdmbn_config.release_get_pkts == sdmbn_stats.pkts_received)
        {
            INFO_PRINT("Reached packet threshold => Get lock released");
            pthread_mutex_unlock(&sdmbn_lock_get);
        }
        else if (sdmbn_config.release_get_flows == sdmbn_stats.flows_active)
        {
            INFO_PRINT("Reached active flows threshold => Get lock released");
            pthread_mutex_unlock(&sdmbn_lock_get);
        }
    }
}

void sdmbn_notify_flow_created()
{
    sdmbn_stats.flows_active++;
}

void sdmbn_notify_flow_destroyed()
{
    sdmbn_stats.flows_active--;
}

static byte base64_encode_bits(byte data)
{
    if (data < 26)
        return (data + 'A');
    if (data < 52)
        return (data - 26 + 'a');
    if (data < 62)
        return (data - 52 + '0');
    if (data == 62)
        return '+';
    if (data == 63)
        return '/';
    return 0;
}

char *sdmbn_base64_encode(void *blob, int size)
{
    if (NULL == blob || size < 1)
    { return NULL; }
    byte *ptrBlob = (byte *)blob;
    char *result = (char *)malloc(size*2+1);
    if (NULL == result)
    { return NULL; }
    char *ptrResult = result;
    while (size > 0)
    {
        byte lower = *ptrBlob & 0x0F;
        byte upper = (*ptrBlob & 0xF0) >> 4;
        *ptrResult = base64_encode_bits(lower);
        ptrResult++;
        *ptrResult = base64_encode_bits(upper);
        ptrResult++;
        ptrBlob++;
        size += -1;
    }
    *ptrResult = 0;
    return result;
}

static byte base64_decode_bits(byte data)
{
    if (data >= 'A' && data <= 'Z')
        return (data - 'A');
    if (data >= 'a' && data <= 'z')
        return (data + 26 - 'a');
    if (data >= '0' && data <= '9')
        return (data + 52 - '0');
    if (data == '+')
        return 62;
    if (data == '/')
        return 63;
    return 0;
}

void *sdmbn_base64_decode(char *blob)
{
    if (NULL == blob)
    { return NULL; }
    byte *ptrBlob = (byte *)blob;
    int size = strlen(blob);
    void *result = malloc(size/2);
    if (NULL == result)
    { return NULL; }
    char *ptrResult = (char *)result;
    while (size > 0)
    {
        byte lower = base64_decode_bits(*ptrBlob);
        ptrBlob++;
        byte upper = base64_decode_bits(*ptrBlob);
        ptrBlob++;
        *ptrResult = (upper << 4) | lower;
        ptrResult++;
        size += -2;
    }
//    *ptrResult = 0;
    return result;
}


text:
import { css } from '@emotion/css';
import * as React from 'react';
import {
  IChoiceDescriptor,
  IChoiceInstance,
  IQuestionDescriptor,
  IQuestionInstance,
  IReply,
  IWhQuestionDescriptor,
} from 'wegas-ts-api';
import { entityIs } from '../../../data/entities';
import { getInstance } from '../../../data/methods/VariableDescriptorMethods';
import { State } from '../../../data/Reducer/reducers';
import { select } from '../../../data/selectors/VariableDescriptorSelector';
import { editingStore } from '../../../data/Stores/editingStore';
import { store, useStore } from '../../../data/Stores/store';
import { deepDifferent } from '../../Hooks/storeHookFactory';
import { CbxQuestionDisplay } from './CbxQuestion';
import { SimpleQuestionDisplay } from './SimpleQuestionDisplay';
import { WhQuestionDisplay, whQuestionInfo } from './WhQuestionDisplay';

export interface QuestionInfo {
  questionD?: Readonly<IQuestionDescriptor>;
  questionI?: Readonly<IQuestionInstance> | undefined;
  choicesD: Readonly<IChoiceDescriptor>[];
  choicesI: (Readonly<IChoiceInstance> | undefined)[];
  replies: Readonly<IReply[]>;
}

export const questionStyle = css({
  width: 'fit-content',
});

/**
 * Query subtree / instance about a QuestionDescriptor
 * @param question QuestionDescriptor to query
 */
export function questionInfo(question: IQuestionDescriptor) {
  return function (s: Readonly<State>): QuestionInfo {
    const questionD = select<IQuestionDescriptor>(question.id);
    const choicesD = questionD?.itemsIds
      .map(id => s.variableDescriptors[id])
      .filter(function (
        entity: IChoiceDescriptor | undefined,
      ): entity is IChoiceDescriptor {
        return entity != null;
      });
    const choicesI = choicesD?.map(c => getInstance(c)) || [];

    return {
      questionD,
      questionI: getInstance(question),
      choicesD: choicesD || [],
      choicesI,
      replies: (choicesI || [])
        .reduce<IReply[]>((c, i) => {
          if (i == null) {
            return c;
          }
          return c.concat(i.replies);
        }, [])
        .sort((a, b) => a.createdTime - b.createdTime),
    };
  };
}

interface ConnectedSimpleQuestionDisplayProps extends DisabledReadonly {
  entity: Readonly<IQuestionDescriptor>;
  editMode?: boolean;
}

export function ConnectedSimpleQuestionDisplay({
  entity,
  ...options
}: ConnectedSimpleQuestionDisplayProps) {
  const state = useStore(questionInfo(entity), deepDifferent);
  if (state.questionD == null) {
    return null;
  }
  return state.questionD.cbx ? (
    <CbxQuestionDisplay
      {...state}
      dispatch={editingStore.dispatch}
      {...options}
    />
  ) : (
    <SimpleQuestionDisplay
      {...state}
      dispatch={editingStore.dispatch}
      {...options}
    />
  );
}

interface ConnectedWhQuestionDisplay extends DisabledReadonly {
  entity: Readonly<IWhQuestionDescriptor>;
  editMode?: boolean;
}

export function ConnectedWhQuestionDisplay({
  entity,
  disabled,
  readOnly,
  editMode,
}: ConnectedWhQuestionDisplay) {
  const state = useStore(whQuestionInfo(entity), deepDifferent);
  return (
    <WhQuestionDisplay
      {...state}
      dispatch={store.dispatch}
      disabled={disabled}
      readOnly={readOnly}
      editMode={editMode}
    />
  );
}

export interface ConnectedQuestionDisplayProps extends DisabledReadonly {
  entity: Readonly<IQuestionDescriptor | IWhQuestionDescriptor>;
  editMode?: boolean;
}

export function ConnectedQuestionDisplay({
  entity,
  disabled,
  readOnly,
  editMode,
}: ConnectedQuestionDisplayProps) {
  return entityIs(entity, 'QuestionDescriptor') ? (
    <ConnectedSimpleQuestionDisplay
      entity={entity}
      disabled={disabled}
      readOnly={readOnly}
      editMode={editMode}
    />
  ) : (
    <ConnectedWhQuestionDisplay
      entity={entity}
      disabled={disabled}
      readOnly={readOnly}
      editMode={editMode}
    />
  );
}


text:
.click-shrink:active {
  -webkit-transform: scale(0.92);
          transform: scale(0.92);
}


text:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Title of the document</title>
    <script type="text/javascript">

      function s(stringa){
        console.log(stringa);
      }

      function somma(a,b){
        var c = a+b;
        return c;
      }

      //prova funzione che ritorna niente
      var func = function (){
        return;
      }
      console.log(
        "questo è il risultato di una funzione" +
        "che ritorna void "+ func + "\n e il risultato: " +
        func()
      );

      //costruzione oggetto literal notation
      var oggetto = {nome1 : "davide", nome2:"pippo"}
      var oggetto_ereditato = {};
      oggetto_ereditato.__proto__ = oggetto;
      s("oggetto ereditato: "+oggetto_ereditato.nome1);

      //costruzione tramite costruttore
      var oggetto2 = new Object();
      function Simone(saluto){
        //nuovo oggetto vuoto o con variabili, con 'this'
        this.saluto = saluto;
        this.salutaTutti = function (){
          s(this.saluto + " a tutti!");
        }
      }
      var simoneBuono = new Simone("ciao");
      var simoneCattivo = new Simone("fottetevi u_u");
      simoneBuono.salutaTutti();
      simoneCattivo.salutaTutti();

      //esempi di reperimento valore dalle proprietà
      //e di creazione e assegnazione di valori
      s(oggetto["nome1"]);
      s(oggetto.nome1);
      s(oggetto);
      oggetto.array = ["a","b","c"];
      s(oggetto.array);
      oggetto.array1 = [
        {a:"aaaaa", b:"bbbb"},
        "secondo elemento"
      ];

      s(oggetto.array1);
      s(oggetto.array1[0]);

      oggetto.array1.proprieta_array = "pippo";
      s(oggetto.array1.proprieta_array);
    </script>

  </head>
    <body>
      Content of the document......
    </body>
</html>


text:
layout: docwithnav
title: ESP32 Pico Kit GPIO control and DHT22 sensor monitor using ThingsBoard Arduino SDK
description: ThingsBoard IoT Platform sample for ESP32 Pico Kit GPIO control and temperature/humidity monitor using ThingsBoard Arduino SDK
hidetoc: "true"
---

* TOC
{:toc}

## Introduction

{% include templates/what-is-thingsboard.md %}

[ESP32](https://www.espressif.com/en/products/hardware/esp32/overview) is a series of low-cost, low-power system-on-a-chip microcontrollers with integrated self-contained Wi-Fi and dual-mode Bluetooth. ESP32 is a successor of ESP8266 chip.

This sample application will allow you to control GPIO of your ESP32 device using ThingsBoard web UI and display humidity/temperature data from DHT22 sensor. We will observe GPIO control using LEDs connected to the pins. The purpose of this application is to demonstrate ThingsBoard [RPC capabilities](/docs/user-guide/rpc/) and ThingsBoard [Telemetry](/docs/user-guide/telemetry/).

The application that is running on ESP32 is written using ThingsBoard Arduino SDK which is quite simple and easy to understand.

Current GPIO state and GPIO control widget is visualized using built-in customizable dashboard.

Once you complete this sample/tutorial, you will see your sensor data on the following dashboard.

 ![image](/images/samples/esp32/gpio-temperature/dashboard.png)

## List of hardware

 - [ESP32 Pico Kit board](https://www.espressif.com/en/products/hardware/development-boards).

  ![image](https://docs.espressif.com/projects/esp-idf/en/latest/_images/esp32-pico-kit-v4.1-layout.jpg)

 - [DHT22 sensor](https://www.aliexpress.com/item/1pcs-DHT22-digital-temperature-and-humidity-sensor-Temperature-and-humidity-module-AM2302-replace-SHT11-SHT15/32316036161.html)

  ![image](/images/samples/arduino/temperature/dht22-pinout.png)

 - 6 LEDs
 - 6 Resistors in range between 68Ω and 100Ω
 - Breadboard
 - Micro-USB cable

## Wiring

### DHT22 connection

Pin | Connect to
-----------|-----------
DHT22 VCC |  Pico 5V
DHT22 DATA | Pico 33

### LEDs connection

Pin | Connect to
-----------|-----------
LED1 Anode | Pico 32 trough resistor (68Ω - 100Ω)
LED2 Anode | Pico 26 trough resistor (68Ω - 100Ω)
LED3 Anode | Pico 25 trough resistor (68Ω - 100Ω)
LED4 Anode | Pico 19 trough resistor (68Ω - 100Ω)
LED5 Anode | Pico 22 trough resistor (68Ω - 100Ω)
LED6 Anode | Pico 21 trough resistor (68Ω - 100Ω)
All LEDs cathodes | Pico Ground

### Connection diagram

The following picture summarizes the connections for this project:

![image](/images/samples/esp32/gpio-temperature/wiring.png)

## Device provisioning

This step contains instructions that are necessary to connect your device to ThingsBoard.

Open ThingsBoard Web UI (http://localhost:8080) in browser and login as tenant administrator.
If you loaded the demo data during TB installation, the next credentials can be used:

 - login: tenant@thingsboard.org
 - password: tenant

Go to "Devices" section. Click "+" button and create a device with the name "ESP32 Pico Device". Set "Device type" to "default".

![image](/images/samples/esp32/gpio-temperature/device.png)

Once device created, open its details and click "Manage credentials".

Copy auto-generated access token from the "Access token" field. Please save this device token. It will be referred to later as **$ACCESS_TOKEN**.

![image](/images/samples/esp32/gpio-temperature/credentials.png)

## Provision your dashboard

Download the dashboard file using this [**link**](/docs/samples/esp32/resources/esp32-dht22-temp-and-gpio-dashboard.json).
Use import/export [**instructions**](/docs/user-guide/ui/dashboards/#dashboard-importexport) to import the dashboard to your ThingsBoard instance.

## Creating ESP32 firmware

Easiest way to program ESP32 Pico Kit is to use Arduino IDE. Following sections are describing that approach.

### ESP32 and Arduino IDE setup

First you will need Arduino IDE and all related software installed.

Download and install [Arduino IDE](https://www.arduino.cc/en/Main/Software).

The Pico board support must be added to Arduino IDE before any program can be built and flashed into ESP32. To do so, install ESP32 package as described below:

1. Open Arduino IDE.

1. Open **File -> Preferences** menu, and add a board manager URLs

   ```
   https://dl.espressif.com/dl/package_esp32_index.json,http://arduino.esp8266.com/stable/package_esp8266com_index.json
   ```

   into **Additional Boards Manager URL** field, as shown below:

   ![image](/images/samples/esp32/gpio-temperature/add-esp32-url.png)

1. Select **Tools -> Board... -> Board manager** menu.

1. Enter **ESP32** in the search field. Click **Install**

   ![image](/images/samples/esp32/gpio-temperature/install-esp32-arduino.png)

### Install Arduino ThingsBoard SDK

To simplify application development, install the ThingsBoard Arduino SDK and its dependencies from standard Arduino library repository:

1. Proceed to **Sketch -> Include Library...** submenu. Select **Manage Libraries**.

1. Find and install **ThingsBoard Arduino SDK**, **PubSubClient by Nick O'Leary** and **ArduinoHttpClient** libraries.

   ![image](/images/samples/esp32/gpio-temperature/install-thingsboard-arduino.png)
   ![image](/images/samples/esp32/gpio-temperature/install-pubsubclient-arduino.png)
   ![image](/images/samples/esp32/gpio-temperature/install-arduinohttpclient-arduino.png)

1. Install **ArduinoJSON** library **v6.9.1** or higher. Avoid installing beta releases of the ArduinoJson library.

   ![image](/images/samples/esp32/gpio-temperature/do-not-use-beta-version-arduinojson.png)

From now on, you can use ThingsBoard SDK right from Arduino IDE.

### Install ESP32 DHT22 driver

DHT22 sensor, connected to the ESP32 requires a special driver. To install it, proceed as follows:

1. Click on "Sketch" menu. Open "Include Library..." submenu. Select "Manage Libraries".

1. Type "ESP DHT22" in the search field.

1. Click install on "DHT22 Sensor Library for ESPx", as shown below:

   ![image](/images/samples/esp32/gpio-temperature/install-esp32-dht22-arduino.png)

### Connect ESP32 Pico to PC

ESP32 Pico Kit does not require a sophisticated connection. Just plug micro-USB cable into PC and Pico, this should be enough.

### Prepare and upload sketch

Download and open **esp32-dht-gpio.ino** sketch.

**Note** You need to edit following constants and variables in the sketch:

- `WIFI_AP` - name of your access point
- `WIFI_PASSWORD` - access point password
- `TOKEN` - the **$ACCESS_TOKEN** from ThingsBoard configuration step.
- `THINGSBOARD_SERVER` - ThingsBoard HOST/IP address that is accessible within your wifi network. Specify `demo.thingsboard.io` if you are using [live demo](https://demo.thingsboard.io/) server.

{% capture tabspec %}arduino-sketch
esp32-dht-gpio,esp32-dht-gpio.ino,c,resources/esp32-dht-gpio.ino,/docs/samples/esp32/resources/esp32-dht-gpio.ino{% endcapture %}
{% include tabs.html %}

## Troubleshooting

In order to to perform troubleshooting, you must check ESP32 Pico logs. For that, simply open **Serial Monitor** in the Arduino IDE.

## Data visualization and GPIO control

Finally, open ThingsBoard Web UI. You can access this dashboard by logging in as a tenant administrator.

In case of local installation (if the demo data was added during TB installation):

 - login: tenant@thingsboard.org
 - password: tenant

In case of live-demo server:

 - login: your live-demo username (email)
 - password: your live-demo password

See **[live-demo](/docs/user-guide/live-demo/)** page for more details how to get your account.

Go to **"Devices"** section and locate **"ESP32 Pico Device"**, open device details and switch to **"Latest telemetry"** tab.
If all is configured correctly you should be able to see latest values of *"temperature"* and *"humidity"* in the table.

![image](/images/samples/esp32/gpio-temperature/telemetry.png)

After, open **"Dashboards"** section then locate and open **"ESP32 Pico Dashboard"**.
As a result, you will see a time-series chart displaying temperature and humidity level (similar to dashboard image in the introduction).

You should also observe a GPIO control for your device. It consists of two widgets: one is for controlling LED blink speed (in milliseconds) and second for turning individual LEDs on and off.

You can switch status of GPIOs using control panel. As a result, you will see LEDs status change on the device. To control LED blink speed, simply turn a knob and observe a speed change.

## See also

Browse other [samples](/docs/samples) or explore guides related to main ThingsBoard features:

 - [Device attributes](/docs/user-guide/attributes/) - how to use device attributes.
 - [Telemetry data collection](/docs/user-guide/telemetry/) - how to collect telemetry data.
 - [Using RPC capabilities](/docs/user-guide/rpc/) - how to send commands to/from devices.
 - [Rule Engine](/docs/user-guide/rule-engine/) - how to use rule engine to analyze data from devices.
 - [Data Visualization](/docs/user-guide/visualization/) - how to visualize collected data.

{% include templates/feedback.md %}

{% include socials.html %}

## Next steps

{% assign currentGuide = "HardwareSamples" %}{% include templates/guides-banner.md %}


text:
package org.apache.spark.rdd

import java.io.{IOException, ObjectOutputStream}

import org.apache.spark.util.Utils
import org.apache.spark.{Partition, SparkContext, TaskContext}

import scala.collection.mutable.ArrayBuffer
import scala.reflect.ClassTag
import scala.util.control.NonFatal

object ZippedPartitionsWithLocalityRDD {
  def apply[T: ClassTag, B: ClassTag, V: ClassTag]
  (rdd1: RDD[T], rdd2: RDD[B], preservesPartitioning: Boolean = false)
    (f: (Iterator[T], Iterator[B]) => Iterator[V]): RDD[V] = rdd1.withScope {
    val sc = rdd1.sparkContext
    new ZippedPartitionsWithLocalityRDD(
      sc, sc.clean(f), rdd1, rdd2, preservesPartitioning)
  }
}

class ZippedPartitionsWithLocalityRDD[A: ClassTag, B: ClassTag, V: ClassTag](
  sc: SparkContext,
  _f: (Iterator[A], Iterator[B]) => Iterator[V],
  _rdd1: RDD[A],
  _rdd2: RDD[B],
  preservesPartitioning: Boolean = false)
  extends ZippedPartitionsRDD2[A, B, V](sc, _f, _rdd1, _rdd2, preservesPartitioning) {

  override def getPartitions: Array[Partition] = {
    require(rdds.length == 2, "this is only for 2 rdd zip")
    val numParts = rdds.head.partitions.length
    if (!rdds.forall(rdd => rdd.partitions.length == numParts)) {
      throw new IllegalArgumentException("Can't zip RDDs with unequal numbers of partitions")
    }

    val candidateLocs = new ArrayBuffer[(Int, Seq[String])]()
    (0 until numParts).foreach(p => {
      candidateLocs.append((p, rdds(1).context.getPreferredLocs(rdds(1), p).map(_.host).distinct))
    })
    val nonmatchPartitionId = new ArrayBuffer[Int]()
    val parts = new Array[Partition](numParts)

    (0 until  numParts).foreach { i =>
      val curPrefs = rdds(0).context.getPreferredLocs(rdds(0), i).map(_.host).distinct
      var p = 0
      var matchPartition: (Int, Seq[String]) = null
      var locs: Seq[String] = null
      while (p < candidateLocs.length) {
        locs = candidateLocs(p)._2.intersect(curPrefs)
        if (!locs.isEmpty) {
          matchPartition = candidateLocs.remove(p)
          p = Integer.MAX_VALUE - 1
        }
        p += 1
      }
      if (matchPartition != null) {
        parts(i) =
          new ZippedPartitionsLocalityPartition(i, Array(i, matchPartition._1), rdds, locs)
      } else {
        println(s"can't find locality partition for partition $i " +
          s"Partition locations are (${curPrefs}) Candidate partition locations are\n" +
          s"${candidateLocs.mkString("\n")}.")
        nonmatchPartitionId.append(i)
      }
    }

    require(nonmatchPartitionId.size == candidateLocs.size,
      "unmatched partition size should be the same with candidateLocs size")
    val nonmatchedParts = nonmatchPartitionId.map { i =>
      val locs = rdds(0).context.getPreferredLocs(rdds(0), i).map(_.host).distinct
      val matchPartition = candidateLocs.remove(0)
      parts(i) = new ZippedPartitionsLocalityPartition(i, Array(i, matchPartition._1), rdds, locs)
    }
    parts
  }
}

private[spark] class ZippedPartitionsLocalityPartition(
  idx: Int,
  @transient indexes: Seq[Int],
  @transient rdds: Seq[RDD[_]],
  @transient override val preferredLocations: Seq[String])
  extends ZippedPartitionsPartition(idx, rdds, preferredLocations) {

  override val index: Int = idx
  var _partitionValues = rdds.zip(indexes).map{ case (rdd, i) => rdd.partitions(i) }
  override def partitions: Seq[Partition] = _partitionValues

  @throws(classOf[IOException])
  private def writeObject(oos: ObjectOutputStream): Unit = {
    try {
      // Update the reference to parent split at the time of task serialization
      _partitionValues = rdds.zip(indexes).map{ case (rdd, i) => rdd.partitions(i) }
      oos.defaultWriteObject()
    } catch {
      case e: IOException =>
        throw e
      case NonFatal(e) =>
        throw new IOException(e)
    }
  }
}


text:
import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import TextField from 'material-ui/TextField';
import LeftChevronIcon from 'app/components/Store/Icons/LeftChevronIcon';
import RightChevronIcon from 'app/components/Store/Icons/RightChevronIcon';
import Button from 'app/components/Store/Main/Button';

const Wrapper = styled.div`
  display: flex;
  flex-direction: column;
`;

const Title = styled.h2`

`;

const Divider = styled.div`
  width: 100%;
  height: 1px;
  background: #EEE;
`;

const InputWrapper = styled.div`
`;

const ButtonsWrapper = styled.div`
  display: flex;
  justify-content: space-between;
  margin-top: 16px;
`;

const RequiredWrapper = styled.div`
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
`;

const BackButtonIcon = styled(LeftChevronIcon)`
  opacity: 0.5;
  margin-right: 10px;
`;

const CheckoutButtonIcon = styled(RightChevronIcon)`
  opacity: 0.5;
  margin-left: 10px;
`;

class CheckoutForm extends React.Component {
  componentWillMount() {
    this.setState({
      order: {
        firstName: '',
        lastName: '',
        email: '',
        addressLine1: '',
        addressLine2: '',
        city: '',
        state: '',
        zipCode: '',
        phoneNumber: '',
      },
    });
  }

  onChange = (data) => {
    this.setState({
      order: {
        ...this.state.order,
        ...data,
      },
    });
  }

  render() {
    const {
      errors,
      submitDisabled,
      onSubmit,
      onBackToCartClick,
    } = this.props;

    const {
      order,
    } = this.state;

    return (
      <Wrapper>
        <Title>
          Delivery Address
        </Title>
        <Divider />
        <RequiredWrapper>
          <small>* Required field</small>
        </RequiredWrapper>
        <InputWrapper>
          <TextField
            fullWidth
            floatingLabelText={'*First name'}
            errorText={errors && errors.firstName}
            value={order.firstName}
            onChange={(event) => this.onChange({ firstName: event.target.value })}
          />
        </InputWrapper>
        <InputWrapper>
          <TextField
            fullWidth
            floatingLabelText={'*Last name'}
            errorText={errors && errors.lastName}
            value={order.lastName}
            onChange={(event) => this.onChange({ lastName: event.target.value })}
          />
        </InputWrapper>
        <InputWrapper>
          <TextField
            fullWidth
            floatingLabelText={'*Email'}
            errorText={errors && errors.email}
            value={order.email}
            onChange={(event) => this.onChange({ email: event.target.value })}
          />
        </InputWrapper>
        <InputWrapper>
          <TextField
            fullWidth
            floatingLabelText={'*Address Line 1'}
            errorText={errors && errors.addressLine1}
            value={order.addressLine1}
            onChange={(event) => this.onChange({ addressLine1: event.target.value })}
          />
        </InputWrapper>
        <InputWrapper>
          <TextField
            fullWidth
            floatingLabelText={'Address Line 2'}
            errorText={errors && errors.addressLine2}
            value={order.addressLine2}
            onChange={(event) => this.onChange({ addressLine2: event.target.value })}
          />
        </InputWrapper>
        <InputWrapper>
          <TextField
            fullWidth
            floatingLabelText={'*City'}
            errorText={errors && errors.city}
            value={order.city}
            onChange={(event) => this.onChange({ city: event.target.value })}
          />
        </InputWrapper>
        <InputWrapper>
          <TextField
            fullWidth
            floatingLabelText={'*State'}
            errorText={errors && errors.state}
            value={order.state}
            onChange={(event) => this.onChange({ state: event.target.value })}
          />
        </InputWrapper>
        <InputWrapper>
          <TextField
            fullWidth
            floatingLabelText={'*Zip code'}
            errorText={errors && errors.zipCode}
            value={order.zipCode}
            onChange={(event) => this.onChange({ zipCode: event.target.value })}
          />
        </InputWrapper>
        <InputWrapper>
          <TextField
            fullWidth
            floatingLabelText={'*Phone Number'}
            errorText={errors && errors.phoneNumber}
            value={order.phoneNumber}
            onChange={(event) => this.onChange({ phoneNumber: event.target.value })}
          />
        </InputWrapper>
        <ButtonsWrapper>
          <Button
            primary
            disabled={submitDisabled}
            onClick={onBackToCartClick}
          >
            <BackButtonIcon />
            Back to cart
          </Button>
          <Button
            primary
            disabled={submitDisabled}
            onClick={() => onSubmit(order)}
          >
            Checkout
            <CheckoutButtonIcon />
          </Button>
        </ButtonsWrapper>
      </Wrapper>
    );
  }
}

CheckoutForm.propTypes = {
  errors: PropTypes.object,
  submitDisabled: PropTypes.bool,
  onSubmit: PropTypes.func.isRequired,
  onBackToCartClick: PropTypes.func.isRequired,
};

export default CheckoutForm;


text:
import System.Directory.Extra
import Data.List.Extra
import System.FilePath
import Control.Monad
import Data.Function

main = do
    xs <- listFilesRecursive "index"
    print $ length xs
    files <- return $ map (maximumBy (compare `on` f) . snd) $ groupSort [(takeDirectory $ takeDirectory x, x) | x <- xs ]
    print $ length files
    forM_ files $ \x -> do
        copyFile x ("out" </> takeFileName x)

f :: String -> [Int]
f = map read . wordsBy (== '.') . takeFileName . takeDirectory


text:
class Texture;
class Shader;
class Camera;
struct DirectionalLight;
class Chunk;
class ChunkManager;
class Mesh;
class World;
struct Material;
class Renderer
{
public:
	Renderer(int screenWidth, int screenHeight, bool debug);
	~Renderer();
	void Draw();
	bool Initialize();
	SDL_Window* GetWindow();
	Camera* camera;
private:
	bool debug;
	SDL_Window* sdlWindow;
	int screenWidth;
	int screenHeight;
	bool InitOpenGL();
	//SDL_GLContext gContext;
	Shader* shader;
	Texture* texture;
	DirectionalLight* directionalLight;
	Material* material;
	glm::vec3* target;
	//Chunk* chunk;
	ChunkManager* chunkManager;
	World* world;
};


text:
const tooltipInstance = (
  <div>
    <Tooltip placement="right" className="in">
      Tooltip right
    </Tooltip>

    <Tooltip placement="top" className="in">
      Tooltip top
    </Tooltip>

    <Tooltip placement="left" className="in">
      Tooltip left
    </Tooltip>

    <Tooltip placement="bottom" className="in">
      Tooltip bottom
    </Tooltip>
  </div>
);

ReactDOM.render(tooltipInstance, mountNode);


text:
import untangle
import requests
from models import Aufmacher, Author, Image, TweetJob
from config import db
import csv
from pathlib import Path
import arrow
from collections import defaultdict
from operator import itemgetter

dumb_tag_list = []
all_tags = {}
teaser_texts = []

def get_tags(article_xml):
    head = article_xml.head

    try:
        tags = head.rankedTags
    except AttributeError:
        return []

    saved_tags = []
    for tag in tags.tag:
        tag_name = tag.cdata.strip()
        tag_type = tag["type"].lower()

        saved_tags.append({"name": tag_name, "type": tag_type})

        key = tag_name + tag_type
        if not key in all_tags:
            all_tags[key] = {"name": tag_name, "type": tag_type, "count": 0}

        all_tags[key]["count"] += 1

        dumb_tag_list.append(tag_name)

    return saved_tags

def get_article_data(aufmacher, article_xml, next_aufmacher):
    tags = get_tags(article_xml)

    created = arrow.get(aufmacher.created_at)
    release_date = created.format("YYYY-MM-DD")
    release_time = created.format("HH-mm-ss")

    delta = None
    if next_aufmacher:
        next_created = arrow.get(next_aufmacher.created_at).datetime
        delta = (next_created - created.datetime).seconds

    url_parts = aufmacher.unique_id.replace("http://xml.zeit.de/", "").split("/")

    breaking_news = False
    text_length = None
    for attribute in article_xml.head.attribute:
        if attribute["name"] == "breaking_news":
            if attribute.cdata == "yes":
                breaking_news = True
        if attribute["name"] == "text-length":
            try:
                text_length = int(attribute.cdata)
            except Exception:
                text_length = None

    teaser_super_title = article_xml.teaser.supertitle.cdata.strip()
    teaser_title = article_xml.teaser.title.cdata.strip()
    teaser_text = article_xml.teaser.text.cdata.strip()

    teaser_texts.append({"teaserText": teaser_text, "url": aufmacher.unique_id})

    return {
        "url": aufmacher.unique_id,
        "tags": ",".join([x["name"] for x in tags]),
        "releaseDate": release_date,
        "releaseTime": release_time,
        "title": aufmacher.title,
        "superTitle": aufmacher.supertitle,
        "ressort": url_parts[0],
        "subressort": url_parts[1],
        "breaking": breaking_news,
        "textLength": text_length,
        "questionMarkInTitle": "?" in aufmacher.title,
        "exclamationMarkInTitle": "?" in aufmacher.title,
        "numberOfQuotationMarksInTitle": aufmacher.title.count('"'),
        "secondsAsAufmacher": delta,
        "teaserSuperTitle": teaser_super_title,
        "teaserTitle": teaser_title,
        "questionMarkInTeaserTitle": "?" in teaser_title,
        "exclamationMarkInTeaserTitle": "?" in teaser_title,
        "numberOfQuotationMarksInTeaserTitle": teaser_title.count('"'),
    }

def make_stats():
    start_date = arrow.get("2019-10-14", "YYYY-MM-DD").datetime
    end_date = arrow.get("2020-10-14", "YYYY-MM-DD").datetime
    number_of_days = (end_date - start_date).days

    db.connect()
    aufmacher = (
        Aufmacher.select()
        .where(
            (Aufmacher.created_at >= start_date) & (Aufmacher.created_at <= end_date)
        )
        .order_by(Aufmacher.created_at)
    )
    csv_data = []

    print("{} Aufmacher an {} Tagen".format(len(aufmacher), number_of_days))
    print(len(aufmacher) / number_of_days, " Aufmacher pro Tag")

    for index, auf in enumerate(aufmacher):
        path_to_file = auf.unique_id.replace("http://xml.zeit.de/", "")
        xml_file_path = (Path("xml") / path_to_file).with_suffix(".xml")

        next_aufmacher = aufmacher[index + 1] if index < len(aufmacher) - 1 else None

        if xml_file_path.is_file():
            with open(xml_file_path, "r") as xml_file:
                parsed_article = untangle.parse(xml_file)
                print(xml_file_path)
                try:
                    article_data = get_article_data(
                        auf, parsed_article.article, next_aufmacher
                    )
                    if article_data:
                        csv_data.append(article_data)
                except AttributeError:
                    continue

    with open("stats/aufmacher.csv", "w") as csv_file:
        writer = csv.DictWriter(csv_file, fieldnames=csv_data[0].keys())
        writer.writeheader()
        writer.writerows(csv_data)

    with open("stats/tags.csv", "w") as csv_file:
        writer = csv.DictWriter(csv_file, fieldnames=list(all_tags.values())[0].keys())
        writer.writeheader()
        writer.writerows(
            sorted(list(all_tags.values()), key=itemgetter("count"), reverse=True)
        )

    with open("stats/tagcloud.txt", "w") as out_file:
        out_file.write("\n".join(dumb_tag_list))

    headlines_with_shitlist_words = []
    teasers_with_shitlist_words = []
    with open("shitlist.txt", "r") as shitlist_file:
        shitlist = [line.rstrip("\n").lower() for line in shitlist_file]
        print(shitlist)

        for auf in csv_data:
            if any([word in auf["teaserTitle"].lower() for word in shitlist]):
                headlines_with_shitlist_words.append(
                    {"teaserTitle": auf["teaserTitle"], "url": auf["url"]}
                )

        for auf in teaser_texts:
            if any([word in auf["teaserText"].lower() for word in shitlist]):
                teasers_with_shitlist_words.append(
                    {
                        "teaserText": auf["teaserText"],
                        "url": auf["url"],
                        "words": ", ".join(
                            [
                                word
                                for word in shitlist
                                if word in auf["teaserText"].lower()
                            ]
                        ),
                    }
                )

    if len(headlines_with_shitlist_words):
        with open("stats/shitlisted_headlines.csv", "w") as out_file:
            writer = csv.DictWriter(
                out_file, fieldnames=headlines_with_shitlist_words[0].keys()
            )
            writer.writeheader()
            writer.writerows(headlines_with_shitlist_words)

    if len(teasers_with_shitlist_words):
        with open("stats/shitlisted_teasers.csv", "w") as out_file:
            writer = csv.DictWriter(
                out_file, fieldnames=teasers_with_shitlist_words[0].keys()
            )
            writer.writeheader()
            writer.writerows(teasers_with_shitlist_words)

if __name__ == "__main__":
    make_stats()


text:
require 'spec_helper'

describe Admin::SessionsController, :do_not_mock_admin_mode do
  include_context 'custom session'

  let(:user) { create(:user) }

  before do
    sign_in(user)
  end

  describe '#new' do
    context 'for regular users' do
      it 'shows error page' do
        get :new

        expect(response).to have_gitlab_http_status(:not_found)
        expect(controller.send(:current_user_mode).admin_mode?).to be(false)
      end
    end

    context 'for admin users' do
      let(:user) { create(:admin) }

      it 'renders a password form' do
        get :new

        expect(response).to render_template :new
        expect(controller.send(:current_user_mode).admin_mode?).to be(false)
      end
    end
  end

  describe '#create' do
    context 'for regular users' do
      it 'shows error page' do
        post :create

        expect(response).to have_gitlab_http_status(:not_found)
        expect(controller.send(:current_user_mode).admin_mode?).to be(false)
      end
    end

    context 'for admin users' do
      let(:user) { create(:admin) }

      it 'sets admin mode with a valid password' do
        expect(controller.send(:current_user_mode).admin_mode?).to be(false)

        controller.store_location_for(:redirect, admin_root_path)
        post :create, params: { password: user.password }

        expect(response).to redirect_to admin_root_path
        expect(controller.send(:current_user_mode).admin_mode?).to be(true)
      end

      it 'fails with an invalid password' do
        expect(controller.send(:current_user_mode).admin_mode?).to be(false)

        controller.store_location_for(:redirect, admin_root_path)

        post :create, params: { password: '' }

        expect(response).to render_template :new
        expect(controller.send(:current_user_mode).admin_mode?).to be(false)
      end
    end
  end

  describe '#destroy' do
    context 'for regular users' do
      it 'shows error page' do
        get :destroy

        expect(response).to have_gitlab_http_status(404)
        expect(controller.send(:current_user_mode).admin_mode?).to be(false)
      end
    end

    context 'for admin users' do
      let(:user) { create(:admin) }

      it 'disables admin mode and redirects to main page' do
        expect(controller.send(:current_user_mode).admin_mode?).to be(false)
        post :create, params: { password: user.password }
        expect(controller.send(:current_user_mode).admin_mode?).to be(true)

        get :destroy

        expect(response).to have_gitlab_http_status(:found)
        expect(response).to redirect_to(root_path)
        expect(controller.send(:current_user_mode).admin_mode?).to be(false)
      end
    end
  end
end


text:
<?php
// +----------------------------------------------------------------------
// | Writen By lichunqiang
// +----------------------------------------------------------------------
// | Copyright (c) 2012-2014, All rights reserved.
// +----------------------------------------------------------------------
// | Author: Light <light-li@hotmail.com>
// +----------------------------------------------------------------------

namespace Light\Wechat\Exceptions;

class RuntimeException extends \Exception
{

}


text:
package sample.secure.oauth2;

import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.WebIntegrationTest;
import org.springframework.hateoas.MediaTypes;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.web.context.WebApplicationContext;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;

/**
 * Series of automated integration tests to verify proper behavior of auto-configured,
 * OAuth2-secured system
 *
 * @author Greg Turnquist
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(SampleSecureOAuth2Application.class)
@WebIntegrationTest(randomPort = true)
public class SampleSecureOAuth2ApplicationTests {

	@Autowired
	WebApplicationContext context;

	@Autowired
	FilterChainProxy filterChain;

	private MockMvc mvc;

	private final ObjectMapper objectMapper = new ObjectMapper();

	@Before
	public void setUp() {
		this.mvc = webAppContextSetup(this.context).addFilters(this.filterChain).build();
		SecurityContextHolder.clearContext();
	}

	@Test
	public void everythingIsSecuredByDefault() throws Exception {
		this.mvc.perform(get("/").accept(MediaTypes.HAL_JSON))
				.andExpect(status().isUnauthorized()).andDo(print());
		this.mvc.perform(get("/flights").accept(MediaTypes.HAL_JSON))
				.andExpect(status().isUnauthorized()).andDo(print());
		this.mvc.perform(get("/flights/1").accept(MediaTypes.HAL_JSON))
				.andExpect(status().isUnauthorized()).andDo(print());
		this.mvc.perform(get("/alps").accept(MediaTypes.HAL_JSON))
				.andExpect(status().isUnauthorized()).andDo(print());
	}

	@Test
	@Ignore
	public void accessingRootUriPossibleWithUserAccount() throws Exception {
		String header = "Basic " + new String(Base64.encode("greg:turnquist".getBytes()));
		this.mvc.perform(
				get("/").accept(MediaTypes.HAL_JSON).header("Authorization", header))
				.andExpect(
						header().string("Content-Type", MediaTypes.HAL_JSON.toString()))
				.andExpect(status().isOk()).andDo(print());
	}

	@Test
	public void useAppSecretsPlusUserAccountToGetBearerToken() throws Exception {
		String header = "Basic " + new String(Base64.encode("foo:bar".getBytes()));
		MvcResult result = this.mvc
				.perform(post("/oauth/token").header("Authorization", header)
						.param("grant_type", "password").param("scope", "read")
						.param("username", "greg").param("password", "turnquist"))
				.andExpect(status().isOk()).andDo(print()).andReturn();
		Object accessToken = this.objectMapper
				.readValue(result.getResponse().getContentAsString(), Map.class)
				.get("access_token");
		MvcResult flightsAction = this.mvc
				.perform(get("/flights/1").accept(MediaTypes.HAL_JSON)
						.header("Authorization", "Bearer " + accessToken))
				.andExpect(
						header().string("Content-Type", MediaTypes.HAL_JSON.toString()))
				.andExpect(status().isOk()).andDo(print()).andReturn();

		Flight flight = this.objectMapper.readValue(
				flightsAction.getResponse().getContentAsString(), Flight.class);

		assertThat(flight.getOrigin(), is("Nashville"));
		assertThat(flight.getDestination(), is("Dallas"));
		assertThat(flight.getAirline(), is("Spring Ways"));
		assertThat(flight.getFlightNumber(), is("OAUTH2"));
		assertThat(flight.getTraveler(), is("Greg Turnquist"));
	}

}


text:
namespace Browsio.UnitTest
{
    #region << Using >>

    using System.Web.Mvc;
    using Browsio.Controllers;
    using Browsio.Domain;
    using Incoding.MSpecContrib;
    using Incoding.MvcContrib;
    using Machine.Specifications;

    #endregion

    [Subject(typeof(AccountController))]
    public class When_account_controller_get_sing_in
    {
        #region Establish value

        static MockController<AccountController> mockController;

        static ActionResult result;

        #endregion

        Establish establish = () =>
                                  {
                                      mockController = MockController<AccountController>
                                              .When();
                                  };

        Because of = () => { result = mockController.Original.SignIn(); };

        It should_be_result = () => result.ShouldBeOfType<IncodingResult>();
    }
}