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

using Google.Api.Gax.Grpc;
using Google.Api.Gax.Testing;
using Google.Cloud.Firestore.V1Beta1;
using Google.Protobuf;
using Grpc.Core;
using Grpc.Core.Testing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using static Google.Cloud.Firestore.V1Beta1.FirestoreClient;
using static Google.Cloud.Firestore.V1Beta1.StructuredQuery.Types;
using static Google.Cloud.Firestore.V1Beta1.Target.Types;

namespace Google.Cloud.Firestore.Tests
{
    public class WatchStreamTest
    {
        /// <summary>
        /// A timeout for waiting for asynchronous operations. The code is designed
        /// so that if this *does* time out, it always represents a failure. We should never
        /// actually need this much time; it just prevents tests from hanging entirely.
        /// </summary>
        private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(10);

        [Fact]
        public void Stop()
        {
            var sequence = new TestSequence();
            sequence.ExpectConnect(null, StreamInitializationCause.WatchStarting);
            sequence.ProvideResponse(WatchResponseResult.Continue);
            sequence.WaitForCancellation();

            Task task = sequence.RunToStability();
            sequence.WatchStream.Stop(CancellationToken.None);
            task.Wait();
            sequence.Verify();
        }

        [Fact]
        public void StreamReset()
        {
            ByteString token = ByteString.CopyFromUtf8("token");
            var sequence = new TestSequence();
            sequence.ExpectConnect(null, StreamInitializationCause.WatchStarting);
            sequence.ProvideResponse(WatchResponseResult.Continue);
            sequence.ProvideResponse(WatchResponseResult.ResetStream);
            // First reset doesn't get a token
            sequence.ExpectConnect(null, StreamInitializationCause.ResetRequested);
            sequence.ProvideResponse(WatchResponseResult.StreamHealthy, token);
            sequence.ProvideResponse(WatchResponseResult.ResetStream);
            // Second reset does
            sequence.ExpectConnect(token, StreamInitializationCause.ResetRequested);
            sequence.WaitForCancellation();

            Task task = sequence.RunToStability();
            sequence.WatchStream.Stop(CancellationToken.None);
            task.Wait();
            sequence.Verify();
        }

        [Fact]
        public void StreamComplete()
        {
            ByteString token1 = ByteString.CopyFromUtf8("token1");
            ByteString token2 = ByteString.CopyFromUtf8("token2");
            var sequence = new TestSequence();
            sequence.ExpectConnect(null, StreamInitializationCause.WatchStarting);
            sequence.ProvideResponse(WatchResponseResult.Continue);
            sequence.ProvideResponse(WatchResponseResult.StreamHealthy, token1);
            sequence.ProvideResponse(WatchResponseResult.StreamHealthy, token2);
            sequence.ProvideResponse(WatchResponseResult.Continue);
            // The stream ended. Restart with the last token.
            sequence.ExpectConnect(token2, StreamInitializationCause.StreamCompleted);
            sequence.ProvideResponse(WatchResponseResult.Continue);
            sequence.WaitForCancellation();

            Task task = sequence.RunToStability();
            sequence.WatchStream.Stop(CancellationToken.None);
            task.Wait();
            sequence.Verify();
        }

        [Fact]
        public void RetriableRpcException()
        {
            ByteString token1 = ByteString.CopyFromUtf8("token1");
            ByteString token2 = ByteString.CopyFromUtf8("token2");
            var sequence = new TestSequence();
            sequence.ExpectConnect(null, StreamInitializationCause.WatchStarting);
            sequence.ProvideResponse(WatchResponseResult.Continue);
            sequence.ProvideResponse(WatchResponseResult.StreamHealthy, token1);
            sequence.ProvideResponse(WatchResponseResult.StreamHealthy, token2);
            sequence.RpcException(new RpcException(new Status(StatusCode.DeadlineExceeded, "This exception is transient")));
            // The server throw a retriable exception. Reinitialize.
            sequence.ExpectConnect(token2, StreamInitializationCause.RpcError);
            sequence.ProvideResponse(WatchResponseResult.Continue);
            sequence.WaitForCancellation();

            Task task = sequence.RunToStability();
            sequence.WatchStream.Stop(CancellationToken.None);
            task.Wait();
            sequence.Verify();
        }

        [Fact]
        public void ResourceExhaustedRpcException()
        {
            ByteString token1 = ByteString.CopyFromUtf8("token1");
            ByteString token2 = ByteString.CopyFromUtf8("token2");
            var sequence = new TestSequence();
            sequence.ExpectConnect(null, StreamInitializationCause.WatchStarting);
            sequence.ProvideResponse(WatchResponseResult.Continue);
            sequence.ProvideResponse(WatchResponseResult.StreamHealthy, token1);
            sequence.ProvideResponse(WatchResponseResult.StreamHealthy, token2);
            // This exception will cause us to double our backoff.
            // TODO: Timing tests in general.
            sequence.RpcException(new RpcException(new Status(StatusCode.ResourceExhausted, "This exception is transient")));
            // The server throw a retriable exception. Reinitialize.
            sequence.ExpectConnect(token2, StreamInitializationCause.RpcError);
            sequence.ProvideResponse(WatchResponseResult.Continue);
            sequence.WaitForCancellation();

            Task task = sequence.RunToStability();
            sequence.WatchStream.Stop(CancellationToken.None);
            task.Wait();
            sequence.Verify();
        }

        [Fact]
        public void NonRetriableRpcException()
        {
            ByteString token1 = ByteString.CopyFromUtf8("token1");
            ByteString token2 = ByteString.CopyFromUtf8("token2");
            var sequence = new TestSequence();
            sequence.ExpectConnect(null, StreamInitializationCause.WatchStarting);
            sequence.ProvideResponse(WatchResponseResult.Continue);
            sequence.ProvideResponse(WatchResponseResult.StreamHealthy, token1);
            sequence.ProvideResponse(WatchResponseResult.StreamHealthy, token2);
            // This exception is not retriable.
            var exception = new RpcException(new Status(StatusCode.InvalidArgument, "This exception is permanent"));
            sequence.RpcException(exception);

            Task task = sequence.RunToStability();
            Assert.Equal(TaskStatus.Faulted, task.Status);
            Assert.Equal(exception, task.Exception.InnerException);
            sequence.Verify();
        }

        [Fact]
        public void InitialTokenCancellation_WhileRunning()
        {
            var tokenSource = new CancellationTokenSource();
            var sequence = new TestSequence(tokenSource.Token);
            sequence.ExpectConnect(null, StreamInitializationCause.WatchStarting);
            sequence.ProvideResponse(WatchResponseResult.Continue);
            sequence.WaitForCancellation();

            Task task = sequence.RunToStability();
            tokenSource.Cancel();
            // If it doesn't finish quickly, Task.Wait will time out and the assertion will fail.
            Assert.Throws<AggregateException>(() => task.Wait(s_timeout));
            Assert.Equal(TaskStatus.Canceled, task.Status);
        }

        [Fact]
        public void InitialTokenCancellation_WhileServerHanging()
        {
            var tokenSource = new CancellationTokenSource();
            var sequence = new TestSequence(tokenSource.Token);
            sequence.ExpectConnect(null, StreamInitializationCause.WatchStarting);
            sequence.ProvideResponse(WatchResponseResult.Continue);
            sequence.WaitForCancellation();

            Task task = sequence.RunToStability();
            tokenSource.Cancel();
            AssertTaskIsCancelledSoon(task);
            sequence.Verify();
        }

        [Fact]
        public void InitialTokenCancellation_WhileStateMachineHanging()
        {
            var tokenSource = new CancellationTokenSource();
            var sequence = new TestSequence(tokenSource.Token);
            sequence.ExpectConnect(null, StreamInitializationCause.WatchStarting);
            sequence.ProvideResponse(WatchResponseResult.Continue);
            sequence.ProvideResponseHangingInStateMachine();

            Task task = sequence.RunToStability();
            tokenSource.Cancel();
            AssertTaskIsCancelledSoon(task);
            sequence.Verify();
        }

        [Fact]
        public void StopTokenCancellation()
        {
            var sequence = new TestSequence();
            sequence.ExpectConnect(null, StreamInitializationCause.WatchStarting);
            sequence.ProvideResponse(WatchResponseResult.Continue);
            sequence.ProvideResponseHangingInStateMachine();

            Task task = sequence.RunToStability();
            var tokenSource = new CancellationTokenSource();
            sequence.WatchStream.Stop(tokenSource.Token);
            tokenSource.Cancel();
            AssertTaskIsCancelledSoon(task);
            sequence.Verify();
        }

        [Fact]
        public void CreateTarget_Query()
        {
            var client = new FakeFirestoreClient();
            var db = FirestoreDb.Create("project", "db", client);
            var query = db.Collection("col").Limit(10);
            var expected = new Target
            {
                TargetId = WatchStream.WatchTargetId,
                Query = new QueryTarget
                {
                    Parent = db.DocumentsPath,
                    StructuredQuery = new StructuredQuery
                    {
                        From = { new CollectionSelector { CollectionId = "col" } },
                        Limit = 10
                    }
                }
            };
            var actual = WatchStream.CreateTarget(query);
            Assert.Equal(expected, actual);
        }

        [Fact]
        public void CreateTarget_Document()
        {
            var client = new FakeFirestoreClient();
            var db = FirestoreDb.Create("project", "db", client);
            var doc = db.Document("col/doc");
            var expected = new Target
            {
                TargetId = WatchStream.WatchTargetId,
                Documents = new DocumentsTarget { Documents = { doc.Path } }
            };
            var actual = WatchStream.CreateTarget(doc);
            Assert.Equal(expected, actual);
        }

        private void AssertTaskIsCancelledSoon(Task task)
        {
            // If it doesn't finish quickly, Task.Wait will time out and the assertion will fail.
            Assert.Throws<AggregateException>(() => task.Wait(s_timeout));
            Assert.Equal(TaskStatus.Canceled, task.Status);
        }

        /// <summary>
        /// A test sequence, used to set up expectations of how the gRPC stream and the state machine interact.
        /// </summary>
        private class TestSequence
        {
            private readonly List<FakeWatchStream> _streams;
            private readonly FakeFirestoreListenClient _client;
            /// <summary>
            /// This task will complete when either the server or the state machine is deliberately hanging, waiting
            /// for cancellation.
            /// </summary>
            private readonly TaskCompletionSource<int> _completionTaskSource = new TaskCompletionSource<int>();
            private readonly FakeScheduler _scheduler;

            private FakeWatchStream _currentStream;
            private List<Func<ListenResponse>> _currentResponseList;
            private FakeWatchState _watchState;
            private int _responseIndex;

            internal WatchStream WatchStream { get; }

            internal TestSequence(CancellationToken initialCancellationToken = default)
            {
                _streams = new List<FakeWatchStream>();
                _client = new FakeFirestoreListenClient(_streams, "projects/project/databases/db");
                _watchState = new FakeWatchState(TriggerCompletion);
                var db = FirestoreDb.Create("project", "db", _client);
                var target = WatchStream.CreateTarget(db.Document("col/doc"));
                _scheduler = new FakeScheduler();
                WatchStream = new WatchStream(_scheduler, _watchState, target, db, initialCancellationToken);
            }

            /// <summary>
            /// Expect the WatchStream to call the Listen RPC, and then cll OnStreamInitialization with the given cause.
            /// </summary>
            internal void ExpectConnect(ByteString expectedResumeToken, StreamInitializationCause expectedCause)
            {
                _currentResponseList = new List<Func<ListenResponse>>();
                var expectedRequest = WatchStream.CreateRequest(expectedResumeToken);
                _currentStream = new FakeWatchStream(expectedRequest, new FakeResponseList(_currentResponseList, TriggerCompletion));
                _streams.Add(_currentStream);
                _watchState.ExpectInitialization(expectedCause);
            }

            /// <summary>
            /// Causes the fake server to provide a response, which we expect to be passed to the
            /// state machine. The resume token for the state machine is set to <paramref name="resumeToken"/> for
            /// requests which occur after this point.
            /// </summary>
            internal void ProvideResponse(WatchResponseResult result, ByteString resumeToken)
            {
                _watchState.AddResumeToken(_responseIndex, resumeToken);
                ProvideResponse(result);
            }

            /// <summary>
            /// Causes the fake server to provide a response, which we expect to be passed to the
            /// state machine.
            /// </summary>
            internal void ProvideResponse(WatchResponseResult result)
            {
                // The response is opaque to WatchStream, but we want to make sure the state machine gets the
                var response = new ListenResponse { TargetChange = new TargetChange { TargetIds = { _responseIndex++ } } };
                _currentResponseList.Add(() => response);
                _watchState.ExpectResponse(response, result);
            }

            /// <summary>
            /// Causes the fake server to provide a response which is passed to the state machine - which then
            /// hangs (expecting its cancellation token to be cancelled).
            /// </summary>
            internal void ProvideResponseHangingInStateMachine()
            {
                var response = new ListenResponse { TargetChange = new TargetChange { TargetIds = { _responseIndex++ } } };
                _currentResponseList.Add(() => response);
                _watchState.ExpectResponseAndWaitForUserCancellation(response);
            }

            /// <summary>
            /// Causes the fake server to throw the given exception from the gRPC stream.
            /// </summary>
            internal void RpcException(RpcException exception)
            {
                _currentResponseList.Add(() => throw exception);
            }

            /// <summary>
            /// Causes the fake server to effectively wait: the gRPC stream of responses doesn't return another item.
            /// </summary>
            internal void WaitForCancellation()
            {
                _currentResponseList.Add(null);
            }

            private void TriggerCompletion() => _completionTaskSource.SetResult(0);

            /// <summary>
            /// Verifies that all the RPC stream responses and state machine calls have been consumed appropriately.
            /// </summary>
            internal void Verify()
            {
                // Check the state machine had all the expected calls
                _watchState.Verify();
                // Check that all the streams were closed and disposed, with
                _client.Verify();
            }

            /// <summary>
            /// Runs the test sequence until either the fake server is paused, or all its responses have been consumed.
            /// </summary>
            /// <returns>The task from the WatchStream.StartAsync method</returns>
            internal Task RunToStability()
            {
                Task task = null;
                _scheduler.Run(() =>
                {
                    task = WatchStream.StartAsync();
                    // Wait for:
                    // - The server to go into "hanging" mode
                    // - The listening task to complete (e.g. due to an error)
                    // - A timeout (because something is broken)
                    Task.WaitAny(new[] { task, _completionTaskSource.Task }, s_timeout);
                });
                return task;
            }
        }

        private class FakeWatchState : IWatchState
        {
            private List<(int index, ByteString token)> _resumeTokens = new List<(int, ByteString)> { (-1, null) };
            private int _lastSeenIndex = -1;
            // Very primitive mocking; we can't use Moq due to the types being internal.
            private Queue<Delegate> _expectedCalls = new Queue<Delegate>();
            private readonly Action _hangingCallback;

            public ByteString ResumeToken => _resumeTokens.Last(tuple => tuple.index <= _lastSeenIndex).token;

            internal FakeWatchState(Action hangingCallback) => _hangingCallback = hangingCallback;

            public Task<WatchResponseResult> HandleResponseAsync(ListenResponse response, CancellationToken cancellationToken)
            {
                _lastSeenIndex = response.TargetChange.TargetIds[0];
                var call = (Func<ListenResponse, CancellationToken, Task<WatchResponseResult>>) _expectedCalls.Dequeue();
                return call(response, cancellationToken);
            }

            public void OnStreamInitialization(StreamInitializationCause cause)
            {
                var call = (Action<StreamInitializationCause>) _expectedCalls.Dequeue();
                call(cause);
            }

            internal void AddResumeToken(int index, ByteString token) => _resumeTokens.Add((index, token));

            internal void ExpectResponse(ListenResponse expectedResponse, WatchResponseResult result)
            {
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
                Func<ListenResponse, CancellationToken, Task<WatchResponseResult>> call = async (response, _) =>
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
                {
                    Assert.Equal(expectedResponse, response);
                    return result;
                };
                _expectedCalls.Enqueue(call);
            }

            internal void ExpectResponseAndWaitForUserCancellation(ListenResponse expectedResponse)
            {
                Func<ListenResponse, CancellationToken, Task<WatchResponseResult>> call = async (response, cancellationToken) =>
                {
                    Assert.Equal(expectedResponse, response);
                    _hangingCallback();
                    await Task.Delay(s_timeout, cancellationToken).ConfigureAwait(false);
                    throw new InvalidOperationException("Shouldn't get here");
                };
                _expectedCalls.Enqueue(call);
            }

            internal void ExpectInitialization(StreamInitializationCause expectedCause)
            {
                Action<StreamInitializationCause> call = cause => Assert.Equal(expectedCause, cause);
                _expectedCalls.Enqueue(call);
            }

            internal void Verify() => Assert.Empty(_expectedCalls);
        }

        private class FakeFirestoreListenClient : FakeFirestoreClient
        {
            private readonly string _expectedResourceName;
            private readonly List<FakeWatchStream> _streams;
            private int _index;

            internal FakeFirestoreListenClient(List<FakeWatchStream> streams, string expectedResourceName)
            {
                _streams = streams;
                _expectedResourceName = expectedResourceName;
            }

            public override ListenStream Listen(
                CallSettings callSettings = null,
                BidirectionalStreamingSettings streamingSettings = null)
            {
                var metadata = new Metadata();
                callSettings.HeaderMutation?.Invoke(metadata);
                var resourcePrefixHeader = metadata.FirstOrDefault(entry => entry.Key == FirestoreClientImpl.ResourcePrefixHeader);
                Assert.NotNull(resourcePrefixHeader);
                Assert.Equal(_expectedResourceName, resourcePrefixHeader.Value);
                return _streams[_index++];
            }

            internal void Verify()
            {
                // All streams should have been used.
                Assert.Equal(_streams.Count, _index);

                // Each stream should be exhausted.
                for (int i = 0; i < _streams.Count; i++)
                {
                    _streams[i].Verify(i);
                }
            }
        }

        private class FakeResponseList : IAsyncEnumerator<ListenResponse>
        {
            private readonly List<Func<ListenResponse>> _responses;
            private int _index = -1;
            private readonly Action _hangingCallback;

            public ListenResponse Current => _responses[_index].Invoke();

            internal FakeResponseList(List<Func<ListenResponse>> responses, Action hangingCallback)
            {
                _responses = responses;
                _hangingCallback = hangingCallback;
            }

            public void Dispose() { }

            public async Task<bool> MoveNext(CancellationToken cancellationToken)
            {
                cancellationToken.ThrowIfCancellationRequested();
                if (_index < _responses.Count)
                {
                    _index++;
                }
                // We use a null response provider to mean "Wait, we're expecting to be cancelled".
                if (_index < _responses.Count && _responses[_index] == null)
                {
                    _hangingCallback();
                    await Task.Delay(s_timeout, cancellationToken);
                    cancellationToken.ThrowIfCancellationRequested();
                }
                return _index < _responses.Count;
            }

            internal void Verify(int streamIndex)
            {
                // We should either have exhausted the stream or be looking at the last element.
                Assert.True(_index >= _responses.Count - 1, $"streamIndex={streamIndex}; _index = {_index}; Count={_responses.Count}");
            }
        }

        private class FakeWatchStream : ListenStream
        {
            private readonly FakeResponseList _responses;
            private readonly ListenRequest _expectedRequest;
            internal bool Completed { get; private set; }
            internal bool Disposed { get; private set; }
            private bool _requestWritten = false;
            private AsyncDuplexStreamingCall<ListenRequest, ListenResponse> _grpcCall;

            internal FakeWatchStream(ListenRequest expectedRequest, FakeResponseList responses)
            {
                _expectedRequest = expectedRequest;
                _responses = responses;
                // We only use the gRPC call for disposal. This is a bit unpleasant (rather than providing a reader/writer etc) but
                // it's simple and enough for what we need.
                _grpcCall = TestCalls.AsyncDuplexStreamingCall<ListenResponse, ListenRequest>(null, null, null, null, null, () => Disposed = true);
            }

            public override AsyncDuplexStreamingCall<ListenRequest, ListenResponse> GrpcCall => _grpcCall;

            public override IAsyncEnumerator<ListenResponse> ResponseStream => _responses;

            public override Task TryWriteAsync(ListenRequest message, WriteOptions options) =>
                TryWriteAsync(message);

            public override async Task TryWriteAsync(ListenRequest message)
            {
                Assert.False(_requestWritten);
                _requestWritten = true;
                Assert.Equal(_expectedRequest, message);
                await Task.Yield();
            }

            public override async Task TryWriteCompleteAsync()
            {
                Completed = true;
                await Task.Yield();
            }

            public void Verify(int streamIndex)
            {
                Assert.True(_requestWritten);
                Assert.True(Completed);
                Assert.True(Disposed);
                _responses.Verify(streamIndex);
            }
        }
    }
}


text:
require 'spec_helper'

describe Import do
  describe Import::DistrictImporter do
    subject {Import::DistrictImporter.new(xml_fixture('district'), '2012-2013').build_model}

    it 'should load all simple district data correctly' do
      expect(subject).to be_a(District)
      expect(subject.oid).to eq 66
      expect(subject.year).to eq '2012-2013'
      expect(subject.name).to eq 'KL'
    end

    it 'should load club data correctly' do
       expect(subject.clubs).to_not be_empty
       expect(subject.clubs.size).to be 4
    end

    it 'should load office data correctly' do
      expect(subject.offices).to_not be_empty
      expect(subject.offices.size).to be 7
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
$npm init
$npm install --save express bootstrap
$mkdir public
$touch public/index.html public/styles.css
$touch app-server.js //file which we'll use to run server-side node

(in index.html)
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>Live polling</title>
	<link rel="stylesheet" href="/style.css">
	<link rel="stylesheet" href="css/bootstrap.min.css"> //actual path should be this node_modules/bootstrap/dist/css/bootstrap.min.css, but do as give
	//see how we are serving the static files in app-server.js file

 LIVE POLLING, VIKI! :)

(in app-server.js)
var express = require('express');

var app = express();

//creating a static file server which does the client side and boostrap file!
app.use(express.static('./public'));
app.use(express.static('./node_modules/bootstrap/dist'));

app.listen(3000);
console.log("iit, polling server is running! :)")


text:
/**
 * @license Angulartics v0.17.2
 * (c) 2013 Luis Farzati http://luisfarzati.github.io/angulartics
 * Contributed by Jakub Hampl http://gampleman.eu
 * License: MIT
 */
(function(angular) {
'use strict';

/**
 * @ngdoc overview
 * @name angulartics.newrelic.insights
 * Enables analytics support for New Relic Insights
 */
angular.module('angulartics.newrelic.insights', ['angulartics'])
.config(['$analyticsProvider', function ($analyticsProvider) {
  angulartics.waitForVendorApi('newrelic', 100, function(newrelic) {
    $analyticsProvider.registerEventTrack(function(action, properties) {
      newrelic.addPageAction(action, properties);
    });
    $analyticsProvider.registerSetUsername(function(name) {
      newrelic.setCustomAttribute('username', name);
    });
    $analyticsProvider.registerSetAlias(function(name) {
      newrelic.setCustomAttribute('alias', name);
    });
    $analyticsProvider.registerSetUserProperties(function(properties) {
      angular.forEach(properties, function(value, key) {
        newrelic.setCustomAttribute(key, value);
      });
    });
  });
}]);
})(angular);


text:
from django.http import HttpResponse
from lingcod.features.views import get_object_for_viewing
from lingcod.analysistools.models import Analysis
from lingcod.common import default_mimetypes as mimetypes
from django.utils import simplejson
from django.shortcuts import render_to_response

def progress(request, uid):
    instance = get_object_for_viewing(request, uid)
    if isinstance(instance, HttpResponse):
        return instance

    if issubclass(instance.__class__, Analysis):
        p = instance.progress
        progress = {
            'complete': p[0],
            'total': p[1],
            'html': instance.status_html,
            'error': 0
        }
        if 'error' in instance.status_html.lower():
            progress['error'] = 1
        res = HttpResponse(simplejson.dumps(progress))
        res['Content-Type'] = mimetypes.JSON
        return res

    return HttpResponse("%s is not an analysis!" % (instance), status=500)

def progress_html(request, uid):
    instance = get_object_for_viewing(request, uid)
    if isinstance(instance, HttpResponse):
        return instance

    if issubclass(instance.__class__, Analysis):
        p = instance.progress
        progress = {
            'complete': p[0],
            'total': p[1],
            'done': p[1] == p[0],
            'uid': instance.uid,
            'name': instance.name,
            'html': instance.status_html
        }
        return render_to_response('analysis/progress.html', {'progress': progress})

    return HttpResponse("%s is not an analysis!" % (instance), status=500)


text:
#include <aws/iam/model/GetContextKeysForPrincipalPolicyResult.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/logging/LogMacros.h>

#include <utility>

using namespace Aws::IAM::Model;
using namespace Aws::Utils::Xml;
using namespace Aws::Utils::Logging;
using namespace Aws::Utils;
using namespace Aws;

GetContextKeysForPrincipalPolicyResult::GetContextKeysForPrincipalPolicyResult()
{
}

GetContextKeysForPrincipalPolicyResult::GetContextKeysForPrincipalPolicyResult(const Aws::AmazonWebServiceResult<XmlDocument>& result)
{
  *this = result;
}

GetContextKeysForPrincipalPolicyResult& GetContextKeysForPrincipalPolicyResult::operator =(const Aws::AmazonWebServiceResult<XmlDocument>& result)
{
  const XmlDocument& xmlDocument = result.GetPayload();
  XmlNode rootNode = xmlDocument.GetRootElement();
  XmlNode resultNode = rootNode;
  if (!rootNode.IsNull() && (rootNode.GetName() != "GetContextKeysForPrincipalPolicyResult"))
  {
    resultNode = rootNode.FirstChild("GetContextKeysForPrincipalPolicyResult");
  }

  if(!resultNode.IsNull())
  {
    XmlNode contextKeyNamesNode = resultNode.FirstChild("ContextKeyNames");
    if(!contextKeyNamesNode.IsNull())
    {
      XmlNode contextKeyNamesMember = contextKeyNamesNode.FirstChild("member");
      while(!contextKeyNamesMember.IsNull())
      {
        m_contextKeyNames.push_back(contextKeyNamesMember.GetText());
        contextKeyNamesMember = contextKeyNamesMember.NextNode("member");
      }

    }
  }

  if (!rootNode.IsNull()) {
    XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata");
    m_responseMetadata = responseMetadataNode;
    AWS_LOGSTREAM_DEBUG("Aws::IAM::Model::GetContextKeysForPrincipalPolicyResult", "x-amzn-request-id: " << m_responseMetadata.GetRequestId() );
  }
  return *this;
}


text:
module Refinery
  module Pages
    class Finder
      def self.by_path(path)
        FinderByPath.new(path).find
      end

      def self.by_path_or_id(path, id)
        FinderByPathOrId.new(path, id).find
      end

      def self.by_title(title)
        FinderByTitle.new(title).find
      end

      def self.by_slug(slug, conditions = {})
        FinderBySlug.new(slug, conditions).find
      end

      def self.with_globalize(conditions = {})
        Finder.new(conditions).find
      end

      def initialize(conditions)
        @conditions = conditions
      end

      def find
        with_globalize
      end

      def with_globalize
        globalized_conditions = {:locale => ::Globalize.locale.to_s}.merge(conditions)
        translations_conditions = translations_conditions(globalized_conditions)

        # A join implies readonly which we don't really want.
        Page.where(globalized_conditions).
             joins(:translations).
             where(translations_conditions).
             readonly(false)
      end

      private
      attr_accessor :conditions

      def translated_attributes
        Page.translated_attribute_names.map(&:to_s) | %w(locale)
      end

      def translations_conditions(original_conditions)
        translations_conditions = {}
        original_conditions.keys.each do |key|
          if translated_attributes.include? key.to_s
            translations_conditions["#{Page.translation_class.table_name}.#{key}"] = original_conditions.delete(key)
          end
        end
        translations_conditions
      end

    end

    class FinderByTitle < Finder
      def initialize(title)
        @title = title
        @conditions = default_conditions
      end

      def default_conditions
        { :title => title }
      end

      private
      attr_accessor :title
    end

    class FinderBySlug < Finder
      def initialize(slug, conditions)
        @slug = slug
        @conditions = default_conditions.merge(conditions)
      end

      def default_conditions
        {
          :locale => Refinery::I18n.frontend_locales.map(&:to_s),
          :slug => slug
        }
      end

      private
      attr_accessor :slug
    end

    class FinderByPath
      def initialize(path)
        @path = path
      end

      def find
        if slugs_scoped_by_parent?
          FinderByScopedPath.new(path).find
        else
          FinderByUnscopedPath.new(path).find
        end
      end

      private
      attr_accessor :path

      def slugs_scoped_by_parent?
        ::Refinery::Pages.scope_slug_by_parent
      end

      def by_slug(slug_path, conditions = {})
        Finder.by_slug(slug_path, conditions)
      end
    end

    class FinderByScopedPath < FinderByPath
      def find
        # With slugs scoped to the parent page we need to find a page by its full path.
        # For example with about/example we would need to find 'about' and then its child
        # called 'example' otherwise it may clash with another page called /example.
        page = parent_page
        while page && path_segments.any? do
          page = next_page(page)
        end
        page
      end

      private

      def path_segments
        @path_segments ||= path.split('/').select(&:present?)
      end

      def parent_page
        by_slug(path_segments.shift, :parent_id => nil).first
      end

      def next_page(page)
        slug_or_id = path_segments.shift
        page.children.by_slug(slug_or_id).first || page.children.find(slug_or_id)
      end
    end

    class FinderByUnscopedPath < FinderByPath
      def find
        by_slug(path).first
      end
    end

    class FinderByPathOrId
      def initialize(path, id)
        @path = path
        @id = id
      end

      def find
        if path.present?
          if path.friendly_id?
            Page.friendly.find_by_path(path)
          else
            Page.friendly.find(path)
          end
        elsif id.present?
          Page.friendly.find(id)
        end
      end

      private
      attr_accessor :id, :path
    end
  end
end


text:
package com.example.pac.pacman.event;

public interface IEventManager {
    <T> void registerObserver(Class<T> event, EventListener<?> listener);

    <T> void unregisterObserver(Class<T> event, EventListener<T> listener);

    @SuppressWarnings("unchecked")
    void fire(Object event);
    void fire(Object event, long delay);

    void unregisterAll();
}


text:
<?php
/**
 * @package sapphire
 * @subpackage tests
 */
class EncryptAllPasswordsTaskTest extends SapphireTest {
	function testRun() {
		$m = new Member();
		$m->Password = 'plain';
		$m->PasswordEncryption = 'none';
		$m->write();

		$t = new EncryptAllPasswordsTask();
		$t->run(null);

		$m = DataObject::get_by_id('Member', $m->ID);
		$this->assertEquals($m->PasswordEncryption, 'sha1_v2.4');
		$this->assertNotEquals($m->Password, 'plain');
		$result = $m->checkPassword('plain');
		$this->assertTrue($result->valid());
	}
}


text:
package com.datastax.spark.connector.rdd.partitioner

import scala.collection.JavaConversions._

import org.apache.spark.Logging

import com.datastax.driver.core.exceptions.InvalidQueryException
import com.datastax.spark.connector.cql.CassandraConnector
import com.datastax.spark.connector.rdd.partitioner.dht.{TokenFactory, Token}

/** Estimates amount of data in the Cassandra table.
  * Takes token range size estimates from the `system.size_estimates` table,
  * available since Cassandra 2.1.5. */
class DataSizeEstimates[V, T <: Token[V]](
    conn: CassandraConnector,
    keyspaceName: String,
    tableName: String)(
  implicit
    tokenFactory: TokenFactory[V, T])
  extends Logging {

  /** Represents a single `system.size_estimates` table row */
  private case class TokenRangeSizeEstimate(
      rangeStart: T,
      rangeEnd: T,
      partitionsCount: Long,
      meanPartitionSize: Long) {

    def ringFraction: Double =
      tokenFactory.ringFraction(rangeStart, rangeEnd)

    def totalSizeInBytes: Long =
      partitionsCount * meanPartitionSize
  }

  private lazy val tokenRanges: Seq[TokenRangeSizeEstimate] =
    conn.withSessionDo { session =>
      try {
        val rs = session.execute(
          "SELECT range_start, range_end, partitions_count, mean_partition_size " +
            "FROM system.size_estimates " +
            "WHERE keyspace_name = ? AND table_name = ?", keyspaceName, tableName)

        for (row <- rs.all()) yield TokenRangeSizeEstimate(
          rangeStart = tokenFactory.tokenFromString(row.getString("range_start")),
          rangeEnd = tokenFactory.tokenFromString(row.getString("range_end")),
          partitionsCount = row.getLong("partitions_count"),
          meanPartitionSize = row.getLong("mean_partition_size")
        )

        // The table may not contain the estimates yet if the data was just inserted and the
        // amount of data in the table was small. This is very common situation during tests,
        // when we insert a few rows and immediately query them. However, for tiny data sets the lack
        // of size estimates is not a problem at all, because we don't want to split tiny data anyways.
        // Therefore, we're not issuing a warning if the result set was empty.
      }
      catch {
        case e: InvalidQueryException =>
          logError(
            s"Failed to fetch size estimates for $keyspaceName.$tableName from system.size_estimates " +
              s"table. The number of created Spark partitions may be inaccurate. " +
              s"Please make sure you use Cassandra 2.1.5 or newer.", e)
          Seq.empty
      }
    }

  private lazy val ringFraction =
    tokenRanges.map(_.ringFraction).sum

  /** Estimates the total number of partitions in a ring */
  lazy val partitionCount: Long = {
    val partitionsCount = tokenRanges.map(_.partitionsCount).sum
    val normalizedCount = (partitionsCount / ringFraction).toLong
    logDebug(s"Estimated partition count of $keyspaceName.$tableName is $normalizedCount")
    normalizedCount
  }

  /** Estimates the total amount of data in a table assuming no replication. */
  lazy val dataSizeInBytes: Long = {
    val tokenRangeSizeInBytes = (totalDataSizeInBytes / ringFraction).toLong
    logDebug(s"Estimated size of $keyspaceName.$tableName is $tokenRangeSizeInBytes bytes")
    tokenRangeSizeInBytes
  }

  /** Estimates the total amount of data in a table without normalization assuming no replication. */
  lazy val totalDataSizeInBytes: Long = {
    tokenRanges.map(_.totalSizeInBytes).sum
  }
}

object DataSizeEstimates {

  /** Waits until data size estimates are present in the system.size_estimates table.
    * Returns true if size estimates were written, returns false if timeout was reached
    * while waiting */
  def waitForDataSizeEstimates(
    conn: CassandraConnector,
    keyspaceName: String,
    tableName: String,
    timeoutInMs: Int): Boolean = {

    conn.withSessionDo { session =>
      def hasSizeEstimates: Boolean = {
        session.execute(
          s"SELECT * FROM system.size_estimates " +
            s"WHERE keyspace_name = '$keyspaceName' AND table_name = '$tableName'").all().nonEmpty
      }

      val startTime = System.currentTimeMillis()
      while (!hasSizeEstimates && System.currentTimeMillis() < startTime + timeoutInMs)
        Thread.sleep(1000)

      hasSizeEstimates
    }
  }
}


text:
import assert from '../utils/assert';

export default class AtomNode {
  constructor(editor, atom, model, element, atomOptions) {
    this.editor = editor;
    this.atom = atom;
    this.model = model;
    this.atomOptions = atomOptions;
    this.element = element;

    this._teardownCallback = null;
    this._rendered         = null;
  }

  render() {
    if (!this._rendered) {
      let {atomOptions: options, env, model: { value, payload } } = this;
      // cache initial render
      this._rendered = this.atom.render({options, env, value, payload});
    }

    this._validateAndAppendRenderResult(this._rendered);
  }

  get env() {
    return {
      name: this.atom.name,
      onTeardown: (callback) => this._teardownCallback = callback,
      save: (value, payload={}) => {
        this.model.value = value;
        this.model.payload = payload;

        this.editor._postDidChange();
        this.teardown();
        this.render();
      }
    };
  }

  teardown() {
    if (this._teardownCallback) {
      this._teardownCallback();
      this._teardownCallback = null;
    }
    if (this._rendered) {
      this.element.removeChild(this._rendered);
      this._rendered = null;
    }
  }

  _validateAndAppendRenderResult(rendered) {
    if (!rendered) {
      return;
    }

    let { atom: { name } } = this;
    assert(
      `Atom "${name}" must return a DOM node (returned value was: "${rendered}")`,
      !!rendered.nodeType
    );
    this.element.appendChild(rendered);
  }
}


text:
<!DOCTYPE html>

  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <title>Google Cloud DataLab</title>
  <link rel="shortcut icon" type="image/x-icon" href="<%baseUrl%>static/favicon.ico">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <link rel="stylesheet" href="<%baseUrl%>static/components/codemirror/lib/codemirror.css" />
  <link rel="stylesheet" href="<%baseUrl%>static/style/style.min.css" type="text/css" />
  <link rel="stylesheet" href="<%baseUrl%>static/fonts/fonts.css" type="text/css" />
  <link rel="stylesheet" href="<%baseUrl%>static/style/datalab.css" type="text/css" />
  <link rel="stylesheet" id="themeStylesheet" href="<%baseUrl%>static/style/custom.css" type="text/css" />

<body class="session_list"
  data-base-url="<%baseUrl%>"
  data-notebook-path="/"
  data-terminals-available="True"
  data-feedback-id="<%feedbackId%>"
  data-version-id="<%versionId%>"
  data-signed-in="<%isSignedIn%>"
  data-user-id="<%userId%>"
  data-account="<%account%>">

                        Active Notebooks

There are no notebooks running.

                        Active Terminals

There are no terminals running.


text:
import io
import os
import sys
from shutil import rmtree

from setuptools import find_packages, setup, Command

here = os.path.abspath(os.path.dirname(__file__))

# Import the README and use it as the long-description.
# Note: this will only work if 'README.rst' is present in your MANIFEST.in file!
with io.open(os.path.join(here, 'README.rst'), encoding='utf-8') as f:
    long_description = '\n' + f.read()

version = os.path.join(here, 'falcon_dbapi', '__init__.py')
about = {}
with open(version, 'r') as f:
    exec(f.read(), about)

class UploadCommand(Command):
    """Support setup.py upload."""

    description = 'Build and publish the package.'
    user_options = []

    @staticmethod
    def status(s):
        """Prints things in bold."""
        print('\033[1m{0}\033[0m'.format(s))

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
        try:
            self.status('Removing previous builds…')
            rmtree(os.path.join(here, 'dist'))
        except OSError:
            pass

        self.status('Building Source and Wheel (universal) distribution…')
        os.system('{0} setup.py sdist bdist_wheel --universal'.format(sys.executable))

        self.status('Uploading the package to PyPi via Twine…')
        os.system('twine upload dist/*')

        sys.exit()

setup(
    name=about['__title__'],
    version=about['__version__'],
    description='Falcon API resources for databases',
    long_description=long_description,
    author='Jan Waś',
    author_email='jan.was@opentopic.com',
    url='https://github.com/opentopic/falcon-api',
    platforms=['OS Independent'],
    packages=find_packages(exclude=('tests',)),
    install_requires=[
        'falcon>=1.3.0',
    ],
    include_package_data=True,
    license='MIT',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
    ],
    setup_requires=[
        'pytest-runner',
        'recommonmark',
    ],
    tests_require=[
        'pytest',
        'mongoengine==0.10.6',
        'SQLAlchemy>=1.0.12',
        'alchemyjsonschema>=0.4.2',
        'elasticsearch-dsl==2.1.0',
        'elasticsearch==2.3.0'
    ],
    # $ setup.py publish support.
    cmdclass={
        'upload': UploadCommand,
    },
)


text:
import $ from "jquery";

import render_compose_all_everyone from "../templates/compose_all_everyone.hbs";
import render_compose_announce from "../templates/compose_announce.hbs";
import render_compose_not_subscribed from "../templates/compose_not_subscribed.hbs";

import * as channel from "./channel";
import * as compose_error from "./compose_error";
import * as compose_pm_pill from "./compose_pm_pill";
import * as compose_state from "./compose_state";
import {$t_html} from "./i18n";
import {page_params} from "./page_params";
import * as peer_data from "./peer_data";
import * as people from "./people";
import * as settings_config from "./settings_config";
import * as stream_data from "./stream_data";
import * as util from "./util";

let user_acknowledged_all_everyone = false;
let user_acknowledged_announce = false;
let wildcard_mention;

export const announce_warn_threshold = 60;
export let wildcard_mention_large_stream_threshold = 15;

function show_all_everyone_warnings(stream_id) {
    const stream_count = peer_data.get_subscriber_count(stream_id) || 0;

    const all_everyone_template = render_compose_all_everyone({
        count: stream_count,
        mention: wildcard_mention,
    });
    const error_area_all_everyone = $("#compose-all-everyone");

    // only show one error for any number of @all or @everyone mentions
    if (!error_area_all_everyone.is(":visible")) {
        error_area_all_everyone.append(all_everyone_template);
    }

    error_area_all_everyone.show();
    user_acknowledged_all_everyone = false;
}

export function clear_all_everyone_warnings() {
    $("#compose-all-everyone").hide();
    $("#compose-all-everyone").empty();
    $("#compose-send-status").hide();
}

function show_announce_warnings(stream_id) {
    const stream_count = peer_data.get_subscriber_count(stream_id) || 0;

    const announce_template = render_compose_announce({count: stream_count});
    const error_area_announce = $("#compose-announce");

    if (!error_area_announce.is(":visible")) {
        error_area_announce.append(announce_template);
    }

    error_area_announce.show();
    user_acknowledged_announce = false;
}

export function clear_announce_warnings() {
    $("#compose-announce").hide();
    $("#compose-announce").empty();
    $("#compose-send-status").hide();
}

export function set_user_acknowledged_all_everyone_flag(value) {
    user_acknowledged_all_everyone = value;
}

export function set_user_acknowledged_announce_flag(value) {
    user_acknowledged_announce = value;
}

export function get_invalid_recipient_emails() {
    const private_recipients = util.extract_pm_recipients(
        compose_state.private_message_recipient(),
    );
    const invalid_recipients = private_recipients.filter(
        (email) => !people.is_valid_email_for_compose(email),
    );

    return invalid_recipients;
}

function check_unsubscribed_stream_for_send(stream_name, autosubscribe) {
    let result;
    if (!autosubscribe) {
        return "not-subscribed";
    }

    // In the rare circumstance of the autosubscribe option, we
    // *Synchronously* try to subscribe to the stream before sending
    // the message.  This is deprecated and we hope to remove it; see
    // #4650.
    channel.post({
        url: "/json/subscriptions/exists",
        data: {stream: stream_name, autosubscribe: true},
        async: false,
        success(data) {
            if (data.subscribed) {
                result = "subscribed";
            } else {
                result = "not-subscribed";
            }
        },
        error(xhr) {
            if (xhr.status === 404) {
                result = "does-not-exist";
            } else {
                result = "error";
            }
        },
    });
    return result;
}

export function wildcard_mention_allowed() {
    if (
        page_params.realm_wildcard_mention_policy ===
        settings_config.wildcard_mention_policy_values.by_everyone.code
    ) {
        return true;
    }
    if (
        page_params.realm_wildcard_mention_policy ===
        settings_config.wildcard_mention_policy_values.nobody.code
    ) {
        return false;
    }
    if (
        page_params.realm_wildcard_mention_policy ===
        settings_config.wildcard_mention_policy_values.by_stream_admins_only.code
    ) {
        // TODO: Check the user's stream-level role once stream-level admins exist.
        return page_params.is_admin;
    }

    if (
        page_params.realm_wildcard_mention_policy ===
        settings_config.wildcard_mention_policy_values.by_moderators_only.code
    ) {
        return page_params.is_admin || page_params.is_moderator;
    }
    // TODO: Uncomment when we add support for stream-level administrators.
    // if (
    //     page_params.realm_wildcard_mention_policy ===
    //     settings_config.wildcard_mention_policy_values.by_admins_only.code
    // ) {
    //     return page_params.is_admin;
    // }
    if (
        page_params.realm_wildcard_mention_policy ===
        settings_config.wildcard_mention_policy_values.by_full_members.code
    ) {
        if (page_params.is_admin) {
            return true;
        }
        const person = people.get_by_user_id(page_params.user_id);
        const current_datetime = new Date(Date.now());
        const person_date_joined = new Date(person.date_joined);
        const days = (current_datetime - person_date_joined) / 1000 / 86400;

        return days >= page_params.realm_waiting_period_threshold && !page_params.is_guest;
    }
    return !page_params.is_guest;
}

export function set_wildcard_mention_large_stream_threshold(value) {
    wildcard_mention_large_stream_threshold = value;
}

function validate_stream_message_mentions(stream_id) {
    const stream_count = peer_data.get_subscriber_count(stream_id) || 0;

    // If the user is attempting to do a wildcard mention in a large
    // stream, check if they permission to do so.
    if (wildcard_mention !== null && stream_count > wildcard_mention_large_stream_threshold) {
        if (!wildcard_mention_allowed()) {
            compose_error.show(
                $t_html({
                    defaultMessage:
                        "You do not have permission to use wildcard mentions in this stream.",
                }),
            );
            return false;
        }

        if (
            user_acknowledged_all_everyone === undefined ||
            user_acknowledged_all_everyone === false
        ) {
            // user has not seen a warning message yet if undefined
            show_all_everyone_warnings(stream_id);

            $("#compose-send-button").prop("disabled", false);
            $("#sending-indicator").hide();
            return false;
        }
    } else {
        // the message no longer contains @all or @everyone
        clear_all_everyone_warnings();
    }
    // at this point, the user has either acknowledged the warning or removed @all / @everyone
    user_acknowledged_all_everyone = undefined;

    return true;
}

function validate_stream_message_announce(sub) {
    const stream_count = peer_data.get_subscriber_count(sub.stream_id) || 0;

    if (sub.name === "announce" && stream_count > announce_warn_threshold) {
        if (user_acknowledged_announce === undefined || user_acknowledged_announce === false) {
            // user has not seen a warning message yet if undefined
            show_announce_warnings(sub.stream_id);

            $("#compose-send-button").prop("disabled", false);
            $("#sending-indicator").hide();
            return false;
        }
    } else {
        clear_announce_warnings();
    }
    // at this point, the user has acknowledged the warning
    user_acknowledged_announce = undefined;

    return true;
}

function validate_stream_message_post_policy(sub) {
    if (page_params.is_admin) {
        return true;
    }

    const stream_post_permission_type = stream_data.stream_post_policy_values;
    const stream_post_policy = sub.stream_post_policy;

    if (stream_post_policy === stream_post_permission_type.admins.code) {
        compose_error.show(
            $t_html({
                defaultMessage: "Only organization admins are allowed to post to this stream.",
            }),
        );
        return false;
    }

    if (page_params.is_moderator) {
        return true;
    }

    if (stream_post_policy === stream_post_permission_type.moderators.code) {
        compose_error.show(
            $t_html({
                defaultMessage:
                    "Only organization admins and moderators are allowed to post to this stream.",
            }),
        );
        return false;
    }

    if (page_params.is_guest && stream_post_policy !== stream_post_permission_type.everyone.code) {
        compose_error.show(
            $t_html({defaultMessage: "Guests are not allowed to post to this stream."}),
        );
        return false;
    }

    const person = people.get_by_user_id(page_params.user_id);
    const current_datetime = new Date(Date.now());
    const person_date_joined = new Date(person.date_joined);
    const days = (current_datetime - person_date_joined) / 1000 / 86400;
    let error_html;
    if (
        stream_post_policy === stream_post_permission_type.non_new_members.code &&
        days < page_params.realm_waiting_period_threshold
    ) {
        error_html = $t_html(
            {
                defaultMessage:
                    "New members are not allowed to post to this stream.
Permission will be granted in {days} days.",
            },
            {days},
        );
        compose_error.show(error_html);
        return false;
    }
    return true;
}

export function validation_error(error_type, stream_name) {
    let response;

    switch (error_type) {
        case "does-not-exist":
            response = $t_html(
                {
                    defaultMessage:
                        "
The stream {stream_name} does not exist.

Manage your subscriptions <z-link>on your Streams page</z-link>.
",
                },
                {
                    stream_name,
                    "z-link": (content_html) => `<a href='#streams/all'>${content_html}</a>`,
                },
            );
            compose_error.show(response, $("#stream_message_recipient_stream"));
            return false;
        case "error":
            compose_error.show(
                $t_html({defaultMessage: "Error checking subscription"}),
                $("#stream_message_recipient_stream"),
            );
            return false;
        case "not-subscribed": {
            const sub = stream_data.get_sub(stream_name);
            const new_row = render_compose_not_subscribed({
                should_display_sub_button: stream_data.can_toggle_subscription(sub),
            });
            compose_error.show_not_subscribed(new_row, $("#stream_message_recipient_stream"));
            return false;
        }
    }
    return true;
}

export function validate_stream_message_address_info(stream_name) {
    if (stream_data.is_subscribed(stream_name)) {
        return true;
    }
    const autosubscribe = page_params.narrow_stream !== undefined;
    const error_type = check_unsubscribed_stream_for_send(stream_name, autosubscribe);
    return validation_error(error_type, stream_name);
}

function validate_stream_message() {
    const stream_name = compose_state.stream_name();
    if (stream_name === "") {
        compose_error.show(
            $t_html({defaultMessage: "Please specify a stream"}),
            $("#stream_message_recipient_stream"),
        );
        return false;
    }

    if (page_params.realm_mandatory_topics) {
        const topic = compose_state.topic();
        if (topic === "") {
            compose_error.show(
                $t_html({defaultMessage: "Please specify a topic"}),
                $("#stream_message_recipient_topic"),
            );
            return false;
        }
    }

    const sub = stream_data.get_sub(stream_name);
    if (!sub) {
        return validation_error("does-not-exist", stream_name);
    }

    if (!validate_stream_message_post_policy(sub)) {
        return false;
    }

    /* Note: This is a global and thus accessible in the functions
       below; it's important that we update this state here before
       proceeding with further validation. */
    wildcard_mention = util.find_wildcard_mentions(compose_state.message_content());

    // If both `@all` is mentioned and it's in `#announce`, just validate
    // for `@all`. Users shouldn't have to hit "yes" more than once.
    if (wildcard_mention !== null && stream_name === "announce") {
        if (
            !validate_stream_message_address_info(stream_name) ||
            !validate_stream_message_mentions(sub.stream_id)
        ) {
            return false;
        }
        // If either criteria isn't met, just do the normal validation.
    } else {
        if (
            !validate_stream_message_address_info(stream_name) ||
            !validate_stream_message_mentions(sub.stream_id) ||
            !validate_stream_message_announce(sub)
        ) {
            return false;
        }
    }

    return true;
}

// The function checks whether the recipients are users of the realm or cross realm users (bots
// for now)
function validate_private_message() {
    const user_ids = compose_pm_pill.get_user_ids();

    if (
        page_params.realm_private_message_policy === 2 && // Frontend check for for PRIVATE_MESSAGE_POLICY_DISABLED
        (user_ids.length !== 1 || !people.get_by_user_id(user_ids[0]).is_bot)
    ) {
        // Unless we're composing to a bot
        compose_error.show(
            $t_html({defaultMessage: "Private messages are disabled in this organization."}),
            $("#private_message_recipient"),
        );
        return false;
    }

    if (compose_state.private_message_recipient().length === 0) {
        compose_error.show(
            $t_html({defaultMessage: "Please specify at least one valid recipient"}),
            $("#private_message_recipient"),
        );
        return false;
    } else if (page_params.realm_is_zephyr_mirror_realm) {
        // For Zephyr mirroring realms, the frontend doesn't know which users exist
        return true;
    }

    const invalid_recipients = get_invalid_recipient_emails();

    let context = {};
    if (invalid_recipients.length === 1) {
        context = {recipient: invalid_recipients.join(",")};
        compose_error.show(
            $t_html({defaultMessage: "The recipient {recipient} is not valid"}, context),
            $("#private_message_recipient"),
        );
        return false;
    } else if (invalid_recipients.length > 1) {
        context = {recipients: invalid_recipients.join(",")};
        compose_error.show(
            $t_html({defaultMessage: "The recipients {recipients} are not valid"}, context),
            $("#private_message_recipient"),
        );
        return false;
    }

    for (const user_id of user_ids) {
        if (!people.is_person_active(user_id)) {
            context = {full_name: people.get_by_user_id(user_id).full_name};
            compose_error.show(
                $t_html(
                    {defaultMessage: "You cannot send messages to deactivated users."},
                    context,
                ),
                $("#private_message_recipient"),
            );

            return false;
        }
    }

    return true;
}

export function check_overflow_text() {
    const text = compose_state.message_content();
    const max_length = page_params.max_message_length;
    const indicator = $("#compose_limit_indicator");

    if (text.length > max_length) {
        indicator.addClass("over_limit");
        $("#compose-textarea").addClass("over_limit");
        indicator.text(text.length + "/" + max_length);
        compose_error.show(
            $t_html(
                {
                    defaultMessage:
                        "Message length should'nt be greatar than {max_length} characters.",
                },
                {max_length},
            ),
        );
        $("#compose-send-button").prop("disabled", true);
    } else if (text.length > 0.9 * max_length) {
        indicator.removeClass("over_limit");
        $("#compose-textarea").removeClass("over_limit");
        indicator.text(text.length + "/" + max_length);

        $("#compose-send-button").prop("disabled", false);
        if ($("#compose-send-status").hasClass("alert-error")) {
            $("#compose-send-status").stop(true).fadeOut();
        }
    } else {
        indicator.text("");
        $("#compose-textarea").removeClass("over_limit");

        $("#compose-send-button").prop("disabled", false);
        if ($("#compose-send-status").hasClass("alert-error")) {
            $("#compose-send-status").stop(true).fadeOut();
        }
    }
}

export function warn_for_text_overflow_when_tries_to_send() {
    if (compose_state.message_content().length > page_params.max_message_length) {
        $("#compose-textarea").addClass("flash");
        setTimeout(() => $("#compose-textarea").removeClass("flash"), 1500);
        return false;
    }
    return true;
}

export function validate() {
    const message_content = compose_state.message_content();
    if (/^\s*$/.test(message_content)) {
        // Avoid showing an error message when "enter sends" is enabled,
        // as it is more likely that the user has hit "Enter" accidentally.
        if (!page_params.enter_sends) {
            compose_error.show(
                $t_html({defaultMessage: "You have nothing to send!"}),
                $("#compose-textarea"),
            );
        }
        return false;
    }

    if ($("#zephyr-mirror-error").is(":visible")) {
        compose_error.show(
            $t_html({
                defaultMessage:
                    "You need to be running Zephyr mirroring in order to send messages!",
            }),
        );
        return false;
    }
    if (!warn_for_text_overflow_when_tries_to_send()) {
        return false;
    }

    if (compose_state.get_message_type() === "private") {
        return validate_private_message();
    }
    return validate_stream_message();
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Fl. Boreali-Americ. 324 (1820)

#### Original name
Lobaria quercizans var. quercizans

### Remarks
null


text:
package org.apache.wsrp4j.persistence.xml;

import org.apache.wsrp4j.commons.persistence.PersistentInformation;

/**
 * This class defines the interface for persistent information needed
 * to store and retrieve PersistentDataObjects with castor XML support.
 *
 * @version $Id: PersistentInformationXML.java 374672 2006-02-03 14:10:58Z cziegeler $
 */
public interface PersistentInformationXML extends PersistentInformation {

    /**
     * Set the Store directory for the persistent XML files
     *
     * @param storeDirectory String name of the store
     */
    void setStoreDirectory(String storeDirectory);

    /**
     * Returns the directory for the persistent XML files
     *
     * @return String nanme of the store
     */
    String getStoreDirectory();

    /**
     * Set the Castor XML mapping file name, fully qualified
     *
     * @param mappingFileName String fully qualified filename
     */
    void setMappingFileName(String mappingFileName);

    /**
     * Returns the XML mapping file name, fully qualified
     *
     * @return String fully qualified filename
     */
    String getMappingFileName();

    /**
     * Set the file name stub for persistent XML files. The name contains the
     * store directory followed by a file separator and the class name of the
     * object to be restored.
     *
     * @param stub String file name stub
     */
    void setFilenameStub(String stub);

    /**
     * Returns the file name stub for persistent XML files. @see setFilenameStub
     *
     * @return String file name stub
     */
    String getFilenameStub();

    /**
     * Returns a fully qualified file name for a persistent XML file.
     *
     * @return String file name
     */
    String getFilename();

    /**
     *  Set the fully qualified file name for a persistent XML file.
     *
     * @param filename String file name
     */
    void setFilename(String filename);

    /**
     * Updates the file name, enhanced by a string token, like a handle to
     * idportlet a unique persistent XML file. If a groupID is set, the
     * groupID is used instead of the token to build the filename.
     *
     * @param token String token, like a handle
     */
    void updateFileName(String token);

    /**
     * Returns the file extension used for persistent XML files
     */
    String getExtension();

    /**
     * Set the file extension for persistent XML files.
     *
     * @param extension String file extension
     */
    void setExtension(String extension);

    /**
     * Set the Separator, to be used in a fully qualified file name.
     *
     * @return String Separator character
     */
    String getSeparator();

    /**
     * Set the separator character. (e.g. '@')
     *
     * @param separator String Separator character
     */
    void setSeparator(String separator);

    /**
     * @return this object as String
     */
    String toString();

}


text:
The experimentation repository for building [LambdaCube](http://lambdacube3d.com) example with `stack` using single command:

```
stack install
```

And next you can call `lambdacube-test` from repository root directory:

```
lambdacube-test
```


text:
'''
Frontend module
'''

__all__ = ('frontend', )

from flask import Blueprint, render_template, url_for, redirect, abort, \
    send_file, request, make_response, jsonify
from web.job import read_job, read_logs, JobObj
from werkzeug import secure_filename
from web.config import qjob, r
from os.path import exists
from uuid import uuid4
import subprocess
import re

from time import time
from os import mkdir
from os.path import join, splitext
from flaskext.wtf import Form, TextField, SubmitField, validators, \
    FileField, SelectField, BooleanField

frontend = Blueprint('frontend', __name__, static_folder='static',
        static_url_path='/frontend/static', template_folder='templates')

class JobForm(Form):
    package_name = TextField('Package', [
        validators.Required(), validators.Length(min=3, max=128)],
        description='org.kivy.touchtracer')
    package_version = TextField('Version', [
        validators.Required(), validators.Length(min=1, max=64)],
        description='1.0')
    package_title = TextField('Name', [
        validators.Required(), validators.Length(min=1, max=128)],
        description='Touchtracer')
    modules = TextField('Modules',
        description='pil kivy')
    directory = FileField('Application zipped with main.py',
        description='''You must create a zip of your application directory
        containing main.py in the zip root.''')
    package_permissions = TextField('Permissions', [
        validators.Length(max=2048)],
        description='INTERNET')
    package_orientation = SelectField('Orientation', choices=[
        ('landscape', 'Landscape'),
        ('portrait', 'Portrait')], default='landscape')
    package_icon = FileField('Icon')
    package_presplash = FileField('Presplash')
    emails = TextField('Send notification to', [
        validators.Length(max=2048)],
        description='your@email.com')
    release = BooleanField('Release mode')
    submit = SubmitField('Submit')

@frontend.route('/job/<uid>')
def job(uid):
    job = read_job(uid)
    if job is None:
        return redirect(url_for('frontend.index'))

    # get the log associated to the job
    joblog = list(reversed(read_logs(uid)))
    progress = job.build_status
    if not progress:
        pprogress = 0
        ptotal = 1
        pcurrent = 0
        status = "Waiting a builder"
    else:
        try:
            progress, status = progress[1:].split(']', 1)
            pcurrent, ptotal = progress.split('/')
        except ValueError:
            status = job.build_status
            pcurrent = 1
            ptotal = 1
        pprogress = int((int(pcurrent) / float(ptotal)) * 100.)
        status = status.strip().rstrip('.').capitalize()
    return render_template('frontend/job.html', job=job, joblog=joblog,
            pcurrent=pcurrent, ptotal=ptotal, pprogress=pprogress,
            status=status)

@frontend.route('/job/<uid>/delete')
def delete(uid):
    job = read_job(uid, 'package_name')
    if not job:
        abort(404)

    # delte job directory
    d = job.directory
    if d and len(d) > 10:
        subprocess.Popen(['rm', '-rf', d], shell=False).communicate()

    keys = r.keys('job:%s*' % uid)
    if keys:
        r.delete(*keys)
    keys = r.keys('log:%s*' % uid)
    if keys:
        r.delete(*keys)

    return redirect(url_for('frontend.index'))

@frontend.route('/api/data/<uid>')
def jobdata(uid):
    job = read_job(uid, 'directory', 'data_ext')
    if not job:
        return abort(404)
    print job
    r.set('job:%s:dt_started' % uid, time())
    r.set('job:%s:is_started' % uid, 1)
    return send_file(job.data_fn)

@frontend.route('/api/icon/<uid>')
def jobicon(uid):
    job = read_job(uid, 'directory', 'have_icon')
    if not job or not job.have_icon or not exists(job.icon_fn):
        return abort(404)
    return send_file(job.icon_fn)

@frontend.route('/api/presplash/<uid>')
def jobpresplash(uid):
    job = read_job(uid, 'directory')
    if not job or not job.have_presplash or not exists(job.presplash_fn):
        return abort(404)
    return send_file(job.presplash_fn)

@frontend.route('/api/push/<uid>', methods=['POST'])
def jobpush(uid):
    job = read_job(uid)
    if not job:
        return abort(404)
    file = request.files['file']
    if file and file.filename.rsplit('.', 1)[-1] == 'apk':
        filename = secure_filename(file.filename)
        file.save(join(job.directory, filename))
        r.set('job:%s:apk' % uid, filename)
        r.set('job:%s:dt_done' % uid, time())
        r.set('job:%s:is_done' % uid, 1)

        try:
            job.notify()
        except:
            pass
        return make_response('done')
    else:
        return abort(403)

@frontend.route('/download/<uid>/<apk>')
def download(uid, apk):
    job = read_job(uid, 'apk', 'directory', 'dt_done')
    if not job or not job.apk or not job.dt_done:
        return abort(404)
    return send_file(job.apk_fn)

@frontend.route('/')
def index():
    form = JobForm()
    return render_template('frontend/index.html', form=form)

@frontend.route('/faq')
def faq():
    return render_template('frontend/faq.html')

@frontend.route('/about')
def about():
    return render_template('frontend/about.html')

@frontend.route('/status')
def status():
    key = qjob.key
    queue_len = qjob._HotQueue__redis.llen(key)

    hosts_last_alive = r.keys('host:*:last_alive')
    hosts = [x.split(':')[1] for x in hosts_last_alive]

    stats = {}
    for host in hosts:
        stats[host] = {
                'last_seen': int(time() - float(r.get('host:{}:last_alive'.format(host)))),
                'status': r.get('host:{}:status'.format(host))}

    return render_template('frontend/status.html', queue_len=queue_len,
            stats=stats)

def csplit(s):
    return ' '.join([x for x in re.split(r'[.; ]', s) if len(x)])

@frontend.route('/submit', methods=['POST'])
def submit():
    form = JobForm()
    if form.validate_on_submit():
        fn = secure_filename(form.directory.file.filename)
        ext = splitext(fn)[-1]
        if splitext(fn)[-1] not in (
                '.zip'):#, '.tbz', '.tar.gz', '.tbz2', '.tar.bz2'):
            return render_template('frontend/index.html', form=form,
                    error='Invalid application directory package')

        # create a job
        uid = str(uuid4())

        # fake job obj for getting path
        job = JobObj({'uid': uid})

        jobkey = 'job:%s' % uid
        basekey = jobkey + ':'
        r.set(basekey + 'dt_added', time())

        # create the job directory
        d = job.directory
        mkdir(d)
        form.directory.file.save(join(d, 'data%s' % ext))

        if form.package_presplash.file:
            form.package_presplash.file.save(job.presplash_fn)
            r.set(basekey + 'have_presplash', 1)
        else:
            r.set(basekey + 'have_presplash', 0)

        if form.package_icon.file:
            form.package_icon.file.save(job.icon_fn)
            r.set(basekey + 'have_icon', 1)
        else:
            r.set(basekey + 'have_icon', 0)

        # add in the database
        r.set(basekey + 'package_name', form.package_name.data)
        r.set(basekey + 'package_version', form.package_version.data)
        r.set(basekey + 'package_title', form.package_title.data)
        r.set(basekey + 'package_orientation', form.package_orientation.data)
        r.set(basekey + 'package_permissions', form.package_permissions.data)
        r.set(basekey + 'modules', form.modules.data)
        r.set(basekey + 'emails', form.emails.data)
        r.set(basekey + 'data_ext', ext)
        r.set(basekey + 'is_release', 1 if form.release.data else 0)
        r.set(basekey + 'build_status', '')
        r.set(basekey + 'is_failed', 0)
        r.set(basekey + 'is_started', 0)
        r.set(basekey + 'is_done', 0)
        r.set(basekey + 'apk', '')

        # creation finished
        r.set(jobkey, uid)

        # not optimized, but reread it.
        job = read_job(uid)

        # submit a job in reddis
        qjob.put({
            'uid': job.uid,
            'package_name': job.package_name,
            'package_title': job.package_title,
            'package_version': job.package_version,
            'package_orientation': job.package_orientation,
            'package_permissions': csplit(job.package_permissions),
            'emails': csplit(job.emails),
            'have_icon': job.have_icon,
            'have_presplash': job.have_presplash,
            'mode': 'release' if job.is_release == '1' else 'debug',
            'modules': csplit(job.modules)
        })

        if 'batch' in request.form:
            d = {'status': 'ok',
                'uid': job.uid,
                'url': url_for('frontend.job', uid=job.uid, _external=True)}
            return jsonify(**d)
        else:
            # redirect to the view job
            return redirect(url_for('frontend.job', uid=job.uid))

    return render_template('frontend/index.html', form=form)


text:
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.OESVertexArrayObject
       (js_createVertexArrayOES, createVertexArrayOES,
        js_deleteVertexArrayOES, deleteVertexArrayOES, js_isVertexArrayOES,
        isVertexArrayOES, js_bindVertexArrayOES, bindVertexArrayOES,
        pattern VERTEX_ARRAY_BINDING_OES, OESVertexArrayObject,
        castToOESVertexArrayObject, gTypeOESVertexArrayObject)
       where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSRef(..), JSString, castRef)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSRef(..), FromJSRef(..))
import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.Enums

foreign import javascript unsafe "$1[\"createVertexArrayOES\"]()"
        js_createVertexArrayOES ::
        JSRef OESVertexArrayObject -> IO (JSRef WebGLVertexArrayObjectOES)

-- | <https://developer.mozilla.org/en-US/docs/Web/API/OESVertexArrayObject.createVertexArrayOES Mozilla OESVertexArrayObject.createVertexArrayOES documentation>
createVertexArrayOES ::
                     (MonadIO m) =>
                       OESVertexArrayObject -> m (Maybe WebGLVertexArrayObjectOES)
createVertexArrayOES self
  = liftIO
      ((js_createVertexArrayOES (unOESVertexArrayObject self)) >>=
         fromJSRef)

foreign import javascript unsafe "$1[\"deleteVertexArrayOES\"]($2)"
        js_deleteVertexArrayOES ::
        JSRef OESVertexArrayObject ->
          JSRef WebGLVertexArrayObjectOES -> IO ()

-- | <https://developer.mozilla.org/en-US/docs/Web/API/OESVertexArrayObject.deleteVertexArrayOES Mozilla OESVertexArrayObject.deleteVertexArrayOES documentation>
deleteVertexArrayOES ::
                     (MonadIO m) =>
                       OESVertexArrayObject -> Maybe WebGLVertexArrayObjectOES -> m ()
deleteVertexArrayOES self arrayObject
  = liftIO
      (js_deleteVertexArrayOES (unOESVertexArrayObject self)
         (maybe jsNull pToJSRef arrayObject))

foreign import javascript unsafe
        "($1[\"isVertexArrayOES\"]($2) ? 1 : 0)" js_isVertexArrayOES ::
        JSRef OESVertexArrayObject ->
          JSRef WebGLVertexArrayObjectOES -> IO Bool

-- | <https://developer.mozilla.org/en-US/docs/Web/API/OESVertexArrayObject.isVertexArrayOES Mozilla OESVertexArrayObject.isVertexArrayOES documentation>
isVertexArrayOES ::
                 (MonadIO m) =>
                   OESVertexArrayObject -> Maybe WebGLVertexArrayObjectOES -> m Bool
isVertexArrayOES self arrayObject
  = liftIO
      (js_isVertexArrayOES (unOESVertexArrayObject self)
         (maybe jsNull pToJSRef arrayObject))

foreign import javascript unsafe "$1[\"bindVertexArrayOES\"]($2)"
        js_bindVertexArrayOES ::
        JSRef OESVertexArrayObject ->
          JSRef WebGLVertexArrayObjectOES -> IO ()

-- | <https://developer.mozilla.org/en-US/docs/Web/API/OESVertexArrayObject.bindVertexArrayOES Mozilla OESVertexArrayObject.bindVertexArrayOES documentation>
bindVertexArrayOES ::
                   (MonadIO m) =>
                     OESVertexArrayObject -> Maybe WebGLVertexArrayObjectOES -> m ()
bindVertexArrayOES self arrayObject
  = liftIO
      (js_bindVertexArrayOES (unOESVertexArrayObject self)
         (maybe jsNull pToJSRef arrayObject))
pattern VERTEX_ARRAY_BINDING_OES = 34229


text:
package com.microsoft.azure.management.datafactory.v2018_06_01;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;

/**
 * A copy activity Hubspot Service source.
 */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", defaultImpl = HubspotSource.class)
@JsonTypeName("HubspotSource")
public class HubspotSource extends TabularSource {
    /**
     * A query to retrieve data from source. Type: string (or Expression with
     * resultType string).
     */
    @JsonProperty(value = "query")
    private Object query;

    /**
     * Get a query to retrieve data from source. Type: string (or Expression with resultType string).
     *
     * @return the query value
     */
    public Object query() {
        return this.query;
    }

    /**
     * Set a query to retrieve data from source. Type: string (or Expression with resultType string).
     *
     * @param query the query value to set
     * @return the HubspotSource object itself.
     */
    public HubspotSource withQuery(Object query) {
        this.query = query;
        return this;
    }

}


text:
This template allows you to create a Logic app that has a webhook. When the Logic app is triggered, it will add the payload you pass to an Azure Storage queue that you specify. You can add this webhook to an Azure Alert and then whenever the Alert fires, you'll get that item in the queue.

## Call from your Alerts

To call this whenever your Alert fires, you need to paste in the webhook URI into the alert:

1. Once the template has completed, navigate to the resource group you deployed it to.
2. In the **Essentials** click on the **Last deployment** link.
3. Select the top deployment.
4. This should show you the Outputs for the deployment. Copy the output called **WebHookURI**.
5. Navigate to the alert you want to trigger the Logic app and select **Edit**.
6. Scroll to the bottom and paste in the **WebHook**.
7. Click save.


text:
@echo off
title WebSocket Client
:start
echo.
echo ---------------------------
echo Ready to start
pause
echo Press CTRL-C twice to stop
echo Starting . . .
node test_client.js
goto start


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<targetDefinitions xmlns="http://openstm32.org/stm32TargetDefinitions" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://openstm32.org/stm32TargetDefinitions stm32TargetDefinitions.xsd">
  <board id="cubemx_lo53c8t_demo">
    <name>CubeMx_LO53C8T_demo</name>
    <mcuId>stm32l053c8tx</mcuId>
    <dbgIF>SWD</dbgIF>
    <dbgDEV>ST-LinkV2</dbgDEV>
  </board>
</targetDefinitions>


text:
<OPTION selected value="en">English</OPTION>
<OPTION value="de">Deutsch</OPTION>
<OPTION value="es">Español</OPTION>
<OPTION value="fr">Français</OPTION>
<OPTION value="it">Italian</OPTION>
<OPTION value="nl">Nederlands</OPTION>
<OPTION value="pl">Polski</OPTION>
<OPTION value="ptbr">Português - Brasil</OPTION>
<OPTION value="ro">Românã</OPTION>
<OPTION value="ru">Russian</OPTION>
<OPTION value="bg">Bulgarian</OPTION>
<OPTION value="cs">Czech</OPTION>
<OPTION value="da">Dansk</OPTION>


text:
package org.ext4spring.acl;

import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.ext4spring.acl.model.AclPermission;
import org.ext4spring.acl.model.AclPermissionImpl;
import org.ext4spring.acl.testapp.Contract;
import org.ext4spring.acl.testapp.ContractPermission;
import org.ext4spring.acl.testapp.Project;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/testApplicationContext.xml")
@Transactional
@TransactionConfiguration(transactionManager="transactionManager", defaultRollback=true)
public class AclDaoTest extends AbstractTransactionalJUnit4SpringContextTests {

	@Autowired
	private AclDao aclDao;
	private JdbcTemplate jdbcTemplate;

	@Autowired
	public void setDataSource(DataSource dataSource) {
		this.jdbcTemplate=new JdbcTemplate(dataSource);
	}

	@Test
	public void testInsertEntry() {
		this.aclDao.insertEntry(Contract.class, "domain1", "user1", ContractPermission.CONFIRM);
		Assert.assertEquals(1, this.jdbcTemplate.queryForLong("SELECT count(*) FROM EFS_ACL WHERE OBJECT_ID=? AND USER_ID=? AND ACL_PERMISSION=?","domain1","user1","CONFIRM"));
	}

	@Test
	public void testQuery() {
		Map<String, List<AclPermission>> result=this.aclDao.query(Contract.class, "c1");
		Assert.assertTrue(result.containsKey("admin"));
		Assert.assertTrue(result.get("admin").contains(new AclPermissionImpl("READ")));
		Assert.assertTrue(result.get("admin").contains(new AclPermissionImpl("CONFIRM")));
		Assert.assertTrue(result.get("admin").contains(new AclPermissionImpl("SIGN")));
		Assert.assertTrue(result.containsKey("read"));
		Assert.assertTrue(result.get("read").contains(new AclPermissionImpl("READ")));
		Assert.assertFalse(result.get("read").contains(new AclPermissionImpl("CONFIRM")));
		Assert.assertFalse(result.get("read").contains(new AclPermissionImpl("SIGN")));
		Assert.assertTrue(result.containsKey("confirm"));
		Assert.assertFalse(result.get("confirm").contains(new AclPermissionImpl("READ")));
		Assert.assertTrue(result.get("confirm").contains(new AclPermissionImpl("CONFIRM")));
		Assert.assertFalse(result.get("confirm").contains(new AclPermissionImpl("SIGN")));
		Assert.assertTrue(result.containsKey("sign"));
		Assert.assertFalse(result.get("sign").contains(new AclPermissionImpl("READ")));
		Assert.assertFalse(result.get("sign").contains(new AclPermissionImpl("CONFIRM")));
		Assert.assertTrue(result.get("sign").contains(new AclPermissionImpl("SIGN")));
	}

	@Test
	public void testRemoveAllFromOneDomainObject() {
		Assert.assertEquals(3, this.jdbcTemplate.queryForLong("SELECT count(*) FROM EFS_ACL WHERE OBJECT_TYPE=?","org.ext4spring.acl.testapp.Project"));
		this.aclDao.remove(Project.class, "p1");
		Assert.assertEquals(0, this.jdbcTemplate.queryForLong("SELECT count(*) FROM EFS_ACL WHERE OBJECT_TYPE=?","org.ext4spring.acl.testapp.Project"));
	}
	@Test
	public void testRemoveAllFromOneDomainObjectAndSpecificUser() {
		Assert.assertEquals(1, this.jdbcTemplate.queryForLong("SELECT count(*) FROM EFS_ACL WHERE OBJECT_TYPE=? AND OBJECT_ID=? AND USER_ID=?","org.ext4spring.acl.testapp.Contract","c1","read"));
		this.aclDao.remove(Contract.class, "c1","read");
		Assert.assertEquals(0, this.jdbcTemplate.queryForLong("SELECT count(*) FROM EFS_ACL WHERE OBJECT_TYPE=? AND OBJECT_ID=? AND USER_ID=?","org.ext4spring.acl.testapp.Contract","c1","read"));
	}
	@Test
	public void testRemovePermissionFromDomainObjectAndSpecificUser() {
		Assert.assertEquals(3, this.jdbcTemplate.queryForLong("SELECT count(*) FROM EFS_ACL WHERE OBJECT_TYPE=? AND OBJECT_ID=? AND USER_ID=?","org.ext4spring.acl.testapp.Contract","c1","admin"));
		Assert.assertEquals(1, this.jdbcTemplate.queryForLong("SELECT count(*) FROM EFS_ACL WHERE OBJECT_TYPE=? AND OBJECT_ID=? AND USER_ID=? AND ACL_PERMISSION=?","org.ext4spring.acl.testapp.Contract","c1","admin","READ"));
		this.aclDao.remove(Contract.class, "c1","admin", ContractPermission.READ);
		Assert.assertEquals(2, this.jdbcTemplate.queryForLong("SELECT count(*) FROM EFS_ACL WHERE OBJECT_TYPE=? AND OBJECT_ID=? AND USER_ID=?","org.ext4spring.acl.testapp.Contract","c1","admin"));
		Assert.assertEquals(0, this.jdbcTemplate.queryForLong("SELECT count(*) FROM EFS_ACL WHERE OBJECT_TYPE=? AND OBJECT_ID=? AND USER_ID=? AND ACL_PERMISSION=?","org.ext4spring.acl.testapp.Contract","c1","admin","READ"));
	}

	@Test
	public void testModificationMethodsEvictsCache() {
		int count=this.aclDao.query(Contract.class, "c1").get("admin").size();
		this.aclDao.remove(Contract.class, "c1", "admin", ContractPermission.CONFIRM);
		Assert.assertNotEquals(count, this.aclDao.query(Contract.class, "c1").get("admin").size());
		this.aclDao.insertEntry(Contract.class, "c1", "admin", ContractPermission.CONFIRM);
		Assert.assertEquals(count, this.aclDao.query(Contract.class, "c1").get("admin").size());
		this.aclDao.remove(Contract.class, "c1", "admin");
		Assert.assertEquals(null, this.aclDao.query(Contract.class, "c1").get("admin"));
		this.aclDao.insertEntry(Contract.class, "c1", "admin", ContractPermission.CONFIRM);
		Assert.assertEquals(1, this.aclDao.query(Contract.class, "c1").get("admin").size());
		this.aclDao.remove(Contract.class, "c1");
		Assert.assertEquals(0,this.aclDao.query(Contract.class, "c1").size());
	}

	@Test
	public void manualCacheTest() {
		this.aclDao.query(Contract.class, "c1");
		this.aclDao.query(Contract.class, "c1");
	}
}


text:
#ifndef __USER_INTERFACE_H__
#define __USER_INTERFACE_H__

#include "os_type.h"
#ifdef LWIP_OPEN_SRC
#include "lwip/ip_addr.h"
#else
#include "ip_addr.h"
#endif

#include "queue.h"
#include "user_config.h"
#include "spi_flash.h"

#ifndef MAC2STR
#define MAC2STR(a) (a)[0], (a)[1], (a)[2], (a)[3], (a)[4], (a)[5]
#define MACSTR "%02x:%02x:%02x:%02x:%02x:%02x"
#endif

enum rst_reason {
	DEFAULT_RST_FLAG	= 0,
	WDT_RST_FLAG	= 1,
	EXP_RST_FLAG    = 2
};

struct rst_info{
	uint32 flag;
	uint32 exccause;
	uint32 epc1;
	uint32 epc2;
	uint32 epc3;
	uint32 excvaddr;
	uint32 depc;
};

#define UPGRADE_FW_BIN1         0x00
#define UPGRADE_FW_BIN2         0x01

void system_restore(void);
void system_restart(void);

bool system_deep_sleep_set_option(uint8 option);
void system_deep_sleep(uint32 time_in_us);

uint8 system_upgrade_userbin_check(void);
void system_upgrade_reboot(void);
uint8 system_upgrade_flag_check();
void system_upgrade_flag_set(uint8 flag);

void system_timer_reinit(void);
uint32 system_get_time(void);

/* user task's prio must be 0/1/2 !!!*/
enum {
    USER_TASK_PRIO_0 = 0,
    USER_TASK_PRIO_1,
    USER_TASK_PRIO_2,
    USER_TASK_PRIO_MAX
};

bool system_os_task(os_task_t task, uint8 prio, os_event_t *queue, uint8 qlen);
bool system_os_post(uint8 prio, os_signal_t sig, os_param_t par);

void system_print_meminfo(void);
uint32 system_get_free_heap_size(void);

void system_set_os_print(uint8 onoff);
uint8 system_get_os_print();

uint64 system_mktime(uint32 year, uint32 mon, uint32 day, uint32 hour, uint32 min, uint32 sec);

uint32 system_get_chip_id(void);

typedef void (* init_done_cb_t)(void);

void system_init_done_cb(init_done_cb_t cb);

uint32 system_rtc_clock_cali_proc(void);
uint32 system_get_rtc_time(void);

bool system_rtc_mem_read(uint8 src_addr, void *des_addr, uint16 load_size);
bool system_rtc_mem_write(uint8 des_addr, const void *src_addr, uint16 save_size);

void system_uart_swap(void);

uint16 system_adc_read(void);

const char *system_get_sdk_version(void);

#define NULL_MODE       0x00
#define STATION_MODE    0x01
#define SOFTAP_MODE     0x02
#define STATIONAP_MODE  0x03

typedef enum _auth_mode {
    AUTH_OPEN           = 0,
    AUTH_WEP,
    AUTH_WPA_PSK,
    AUTH_WPA2_PSK,
    AUTH_WPA_WPA2_PSK,
    AUTH_MAX
} AUTH_MODE;

uint8 wifi_get_opmode(void);
bool wifi_set_opmode(uint8 opmode);

struct bss_info {
    STAILQ_ENTRY(bss_info)     next;

    uint8 bssid[6];
    uint8 ssid[32];
    uint8 channel;
    sint8 rssi;
    AUTH_MODE authmode;
    uint8 is_hidden;
};

typedef struct _scaninfo {
    STAILQ_HEAD(, bss_info) *pbss;
    struct espconn *pespconn;
    uint8 totalpage;
    uint8 pagenum;
    uint8 page_sn;
    uint8 data_cnt;
} scaninfo;

typedef void (* scan_done_cb_t)(void *arg, STATUS status);

struct station_config {
    uint8 ssid[32];
    uint8 password[64];
    uint8 bssid_set;	// Note: If bssid_set is 1, station will just connect to the router
                        // with both ssid[] and bssid[] matched. Please check about this.
    uint8 bssid[6];
};

bool wifi_station_get_config(struct station_config *config);
bool wifi_station_set_config(struct station_config *config);

bool wifi_station_connect(void);
bool wifi_station_disconnect(void);

struct scan_config {
    uint8 *ssid;	// Note: ssid == NULL, don't filter ssid.
    uint8 *bssid;	// Note: bssid == NULL, don't filter bssid.
    uint8 channel;	// Note: channel == 0, scan all channels, otherwise scan set channel.
    uint8 show_hidden;	// Note: show_hidden == 1, can get hidden ssid routers' info.
};

bool wifi_station_scan(struct scan_config *config, scan_done_cb_t cb);

uint8 wifi_station_get_auto_connect(void);
bool wifi_station_set_auto_connect(uint8 set);

enum {
    STATION_IDLE = 0,
    STATION_CONNECTING,
    STATION_WRONG_PASSWORD,
    STATION_NO_AP_FOUND,
    STATION_CONNECT_FAIL,
    STATION_GOT_IP
};

enum dhcp_status {
	DHCP_STOPPED,
	DHCP_STARTED
};

uint8 wifi_station_get_connect_status(void);

uint8 wifi_station_get_current_ap_id(void);
bool wifi_station_ap_change(uint8 current_ap_id);
bool wifi_station_ap_number_set(uint8 ap_number);

bool wifi_station_dhcpc_start(void);
bool wifi_station_dhcpc_stop(void);
enum dhcp_status wifi_station_dhcpc_status(void);

struct softap_config {
    uint8 ssid[32];
    uint8 password[64];
    uint8 ssid_len;	// Note: Recommend to set it according to your ssid
    uint8 channel;	// Note: support 1 ~ 13
    AUTH_MODE authmode;	// Note: Don't support AUTH_WEP in softAP mode.
    uint8 ssid_hidden;	// Note: default 0
    uint8 max_connection;	// Note: default 4, max 4
    uint16 beacon_interval;	// Note: support 100 ~ 60000 ms, default 100
};

bool wifi_softap_get_config(struct softap_config *config);
bool wifi_softap_set_config(struct softap_config *config);

struct station_info {
	STAILQ_ENTRY(station_info)	next;

	uint8 bssid[6];
	struct ip_addr ip;
};

struct dhcps_lease {
	uint32 start_ip;
	uint32 end_ip;
};

struct station_info * wifi_softap_get_station_info(void);
void wifi_softap_free_station_info(void);
uint8 wifi_station_get_ap_info(struct station_config config[]);

bool wifi_softap_dhcps_start(void);
bool wifi_softap_dhcps_stop(void);
bool wifi_softap_set_dhcps_lease(struct dhcps_lease *please);
enum dhcp_status wifi_softap_dhcps_status(void);

#define STATION_IF      0x00
#define SOFTAP_IF       0x01

bool wifi_get_ip_info(uint8 if_index, struct ip_info *info);
bool wifi_set_ip_info(uint8 if_index, struct ip_info *info);
bool wifi_get_macaddr(uint8 if_index, uint8 *macaddr);
bool wifi_set_macaddr(uint8 if_index, uint8 *macaddr);

uint8 wifi_get_channel(void);
bool wifi_set_channel(uint8 channel);

void wifi_status_led_install(uint8 gpio_id, uint32 gpio_name, uint8 gpio_func);
void wifi_status_led_uninstall();

/** Get the absolute difference between 2 u32_t values (correcting overflows)
 * 'a' is expected to be 'higher' (without overflow) than 'b'. */
#define ESP_U32_DIFF(a, b) (((a) >= (b)) ? ((a) - (b)) : (((a) + ((b) ^ 0xFFFFFFFF) + 1)))

void wifi_promiscuous_enable(uint8 promiscuous);

typedef void (* wifi_promiscuous_cb_t)(uint8 *buf, uint16 len);

void wifi_set_promiscuous_rx_cb(wifi_promiscuous_cb_t cb);

enum phy_mode {
	PHY_MODE_11B	= 1,
	PHY_MODE_11G	= 2,
	PHY_MODE_11N    = 3
};

enum phy_mode wifi_get_phy_mode(void);
bool wifi_set_phy_mode(enum phy_mode mode);

enum sleep_type {
	NONE_SLEEP_T	= 0,
	LIGHT_SLEEP_T,
	MODEM_SLEEP_T
};

bool wifi_set_sleep_type(enum sleep_type type);
enum sleep_type wifi_get_sleep_type(void);

#endif


text:
package kubernetes

import (
	"reflect"
	"testing"

	"github.com/GoogleContainerTools/skaffold/pkg/skaffold/config"
	"github.com/GoogleContainerTools/skaffold/pkg/skaffold/deploy/label"
	k8sstatus "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes/status"
	"github.com/GoogleContainerTools/skaffold/pkg/skaffold/util"
	"github.com/GoogleContainerTools/skaffold/testutil"
)

type mockStatusConfig struct {
	k8sstatus.Config
	statusCheck *bool
}

func (m mockStatusConfig) StatusCheck() *bool { return m.statusCheck }

func (m mockStatusConfig) GetKubeContext() string { return "" }

func (m mockStatusConfig) StatusCheckDeadlineSeconds() int { return 0 }

func (m mockStatusConfig) StatusCheckTolerateFailures() bool { return false }

func (m mockStatusConfig) FastFailStatusCheck() bool { return true }

func (m mockStatusConfig) Muted() config.Muted { return config.Muted{} }

func TestGetMonitor(t *testing.T) {
	tests := []struct {
		description string
		statusCheck *bool
		isNoop      bool
	}{
		{
			description: "unspecified statusCheck parameter",
		},
		{
			description: "statusCheck parameter set to true",
			statusCheck: util.Ptr(true),
		},
		{
			description: "statusCheck parameter set to false",
			statusCheck: util.Ptr(false),
			isNoop:      true,
		},
	}

	for _, test := range tests {
		testutil.Run(t, test.description, func(t *testutil.T) {
			m := NewMonitor(mockStatusConfig{statusCheck: test.statusCheck}, test.description, label.NewLabeller(false, nil, ""), nil)
			t.CheckDeepEqual(test.isNoop, reflect.Indirect(reflect.ValueOf(m)).Type() == reflect.TypeOf(k8sstatus.NoopMonitor{}))
		})
	}
}


text:
"use strict";
var Lines;
(function (Lines) {
    var Line = (function () {
        function Line(point, next) {
            if (next === void 0) { next = null; }
            this.point = point;
            this.next = next;
            this.color = "black";
        }
        Line.prototype.getPoint = function () {
            return this.point;
        };
        Line.prototype.getNext = function () {
            return this.next;
        };
        Line.prototype.hasNext = function () {
            return this.next !== null;
        };
        Line.prototype.setNext = function (other) {
            this.next = other;
        };
        //for interconnecting lines, gets last point in the chain
        Line.prototype.getLast = function () {
            if (this.hasNext()) {
                return this.next.getLast();
            }
            else
                return this;
        };
        Line.prototype.strFormat = function () {
            if (this.hasNext())
                return this.point.strFormat() + " -> " + this.next.strFormat();
            else
                return "" + this.point.strFormat();
        };
        Line.prototype.type = function () {
            return "line";
        };
        return Line;
    }());
    Lines.Line = Line;
})(Lines = exports.Lines || (exports.Lines = {}));
//# sourceMappingURL=Line.js.map